<commit_before>import React from "react";
import Markdoc, { Ast, Node, Tag } from "@markdoc/markdoc";
import { heading } from "./schema/Heading.markdoc";
import { footnoteRef } from "./schema/footnoteRef.markdoc";
import { footnoteItem } from "./schema/footnoteItem.markdoc";
import Tabs from "../components/Tabs";
import Tab from "../components/Tab";
import Highlight, { defaultProps } from "prism-react-renderer";
import Prism from "prism-react-renderer/prism";
(typeof global !== "undefined" ? global : window).Prism = Prism;
require("prismjs/components/prism-hoon");

// img is wrapped in figure so that images can be extra wide in the blog posts
// function img(h, node) {
//   var props = { src: normalize(node.url), alt: node.alt };
//   if (node.title !== null && node.title !== undefined) {
//     props.title = node.title;
//   }
//   return {
//     type: "element",
//     tagName: "figure",
//     properties: {},
//     children: [
//       {
//         type: "element",
//         tagName: "img",
//         properties: props,
//       },
//     ],
//   };
// }

// function a(h, node) {
//   const url = node.url;

//   if (
//     url.includes("https://urbit.org") ||
//     url.startsWith("/") ||
//     url.startsWith("#")
//   ) {
//     return {
//       type: "element",
//       tagName: "a",
//       properties: {
//         href: url,
//       },
//       children: all(h, node),
//     };
//   } else {
//     return {
//       type: "element",
//       tagName: "a",
//       properties: {
//         target: "_blank",
//         rel: "noopener",
//         href: url,
//       },
//       children: all(h, node),
//     };
//   }
// }

// const handlers = defaultHandlers;
// handlers.link = a;
// handlers.image = img;

export function Fence({ children, language }) {
  return (
    <Highlight
      {...defaultProps}
      key={language}
      language={language}
      code={children}
      theme={undefined}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => (

          {tokens.slice(0, -1).map((line, i) => (

              {line.map((token, key) => (

              ))}

          ))}

      )}
    </Highlight>
  );
}

const fence = {
  render: "Fence",
  attributes: {
    language: {
      type: String,
      description:
        "The programming language of the code block. Place it after the backticks.",
    },
  },
};

const tab = {
  render: "Tab",
  attributes: {
    label: {
      type: String,
    },
  },
};

const tabs = {
  render: "Tabs",
  attributes: {},
  children: [],
  transform(node, config) {
    const labels = node
      .transformChildren(config)
      .filter((child) => child && child.name === "Tab")
      .map((tab) => (typeof tab === "object" ? tab.attributes.label : null));

    return new Tag(this.render, { labels }, tabs);
  },
};

export default function Markdown({ post }) {
  const ast = Markdoc.parse(post.content);
  const finalAst = footnoteParse(ast);
  const content = Markdoc.transform(finalAst, {
    nodes: {
      fence,
      heading,
      footnoteItem,
      footnoteRef,
    },
    // tags: {
    //   tabs,
    //   tab,
    // },
  });
  return Markdoc.renderers.react(content, React, {
    components: {
      Fence,
      Tabs,
      Tab,
    },
  });
}

const footnoteParse = (partialAst) => {
  const endNotePattern = /\[\^(\d+)\]:\s/m;
  const inlineFnPattern = /\[\^(\d+)\](?!:)/gm;

  function* getFootnoteItemNodes(nodes) {
    let results = [];
    let itemsProcessed = 0;
    for (const n of nodes) {
      itemsProcessed += 1;
      if (n.type !== "softbreak") results.push(n);
      if (n.type === "softbreak" || itemsProcessed === nodes.length) {
        yield results;
        results = [];
      }
    }
  }

  function findFootnoteContainerNode(ast) {
    const generator = ast.walk();
    let container;
    let match = false;
    for (const node of generator) {
      if (
        node.attributes.content &&
        endNotePattern.test(node.attributes.content)
      ) {
        match = true;
        generator.return();
      }
      if (node.type === "inline") container = node;
    }
    return match ? container : undefined;
  }

  function processFootnotes(ast) {
    // Get a refrence to the node containing endNotes; if not present, early return
    const fnContainerNode = findFootnoteContainerNode(ast);
    if (!fnContainerNode) return;
    // We have footnotes, so create a new list node which will contain the list of endNotes
    const fnList = new Ast.Node("list", {
      ordered: true,
      class: "footnotes",
    });
    // Get the children nodes for each footnote item
    const fnItems = getFootnoteItemNodes(fnContainerNode.children);
    for (const fn of fnItems) {
      const token = endNotePattern.exec(fn[0].attributes.content);
      if (token) {
        // Remove the markdown footnote syntax (e.g. [^1]) from the string
        fn[0].attributes.content = fn[0].attributes.content.replace(
          token[0],
          ""
        );
        // Create a new footnote item and append to the fnList
        const id = token[1];
        const fnItem = new Ast.Node(
          "footnoteItem",
          {
            id: `fn${id}`,
            href: `#fnref${id}`,
          },
          fn
        );
        fnList.push(fnItem);
      }
    }
    ast.children.pop(); // remove the last paragraph in the doc being replaced by the fnList
    ast.push(fnList);
  }

  function processFootnoteRefs(ast) {
    let parent = ast;
    for (const node of ast.walk()) {
      if (node.attributes.content) {
        // Check if there's a footnote ref token
        const token = inlineFnPattern.exec(node.attributes.content);
        if (token) {
          // Break the string where the foonote ref is, assign first part of string to the current node content
          const [prevText, nextText] = node.attributes.content.split(token[0]);
          node.attributes.content = prevText;

          // Create a footnote node and insert it in the tree
          const id = token[1];
          const fn = new Ast.Node("footnoteRef", {
            id: `fnref${id}`,
            href: `#fn${id}`,
            label: `${id}`,
          });
          parent.push(fn);

          // Create a text node for the text which follows after the footnote and insert it in the tree
          const next = new Ast.Node("text", { content: nextText });
          parent.push(next);
        }
      }
      // If the node is of inline type, update parent
      if (node.type == "inline") parent = node;
    }
  }

  processFootnoteRefs(partialAst);
  processFootnotes(partialAst);
  return partialAst;
};
<commit_msg>Markdown: fix tabs<commit_after>import React from "react";
import Markdoc, { Ast, Node, Tag } from "@markdoc/markdoc";
import { heading } from "./schema/Heading.markdoc";
import { footnoteRef } from "./schema/footnoteRef.markdoc";
import { footnoteItem } from "./schema/footnoteItem.markdoc";
import Tabs from "../components/Tabs";
import Tab from "../components/Tab";
import Highlight, { defaultProps } from "prism-react-renderer";
import Prism from "prism-react-renderer/prism";
(typeof global !== "undefined" ? global : window).Prism = Prism;
require("prismjs/components/prism-hoon");

// img is wrapped in figure so that images can be extra wide in the blog posts
// function img(h, node) {
//   var props = { src: normalize(node.url), alt: node.alt };
//   if (node.title !== null && node.title !== undefined) {
//     props.title = node.title;
//   }
//   return {
//     type: "element",
//     tagName: "figure",
//     properties: {},
//     children: [
//       {
//         type: "element",
//         tagName: "img",
//         properties: props,
//       },
//     ],
//   };
// }

// function a(h, node) {
//   const url = node.url;

//   if (
//     url.includes("https://urbit.org") ||
//     url.startsWith("/") ||
//     url.startsWith("#")
//   ) {
//     return {
//       type: "element",
//       tagName: "a",
//       properties: {
//         href: url,
//       },
//       children: all(h, node),
//     };
//   } else {
//     return {
//       type: "element",
//       tagName: "a",
//       properties: {
//         target: "_blank",
//         rel: "noopener",
//         href: url,
//       },
//       children: all(h, node),
//     };
//   }
// }

// const handlers = defaultHandlers;
// handlers.link = a;
// handlers.image = img;

export function Fence({ children, language }) {
  return (
    <Highlight
      {...defaultProps}
      key={language}
      language={language}
      code={children}
      theme={undefined}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => (

          {tokens.slice(0, -1).map((line, i) => (

              {line.map((token, key) => (

              ))}

          ))}

      )}
    </Highlight>
  );
}

const fence = {
  render: "Fence",
  attributes: {
    language: {
      type: String,
      description:
        "The programming language of the code block. Place it after the backticks.",
    },
  },
};

const tab = {
  render: "Tab",
  attributes: {
    label: {
      type: String,
    },
  },
};

const tabs = {
  render: "Tabs",
  attributes: {},
  transform(node, config) {
    const labels = node
      .transformChildren(config)
      .filter((child) => child && child.name === "Tab")
      .map((tab) => (typeof tab === "object" ? tab.attributes.label : null));

    return new Tag(this.render, { labels }, node.transformChildren(config));
  },
};

export default function Markdown({ post }) {
  const ast = Markdoc.parse(post.content);
  const finalAst = footnoteParse(ast);
  const content = Markdoc.transform(finalAst, {
    nodes: {
      fence,
      heading,
      footnoteItem,
      footnoteRef,
    },
    tags: {
      tabs,
      tab,
    },
  });
  return Markdoc.renderers.react(content, React, {
    components: {
      Fence,
      Tabs,
      Tab,
    },
  });
}

const footnoteParse = (partialAst) => {
  const endNotePattern = /\[\^(\d+)\]:\s/m;
  const inlineFnPattern = /\[\^(\d+)\](?!:)/gm;

  function* getFootnoteItemNodes(nodes) {
    let results = [];
    let itemsProcessed = 0;
    for (const n of nodes) {
      itemsProcessed += 1;
      if (n.type !== "softbreak") results.push(n);
      if (n.type === "softbreak" || itemsProcessed === nodes.length) {
        yield results;
        results = [];
      }
    }
  }

  function findFootnoteContainerNode(ast) {
    const generator = ast.walk();
    let container;
    let match = false;
    for (const node of generator) {
      if (
        node.attributes.content &&
        endNotePattern.test(node.attributes.content)
      ) {
        match = true;
        generator.return();
      }
      if (node.type === "inline") container = node;
    }
    return match ? container : undefined;
  }

  function processFootnotes(ast) {
    // Get a refrence to the node containing endNotes; if not present, early return
    const fnContainerNode = findFootnoteContainerNode(ast);
    if (!fnContainerNode) return;
    // We have footnotes, so create a new list node which will contain the list of endNotes
    const fnList = new Ast.Node("list", {
      ordered: true,
      class: "footnotes",
    });
    // Get the children nodes for each footnote item
    const fnItems = getFootnoteItemNodes(fnContainerNode.children);
    for (const fn of fnItems) {
      const token = endNotePattern.exec(fn[0].attributes.content);
      if (token) {
        // Remove the markdown footnote syntax (e.g. [^1]) from the string
        fn[0].attributes.content = fn[0].attributes.content.replace(
          token[0],
          ""
        );
        // Create a new footnote item and append to the fnList
        const id = token[1];
        const fnItem = new Ast.Node(
          "footnoteItem",
          {
            id: `fn${id}`,
            href: `#fnref${id}`,
          },
          fn
        );
        fnList.push(fnItem);
      }
    }
    ast.children.pop(); // remove the last paragraph in the doc being replaced by the fnList
    ast.push(fnList);
  }

  function processFootnoteRefs(ast) {
    let parent = ast;
    for (const node of ast.walk()) {
      if (node.attributes.content) {
        // Check if there's a footnote ref token
        const token = inlineFnPattern.exec(node.attributes.content);
        if (token) {
          // Break the string where the foonote ref is, assign first part of string to the current node content
          const [prevText, nextText] = node.attributes.content.split(token[0]);
          node.attributes.content = prevText;

          // Create a footnote node and insert it in the tree
          const id = token[1];
          const fn = new Ast.Node("footnoteRef", {
            id: `fnref${id}`,
            href: `#fn${id}`,
            label: `${id}`,
          });
          parent.push(fn);

          // Create a text node for the text which follows after the footnote and insert it in the tree
          const next = new Ast.Node("text", { content: nextText });
          parent.push(next);
        }
      }
      // If the node is of inline type, update parent
      if (node.type == "inline") parent = node;
    }
  }

  processFootnoteRefs(partialAst);
  processFootnotes(partialAst);
  return partialAst;
};
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import Toolbar from './Toolbar';

class PriceBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editing: false
    };
  }
  save() {
    const arr = this.props.prices.slice();
    arr[this.props.index] = {
        className: [this.refs.class1.value, this.refs.class2.value],
        price: this.refs.price.value,
        completion: this.refs.completion.value,
        prodId: this.refs.prodId.value,
        neededToComplete: Array.from(this.refs.needed.children).map((item, i) => item.querySelector('input').value),
        specs: Array.from(this.refs.specs.children).map((row, i) => ({name: row.children[0].value,value: row.children[2].value})),
        url: this.refs.url.value
      };
    this.props.updateState({
      prices: arr
    });
    this.toggleEditing();
  }
  toggleEditing() {
    this.setState({
      editing: !this.state.editing
    });
    return false;
  }
  deleteItem() {
    const arr = this.props.prices.slice();
    if(arr.length === 1) return;
    arr.splice([this.props.index], 1);
    this.props.updateState({
      prices: arr
    });
  }
  addItem() {
    const arr = this.props.prices.slice();
    if(arr.length === 3) return;
    arr.push(arr[0]);
    this.props.updateState({
      prices: arr
    });
  }
  deleteNeededItem(idx) {
    const arr = this.props.prices.slice();
    if(arr[this.props.index].neededToComplete.length === 1) return;
    arr[this.props.index].neededToComplete.splice(idx, 1);
    this.props.updateState({
      prices: arr
    });
  }
  addNeededItem() {
    const arr = this.props.prices.slice();
    arr[this.props.index].neededToComplete.push(arr[this.props.index].neededToComplete[0]);
    this.props.updateState({
      prices: arr
    });
  }
  deleteSpecItem() {
    let arr = this.props.prices.slice();
    if(arr[this.props.index].specs.length === 1) return;
    arr[this.props.index].specs.splice(null, 1);
    this.props.updateState({
      prices: arr
    });
  }
  addSpecItem() {
    const arr = this.props.prices.slice();
    arr[this.props.index].specs.push(arr[this.props.index].specs[0]);
    this.props.updateState({
      prices: arr
    });
  }
  renderItemOrEdit() {
    const box = this.props.prices[this.props.index];
    if (this.state.editing) {
      return(

            Plan:
            <select ref="class1" defaultValue={box.className[0]}>
              <option value="">Regular</option>
              <option value="best-plan">Best</option>
            </select>

            Background-color:
            <select ref="class2" defaultValue={box.className[1]}>
              <option value="text-price">Red</option>
              <option value="text-price-grey">Grey</option>
            </select>

            Price:
            <input ref="price" defaultValue={box.price}/>

            Completion:
            <input ref="completion" defaultValue={box.completion}/>

            ProdID:
            <input ref="prodId" defaultValue={box.prodId}/>

          Needed To Complete:

            {box.neededToComplete.map((item, i) => (

                <input defaultValue={item} style={{width: '100%'}}/>
                {(i === box.neededToComplete.length - 1) && <Toolbar miniclass=" mini" onClick={() => this.toggleEditing()} onDelete={() => this.deleteNeededItem()} onAdd={() => this.addNeededItem()}/>}

            ))}

          Specs:

            {box.specs.map((item, i) => (

                <input defaultValue={item.name}/> <input defaultValue={item.value}/>
                {(i === box.specs.length - 1) && <Toolbar miniclass=" mini" onClick={() => this.toggleEditing()} onDelete={() => this.deleteSpecItem()} onAdd={() => this.addSpecItem()}/>}

            ))}

          Purchase URL:

            <input ref="url" defaultValue={box.url}/>

          <button className="saver" onClick={() => this.save()}>Save</button>

)
    } else {
      return (
        <div className={`flex-item-auto ${box.className[0]} editable-item`}>

${box.price}

            {box.completion}

              {box.prodId}

              {box.neededToComplete.map((item, i) => (

{item}

              ))}

Specs:

                {box.specs.map((spec, i) => (

{spec.name}: {spec.value}

                ))}

                Find a Retailer

                Buy Now

          {this.props.updateState && <Toolbar onClick={() => this.toggleEditing()} onDelete={() => this.deleteItem()} onAdd={() => this.addItem()}/>}

      )
    }
  }
  render() {
    return this.renderItemOrEdit();
  }
}

PriceBox.propTypes = {
  updateState: React.PropTypes.func,
  prices: React.PropTypes.array.isRequired,
  index: React.PropTypes.number.isRequired
};

export default PriceBox;
<commit_msg>no longer a third child in specs<commit_after>import React, {Component} from 'react';
import Toolbar from './Toolbar';

class PriceBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editing: false
    };
  }
  save() {
    const arr = this.props.prices.slice();
    arr[this.props.index] = {
        className: [this.refs.class1.value, this.refs.class2.value],
        price: this.refs.price.value,
        completion: this.refs.completion.value,
        prodId: this.refs.prodId.value,
        neededToComplete: Array.from(this.refs.needed.children).map((item, i) => item.querySelector('input').value),
        specs: Array.from(this.refs.specs.children).map((row, i) => ({name: row.children[0].value,value: row.children[1].value})),
        url: this.refs.url.value
      };
    this.props.updateState({
      prices: arr
    });
    this.toggleEditing();
  }
  toggleEditing() {
    this.setState({
      editing: !this.state.editing
    });
    return false;
  }
  deleteItem() {
    const arr = this.props.prices.slice();
    if(arr.length === 1) return;
    arr.splice([this.props.index], 1);
    this.props.updateState({
      prices: arr
    });
  }
  addItem() {
    const arr = this.props.prices.slice();
    if(arr.length === 3) return;
    arr.push(arr[0]);
    this.props.updateState({
      prices: arr
    });
  }
  deleteNeededItem(idx) {
    const arr = this.props.prices.slice();
    if(arr[this.props.index].neededToComplete.length === 1) return;
    arr[this.props.index].neededToComplete.splice(idx, 1);
    this.props.updateState({
      prices: arr
    });
  }
  addNeededItem() {
    const arr = this.props.prices.slice();
    arr[this.props.index].neededToComplete.push(arr[this.props.index].neededToComplete[0]);
    this.props.updateState({
      prices: arr
    });
  }
  deleteSpecItem() {
    let arr = this.props.prices.slice();
    if(arr[this.props.index].specs.length === 1) return;
    arr[this.props.index].specs.splice(null, 1);
    this.props.updateState({
      prices: arr
    });
  }
  addSpecItem() {
    const arr = this.props.prices.slice();
    arr[this.props.index].specs.push(arr[this.props.index].specs[0]);
    this.props.updateState({
      prices: arr
    });
  }
  renderItemOrEdit() {
    const box = this.props.prices[this.props.index];
    if (this.state.editing) {
      return(

            Plan:
            <select ref="class1" defaultValue={box.className[0]}>
              <option value="">Regular</option>
              <option value="best-plan">Best</option>
            </select>

            Background-color:
            <select ref="class2" defaultValue={box.className[1]}>
              <option value="text-price">Red</option>
              <option value="text-price-grey">Grey</option>
            </select>

            Price:
            <input ref="price" defaultValue={box.price}/>

            Completion:
            <input ref="completion" defaultValue={box.completion}/>

            ProdID:
            <input ref="prodId" defaultValue={box.prodId}/>

          Needed To Complete:

            {box.neededToComplete.map((item, i) => (

                <input defaultValue={item} style={{width: '100%'}}/>
                {(i === box.neededToComplete.length - 1) && <Toolbar miniclass=" mini" onClick={() => this.toggleEditing()} onDelete={() => this.deleteNeededItem()} onAdd={() => this.addNeededItem()}/>}

            ))}

          Specs:

            {box.specs.map((item, i) => (

                <input defaultValue={item.name}/> <input defaultValue={item.value}/>
                {(i === box.specs.length - 1) && <Toolbar miniclass=" mini" onClick={() => this.toggleEditing()} onDelete={() => this.deleteSpecItem()} onAdd={() => this.addSpecItem()}/>}

            ))}

          Purchase URL:

            <input ref="url" defaultValue={box.url}/>

          <button className="saver" onClick={() => this.save()}>Save</button>

)
    } else {
      return (
        <div className={`flex-item-auto ${box.className[0]} editable-item`}>

${box.price}

            {box.completion}

              {box.prodId}

              {box.neededToComplete.map((item, i) => (

{item}

              ))}

Specs:

                {box.specs.map((spec, i) => (

{spec.name}: {spec.value}

                ))}

                Find a Retailer

                Buy Now

          {this.props.updateState && <Toolbar onClick={() => this.toggleEditing()} onDelete={() => this.deleteItem()} onAdd={() => this.addItem()}/>}

      )
    }
  }
  render() {
    return this.renderItemOrEdit();
  }
}

PriceBox.propTypes = {
  updateState: React.PropTypes.func,
  prices: React.PropTypes.array.isRequired,
  index: React.PropTypes.number.isRequired
};

export default PriceBox;
<|endoftext|>


<commit_before>var fs = require('fs')
var os = require('os')
var randomPath = require('random-path')

var retry = require('./retry')
var WriteStream = require('./write-stream')

var tmpdir = os.tmpDir()

function open (template, flags, mode, cb) {
  switch (flags) {
    case 'w': flags = 'wx'; break
    case 'w+': flags = 'wx+'; break
    default: throw new Error('Unknown file open flag: ' + flags)
  }

  if (typeof mode === 'function') {
    cb = mode
    mode = undefined
  }

  var path

  retry.async(function (cb) {
    path = randomPath(tmpdir, template)
    fs.open(path, flags, mode, cb)
  }, function (err, fd) {
    cb(err, err ? undefined : { fd: fd, path: path })
  })
}

function openSync (template, flags, mode) {
  switch (flags) {
    case 'w': flags = 'wx'; break
    case 'w+': flags = 'wx+'; break
    default: throw new Error('Unknown file open flag: ' + flags)
  }

  var path

  var fd = retry.sync(function () {
    path = randomPath(tmpdir, template)
    return fs.openSync(path, flags, mode)
  })

  return { fd: fd, path: path }
}

function mkdir (template, mode, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = undefined
  }

  var path

  retry.async(function (cb) {
    path = randomPath(tmpdir, template)
    fs.mkdir(path, mode, cb)
  }, function (err) {
    cb(err, err ? undefined : path)
  })
}

function mkdirSync (template, mode) {
  var path

  retry.sync(function () {
    path = randomPath(tmpdir, template)
    fs.mkdirSync(path, mode)
  })

  return path
}

function writeFile (template, data, options, cb) {
  cb = arguments[arguments.length - 1]

  if (typeof options === 'function' || !options) {
    options = { flag: 'wx' }
  } else if (typeof options === 'string') {
    options = { encoding: options, flag: 'wx' }
  } else if (typeof options === 'object') {
    options.flag = 'wx'
  } else {
    throw new TypeError('Bad arguments')
  }

  var path

  retry.async(function (cb) {
    path = randomPath(tmpdir, template)
    fs.writeFile(path, data, options, cb)
  }, function (err) {
    cb(err, err ? undefined : path)
  })
}

function writeFileSync (template, data, options, cb) {
  if (!options) {
    options = { flag: 'wx' }
  } else if (typeof options === 'string') {
    options = { encoding: options, flag: 'wx' }
  } else if (typeof options === 'object') {
    options.flag = 'wx'
  } else {
    throw new TypeError('Bad arguments')
  }

  var path

  retry.sync(function () {
    path = randomPath(tmpdir, template)
    fs.writeFileSync(path, data, options)
  })

  return path
}

function createWriteStream (template, options) {
  return new WriteStream(template, options)
}

exports.open = open
exports.openSync = openSync
exports.mkdir = mkdir
exports.mkdirSync = mkdirSync
exports.writeFile = writeFile
exports.writeFileSync = writeFileSync
exports.createWriteStream = createWriteStream
<commit_msg>lib: use os.tmpdir()<commit_after>var fs = require('fs')
var os = require('os')
var randomPath = require('random-path')

var retry = require('./retry')
var WriteStream = require('./write-stream')

var tmpdir = os.tmpdir()

function open (template, flags, mode, cb) {
  switch (flags) {
    case 'w': flags = 'wx'; break
    case 'w+': flags = 'wx+'; break
    default: throw new Error('Unknown file open flag: ' + flags)
  }

  if (typeof mode === 'function') {
    cb = mode
    mode = undefined
  }

  var path

  retry.async(function (cb) {
    path = randomPath(tmpdir, template)
    fs.open(path, flags, mode, cb)
  }, function (err, fd) {
    cb(err, err ? undefined : { fd: fd, path: path })
  })
}

function openSync (template, flags, mode) {
  switch (flags) {
    case 'w': flags = 'wx'; break
    case 'w+': flags = 'wx+'; break
    default: throw new Error('Unknown file open flag: ' + flags)
  }

  var path

  var fd = retry.sync(function () {
    path = randomPath(tmpdir, template)
    return fs.openSync(path, flags, mode)
  })

  return { fd: fd, path: path }
}

function mkdir (template, mode, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = undefined
  }

  var path

  retry.async(function (cb) {
    path = randomPath(tmpdir, template)
    fs.mkdir(path, mode, cb)
  }, function (err) {
    cb(err, err ? undefined : path)
  })
}

function mkdirSync (template, mode) {
  var path

  retry.sync(function () {
    path = randomPath(tmpdir, template)
    fs.mkdirSync(path, mode)
  })

  return path
}

function writeFile (template, data, options, cb) {
  cb = arguments[arguments.length - 1]

  if (typeof options === 'function' || !options) {
    options = { flag: 'wx' }
  } else if (typeof options === 'string') {
    options = { encoding: options, flag: 'wx' }
  } else if (typeof options === 'object') {
    options.flag = 'wx'
  } else {
    throw new TypeError('Bad arguments')
  }

  var path

  retry.async(function (cb) {
    path = randomPath(tmpdir, template)
    fs.writeFile(path, data, options, cb)
  }, function (err) {
    cb(err, err ? undefined : path)
  })
}

function writeFileSync (template, data, options, cb) {
  if (!options) {
    options = { flag: 'wx' }
  } else if (typeof options === 'string') {
    options = { encoding: options, flag: 'wx' }
  } else if (typeof options === 'object') {
    options.flag = 'wx'
  } else {
    throw new TypeError('Bad arguments')
  }

  var path

  retry.sync(function () {
    path = randomPath(tmpdir, template)
    fs.writeFileSync(path, data, options)
  })

  return path
}

function createWriteStream (template, options) {
  return new WriteStream(template, options)
}

exports.open = open
exports.openSync = openSync
exports.mkdir = mkdir
exports.mkdirSync = mkdirSync
exports.writeFile = writeFile
exports.writeFileSync = writeFileSync
exports.createWriteStream = createWriteStream
<|endoftext|>


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

'use strict';

const path = require('path');
const assert = require('assert');
const utils = require('../utils.js');

assert(!module.parent);
assert(__dirname === process.cwd());

const host = 'node' + process.version[1];
const target = process.argv[2] || host;
const input = './test-x-index.js';
const output = './run-time/test-output.exe';

// see readFromSnapshot "NODE_VERSION_MAJOR"

function bitty (version) {
  return (2 * (/^(node|v)?4/.test(version))) |
         (2 * (/^(node|v)?5/.test(version))) |
         (4 * (/^(node|v)?6/.test(version))) |
         (4 * (/^(node|v)?7/.test(version))) |
         (4 * (/^(node|v)?8/.test(version)));
}

const version1 = process.version;
const version2 = target;
if (bitty(version1) !== bitty(version2)) return;

let left, right;
utils.mkdirp.sync(path.dirname(output));

left = utils.spawn.sync(
  'node', [ path.basename(input) ],
  { cwd: path.dirname(input) }
);

utils.pkg.sync([
  '--target', target,
  '--output', output, input
]);

right = utils.spawn.sync(
  './' + path.basename(output), [],
  { cwd: path.dirname(output) }
);

left = left.split('\n');
right = right.split('\n');
// right may have less lines, premature exit,
// less trusted, so using left.length here
for (let i = 0; i < left.length; i += 1) {
  assert.equal(left[i], right[i]);
}

utils.vacuum.sync(path.dirname(output));
<commit_msg>fix fs-2 test for node10<commit_after>#!/usr/bin/env node

'use strict';

const path = require('path');
const assert = require('assert');
const utils = require('../utils.js');

assert(!module.parent);
assert(__dirname === process.cwd());

const host = 'node' + process.version[1];
const target = process.argv[2] || host;
const input = './test-x-index.js';
const output = './run-time/test-output.exe';

// see readFromSnapshot "NODE_VERSION_MAJOR"

function bitty (version) {
  return (2 *  (/^(node|v)?4/.test(version))) |
         (2 *  (/^(node|v)?5/.test(version))) |
         (4 *  (/^(node|v)?6/.test(version))) |
         (4 *  (/^(node|v)?7/.test(version))) |
         (4 *  (/^(node|v)?8/.test(version))) |
         (4 *  (/^(node|v)?9/.test(version))) |
         (8 * (/^(node|v)?10/.test(version)));
}

const version1 = process.version;
const version2 = target;
if (bitty(version1) !== bitty(version2)) return;

let left, right;
utils.mkdirp.sync(path.dirname(output));

left = utils.spawn.sync(
  'node', [ path.basename(input) ],
  { cwd: path.dirname(input) }
);

utils.pkg.sync([
  '--target', target,
  '--output', output, input
]);

right = utils.spawn.sync(
  './' + path.basename(output), [],
  { cwd: path.dirname(output) }
);

left = left.split('\n');
right = right.split('\n');
// right may have less lines, premature exit,
// less trusted, so using left.length here
for (let i = 0; i < left.length; i += 1) {
  assert.equal(left[i], right[i]);
}

utils.vacuum.sync(path.dirname(output));
<|endoftext|>


<commit_before>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var classSet = chessground.util.classSet;
var renderConfig = require('./explorerConfig').view;

function resultBar(move) {
  var sum = move.white + move.draws + move.black;
  var section = function(key) {
    var percent = move[key] * 100 / sum;
    return percent === 0 ? null : m('span', {
      class: key,
      style: {
        width: (Math.round(move[key] * 1000 / sum) / 10) + '%'
      },
    }, percent > 12 ? Math.round(percent) + '%' : null);
  }
  return m('div.bar', ['white', 'draws', 'black'].map(section));
}

var lastShow = null;

function $trUci($tr) {
  return $tr[0] ? $tr[0].getAttribute('data-uci') : null;
}

function showMoveTable(ctrl, moves) {
  if (!moves.length) return null;
  return m('table.moves', [
    m('thead', [
      m('tr', [
        m('th', 'Move'),
        m('th', 'Games'),
        m('th', 'White / Draw / Black')
      ])
    ]),
    m('tbody', {
      config: function(el, isUpdate, ctx) {
        if (!isUpdate || ctx.lastFen === ctrl.vm.step.fen) return;
        ctx.lastFen = ctrl.vm.step.fen;
        setTimeout(function() {
          ctrl.explorer.setHoveringUci($trUci($(el).find('tr:hover')));
        }, 100);
      },
      onclick: function(e) {
        var $tr = $(e.target).parents('tr');
        if ($tr.length) ctrl.explorerMove($trUci($tr));
      },
      onmouseover: function(e) {
        var $tr = $(e.target).parents('tr');
        ctrl.explorer.setHoveringUci($trUci($tr));
      },
      onmouseout: function(e) {
        ctrl.explorer.setHoveringUci(null);
      }
    }, moves.map(function(move) {
      return m('tr', {
        key: move.uci,
        'data-uci': move.uci
      }, [
        m('td', move.san),
        m('td', lichess.numberFormat(move.white + move.draws + move.black)),
        m('td', resultBar(move))
      ]);
    }))
  ]);
}

function showResult(winner) {
  if (winner === 'white') return '1-0';
  if (winner === 'black') return '0-1';
  return '½-½';
}

function showGameTable(ctrl, type, games) {
  if (!games.length) return null;
  return m('table.games', [
    m('thead', [
      m('tr', [
        m('th[colspan=4]', type + ' games')
      ])
    ]),
    m('tbody', {
      onclick: function(e) {
        var $tr = $(e.target).parents('tr');
        if (!$tr.length) return;
        var baseUrl = ctrl.explorer.config.data.db.selected() === 'lichess' ? '/' : '/import/master/';
        window.open(baseUrl + $tr.data('id'), '_blank');
      }
    }, games.map(function(game) {
      return m('tr', {
        key: game.id,
        'data-id': game.id
      }, [
        m('td', [game.white, game.black].map(function(p) {
          return m('span', p.rating);
        })),
        m('td', [game.white, game.black].map(function(p) {
          return m('span', p.name);
        })),
        m('td', showResult(game.winner)),
        m('td', game.year)
      ]);
    }))
  ]);
}

function show(ctrl) {
  var data = ctrl.explorer.current();
  if (data) {
    var db = ctrl.explorer.config.data.db.selected();
    var moveTable = showMoveTable(ctrl, data.moves);
    var recentTable = showGameTable(ctrl, 'recent', data['recentGames'] || []);
    var topTable = showGameTable(ctrl, 'top', data['topGames'] || []);
    if (moveTable || recentTable || topTable) lastShow = m('div.data', [moveTable, recentTable, topTable]);
    else lastShow = m('div.data.empty', [
      m('div.title', 'No game found'),
      m('div.message', [
        m('i[data-icon=]'),
        m('h3', "That's all we got!"),
        m('p',
          ctrl.explorer.config.fullHouse() ?
          "Already searching through all available games." :
          "Maybe include more games from the preferences menu?")
      ])
    ]);
  }
  return lastShow;
}

function showConfig(ctrl) {
  return m('div.config', [
    m('div.title', ctrl.data.game.variant.name + ' opening explorer'),
    renderConfig(ctrl.explorer.config, ctrl.data.game.variant)
  ]);
}

var overlay = m('div.overlay', m.trust(lichess.spinnerHtml));

function failing() {
  return m('div.failing.message', [
    m('i[data-icon=,]'),
    m('h3', 'Oops, sorry!'),
    m('p', 'The explorer is temporarily'),
    m('p', 'out of service. Try again soon!')
  ]);
}

module.exports = {
  renderExplorer: function(ctrl) {
    if (!ctrl.explorer.enabled()) return;
    var config = ctrl.explorer.config;
    var configOpened = config.data.open();
    var loading = !configOpened && (ctrl.explorer.loading() || (!ctrl.explorer.current() && !ctrl.explorer.failing()));
    return m('div', {
      class: classSet({
        explorer_box: true,
        loading: loading,
        config: configOpened
      })
    }, [
      overlay,
      configOpened ? showConfig(ctrl) : (ctrl.explorer.failing() ? failing() : show(ctrl)),
      m('span.toconf', {
        'data-icon': configOpened ? 'L' : '%',
        onclick: config.toggleOpen
      })
    ]);
  }
};
<commit_msg>show explorer move average rating in a tooltip. Not sure about that.<commit_after>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var classSet = chessground.util.classSet;
var renderConfig = require('./explorerConfig').view;

function resultBar(move) {
  var sum = move.white + move.draws + move.black;
  var section = function(key) {
    var percent = move[key] * 100 / sum;
    return percent === 0 ? null : m('span', {
      class: key,
      style: {
        width: (Math.round(move[key] * 1000 / sum) / 10) + '%'
      },
    }, percent > 12 ? Math.round(percent) + '%' : null);
  }
  return m('div.bar', ['white', 'draws', 'black'].map(section));
}

var lastShow = null;

function $trUci($tr) {
  return $tr[0] ? $tr[0].getAttribute('data-uci') : null;
}

function showMoveTable(ctrl, moves) {
  if (!moves.length) return null;
  return m('table.moves', [
    m('thead', [
      m('tr', [
        m('th', 'Move'),
        m('th', 'Games'),
        m('th', 'White / Draw / Black')
      ])
    ]),
    m('tbody', {
      config: function(el, isUpdate, ctx) {
        if (!isUpdate || ctx.lastFen === ctrl.vm.step.fen) return;
        ctx.lastFen = ctrl.vm.step.fen;
        setTimeout(function() {
          ctrl.explorer.setHoveringUci($trUci($(el).find('tr:hover')));
        }, 100);
      },
      onclick: function(e) {
        var $tr = $(e.target).parents('tr');
        if ($tr.length) ctrl.explorerMove($trUci($tr));
      },
      onmouseover: function(e) {
        var $tr = $(e.target).parents('tr');
        ctrl.explorer.setHoveringUci($trUci($tr));
      },
      onmouseout: function(e) {
        ctrl.explorer.setHoveringUci(null);
      }
    }, moves.map(function(move) {
      return m('tr', {
        key: move.uci,
        'data-uci': move.uci,
        title: 'Average rating: ' + move.averageRating
      }, [
        m('td', move.san),
        m('td', lichess.numberFormat(move.white + move.draws + move.black)),
        m('td', resultBar(move))
      ]);
    }))
  ]);
}

function showResult(winner) {
  if (winner === 'white') return '1-0';
  if (winner === 'black') return '0-1';
  return '½-½';
}

function showGameTable(ctrl, type, games) {
  if (!games.length) return null;
  return m('table.games', [
    m('thead', [
      m('tr', [
        m('th[colspan=4]', type + ' games')
      ])
    ]),
    m('tbody', {
      onclick: function(e) {
        var $tr = $(e.target).parents('tr');
        if (!$tr.length) return;
        var baseUrl = ctrl.explorer.config.data.db.selected() === 'lichess' ? '/' : '/import/master/';
        window.open(baseUrl + $tr.data('id'), '_blank');
      }
    }, games.map(function(game) {
      return m('tr', {
        key: game.id,
        'data-id': game.id
      }, [
        m('td', [game.white, game.black].map(function(p) {
          return m('span', p.rating);
        })),
        m('td', [game.white, game.black].map(function(p) {
          return m('span', p.name);
        })),
        m('td', showResult(game.winner)),
        m('td', game.year)
      ]);
    }))
  ]);
}

function show(ctrl) {
  var data = ctrl.explorer.current();
  if (data) {
    var db = ctrl.explorer.config.data.db.selected();
    var moveTable = showMoveTable(ctrl, data.moves);
    var recentTable = showGameTable(ctrl, 'recent', data['recentGames'] || []);
    var topTable = showGameTable(ctrl, 'top', data['topGames'] || []);
    if (moveTable || recentTable || topTable) lastShow = m('div.data', [moveTable, recentTable, topTable]);
    else lastShow = m('div.data.empty', [
      m('div.title', 'No game found'),
      m('div.message', [
        m('i[data-icon=]'),
        m('h3', "That's all we got!"),
        m('p',
          ctrl.explorer.config.fullHouse() ?
          "Already searching through all available games." :
          "Maybe include more games from the preferences menu?")
      ])
    ]);
  }
  return lastShow;
}

function showConfig(ctrl) {
  return m('div.config', [
    m('div.title', ctrl.data.game.variant.name + ' opening explorer'),
    renderConfig(ctrl.explorer.config, ctrl.data.game.variant)
  ]);
}

var overlay = m('div.overlay', m.trust(lichess.spinnerHtml));

function failing() {
  return m('div.failing.message', [
    m('i[data-icon=,]'),
    m('h3', 'Oops, sorry!'),
    m('p', 'The explorer is temporarily'),
    m('p', 'out of service. Try again soon!')
  ]);
}

module.exports = {
  renderExplorer: function(ctrl) {
    if (!ctrl.explorer.enabled()) return;
    var config = ctrl.explorer.config;
    var configOpened = config.data.open();
    var loading = !configOpened && (ctrl.explorer.loading() || (!ctrl.explorer.current() && !ctrl.explorer.failing()));
    return m('div', {
      class: classSet({
        explorer_box: true,
        loading: loading,
        config: configOpened
      })
    }, [
      overlay,
      configOpened ? showConfig(ctrl) : (ctrl.explorer.failing() ? failing() : show(ctrl)),
      m('span.toconf', {
        'data-icon': configOpened ? 'L' : '%',
        onclick: config.toggleOpen
      })
    ]);
  }
};
<|endoftext|>


<commit_before>var tv4 = require('tv4'),
    path = require('path')
    refaker = require('./index');

var schema = require('../schemas/parent/schema.json'),
    data = require('../schemas/example.json');

refaker({
  schemas: [schema],
  fakeroot: 'http://example.com',
  directory: path.resolve(__dirname + '/../schemas')
}, function(err, refs) {
  if (refs) {
    for (var id in refs) {
      tv4.addSchema(id, refs[id]);
    }
  }

  var result = tv4.validateResult(data, schema);

  if (err || result.error || result.missing.length) {
    console.log(err);
    console.log(result.missing);
    console.log(result.error.message);

    process.exit(1);
  }

  console.log('OK');
});
<commit_msg>Fixed debug<commit_after>var tv4 = require('tv4'),
    path = require('path')
    refaker = require('./index');

var schema = require('../schemas/parent/schema.json'),
    data = require('../schemas/example.json');

refaker({
  schemas: [schema],
  fakeroot: 'http://example.com',
  directory: path.resolve(__dirname + '/../schemas')
}, function(err, refs) {
  if (refs) {
    for (var id in refs) {
      tv4.addSchema(id, refs[id]);
    }
  }

  var result = tv4.validateResult(data, schema);

  if (err || result.error || result.missing.length) {
    console.log(err);
    console.log(result.missing);
    console.log(result.error ? result.error.message : result.error);

    process.exit(1);
  }

  console.log('OK');
});
<|endoftext|>


<commit_before>import Vue from 'vue'

import QBtn from '../btn/QBtn.js'

import DarkMixin from '../../mixins/dark.js'
import { PanelParentMixin } from '../../mixins/panel.js'
import FullscreenMixin from '../../mixins/fullscreen.js'

import { isNumber } from '../../utils/is.js'
import { mergeSlot } from '../../utils/slot.js'
import cache from '../../utils/cache.js'

export default Vue.extend({
  name: 'QCarousel',

  mixins: [ DarkMixin, PanelParentMixin, FullscreenMixin ],

  props: {
    height: String,
    padding: Boolean,

    controlType: {
      type: String,
      validator: v => [ 'regular', 'flat', 'outline', 'push', 'unelevated' ].includes(v),
      default: 'flat'
    },
    controlColor: String,
    controlTextColor: String,

    autoplay: [Number, Boolean],

    arrows: Boolean,
    prevIcon: String,
    nextIcon: String,

    navigation: Boolean,
    navigationPosition: {
      type: String,
      validator: v => ['top', 'right', 'bottom', 'left'].includes(v)
    },
    navigationIcon: String,

    thumbnails: Boolean
  },

  computed: {
    style () {
      if (this.inFullscreen !== true && this.height !== void 0) {
        return {
          height: this.height
        }
      }
    },

    direction () {
      return this.vertical === true ? 'vertical' : 'horizontal'
    },

    classes () {
      return `q-carousel q-panel-parent q-carousel--with${this.padding === true ? '' : 'out'}-padding` +
        (this.inFullscreen === true ? ' fullscreen' : '') +
        (this.isDark === true ? ' q-carousel--dark q-dark' : '') +
        (this.arrows === true ? ` q-carousel--arrows-${this.direction}` : '') +
        (this.navigation === true ? ` q-carousel--navigation-${this.navigationPositionComputed}` : '')
    },

    arrowIcons () {
      const ico = [
        this.prevIcon || this.$q.iconSet.carousel[this.vertical === true ? 'up' : 'left'],
        this.nextIcon || this.$q.iconSet.carousel[this.vertical === true ? 'down' : 'right']
      ]

      return this.vertical === false && this.$q.lang.rtl === true
        ? ico.reverse()
        : ico
    },

    navIcon () {
      return this.navigationIcon || this.$q.iconSet.carousel.navigationIcon
    },

    navigationPositionComputed () {
      return this.navigationPosition || (this.vertical === true ? 'right' : 'bottom')
    },

    controlProps () {
      return {
        color: this.controlColor,
        textColor: this.controlTextColor,
        round: true,
        [ this.controlType ]: true,
        dense: true
      }
    },

    transitionPrevComputed () {
      return this.transitionPrev || `fade`
    },

    transitionNextComputed () {
      return this.transitionNext || `fade`
    }
  },

  watch: {
    value () {
      if (this.autoplay) {
        clearInterval(this.timer)
        this.__startTimer()
      }
    },

    autoplay (val) {
      if (val) {
        this.__startTimer()
      }
      else {
        clearInterval(this.timer)
      }
    }
  },

  methods: {
    __startTimer () {
      this.timer = setTimeout(
        this.next,
        isNumber(this.autoplay) ? this.autoplay : 5000
      )
    },

    __getNavigationContainer (h, type, mapping) {
      return h('div', {
        class: 'q-carousel__control q-carousel__navigation no-wrap absolute flex' +
          ` q-carousel__navigation--${type} q-carousel__navigation--${this.navigationPositionComputed}` +
          (this.controlColor !== void 0 ? ` text-${this.controlColor}` : '')
      }, [
        h('div', {
          staticClass: 'q-carousel__navigation-inner flex no-wrap justify-center'
        }, this.__getAvailablePanels().map(mapping))
      ])
    },

    __getContent (h) {
      const node = []

      if (this.navigation === true) {
        node.push(this.__getNavigationContainer(h, 'buttons', panel => {
          const name = panel.componentOptions.propsData.name

          return h(QBtn, {
            key: name,
            class: `q-carousel__navigation-icon q-carousel__navigation-icon--${name === this.value ? '' : 'in'}active`,
            props: {
              icon: this.navIcon,
              size: 'sm',
              ...this.controlProps
            },
            on: cache(this, 'nav#' + name, { click: () => { this.goTo(name) } })
          })
        }))
      }
      else if (this.thumbnails === true) {
        const color = this.controlColor !== void 0
          ? ` text-${this.controlColor}`
          : ''

        node.push(this.__getNavigationContainer(h, 'thumbnails', panel => {
          const slide = panel.componentOptions.propsData

          return h('img', {
            class: `q-carousel__thumbnail q-carousel__thumbnail--${slide.name === this.value ? '' : 'in'}active` + color,
            attrs: {
              src: slide.imgSrc
            },
            key: 'tmb#' + slide.name,
            on: cache(this, 'tmb#' + slide.name, { click: () => { this.goTo(slide.name) } })
          })
        }))
      }

      if (this.arrows === true) {
        node.push(
          h('div', {
            staticClass: `q-carousel__control q-carousel__arrow q-carousel__prev-arrow q-carousel__prev-arrow--${this.direction} absolute flex flex-center`
          }, [
            h(QBtn, {
              props: { icon: this.arrowIcons[0], ...this.controlProps },
              on: cache(this, 'prev', { click: this.previous })
            })
          ]),
          h('div', {
            staticClass: `q-carousel__control q-carousel__arrow q-carousel__next-arrow q-carousel__next-arrow--${this.direction} absolute flex flex-center`
          }, [
            h(QBtn, {
              props: { icon: this.arrowIcons[1], ...this.controlProps },
              on: cache(this, 'next', { click: this.next })
            })
          ])
        )
      }

      return mergeSlot(node, this, 'control')
    },

    __renderPanels (h) {
      return h('div', {
        style: this.style,
        class: this.classes,
        on: { ...this.qListeners }
      }, [
        h('div', {
          staticClass: 'q-carousel__slides-container',
          directives: this.panelDirectives
        }, this.__getPanelContent(h))
      ].concat(this.__getContent(h)))
    }
  },

  mounted () {
    this.autoplay && this.__startTimer()
  },

  beforeDestroy () {
    clearInterval(this.timer)
  }
})
<commit_msg>feat(QCarousel): display back/next arrows only when necessary<commit_after>import Vue from 'vue'

import QBtn from '../btn/QBtn.js'

import DarkMixin from '../../mixins/dark.js'
import { PanelParentMixin } from '../../mixins/panel.js'
import FullscreenMixin from '../../mixins/fullscreen.js'

import { isNumber } from '../../utils/is.js'
import { mergeSlot } from '../../utils/slot.js'
import cache from '../../utils/cache.js'

export default Vue.extend({
  name: 'QCarousel',

  mixins: [ DarkMixin, PanelParentMixin, FullscreenMixin ],

  props: {
    height: String,
    padding: Boolean,

    controlType: {
      type: String,
      validator: v => [ 'regular', 'flat', 'outline', 'push', 'unelevated' ].includes(v),
      default: 'flat'
    },
    controlColor: String,
    controlTextColor: String,

    autoplay: [ Number, Boolean ],

    arrows: Boolean,
    prevIcon: String,
    nextIcon: String,

    navigation: Boolean,
    navigationPosition: {
      type: String,
      validator: v => [ 'top', 'right', 'bottom', 'left' ].includes(v)
    },
    navigationIcon: String,

    thumbnails: Boolean
  },

  computed: {
    style () {
      if (this.inFullscreen !== true && this.height !== void 0) {
        return {
          height: this.height
        }
      }
    },

    direction () {
      return this.vertical === true ? 'vertical' : 'horizontal'
    },

    classes () {
      return `q-carousel q-panel-parent q-carousel--with${this.padding === true ? '' : 'out'}-padding` +
        (this.inFullscreen === true ? ' fullscreen' : '') +
        (this.isDark === true ? ' q-carousel--dark q-dark' : '') +
        (this.arrows === true ? ` q-carousel--arrows-${this.direction}` : '') +
        (this.navigation === true ? ` q-carousel--navigation-${this.navigationPositionComputed}` : '')
    },

    arrowIcons () {
      const ico = [
        this.prevIcon || this.$q.iconSet.carousel[this.vertical === true ? 'up' : 'left'],
        this.nextIcon || this.$q.iconSet.carousel[this.vertical === true ? 'down' : 'right']
      ]

      return this.vertical === false && this.$q.lang.rtl === true
        ? ico.reverse()
        : ico
    },

    navIcon () {
      return this.navigationIcon || this.$q.iconSet.carousel.navigationIcon
    },

    navigationPositionComputed () {
      return this.navigationPosition || (this.vertical === true ? 'right' : 'bottom')
    },

    controlProps () {
      return {
        color: this.controlColor,
        textColor: this.controlTextColor,
        round: true,
        [ this.controlType ]: true,
        dense: true
      }
    },

    transitionPrevComputed () {
      return this.transitionPrev || `fade`
    },

    transitionNextComputed () {
      return this.transitionNext || `fade`
    }
  },

  watch: {
    value () {
      if (this.autoplay) {
        clearInterval(this.timer)
        this.__startTimer()
      }
    },

    autoplay (val) {
      if (val) {
        this.__startTimer()
      }
      else {
        clearInterval(this.timer)
      }
    }
  },

  methods: {
    __startTimer () {
      this.timer = setTimeout(
        this.next,
        isNumber(this.autoplay) ? this.autoplay : 5000
      )
    },

    __getNavigationContainer (h, type, mapping) {
      return h('div', {
        class: 'q-carousel__control q-carousel__navigation no-wrap absolute flex' +
          ` q-carousel__navigation--${type} q-carousel__navigation--${this.navigationPositionComputed}` +
          (this.controlColor !== void 0 ? ` text-${this.controlColor}` : '')
      }, [
        h('div', {
          staticClass: 'q-carousel__navigation-inner flex no-wrap justify-center'
        }, this.__getAvailablePanels().map(mapping))
      ])
    },

    __getContent (h) {
      const node = []

      if (this.navigation === true) {
        node.push(this.__getNavigationContainer(h, 'buttons', panel => {
          const name = panel.componentOptions.propsData.name

          return h(QBtn, {
            key: name,
            class: `q-carousel__navigation-icon q-carousel__navigation-icon--${name === this.value ? '' : 'in'}active`,
            props: {
              icon: this.navIcon,
              size: 'sm',
              ...this.controlProps
            },
            on: cache(this, 'nav#' + name, { click: () => { this.goTo(name) } })
          })
        }))
      }
      else if (this.thumbnails === true) {
        const color = this.controlColor !== void 0
          ? ` text-${this.controlColor}`
          : ''

        node.push(this.__getNavigationContainer(h, 'thumbnails', panel => {
          const slide = panel.componentOptions.propsData

          return h('img', {
            class: `q-carousel__thumbnail q-carousel__thumbnail--${slide.name === this.value ? '' : 'in'}active` + color,
            attrs: {
              src: slide.imgSrc
            },
            key: 'tmb#' + slide.name,
            on: cache(this, 'tmb#' + slide.name, { click: () => { this.goTo(slide.name) } })
          })
        }))
      }

      if (this.arrows === true && this.panelIndex >= 0) {
        if (this.infinite === true || this.panelIndex > 0) {
          node.push(
            h('div', {
              key: 'prev',
              staticClass: `q-carousel__control q-carousel__arrow q-carousel__prev-arrow q-carousel__prev-arrow--${this.direction} absolute flex flex-center`
            }, [
              h(QBtn, {
                props: { icon: this.arrowIcons[0], ...this.controlProps },
                on: cache(this, 'prev', { click: this.previous })
              })
            ])
          )
        }

        if (this.infinite === true || this.panelIndex < this.panels.length - 1) {
          node.push(
            h('div', {
              key: 'next',
              staticClass: `q-carousel__control q-carousel__arrow q-carousel__next-arrow q-carousel__next-arrow--${this.direction} absolute flex flex-center`
            }, [
              h(QBtn, {
                props: { icon: this.arrowIcons[1], ...this.controlProps },
                on: cache(this, 'next', { click: this.next })
              })
            ])
          )
        }
      }

      return mergeSlot(node, this, 'control')
    },

    __renderPanels (h) {
      return h('div', {
        style: this.style,
        class: this.classes,
        on: { ...this.qListeners }
      }, [
        h('div', {
          staticClass: 'q-carousel__slides-container',
          directives: this.panelDirectives
        }, this.__getPanelContent(h))
      ].concat(this.__getContent(h)))
    }
  },

  mounted () {
    this.autoplay && this.__startTimer()
  },

  beforeDestroy () {
    clearInterval(this.timer)
  }
})
<|endoftext|>


<commit_before>'use strict';
const assert = require('./assert');
const Promise = require('bluebird');

function Test(title, action, options) {
    this._title = title;
    this._action = action;
    this._options = options || {};
    this._ran = false;

    if (!title || typeof action !== 'function')
        throw new Error('invalid test()');
}

Test.prototype.run = function (beforeEach, afterEach) {
    return Promise.resolve(beforeEach ? beforeEach(assert) : undefined)
        .then(state => {
            if (this._action.length > 1) {
                return new Promise(resolve => {
                    this._action(assert, state, () => resolve());
                });
            }

            return Promise.resolve(this._action(assert, state))
                .then(() => {
                    return Promise.resolve(afterEach ? afterEach(assert, state) : undefined);
                })
        })
        .then(
            state => {
                this._ran = true;
            },
            err => {
                this._ran = true;
                this._err = err;
            });
};

Test.prototype.getResolution = function() {
    if (!this._ran)
        throw new Error('test has not been run');

    if (this._options.fail) {
        if (this._err)
            return [true];
        else
            return [false];
    }

    if (this._err)
        return [ false, this._err ];
    else
        return [ true ];
};

Test.prototype.getTitle = function() {
    return this._title;
};

Test.prototype.hasOption = function(option) {
    return !!this._options[option];
};

module.exports = Test;<commit_msg>made done work as a node callback<commit_after>'use strict';
const assert = require('./assert');
const Promise = require('bluebird');

function Test(title, action, options) {
    this._title = title;
    this._action = action;
    this._options = options || {};
    this._ran = false;

    if (!title || typeof action !== 'function')
        throw new Error('invalid test()');
}

Test.prototype.run = function (beforeEach, afterEach) {
    return Promise.resolve(beforeEach ? beforeEach(assert) : undefined)
        .then(state => {
            if (this._action.length > 1) {
                return new Promise((resolve, reject) => {
                    this._action(assert, state, (err) => {
                        if (err) {
                            reject(err);
                            return;
                        }

                        resolve();
                    });
                });
            }

            return Promise.resolve(this._action(assert, state))
                .then(() => {
                    return Promise.resolve(afterEach ? afterEach(assert, state) : undefined);
                })
        })
        .then(
            state => {
                this._ran = true;
            },
            err => {
                this._ran = true;
                this._err = err;
            });
};

Test.prototype.getResolution = function() {
    if (!this._ran)
        throw new Error('test has not been run');

    if (this._options.fail) {
        if (this._err)
            return [true];
        else
            return [false];
    }

    if (this._err)
        return [ false, this._err ];
    else
        return [ true ];
};

Test.prototype.getTitle = function() {
    return this._title;
};

Test.prototype.hasOption = function(option) {
    return !!this._options[option];
};

module.exports = Test;<|endoftext|>


<commit_before>import { h, defineComponent } from 'vue'

import useCheckbox, { useCheckboxProps, useCheckboxEmits } from './use-checkbox.js'

const bgNode = [
  h('div', {
    class: 'q-checkbox__bg absolute'
  }, [
    h('svg', {
      class: 'q-checkbox__svg fit absolute-full',
      viewBox: '0 0 24 24',
      'aria-hidden': 'true'
    }, [
      h('path', {
        class: 'q-checkbox__truthy',
        fill: 'none',
        d: 'M1.73,12.91 8.1,19.28 22.79,4.59'
      }),

      h('path', {
        class: 'q-checkbox__indet',
        d: 'M4,14H20V10H4'
      })
    ])
  ])
]

export default defineComponent({
  name: 'QCheckbox',

  props: useCheckboxProps,
  emits: useCheckboxEmits,

  setup () {
    const getInner = () => () => bgNode
    return useCheckbox('checkbox', getInner)
  }
})
<commit_msg>fix(QCheckbox): SSR support<commit_after>import { h, defineComponent } from 'vue'

import useCheckbox, { useCheckboxProps, useCheckboxEmits } from './use-checkbox.js'

export default defineComponent({
  name: 'QCheckbox',

  props: useCheckboxProps,
  emits: useCheckboxEmits,

  setup () {
    const bgNode = [
      h('div', {
        class: 'q-checkbox__bg absolute'
      }, [
        h('svg', {
          class: 'q-checkbox__svg fit absolute-full',
          viewBox: '0 0 24 24',
          'aria-hidden': 'true'
        }, [
          h('path', {
            class: 'q-checkbox__truthy',
            fill: 'none',
            d: 'M1.73,12.91 8.1,19.28 22.79,4.59'
          }),

          h('path', {
            class: 'q-checkbox__indet',
            d: 'M4,14H20V10H4'
          })
        ])
      ])
    ]

    const getInner = () => () => bgNode
    return useCheckbox('checkbox', getInner)
  }
})
<|endoftext|>


<commit_before>/**
 * Utility library for panthrBase.
 * @module utils
 * @author Haris Skiadas <skiadas@hanover.edu>, Barb Wahl <wahl@hanover.edu>
 */
(function(define) {'use strict';
define(function(require) {

   /**
    * A collection of utilities used by panthrBase
    */
   var utils = {};

   /** Value to be used for missing */
   utils.missing = NaN;

   /** Returns true iff `val` is undefined, null, or NaN. **/
   utils.isMissing = function isMissing(val) {
      /* eslint-disable no-self-compare */
      return val == null || val !== val;
      /* eslint-enable */
   };

   utils.isNotMissing = function isNotMissing(val) {
      /* eslint-disable no-self-compare */
      return val != null && val === val;
      /* eslint-enable */
   };

   /** For an array, returns whether the array has any "missing values" in it. */
   utils.hasMissing = function hasMissing(arr) {
      return arr.some(utils.isMissing);
   };

   utils.singleMissing = function singleMissing(val) {
      return utils.isMissing(val) ? NaN : val;
   };

   /* Returns a new function `g` such that: `g(any missing)` is `null`, and `g(val)` is either `f(val)`
    * or `null` if `f(val)` would be "isMissing". */
   utils.makePreserveMissing = function makePreserveMissing(f) {
      return function(val) {
         return utils.isMissing(val) ? NaN :
               utils.singleMissing(f.apply(null, [].slice.call(arguments)));
      };
   };

  /** Return true if all entries in the array are missing */
  utils.allMissing = function allMissing(arr) {
    return arr.every(utils.isMissing);
  };

   utils.equal = function equal(a, b) {
      return utils.isMissing(a) ? utils.isMissing(b)
                                : utils.isNotMissing(b) && a === b;
   };

   /**
    * Checks for array element equality where NaN is considered equal to NaN. Does not
    * recurse.
    */
   utils.areEqualArrays = function areEqualArrays(A, B) {
      var i;
      if (A.length !== B.length) { return false; }
      for (i = 0; i < A.length; i += 1) {
         if (!utils.equal(A[i], B[i])) { return false; }
      }
      return true;
   };

   utils.seq = function seq(from, to, step) {
      var arr = [];
      if (arguments.length === 1) { to = from; from = 1; }
      if (arguments.length < 3) { step = to >= from ? 1 : -1; }
      while ((to - from) * step >= 0) {
         arr.push(from);
         from += step;
      }
      return arr;
   };

   /** Arithmetic operators */
   utils.op = {};

   /** The function that adds two numbers. Also available as `utils.op['+']`. */
   utils.op.add = function add(a, b) { return a + b; };
   utils.op['+'] = utils.op.add;

   /** The function that subtracts two numbers. Also available as `utils.op['-']`. */
   utils.op.sub = function sub(a, b) { return a - b; };
   utils.op['-'] = utils.op.sub;

   /** The function that multiplies two numbers. Also available as `utils.op['*']`. */
   utils.op.mult = function mult(a, b) { return a * b; };
   utils.op['*'] = utils.op.mult;

   /** The function that divides two numbers. Also available as `utils.op['/']`. */
   utils.op.div = function divide(a, b) { return a / b; };
   utils.op['/'] = utils.op.div;

   /** The function that takes two values and returns the minimum. */
   utils.op.min2 = function min2(a, b) { return Math.min(a, b); };

   /** The function that takes two values and returns the maximum. */
   utils.op.max2 = function max2(a, b) { return Math.max(a, b); };

   /**
    * Take a user-provided option description `s` and a list of
    * allowable option settings.  Return the first element of the list
    * that has the string `s` as its initial substring.  Return `null`
    * if no such match is found.
    *
    * If `s` is empty or `null` / undefined, return the default setting `def`.
    */
   utils.getOption = function getOption(s, optList, def) {
      var i;
      if (s == null || s === '') { return def; }
      s = s.toLowerCase();
      for (i = 0; i < optList.length; i += 1) {
         if (optList[i].toLowerCase().indexOf(s) === 0) { return optList[i]; }
      }
      return null;
   };

   return utils;

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<commit_msg>Add utils.arrayToObject<commit_after>/**
 * Utility library for panthrBase.
 * @module utils
 * @author Haris Skiadas <skiadas@hanover.edu>, Barb Wahl <wahl@hanover.edu>
 */
(function(define) {'use strict';
define(function(require) {

   /**
    * A collection of utilities used by panthrBase
    */
   var utils = {};

   /** Value to be used for missing */
   utils.missing = NaN;

   /** Returns true iff `val` is undefined, null, or NaN. **/
   utils.isMissing = function isMissing(val) {
      /* eslint-disable no-self-compare */
      return val == null || val !== val;
      /* eslint-enable */
   };

   utils.isNotMissing = function isNotMissing(val) {
      /* eslint-disable no-self-compare */
      return val != null && val === val;
      /* eslint-enable */
   };

   /** For an array, returns whether the array has any "missing values" in it. */
   utils.hasMissing = function hasMissing(arr) {
      return arr.some(utils.isMissing);
   };

   utils.singleMissing = function singleMissing(val) {
      return utils.isMissing(val) ? NaN : val;
   };

   /* Returns a new function `g` such that: `g(any missing)` is `null`, and `g(val)` is either `f(val)`
    * or `null` if `f(val)` would be "isMissing". */
   utils.makePreserveMissing = function makePreserveMissing(f) {
      return function(val) {
         return utils.isMissing(val) ? NaN :
               utils.singleMissing(f.apply(null, [].slice.call(arguments)));
      };
   };

  /** Return true if all entries in the array are missing */
  utils.allMissing = function allMissing(arr) {
    return arr.every(utils.isMissing);
  };

   utils.equal = function equal(a, b) {
      return utils.isMissing(a) ? utils.isMissing(b)
                                : utils.isNotMissing(b) && a === b;
   };

   /**
    * Checks for array element equality where NaN is considered equal to NaN. Does not
    * recurse.
    */
   utils.areEqualArrays = function areEqualArrays(A, B) {
      var i;
      if (A.length !== B.length) { return false; }
      for (i = 0; i < A.length; i += 1) {
         if (!utils.equal(A[i], B[i])) { return false; }
      }
      return true;
   };

   utils.arrayToObject = function arrayToObject(arr) {
      var obj;
      obj = {};
      arr.forEach(function(k, i) { obj[k] = i + 1; });
      return obj;
   };

   utils.seq = function seq(from, to, step) {
      var arr = [];
      if (arguments.length === 1) { to = from; from = 1; }
      if (arguments.length < 3) { step = to >= from ? 1 : -1; }
      while ((to - from) * step >= 0) {
         arr.push(from);
         from += step;
      }
      return arr;
   };

   /** Arithmetic operators */
   utils.op = {};

   /** The function that adds two numbers. Also available as `utils.op['+']`. */
   utils.op.add = function add(a, b) { return a + b; };
   utils.op['+'] = utils.op.add;

   /** The function that subtracts two numbers. Also available as `utils.op['-']`. */
   utils.op.sub = function sub(a, b) { return a - b; };
   utils.op['-'] = utils.op.sub;

   /** The function that multiplies two numbers. Also available as `utils.op['*']`. */
   utils.op.mult = function mult(a, b) { return a * b; };
   utils.op['*'] = utils.op.mult;

   /** The function that divides two numbers. Also available as `utils.op['/']`. */
   utils.op.div = function divide(a, b) { return a / b; };
   utils.op['/'] = utils.op.div;

   /** The function that takes two values and returns the minimum. */
   utils.op.min2 = function min2(a, b) { return Math.min(a, b); };

   /** The function that takes two values and returns the maximum. */
   utils.op.max2 = function max2(a, b) { return Math.max(a, b); };

   /**
    * Take a user-provided option description `s` and a list of
    * allowable option settings.  Return the first element of the list
    * that has the string `s` as its initial substring.  Return `null`
    * if no such match is found.
    *
    * If `s` is empty or `null` / undefined, return the default setting `def`.
    */
   utils.getOption = function getOption(s, optList, def) {
      var i;
      if (s == null || s === '') { return def; }
      s = s.toLowerCase();
      for (i = 0; i < optList.length; i += 1) {
         if (optList[i].toLowerCase().indexOf(s) === 0) { return optList[i]; }
      }
      return null;
   };

   return utils;

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<|endoftext|>


<commit_before>//     keymaster.js
//     (c) 2011-2012 Thomas Fuchs
//     keymaster.js may be freely distributed under the MIT license.
(function(e){function a(e,t){var n=e.length;while(n--)if(e[n]===t)return n;return-1}function f(e,t){var i,o,f,l,c;i=e.keyCode,a(u,i)==-1&&u.push(i);if(i==93||i==224)i=91;if(i in r){r[i]=!0;for(f in s)s[f]==i&&(h[f]=!0);return}if(!h.filter.call(this,e))return;if(!(i in n))return;for(l=0;l<n[i].length;l++){o=n[i][l];if(o.scope==t||o.scope=="all"){c=o.mods.length>0;for(f in r)if(!r[f]&&a(o.mods,+f)>-1||r[f]&&a(o.mods,+f)==-1)c=!1;(o.mods.length==0&&!r[16]&&!r[18]&&!r[17]&&!r[91]||c)&&o.method(e,o)===!1&&(e.preventDefault?e.preventDefault():e.returnValue=!1,e.stopPropagation&&e.stopPropagation(),e.cancelBubble&&(e.cancelBubble=!0))}}}function l(e){var t=e.keyCode,n,i=a(u,t);i>=0&&u.splice(i,1);if(t==93||t==224)t=91;if(t in r){r[t]=!1;for(n in s)s[n]==t&&(h[n]=!1)}}function c(){for(t in r)r[t]=!1;for(t in s)h[t]=!1}function h(e,t,r){var i,u,a,f;r===undefined&&(r=t,t="all"),e=e.replace(/\s/g,""),i=e.split(","),i[i.length-1]==""&&(i[i.length-2]+=",");for(a=0;a<i.length;a++){u=[],e=i[a].split("+");if(e.length>1){u=e.slice(0,e.length-1);for(f=0;f<u.length;f++)u[f]=s[u[f]];e=[e[e.length-1]]}e=e[0],e=o[e]||e.toUpperCase().charCodeAt(0),e in n||(n[e]=[]),n[e].push({shortcut:i[a],scope:t,method:r,key:i[a],mods:u})}}function p(e){if(typeof e=="string"){if(e.length!=1)return!1;e=e.toUpperCase().charCodeAt(0)}return a(u,e)!=-1}function d(){return u}function v(e){var t=(e.target||e.srcElement).tagName;return t!="INPUT"&&t!="SELECT"&&t!="TEXTAREA"}function m(e){i=e||"all"}function g(){return i||"all"}function y(e){var t,r,i;for(t in n){r=n[t];for(i=0;i<r.length;)r[i].scope===e?r.splice(i,1):i++}}function b(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,function(){n(window.event)})}function E(){var t=e.key;return e.key=w,t}var t,n={},r={16:!1,18:!1,17:!1,91:!1},i="all",s={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,command:91},o={backspace:8,tab:9,clear:12,enter:13,"return":13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,del:46,"delete":46,home:36,end:35,pageup:33,pagedown:34,",":188,".":190,"/":191,"`":192,"-":189,"=":187,";":186,"'":222,"[":219,"]":221,"\\":220},u=[];for(t=1;t<20;t++)s["f"+t]=111+t;for(t in s)h[t]=!1;b(document,"keydown",function(e){f(e,i)}),b(document,"keyup",l),b(window,"focus",c);var w=e.key;e.key=h,e.key.setScope=m,e.key.getScope=g,e.key.deleteScope=y,e.key.filter=v,e.key.isPressed=p,e.key.getPressedKeyCodes=d,e.key.noConflict=E,typeof module!="undefined"&&(module.exports=key)})(this);<commit_msg>update minified version<commit_after>//     keymaster.js
//     (c) 2011-2012 Thomas Fuchs
//     keymaster.js may be freely distributed under the MIT license.
(function(e){function f(e,t){var n=e.length;while(n--)if(e[n]===t)return n;return-1}function l(e,t){if(e.length!=t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function h(e){for(t in r)r[t]=e[c[t]]}function p(e,t){var i,o,u,l,c;i=e.keyCode,f(a,i)==-1&&a.push(i);if(i==93||i==224)i=91;if(i in r){r[i]=!0;for(u in s)s[u]==i&&(m[u]=!0);return}h(e);if(!m.filter.call(this,e))return;if(!(i in n))return;for(l=0;l<n[i].length;l++){o=n[i][l];if(o.scope==t||o.scope=="all"){c=o.mods.length>0;for(u in r)if(!r[u]&&f(o.mods,+u)>-1||r[u]&&f(o.mods,+u)==-1)c=!1;(o.mods.length==0&&!r[16]&&!r[18]&&!r[17]&&!r[91]||c)&&o.method(e,o)===!1&&(e.preventDefault?e.preventDefault():e.returnValue=!1,e.stopPropagation&&e.stopPropagation(),e.cancelBubble&&(e.cancelBubble=!0))}}}function d(e){var t=e.keyCode,n,i=f(a,t);i>=0&&a.splice(i,1);if(t==93||t==224)t=91;if(t in r){r[t]=!1;for(n in s)s[n]==t&&(m[n]=!1)}}function v(){for(t in r)r[t]=!1;for(t in s)m[t]=!1}function m(e,t,r){var i,s,o,a;i=T(e),r===undefined&&(r=t,t="all");for(o=0;o<i.length;o++)s=[],e=i[o].split("+"),e.length>1&&(s=N(e),e=[e[e.length-1]]),e=e[0],e=u(e),e in n||(n[e]=[]),n[e].push({shortcut:i[o],scope:t,method:r,key:i[o],mods:s})}function g(e,t){var r=e.split("+"),i=[],s,o;r.length>1&&(i=N(r),e=r[r.length-1]),e=u(e),t===undefined&&(t=S());if(!n[e])return;for(s in n[e])o=n[e][s],o.scope===t&&l(o.mods,i)&&(n[e][s]={})}function y(e){return typeof e=="string"&&(e=u(e)),f(a,e)!=-1}function b(){return a.slice(0)}function w(e){var t=(e.target||e.srcElement).tagName;return t!="INPUT"&&t!="SELECT"&&t!="TEXTAREA"}function E(e){i=e||"all"}function S(){return i||"all"}function x(e){var t,r,i;for(t in n){r=n[t];for(i=0;i<r.length;)r[i].scope===e?r.splice(i,1):i++}}function T(e){var t;return e=e.replace(/\s/g,""),t=e.split(","),t[t.length-1]==""&&(t[t.length-2]+=","),t}function N(e){var t=e.slice(0,e.length-1);for(mi=0;mi<t.length;mi++)t[mi]=s[t[mi]];return t}function C(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,function(){n(window.event)})}function L(){var t=e.key;return e.key=k,t}var t,n={},r={16:!1,18:!1,17:!1,91:!1},i="all",s={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,command:91},o={backspace:8,tab:9,clear:12,enter:13,"return":13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,del:46,"delete":46,home:36,end:35,pageup:33,pagedown:34,",":188,".":190,"/":191,"`":192,"-":189,"=":187,";":186,"'":222,"[":219,"]":221,"\\":220},u=function(e){return o[e]||e.toUpperCase().charCodeAt(0)},a=[];for(t=1;t<20;t++)o["f"+t]=111+t;var c={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey"};for(t in s)m[t]=!1;C(document,"keydown",function(e){p(e,i)}),C(document,"keyup",d),C(window,"focus",v);var k=e.key;e.key=m,e.key.setScope=E,e.key.getScope=S,e.key.deleteScope=x,e.key.filter=w,e.key.isPressed=y,e.key.getPressedKeyCodes=b,e.key.noConflict=L,e.key.unbind=g,typeof module!="undefined"&&(module.exports=key)})(this);<|endoftext|>


<commit_before>const expect = require('chai').expect;

const converter = require('../../../utils/inputConverter');

describe('Input Converter tests', () => {
    const stringWithSlash = 'some/thing';
    const stringWithApostrophe = 'some\'thing';
    const stringWithQuote = 'some"thing';
    const stringWithLessThan = 'some<thing';
    const stringWithGreaterThan = 'some>thing';
    const stringWithAmpersand = 'some&thing';
    const expectedString = 'something';

    it('Should return escaped string without slash', () => {
        expect(() => converter(stringWithSlash).to.equal(expectedString));
    });

    it('Should return escaped string without Apostrophe', () => {
        expect(() => converter(stringWithApostrophe).to.equal(expectedString));
    });

    it('Should return escaped string without Quote', () => {
        expect(() => converter(stringWithQuote).to.equal(expectedString));
    });

    it('Should return escaped string without Less than sign', () => {
        expect(() => converter(stringWithLessThan).to.equal(expectedString));
    });

    it('Should return escaped string without Greater than sign', () => {
        expect(() => converter(stringWithGreaterThan).to.equal(expectedString));
    });

    it('Should return escaped string without Ampersand', () => {
        expect(() => converter(stringWithAmpersand).to.equal(expectedString));
    });
});
<commit_msg>refactored tests<commit_after>const expect = require('chai').expect;

const converter = require('../../../utils/inputConverter').convert;

describe('Input Converter tests', () => {
    const stringWithSlash = 'some/thing';
    const escapedStringWithSlash = 'some/thing';
    const stringWithApostrophe = 'some\'thing';
    const escapedStringWithApostrophe = 'some'thing';
    const stringWithQuote = 'some"thing';
    const escapedStringWithQuote = 'some"thing';
    const stringWithLessThan = 'some<thing';
    const escapedStringWithLessThan = 'some<thing';
    const stringWithGreaterThan = 'some>thing';
    const escapedStringWithGreaterThan = 'some>thing';
    const stringWithAmpersand = 'some&thing';
    const escapedStringWithAmpersand = 'some&thing';

    it('Should return escaped string without slash', () => {
        const converted = converter(stringWithSlash);
        expect(converted).to.equal(escapedStringWithSlash);
    });

    it('Should return escaped string without Apostrophe', () => {
        const converted = converter(stringWithApostrophe);
        expect(converted).to.equal(escapedStringWithApostrophe);
    });

    it('Should return escaped string without Quote', () => {
        const converted = converter(stringWithQuote);
        expect(converted).to.equal(escapedStringWithQuote);
    });

    it('Should return escaped string without Less than sign', () => {
        const converted = converter(stringWithLessThan);
        expect(converted).to.equal(escapedStringWithLessThan);
    });

    it('Should return escaped string without Greater than sign', () => {
        const converted = converter(stringWithGreaterThan);
        expect(converted).to.equal(escapedStringWithGreaterThan);
    });

    it('Should return escaped string without Ampersand', () => {
        const converted = converter(stringWithAmpersand);
        expect(converted).to.equal(escapedStringWithAmpersand);
    });
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var utils = require('./utils');
var Manager = require('./manager');
var Widget = require('./widget');

function WidgetType(manager, opts) {
    this.id = _.uniqueId('widgetsType');

    this.manager = manager;
    this.editor = this.manager.editor;
    this.opts = opts || {};
    this.enabled = false;

    _.bindAll(this);
}
util.inherits(WidgetType, EventEmitter);

WidgetType.prototype.className = 'widget';
WidgetType.prototype.debounceWait = 500;

// Return all occurrences in a text
WidgetType.prototype.find = function(text) {
    return [];
};

// If edition is not inside a marker, detect section to process
// For example if the widget is inline, we can limit this to a single line
// Should return a range
WidgetType.prototype.findEditRange = function(range) {
    return range;
};

// Create the dom element for a specific widget
WidgetType.prototype.createElement = function(widget) {
    var el = document.createElement('span');
    return el;
};

// Create a new widget
WidgetType.prototype.createWidget = function(range, props) {
    var that = this;
    var doc = this.doc();
    var cursor = doc.getCursor();

    // Is cursor inside?
    if (utils.posInsideRange(cursor, range)) {
        this.unrenderRange(range, props);
    } else {
        var widget = new Widget(this, range, props);

        widget.marker.on('clear', function(_from, _to) {
            if (!that.enabled) return;

            that.unrenderRange(utils.Range(_from, _to), props);
        });

        that.prepareWidget(widget);
    }
};

// Prepare a widget
// Can be extend by mixin (see "menu")
WidgetType.prototype.prepareWidget = function(widget) {

}

// Render as text a marker
WidgetType.prototype.unrenderRange = function(range, props) {
    var doc = this.doc();
    var marker = this.bindMarker(doc.markText(range.from, range.to), props);
    this.manager.setUnrendered(marker);
}

// Bind a marker to be identifiable
WidgetType.prototype.bindMarker = function(marker, props) {
    marker.xProps = props;
    marker.xType = this.id;
    return marker;
};

// Create a marker for a widget
WidgetType.prototype.createWidgetMarker = function(from, to, opts) {
    var marker = this.doc().markText(from, to, _.extend(opts || {}, {
        clearOnEnter: true,
        atomic: true
    }));
    return this.bindMarker(marker);
};

// Convert a list of matches in widgets
WidgetType.prototype.processMatches = function(from, matches) {
    var that = this;
    var fromIndex = from? this.editor.indexFromPos(from) : 0;
    var doc = this.doc();

    _.each(matches, function(match) {
        var range = utils.Range(
            doc.posFromIndex(fromIndex + match.start),
            doc.posFromIndex(fromIndex + match.end)
        );

        that.createWidget(range, match.props);
    });
};

// Apply widgets in a specific sections
WidgetType.prototype.processRange = function(range) {
    // Extract text
    var text = this.doc().getRange(range.from, range.to);

    // Extract matches
    var matches = this.find(text, range);

    // Process matches
    this.processMatches(range.from, matches);
};

// Render all widgets
WidgetType.prototype.renderAll = function() {
    // Extract text
    var text = this.doc().getValue();

    // Extract matches
    var matches = this.find(text);

    this.processMatches({
        line: 0,
        ch: 0
    }, matches);
};

// Unrender all widgets
WidgetType.prototype.unrenderAll = function() {
    var that = this;

    _.each(this.doc().getAllMarks(), function(mark) {
        if (mark.xType != that.id) return;
        mark.clear();
    });
};

// Cleanup all markers in a specified range
// Return the largest range that contain markers
WidgetType.prototype.cleanupMarkers = function(origin) {
    var that = this;
    var range = { from: origin.from, to: origin.to };

    _.each(this.doc().getAllMarks(), function(mark) {
        if (mark.xType != that.id) return;

        var markRange = mark.find();
        if (!markRange) return;

        var isInRange = markRange.line? posInsideRange(markRange, origin) : utils.rangesOverlap(markRange, origin);
        if (!isInRange) return;

        if (utils.posIsBefore(markRange.from, range.from)) {
            range.from = markRange.from;
        }
        if (utils.posIsBefore(range.to, markRange.to)) {
            range.to = markRange.to;
        }

        mark.clear();
    });

    // If nothing found, find larger section to process
    if (utils.rangesEqual(origin, range)) {
        range = this.findEditRange(origin);
    }

    return range;
};

// Blur from editor
WidgetType.prototype.onBlur = function() {

};

// Editor content changed
WidgetType.prototype.processChange = function(change) {
    if (change.origin == 'setValue') {
        return this.renderAll();
    }

    // Calcul range of change (change is pre-operation)
    var changeRange = {
        from: utils.Pos(change.from.line, change.from.ch),
        to: utils.Pos(change.to.line + (change.text.length - 1), change.to.ch + _.last(change.text).length)
    };

    // Determine large range and cleanup markers in it
    var range = this.cleanupMarkers(changeRange);
    this.processRange(range);
};
WidgetType.prototype.onChange = function(inst, change) {
    var that = this;

    if (this._onChange) clearTimeout(this._onChange);
    this._onChange = setTimeout(function() {
        that.processChange(change);
    }, this.debounceWait);
};

WidgetType.prototype.enable = function() {
    if (this.enabled) return;

    this.enabled = true;
    this.manager.editor.on('change', this.onChange);
    this.manager.editor.on('blur', this.onBlur);
    this.renderAll();
};

WidgetType.prototype.disable = function() {
    if (!this.enabled) return;

    this.enabled = false;
    this.manager.editor.off('change', this.onChange);
    this.manager.editor.off('blur', this.onBlur);
    this.unrenderAll();
};

// Return the concerned document
WidgetType.prototype.doc = function() {
    return this.manager.doc();
};

// Define option to CodeMirror
function setupOption(Type, CodeMirror) {
    CodeMirror.defineOption(Type.prototype.className + 'Widget', false, function(cm, val, old) {
        if (old == CodeMirror.Init) old = false;
        if (val == old) return;

        // If editor has no manager, add one
        if (!cm._widgets) Manager(cm);

        if (val) {
            cm._widgets.enable(Type, val);
        } else {
            cm._widgets.disable(Type);
        }
    });
}

// Create an new type
function createType(type) {
    var CustomType = function() {
        WidgetType.apply(this, arguments);
    };
    util.inherits(CustomType, WidgetType);

    CustomType.prototype = utils.composeMixins(
        CustomType.prototype,
        (type.mixins || []).concat([type]),
        {
            composables: ['enable', 'disable', 'prepareWidget']
        }
    );

    CustomType.id = _.uniqueId('WidgetType');
    CustomType.setupOption = _.partial(setupOption, CustomType);

    return CustomType;
}

module.exports = {
    WidgetType: WidgetType,
    create: createType
};
<commit_msg>Correctly update markers after a change<commit_after>var _ = require('lodash');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var utils = require('./utils');
var Manager = require('./manager');
var Widget = require('./widget');

function WidgetType(manager, opts) {
    this.id = _.uniqueId('widgetsType');

    this.manager = manager;
    this.editor = this.manager.editor;
    this.opts = opts || {};
    this.enabled = false;

    _.bindAll(this);
}
util.inherits(WidgetType, EventEmitter);

WidgetType.prototype.className = 'widget';
WidgetType.prototype.debounceWait = 500;

// Return all occurrences in a text
WidgetType.prototype.find = function(text) {
    return [];
};

// If edition is not inside a marker, detect section to process
// For example if the widget is inline, we can limit this to a single line
// Should return a range
WidgetType.prototype.findEditRange = function(range) {
    return range;
};

// Create the dom element for a specific widget
WidgetType.prototype.createElement = function(widget) {
    var el = document.createElement('span');
    return el;
};

// Create a new widget
WidgetType.prototype.createWidget = function(range, props) {
    var that = this;
    var doc = this.doc();
    var cursor = doc.getCursor();

    // Is cursor inside?
    if (utils.posInsideRange(cursor, range)) {
        this.unrenderRange(range, props);
    } else {
        var widget = new Widget(this, range, props);

        widget.marker.on('clear', function(_from, _to) {
            if (!that.enabled) return;

            that.unrenderRange(utils.Range(_from, _to), props);
        });

        that.prepareWidget(widget);
    }
};

// Prepare a widget
// Can be extend by mixin (see "menu")
WidgetType.prototype.prepareWidget = function(widget) {

}

// Render as text a marker
WidgetType.prototype.unrenderRange = function(range, props) {
    var doc = this.doc();
    var marker = this.bindMarker(doc.markText(range.from, range.to), props);
    this.manager.setUnrendered(marker);
}

// Bind a marker to be identifiable
WidgetType.prototype.bindMarker = function(marker, props) {
    marker.xProps = props;
    marker.xType = this.id;
    return marker;
};

// Create a marker for a widget
WidgetType.prototype.createWidgetMarker = function(from, to, opts) {
    var marker = this.doc().markText(from, to, _.extend(opts || {}, {
        clearOnEnter: true,
        atomic: true
    }));
    return this.bindMarker(marker);
};

// Convert a list of matches in widgets
WidgetType.prototype.processMatches = function(from, matches) {
    var that = this;
    var fromIndex = from? this.editor.indexFromPos(from) : 0;
    var doc = this.doc();

    _.each(matches, function(match) {
        var range = utils.Range(
            doc.posFromIndex(fromIndex + match.start),
            doc.posFromIndex(fromIndex + match.end)
        );

        that.createWidget(range, match.props);
    });
};

// Apply widgets in a specific sections
WidgetType.prototype.processRange = function(range) {
    // Extract text
    var text = this.doc().getRange(range.from, range.to);

    // Extract matches
    var matches = this.find(text, range);

    // Process matches
    this.processMatches(range.from, matches);
};

// Render all widgets
WidgetType.prototype.renderAll = function() {
    // Extract text
    var text = this.doc().getValue();

    // Extract matches
    var matches = this.find(text);

    this.processMatches({
        line: 0,
        ch: 0
    }, matches);
};

// Unrender all widgets
WidgetType.prototype.unrenderAll = function() {
    var that = this;

    _.each(this.doc().getAllMarks(), function(mark) {
        if (mark.xType != that.id) return;
        mark.clear();
    });
};

// Cleanup all markers in a specified range
// Return the largest range that contain markers
WidgetType.prototype.cleanupMarkers = function(origin) {
    var that = this;
    var range = { from: origin.from, to: origin.to };

    _.each(this.doc().getAllMarks(), function(mark) {
        if (mark.xType != that.id) return;

        var markRange = mark.find();
        if (!markRange) return;

        var isInRange = markRange.line? posInsideRange(markRange, origin) : utils.rangesOverlap(markRange, origin);
        if (!isInRange) return;

        if (utils.posIsBefore(markRange.from, range.from)) {
            range.from = markRange.from;
        }
        if (utils.posIsBefore(range.to, markRange.to)) {
            range.to = markRange.to;
        }

        mark.clear();
    });

    return range;
};

// Blur from editor
WidgetType.prototype.onBlur = function() {

};

// Editor content changed
WidgetType.prototype.processChange = function(change) {
    if (change.origin == 'setValue') {
        return this.renderAll();
    }

    // Calcul range of change (change is pre-operation)
    var changeRange = {
        from: utils.Pos(change.from.line, change.from.ch),
        to: utils.Pos(change.to.line + (change.text.length - 1), change.to.ch + _.last(change.text).length)
    };

    // Determine large range and cleanup markers in it
    var range = this.cleanupMarkers(changeRange);

    // If nothing found, find larger section to process
    if (utils.rangesEqual(changeRange, range)) {
        range = this.findEditRange(changeRange);
        this.cleanupMarkers(changeRange);
    }

    // Update markers in this range
    this.processRange(range);
};
WidgetType.prototype.onChange = function(inst, change) {
    var that = this;

    if (this._onChange) clearTimeout(this._onChange);
    this._onChange = setTimeout(function() {
        that.processChange(change);
    }, this.debounceWait);
};

WidgetType.prototype.enable = function() {
    if (this.enabled) return;

    this.enabled = true;
    this.manager.editor.on('change', this.onChange);
    this.manager.editor.on('blur', this.onBlur);
    this.renderAll();
};

WidgetType.prototype.disable = function() {
    if (!this.enabled) return;

    this.enabled = false;
    this.manager.editor.off('change', this.onChange);
    this.manager.editor.off('blur', this.onBlur);
    this.unrenderAll();
};

// Return the concerned document
WidgetType.prototype.doc = function() {
    return this.manager.doc();
};

// Define option to CodeMirror
function setupOption(Type, CodeMirror) {
    CodeMirror.defineOption(Type.prototype.className + 'Widget', false, function(cm, val, old) {
        if (old == CodeMirror.Init) old = false;
        if (val == old) return;

        // If editor has no manager, add one
        if (!cm._widgets) Manager(cm);

        if (val) {
            cm._widgets.enable(Type, val);
        } else {
            cm._widgets.disable(Type);
        }
    });
}

// Create an new type
function createType(type) {
    var CustomType = function() {
        WidgetType.apply(this, arguments);
    };
    util.inherits(CustomType, WidgetType);

    CustomType.prototype = utils.composeMixins(
        CustomType.prototype,
        (type.mixins || []).concat([type]),
        {
            composables: ['enable', 'disable', 'prepareWidget']
        }
    );

    CustomType.id = _.uniqueId('WidgetType');
    CustomType.setupOption = _.partial(setupOption, CustomType);

    return CustomType;
}

module.exports = {
    WidgetType: WidgetType,
    create: createType
};
<|endoftext|>


<commit_before>
exports.version = '0.0.0';
<commit_msg>lib: add type detect lib<commit_after>/*!
 * type-detect
 * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
 * MIT Licensed
 */

/*!
 * Primary Exports
 */

var exports = module.exports = getType;

/*!
 * Detectable javascript natives
 */

var natives = {
    '[object Array]': 'array'
  , '[object RegExp]': 'regexp'
  , '[object Function]': 'function'
  , '[object Arguments]': 'arguments'
  , '[object Date]': 'date'
};

/**
 * Use several different techniques to determine
 * the type of object being passed.
 *
 * Provided as primary export.
 *
 * @param {Mixed} object
 * @return {String} object type
 * @api public
 */

function getType (obj) {
  var str = Object.prototype.toString.call(obj);
  if (natives[str]) return natives[str];
  if (obj === null) return 'null';
  if (obj === undefined) return 'undefined';
  if (obj === Object(obj)) return 'object';
  return typeof obj;
}

exports.Library = Library;

/**
 * ### Library
 *
 * Create a repository for custom type detection.
 *
 * ```js
 * var lib = new type.Library;
 * ```
 *
 */

function Library () {
  this.tests = {};
}

/**
 * #### .of (obj)
 *
 * Expose native type detection to a library.
 *
 * ```js
 * if ('string' === lib.of('hello world')) {
 *   // ...
 * }
 * ```
 *
 * @param {Mixed} object to test
 * @return {String} type
 */

Library.prototype.of = getType;

/**
 * Add a test to for the `.is()` assertion.
 *
 * @param {String} type
 * @param {RegExp|Function} test
 * @api public
 */

Library.prototype.define = function (type, test) {
  if (arguments.length === 1) return this.tests[type];
  this.tests[type] = test;
  return this;
};

/**
 * Assert that an object is of type. Will first
 * check natives, and if that does not pass it will
 * use the user defined custom tests.
 *
 * @param {Mixed} object
 * @param {String} type
 * @return {Boolean} result
 * @api public
 */

Library.prototype.test = function (obj, type) {
  if (type === getType(obj)) return true;

  if (this.tests[type]) {
    var test = this.tests[type];
    if ('regexp' === getType(test)) return test.test(obj);
    if ('function' === getType(test)) return test(obj);
  } else {
    throw new ReferenceError('Type test "' + type + '" not defined.');
  }

  return false;
};
<|endoftext|>


<commit_before>function FindProxyForURL(url, host) {
    if (shExpMatch(url, "http://v.youku.com/player/*") ||
            shExpMatch(url, "http://apps.bdimg.com/cloudaapi/lightapp.js*") ||
            shExpMatch(url, "http://apps.bdimg.com/cloudaapi/api-list.js*") ||

            shExpMatch(url, "http://openapi.baidu.com/cloudaapi/lightapp.js*") ||
            shExpMatch(url, "https://openapi.baidu.com/cloudaapi/lightapp.js*") ||

            shExpMatch(url, "http://apps.bdimg.com/cloudaapi/*") ||

            shExpMatch(url, "http://m.baidu.com/static/search/siteapp/lego/*")) {

        return "PROXY tc-dev-light00.tc.baidu.com:8080";

        #return "PROXY tc-dev-light00.tc.baidu.com:8080/static/cloudaapi/lightapp.js";

        return "PROXY 127.0.0.1:8888";

        return "PROXY 172.22.149.109:8888";

        #return "SOCKS5 127.0.0.1:7070; DIRECT";

    }
    return "DIRECT";
}<commit_msg>opt pac<commit_after>function FindProxyForURL(url, host) {
    if (shExpMatch(url, "http://music.baidu.com/player/*") ||
            shExpMatch(url, "http://apps.bdimg.com/cloudaapi/lightapp.js*") ||
            shExpMatch(url, "http://apps.bdimg.com/cloudaapi/api-list.js*") ||

            shExpMatch(url, "http://openapi.baidu.com/cloudaapi/lightapp.js*") ||
            shExpMatch(url, "https://openapi.baidu.com/cloudaapi/lightapp.js*") ||

            shExpMatch(url, "http://apps.bdimg.com/cloudaapi/*") ||

            shExpMatch(url, "http://m.baidu.com/static/search/siteapp/lego/*")) {

        #return "PROXY tc-dev-light00.tc.baidu.com:8080";

        #return "PROXY tc-dev-light00.tc.baidu.com:8080/static/cloudaapi/lightapp.js";

        return "PROXY 127.0.0.1:8080";

        #return "PROXY 172.22.149.109:8080";

        #return "SOCKS5 127.0.0.1:7070; DIRECT";

    }
    return "DIRECT";
}<|endoftext|>