<commit_before>/**
 * @file PopupProvider component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, cloneElement, Fragment, createRef} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';

// components
import Popup from '../Popup';

// statics
import Theme from '../Theme';
import Position from '../_statics/Position';

// vendors
import Util from '../_vendors/Util';
import ComponentUtil from '../_vendors/ComponentUtil';

class PopupProvider extends Component {

    static Position = Position;
    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            value: ComponentUtil.getDerivedState(props, state, 'visible')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.trigger = createRef();
        this.triggerEl = null;

        this.state = {
            visible: props.visible
        };

    }

    /**
     * public
     */
    show = () => {

        if (this.state.visible) {
            return;
        }

        this.setState({
            visible: true
        }, () => {
            const {onRequestOpen} = this.props;
            onRequestOpen && onRequestOpen();
        });

    };

    /**
     * public
     */
    hide = () => {

        if (!this.state.visible) {
            return;
        }

        this.setState({
            visible: false
        }, () => {
            const {onRequestClose} = this.props;
            onRequestClose && onRequestClose();
        });

    };

    /**
     * public
     */
    toggle = () => {
        this.setState({
            visible: !this.state.visible
        }, () => {
            if (!this.state.visible) {
                const {onRequestClose} = this.props;
                onRequestClose && onRequestClose();
            } else {
                const {onRequestOpen} = this.props;
                onRequestOpen && onRequestOpen();
            }
        });
    };

    handleClick = e => {

        const {children} = this.props;

        if (children && children.props && children.props.onClick
            && typeof children.props.onClick === 'function') {
            children.props.onClick(e);
        }

        this.toggle();

    };

    componentDidMount() {
        this.triggerEl = this.trigger && this.trigger.current && findDOMNode(this.trigger.current);
    }

    render() {

        const {

                children, popupContent,

                // not passing down these props
                onRequestOpen, onRequestClose,

                ...restProps

            } = this.props,
            {visible} = this.state;

        if (!popupContent) {
            return children;
        }

        return (
            <Fragment>

                {
                    cloneElement(children, {
                        ref: this.trigger,
                        onClick: this.handleClick
                    })
                }

                <Popup {...restProps}
                       triggerEl={this.triggerEl}
                       visible={visible}
                       onRequestClose={this.hide}>
                    {popupContent}
                </Popup>

            </Fragment>
        );
    }

}

PopupProvider.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the content element.
     */
    contentClassName: PropTypes.string,

    modalClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The popup theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    parentEl: PropTypes.object,

    /**
     * This is the DOM element that will be used to set the position of the popup.
     */
    triggerEl: PropTypes.object,

    /**
     * If true,the popup is visible.
     */
    visible: PropTypes.bool,

    /**
     * If true,the popup will have a triangle on the top of the DOM element.
     */
    hasTriangle: PropTypes.bool,

    triangle: PropTypes.element,

    /**
     * The popup alignment.
     */
    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * If true,popup will have animation effects.
     */
    isAnimated: PropTypes.bool,

    /**
     * The depth of Paper component.
     */
    depth: PropTypes.number,

    isBlurClose: PropTypes.bool,
    isEscClose: PropTypes.bool,

    shouldFollowScroll: PropTypes.bool,
    scrollEl: PropTypes.object,

    resetPositionWait: PropTypes.number,
    showModal: PropTypes.bool,

    /**
     * The function of popup event handler.
     */
    triggerHandler: PropTypes.func,

    /**
     * The function of popup render.
     */
    onRender: PropTypes.func,

    /**
     * The function of popup rendered.
     */
    onRendered: PropTypes.func,

    /**
     * The function of popup destroy.
     */
    onDestroy: PropTypes.func,

    /**
     * The function of popup destroyed.
     */
    onDestroyed: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be opened.
     */
    onRequestOpen: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be closed.
     */
    onRequestClose: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func,

    popupContent: PropTypes.any

};

PopupProvider.defaultProps = {

    parentEl: document.body,

    visible: false,
    hasTriangle: true,
    position: Position.BOTTOM,
    isAnimated: true,

    isBlurClose: true,
    isEscClose: true,
    shouldFollowScroll: false,
    resetPositionWait: 250,
    showModal: false

};

export default PopupProvider;
<commit_msg>update PopupProvider<commit_after>/**
 * @file PopupProvider component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, cloneElement, Fragment, createRef} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';

// components
import Popup from '../Popup';

// statics
import Theme from '../Theme';
import Position from '../_statics/Position';

// vendors
import Util from '../_vendors/Util';
import ComponentUtil from '../_vendors/ComponentUtil';

class PopupProvider extends Component {

    static Position = Position;
    static Theme = Theme;

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            visible: ComponentUtil.getDerivedState(props, state, 'visible')
        };
    }

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.trigger = createRef();
        this.triggerEl = null;

        this.state = {
            visible: props.visible
        };

    }

    componentDidMount() {
        this.triggerEl = findDOMNode(this.trigger?.current);
    }

    /**
     * public
     */
    show = () => {

        if (this.state.visible) {
            return;
        }

        this.setState({
            visible: true
        }, () => this.props.onRequestOpen?.());

    };

    /**
     * public
     */
    hide = () => {

        if (!this.state.visible) {
            return;
        }

        this.setState({
            visible: false
        }, () => this.props.onRequestClose?.());

    };

    /**
     * public
     */
    toggle = () => {
        this.setState({
            visible: !this.state.visible
        }, () => {
            if (!this.state.visible) {
                this.props.onRequestClose?.();
            } else {
                this.props.onRequestOpen?.();
            }
        });
    };

    handleClick = e => {

        const {children} = this.props;

        if (children && children.props && children.props.onClick
            && typeof children.props.onClick === 'function') {
            children.props.onClick(e);
        }

        this.toggle();

    };

    render() {

        const {

                children, popupContent,

                // not passing down these props
                // eslint-disable-next-line no-unused-vars
                onRequestOpen, onRequestClose,

                ...restProps

            } = this.props,
            {visible} = this.state;

        if (!popupContent) {
            return children;
        }

        return (
            <Fragment>

                {
                    cloneElement(children, {
                        ref: this.trigger,
                        onClick: this.handleClick
                    })
                }

                <Popup {...restProps}
                       triggerEl={this.triggerEl}
                       visible={visible}
                       onRequestClose={this.hide}>
                    {popupContent}
                </Popup>

            </Fragment>
        );
    }

}

PopupProvider.propTypes = {

    children: PropTypes.any,

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the content element.
     */
    contentClassName: PropTypes.string,

    modalClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The popup theme.Can be primary,highlight,success,warning,error.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    parentEl: PropTypes.object,

    /**
     * This is the DOM element that will be used to set the position of the popup.
     */
    triggerEl: PropTypes.object,

    /**
     * If true,the popup is visible.
     */
    visible: PropTypes.bool,

    /**
     * If true,the popup will have a triangle on the top of the DOM element.
     */
    hasTriangle: PropTypes.bool,

    triangle: PropTypes.element,

    /**
     * The popup alignment.
     */
    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * If true,popup will have animation effects.
     */
    isAnimated: PropTypes.bool,

    /**
     * The depth of Paper component.
     */
    depth: PropTypes.number,

    isBlurClose: PropTypes.bool,
    isEscClose: PropTypes.bool,

    shouldFollowScroll: PropTypes.bool,
    scrollEl: PropTypes.object,

    resetPositionWait: PropTypes.number,
    showModal: PropTypes.bool,

    /**
     * The function of popup event handler.
     */
    triggerHandler: PropTypes.func,

    /**
     * The function of popup render.
     */
    onRender: PropTypes.func,

    /**
     * The function of popup rendered.
     */
    onRendered: PropTypes.func,

    /**
     * The function of popup destroy.
     */
    onDestroy: PropTypes.func,

    /**
     * The function of popup destroyed.
     */
    onDestroyed: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be opened.
     */
    onRequestOpen: PropTypes.func,

    /**
     * Callback function fired when the popup is requested to be closed.
     */
    onRequestClose: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func,

    popupContent: PropTypes.any

};

PopupProvider.defaultProps = {

    parentEl: document.body,

    visible: false,
    hasTriangle: true,
    position: Position.BOTTOM,
    isAnimated: true,

    isBlurClose: true,
    isEscClose: true,
    shouldFollowScroll: false,
    resetPositionWait: 250,
    showModal: false

};

export default PopupProvider;
<|endoftext|>


<commit_before>import r from 'rethinkdb';
import { DB_HOST, DB_PORT } from '../../constants/configurations.js';

const ES_HOST = '192.168.95.138:9200'
const ES_INDEX = 'kb';
const ES_TYPE_ARTICLES = 'articles';
const ES_TYPE_FILES = 'files';
const ES_TYPE_WORKLOGS = 'worklog';
const ES_TYPE_COMMENTS = 'comments';
const ES_TYPE_BUGTRACKINGS = 'bug_tracking';

let elasticsearch = require('elasticsearch');
let client = new elasticsearch.Client({
  host: ES_HOST
  //, log: 'trace'
});

const VALID_FROM_SIZE_REGEXP = /^[0-9]+$/;

let KbElastic = {
  // _decorateFromSize: (searchObj, _from, _size) => {
  //   return Object.assign({}, searchObj, {

  //   })
  // },
  isValidFromSize: (val) => {
    return VALID_FROM_SIZE_REGEXP.exec(val+'');
  },
  getSearchObj: (opt) => {
    let obj = {
        index: ES_INDEX,
        type: opt.typeName //ES_TYPE_ARTICLES,
      };

    if (opt.q) {
      obj.q = opt.q;
    }

    obj.body = opt.body || {};
    // console.log('getSearchObj opt', opt);
    if (KbElastic.isValidFromSize(opt.from)) {
      obj.from = opt.from;
    }
    if (KbElastic.isValidFromSize(opt.size)) {
      obj.size = opt.size;
    }
    // console.log('getSearchObj', obj);
    return obj;
  },
  jsonResult: (result) => {
    const hasHit = result.hits && result.hits.hits && result.hits.hits.length;

    let ret = {
      total: hasHit ? result.hits.total : 0,
      hits: hasHit ? result.hits.hits : []
    };
    return ret;
  }
};

let ArticleElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_ARTICLES;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let FileElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_FILES;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let WorklogElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_WORKLOGS;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let CommentElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_COMMENTS;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let BugtrackingElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_BUGTRACKINGS;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};

let responseSearch = async (req, res, searchMethod) => {
  let searchq = req.query && req.query.searchq;
  let start = req.query && req.query.start; // from
  let count = req.query && req.query.count; // size
  if (searchq) {
    searchq = encodeURIComponent(searchq);
    try {
      let data = await searchMethod.apply(null, [searchq, {from:start, size:count}]);
      data.from = start;
      data.size = count; // http://localhost:3000/search?searchq=knowledges&start=2&count=1
      res.json({'code':0, 'data': data });
    } catch (err) {
      res.json({'err': err});
    }

  } else {
    res.json({'code':0, 'data':null});
  }
};

export const searchArticleHandler = async (req, res) => {
  responseSearch(req, res, ArticleElastic.search);
};
export const searchFileHandler = async (req, res) => {
  responseSearch(req, res, FileElastic.search);
};
export const searchWorklogHandler = async (req, res) => {
  responseSearch(req, res, WorklogElastic.search);
};
export const searchCommentHandler = async (req, res) => {
  responseSearch(req, res, CommentElastic.search);
};
export const searchBugtrackingHandler = async (req, res) => {
  responseSearch(req, res, BugtrackingElastic.search);
};

/*
export const searchFileHandler = async (req, res) => {
  let searchq = req.query && req.query.searchq;
  let start = req.query && req.query.start; // from
  let count = req.query && req.query.count; // size
  if (searchq) {
    searchq = encodeURIComponent(searchq);
    try {
      res.json({'code':0, 'data': await ArticleElastic.search(searchq)});
    } catch (err) {
      res.json({'err': err});
    }

  } else {
    res.json({'code':0, 'data':[]});
  }
};
*/
<commit_msg>[Search] remove useless comment<commit_after>import r from 'rethinkdb';
import { DB_HOST, DB_PORT } from '../../constants/configurations.js';

const ES_HOST = '192.168.95.138:9200'
const ES_INDEX = 'kb';
const ES_TYPE_ARTICLES = 'articles';
const ES_TYPE_FILES = 'files';
const ES_TYPE_WORKLOGS = 'worklog';
const ES_TYPE_COMMENTS = 'comments';
const ES_TYPE_BUGTRACKINGS = 'bug_tracking';

let elasticsearch = require('elasticsearch');
let client = new elasticsearch.Client({
  host: ES_HOST
  //, log: 'trace'
});

const VALID_FROM_SIZE_REGEXP = /^[0-9]+$/;

let KbElastic = {
  // _decorateFromSize: (searchObj, _from, _size) => {
  //   return Object.assign({}, searchObj, {

  //   })
  // },
  isValidFromSize: (val) => {
    return VALID_FROM_SIZE_REGEXP.exec(val+'');
  },
  getSearchObj: (opt) => {
    let obj = {
        index: ES_INDEX,
        type: opt.typeName //ES_TYPE_ARTICLES,
      };

    if (opt.q) {
      obj.q = opt.q;
    }

    obj.body = opt.body || {};
    // console.log('getSearchObj opt', opt);
    if (KbElastic.isValidFromSize(opt.from)) {
      obj.from = opt.from;
    }
    if (KbElastic.isValidFromSize(opt.size)) {
      obj.size = opt.size;
    }
    // console.log('getSearchObj', obj);
    return obj;
  },
  jsonResult: (result) => {
    const hasHit = result.hits && result.hits.hits && result.hits.hits.length;

    let ret = {
      total: hasHit ? result.hits.total : 0,
      hits: hasHit ? result.hits.hits : []
    };
    return ret;
  }
};

let ArticleElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_ARTICLES;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let FileElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_FILES;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let WorklogElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_WORKLOGS;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let CommentElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_COMMENTS;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};
let BugtrackingElastic = {
  search: async (q, opt={}) => {
    opt.typeName = ES_TYPE_BUGTRACKINGS;
    opt.q = q;
    let ret = await client.search(KbElastic.getSearchObj(opt));
    return KbElastic.jsonResult(ret);
  }
};

let responseSearch = async (req, res, searchMethod) => {
  let searchq = req.query && req.query.searchq;
  let start = req.query && req.query.start; // from
  let count = req.query && req.query.count; // size
  if (searchq) {
    searchq = encodeURIComponent(searchq);
    try {
      let data = await searchMethod.apply(null, [searchq, {from:start, size:count}]);
      data.from = start;
      data.size = count; // http://localhost:3000/search?searchq=knowledges&start=2&count=1
      res.json({'code':0, 'data': data });
    } catch (err) {
      res.json({'err': err});
    }

  } else {
    res.json({'code':0, 'data':null});
  }
};

export const searchArticleHandler = async (req, res) => {
  responseSearch(req, res, ArticleElastic.search);
};
export const searchFileHandler = async (req, res) => {
  responseSearch(req, res, FileElastic.search);
};
export const searchWorklogHandler = async (req, res) => {
  responseSearch(req, res, WorklogElastic.search);
};
export const searchCommentHandler = async (req, res) => {
  responseSearch(req, res, CommentElastic.search);
};
export const searchBugtrackingHandler = async (req, res) => {
  responseSearch(req, res, BugtrackingElastic.search);
};
<|endoftext|>


<commit_before>/*
 * grunt-html-sitemap
 * https://github.com/Clever-Labs/grunt-html-sitemap
 *
 * Copyright (c) 2014 Bill Patrianakos
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Gather up dependencies
  var util    = require('util');
  var cheerio = require('cheerio');
  var _       = require('lodash');

  // Register our task
  grunt.registerMultiTask('html_sitemap', 'Create HTML sitemaps from a directory.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var taskOpts = this.options({
      siteBase: JSON.parse(grunt.file.read('package.json')).homepage,
      separator: false,
      searchPath: '',
      template: false,
      descriptions: false
    });

    var markup    = cheerio.load('
\n
');
    var regbuild  = //; // Extract options specified in comment blocks
    var siteMap   = [];
    var outFiles  = [];

    this.files.forEach(function(file) {
      // Add an output path to the list
      outFiles.push(file.dest);

      // Get the contents of the file
      var page = file.src.filter(function(path) {
        if (!grunt.file.exists(path) || grunt.file.isDir(path) || !grunt.file.isFile(path)) {
          grunt.warn('Invalid input file in your ' + this.target + ': ' + path);
          return false;
        } else {
          return true;
        }
      }).map(function(path) {
        var basePath = (typeof path === 'undefined') ? path : path.replace(taskOpts.searchPath, '');
        return {
          contents: grunt.file.read(path),
          path: taskOpts.siteBase + basePath
        };
      });

      // Parse each found page's content
      if (page) {
        page.forEach(function(pageData) {
          var lines = pageData.contents.replace(/\r\n/g, '\n').split(/\n/);
          var options = {};

          // Iterate over each line
          lines.forEach(function(line) {
            var indent = (line.match(/^\s*/) || [])[0];
            var option = line.match(regbuild);

            // If option found
            if (option && option[1] === 'anchor') {
              options.anchor = option[3];
            } else if (option && option[1] === 'order') {
              options.order = option[2];
            } else if (option && option[1] === 'description') {
              options.description = option[3];
            }
          });

          var $ = cheerio.load(pageData.contents); // Page data we can parse

          // Check if file needs to be read
          if (options.anchor) {
            pageData.anchor = options.anchor;
          } else {
            pageData.anchor = (!taskOpts.separator) ? $('title').text() : $('title').text().split(taskOpts.separator)[0];
          }

          // The minimal amount of code a sitemap item can have
          var mapItemString = '
\n' + pageData.anchor + '';

          if (taskOpts.descriptions) {
            if (options.description) {
              markup('ul').append(mapItemString + '\n
' + options.description + '
\n
');
            } else {
              markup('ul').append(mapItemString + '\n
' + $('meta[name="description"]').attr('content') + '
\n
');
            }
          } else {
            // Append the new item to the sitemap

            markup('ul').append(mapItemString + '
');
          }
        });
      }
    });

    // Get unique destinations and write to them
    var destinations = _.uniq(outFiles, function(file) {
      if (taskOpts.template) {
        var sitemapFile = grunt.template.process(grunt.file.read(taskOpts.template), {data: {sitemap: markup.html()}});
        grunt.file.write(file, sitemapFile);
      } else {
        grunt.file.write(file, markup.html());
        grunt.log.writeln('Sitemap file written to ' + file);
      }
    });

  });
};
<commit_msg>Fix for title being pulled from SVGs, it should only look for title tags in head section<commit_after>/*
 * grunt-html-sitemap
 * https://github.com/Clever-Labs/grunt-html-sitemap
 *
 * Copyright (c) 2014 Bill Patrianakos
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Gather up dependencies
  var util    = require('util');
  var cheerio = require('cheerio');
  var _       = require('lodash');

  // Register our task
  grunt.registerMultiTask('html_sitemap', 'Create HTML sitemaps from a directory.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var taskOpts = this.options({
      siteBase: JSON.parse(grunt.file.read('package.json')).homepage,
      separator: false,
      searchPath: '',
      template: false,
      descriptions: false
    });

    var markup    = cheerio.load('
\n
');
    var regbuild  = //; // Extract options specified in comment blocks
    var siteMap   = [];
    var outFiles  = [];

    this.files.forEach(function(file) {
      // Add an output path to the list
      outFiles.push(file.dest);

      // Get the contents of the file
      var page = file.src.filter(function(path) {
        if (!grunt.file.exists(path) || grunt.file.isDir(path) || !grunt.file.isFile(path)) {
          grunt.warn('Invalid input file in your ' + this.target + ': ' + path);
          return false;
        } else {
          return true;
        }
      }).map(function(path) {
        var basePath = (typeof path === 'undefined') ? path : path.replace(taskOpts.searchPath, '');
        return {
          contents: grunt.file.read(path),
          path: taskOpts.siteBase + basePath
        };
      });

      // Parse each found page's content
      if (page) {
        page.forEach(function(pageData) {
          var lines = pageData.contents.replace(/\r\n/g, '\n').split(/\n/);
          var options = {};

          // Iterate over each line
          lines.forEach(function(line) {
            var indent = (line.match(/^\s*/) || [])[0];
            var option = line.match(regbuild);

            // If option found
            if (option && option[1] === 'anchor') {
              options.anchor = option[3];
            } else if (option && option[1] === 'order') {
              options.order = option[2];
            } else if (option && option[1] === 'description') {
              options.description = option[3];
            }
          });

          var $ = cheerio.load(pageData.contents); // Page data we can parse

          // Check if file needs to be read
          if (options.anchor) {
            pageData.anchor = options.anchor;
          } else {
            pageData.anchor = (!taskOpts.separator) ? $('head title').text() : $('head title').text().split(taskOpts.separator)[0];
          }

          // The minimal amount of code a sitemap item can have
          var mapItemString = '
\n' + pageData.anchor + '';

          if (taskOpts.descriptions) {
            if (options.description) {
              markup('ul').append(mapItemString + '\n
' + options.description + '
\n
');
            } else {
              markup('ul').append(mapItemString + '\n
' + $('meta[name="description"]').attr('content') + '
\n
');
            }
          } else {
            // Append the new item to the sitemap

            markup('ul').append(mapItemString + '
');
          }
        });
      }
    });

    // Get unique destinations and write to them
    var destinations = _.uniq(outFiles, function(file) {
      if (taskOpts.template) {
        var sitemapFile = grunt.template.process(grunt.file.read(taskOpts.template), {data: {sitemap: markup.html()}});
        grunt.file.write(file, sitemapFile);
      } else {
        grunt.file.write(file, markup.html());
        grunt.log.writeln('Sitemap file written to ' + file);
      }
    });

  });
};
<|endoftext|>


<commit_before>var Parser = function() {
    this.mark = 'THIS-NEEDS-TO-BE-UNIQUE-TO-SERVE-AS-A-BOUNDARY';
    this.memo = {};
    this.stack = [];
};

Parser.prototype.load = function(pickle) {
    var APPEND = 'a'            // append stack top to list below it
      , APPENDS = 'e'           // extend list on stack by topmost stack slice
      , INT = 'I'               // push integer or bool; decimal string argument
      , BININT = 'J'            // push 4-byte unsigned int
      , BININT1 = 'K'           // push 1-byte unsigned int
      , BININT2 = 'M'           // push 2-byte unsigned int
      , BINFLOAT = 'G'          // push float; arg is 8-byte float encoding
      , BINPUT = 'q'            // store stack top in memo; index is string 1-byte arg
      , BINSTRING = 'T'
      , DICT = 'd'
      , EMPTY_DICT = '}'
      , EMPTY_LIST = ']'
      , FLOAT = 'F'
      , LIST = 'l'
      , MARK = '('
      , PROTO = '\x80'
      , PUT = 'p'
      , SETITEM = 's'
      , SETITEMS = 'u'
      , SHORT_BINSTRING = 'U'
      , STOP = '.'
      , STRING = 'S';

    var buffer = new Buffer(pickle, 'binary');

    function readline(pickle, i) {
        var index = pickle.indexOf('\n', i);
        if (index == -1)
            throw "Could not find end of line";
        return pickle.substr(i, index - i);
    }

    for (var i = 0; i < pickle.length; ) {
        var opindex = i
          , opcode = pickle[i++];
        //console.log('opcode ' + opindex + ' ' + opcode);
        switch (opcode) {
        case PROTO:
            var proto = pickle.charCodeAt(i++);
            if (proto != 2)
                throw 'Unhandled pickle protocol version';
            break;
        case EMPTY_DICT:
            this.stack.push({});
            break;
        case EMPTY_LIST:
            this.stack.push([]);
            break;
        case BINPUT:
            var index = buffer.readUInt8(i++);
            this.memo['' + index] = this.stack[this.stack.length-1];
            break;
        case PUT:
            var index = readline(pickle, i);
            i += index.length + 1;
            this.memo[index] = this.stack[this.stack.length-1];
            break;
        case INT:
            var value = readline(pickle, i);
            i += value.length + 1;
            this.stack.push(parseInt(value));
            break;
        case BININT:
            this.stack.push(buffer.readUInt32LE(i));
            i += 4;
            break;
        case BININT1:
            this.stack.push(buffer.readUInt8(i));
            i += 1;
            break;
        case BININT2:
            this.stack.push(buffer.readUInt16LE(i));
            i += 2;
            break;
        case MARK:
            this.stack.push(this.mark);
            break;
        case FLOAT:
            var value = readline(pickle, i);
            i += value.length + 1;
            this.stack.push(parseFloat(value));
            break;
        case BINFLOAT:
            this.stack.push(buffer.readDoubleBE(i));
            i += 8;
            break;
        case STRING:
            var value = readline(pickle, i);
            i += value.length + 1;
            var quotes = "\"'";
            if (value[0] == "'") {
                if (value[value.length-1] != "'")
                    throw "insecure string pickle";
            } else if (value[0] = '"') {
                if (value[value.length-1] != '"')
                    throw "insecure string pickle";
            } else {
                throw "insecure string pickle";
            }
            this.stack.push(value.substr(1, value.length-2));
            break;
        case BINSTRING:
            var length = buffer.readUInt32LE(i);
            i += 4;
            this.stack.push(pickle.substr(i, length));
            i += length;
            break;
        case SHORT_BINSTRING:
            var length = buffer.readUInt8(i++);
            this.stack.push(pickle.substr(i, length));
            i += length;
            break;
        case APPEND:
            var value = this.stack.pop();
            this.stack[this.stack.length-1].push(value);
            break;
        case APPENDS:
            var mark = this.marker(),
                list = this.stack[mark - 1];
            list.push.apply(list, this.stack.slice(mark + 1));
            this.stack = this.stack.slice(0, mark);
            break;
        case SETITEM:
            var value = this.stack.pop()
              , key = this.stack.pop();
            this.stack[this.stack.length-1][key] = value;
            break;
        case SETITEMS:
            var mark = this.marker()
              , obj = this.stack[mark - 1];
            for (var pos = mark + 1; pos < this.stack.length; pos += 2) {
                obj[this.stack[pos]] = this.stack[pos + 1];
            }
            this.stack = this.stack.slice(0, mark);
            break;
        case LIST:
            var mark = this.marker()
              , list = this.stack.slice(mark + 1);
            this.stack = this.stack.slice(0, mark);
            this.stack.push(list);
            break;
        case DICT:
            var mark = this.marker()
                obj = {};
            for (var pos = mark + 1; pos < this.stack.length; pos += 2) {
                obj[this.stack[pos]] = this.stack[pos + 1];
            }
            this.stack = this.stack.slice(0, mark);
            this.stack.push(obj);
            break;
        case STOP:
            return this.stack.pop();
        default:
            throw "Unhandled opcode '" + opcode + "'";
        }
    }
};

Parser.prototype.marker = function(parser) {
    var k = this.stack.length - 1
    while (k > 0 && this.stack[k] !== this.mark) {
        --k;
    }
    return k;
};

module.exports.loads = function(data) {
    var parser = new Parser();
    return parser.load(data);
};
<commit_msg>whitespace fix<commit_after>var Parser = function() {
    this.mark = 'THIS-NEEDS-TO-BE-UNIQUE-TO-SERVE-AS-A-BOUNDARY';
    this.memo = {};
    this.stack = [];
};

Parser.prototype.load = function(pickle) {
    var APPEND = 'a'            // append stack top to list below it
      , APPENDS = 'e'           // extend list on stack by topmost stack slice
      , INT = 'I'               // push integer or bool; decimal string argument
      , BININT = 'J'            // push 4-byte unsigned int
      , BININT1 = 'K'           // push 1-byte unsigned int
      , BININT2 = 'M'           // push 2-byte unsigned int
      , BINFLOAT = 'G'          // push float; arg is 8-byte float encoding
      , BINPUT = 'q'            // store stack top in memo; index is string 1-byte arg
      , BINSTRING = 'T'
      , DICT = 'd'
      , EMPTY_DICT = '}'
      , EMPTY_LIST = ']'
      , FLOAT = 'F'
      , LIST = 'l'
      , MARK = '('
      , PROTO = '\x80'
      , PUT = 'p'
      , SETITEM = 's'
      , SETITEMS = 'u'
      , SHORT_BINSTRING = 'U'
      , STOP = '.'
      , STRING = 'S';

    var buffer = new Buffer(pickle, 'binary');

    function readline(pickle, i) {
        var index = pickle.indexOf('\n', i);
        if (index == -1)
            throw "Could not find end of line";
        return pickle.substr(i, index - i);
    }

    for (var i = 0; i < pickle.length; ) {
        var opindex = i
          , opcode = pickle[i++];
        //console.log('opcode ' + opindex + ' ' + opcode);
        switch (opcode) {
        case PROTO:
            var proto = pickle.charCodeAt(i++);
            if (proto != 2)
                throw 'Unhandled pickle protocol version';
            break;
        case EMPTY_DICT:
            this.stack.push({});
            break;
        case EMPTY_LIST:
            this.stack.push([]);
            break;
        case BINPUT:
            var index = buffer.readUInt8(i++);
            this.memo['' + index] = this.stack[this.stack.length-1];
            break;
        case PUT:
            var index = readline(pickle, i);
            i += index.length + 1;
            this.memo[index] = this.stack[this.stack.length-1];
            break;
        case INT:
            var value = readline(pickle, i);
            i += value.length + 1;
            this.stack.push(parseInt(value));
            break;
        case BININT:
            this.stack.push(buffer.readUInt32LE(i));
            i += 4;
            break;
        case BININT1:
            this.stack.push(buffer.readUInt8(i));
            i += 1;
            break;
        case BININT2:
            this.stack.push(buffer.readUInt16LE(i));
            i += 2;
            break;
        case MARK:
            this.stack.push(this.mark);
            break;
        case FLOAT:
            var value = readline(pickle, i);
            i += value.length + 1;
            this.stack.push(parseFloat(value));
            break;
        case BINFLOAT:
            this.stack.push(buffer.readDoubleBE(i));
            i += 8;
            break;
        case STRING:
            var value = readline(pickle, i);
            i += value.length + 1;
            var quotes = "\"'";
            if (value[0] == "'") {
                if (value[value.length-1] != "'")
                    throw "insecure string pickle";
            } else if (value[0] = '"') {
                if (value[value.length-1] != '"')
                    throw "insecure string pickle";
            } else {
                throw "insecure string pickle";
            }
            this.stack.push(value.substr(1, value.length-2));
            break;
        case BINSTRING:
            var length = buffer.readUInt32LE(i);
            i += 4;
            this.stack.push(pickle.substr(i, length));
            i += length;
            break;
        case SHORT_BINSTRING:
            var length = buffer.readUInt8(i++);
            this.stack.push(pickle.substr(i, length));
            i += length;
            break;
        case APPEND:
            var value = this.stack.pop();
            this.stack[this.stack.length-1].push(value);
            break;
        case APPENDS:
            var mark = this.marker(),
                list = this.stack[mark - 1];
            list.push.apply(list, this.stack.slice(mark + 1));
            this.stack = this.stack.slice(0, mark);
            break;
        case SETITEM:
            var value = this.stack.pop()
              , key = this.stack.pop();
            this.stack[this.stack.length-1][key] = value;
            break;
        case SETITEMS:
            var mark = this.marker()
              , obj = this.stack[mark - 1];
            for (var pos = mark + 1; pos < this.stack.length; pos += 2) {
                obj[this.stack[pos]] = this.stack[pos + 1];
            }
            this.stack = this.stack.slice(0, mark);
            break;
        case LIST:
            var mark = this.marker()
              , list = this.stack.slice(mark + 1);
            this.stack = this.stack.slice(0, mark);
            this.stack.push(list);
            break;
        case DICT:
            var mark = this.marker()
                obj = {};
            for (var pos = mark + 1; pos < this.stack.length; pos += 2) {
                obj[this.stack[pos]] = this.stack[pos + 1];
            }
            this.stack = this.stack.slice(0, mark);
            this.stack.push(obj);
            break;
        case STOP:
            return this.stack.pop();
        default:
            throw "Unhandled opcode '" + opcode + "'";
        }
    }
};

Parser.prototype.marker = function(parser) {
    var k = this.stack.length - 1
    while (k > 0 && this.stack[k] !== this.mark) {
        --k;
    }
    return k;
};

module.exports.loads = function(data) {
    var parser = new Parser();
    return parser.load(data);
};
<|endoftext|>


<commit_before>var deps = [
  'ui.router',
  'ngAnimate',
  'colorpicker.module',
  'hljs',
  'LocalStorageModule',
  'oc.lazyLoad',
  'ngProgress',
  'rt.debounce',
  'duScroll'
];

if( window._styleguideConfig &&
  window._styleguideConfig.additionalNgDependencies &&
  window._styleguideConfig.additionalNgDependencies.length &&
  window._styleguideConfig.additionalNgDependencies.length > 0 ){
  deps = deps.concat( window._styleguideConfig.additionalNgDependencies );
  console.info('Merging dependencies: ' + deps);
}

angular.module('sgApp', deps)
  .value('duScrollOffset', 30)
  .config(function($stateProvider, $urlRouterProvider, $locationProvider, localStorageServiceProvider, $ocLazyLoadProvider) {
    var styleguideConfig = {};
    if (typeof window._styleguideConfig !== 'undefined') {
      styleguideConfig = window._styleguideConfig;
    }
    $urlRouterProvider.otherwise('/');
    $stateProvider
      .state('app', {
        template: '<ui-view />',
        controller: 'AppCtrl',
        abstract: true
      })
      .state('app.index', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .state('app.index.section', {
        url: '/section/:section',
        templateUrl: 'views/sections.html',
        controller: 'SectionsCtrl',
        resolve: {
          loadLazyModule: function($ocLazyLoad) {
            return loadModule($ocLazyLoad);
          }
        }
      })
      .state('app.index.search', {
        url: '/search/:section',
        templateUrl: 'views/sections.html',
        controller: 'SectionsCtrl',
        resolve: {
          loadLazyModule: function($ocLazyLoad) {
            return loadModule($ocLazyLoad);
          }
        }
      })
      .state('app.index.overview', {
        url: '/',
        templateUrl: 'overview.html',
        controller: function($rootScope, Styleguide) {
          $rootScope.currentSection = 'overview';
          // Update current reference to update the designer tool view
          $rootScope.currentReference.section = {
            header: 'Overview',
            reference: ''
          };

          $rootScope.$watch(function() {
            return Styleguide.config.data;
          }, function(newVal) {
            if (newVal) {
              $rootScope.pageTitle = newVal.title;
            }
          });
        }
      })
      .state('app.index.variable', {
        url: '/variable/:variableName',
        templateUrl: 'views/variable-sections.html',
        controller: 'VariablesCtrl',
        resolve: {
          loadLazyModule: function($ocLazyLoad) {
            return loadModule($ocLazyLoad);
          }
        }
      })
      .state('app.fullscreen', {
        url: '/section/:section/fullscreen',
        templateUrl: 'views/element-fullscreen.html',
        controller: 'ElementCtrl',
        resolve: {
          loadLazyModule: function($ocLazyLoad) {
            return loadModule($ocLazyLoad);
          }
        }
      }).state('app.index.404', {
        url: '/:all',
        templateUrl: 'views/404.html'
      });

    function loadModule($ocLazyLoad) {
      if (window.filesConfig && window.filesConfig.length) {
        var moduleNames = [];
        angular.forEach(window.filesConfig, function(lazyLoadmodule) {
          moduleNames.push(lazyLoadmodule.name);
        });
        return $ocLazyLoad.load(moduleNames);
      }
    }

    $locationProvider.html5Mode(!styleguideConfig.disableHtml5Mode);
    localStorageServiceProvider.setPrefix('sgLs');

    $ocLazyLoadProvider.config({
      events: true,
      debug: true,
      modules: window.filesConfig
    });
  })
  .factory('lodash', ['$window',
    function($window) {
      // Use both methods to access _ so it will work eventhough $window is mocked
      return $window._ || window._;
    }
  ])
  .run(function($rootScope, $window, lodash) {
    $rootScope.currentReference = {
      section: {
      }
    };

    // Create global throttled scorll
    function broadcastScrollEvent(event) {
      $rootScope.$broadcast('scroll', event);
    }
    // Some tests replace $window with a mock, make sure that we have real window
    if (typeof $window.addEventListener === 'function') {
      angular.element($window).bind('scroll', lodash.throttle(broadcastScrollEvent, 350));
    }
  })
  .filter('addWrapper', ['Styleguide', function(Styleguide) {
    return function(html) {
      if (Styleguide.config && Styleguide.config.data && Styleguide.config.data.commonClass) {
        return '<sg-common-class-wrapper class="' + Styleguide.config.data.commonClass + '">' + html + '</sg-common-class-wrapper>';
      }
      return html;
    };
  }])
  // Trust modifier markup to be safe html
  .filter('unsafe', ['$sce', function($sce) {
    return function(val) {
      return $sce.trustAsHtml(val);
    };
  }])
  .filter('filterRelated', function() {
    return function(variables, sectionVariableNames) {
      var filtered = [];
      angular.forEach(variables, function(variable) {
        if (sectionVariableNames && sectionVariableNames.indexOf(variable.name) > -1) {
          filtered.push(variable);
        }
      });
      return filtered;
    };
  })
  // Replaces modifier markup's {$modifiers} with modifier's modifierClass
  .filter('setModifierClass', function() {
    return function(items, modifierClass) {
      if (items) {
        items = items.replace(/\{\$modifiers\}/g, modifierClass);
      }
      return items;
    };
  })
  // Replace $variables with values found in variables object
  .filter('setVariables', ['lodash', function(_) {
    function filterFn(str, variables) {
      if (!str) {
        return '';
      }

      var sortedVariables;
      if (variables) {
        sortedVariables = variables.slice().sort(function(a, b) {
          return b.name.length - a.name.length;
        });
      }

      angular.forEach(sortedVariables, function(variable) {
        var cleanedValue = variable.value.replace(/\s*\!default$/, '');

        if (cleanedValue.match('\[\$\@]') !== null) {
          var varName = cleanedValue.substring(1);
          angular.forEach(sortedVariables, function(_var) {
            if (_var.name === varName) {
              cleanedValue = _var.value;
            }
          });
        }

        str = str.replace(new RegExp('\[\$\@]' + variable.name, 'g'), cleanedValue);
      });
      return str;
    }
    return _.memoize(filterFn);
  }]);
<commit_msg>Inject 11957animteJS on loadModules to prevent the override of the animation provider when loading a module with ngModule<commit_after>var deps = [
  'ui.router',
  'ngAnimate',
  'colorpicker.module',
  'hljs',
  'LocalStorageModule',
  'oc.lazyLoad',
  'ngProgress',
  'rt.debounce',
  'duScroll'
];

if( window._styleguideConfig &&
  window._styleguideConfig.additionalNgDependencies &&
  window._styleguideConfig.additionalNgDependencies.length &&
  window._styleguideConfig.additionalNgDependencies.length > 0 ){
  deps = deps.concat( window._styleguideConfig.additionalNgDependencies );
  console.info('Merging dependencies: ' + deps);
}

angular.module('sgApp', deps)
  .value('duScrollOffset', 30)
  .config(function($stateProvider, $urlRouterProvider, $locationProvider, localStorageServiceProvider, $ocLazyLoadProvider) {
    var styleguideConfig = {};
    if (typeof window._styleguideConfig !== 'undefined') {
      styleguideConfig = window._styleguideConfig;
    }
    $urlRouterProvider.otherwise('/');
    $stateProvider
      .state('app', {
        template: '<ui-view />',
        controller: 'AppCtrl',
        abstract: true
      })
      .state('app.index', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .state('app.index.section', {
        url: '/section/:section',
        templateUrl: 'views/sections.html',
        controller: 'SectionsCtrl',
        resolve: {
          loadLazyModule: function($$animateJs, $ocLazyLoad) {
            return loadModule($$animateJs, $ocLazyLoad);
          }
        }
      })
      .state('app.index.search', {
        url: '/search/:section',
        templateUrl: 'views/sections.html',
        controller: 'SectionsCtrl',
        resolve: {
          loadLazyModule: function($$animateJs, $ocLazyLoad) {
            return loadModule($$animateJs, $ocLazyLoad);
          }
        }
      })
      .state('app.index.overview', {
        url: '/',
        templateUrl: 'overview.html',
        controller: function($rootScope, Styleguide) {
          $rootScope.currentSection = 'overview';
          // Update current reference to update the designer tool view
          $rootScope.currentReference.section = {
            header: 'Overview',
            reference: ''
          };

          $rootScope.$watch(function() {
            return Styleguide.config.data;
          }, function(newVal) {
            if (newVal) {
              $rootScope.pageTitle = newVal.title;
            }
          });
        }
      })
      .state('app.index.variable', {
        url: '/variable/:variableName',
        templateUrl: 'views/variable-sections.html',
        controller: 'VariablesCtrl',
        resolve: {
          loadLazyModule: function($$animateJs, $ocLazyLoad) {
            return loadModule($$animateJs, $ocLazyLoad);
          }
        }
      })
      .state('app.fullscreen', {
        url: '/section/:section/fullscreen',
        templateUrl: 'views/element-fullscreen.html',
        controller: 'ElementCtrl',
        resolve: {
          loadLazyModule: function($$animateJs, $ocLazyLoad) {
            return loadModule($$animateJs, $ocLazyLoad);
          }
        }
      }).state('app.index.404', {
        url: '/:all',
        templateUrl: 'views/404.html'
      });

    function loadModule($$animateJs, $ocLazyLoad) {
      if (window.filesConfig && window.filesConfig.length) {
        var moduleNames = [];
        angular.forEach(window.filesConfig, function(lazyLoadmodule) {
          moduleNames.push(lazyLoadmodule.name);
        });
        return $ocLazyLoad.load(moduleNames);
      }
    }

    $locationProvider.html5Mode(!styleguideConfig.disableHtml5Mode);
    localStorageServiceProvider.setPrefix('sgLs');

    $ocLazyLoadProvider.config({
      events: true,
      debug: true,
      modules: window.filesConfig
    });
  })
  .factory('lodash', ['$window',
    function($window) {
      // Use both methods to access _ so it will work eventhough $window is mocked
      return $window._ || window._;
    }
  ])
  .run(function($rootScope, $window, lodash) {
    $rootScope.currentReference = {
      section: {
      }
    };

    // Create global throttled scorll
    function broadcastScrollEvent(event) {
      $rootScope.$broadcast('scroll', event);
    }
    // Some tests replace $window with a mock, make sure that we have real window
    if (typeof $window.addEventListener === 'function') {
      angular.element($window).bind('scroll', lodash.throttle(broadcastScrollEvent, 350));
    }
  })
  .filter('addWrapper', ['Styleguide', function(Styleguide) {
    return function(html) {
      if (Styleguide.config && Styleguide.config.data && Styleguide.config.data.commonClass) {
        return '<sg-common-class-wrapper class="' + Styleguide.config.data.commonClass + '">' + html + '</sg-common-class-wrapper>';
      }
      return html;
    };
  }])
  // Trust modifier markup to be safe html
  .filter('unsafe', ['$sce', function($sce) {
    return function(val) {
      return $sce.trustAsHtml(val);
    };
  }])
  .filter('filterRelated', function() {
    return function(variables, sectionVariableNames) {
      var filtered = [];
      angular.forEach(variables, function(variable) {
        if (sectionVariableNames && sectionVariableNames.indexOf(variable.name) > -1) {
          filtered.push(variable);
        }
      });
      return filtered;
    };
  })
  // Replaces modifier markup's {$modifiers} with modifier's modifierClass
  .filter('setModifierClass', function() {
    return function(items, modifierClass) {
      if (items) {
        items = items.replace(/\{\$modifiers\}/g, modifierClass);
      }
      return items;
    };
  })
  // Replace $variables with values found in variables object
  .filter('setVariables', ['lodash', function(_) {
    function filterFn(str, variables) {
      if (!str) {
        return '';
      }

      var sortedVariables;
      if (variables) {
        sortedVariables = variables.slice().sort(function(a, b) {
          return b.name.length - a.name.length;
        });
      }

      angular.forEach(sortedVariables, function(variable) {
        var cleanedValue = variable.value.replace(/\s*\!default$/, '');

        if (cleanedValue.match('\[\$\@]') !== null) {
          var varName = cleanedValue.substring(1);
          angular.forEach(sortedVariables, function(_var) {
            if (_var.name === varName) {
              cleanedValue = _var.value;
            }
          });
        }

        str = str.replace(new RegExp('\[\$\@]' + variable.name, 'g'), cleanedValue);
      });
      return str;
    }
    return _.memoize(filterFn);
  }]);
<|endoftext|>


<commit_before>//@include common.js
//@include constants.js

/*
 * Saver constructor.
 */
sp.Saver = function() { }

/**
 * Saves the active document.
 */
sp.Saver.prototype.save = function(options)
{
	if (0 == documents.length) {
		if (13 > parseFloat(app.version))
			alert('Nothing to save.');
		return [{ success: false, message: 'Nothing to save' }];
	}

	this.settings = options;

	var self         = this
	  , doc          = activeDocument
	  , name         = options.filename.replace('$name', sp.basename(doc.name)) // Don't allow filenames longer than 255 characters.
	  , destDir      = self.getDestDir(options.path)
	  , dest         = options.overwrite ? destDir + '/' + name : sp.nextFilename(destDir, name, options.outputFormats, false)
	  , beforeState  = null
	  , jpgSuffix    = null
	  , relativeDest = options.path + '/' + new File(dest).name
	  , result       = []
	  , formats      = {
			'jpg': self.getJpgSaveOptions(),
			'psd': self.getPsdSaveOptions(),
			'png': self.getPngSaveOptions(),
			'webjpg': self.getSfwSaveOptions()
		}
	;

	if (!destDir)
		return alert('Cannot save an unsaved document to a relative path.');

	self.createDirectories(destDir);

	// Remember what state we were in before resizing.
	// If we've already applied a save preset use the state before the last
	// state.
	if (doc.historyStates[doc.historyStates.length - 1].toString() == '[HistoryState ' + SP_HISTORY_STATE + ']')
		beforeState = doc.historyStates.length - 2;
	else
		beforeState = doc.historyStates.length - 1;

	var f = function() {
		var formatOptions, formatDest;

		self.applyAction(doc, options.action);

		for (format in options.outputFormats) {
			formatOptions = formats[format];
			formatDest    = dest;
			jpgSuffix     = '';

			if (options.outputFormats[format]) {
				// Do we save two jpegs? Then add a suffix to the save for web file.
				if ('webjpg' == format && options.outputFormats['jpg'])
					jpgSuffix = '_web';

				formatDest = dest + jpgSuffix + '.' + formatOptions.extension;

				self.saveFile(formatOptions, formatDest);

				result.push({ success: true, message: relativeDest + jpgSuffix + '.' + formatOptions.extension });
			}
		}
	}

	doc.suspendHistory(SP_HISTORY_STATE, 'f()');

	// Restore the state.
	doc.activeHistoryState = doc.historyStates[beforeState];

	if (options.close)
		doc.close(SaveOptions.DONOTSAVECHANGES);

	return result;
}

sp.Saver.prototype.saveFile = function(format, dest)
{
	if ('ExportOptionsSaveForWeb' == format.typename)
		activeDocument.exportDocument(new File(dest), ExportType.SAVEFORWEB, format);
	else
		activeDocument.saveAs(new File(dest), format, true, Extension.LOWERCASE);
}

sp.Saver.prototype.getDestDir = function(targetPath)
{
	var basePath;

	try {
		if ('psd' == sp.extension(activeDocument.fullName.name))
			basePath = this.getOriginalDir(activeDocument.path);
		else
			basePath = activeDocument.path;
	} catch (e) {
		if (sp.isRelative(targetPath))
			return false;
	}

	if (sp.isRelative(targetPath) && '/' != basePath)
		return basePath + '/' + targetPath;
	else
		return targetPath;
}

/**
 * Try to work out the directory of the original file.
 *
 * Looks through all presets and see if any of the directory patterns match the
 * location of the current document. If we get a match, we traverse back and
 * return the resulting directory.
 */
sp.Saver.prototype.getOriginalDir = function()
{
	var docDir = null;

	try {
		docDir = new Folder(activeDocument.path);
	} catch (e) {
		return false;
	}

	var root     = docDir
	  , presets  = sp.loadPresets()
	  , traverse = 0
	;

	for (i in presets) {
		if(!sp.isRelative(presets[i].path))
			continue;

		var presetDirs = presets[i].path.split(/[\/\\]/);
		var realDirs = docDir.fullName.split(/[\/\\]/);

		if ('.' === presetDirs[0])
			presetDirs = presetDirs.splice(1);

		realDirs.splice(0, realDirs.length - presetDirs.length);

		if (sp.arraysEqual(presetDirs, realDirs)) {
			traverse = presetDirs.length;
			break;
		}
	}

	for (i = 0; i < traverse; i++)
		root = root.parent;

	return root;
}

sp.Saver.prototype.applyAction = function(doc, action)
{
	if (SP_NOACTION == action.type)
		return;
	else if (SP_RESIZETOFIT == action.type)
		this.resizeToFit(doc, action.args[0], action.args[1]);
	else if (SP_CUSTOMACTION == action.type)
		this.applyCustomAction(doc, action.args[0], action.args[1]);
}

sp.Saver.prototype.applyCustomAction = function(doc, set, action)
{
	var tmp        = activeDocument;
	activeDocument = doc;
	app.doAction(action, set);
	activeDocument = tmp;
}

sp.Saver.prototype.resizeToFit = function(doc, width, height)
{
	var docWidth, docHeight, scale, tmpHeight, rulerUnits;

	// Temporary set units to pixels.
	rulerUnits = preferences.rulerUnits;
	preferences.rulerUnits = Units.PIXELS;

	docWidth  = parseFloat(doc.width);
	docHeight = parseFloat(doc.height);
	scale     = null;
	newWidth  = null;
	newHeight = null;

	// Is scaling needed?
	if (docWidth <= width && docHeight <= height)
		return;

	doc.flatten();

	// Get scale to fit width.
	if (docWidth > width)
		scale = width / docWidth;

	tmpHeight = Math.round(scale * docHeight);

	// Get scale to fit height.
	if (tmpHeight > height)
		scale *= (height / tmpHeight);

	newWidth  = scale * docWidth;
	newHeight = scale * docHeight;

	doc.resizeImage(newWidth, newHeight, null, preferences.interpolation);

	// Restore ruler units.
	preferences.rulerUnits = rulerUnits;
}

sp.Saver.prototype.createDirectories = function(path)
{
	var dirs, current;

	dirs = path.split(/[\/\\]/);

	// Take care of network paths on Windows beginning with a double-slash.
	if ('' == dirs[0] && '' == dirs[1]) {
        dirs[2] = '/' + dirs[2];
        dirs.shift();
        dirs.shift();
	}

	current = new Folder('/' + dirs[0]);

	for (i = 1; i < dirs.length; i++) {
		current = new Folder(current.fullName + '/' + dirs[parseInt(i)]);
		if (!current.exists)
			current.create();
	}
}

sp.Saver.prototype.getJpgSaveOptions = function()
{
	var	options = new JPEGSaveOptions();
	options.embedColorProfile = true;
	options.formatOptions = FormatOptions.STANDARDBASELINE;

	options.matte = MatteType.NONE;
	options.quality = this.settings.jpegQuality;
	options.quality = 11;
	options.extension = 'jpg';
	return options;
}

sp.Saver.prototype.getPngSaveOptions = function()
{
	options = new PNGSaveOptions();
	options.interlaced = false;
	options.compression = 5;
	options.extension = 'png';
	return options;
}

sp.Saver.prototype.getPsdSaveOptions = function()
{
	var options = new PhotoshopSaveOptions();
	options.layers = true;
	options.embedColorProfile = true;
	options.annotations = true;
	options.alphaChannels = true;
	options.spotColors = true;
	options.extension = 'psd';
	return options;
}

sp.Saver.prototype.getSfwSaveOptions = function()
{
	var options = new ExportOptionsSaveForWeb();
	options.format = SaveDocumentType.JPEG;
	options.includeProfile = true;
	options.quality = parseInt(this.settings.jpegQuality / 12 * 100);
	options.extension = 'jpg';
	return options;
}

//presets = sp.loadPresets();
//for (i in presets) {
	//if ('Desktop' == presets[i].name)
		//preset = presets[i];
//}

//preset = {
	//name: 'full',
	//path: 'jpeg/full',
	////outputFormats: { jpg: true, psd: true, png: true, webjpg: false },
	//outputFormats: { jpg: true, psd: false, png: false, webjpg: false },
	//jpegQuality: 11,
	//overwrite: false,
	//filename: '$name',
	//close: false,
	//action: {
		////type: SP_RESIZETOFIT,
		////type: SP_CUSTOMACTION,
		//type: SP_NOACTION,
		////args: [920, 2000]
		//args: ['Reimund', 'Look 1']
	//},
//}

//var s = new sp.Saver();
//s.save(preset);
<commit_msg>Get original directory if file resides in a directory named 'full'.<commit_after>//@include common.js
//@include constants.js

/*
 * Saver constructor.
 */
sp.Saver = function() { }

/**
 * Saves the active document.
 */
sp.Saver.prototype.save = function(options)
{
	if (0 == documents.length) {
		if (13 > parseFloat(app.version))
			alert('Nothing to save.');
		return [{ success: false, message: 'Nothing to save' }];
	}

	this.settings = options;

	var self         = this
	  , doc          = activeDocument
	  , name         = options.filename.replace('$name', sp.basename(doc.name)) // Don't allow filenames longer than 255 characters.
	  , destDir      = self.getDestDir(options.path)
	  , dest         = options.overwrite ? destDir + '/' + name : sp.nextFilename(destDir, name, options.outputFormats, false)
	  , beforeState  = null
	  , jpgSuffix    = null
	  , relativeDest = options.path + '/' + new File(dest).name
	  , result       = []
	  , formats      = {
			'jpg': self.getJpgSaveOptions(),
			'psd': self.getPsdSaveOptions(),
			'png': self.getPngSaveOptions(),
			'webjpg': self.getSfwSaveOptions()
		}
	;

	if (!destDir)
		return alert('Cannot save an unsaved document to a relative path.');

	self.createDirectories(destDir);

	// Remember what state we were in before resizing.
	// If we've already applied a save preset use the state before the last
	// state.
	if (doc.historyStates[doc.historyStates.length - 1].toString() == '[HistoryState ' + SP_HISTORY_STATE + ']')
		beforeState = doc.historyStates.length - 2;
	else
		beforeState = doc.historyStates.length - 1;

	var f = function() {
		var formatOptions, formatDest;

		self.applyAction(doc, options.action);

		for (format in options.outputFormats) {
			formatOptions = formats[format];
			formatDest    = dest;
			jpgSuffix     = '';

			if (options.outputFormats[format]) {
				// Do we save two jpegs? Then add a suffix to the save for web file.
				if ('webjpg' == format && options.outputFormats['jpg'])
					jpgSuffix = '_web';

				formatDest = dest + jpgSuffix + '.' + formatOptions.extension;

				self.saveFile(formatOptions, formatDest);

				result.push({ success: true, message: relativeDest + jpgSuffix + '.' + formatOptions.extension });
			}
		}
	}

	doc.suspendHistory(SP_HISTORY_STATE, 'f()');

	// Restore the state.
	doc.activeHistoryState = doc.historyStates[beforeState];

	if (options.close)
		doc.close(SaveOptions.DONOTSAVECHANGES);

	return result;
}

sp.Saver.prototype.saveFile = function(format, dest)
{
	if ('ExportOptionsSaveForWeb' == format.typename)
		activeDocument.exportDocument(new File(dest), ExportType.SAVEFORWEB, format);
	else
		activeDocument.saveAs(new File(dest), format, true, Extension.LOWERCASE);
}

sp.Saver.prototype.getDestDir = function(targetPath)
{
	var basePath;

	try {
		// XXX: Let the user decide this with an option in the preset.
		if ('psd' === sp.extension(activeDocument.fullName.name) || 'full' === activeDocument.fullName.parent.name)
			basePath = this.getOriginalDir(activeDocument.path);
		else
			basePath = activeDocument.path;
	} catch (e) {
		if (sp.isRelative(targetPath))
			return false;
	}

	if (sp.isRelative(targetPath) && '/' != basePath)
		return basePath + '/' + targetPath;
	else
		return targetPath;
}

/**
 * Try to work out the directory of the original file.
 *
 * Looks through all presets and see if any of the directory patterns match the
 * location of the current document. If we get a match, we traverse back and
 * return the resulting directory.
 */
sp.Saver.prototype.getOriginalDir = function()
{
	var docDir = null;

	try {
		docDir = new Folder(activeDocument.path);
	} catch (e) {
		return false;
	}

	var root     = docDir
	  , presets  = sp.loadPresets()
	  , traverse = 0
	;

	for (i in presets) {
		if(!sp.isRelative(presets[i].path))
			continue;

		var presetDirs = presets[i].path.split(/[\/\\]/);
		var realDirs = docDir.fullName.split(/[\/\\]/);

		if ('.' === presetDirs[0])
			presetDirs = presetDirs.splice(1);

		realDirs.splice(0, realDirs.length - presetDirs.length);

		if (sp.arraysEqual(presetDirs, realDirs)) {
			traverse = presetDirs.length;
			break;
		}
	}

	for (i = 0; i < traverse; i++)
		root = root.parent;

	return root;
}

sp.Saver.prototype.applyAction = function(doc, action)
{
	if (SP_NOACTION == action.type)
		return;
	else if (SP_RESIZETOFIT == action.type)
		this.resizeToFit(doc, action.args[0], action.args[1]);
	else if (SP_CUSTOMACTION == action.type)
		this.applyCustomAction(doc, action.args[0], action.args[1]);
}

sp.Saver.prototype.applyCustomAction = function(doc, set, action)
{
	var tmp        = activeDocument;
	activeDocument = doc;
	app.doAction(action, set);
	activeDocument = tmp;
}

sp.Saver.prototype.resizeToFit = function(doc, width, height)
{
	var docWidth, docHeight, scale, tmpHeight, rulerUnits;

	// Temporary set units to pixels.
	rulerUnits = preferences.rulerUnits;
	preferences.rulerUnits = Units.PIXELS;

	docWidth  = parseFloat(doc.width);
	docHeight = parseFloat(doc.height);
	scale     = null;
	newWidth  = null;
	newHeight = null;

	// Is scaling needed?
	if (docWidth <= width && docHeight <= height)
		return;

	doc.flatten();

	// Get scale to fit width.
	if (docWidth > width)
		scale = width / docWidth;

	tmpHeight = Math.round(scale * docHeight);

	// Get scale to fit height.
	if (tmpHeight > height)
		scale *= (height / tmpHeight);

	newWidth  = scale * docWidth;
	newHeight = scale * docHeight;

	doc.resizeImage(newWidth, newHeight, null, preferences.interpolation);

	// Restore ruler units.
	preferences.rulerUnits = rulerUnits;
}

sp.Saver.prototype.createDirectories = function(path)
{
	var dirs, current;

	dirs = path.split(/[\/\\]/);

	// Take care of network paths on Windows beginning with a double-slash.
	if ('' == dirs[0] && '' == dirs[1]) {
        dirs[2] = '/' + dirs[2];
        dirs.shift();
        dirs.shift();
	}

	current = new Folder('/' + dirs[0]);

	for (i = 1; i < dirs.length; i++) {
		current = new Folder(current.fullName + '/' + dirs[parseInt(i)]);
		if (!current.exists)
			current.create();
	}
}

sp.Saver.prototype.getJpgSaveOptions = function()
{
	var	options = new JPEGSaveOptions();
	options.embedColorProfile = true;
	options.formatOptions = FormatOptions.STANDARDBASELINE;

	options.matte = MatteType.NONE;
	options.quality = this.settings.jpegQuality;
	options.quality = 11;
	options.extension = 'jpg';
	return options;
}

sp.Saver.prototype.getPngSaveOptions = function()
{
	options = new PNGSaveOptions();
	options.interlaced = false;
	options.compression = 5;
	options.extension = 'png';
	return options;
}

sp.Saver.prototype.getPsdSaveOptions = function()
{
	var options = new PhotoshopSaveOptions();
	options.layers = true;
	options.embedColorProfile = true;
	options.annotations = true;
	options.alphaChannels = true;
	options.spotColors = true;
	options.extension = 'psd';
	return options;
}

sp.Saver.prototype.getSfwSaveOptions = function()
{
	var options = new ExportOptionsSaveForWeb();
	options.format = SaveDocumentType.JPEG;
	options.includeProfile = true;
	options.quality = parseInt(this.settings.jpegQuality / 12 * 100);
	options.extension = 'jpg';
	return options;
}

//presets = sp.loadPresets();
//for (i in presets) {
	//if ('Desktop' == presets[i].name)
		//preset = presets[i];
//}

//preset = {
	//name: 'full',
	//path: 'jpeg/full',
	////outputFormats: { jpg: true, psd: true, png: true, webjpg: false },
	//outputFormats: { jpg: true, psd: false, png: false, webjpg: false },
	//jpegQuality: 11,
	//overwrite: false,
	//filename: '$name',
	//close: false,
	//action: {
		////type: SP_RESIZETOFIT,
		////type: SP_CUSTOMACTION,
		//type: SP_NOACTION,
		////args: [920, 2000]
		//args: ['Reimund', 'Look 1']
	//},
//}

//var s = new sp.Saver();
//s.save(preset);
<|endoftext|>


<commit_before>var GridRemoteDataSource = require("../../models/gridRemoteDataSource");
var GridLocalDataSource = require("../../models/gridLocalDataSource");
var apiBuilder = require("../../models/api/ApiGridBuilder");

function gridDataSourceFac(data) {
    return data.url ? new GridRemoteDataSource(data) : new GridLocalDataSource(data);
}

function GridViewModel(params) {
    params = params || {};
    var self = this;
    this.name = ko.observable(params.name);
    this.identityProp = ko.observable(params.identityProp)
    this.onRefresh = new ko.subscribable();

    this.onRefreshCallback = function (data) {
        this.onRefresh.notifySubscribers(data);
    }
    this.isMultiSelect = ko.observable(params.isMultiSelect);

    this.rowDoubleClickAction = params.rowDoubleClickAction || params.defaultAction || function () { };

    this.collumns = ko.observableArray(params.collumns);

    this.dataSource = ko.observable(gridDataSourceFac({ url: params.url, dataSet: params.data, defaultAction: params.defaulAction, onRefresh: this.onRefreshCallback.bind(this) }));

    this.selectedRows = ko.observableArray([]);
    //TODO: selected rows on current page
    this.totalPages = ko.computed(function () {
        return this.dataSource().gridRequest().totalPages();
    }, this);

    this.currentPage = ko.computed(function () {
        return this.dataSource().gridRequest().currentPage();
    }, this);

    this.dataSourceDescription = ko.computed(function () {
        var firstIndexInPage = (this.dataSource().gridRequest().currentPage() - 1) * this.dataSource().gridRequest().pageLength()+1;
        var lastIndexInPage = (firstIndexInPage + this.dataSource().gridRequest().data().length-1);
        return "Mostrando de " + firstIndexInPage + " para " + lastIndexInPage + ". Total: " + this.dataSource().gridRequest().totalData() + " itens";
    }, this);

    this.checkAll = ko.computed({
        read: function () {
            return this.selectedRows().length === this.dataSource().dataSet().length;
        },
        write: function (value) {
            if (value) {
                self.selectedRows.removeAll();
                this.dataSource().dataSet().forEach(function (item) {
                    self.selectedRows.push(item['id'] || item['Id']);
                });
            } else {
                this.selectedRows.removeAll();
            }
        },
        owner: this
    });

    params.gridAPI && ko.isObservable(params.gridAPI) ? params.gridAPI(apiBuilder(this)) : params.gridAPI = apiBuilder(this);

    this.dataSource().refresh();
};

GridViewModel.prototype._getDataValue = function (data, prop) {
    var splited = prop.split('.');
    var value = data[splited[0]];
    if (splited.length > 1)
        return this._getDataValue(value, splited.slice(1).join('.'))
    return value;
};
GridViewModel.prototype.defaultAction = function (rowObject) {
    this.defaulActionCallback && this.defaulActionCallback(rowObject[this.identityProp()] || rowObject["id"] || rowObject["Id"]);
}

GridViewModel.prototype.refresh = function () {
    this.dataSource().refresh();
}
GridViewModel.prototype.filter = function (filter) {
    this.dataSource().refresh(filter);
}

GridViewModel.prototype.goToPage = function (pageNumber) {
    this.dataSource().goto(pageNumber);
};

GridViewModel.prototype.next = function () {
    this.dataSource().next();
};

GridViewModel.prototype.prev = function () {
    this.dataSource().prev();
};

module.exports = GridViewModel;<commit_msg>correcao select all<commit_after>var GridRemoteDataSource = require("../../models/gridRemoteDataSource");
var GridLocalDataSource = require("../../models/gridLocalDataSource");
var apiBuilder = require("../../models/api/ApiGridBuilder");

function gridDataSourceFac(data) {
    return data.url ? new GridRemoteDataSource(data) : new GridLocalDataSource(data);
}

function GridViewModel(params) {
    params = params || {};
    var self = this;
    this.name = ko.observable(params.name);
    this.identityProp = ko.observable(params.identityProp)
    this.onRefresh = new ko.subscribable();

    this.onRefreshCallback = function (data) {
        this.onRefresh.notifySubscribers(data);
    }
    this.isMultiSelect = ko.observable(params.isMultiSelect);

    this.rowDoubleClickAction = params.rowDoubleClickAction || params.defaultAction || function () { };

    this.collumns = ko.observableArray(params.collumns);

    this.dataSource = ko.observable(gridDataSourceFac({ url: params.url, dataSet: params.data, defaultAction: params.defaulAction, onRefresh: this.onRefreshCallback.bind(this) }));

    this.selectedRows = ko.observableArray([]);
    //TODO: selected rows on current page
    this.totalPages = ko.computed(function () {
        return this.dataSource().gridRequest().totalPages();
    }, this);

    this.currentPage = ko.computed(function () {
        return this.dataSource().gridRequest().currentPage();
    }, this);

    this.dataSourceDescription = ko.computed(function () {
        var firstIndexInPage = (this.dataSource().gridRequest().currentPage() - 1) * this.dataSource().gridRequest().pageLength()+1;
        var lastIndexInPage = (firstIndexInPage + this.dataSource().gridRequest().data().length-1);
        return "Mostrando de " + firstIndexInPage + " para " + lastIndexInPage + ". Total: " + this.dataSource().gridRequest().totalData() + " itens";
    }, this);

    this.checkAll = ko.computed({
        read: function () {
            return this.selectedRows().length === this.dataSource().dataSet().length;
        },
        write: function (value) {
            if (value) {
                self.selectedRows.removeAll();
                this.dataSource().dataSet().forEach(function (item) {
                    self.selectedRows.push(item[this.identityProp()] || item['id'] || item['Id']);
                });
            } else {
                this.selectedRows.removeAll();
            }
        },
        owner: this
    });

    params.gridAPI && ko.isObservable(params.gridAPI) ? params.gridAPI(apiBuilder(this)) : params.gridAPI = apiBuilder(this);

    this.dataSource().refresh();
};

GridViewModel.prototype._getDataValue = function (data, prop) {
    var splited = prop.split('.');
    var value = data[splited[0]];
    if (splited.length > 1)
        return this._getDataValue(value, splited.slice(1).join('.'))
    return value;
};
<<<<<<< Updated upstream
=======

GridViewModel.prototype._getAggregate = function (data) {
    if (data.aggregate)
        return this.dataSource().getAggregate({ column: data.prop, aggregate: data.aggregate });
};

>>>>>>> Stashed changes
GridViewModel.prototype.defaultAction = function (rowObject) {
    this.defaulActionCallback && this.defaulActionCallback(rowObject[this.identityProp()] || rowObject["id"] || rowObject["Id"]);
}

GridViewModel.prototype.refresh = function () {
    this.dataSource().refresh();
}
GridViewModel.prototype.filter = function (filter) {
    this.dataSource().refresh(filter);
}

GridViewModel.prototype.goToPage = function (pageNumber) {
    this.dataSource().goto(pageNumber);
};

GridViewModel.prototype.next = function () {
    this.dataSource().next();
};

GridViewModel.prototype.prev = function () {
    this.dataSource().prev();
};

module.exports = GridViewModel;<|endoftext|>


<commit_before>import './jkReactMarkdown.css'
import 'highlight.js/styles/default.css'

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import Panel from './components/Panel'
import Buttons from './libs/Buttons'
import getNewText from './libs/getNewText'
import buttonsDetector from './libs/buttonsDetector'
import ReactMarkdown from 'react-markdown'
import hljs from 'highlight.js'

hljs.configure({
  languages: ['javascript', 'python', 'php']
})

const {
  getButtonByName,
  getList,
  getTypes
} = new Buttons()

class JkReactMarkdown extends Component {
  static propTypes = {
    className: PropTypes.string,
    cols: PropTypes.string,
    rows: PropTypes.string,
    value: PropTypes.string,
    onChange: PropTypes.func,
    styles: PropTypes.object,
    buttons: PropTypes.array
  }

  state = {
    selectionStart: 0,
    selectionEnd: 0,
    showResult: false,
    textArr: this.props.value.split(/[\r\n]/),
    selectionButtons: []
  }

  componentDidUpdate (prevProps, prevState) {
    console.log(this.state.showResult)
    console.log(prevState.showResult)
    if (this.state.showResult && !prevState.showResult) {
      this.highlightCode()
    }
  }

  componentWillReceiveProps (newProps) {
    if (this.props.value !== newProps.value) {
      this.setState({
        textArr: newProps.value.split(/[\r\n]/)
      })
    }
  }

  highlightCode () {
    const domNode = ReactDOM.findDOMNode(this)
    const nodes = domNode.querySelectorAll('pre code')
    for (let i = 0; i < nodes.length; i++) {
      hljs.highlightBlock(nodes[i])
    }
  }

  onClickButton = (name) => {
    if (name === 'showResult') {
      this.setState({showResult: !this.state.showResult})
      return
    }

    if (this.state.showResult) return

    let newText = getNewText({
      button: getButtonByName(name),
      text: this.props.value,
      textArr: this.state.textArr,
      selectionStart: this.state.selectionStart,
      selectionEnd: this.state.selectionEnd,
      selectionButtons: this.state.selectionButtons,
      getButtonByName: getButtonByName,
      types: getTypes()
    })

    this.props.onChange(newText)
  }

  onChange = (e) => {
    this.props.onChange(e.target.value)
  }

  onSelect = (e) => {
    let selectionButtons = buttonsDetector({
      text: this.props.value,
      textArr: this.state.textArr,
      selectionStart: e.target.selectionStart,
      selectionEnd: e.target.selectionEnd,
      list: getList(),
      types: getTypes()
    })
    this.setState({
      selectionStart: e.target.selectionStart,
      selectionEnd: e.target.selectionEnd,
      selectionButtons: selectionButtons
    })
  }

  render () {
    let { styles } = this.props
    styles = styles || {}
    let cols = this.props.cols ? this.props.cols : '30'
    let rows = this.props.rows ? this.props.rows : '5'
    let styleEditor = styles.editor || {}
    let styleResult = styles.result || {}
    let editor = (
      <textarea
        cols={ cols }
        rows={ rows }
        style={ styleEditor }
        className={ this.props.className || 'JkReactMarkdown__textarea' }
        value={ this.props.value }
        onChange={ this.onChange }
        onSelect={ this.onSelect }></textarea>
    )
    let result = (

        <ReactMarkdown source={ this.props.value } />

    )

    return (

        <Panel
          onClick={ this.onClickButton }
          style={ this.props.styles }
          showResult={ this.state.showResult }
          selectionButtons={ this.state.selectionButtons }
          list={ getList(this.props.buttons) }
        />
        { this.state.showResult ? result : editor }

    )
  }
}

export default JkReactMarkdown
<commit_msg>- console.log<commit_after>import './jkReactMarkdown.css'
import 'highlight.js/styles/default.css'

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import Panel from './components/Panel'
import Buttons from './libs/Buttons'
import getNewText from './libs/getNewText'
import buttonsDetector from './libs/buttonsDetector'
import ReactMarkdown from 'react-markdown'
import hljs from 'highlight.js'

hljs.configure({
  languages: ['javascript', 'python', 'php']
})

const {
  getButtonByName,
  getList,
  getTypes
} = new Buttons()

class JkReactMarkdown extends Component {
  static propTypes = {
    className: PropTypes.string,
    cols: PropTypes.string,
    rows: PropTypes.string,
    value: PropTypes.string,
    onChange: PropTypes.func,
    styles: PropTypes.object,
    buttons: PropTypes.array
  }

  state = {
    selectionStart: 0,
    selectionEnd: 0,
    showResult: false,
    textArr: this.props.value.split(/[\r\n]/),
    selectionButtons: []
  }

  componentDidUpdate (prevProps, prevState) {
    if (this.state.showResult && !prevState.showResult) {
      this.highlightCode()
    }
  }

  componentWillReceiveProps (newProps) {
    if (this.props.value !== newProps.value) {
      this.setState({
        textArr: newProps.value.split(/[\r\n]/)
      })
    }
  }

  highlightCode () {
    const domNode = ReactDOM.findDOMNode(this)
    const nodes = domNode.querySelectorAll('pre code')
    for (let i = 0; i < nodes.length; i++) {
      hljs.highlightBlock(nodes[i])
    }
  }

  onClickButton = (name) => {
    if (name === 'showResult') {
      this.setState({showResult: !this.state.showResult})
      return
    }

    if (this.state.showResult) return

    let newText = getNewText({
      button: getButtonByName(name),
      text: this.props.value,
      textArr: this.state.textArr,
      selectionStart: this.state.selectionStart,
      selectionEnd: this.state.selectionEnd,
      selectionButtons: this.state.selectionButtons,
      getButtonByName: getButtonByName,
      types: getTypes()
    })

    this.props.onChange(newText)
  }

  onChange = (e) => {
    this.props.onChange(e.target.value)
  }

  onSelect = (e) => {
    let selectionButtons = buttonsDetector({
      text: this.props.value,
      textArr: this.state.textArr,
      selectionStart: e.target.selectionStart,
      selectionEnd: e.target.selectionEnd,
      list: getList(),
      types: getTypes()
    })
    this.setState({
      selectionStart: e.target.selectionStart,
      selectionEnd: e.target.selectionEnd,
      selectionButtons: selectionButtons
    })
  }

  render () {
    let { styles } = this.props
    styles = styles || {}
    let cols = this.props.cols ? this.props.cols : '30'
    let rows = this.props.rows ? this.props.rows : '5'
    let styleEditor = styles.editor || {}
    let styleResult = styles.result || {}
    let editor = (
      <textarea
        cols={ cols }
        rows={ rows }
        style={ styleEditor }
        className={ this.props.className || 'JkReactMarkdown__textarea' }
        value={ this.props.value }
        onChange={ this.onChange }
        onSelect={ this.onSelect }></textarea>
    )
    let result = (

        <ReactMarkdown source={ this.props.value } />

    )

    return (

        <Panel
          onClick={ this.onClickButton }
          style={ this.props.styles }
          showResult={ this.state.showResult }
          selectionButtons={ this.state.selectionButtons }
          list={ getList(this.props.buttons) }
        />
        { this.state.showResult ? result : editor }

    )
  }
}

export default JkReactMarkdown
<|endoftext|>


<commit_before>/*!
 * string_score.js: String Scoring Algorithm 0.1.10
 *
 * http://joshaven.com/string_score
 * https://github.com/joshaven/string_score
 *
 * Copyright (C) 2009-2011 Joshaven Potter <yourtech@gmail.com>
 * Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
 * MIT license: http://www.opensource.org/licenses/mit-license.php
 *
 * Date: Tue Mar 1 2011
*/

/**
 * Scores a string against another string.
 *  'Hello World'.score('he');     //=> 0.5931818181818181
 *  'Hello World'.score('Hello');  //=> 0.7318181818181818
 */
String.prototype.score = function(abbreviation, fuzziness) {
  // If the string is equal to the abbreviation, perfect match.
  if (this == abbreviation) {return 1;}
  //if it's not a perfect match and is empty return 0
  if(abbreviation == "") {return 0;}

  var total_character_score = 0,
      abbreviation_length = abbreviation.length,
      string = this,
      string_length = string.length,
      start_of_string_bonus,
      abbreviation_score,
      fuzzies=1,
      final_score;

  // Walk through abbreviation and add up scores.
  for (var i = 0,
         character_score/* = 0*/,
         index_in_string/* = 0*/,
         c/* = ''*/,
         index_c_lowercase/* = 0*/,
         index_c_uppercase/* = 0*/,
         min_index/* = 0*/;
     i < abbreviation_length;
     ++i) {

    // Find the first case-insensitive match of a character.
    c = abbreviation[i];

    //index_in_string = __first_valid_index(
    //    string.indexOf(c.toLowerCase()),
    //    string.indexOf(c.toUpperCase())
    //);
    // Inlined the above call below.
    index_c_lowercase = string.indexOf(c.toLowerCase());
    index_c_uppercase = string.indexOf(c.toUpperCase());
    min_index = Math.min(index_c_lowercase, index_c_uppercase);
    index_in_string = (min_index > -1) ?
        min_index :
        Math.max(index_c_lowercase, index_c_uppercase);
    // End inlining.

    if (index_in_string === -1) {
      if (fuzziness) {
        fuzzies += 1-fuzziness;
        continue;
      } else {
        return 0;
      }
    } else {
      character_score = 0.1;
    }

    // Set base score for matching 'c'.

    // Same case bonus.
    if (string[index_in_string] === c) {
      character_score += 0.1;
    }

    // Consecutive letter & start-of-string Bonus
    if (index_in_string === 0) {
      // Increase the score when matching first character of the
      // remainder of the string
      character_score += 0.6;
      if (i === 0) {
        // If match is the first character of the string
        // & the first character of abbreviation, add a
        // start-of-string match bonus.
        start_of_string_bonus = 1 //true;
      }
    }
    else {
	// Acronym Bonus
	// Weighing Logic: Typing the first character of an acronym is as if you
	// preceded it with two perfect character matches.
	if (string.charAt(index_in_string - 1) === ' ') {
	character_score += 0.8; // * Math.min(index_in_string, 5); // Cap bonus at 0.4 * 5
	}
    }

    // Left trim the already matched part of the string
    // (forces sequential matching).
    string = string.substring(index_in_string + 1, string_length);

    total_character_score += character_score;
  } // end of for loop

  // Uncomment to weigh smaller words higher.
  // return total_character_score / string_length;

  abbreviation_score = total_character_score / abbreviation_length;
  //percentage_of_matched_string = abbreviation_length / string_length;
  //word_score = abbreviation_score * percentage_of_matched_string;

  // Reduce penalty for longer strings.
  //final_score = (word_score + abbreviation_score) / 2;
  final_score = ((abbreviation_score * (abbreviation_length / string_length)) + abbreviation_score) / 2;

  final_score = final_score / fuzzies;

  if (start_of_string_bonus && (final_score + 0.15 < 1)) {
    final_score += 0.15;
  }

  return final_score;
};
<commit_msg>Cleanup the code, no real changes<commit_after>/*!
 * string_score.js: String Scoring Algorithm 0.1.10
 *
 * http://joshaven.com/string_score
 * https://github.com/joshaven/string_score
 *
 * Copyright (C) 2009-2011 Joshaven Potter <yourtech@gmail.com>
 * Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
 * MIT license: http://www.opensource.org/licenses/mit-license.php
 *
 * Date: Tue Mar 1 2011
*/

/**
 * Scores a string against another string.
 *  'Hello World'.score('he');     //=> 0.5931818181818181
 *  'Hello World'.score('Hello');  //=> 0.7318181818181818
 */
String.prototype.score = function(abbreviation, fuzziness) {
  // If the string is equal to the abbreviation, perfect match.
  if (this == abbreviation) {return 1;}
  //if it's not a perfect match and is empty return 0
  if(abbreviation == "") {return 0;}

  var total_character_score = 0,
      abbreviation_length = abbreviation.length,
      string = this,
      string_length = string.length,
      start_of_string_bonus,
      abbreviation_score,
      fuzzies=1,
      final_score;

  // Walk through abbreviation and add up scores.
  for (var i = 0,
         character_score/* = 0*/,
         index_in_string/* = 0*/,
         c/* = ''*/,
         index_c_lowercase/* = 0*/,
         index_c_uppercase/* = 0*/,
         min_index/* = 0*/;
     i < abbreviation_length;
     ++i) {

    // Find the first case-insensitive match of a character.
    c = abbreviation[i];

    index_c_lowercase = string.indexOf(c.toLowerCase());
    index_c_uppercase = string.indexOf(c.toUpperCase());
    min_index = Math.min(index_c_lowercase, index_c_uppercase);
    index_in_string = (min_index > -1) ? min_index : Math.max(index_c_lowercase, index_c_uppercase);

    if (index_in_string === -1) {
      if (fuzziness) {
        fuzzies += 1-fuzziness;
        continue;
      } else {
        return 0;
      }
    } else {
      character_score = 0.1;
    }

    // Set base score for matching 'c'.

    // Same case bonus.
    if (string[index_in_string] === c) {
      character_score += 0.1;
    }

    // Consecutive letter & start-of-string Bonus
    if (index_in_string === 0) {
      // Increase the score when matching first character of the remainder of the string
      character_score += 0.6;
      if (i === 0) {
        // If match is the first character of the string
        // & the first character of abbreviation, add a
        // start-of-string match bonus.
        start_of_string_bonus = 1 //true;
      }
    }
    else {
  // Acronym Bonus
  // Weighing Logic: Typing the first character of an acronym is as if you
  // preceded it with two perfect character matches.
  if (string.charAt(index_in_string - 1) === ' ') {
    character_score += 0.8; // * Math.min(index_in_string, 5); // Cap bonus at 0.4 * 5
  }
    }

    // Left trim the already matched part of the string
    // (forces sequential matching).
    string = string.substring(index_in_string + 1, string_length);

    total_character_score += character_score;
  } // end of for loop

  // Uncomment to weigh smaller words higher.
  // return total_character_score / string_length;

  abbreviation_score = total_character_score / abbreviation_length;
  //percentage_of_matched_string = abbreviation_length / string_length;
  //word_score = abbreviation_score * percentage_of_matched_string;

  // Reduce penalty for longer strings.
  //final_score = (word_score + abbreviation_score) / 2;
  final_score = ((abbreviation_score * (abbreviation_length / string_length)) + abbreviation_score) / 2;

  final_score = final_score / fuzzies;

  if (start_of_string_bonus && (final_score + 0.15 < 1)) {
    final_score += 0.15;
  }

  return final_score;
};
<|endoftext|>