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

import path from "path";
import fs from "fs-extra";
import meow from "meow";
import resolveFrom from "resolve-from";
import standalone from "./standalone";

const cli = meow(
  `
    Usage: webfont [input] [options]

    Input: File(s) or glob(s).

        If an input argument is wrapped in quotation marks, it will be passed to "fast-glob"
        for cross-platform glob support.

    Options:

        --config

            Path to a specific configuration file (JSON, YAML, or CommonJS)
            or the name of a module in \`node_modules\` that points to one.
            If no \`--config\` argument is provided, webfont will search for
            configuration  files in the following places, in this order:
               - a \`webfont\` property in \`package.json\`
               - a \`.webfontrc\` file (with or without filename extension:
                   \`.json\`, \`.yaml\`, and \`.js\` are available)
               - a \`webfont.config.js\` file exporting a JS object
            The search will begin in the working directory and move up the
            directory tree until a configuration file is found.

        -f, --font-name

            The font family name you want, default: "webfont".

        -h, --help

            Output usage information.

        -v, --version

            Output the version number.

        -r, --formats

            Only this formats generate.

        -d, --dest

            Destination for generated fonts.

        -t, --template

            Type of template ('css', 'scss') or path to custom template.

        -s, --dest-template

            Destination for generated template. If not passed used \`dest\` argument value.

        -c, --template-class-name

            Class name in css template.

        -p, --template-font-path

            Font path in css template.

        -n, --template-font-name

            Font name in css template.

        --no-sort

            Keeps the files in the same order of entry

        --verbose

            Tell me everything!.

    For "svgicons2svgfont":

        --font-id

            The font id you want, default as "--font-name".

        --font-style

            The font style you want.

        --font-weight

            The font weight you want.

        --fixed-width

            Creates a monospace font of the width of the largest input icon.

        --center-horizontally

            Calculate the bounds of a glyph and center it horizontally.

        --normalize

            Normalize icons by scaling them to the height of the highest icon.

        --font-height

            The outputted font height [MAX(icons.height)].

        --round

            Setup the SVG path rounding [10e12].

        --descent

            The font descent [0].

        --ascent

            The font ascent [height - descent].

        --start-unicode

            The start unicode codepoint for unprefixed files [0xEA01].

        --prepend-unicode

            Prefix files with their automatically allocated unicode codepoint.

        --metadata

            Content of the metadata tag.
`,
  {
    autoHelp: false,
    autoVersion: false,
    flags: {
      ascent: {
        type: "string"
      },
      "center-horizontally": {
        type: "boolean"
      },
      config: {
        default: null
      },
      descent: {
        type: "string"
      },
      dest: {
        alias: "d",
        default: process.cwd(),
        type: "string"
      },
      "dest-template": {
        alias: "s",
        type: "string"
      },
      "fixed-width": {
        type: "boolean"
      },
      "font-height": {
        type: "string"
      },
      "font-id": {
        type: "string"
      },
      "font-name": {
        alias: "u",
        type: "string"
      },
      "font-style": {
        type: "string"
      },
      "font-weight": {
        type: "string"
      },
      formats: {
        alias: "f"
      },
      help: {
        alias: "h",
        type: "boolean"
      },
      normalize: {
        type: "boolean"
      },
      "prepend-unicode": {
        type: "boolean"
      },
      round: {
        type: "string"
      },
      sort: {
        default: true,
        type: "boolean"
      },
      "start-unicode": {
        type: "string"
      },
      template: {
        alias: "t",
        type: "string"
      },
      "template-class-name": {
        alias: "c",
        type: "string"
      },
      "template-font-name": {
        alias: "n",
        type: "string"
      },
      "template-font-path": {
        alias: "p",
        type: "string"
      },
      verbose: {
        default: false,
        type: "boolean"
      },
      version: {
        alias: "v",
        type: "boolean"
      }
    }
  }
);

const optionsBase = {};

if (cli.flags.config) {
  // Should check these possibilities:
  //   a. name of a node_module
  //   b. absolute path
  //   c. relative path relative to `process.cwd()`.
  // If none of the above work, we'll try a relative path starting
  // in `process.cwd()`.
  optionsBase.configFile =
    resolveFrom(process.cwd(), cli.flags.config) ||
    path.join(process.cwd(), cli.flags.config);
}

if (cli.flags.fontName) {
  optionsBase.fontName = cli.flags.fontName;
}

if (cli.flags.formats) {
  optionsBase.formats = cli.flags.formats;
}

if (cli.flags.dest) {
  optionsBase.dest = cli.flags.dest;
}

if (cli.flags.template) {
  optionsBase.template = cli.flags.template;
}

if (cli.flags.templateClassName) {
  optionsBase.templateClassName = cli.flags.templateClassName;
}

if (cli.flags.templateFontPath) {
  optionsBase.templateFontPath = cli.flags.templateFontPath;
}

if (cli.flags.templateFontName) {
  optionsBase.templateFontName = cli.flags.templateFontName;
}

if (cli.flags.destTemplate) {
  optionsBase.destTemplate = cli.flags.destTemplate;
}

if (cli.flags.verbose) {
  optionsBase.verbose = cli.flags.verbose;
}

if (cli.flags.fontId) {
  optionsBase.fontId = cli.flags.fontId;
}

if (cli.flags.fontStyle) {
  optionsBase.fontStyle = cli.flags.fontStyle;
}

if (cli.flags.fontWeight) {
  optionsBase.fontWeight = cli.flags.fontWeight;
}

if (cli.flags.fixedWidth) {
  optionsBase.fixedWidth = cli.flags.fixedWidth;
}

if (cli.flags.centerHorizontally) {
  optionsBase.centerHorizontally = cli.flags.centerHorizontally;
}

if (cli.flags.normalize) {
  optionsBase.normalize = cli.flags.normalize;
}

if (cli.flags.fontHeight) {
  optionsBase.fontHeight = cli.flags.fontHeight;
}

if (cli.flags.round) {
  optionsBase.round = cli.flags.round;
}

if (cli.flags.descent) {
  optionsBase.descent = cli.flags.descent;
}

if (cli.flags.ascent) {
  optionsBase.ascent = cli.flags.ascent;
}

if (cli.flags.startUnicode) {
  optionsBase.startUnicode = cli.flags.startUnicode;
}

if (cli.flags.prependUnicode) {
  optionsBase.prependUnicode = cli.flags.prependUnicode;
}

if (cli.flags.metadata) {
  optionsBase.metadata = cli.flags.metadata;
}

if (cli.flags.sort === false) {
  optionsBase.sort = cli.flags.sort;
}

if (cli.flags.help || cli.flags.h) {
  cli.showHelp();
}

if (cli.flags.version || cli.flags.v) {
  cli.showVersion();
}

Promise.resolve()
  .then(() => {
    const options = Object.assign({}, optionsBase, {
      files: cli.input
    });

    if (options.files.length === 0) {
      cli.showHelp();
    }

    return standalone(options).then(result => {
      result.config = Object.assign(
        {},
        {
          dest: options.dest,
          destTemplate: options.destTemplate
        },
        result.config
      );

      return result;
    });
  })
  .then(result => {
    const { fontName, dest } = result.config;

    let destTemplate = null;

    if (result.template) {
      ({ destTemplate } = result.config);

      if (!destTemplate) {
        destTemplate = dest;
      }

      if (result.usedBuildInTemplate) {
        destTemplate = path.join(
          destTemplate,
          `${result.config.fontName}.${result.config.template}`
        );
      } else {
        destTemplate = path.join(
          destTemplate,
          path.basename(result.config.template).replace(".njk", "")
        );
      }
    }

    return Promise.resolve()
      .then(() =>
        Promise.all(
          Object.keys(result).map(type => {
            if (
              type === "config" ||
              type === "usedBuildInTemplate" ||
              type === "glyphsData"
            ) {
              return null;
            }

            const content = result[type];
            let file = null;

            if (type !== "template") {
              file = path.resolve(path.join(dest, `${fontName}.${type}`));
            } else {
              file = path.resolve(destTemplate);
            }

            return fs.writeFile(file, content);
          })
        )
      )
      .then(() => Promise.resolve(result));
  })
  .catch(error => {
    // eslint-disable-next-line no-console
    console.log(error.stack);

    const exitCode = typeof error.code === "number" ? error.code : 1;

    process.exit(exitCode);
  });
<commit_msg>fix(cli): use `fs` instead of `fs-extra` for writing files<commit_after>#!/usr/bin/env node

import path from "path";
import fs from "fs";
import meow from "meow";
import resolveFrom from "resolve-from";
import standalone from "./standalone";

const cli = meow(
  `
    Usage: webfont [input] [options]

    Input: File(s) or glob(s).

        If an input argument is wrapped in quotation marks, it will be passed to "fast-glob"
        for cross-platform glob support.

    Options:

        --config

            Path to a specific configuration file (JSON, YAML, or CommonJS)
            or the name of a module in \`node_modules\` that points to one.
            If no \`--config\` argument is provided, webfont will search for
            configuration  files in the following places, in this order:
               - a \`webfont\` property in \`package.json\`
               - a \`.webfontrc\` file (with or without filename extension:
                   \`.json\`, \`.yaml\`, and \`.js\` are available)
               - a \`webfont.config.js\` file exporting a JS object
            The search will begin in the working directory and move up the
            directory tree until a configuration file is found.

        -f, --font-name

            The font family name you want, default: "webfont".

        -h, --help

            Output usage information.

        -v, --version

            Output the version number.

        -r, --formats

            Only this formats generate.

        -d, --dest

            Destination for generated fonts.

        -t, --template

            Type of template ('css', 'scss', 'styl') or path to custom template.

        -s, --dest-template

            Destination for generated template. If not passed used \`dest\` argument value.

        -c, --template-class-name

            Class name in css template.

        -p, --template-font-path

            Font path in css template.

        -n, --template-font-name

            Font name in css template.

        --no-sort

            Keeps the files in the same order of entry

        --verbose

            Tell me everything!.

    For "svgicons2svgfont":

        --font-id

            The font id you want, default as "--font-name".

        --font-style

            The font style you want.

        --font-weight

            The font weight you want.

        --fixed-width

            Creates a monospace font of the width of the largest input icon.

        --center-horizontally

            Calculate the bounds of a glyph and center it horizontally.

        --normalize

            Normalize icons by scaling them to the height of the highest icon.

        --font-height

            The outputted font height [MAX(icons.height)].

        --round

            Setup the SVG path rounding [10e12].

        --descent

            The font descent [0].

        --ascent

            The font ascent [height - descent].

        --start-unicode

            The start unicode codepoint for files without prefix [0xEA01].

        --prepend-unicode

            Prefix files with their automatically allocated unicode codepoint.

        --metadata

            Content of the metadata tag.
`,
  {
    autoHelp: false,
    autoVersion: false,
    flags: {
      ascent: {
        type: "string"
      },
      "center-horizontally": {
        type: "boolean"
      },
      config: {
        default: null
      },
      descent: {
        type: "string"
      },
      dest: {
        alias: "d",
        default: process.cwd(),
        type: "string"
      },
      "dest-template": {
        alias: "s",
        type: "string"
      },
      "fixed-width": {
        type: "boolean"
      },
      "font-height": {
        type: "string"
      },
      "font-id": {
        type: "string"
      },
      "font-name": {
        alias: "u",
        type: "string"
      },
      "font-style": {
        type: "string"
      },
      "font-weight": {
        type: "string"
      },
      formats: {
        alias: "f"
      },
      help: {
        alias: "h",
        type: "boolean"
      },
      normalize: {
        type: "boolean"
      },
      "prepend-unicode": {
        type: "boolean"
      },
      round: {
        type: "string"
      },
      sort: {
        default: true,
        type: "boolean"
      },
      "start-unicode": {
        type: "string"
      },
      template: {
        alias: "t",
        type: "string"
      },
      "template-class-name": {
        alias: "c",
        type: "string"
      },
      "template-font-name": {
        alias: "n",
        type: "string"
      },
      "template-font-path": {
        alias: "p",
        type: "string"
      },
      verbose: {
        default: false,
        type: "boolean"
      },
      version: {
        alias: "v",
        type: "boolean"
      }
    }
  }
);

const optionsBase = {};

if (cli.flags.config) {
  // Should check these possibilities:
  //   a. name of a node_module
  //   b. absolute path
  //   c. relative path relative to `process.cwd()`.
  // If none of the above work, we'll try a relative path starting
  // in `process.cwd()`.
  optionsBase.configFile =
    resolveFrom(process.cwd(), cli.flags.config) ||
    path.join(process.cwd(), cli.flags.config);
}

if (cli.flags.fontName) {
  optionsBase.fontName = cli.flags.fontName;
}

if (cli.flags.formats) {
  optionsBase.formats = cli.flags.formats;
}

if (cli.flags.dest) {
  optionsBase.dest = cli.flags.dest;
}

if (cli.flags.template) {
  optionsBase.template = cli.flags.template;
}

if (cli.flags.templateClassName) {
  optionsBase.templateClassName = cli.flags.templateClassName;
}

if (cli.flags.templateFontPath) {
  optionsBase.templateFontPath = cli.flags.templateFontPath;
}

if (cli.flags.templateFontName) {
  optionsBase.templateFontName = cli.flags.templateFontName;
}

if (cli.flags.destTemplate) {
  optionsBase.destTemplate = cli.flags.destTemplate;
}

if (cli.flags.verbose) {
  optionsBase.verbose = cli.flags.verbose;
}

if (cli.flags.fontId) {
  optionsBase.fontId = cli.flags.fontId;
}

if (cli.flags.fontStyle) {
  optionsBase.fontStyle = cli.flags.fontStyle;
}

if (cli.flags.fontWeight) {
  optionsBase.fontWeight = cli.flags.fontWeight;
}

if (cli.flags.fixedWidth) {
  optionsBase.fixedWidth = cli.flags.fixedWidth;
}

if (cli.flags.centerHorizontally) {
  optionsBase.centerHorizontally = cli.flags.centerHorizontally;
}

if (cli.flags.normalize) {
  optionsBase.normalize = cli.flags.normalize;
}

if (cli.flags.fontHeight) {
  optionsBase.fontHeight = cli.flags.fontHeight;
}

if (cli.flags.round) {
  optionsBase.round = cli.flags.round;
}

if (cli.flags.descent) {
  optionsBase.descent = cli.flags.descent;
}

if (cli.flags.ascent) {
  optionsBase.ascent = cli.flags.ascent;
}

if (cli.flags.startUnicode) {
  optionsBase.startUnicode = cli.flags.startUnicode;
}

if (cli.flags.prependUnicode) {
  optionsBase.prependUnicode = cli.flags.prependUnicode;
}

if (cli.flags.metadata) {
  optionsBase.metadata = cli.flags.metadata;
}

if (cli.flags.sort === false) {
  optionsBase.sort = cli.flags.sort;
}

if (cli.flags.help || cli.flags.h) {
  cli.showHelp();
}

if (cli.flags.version || cli.flags.v) {
  cli.showVersion();
}

Promise.resolve()
  .then(() => {
    const options = Object.assign({}, optionsBase, {
      files: cli.input
    });

    if (options.files.length === 0) {
      cli.showHelp();
    }

    return standalone(options).then(result => {
      result.config = Object.assign(
        {},
        {
          dest: options.dest,
          destTemplate: options.destTemplate
        },
        result.config
      );

      return result;
    });
  })
  .then(result => {
    const { fontName, dest } = result.config;

    let destTemplate = null;

    if (result.template) {
      ({ destTemplate } = result.config);

      if (!destTemplate) {
        destTemplate = dest;
      }

      if (result.usedBuildInTemplate) {
        destTemplate = path.join(
          destTemplate,
          `${result.config.fontName}.${result.config.template}`
        );
      } else {
        destTemplate = path.join(
          destTemplate,
          path.basename(result.config.template).replace(".njk", "")
        );
      }
    }

    return Promise.resolve()
      .then(() =>
        Promise.all(
          Object.keys(result).map(type => {
            if (
              type === "config" ||
              type === "usedBuildInTemplate" ||
              type === "glyphsData"
            ) {
              return null;
            }

            const content = result[type];
            // eslint-disable-next-line init-declarations
            let file;

            if (type !== "template") {
              file = path.resolve(path.join(dest, `${fontName}.${type}`));
            } else {
              file = path.resolve(destTemplate);
            }

            return fs.writeFile(file, content, () => {
              Function.prototype();
            });
          })
        )
      )
      .then(() => Promise.resolve(result));
  })
  .catch(error => {
    // eslint-disable-next-line no-console
    console.log(error.stack);

    const exitCode = typeof error.code === "number" ? error.code : 1;

    process.exit(exitCode);
  });
<|endoftext|>


<commit_before>angular.module('sikre.controllers', [])

  // We REALLY shouldn't be using rootScope for this...
  .controller('groupsController', function ($scope, sikreAPIservice) {

    sikreAPIservice.getGroups()
      .success(function (response) {
        $scope.groupList = response;
      })
      .error(function () {
        $.notify("Can't access the API to get the groups.", "error");
      });
  })

  .controller('LoginCtrl', function ($scope, $auth) {

    $scope.authenticate = function (provider) {
      $auth.authenticate(provider);
    };
  })

  .controller('LogoutCtrl', function ($scope, $auth) {

    $scope.logout = function () {
      $auth.logout();
      $.notify("You have been logged out", "error");
    };
  })

  .controller('addItem', function ($scope, sikreAPIservice) {

    $scope.update = function (item) {
      payload = {
        "name": item.name,
        "description": item.description,
        "group": item.group,
        "tags": item.tags
      };

      sikreAPIservice.saveItem(payload)
        .success(function (response) {
          $.notify("Data saved successfully", "success");
        })
        .error(function () {
          $.notify("Can't save the item", "error");
        });
    };

    $scope.reset = function () {
      $scope.user = angular.copy($scope.master);
    };
  });
<commit_msg>Added the grouplsit to the additem controler<commit_after>angular.module('sikre.controllers', [])

  // We REALLY shouldn't be using rootScope for this...
  .controller('groupsController', function ($scope, sikreAPIservice) {

    sikreAPIservice.getGroups()
      .success(function (response) {
        $scope.groupList = response;
      })
      .error(function () {
        $.notify("Can't access the API to get the groups.", "error");
      });
  })

  .controller('LoginCtrl', function ($scope, $auth) {

    $scope.authenticate = function (provider) {
      $auth.authenticate(provider);
    };
  })

  .controller('LogoutCtrl', function ($scope, $auth) {

    $scope.logout = function () {
      $auth.logout();
      $.notify("You have been logged out", "error");
    };
  })

  .controller('addItem', function ($scope, sikreAPIservice) {

    $scope.groupList = sikreAPIservice.getGroups()
      .error(function () {
        $.notify("Can't retrieve the groups", "error");
      });

    $scope.update = function (item) {
      payload = {
        "name": item.name,
        "description": item.description,
        "group": item.group,
        "tags": item.tags
      };

      sikreAPIservice.saveItem(payload)
        .success(function (response) {
          $.notify("Data saved successfully", "success");
        })
        .error(function () {
          $.notify("Can't save the item", "error");
        });
    };

    $scope.reset = function () {
      $scope.user = angular.copy($scope.master);
    };
  });
<|endoftext|>


<commit_before>const commander = require("commander");
const fs = require("fs");
const path = require("path");
const process = require("process");
const {exec, spawn} = require("child_process");
const lazyMethodRequire = require("./lib/LazyMethodRequire")(__dirname);

const newApp = lazyMethodRequire("./commands/new");
const startClient = lazyMethodRequire("./commands/start-client");
const startServer = lazyMethodRequire("./commands/start-server");
const startTest = lazyMethodRequire("./commands/test");
const generate = lazyMethodRequire("./commands/generate");
const destroy = lazyMethodRequire("./commands/destroy");
const dockerize = lazyMethodRequire("./commands/dockerize");

const chalk = require("chalk");
const autoUpgrade = require("./auto-upgrade");
const chokidar = require("chokidar");

const command = process.argv[2];
const isProduction = process.env.NODE_ENV === "production";

const IS_WINDOWS = process.platform === "win32";

commander
  .version(getVersion());

commander
  .command("touch")
  .description("update project version")
  .action((options)=> updateLastVersionUsed())

commander
  .command("new")
  .description("generate a new application")
  .arguments("<app_name>")
  .action(newApp)
  .action((options)=> updateLastVersionUsed());

commander
  .command("generate <container|component|reducer>")
  .description("generate a new container")
  .arguments("<name>")
  .action((type, name) => generate(type, name, (err) => {
    if (err) console.log(chalk.red(`ERROR: ${err}`));
  }))
  .action((options)=> updateLastVersionUsed())

commander
  .command("destroy <container|component|reducer>")
  .description("destroy a generated container")
  .arguments("<name>")
  .action(destroy)
  .action((options)=> updateLastVersionUsed());

const debugOption = {
  command: "-D, --debug",
  description: "debug server side rendering with node-inspector"
};

commander
  .command("start")
  .description("start everything")
  .option("-T, --no_tests", "ignore test hook")
  .option(debugOption.command, debugOption.description)
  .action((options) => startAll(options.no_tests, options.debug))
  .action((options)=> updateLastVersionUsed());

commander
  .command("build")
  .description("create production asset build")
  .action(() => startClient(true))
  .action((options)=> updateLastVersionUsed());

commander
  .command("dockerize")
  .description("create docker image")
  .arguments("<name>")
  .action(upgradeAndDockerize)
  .action((options)=> updateLastVersionUsed());

commander
  .command("start-client", null, {noHelp: true})
  .description("start client")
  .action(() => startClient(false))
  .action((options)=> updateLastVersionUsed());

commander
  .command("start-server", null, {noHelp: true})
  .description("start server")
  .option(debugOption.command, debugOption.description)
  .action((options) => startServer(options.debug))
  .action((options)=> updateLastVersionUsed());

const firefoxOption = {
  command: "-F, --firefox",
  description: "Use Firefox with test runner"
};

commander
  .command("start-test", null, {noHelp: true})
  .option(firefoxOption.command, firefoxOption.description)
  .description("start test")
  .action((options) => startTest(options))
  .action((options)=> updateLastVersionUsed());

commander
  .command("test")
  .option(firefoxOption.command, firefoxOption.description)
  .description("start tests")
  .action(() => spawnProcess("test", process.argv.slice(3)))
  .action((options)=> updateLastVersionUsed());

// This is a catch all command. DO NOT PLACE ANY COMMANDS BELOW THIS
commander
  .command('*', null, {noHelp: true})
  .action(function(cmd){
    console.log(`Error: Command '${cmd}' not recognized`);
    commander.help();
});

commander.parse(process.argv);

function getVersion () {
  var packageFileContents = fs.readFileSync(path.join(__dirname, "..", "package.json"));
  var packageObject = JSON.parse(packageFileContents);
  return packageObject.version;
}

function spawnProcess (type, args=[]) {
  var childProcess;
  var postFix = IS_WINDOWS ? ".cmd" : "";
  switch (type) {
    case "client":
      childProcess = spawn("gluestick" + postFix, ["start-client", ...args], {stdio: "inherit", env: Object.assign({}, process.env)});
      break;
    case "server":
      childProcess = spawn("gluestick" + postFix, ["start-server", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-server"})});
      break;
    case "test":
      childProcess = spawn("gluestick" + postFix, ["start-test", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-test"})});
      break;
  }

  childProcess.on("error", function (data) { console.log(chalk.red(JSON.stringify(arguments))) });
  return childProcess;
}

async function startAll(withoutTests=false, debug=false) {
  try {
    await autoUpgrade();
  }
  catch (e) {
    console.log(chalk.red("ERROR during auto upgrade"), e);
    process.exit();
  }

  var client = spawnProcess("client");
  var server = spawnProcess("server", (debug ? ["--debug"] : []));

  // Start tests unless they asked us not to or we are in production mode
  if (!isProduction && !withoutTests) {
    var testProcess = spawnProcess("test");
  }
}

async function upgradeAndDockerize (name) {
  await autoUpgrade();
  dockerize(name);
}

function updateLastVersionUsed() {
  const fileHeader = "DO NOT MODIFY";

  // Check version in .gluestick file
  const gluestickDotFile = path.join(process.cwd(), ".gluestick");
  var fileContents = fs.readFileSync(gluestickDotFile, {encoding: "utf8"}).replace(fileHeader, "");
  // If the dot file only had the header (and possibly a new line character), then it definitely doesn't have the version check and is old
  fileContents = (fileContents.length <= 1)? '{"version": "`unknown version`"}': fileContents;
  var json = JSON.parse(fileContents);
  if (shouldUpdateForProjectGluestickVersion(json.version)) {
    console.log(chalk.yellow("This project is configured to work with versions >= " + json.version + " Please upgrade your global `gluestick` module with `sudo npm install gluestick -g"));
  }

  // update version in dot file
  var newContents = fileHeader + "\n";
  newContents += JSON.stringify({version: getVersion()});
  fs.writeFileSync(gluestickDotFile, newContents);
}

function shouldUpdateForProjectGluestickVersion(projectGluestickVersion) {
  var mine = getVersion().split('.');
  var project = projectGluestickVersion.split('.');

  if (mine[0] !== project[0]
      || mine[1] !== project[1]
      || mine[2] !== project[2]) {
    return true;
  }
  else {
    return false;
  }
}
<commit_msg>always be able to deal with old file header, but never re-add it<commit_after>const commander = require("commander");
const fs = require("fs");
const path = require("path");
const process = require("process");
const {exec, spawn} = require("child_process");
const lazyMethodRequire = require("./lib/LazyMethodRequire")(__dirname);

const newApp = lazyMethodRequire("./commands/new");
const startClient = lazyMethodRequire("./commands/start-client");
const startServer = lazyMethodRequire("./commands/start-server");
const startTest = lazyMethodRequire("./commands/test");
const generate = lazyMethodRequire("./commands/generate");
const destroy = lazyMethodRequire("./commands/destroy");
const dockerize = lazyMethodRequire("./commands/dockerize");

const chalk = require("chalk");
const autoUpgrade = require("./auto-upgrade");
const chokidar = require("chokidar");

const command = process.argv[2];
const isProduction = process.env.NODE_ENV === "production";

const IS_WINDOWS = process.platform === "win32";

commander
  .version(getVersion());

commander
  .command("touch")
  .description("update project version")
  .action((options)=> updateLastVersionUsed())

commander
  .command("new")
  .description("generate a new application")
  .arguments("<app_name>")
  .action(newApp)
  .action((options)=> updateLastVersionUsed());

commander
  .command("generate <container|component|reducer>")
  .description("generate a new container")
  .arguments("<name>")
  .action((type, name) => generate(type, name, (err) => {
    if (err) console.log(chalk.red(`ERROR: ${err}`));
  }))
  .action((options)=> updateLastVersionUsed())

commander
  .command("destroy <container|component|reducer>")
  .description("destroy a generated container")
  .arguments("<name>")
  .action(destroy)
  .action((options)=> updateLastVersionUsed());

const debugOption = {
  command: "-D, --debug",
  description: "debug server side rendering with node-inspector"
};

commander
  .command("start")
  .description("start everything")
  .option("-T, --no_tests", "ignore test hook")
  .option(debugOption.command, debugOption.description)
  .action((options) => startAll(options.no_tests, options.debug))
  .action((options)=> updateLastVersionUsed());

commander
  .command("build")
  .description("create production asset build")
  .action(() => startClient(true))
  .action((options)=> updateLastVersionUsed());

commander
  .command("dockerize")
  .description("create docker image")
  .arguments("<name>")
  .action(upgradeAndDockerize)
  .action((options)=> updateLastVersionUsed());

commander
  .command("start-client", null, {noHelp: true})
  .description("start client")
  .action(() => startClient(false))
  .action((options)=> updateLastVersionUsed());

commander
  .command("start-server", null, {noHelp: true})
  .description("start server")
  .option(debugOption.command, debugOption.description)
  .action((options) => startServer(options.debug))
  .action((options)=> updateLastVersionUsed());

const firefoxOption = {
  command: "-F, --firefox",
  description: "Use Firefox with test runner"
};

commander
  .command("start-test", null, {noHelp: true})
  .option(firefoxOption.command, firefoxOption.description)
  .description("start test")
  .action((options) => startTest(options))
  .action((options)=> updateLastVersionUsed());

commander
  .command("test")
  .option(firefoxOption.command, firefoxOption.description)
  .description("start tests")
  .action(() => spawnProcess("test", process.argv.slice(3)))
  .action((options)=> updateLastVersionUsed());

// This is a catch all command. DO NOT PLACE ANY COMMANDS BELOW THIS
commander
  .command('*', null, {noHelp: true})
  .action(function(cmd){
    console.log(`Error: Command '${cmd}' not recognized`);
    commander.help();
});

commander.parse(process.argv);

function getVersion () {
  var packageFileContents = fs.readFileSync(path.join(__dirname, "..", "package.json"));
  var packageObject = JSON.parse(packageFileContents);
  return packageObject.version;
}

function spawnProcess (type, args=[]) {
  var childProcess;
  var postFix = IS_WINDOWS ? ".cmd" : "";
  switch (type) {
    case "client":
      childProcess = spawn("gluestick" + postFix, ["start-client", ...args], {stdio: "inherit", env: Object.assign({}, process.env)});
      break;
    case "server":
      childProcess = spawn("gluestick" + postFix, ["start-server", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-server"})});
      break;
    case "test":
      childProcess = spawn("gluestick" + postFix, ["start-test", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-test"})});
      break;
  }

  childProcess.on("error", function (data) { console.log(chalk.red(JSON.stringify(arguments))) });
  return childProcess;
}

async function startAll(withoutTests=false, debug=false) {
  try {
    await autoUpgrade();
  }
  catch (e) {
    console.log(chalk.red("ERROR during auto upgrade"), e);
    process.exit();
  }

  var client = spawnProcess("client");
  var server = spawnProcess("server", (debug ? ["--debug"] : []));

  // Start tests unless they asked us not to or we are in production mode
  if (!isProduction && !withoutTests) {
    var testProcess = spawnProcess("test");
  }
}

async function upgradeAndDockerize (name) {
  await autoUpgrade();
  dockerize(name);
}

function updateLastVersionUsed() {
  const fileHeader = "DO NOT MODIFY";

  // Check version in .gluestick file
  const gluestickDotFile = path.join(process.cwd(), ".gluestick");
  var fileContents = fs.readFileSync(gluestickDotFile, {encoding: "utf8"})
  // We won't know how old this version is, it might have still have the 'DO NOT MODIFY' header
  fileContents = fileContents.replace(fileHeader, "");
  // If the dot file only had the header (and possibly a new line character), then it definitely doesn't have the version check and is old
  fileContents = (fileContents.length <= 1)? '{"version": "`unknown version`"}': fileContents;
  var json = JSON.parse(fileContents);
  if (shouldUpdateForProjectGluestickVersion(json.version)) {
    console.log(chalk.yellow("This project is configured to work with versions >= " + json.version + " Please upgrade your global `gluestick` module with `sudo npm install gluestick -g"));
  }

  // update version in dot file. No longer want the 'Do Not Modify' text
  const newContents = JSON.stringify({version: getVersion()});
  fs.writeFileSync(gluestickDotFile, newContents);
}

function shouldUpdateForProjectGluestickVersion(projectGluestickVersion) {
  var mine = getVersion().split('.');
  var project = projectGluestickVersion.split('.');

  if (mine[0] !== project[0]
      || mine[1] !== project[1]
      || mine[2] !== project[2]) {
    return true;
  }
  else {
    return false;
  }
}
<|endoftext|>


<commit_before>const commander = require("commander");
const process = require("process");
const { spawn } = require("cross-spawn");
const fs = require("fs-extra");
const path = require("path");
const lazyMethodRequire = require("./lib/LazyMethodRequire").default(__dirname);

const newApp = lazyMethodRequire("./commands/new");
const startClient = lazyMethodRequire("./commands/start-client");
const startServer = lazyMethodRequire("./commands/start-server");
const startTest = lazyMethodRequire("./commands/test");
const generate = lazyMethodRequire("./commands/generate");
const destroy = lazyMethodRequire("./commands/destroy");
const dockerize = lazyMethodRequire("./commands/dockerize");

const updateLastVersionUsed = require("./lib/updateVersion");
const getVersion = require("./lib/getVersion");
const logger = require("./lib/logger");
const logsColorScheme = require("./lib/logsColorScheme");
const { highlight } = logsColorScheme;

const utils = require("./lib/utils");
const { quitUnlessGluestickProject } = utils;

const autoUpgrade = require("./autoUpgrade");

const isProduction = process.env.NODE_ENV === "production";

const IS_WINDOWS = process.platform === "win32";

const currentGluestickVersion = getVersion();

const debugServerOption = ["-D, --debug-server", "debug server side rendering with node-inspector"];
const debugTestOption = ["-B, --debug-test", "debug tests with node-inspector"];
const karmaTestOption = ["-k, --karma", "run tests in Karma"];
const mochaReporterOption = ["-r, --reporter [type]", "run tests in Node.js"];
const firefoxOption = ["-F, --firefox", "Use Firefox with test runner"];
const singleRunOption = ["-S, --single", "Run test suite only once"];
const skipBuildOption = ["-P, --skip-build", "skip build when running in production mode"];

commander
  .version(currentGluestickVersion);

commander
  .command("touch")
  .description("update project version")
  .action(checkGluestickProject)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("new")
  .description("generate a new application")
  .arguments("<app_name>")
  .action((app_name) => {
    if(newApp(app_name)) {
      updateLastVersionUsed(currentGluestickVersion, false);
    }
  });

commander
  .command("generate <container|component|reducer>")
  .description("generate a new container")
  .arguments("<name>")
  .action(checkGluestickProject)
  .action((type, name) => generate(type, name, (err) => {
    if (err) { logger.error(err); }
  }))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("destroy <container|component|reducer>")
  .description("destroy a generated container")
  .arguments("<name>")
  .action(checkGluestickProject)
  .action(destroy)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start")
  .description("start everything")
  .option("-T, --skip-tests", "ignore test hook")
  .option(...debugServerOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .option(...karmaTestOption)
  .option(...skipBuildOption)
  .action(checkGluestickProject)
  .action(() => notifyUpdates())
  .action(startAll)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("build")
  .description("create production asset build")
  .action(checkGluestickProject)
  .action(() => startClient(true))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("dockerize")
  .description("create docker image")
  .arguments("<name>")
  .action(checkGluestickProject)
  .action(upgradeAndDockerize)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start-client", null, {noHelp: true})
  .description("start client")
  .action(checkGluestickProject)
  .action(() => startClient(false))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start-server", null, {noHelp: true})
  .description("start server")
  .option(...debugServerOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .action(checkGluestickProject)
  .action((options) => startServer(options.debugServer))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start-test", null, {noHelp: true})
  .option(...firefoxOption)
  .option(...singleRunOption)
  .option(...karmaTestOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .description("start test")
  .action(checkGluestickProject)
  .action(startTest)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("test")
  .option(...firefoxOption)
  .option(...singleRunOption)
  .option(...karmaTestOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .description("start tests")
  .action(checkGluestickProject)
  .action(() => updateLastVersionUsed(currentGluestickVersion))
  .action(() => {
    const proc = spawnProcess("test", commander.rawArgs.slice(3));
    proc.on("close", code => { process.exit(code); });
  });

// This is a catch all command. DO NOT PLACE ANY COMMANDS BELOW THIS
commander
  .command("*", null, {noHelp: true})
  .action(function(cmd){
    logger.error(`Command '${highlight(cmd)}' not recognized`);
    commander.help();
  });

commander.parse(process.argv);

function checkGluestickProject () {
  quitUnlessGluestickProject(commander.rawArgs[2]);
}

function notifyUpdates () {
  const indexFilePath = path.join(process.cwd(), "Index.js");
  const data = fs.readFileSync(indexFilePath);
  if (data.indexOf("Helmet.rewind()") === -1) {
    logger.info(`
##########################################################################
Upgrade Notice: Newer versions of Index.js now include react-helmet
for allowing dynamic changes to document header data. You will need to
manually update your Index.js file to receive this change.
For a simple example see:
https://github.com/TrueCar/gluestick/blob/develop/templates/new/Index.js
##########################################################################
    `);
  }
}

function spawnProcess (type, args=[]) {
  let childProcess;
  const postFix = IS_WINDOWS ? ".cmd" : "";
  switch (type) {
    case "client":
      childProcess = spawn("gluestick" + postFix, ["start-client", ...args], {stdio: "inherit", env: Object.assign({}, process.env)});
      break;
    case "server":
      childProcess = spawn("gluestick" + postFix, ["start-server", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-server"})});
      break;
    case "test":
      childProcess = spawn("gluestick" + postFix, ["start-test", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-test"})});
      break;
    default:
      break;
  }
  childProcess.on("error", function () { logger.error(JSON.stringify(arguments)); });
  return childProcess;
}

/*
 * Start server and (optionally) tests in different processes.
 *
 * @param {object} options        Command-line options object directly from Commander
 */
async function startAll(options) {
  try {
    await autoUpgrade();
  }
  catch (e) {
    logger.error(`During auto upgrade: ${e}`);
    process.exit();
  }

  // in production spawning the client really just creates a build. Our docker
  // images pre-build and therefor they start with the skip build option as
  // true.  We only want to start the client in development mode or if
  // skipBuild is not specified
  if (!(isProduction && options.skipBuild)) {
    spawnProcess("client");
  }

  spawnProcess("server", (options.debugServer ? ["--debug-server"] : []));

  // Start tests unless they asked us not to or we are in production mode
  if (!isProduction && !options.skipTests) {
    spawnProcess("test", commander.rawArgs.slice(3));
  }
}

async function upgradeAndDockerize (name) {
  await autoUpgrade();
  dockerize(name);
}

<commit_msg>Alias `s` to `start` command<commit_after>const commander = require("commander");
const process = require("process");
const { spawn } = require("cross-spawn");
const fs = require("fs-extra");
const path = require("path");
const lazyMethodRequire = require("./lib/LazyMethodRequire").default(__dirname);

const newApp = lazyMethodRequire("./commands/new");
const startClient = lazyMethodRequire("./commands/start-client");
const startServer = lazyMethodRequire("./commands/start-server");
const startTest = lazyMethodRequire("./commands/test");
const generate = lazyMethodRequire("./commands/generate");
const destroy = lazyMethodRequire("./commands/destroy");
const dockerize = lazyMethodRequire("./commands/dockerize");

const updateLastVersionUsed = require("./lib/updateVersion");
const getVersion = require("./lib/getVersion");
const logger = require("./lib/logger");
const logsColorScheme = require("./lib/logsColorScheme");
const { highlight } = logsColorScheme;

const utils = require("./lib/utils");
const { quitUnlessGluestickProject } = utils;

const autoUpgrade = require("./autoUpgrade");

const isProduction = process.env.NODE_ENV === "production";

const IS_WINDOWS = process.platform === "win32";

const currentGluestickVersion = getVersion();

const debugServerOption = ["-D, --debug-server", "debug server side rendering with node-inspector"];
const debugTestOption = ["-B, --debug-test", "debug tests with node-inspector"];
const karmaTestOption = ["-k, --karma", "run tests in Karma"];
const mochaReporterOption = ["-r, --reporter [type]", "run tests in Node.js"];
const firefoxOption = ["-F, --firefox", "Use Firefox with test runner"];
const singleRunOption = ["-S, --single", "Run test suite only once"];
const skipBuildOption = ["-P, --skip-build", "skip build when running in production mode"];

commander
  .version(currentGluestickVersion);

commander
  .command("touch")
  .description("update project version")
  .action(checkGluestickProject)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("new")
  .description("generate a new application")
  .arguments("<app_name>")
  .action((app_name) => {
    if(newApp(app_name)) {
      updateLastVersionUsed(currentGluestickVersion, false);
    }
  });

commander
  .command("generate <container|component|reducer>")
  .description("generate a new container")
  .arguments("<name>")
  .action(checkGluestickProject)
  .action((type, name) => generate(type, name, (err) => {
    if (err) { logger.error(err); }
  }))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("destroy <container|component|reducer>")
  .description("destroy a generated container")
  .arguments("<name>")
  .action(checkGluestickProject)
  .action(destroy)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start")
  .alias("s")
  .description("start everything")
  .option("-T, --skip-tests", "ignore test hook")
  .option(...debugServerOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .option(...karmaTestOption)
  .option(...skipBuildOption)
  .action(checkGluestickProject)
  .action(() => notifyUpdates())
  .action(startAll)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("build")
  .description("create production asset build")
  .action(checkGluestickProject)
  .action(() => startClient(true))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("dockerize")
  .description("create docker image")
  .arguments("<name>")
  .action(checkGluestickProject)
  .action(upgradeAndDockerize)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start-client", null, {noHelp: true})
  .description("start client")
  .action(checkGluestickProject)
  .action(() => startClient(false))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start-server", null, {noHelp: true})
  .description("start server")
  .option(...debugServerOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .action(checkGluestickProject)
  .action((options) => startServer(options.debugServer))
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("start-test", null, {noHelp: true})
  .option(...firefoxOption)
  .option(...singleRunOption)
  .option(...karmaTestOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .description("start test")
  .action(checkGluestickProject)
  .action(startTest)
  .action(() => updateLastVersionUsed(currentGluestickVersion));

commander
  .command("test")
  .option(...firefoxOption)
  .option(...singleRunOption)
  .option(...karmaTestOption)
  .option(...debugTestOption)
  .option(...mochaReporterOption)
  .description("start tests")
  .action(checkGluestickProject)
  .action(() => updateLastVersionUsed(currentGluestickVersion))
  .action(() => {
    const proc = spawnProcess("test", commander.rawArgs.slice(3));
    proc.on("close", code => { process.exit(code); });
  });

// This is a catch all command. DO NOT PLACE ANY COMMANDS BELOW THIS
commander
  .command("*", null, {noHelp: true})
  .action(function(cmd){
    logger.error(`Command '${highlight(cmd)}' not recognized`);
    commander.help();
  });

commander.parse(process.argv);

function checkGluestickProject () {
  quitUnlessGluestickProject(commander.rawArgs[2]);
}

function notifyUpdates () {
  const indexFilePath = path.join(process.cwd(), "Index.js");
  const data = fs.readFileSync(indexFilePath);
  if (data.indexOf("Helmet.rewind()") === -1) {
    logger.info(`
##########################################################################
Upgrade Notice: Newer versions of Index.js now include react-helmet
for allowing dynamic changes to document header data. You will need to
manually update your Index.js file to receive this change.
For a simple example see:
https://github.com/TrueCar/gluestick/blob/develop/templates/new/Index.js
##########################################################################
    `);
  }
}

function spawnProcess (type, args=[]) {
  let childProcess;
  const postFix = IS_WINDOWS ? ".cmd" : "";
  switch (type) {
    case "client":
      childProcess = spawn("gluestick" + postFix, ["start-client", ...args], {stdio: "inherit", env: Object.assign({}, process.env)});
      break;
    case "server":
      childProcess = spawn("gluestick" + postFix, ["start-server", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-server"})});
      break;
    case "test":
      childProcess = spawn("gluestick" + postFix, ["start-test", ...args], {stdio: "inherit", env: Object.assign({}, process.env, {NODE_ENV: isProduction ? "production": "development-test"})});
      break;
    default:
      break;
  }
  childProcess.on("error", function () { logger.error(JSON.stringify(arguments)); });
  return childProcess;
}

/*
 * Start server and (optionally) tests in different processes.
 *
 * @param {object} options        Command-line options object directly from Commander
 */
async function startAll(options) {
  try {
    await autoUpgrade();
  }
  catch (e) {
    logger.error(`During auto upgrade: ${e}`);
    process.exit();
  }

  // in production spawning the client really just creates a build. Our docker
  // images pre-build and therefor they start with the skip build option as
  // true.  We only want to start the client in development mode or if
  // skipBuild is not specified
  if (!(isProduction && options.skipBuild)) {
    spawnProcess("client");
  }

  spawnProcess("server", (options.debugServer ? ["--debug-server"] : []));

  // Start tests unless they asked us not to or we are in production mode
  if (!isProduction && !options.skipTests) {
    spawnProcess("test", commander.rawArgs.slice(3));
  }
}

async function upgradeAndDockerize (name) {
  await autoUpgrade();
  dockerize(name);
}

<|endoftext|>


<commit_before>/*!
 * ====================================================
 * kv-markdown.js
 * ====================================================
 * A markdown editor parser for PHP Markdown Extra and
 * PHP SmartyPants. Designed for Yii Framework 2.0
 *
 * https://github.com/kartik-v/yii2-markdown
 *
 * Copyright (c) 2013, Kartik Visweswaran
 * Krajee.com
 * Licensed under BSD-3 License.
 * Refer attached LICENSE.md for details.
 * Version: 1.0.1
 * Build date: 6 September 2013
 */
String.prototype.trimRight = function(charlist) {
    if (charlist === undefined) {
        charlist = "\s";
    }
    return this.replace(new RegExp("[" + charlist + "]+$"), "");
};

String.prototype.repeat = function(n) {
    n = n || 1;
    return Array(n + 1).join(this);
}

function isEmpty(value, trim) {
    return value === null || value === undefined || value == []
            || value === '' || trim && $.trim(value) === '';
}

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function genSaveFile(vCss, vHeader, vData, vType, vAlert, vUrl, vNullMsg) {
    alert(vAlert)
    output = vHeader + vData

    if (vType == 'HTML') {
        $.ajax({
            type: "POST",
            url: vUrl,
            dataType: "json",
            data: {
                source: output,
                nullMsg: vNullMsg
            },
            success: function(data) {
                if (data) {
                    url = "data:x-application/text," + escape(vCss + data)
                    window.open(url);
                } else {
                    alert('HTML conversion failed! Try again later.'); // debug purposes
                }
            }
        });
    } else {
        url = "data:x-application/text," + escape(output)
        window.open(url);
    }

}

function togglePreview(params) {
    var editor = params.editor,
            preview = params.preview,
            source = params.source,
            target = params.target,
            url = params.url,
            progress = params.progress,
            nullMsg = params.nullMsg;

    $(preview).toggleClass('active');
    if ($(target).hasClass('hidden')) {
        disableButtons(editor)
        $(preview).removeAttr('disabled')
        $(source).addClass('hidden');
        $(target).removeClass('hidden');
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            data: {
                source: $(source).val(),
                nullMsg: nullMsg
            },
            beforeSend: function() {
                $(target).html(progress);
            },
            success: function(data) {
                if (data) {
                    $(target).html(data);
                } else {
                    alert('HTML preview failed! Try again later.'); //testing purpose
                }
            }
        });
        $(target).focus();
    } else {
        enableButtons(editor)
        $(source).removeClass('hidden');
        $(target).addClass('hidden');
        $(source).focus();
    }
}

function enableButtons(editor) {
    $(editor + ' button').each(function() {
        $(this).removeAttr('disabled')
    })
}

function disableButtons(editor) {
    $(editor + ' button').each(function() {
        if ($(this).attr('data-enabled') == undefined) {
            $(this).attr('disabled', 'disabled')
        }
    })
}

function getMarkUp(txt, begin, end) {
    var m = begin.length,
            n = end.length
    var str = txt
    if (m > 0) {
        str = (str.slice(0, m) == begin) ? str.slice(m) : begin + str
    }
    if (n > 0) {
        str = (str.slice(-n) == end) ? str.slice(0, -n) : str + end
    }
    return str;
}

function getBlockMarkUp(txt, begin, end) {
    var str = txt
    if (str.indexOf('\n') < 0) {
        str = getMarkUp(txt, begin, end);
    } else {
        var list = []
        list = txt.split('\n')
        $.each(list, function(k, v) {
            list[k] = getMarkUp(v.trimRight(), begin, end + '  ')
        })
        str = list.join('\n')
    }
    return str
}

function markUp(btn, source) {
    var el = $(source)
    el.focus();
    var txt = el.extractSelectedText(),
            len = txt.length,
            str = txt

    // Bold
    if (btn == 1) {
        str = (txt.length > 0) ? getBlockMarkUp(txt, '**', '**') : '**(bold text here)**';
    }
    // Italic
    else if (btn == 2) {
        str = (txt.length > 0) ? getBlockMarkUp(txt, '*', '*') : '*(italic text here)*';
    }
    // Paragraph
    else if (btn == 3) {
        str = (txt.length > 0) ? getMarkUp(txt, '\n', '\n') : '\n(paragraph text here)\n';
    }
    // New Line
    else if (btn == 4) {
        str = getBlockMarkUp(txt, '', '  ');
    }
    // Header
    else if (btn > 100) {
        n = btn - 100
        var pad = "#".repeat(n)
        str = getMarkUp(txt, pad + " ", " " + pad);
    }
    // Hyperlink
    else if (btn == 5) {
        link = prompt('Insert Hyperlink', 'http://')
        str = (link != null && link != '' && link != 'http://') ? '[' + txt + '] (' + link + ')' : txt
    }
    // Image
    else if (btn == 6) {
        link = prompt('Insert Image Hyperlink', 'http://')
        str = (link != null && link != '' && link != 'http://') ? '![' + txt + '] (' + link + ' "enter image title here")' : txt
    }
    // Add Indent
    else if (btn == 7) {
        var str = txt,
                ind = '  '
        if (str.indexOf('\n') < 0) {
            str = ind + str
        } else {
            var list = []
            list = txt.split('\n')
            $.each(list, function(k, v) {
                list[k] = ind + v
            })
            str = list.join('\n')
        }
    }
    // Remove Indent
    else if (btn == 8) {
        var str = txt,
                ind = '  '
        if (str.indexOf('\n') < 0 && str.substr(0, 2) == ind) {
            str = str.slice(2)
        } else {
            var list = []
            list = txt.split('\n')
            $.each(list, function(k, v) {
                list[k] = v
                if (v.substr(0, 2) == ind) {
                    list[k] = v.slice(2)
                }
            })
            str = list.join('\n')
        }
    }
    // Unordered List
    else if (btn == 9) {
        str = getBlockMarkUp(txt, "- ", "");
    }
    // Ordered List
    else if (btn == 10) {
        start = prompt('Enter starting number', 1)
        if (start != null && start != '') {
            if (!isNumber(start)) {
                start = 1
            }
            if (txt.indexOf('\n') < 0) {
                str = getMarkUp(txt, start + '. ', '');
            } else {
                var list = [],
                        i = start
                list = txt.split('\n')
                $.each(list, function(k, v) {
                    list[k] = getMarkUp(v, i + '. ', '')
                    i++
                })
                str = list.join('\n')
            }
        }
    }
    // Definition List
    else if (btn == 11) {
        if (txt.indexOf('\n') > 0) {
            var list = [],
                    i = 1
            list = txt.split('\n')
            $.each(list, function(k, v) {
                tag = (i % 2 == 0) ? ':    ' : '';
                list[k] = getMarkUp(v, tag, '')
                i++
            })
            str = list.join('\n')
        } else {
            str = txt + "\n:    \n"
        }
    }
    // Footnote
    else if (btn == 12) {
        title = 'Enter footnote '
        notes = ''
        if (txt.indexOf('\n') < 0) {
            notes = '[^1]: ' + title + '1\n'
            str = getMarkUp(txt, '', title + '[^1]') + "\n" + notes;
        } else {
            var list = [],
                    i = 1
            list = txt.split('\n')
            $.each(list, function(k, v) {
                id = '[^' + i + ']'
                list[k] = getMarkUp(v, '', id + '  ')
                notes = notes + id + ': ' + title + i + '\n'
                i++
            })
            str = list.join('\n') + "  \n\n" + notes
        }
    }
    // Blockquote
    else if (btn == 13) {
        str = getBlockMarkUp(txt, "> ", "  ");
    }
    // Inline Code
    else if (btn == 14) {
        str = getMarkUp(txt, "`", "`");
    }
    // Code Block
    else if (btn == 15) {
        lang = prompt('Enter code language (e.g. html)', '')
        if (isEmpty(lang, true)) {
            lang = '';
        }
        str = getMarkUp(txt, "~~~" + lang + " \n", "\n~~~  \n");
    }
    // Horizontal Line
    else if (btn == 16) {
        str = getMarkUp(txt, '', '\n- - -');
    }
    if (!isEmpty(str)) {
        el.replaceSelectedText(str, "select")
    }
}

function toggleScreen(btn, container, editor, modal, preview, defHeight) {
    h = $(window).height();
    if ($(btn).hasClass('active')) {
        $(btn).removeClass('active')
        val = $(modal + ' textarea').val()
        $(modal + ' textarea').height(defHeight);
        $(modal + ' ' + preview).css('max-height', defHeight);
        $(modal + ' ' + editor).clone(true).appendTo(container);
        $(container + ' textarea').val(val)
        $(modal + ' ' + editor).remove();
        $('.kv-fullscreen').modal("hide");
    } else {
        $(btn).addClass('active')
        val = $(container + ' textarea').val()
        $(container + ' ' + editor).clone(true).appendTo(modal)
        $(container + ' ' + editor).remove();
        $(modal + ' textarea').height(0.75 * h);
        $(modal + ' ' + preview).css('max-height', 0.75 * h);
        $(modal + ' textarea').val(val)
        $('.kv-fullscreen').modal("show")
    }
}

function initEditor(params) {
    var input = params.source,
            editor = params.editor,
            preview = params.preview,
            target = params.target,
            maximize = params.maximize,
            container = params.container,
            modal = editor.slice(1) + '-modal',
            save1 = params.save1,
            save2 = params.save2,
            defHeight = params.height

    $(input).focus(function() {
        $(editor).addClass('active');
    });

    $(input).blur(function() {
        $(editor).removeClass('active');
    });

    $(preview).click(function() {
        togglePreview(params);
    });

    $(save1).click(function() {
        genSaveFile('', params.saveHeader, $(input).val(), 'Text', params.saveText, params.url, params.nullMsg);
    });

    $(save2).click(function() {
        genSaveFile(params.saveCss, params.saveHeader, $(input).val(), 'HTML', params.saveHtml, params.url, params.nullMsg);
    });

    $('body').remove('.kv-fullscreen');
    $('body').append('

')
    modal = '#' + modal

    $(editor + ' ' + target).css('max-height', defHeight)
    $(editor + ' textarea').height(defHeight)

    $(maximize).click(function() {
        toggleScreen(maximize, container, editor, modal, target, defHeight);
    });
}<commit_msg>Updated null display when data is empty<commit_after>/*!
 * ====================================================
 * kv-markdown.js
 * ====================================================
 * A markdown editor parser for PHP Markdown Extra and
 * PHP SmartyPants. Designed for Yii Framework 2.0
 *
 * https://github.com/kartik-v/yii2-markdown
 *
 * Copyright (c) 2013, Kartik Visweswaran
 * Krajee.com
 * Licensed under BSD-3 License.
 * Refer attached LICENSE.md for details.
 * Version: 1.0.1
 * Build date: 6 September 2013
 */
String.prototype.trimRight = function(charlist) {
    if (charlist === undefined) {
        charlist = "\s";
    }
    return this.replace(new RegExp("[" + charlist + "]+$"), "");
};

String.prototype.repeat = function(n) {
    n = n || 1;
    return Array(n + 1).join(this);
}

function isEmpty(value, trim) {
    return value === null || value === undefined || value == []
            || value === '' || trim && $.trim(value) === '';
}

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function genSaveFile(vCss, vHeader, vData, vType, vAlert, vUrl, vNullMsg) {
    alert(vAlert)
    output = vHeader + vData

    if (vType == 'HTML') {
        $.ajax({
            type: "POST",
            url: vUrl,
            dataType: "json",
            data: {
                source: output,
                nullMsg: vNullMsg
            },
            success: function(data) {
                if (data) {
                    url = "data:x-application/text," + escape(vCss + data)
                    window.open(url);
                } else {
                    alert('HTML conversion failed! Try again later.'); // debug purposes
                }
            }
        });
    } else {
        url = "data:x-application/text," + escape(output)
        window.open(url);
    }

}

function togglePreview(params) {
    var editor = params.editor,
            preview = params.preview,
            source = params.source,
            target = params.target,
            url = params.url,
            progress = params.progress,
            nullMsg = params.nullMsg;

    $(preview).toggleClass('active');
    if ($(target).hasClass('hidden')) {
        disableButtons(editor)
        $(preview).removeAttr('disabled')
        $(source).addClass('hidden');
        $(target).removeClass('hidden');
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            data: {
                source: $(source).val(),
                nullMsg: nullMsg
            },
            beforeSend: function() {
                $(target).html(progress);
            },
            success: function(data) {
                if (data) {
                    $(target).html(data);
                } else {
                    $(target).html(nullMsg);
                }
            }
        });
        $(target).focus();
    } else {
        enableButtons(editor)
        $(source).removeClass('hidden');
        $(target).addClass('hidden');
        $(source).focus();
    }
}

function enableButtons(editor) {
    $(editor + ' button').each(function() {
        $(this).removeAttr('disabled')
    })
}

function disableButtons(editor) {
    $(editor + ' button').each(function() {
        if ($(this).attr('data-enabled') == undefined) {
            $(this).attr('disabled', 'disabled')
        }
    })
}

function getMarkUp(txt, begin, end) {
    var m = begin.length,
            n = end.length
    var str = txt
    if (m > 0) {
        str = (str.slice(0, m) == begin) ? str.slice(m) : begin + str
    }
    if (n > 0) {
        str = (str.slice(-n) == end) ? str.slice(0, -n) : str + end
    }
    return str;
}

function getBlockMarkUp(txt, begin, end) {
    var str = txt
    if (str.indexOf('\n') < 0) {
        str = getMarkUp(txt, begin, end);
    } else {
        var list = []
        list = txt.split('\n')
        $.each(list, function(k, v) {
            list[k] = getMarkUp(v.trimRight(), begin, end + '  ')
        })
        str = list.join('\n')
    }
    return str
}

function markUp(btn, source) {
    var el = $(source)
    el.focus();
    var txt = el.extractSelectedText(),
            len = txt.length,
            str = txt

    // Bold
    if (btn == 1) {
        str = (txt.length > 0) ? getBlockMarkUp(txt, '**', '**') : '**(bold text here)**';
    }
    // Italic
    else if (btn == 2) {
        str = (txt.length > 0) ? getBlockMarkUp(txt, '*', '*') : '*(italic text here)*';
    }
    // Paragraph
    else if (btn == 3) {
        str = (txt.length > 0) ? getMarkUp(txt, '\n', '\n') : '\n(paragraph text here)\n';
    }
    // New Line
    else if (btn == 4) {
        str = getBlockMarkUp(txt, '', '  ');
    }
    // Header
    else if (btn > 100) {
        n = btn - 100
        var pad = "#".repeat(n)
        str = getMarkUp(txt, pad + " ", " " + pad);
    }
    // Hyperlink
    else if (btn == 5) {
        link = prompt('Insert Hyperlink', 'http://')
        str = (link != null && link != '' && link != 'http://') ? '[' + txt + '] (' + link + ')' : txt
    }
    // Image
    else if (btn == 6) {
        link = prompt('Insert Image Hyperlink', 'http://')
        str = (link != null && link != '' && link != 'http://') ? '![' + txt + '] (' + link + ' "enter image title here")' : txt
    }
    // Add Indent
    else if (btn == 7) {
        var str = txt,
                ind = '  '
        if (str.indexOf('\n') < 0) {
            str = ind + str
        } else {
            var list = []
            list = txt.split('\n')
            $.each(list, function(k, v) {
                list[k] = ind + v
            })
            str = list.join('\n')
        }
    }
    // Remove Indent
    else if (btn == 8) {
        var str = txt,
                ind = '  '
        if (str.indexOf('\n') < 0 && str.substr(0, 2) == ind) {
            str = str.slice(2)
        } else {
            var list = []
            list = txt.split('\n')
            $.each(list, function(k, v) {
                list[k] = v
                if (v.substr(0, 2) == ind) {
                    list[k] = v.slice(2)
                }
            })
            str = list.join('\n')
        }
    }
    // Unordered List
    else if (btn == 9) {
        str = getBlockMarkUp(txt, "- ", "");
    }
    // Ordered List
    else if (btn == 10) {
        start = prompt('Enter starting number', 1)
        if (start != null && start != '') {
            if (!isNumber(start)) {
                start = 1
            }
            if (txt.indexOf('\n') < 0) {
                str = getMarkUp(txt, start + '. ', '');
            } else {
                var list = [],
                        i = start
                list = txt.split('\n')
                $.each(list, function(k, v) {
                    list[k] = getMarkUp(v, i + '. ', '')
                    i++
                })
                str = list.join('\n')
            }
        }
    }
    // Definition List
    else if (btn == 11) {
        if (txt.indexOf('\n') > 0) {
            var list = [],
                    i = 1
            list = txt.split('\n')
            $.each(list, function(k, v) {
                tag = (i % 2 == 0) ? ':    ' : '';
                list[k] = getMarkUp(v, tag, '')
                i++
            })
            str = list.join('\n')
        } else {
            str = txt + "\n:    \n"
        }
    }
    // Footnote
    else if (btn == 12) {
        title = 'Enter footnote '
        notes = ''
        if (txt.indexOf('\n') < 0) {
            notes = '[^1]: ' + title + '1\n'
            str = getMarkUp(txt, '', title + '[^1]') + "\n" + notes;
        } else {
            var list = [],
                    i = 1
            list = txt.split('\n')
            $.each(list, function(k, v) {
                id = '[^' + i + ']'
                list[k] = getMarkUp(v, '', id + '  ')
                notes = notes + id + ': ' + title + i + '\n'
                i++
            })
            str = list.join('\n') + "  \n\n" + notes
        }
    }
    // Blockquote
    else if (btn == 13) {
        str = getBlockMarkUp(txt, "> ", "  ");
    }
    // Inline Code
    else if (btn == 14) {
        str = getMarkUp(txt, "`", "`");
    }
    // Code Block
    else if (btn == 15) {
        lang = prompt('Enter code language (e.g. html)', '')
        if (isEmpty(lang, true)) {
            lang = '';
        }
        str = getMarkUp(txt, "~~~" + lang + " \n", "\n~~~  \n");
    }
    // Horizontal Line
    else if (btn == 16) {
        str = getMarkUp(txt, '', '\n- - -');
    }
    if (!isEmpty(str)) {
        el.replaceSelectedText(str, "select")
    }
}

function toggleScreen(btn, container, editor, modal, preview, defHeight) {
    h = $(window).height();
    if ($(btn).hasClass('active')) {
        $(btn).removeClass('active')
        val = $(modal + ' textarea').val()
        $(modal + ' textarea').height(defHeight);
        $(modal + ' ' + preview).css('max-height', defHeight);
        $(modal + ' ' + editor).clone(true).appendTo(container);
        $(container + ' textarea').val(val)
        $(modal + ' ' + editor).remove();
        $('.kv-fullscreen').modal("hide");
    } else {
        $(btn).addClass('active')
        val = $(container + ' textarea').val()
        $(container + ' ' + editor).clone(true).appendTo(modal)
        $(container + ' ' + editor).remove();
        $(modal + ' textarea').height(0.75 * h);
        $(modal + ' ' + preview).css('max-height', 0.75 * h);
        $(modal + ' textarea').val(val)
        $('.kv-fullscreen').modal("show")
    }
}

function initEditor(params) {
    var input = params.source,
            editor = params.editor,
            preview = params.preview,
            target = params.target,
            maximize = params.maximize,
            container = params.container,
            modal = editor.slice(1) + '-modal',
            save1 = params.save1,
            save2 = params.save2,
            defHeight = params.height

    $(input).focus(function() {
        $(editor).addClass('active');
    });

    $(input).blur(function() {
        $(editor).removeClass('active');
    });

    $(preview).click(function() {
        togglePreview(params);
    });

    $(save1).click(function() {
        genSaveFile('', params.saveHeader, $(input).val(), 'Text', params.saveText, params.url, params.nullMsg);
    });

    $(save2).click(function() {
        genSaveFile(params.saveCss, params.saveHeader, $(input).val(), 'HTML', params.saveHtml, params.url, params.nullMsg);
    });

    $('body').remove('.kv-fullscreen');
    $('body').append('

')
    modal = '#' + modal

    $(editor + ' ' + target).css('max-height', defHeight)
    $(editor + ' textarea').height(defHeight)

    $(maximize).click(function() {
        toggleScreen(maximize, container, editor, modal, target, defHeight);
    });
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var run = require('./run');
var log = require('./log');
var UserError = require('./error/UserError');

////////

// handler for all unhandled errors
// might be a UserError, format it accordingly

process.on('uncaughtException', function (err) {
  if (err instanceof UserError) {
    log.pref(err.userMessage);
  } else {
    console.log(err.message);
  }
  if (err.stack) {
    console.log(err.stack);
  }
});

// read user input

var args = process.argv.slice(2);
var command = args[0];

switch (command) {

case 'create':
  validate(args[1], 'Missing path to output file.', 'create');
  run.create(args[1]);
  break;

case 'init':
  validate(args[1], 'Missing path to output folder.', 'init');
  run.init(args[1]);
  break;

case 'use':
  validate(args[1], 'Missing path to config file.', 'use');
  run.use(args[1]);
  break;

case 'default':
  run.default();
  break;

case 'current':
  run.current();
  break;

default:

  if (args.length === 2) {
    run.parse(args[0], args[1]);
    break;
  }

  help();

}

////////

function validate(expression, message, command) {
  if (expression) { return; }
  log.pref(message);
  if (command) {
    help(command);
  }
  process.exit(0);
}

function help(one) {

  var commands = [
    {
      name: 'parse',
      usage: '[/path/to/source.js] [/path/to/output.spec.js]',
      description: 'Create a test by parsing existing AngularJS source file.'
    },
    {
      name: 'create',
      usage: 'create [/path/to/output.spec.js]',
      description: 'Create a test by manually entering details.'
    },
    {
      name: 'init',
      usage: 'init [/path/to/folder]',
      description: 'Copy default config and templates to a folder.'
    },
    {
      name: 'use',
      usage: 'use [/path/to/config.js]',
      description: 'Use destination config and templates.'
    },
    {
      name: 'default',
      usage: 'default',
      description: 'Use default config and templates.'
    },
    {
      name: 'current',
      usage: 'current',
      description: 'Show path of currently used config.'
    },

  ];

  var output = '';

  if (!one) {
    output += '\n';
    output += 'tleaf - AngularJS unit test generator.';
    output += '\n';
  }

  output += '\n';
  output += 'Usage:';
  output += '\n';

  _.each(commands, function (command) {
    if (!one || one === command.name) {
      var message = '';
      message += '\n';
      message += '  tleaf ' + command.usage + '\n';
      message += '    ' + command.description + '\n';

      output += message;
    }
  });

  log.info(output);
}<commit_msg>fix(cli): Add check if current process is a tty<commit_after>'use strict';

var _ = require('lodash');
var run = require('./run');
var log = require('./log');
var UserError = require('./error/UserError');

////////

// handler for all unhandled errors
// might be a UserError, format it accordingly

process.on('uncaughtException', function (err) {
  if (err instanceof UserError) {
    log.pref(err.userMessage);
  } else {
    console.log(err.message);
  }
  if (err.stack) {
    console.log(err.stack);
  }
});

// inquirer may not work with some Windows terminal wrappers
// better show user friendly message about it
// https://github.com/SBoudrias/Inquirer.js/issues/272
if (!process.stdout.isTTY) {
  throw new UserError(
    'The type of the terminal you use is not supported (not tty).'
  );
}

// read user input

var args = process.argv.slice(2);
var command = args[0];

switch (command) {

case 'create':
  validate(args[1], 'Missing path to output file.', 'create');
  run.create(args[1]);
  break;

case 'init':
  validate(args[1], 'Missing path to output folder.', 'init');
  run.init(args[1]);
  break;

case 'use':
  validate(args[1], 'Missing path to config file.', 'use');
  run.use(args[1]);
  break;

case 'default':
  run.default();
  break;

case 'current':
  run.current();
  break;

default:

  if (args.length === 2) {
    run.parse(args[0], args[1]);
    break;
  }

  help();

}

////////

function validate(expression, message, command) {
  if (expression) { return; }
  log.pref(message);
  if (command) {
    help(command);
  }
  process.exit(0);
}

function help(one) {

  var commands = [
    {
      name: 'parse',
      usage: '[/path/to/source.js] [/path/to/output.spec.js]',
      description: 'Create a test by parsing existing AngularJS source file.'
    },
    {
      name: 'create',
      usage: 'create [/path/to/output.spec.js]',
      description: 'Create a test by manually entering details.'
    },
    {
      name: 'init',
      usage: 'init [/path/to/folder]',
      description: 'Copy default config and templates to a folder.'
    },
    {
      name: 'use',
      usage: 'use [/path/to/config.js]',
      description: 'Use destination config and templates.'
    },
    {
      name: 'default',
      usage: 'default',
      description: 'Use default config and templates.'
    },
    {
      name: 'current',
      usage: 'current',
      description: 'Show path of currently used config.'
    },

  ];

  var output = '';

  if (!one) {
    output += '\n';
    output += 'tleaf - AngularJS unit test generator.';
    output += '\n';
  }

  output += '\n';
  output += 'Usage:';
  output += '\n';

  _.each(commands, function (command) {
    if (!one || one === command.name) {
      var message = '';
      message += '\n';
      message += '  tleaf ' + command.usage + '\n';
      message += '    ' + command.description + '\n';

      output += message;
    }
  });

  log.info(output);
}<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initLists();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		//this.initHoldsReady();
		this.initHoldsPending();

	} // initHolds()

, initHoldsPending: function() {

		this.initHoldsPendingSuspend();

		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold requests(s).');
				}

			}

		});

	} // initHoldsPending()

, initHoldsPendingSuspend: function() {
		var $suspend = $('.spl-field-holds-pending-suspend');
		var $date = $('.spl-field-holds-pending-date');
		$date.on('change', function(e) {
			if ( $(this).val().length > 0 ) {
				$suspend.attr('disabled', false);
			} else {
				$suspend.attr('disabled', true);
			}
		});
		// disallow dates in the past
		$date.datepicker({startDate: new Date() });

} // initHoldsPendingSuspend()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $location = $('.spl-field-holds-pending-location');
		var $date = $('.spl-field-holds-pending-date');

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {sessionToken: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;

		switch ( action ) {
			case 'cancel':
				endpoint = 'cancel';
				break;
			case 'pickup':
				endpoint = 'pickup';
				data.params.newLocation = $location.val();
				break;
			case 'suspend':
				endpoint = 'suspend';
				data.params.suspendEndDate = $date.val();
				break;
			case 'resume':
				endpoint = 'resume';
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				//console.log(obj);
				//$submit.button('reset');
				$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initLists: function() {
		this.initListCreate();
		this.initListDelete();

	} // initLists()

, initListDelete: function() {

	}

, initListCreate: function() {
		var $form = $('#spl-form-list-create');

		var $label = $('#spl-field-list-create-label');

		$form.on('submit', function(e) {
			e.preventDefault();
			console.log('submitting new list');
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();
				console.log('process: ajax');
				var label = $label.val();
				if ( label.length > 0 ) {
					_self.createList(label);
				} else {
					alert('Please add a List Name');
				}
			} else {
				console.log('process: '+$form.data('process'));
			}

		});

	} //initListCreate

, createList: function(label) {
		var $form = $('#spl-form-list-create');
		var $submit = $('spl-submit-list-create');
		var $hidden = $('#spl-field-list-create');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'list'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	description: label
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			//console.log(obj);
			//$submit.button('reset');
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} //createList()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item) {
		var $selectAll = $(all);
		var $selectItem = $(item);

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<commit_msg>my list<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initLists();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		//this.initHoldsReady();
		this.initHoldsPending();

	} // initHolds()

, initHoldsPending: function() {

		this.initHoldsPendingSuspend();

		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold requests(s).');
				}

			}

		});

	} // initHoldsPending()

, initHoldsPendingSuspend: function() {
		var $suspend = $('.spl-field-holds-pending-suspend');
		var $date = $('.spl-field-holds-pending-date');
		$date.on('change', function(e) {
			if ( $(this).val().length > 0 ) {
				$suspend.attr('disabled', false);
			} else {
				$suspend.attr('disabled', true);
			}
		});
		// disallow dates in the past
		$date.datepicker({startDate: new Date() });

} // initHoldsPendingSuspend()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $location = $('.spl-field-holds-pending-location');
		var $date = $('.spl-field-holds-pending-date');

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {sessionToken: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;

		switch ( action ) {
			case 'cancel':
				endpoint = 'cancel';
				break;
			case 'pickup':
				endpoint = 'pickup';
				data.params.newLocation = $location.val();
				break;
			case 'suspend':
				endpoint = 'suspend';
				data.params.suspendEndDate = $date.val();
				break;
			case 'resume':
				endpoint = 'resume';
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				//console.log(obj);
				//$submit.button('reset');
				$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initLists: function() {
		this.initListCreate();
		this.initListDelete();

	} // initLists()

, initListDelete: function() {

	}

, initListCreate: function() {
		var $form = $('#spl-form-list-create');

		var $label = $('#spl-field-list-create-label');

		$form.on('submit', function(e) {
			e.preventDefault();
			console.log('submitting new list');
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();
				console.log('process: ajax');
				var label = $label.val();
				if ( label.length > 0 ) {
					_self.createList(label);
				} else {
					alert('Please add a List Name');
				}
			} else {
				console.log('process: '+$form.data('process'));
			}

		});

	} //initListCreate

, createList: function(label) {
		var $form = $('#spl-form-list-create');
		var $submit = $('.spl-submit-list-create');
		var $hidden = $('#spl-field-list-create');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'list'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	description: label
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			//console.log(obj);
			//$submit.button('reset');
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} //createList()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item) {
		var $selectAll = $(all);
		var $selectItem = $(item);

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

export const state = () => ({
    flags: {},
    version: null,
    sessionId: null,
    wiki: "enwiki", // default to English
});

export const mutations = {
    setFlags (state, flagObject) {
        state.flags = flagObject;
    },
    clearFlags (state, ) {
        state.flags = {}
    },
    setFlag (state, kv) {
        state.flags[kv.key] = kv.value;
    },
    setVersion(state, version) {
        state.version = version;
    },
    setSessionId (state, sessionId) {
        state.sessionId = sessionId;
    },
    setWiki(state, wiki) {
        state.wiki = wiki
    }
};

export const actions = {
    async nuxtServerInit({ commit, state }, { req }) {
        const flags = await this.$axios.$get(`/api/flags`);
        commit('setFlags', flags);
        const version = await this.$axios.$get(`/api/version`);
        commit('setVersion', version);
        if (req.session && req.session.id) {
            commit('setSessionId', req.session.id);
            console.log(`nuxtServerInit req.session.id`, req.session.id);
        }
        if (req.user) {
            console.log(`nuxtServerInit store state setProfile req.user`, req.user);
            commit('user/setProfile', req.user);
        } else {
            console.log(`nuxtServerInit store state clearProfile because req.user is not defined`);
            commit('user/clearProfile');
        }
    },
    async changeWiki({ commit, state, dispatch}, wiki) {
      let oldWiki = state.wiki;
      let newWiki = wiki;
      commit(`setWiki`, wiki);
      commit(`revisions/initHeap`);
      dispatch(`revisions/loadMoreWikiRevs`);
    }
};
<commit_msg>Add documentation<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

export const state = () => ({
    flags: {},
    version: null,
    sessionId: null,
    wiki: "enwiki", // default to English
});

export const mutations = {
    setFlags (state, flagObject) {
        state.flags = flagObject;
    },
    clearFlags (state, ) {
        state.flags = {}
    },
    setFlag (state, kv) {
        state.flags[kv.key] = kv.value;
    },
    setVersion(state, version) {
        state.version = version;
    },
    setSessionId (state, sessionId) {
        state.sessionId = sessionId;
    },
    setWiki(state, wiki) {
        state.wiki = wiki
    }
};

export const actions = {
    async nuxtServerInit({ commit, state }, { req }) {
        const flags = await this.$axios.$get(`/api/flags`);
        commit('setFlags', flags);
        const version = await this.$axios.$get(`/api/version`);
        commit('setVersion', version);
        if (req.session && req.session.id) {
            commit('setSessionId', req.session.id);
            console.log(`nuxtServerInit req.session.id`, req.session.id);
        }
        if (req.user) {
            console.log(`nuxtServerInit store state setProfile req.user`, req.user);
            commit('user/setProfile', req.user);
        } else {
            console.log(`nuxtServerInit store state clearProfile because req.user is not defined`);
            commit('user/clearProfile');
        }
    },
   /** An vuex action to change the current wiki, denoted by `wiki`.
   *
   * When switching a language, we store the `wiki` into the Vuex store.
   * this action also dispatches the command to load the revisions of the new
   * wiki
   * @param commit
   * @param state
   * @param dispatch
   * @param wiki
   * @return {Promise<void>}
   */
    async changeWiki({ commit, state, dispatch}, wiki) {
      let oldWiki = state.wiki;
      let newWiki = wiki;
      commit(`setWiki`, wiki);
      commit(`revisions/initHeap`);
      dispatch(`revisions/loadMoreWikiRevs`);
    }
};
<|endoftext|>