<commit_before>const DefaultFileIcons = require('./default-file-icons')
const {Emitter, CompositeDisposable} = require('atom')
const {repoForPath} = require('./helpers')

let iconServices
module.exports = function getIconServices () {
  if (!iconServices) iconServices = new IconServices()
  return iconServices
}

class IconServices {
  constructor () {
    this.emitter = new Emitter()
    this.elementIcons = null
    this.elementIconDisposables = new CompositeDisposable()
    this.fileIcons = DefaultFileIcons
  }

  onDidChange (callback) {
    return this.emitter.on('did-change', callback)
  }

  resetElementIcons () {
    this.setElementIcons(null)
  }

  resetFileIcons () {
    this.setFileIcons(DefaultFileIcons)
  }

  setElementIcons (service) {
    if (service !== this.elementIcons) {
      if (this.elementIconDisposables != null) {
        this.elementIconDisposables.dispose()
      }
      if (service) {
        this.elementIconDisposables = new CompositeDisposable()
      }
      this.elementIcons = service
      this.emitter.emit('did-change')
    }
  }

  setFileIcons (service) {
    if (service !== this.fileIcons) {
      this.fileIcons = service
      this.emitter.emit('did-change')
    }
  }

  updateDirectoryIcon (view) {
    if (this.elementIcons) {
      const disposable = this.elementIcons(view.directoryName, view.directory.path)
      this.elementIconDisposables.add(disposable)
    } else {
      let iconClass
      if (view.directory.symlink) {
        iconClass = 'icon-file-symlink-directory'
      } else {
        iconClass = 'icon-file-directory'
        if (view.directory.isRoot) {
          const repo = repoForPath(view.directory.path)
          if (repo && repo.isProjectAtRoot()) iconClass = 'icon-repo'
        } else {
          if (view.directory.submodule) iconClass = 'icon-file-submodule'
        }
      }
      view.directoryName.classList.add(iconClass)
    }
  }

  updateFileIcon (view) {
    const classes = ['name', 'icon']
    let iconClass
    if (this.elementIcons) {
      const disposable = this.elementIcons(view.fileName, view.file.path)
      this.elementIconDisposables.add(disposable)
    } else {
      iconClass = this.fileIcons.iconClassForPath(view.file.path, 'tree-view')
    }
    if (iconClass) {
      if (!Array.isArray(iconClass)) {
        iconClass = iconClass.toString().split(/\s+/g)
      } classes.push(...iconClass)
    }
    view.fileName.classList.add(...classes)
  }
}
<commit_msg>Reset icon classes before updating them<commit_after>const DefaultFileIcons = require('./default-file-icons')
const {Emitter, CompositeDisposable} = require('atom')
const {repoForPath} = require('./helpers')

let iconServices
module.exports = function getIconServices () {
  if (!iconServices) iconServices = new IconServices()
  return iconServices
}

class IconServices {
  constructor () {
    this.emitter = new Emitter()
    this.elementIcons = null
    this.elementIconDisposables = new CompositeDisposable()
    this.fileIcons = DefaultFileIcons
  }

  onDidChange (callback) {
    return this.emitter.on('did-change', callback)
  }

  resetElementIcons () {
    this.setElementIcons(null)
  }

  resetFileIcons () {
    this.setFileIcons(DefaultFileIcons)
  }

  setElementIcons (service) {
    if (service !== this.elementIcons) {
      if (this.elementIconDisposables != null) {
        this.elementIconDisposables.dispose()
      }
      if (service) {
        this.elementIconDisposables = new CompositeDisposable()
      }
      this.elementIcons = service
      this.emitter.emit('did-change')
    }
  }

  setFileIcons (service) {
    if (service !== this.fileIcons) {
      this.fileIcons = service
      this.emitter.emit('did-change')
    }
  }

  updateDirectoryIcon (view) {
    view.directoryName.className = ''

    const classes = ['name', 'icon']
    if (this.elementIcons) {
      const disposable = this.elementIcons(view.directoryName, view.directory.path)
      this.elementIconDisposables.add(disposable)
    } else {
      let iconClass
      if (view.directory.symlink) {
        iconClass = 'icon-file-symlink-directory'
      } else {
        iconClass = 'icon-file-directory'
        if (view.directory.isRoot) {
          const repo = repoForPath(view.directory.path)
          if (repo && repo.isProjectAtRoot()) iconClass = 'icon-repo'
        } else {
          if (view.directory.submodule) iconClass = 'icon-file-submodule'
        }
      }
      classes.push(iconClass)
      view.directoryName.classList.add(...classes)
    }
  }

  updateFileIcon (view) {
    view.fileName.className = ''

    const classes = ['name', 'icon']
    let iconClass
    if (this.elementIcons) {
      const disposable = this.elementIcons(view.fileName, view.file.path)
      this.elementIconDisposables.add(disposable)
    } else {
      iconClass = this.fileIcons.iconClassForPath(view.file.path, 'tree-view')
    }
    if (iconClass) {
      if (!Array.isArray(iconClass)) {
        iconClass = iconClass.toString().split(/\s+/g)
      }
      classes.push(...iconClass)
    }
    view.fileName.classList.add(...classes)
  }
}
<|endoftext|>


<commit_before>function setupParser() {
    // prepare *Marked* (a Markdown parser) library; see https://github.com/chjj/marked
    marked.setOptions({
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: true,
        smartLists: true,
        smartypants: false,
    });
}

function translateFragments() {
    var fg = $("#fragment-group");

    // highlight any search keyword contained in fragment titles;
    fg.find(".fragment-title").each(function() {
        var $this = $(this);
        $this.html(translateSearchKeywordCommands($this.html()));
    });

    // translate Markdown formatted fragment contents into HTML format
    fg.find(".fragment-content").each(function() {
        var $this = $(this);
        var text = $this.text();
        $this.html(translateFragmentContent(text));
        $this.find(".-cvz-tag, .-cvz-file").each(function() {
            var $t = $(this);
            $t.text(removeSearchKeywordCommands($t.text()));
        });
        if ($this.hasClass("fp-search")) {
            // Highlight search keywords
            $this.find("*").each(function() {
               var elem = $(this), attrs = this.attributes;
               // Remove any of search keyword markups from HTML attributes
               for (var i=0; i<attrs.length; ++i) {
                   var attr = attrs[i];
                   attr.value = removeSearchKeywordCommands(attr.value);
                   elem.attr(attr.name, attr.value);
               }
            });
            // Translate search keyword markups
            $this.html(translateSearchKeywordCommands($this.html()));
        }
        postprocessFragmentContent($this);
    });

    // add a tooltip message of updated and created time
    fg.find(".fragment-header .fa-clock-o, .fragment-header .fa-birthday-cake").each(function() {
        var $this = $(this);
        $this[0].title = formatDatetime($this.prev("span").text());
    });

    fg.find(".each-tag").each(function() {
        formatTagsOnFragmentHeader($(this));
    });

    // set click handler for every folding in fragments and fragment overlay
    $("body").off("click.fold_toggle").on("click.fold_toggle", ".-cvz-fold-handle", function(e) {
        var $this = $(this);
        $this.find(".fold-toggle-icon").toggleClass("fa-plus-square fa-minus-square");
        showOrHide($this.next(".-cvz-fold"));
        e.preventDefault();
    });
}

function populateFragmentOverlay(data) {
    // show the fragment overlay as a popup
    var overlayFrame = $("#fragment-overlay");
    overlayFrame.lightbox_me({
        centered:false
        , showOverlay:false
        , lightboxSpeed:"fast"
        , closeSelector:"#fragment-overlay-close-button"
        , closeEsc:true
        , modalCSS:{ position:"fixed", bottom: '34px', right: '4px' }
    });

    var titleBar = $("#fragment-overlay-title-bar");
    if (titleBar.next().is(":visible") == false) {
        toggleWindow(overlayFrame, titleBar);
    }

    $("#fragment-overlay-title").text("");

    // Set up a link to the previous fragment if any.
    var overlayContent = $("#fragment-overlay-content");
    var prevHdr = overlayContent.find(".fragment-header");
    var backBtn = $("#fragment-overlay-back-button");
    if (prevHdr.length > 0) {
        backBtn.show().attr("href", "fragment/"+prevHdr.attr("_fid"))
            .addClass("-cvz-frgm");
    }
    else {
        backBtn.hide();
    }
    var resizeBtn = $("#fragment-overlay-resize-button");

    if (! overlayFrame.data("initialized")) {
        resizeBtn.off("click.fragment_overlay").on("click.fragment_overlay", function(e) {
            overlayContent.toggleClass("normal-size large-size");
            $(this).find("span").toggleClass("fa-expand fa-compress");
        });
        overlayFrame.data("initialized", true);
    }

    overlayContent.html(data);

    $("#fragment-overlay-content .fragment-header .fa-clock-o, #fragment-overlay-content .fragment-header .fa-birthday-cake")
    .each(function() {
        var $this = $(this);
        $this[0].title = formatDatetime($this.prev("span").text());
    });

    // translate Markdown formatted fragment contents into HTML format
    overlayContent.find(".fragment-content").each(function(){
        var $this = $(this);
        $this.html(translateFragmentContent($this.text()));
        postprocessFragmentContent($this);
    });

    // make titles on the overlay window also draggable/droppable
    setupDndForFragments(true);
    setupDndForTags(true);

    setContextMenuForFragments();

    setContextMenuForTags();

    overlayContent.find(".each-tag").each(function() {formatTagsOnFragmentHeader($(this))});

    setupRelatedFragments();
}

const SEARCH_KEYWORD_PATTERN_BEGIN = /%28%7B%28%5B(.+?)%5D%20/g;
const SEARCH_KEYWORD_PATTERN_END = /%20%29%7D%29/g;

function translateSearchKeywordCommands(html) {
    return html
        // ({([keyword] ... text ... )}) --- translated to a ;
        // used for one special purpose; highlighting search phrase
        .replace(SEARCH_KEYWORD_PATTERN_BEGIN, function(match, p1, pos, originalText) {
            return "";
        })
        .replace(SEARCH_KEYWORD_PATTERN_END, function(match, pos, originalText) {
            return "";
        })
        ;
}

function removeSearchKeywordCommands(html) {
    return html
        .replace(SEARCH_KEYWORD_PATTERN_BEGIN, function(match, p1, pos, originalText) {
            return "";
        })
        .replace(SEARCH_KEYWORD_PATTERN_END, function(match, pos, originalText) {
            return "";
        })
        ;
}

function translateCustomMarkupCommands(html) {
    return html
    // {{{[keyword] ... text ... }}} --- translated to a
 block
    .replace(/\{\{\{\[(.+?)({.*})?\]\s?/g, function(match, p1, p2, pos, originalText) {
        var output = "
";
    })
    .replace(/\s?\}\}\}/g, function(match, pos, originalText) {
        return "
";
    })
    // {{[keyword] ... text ... }} --- translated to a
    .replace(/\{\{\[([^,]+?)\]\s?/g, function(match, p1, pos, originalText) {
        return "";
    })
    .replace(/\s?\}\}/g, function(match, pos, originalText) {
        return "";
    })
    .replace(/((&#125;){2,3})/g, function(match, p1) {
        var output = "";
        for (var i=0,c=p1.length; i<c; ++i) {
            if (p1[i] === "&") output += "}";
        }
        return output;
    })
    ;
}

function translateFragmentContent(content) {
    // translate Markdown text into HTML;
    var outputHtml = parseMarkdown(content);

    // take care of custom markup commands
    return translateCustomMarkupCommands(outputHtml);
}

function setupFragmentLinks(content) {
    content.find("span.-cvz-frgm").each(function() {
        var $this = $(this);
        var txt = $this.text();
        var patt = /\s*(\d+)\s+(.*)/g;
        if (txt.match(patt)) {
            var newTag = $("" + RegExp.$2 + "");
            $this.replaceWith(newTag);
        }
    });
}

function processFoldings(content) {
    content.find(".-cvz-fold").each(function() {
        var $this = $(this), args = parseJsonArgs($this);

        // search keyword commands may touch folding parameters.
        // when that happens, we need to restore original key names;
        for (var k in args) {
            var v = args[k];
            k = removeSearchKeywordCommands(k);
            args[k] = v;
        }

        $this.wrapInner("
");
        var handle = $("");
        var icon = $("");
        if (args.title) {
            handle.append($(""+args.title+""));
        }
        if (args.hide == "true") {
            handle.click();
            // with the only above code, the target element would be hidden.
            // but it doesn't work on Safari, so make sure it becomes hidden.
            $this.hide();
        }
        $this.before(handle.prepend(icon));
    });
}

function processEmbeddedFragments(content) {
    content.find(".-cvz-frgm-embed").each(function() {
        var $this = $(this);
        $.get("fragment/"+$this.text().trim(), "", function(data) {
            var content = $(data).find(".fragment-content").text();
            $this.html(translateFragmentContent(content));
            postprocessFragmentContent($this);
        });
    })
}

function unsanitizeHtml(content) {
    content.find(".-cvz-html").each(function() {
        var $this = $(this);
        var res = $this.text()
            .replace(/<(\/?)(.+)>/g, function(match, cg1, cg2, pos, originalText) {
//                var cg1 = RegExp.$1;
//                var cg2 = RegExp.$2;
                if (cg2.indexOf("html") == 0
                   || cg2.indexOf("head") == 0
                   || cg2.indexOf("body") == 0
                   || cg2.indexOf("link") == 0
                   || cg2.indexOf("script") == 0
                   )
                    // these tags should be sanitized for safety
                    return "<"+cg1+cg2+"&gt";
                return match;
            });
        $this.text(null).html(res);
    });
}

function embedYoutubeVideo(content) {
    $("#fragment-group").off("click.ytv").on("click.ytv", ".yt-video", function() {
        var $this = $(this),
            iframe = $("");
        $this.replaceWith(iframe);
        return false;
    });

    content.find("iframe[src*='www.youtube.com/embed/'], a[href*='youtu.be/'], a[href*='www.youtube.com/watch?']")
    .each(function() {
        var $this = $(this), videoId;
        if ($this.is("iframe"))
            videoId = suffix($this.attr("src"), "/", true);
        else if ($this.is("a[href*='youtu.be/']"))
            videoId = suffix($this.attr("href"), "/", true);
        else if ($this.is("a[href*='www.youtube.com/watch?']"))
            videoId = inbetween($this.attr("href"), "v=", "&")
                || suffix($this.attr("href"), "v=", true);
        var div = $("
" +
            '

');
        $this.replaceWith(div);
    });
}

function postprocessFragmentContent(content) {
    // translate foldings
    // Rule - {{{[fold]...}}}
    processFoldings(content);

    // translate embedded fragemnts
    // Rule - {{[frgm-embed]...}}
    processEmbeddedFragments(content);

    // translate fragemnt links
    // Rule - {{[frgm]...}}
    setupFragmentLinks(content);

    // translate tag links
    // Rule - {{[tag]...}}
    setupTagLinks(content);

    // convert links to images into  tags
    content.find("a").each(function() {
        var $this = $(this);
        var href = $this.attr("href");
        if (isImage(suffix(href, ".")))
            $this.replaceWith("");
    });

    // translate file box elements into HTML links
    // Rule - {{[file]...}}
    processFileClasses(content);

    // unsanitize HTML code if any
    // Rule - {{[html]...}}
    unsanitizeHtml(content);

    embedYoutubeVideo(content);
}
<commit_msg>[bug fix] JS const keyword caused a trouble in older browsers<commit_after>function setupParser() {
    // prepare *Marked* (a Markdown parser) library; see https://github.com/chjj/marked
    marked.setOptions({
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: true,
        smartLists: true,
        smartypants: false,
    });
}

function translateFragments() {
    var fg = $("#fragment-group");

    // highlight any search keyword contained in fragment titles;
    fg.find(".fragment-title").each(function() {
        var $this = $(this);
        $this.html(translateSearchKeywordCommands($this.html()));
    });

    // translate Markdown formatted fragment contents into HTML format
    fg.find(".fragment-content").each(function() {
        var $this = $(this);
        var text = $this.text();
        $this.html(translateFragmentContent(text));
        $this.find(".-cvz-tag, .-cvz-file").each(function() {
            var $t = $(this);
            $t.text(removeSearchKeywordCommands($t.text()));
        });
        if ($this.hasClass("fp-search")) {
            // Highlight search keywords
            $this.find("*").each(function() {
               var elem = $(this), attrs = this.attributes;
               // Remove any of search keyword markups from HTML attributes
               for (var i=0; i<attrs.length; ++i) {
                   var attr = attrs[i];
                   attr.value = removeSearchKeywordCommands(attr.value);
                   elem.attr(attr.name, attr.value);
               }
            });
            // Translate search keyword markups
            $this.html(translateSearchKeywordCommands($this.html()));
        }
        postprocessFragmentContent($this);
    });

    // add a tooltip message of updated and created time
    fg.find(".fragment-header .fa-clock-o, .fragment-header .fa-birthday-cake").each(function() {
        var $this = $(this);
        $this[0].title = formatDatetime($this.prev("span").text());
    });

    fg.find(".each-tag").each(function() {
        formatTagsOnFragmentHeader($(this));
    });

    // set click handler for every folding in fragments and fragment overlay
    $("body").off("click.fold_toggle").on("click.fold_toggle", ".-cvz-fold-handle", function(e) {
        var $this = $(this);
        $this.find(".fold-toggle-icon").toggleClass("fa-plus-square fa-minus-square");
        showOrHide($this.next(".-cvz-fold"));
        e.preventDefault();
    });
}

function populateFragmentOverlay(data) {
    // show the fragment overlay as a popup
    var overlayFrame = $("#fragment-overlay");
    overlayFrame.lightbox_me({
        centered:false
        , showOverlay:false
        , lightboxSpeed:"fast"
        , closeSelector:"#fragment-overlay-close-button"
        , closeEsc:true
        , modalCSS:{ position:"fixed", bottom: '34px', right: '4px' }
    });

    var titleBar = $("#fragment-overlay-title-bar");
    if (titleBar.next().is(":visible") == false) {
        toggleWindow(overlayFrame, titleBar);
    }

    $("#fragment-overlay-title").text("");

    // Set up a link to the previous fragment if any.
    var overlayContent = $("#fragment-overlay-content");
    var prevHdr = overlayContent.find(".fragment-header");
    var backBtn = $("#fragment-overlay-back-button");
    if (prevHdr.length > 0) {
        backBtn.show().attr("href", "fragment/"+prevHdr.attr("_fid"))
            .addClass("-cvz-frgm");
    }
    else {
        backBtn.hide();
    }
    var resizeBtn = $("#fragment-overlay-resize-button");

    if (! overlayFrame.data("initialized")) {
        resizeBtn.off("click.fragment_overlay").on("click.fragment_overlay", function(e) {
            overlayContent.toggleClass("normal-size large-size");
            $(this).find("span").toggleClass("fa-expand fa-compress");
        });
        overlayFrame.data("initialized", true);
    }

    overlayContent.html(data);

    $("#fragment-overlay-content .fragment-header .fa-clock-o, #fragment-overlay-content .fragment-header .fa-birthday-cake")
    .each(function() {
        var $this = $(this);
        $this[0].title = formatDatetime($this.prev("span").text());
    });

    // translate Markdown formatted fragment contents into HTML format
    overlayContent.find(".fragment-content").each(function(){
        var $this = $(this);
        $this.html(translateFragmentContent($this.text()));
        postprocessFragmentContent($this);
    });

    // make titles on the overlay window also draggable/droppable
    setupDndForFragments(true);
    setupDndForTags(true);

    setContextMenuForFragments();

    setContextMenuForTags();

    overlayContent.find(".each-tag").each(function() {formatTagsOnFragmentHeader($(this))});

    setupRelatedFragments();
}

var SEARCH_KEYWORD_PATTERN_BEGIN = /%28%7B%28%5B(.+?)%5D%20/g;
var SEARCH_KEYWORD_PATTERN_END = /%20%29%7D%29/g;

function translateSearchKeywordCommands(html) {
    return html
        // ({([keyword] ... text ... )}) --- translated to a ;
        // used for one special purpose; highlighting search phrase
        .replace(SEARCH_KEYWORD_PATTERN_BEGIN, function(match, p1, pos, originalText) {
            return "";
        })
        .replace(SEARCH_KEYWORD_PATTERN_END, function(match, pos, originalText) {
            return "";
        })
        ;
}

function removeSearchKeywordCommands(html) {
    return html
        .replace(SEARCH_KEYWORD_PATTERN_BEGIN, function(match, p1, pos, originalText) {
            return "";
        })
        .replace(SEARCH_KEYWORD_PATTERN_END, function(match, pos, originalText) {
            return "";
        })
        ;
}

function translateCustomMarkupCommands(html) {
    return html
    // {{{[keyword] ... text ... }}} --- translated to a
 block
    .replace(/\{\{\{\[(.+?)({.*})?\]\s?/g, function(match, p1, p2, pos, originalText) {
        var output = "
";
    })
    .replace(/\s?\}\}\}/g, function(match, pos, originalText) {
        return "
";
    })
    // {{[keyword] ... text ... }} --- translated to a
    .replace(/\{\{\[([^,]+?)\]\s?/g, function(match, p1, pos, originalText) {
        return "";
    })
    .replace(/\s?\}\}/g, function(match, pos, originalText) {
        return "";
    })
    .replace(/((&#125;){2,3})/g, function(match, p1) {
        var output = "";
        for (var i=0,c=p1.length; i<c; ++i) {
            if (p1[i] === "&") output += "}";
        }
        return output;
    })
    ;
}

function translateFragmentContent(content) {
    // translate Markdown text into HTML;
    var outputHtml = parseMarkdown(content);

    // take care of custom markup commands
    return translateCustomMarkupCommands(outputHtml);
}

function setupFragmentLinks(content) {
    content.find("span.-cvz-frgm").each(function() {
        var $this = $(this);
        var txt = $this.text();
        var patt = /\s*(\d+)\s+(.*)/g;
        if (txt.match(patt)) {
            var newTag = $("" + RegExp.$2 + "");
            $this.replaceWith(newTag);
        }
    });
}

function processFoldings(content) {
    content.find(".-cvz-fold").each(function() {
        var $this = $(this), args = parseJsonArgs($this);

        // search keyword commands may touch folding parameters.
        // when that happens, we need to restore original key names;
        for (var k in args) {
            var v = args[k];
            k = removeSearchKeywordCommands(k);
            args[k] = v;
        }

        $this.wrapInner("
");
        var handle = $("");
        var icon = $("");
        if (args.title) {
            handle.append($(""+args.title+""));
        }
        if (args.hide == "true") {
            handle.click();
            // with the only above code, the target element would be hidden.
            // but it doesn't work on Safari, so make sure it becomes hidden.
            $this.hide();
        }
        $this.before(handle.prepend(icon));
    });
}

function processEmbeddedFragments(content) {
    content.find(".-cvz-frgm-embed").each(function() {
        var $this = $(this);
        $.get("fragment/"+$this.text().trim(), "", function(data) {
            var content = $(data).find(".fragment-content").text();
            $this.html(translateFragmentContent(content));
            postprocessFragmentContent($this);
        });
    })
}

function unsanitizeHtml(content) {
    content.find(".-cvz-html").each(function() {
        var $this = $(this);
        var res = $this.text()
            .replace(/<(\/?)(.+)>/g, function(match, cg1, cg2, pos, originalText) {
//                var cg1 = RegExp.$1;
//                var cg2 = RegExp.$2;
                if (cg2.indexOf("html") == 0
                   || cg2.indexOf("head") == 0
                   || cg2.indexOf("body") == 0
                   || cg2.indexOf("link") == 0
                   || cg2.indexOf("script") == 0
                   )
                    // these tags should be sanitized for safety
                    return "<"+cg1+cg2+"&gt";
                return match;
            });
        $this.text(null).html(res);
    });
}

function embedYoutubeVideo(content) {
    $("#fragment-group").off("click.ytv").on("click.ytv", ".yt-video", function() {
        var $this = $(this),
            iframe = $("");
        $this.replaceWith(iframe);
        return false;
    });

    content.find("iframe[src*='www.youtube.com/embed/'], a[href*='youtu.be/'], a[href*='www.youtube.com/watch?']")
    .each(function() {
        var $this = $(this), videoId;
        if ($this.is("iframe"))
            videoId = suffix($this.attr("src"), "/", true);
        else if ($this.is("a[href*='youtu.be/']"))
            videoId = suffix($this.attr("href"), "/", true);
        else if ($this.is("a[href*='www.youtube.com/watch?']"))
            videoId = inbetween($this.attr("href"), "v=", "&")
                || suffix($this.attr("href"), "v=", true);
        var div = $("
" +
            '

');
        $this.replaceWith(div);
    });
}

function postprocessFragmentContent(content) {
    // translate foldings
    // Rule - {{{[fold]...}}}
    processFoldings(content);

    // translate embedded fragemnts
    // Rule - {{[frgm-embed]...}}
    processEmbeddedFragments(content);

    // translate fragemnt links
    // Rule - {{[frgm]...}}
    setupFragmentLinks(content);

    // translate tag links
    // Rule - {{[tag]...}}
    setupTagLinks(content);

    // convert links to images into  tags
    content.find("a").each(function() {
        var $this = $(this);
        var href = $this.attr("href");
        if (isImage(suffix(href, ".")))
            $this.replaceWith("");
    });

    // translate file box elements into HTML links
    // Rule - {{[file]...}}
    processFileClasses(content);

    // unsanitize HTML code if any
    // Rule - {{[html]...}}
    unsanitizeHtml(content);

    embedYoutubeVideo(content);
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var errors = require('./errors');

function RelayHandler(channel) {
    var self = this;
    self.channel = channel;
}

RelayHandler.prototype.type = 'tchannel.relay-handler';

RelayHandler.prototype.handleRequest = function handleRequest(req, buildRes) {
    var self = this;
    // TODO: frame-at-a-time rather than re-streaming?

    var outres = null;
    var outreq = self.channel.request({
        streamed: req.streamed,
        ttl: req.ttl,
        service: req.service,
        headers: req.headers,
        retryFlags: req.retryFlags
    });

    outreq.on('response', onResponse);
    outreq.on('error', onError);
    if (outreq.streamed) {
        req.arg1.pipe(outreq.arg1);
        req.arg2.pipe(outreq.arg2);
        req.arg3.pipe(outreq.arg3);
    } else {
        outreq.send(req.arg1, req.arg2, req.arg3);
    }
    return outreq;

    function onResponse(res) {
        if (outres) {
            return;
        }
        outres = buildRes({
            streamed: res.streamed,
            code: res.code
        });
        if (outres.streamed) {
            outres.arg1.end();
            res.arg2.pipe(outres.arg2);
            res.arg3.pipe(outres.arg3);
        } else {
            outres.send(res.arg2, res.arg3);
        }
    }

    function onError(err) {
        if (outres) {
            return;
        }
        outres = buildRes();
        var codeName = errors.classify(err);
        if (codeName) {
            outres.sendError(codeName, err.message);
        } else {
            outres.sendError('UnexpectedError', err.message);
            self.channel.logger.error('unexpected error while forwarding', {
                error: err
                // TODO context
            });
        }

        // TODO: stat in some cases, e.g. declined / peer not available
    }
};

module.exports = RelayHandler;
<commit_msg>Factor RelayRequest out of RelayHandler<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var errors = require('./errors');

function RelayRequest(channel, inreq, buildRes) {
    var self = this;
    self.channel = channel;
    self.inreq = inreq;
    self.inres = null;
    self.outres = null;
    self.outreq = null;
    self.buildRes = buildRes;
}

RelayRequest.prototype.createOutRequest = function createOutRequest() {
    var self = this;

    self.outreq = self.channel.request({
        streamed: self.inreq.streamed,
        ttl: self.inreq.ttl,
        service: self.inreq.service,
        headers: self.inreq.headers,
        retryFlags: self.inreq.retryFlags
    });
    self.outreq.on('response', onResponse);
    self.outreq.on('error', onError);

    if (self.outreq.streamed) {
        // TODO: frame-at-a-time rather than re-streaming?
        self.inreq.arg1.pipe(self.outreq.arg1);
        self.inreq.arg2.pipe(self.outreq.arg2);
        self.inreq.arg3.pipe(self.outreq.arg3);
    } else {
        self.outreq.send(self.inreq.arg1, self.inreq.arg2, self.inreq.arg3);
    }

    return self.outreq;

    function onResponse(res) {
        self.onResponse(res);
    }

    function onError(err) {
        self.onError(err);
    }
};

RelayRequest.prototype.createOutResponse = function createOutResponse(options) {
    var self = this;
    if (self.outres) {
        return;
    }
    self.outres = self.buildRes(options);
    return self.outres;
};

RelayRequest.prototype.onResponse = function onResponse(res) {
    var self = this;

    self.inres = res;

    if (!self.createOutResponse({
        streamed: self.inres.streamed,
        code: self.inres.code
    })) return;

    if (self.outres.streamed) {
        self.outres.arg1.end();
        self.inres.arg2.pipe(self.outres.arg2);
        self.inres.arg3.pipe(self.outres.arg3);
    } else {
        self.outres.send(self.inres.arg2, self.inres.arg3);
    }
};

RelayRequest.prototype.onError = function onError(err) {
    var self = this;
    if (!self.createOutResponse()) return;
    var codeName = errors.classify(err);
    if (codeName) {
        self.outres.sendError(codeName, err.message);
    } else {
        self.outres.sendError('UnexpectedError', err.message);
        self.channel.logger.error('unexpected error while forwarding', {
            error: err
            // TODO context
        });
    }

    // TODO: stat in some cases, e.g. declined / peer not available
};

function RelayHandler(channel) {
    var self = this;
    self.channel = channel;
}

RelayHandler.prototype.type = 'tchannel.relay-handler';

RelayHandler.prototype.handleRequest = function handleRequest(req, buildRes) {
    var self = this;
    var rereq = new RelayRequest(self.channel, req, buildRes);
    rereq.createOutRequest();
};

module.exports = RelayHandler;
<|endoftext|>


<commit_before>'use strict';

var log = require('anyfetch-provider').log;
var logError = require('anyfetch-provider').util.logError;
var request = require('supertest');
var async = require('async');

module.exports = function upload(serviceData, queues, cb) {
  var apiUrl = "https://api.box.com/2.0/";
  var url = "/events?" + 'stream_position=';
  url += !serviceData.next_stream_position ? 'now' : serviceData.next_stream_position;

  async.waterfall([
    function getEvents(cb) {
      request(apiUrl)
        .get(url)
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set('Authorization', 'Bearer ' + serviceData.access_token)
        .expect(200)
        .end(cb);
    },
    function handleMetada(metadata, cb) {
      if(serviceData.next_stream_position) {
        // handling deleted items
        var deletedFilesId = metadata.body.entries.filter(function(item) {
          return item.event_type === 'ITEM_TRASH' && item.source.type === 'file';
        }).map(function(item) {
          return {identifier: item.source.id};
        });
        deletedFilesId.forEach(function(item) {
          queues.deletion.push(item);
        });
      }
      serviceData.next_stream_position = metadata.body.next_stream_position;
      cb(null);
    }
  ], function(err) {
    if(err) {
      log.error(err);
      logError(err);
      return cb(err);
    }
    cb();
  });
};
<commit_msg>Adding comments<commit_after>'use strict';

var log = require('anyfetch-provider').log;
var logError = require('anyfetch-provider').util.logError;
var request = require('supertest');
var async = require('async');

module.exports = function upload(serviceData, queues, cb) {
  var apiUrl = "https://api.box.com/2.0/";
  var url = "/events?" + 'stream_position=';
  url += !serviceData.next_stream_position ? 'now' : serviceData.next_stream_position;

  async.waterfall([
    function getEvents(cb) {
      request(apiUrl)
        .get(url)
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set('Authorization', 'Bearer ' + serviceData.access_token)
        .expect(200)
        .end(cb);
    },
    function handleMetada(metadata, cb) {
      // if this is the first call, just store the new stream position
      if(serviceData.next_stream_position) {
        // handling deleted items
        var deletedFilesId = metadata.body.entries.filter(function(item) {
          return item.event_type === 'ITEM_TRASH' && item.source.type === 'file';
        }).map(function(item) {
          return {identifier: item.source.id};
        });
        deletedFilesId.forEach(function(item) {
          queues.deletion.push(item);
        });
      }
      serviceData.next_stream_position = metadata.body.next_stream_position;
      cb(null);
    }
  ], function(err) {
    if(err) {
      log.error(err);
      logError(err);
      return cb(err);
    }
    cb();
  });
};
<|endoftext|>


<commit_before>/* Web to Plex - Toloka Plugin
 * Aurthor(s) - @chmez (2017)
 */

// REQUIRED [var plugin:object]: The plugin variable, must be a variable
var plugin = {
    // REQUIRED [plugin.url]: this is what you ask Web to Plex access to; currently limited to a single domain
    url: "https://toloka.to/t*",

    // OPTIONAL: this is purely for your code functionality
    getID: () => {
        let links = document.querySelectorAll('.postlink'),
            regex = /^https?\:\/\/(?:w{3}\.)?imdb\.com\/title\/(tt\d+)/i;

        for(let link in links)
            if(regex.test(links[link]))
                return RegExp.$1;
    },

    // REQUIRED [plugin.init]: this is what Web to Plex will call on when the url is detected
    // it will always be fired after the page and Web to Plex have been loaded
    init: (IMDbID) => {
        let title = document.querySelector('.maintitle').textContent.replace(/^[^\/]+\/\s+([^\(]+)\(([\d]{4})/, '$1').trim(),
                // REQUIRED [title:string]
            year = RegExp.$2,
                // PREFERRED [year:number, null, undefined]
            image = document.querySelector('.postbody img').src;
                // OPTIONAL [image:string]

        // REQUIRED [{ type:'movie', 'show'; title:string; year:number; target:'web-to-plex' }]
        // PREFERRED [{ image:string; IMDbID:string; TMDbID:string, number; TVDbID:string, number }]
        window.postMessage({ type: 'movie', title, year, image, IMDbID, target: 'web-to-plex' }, '*');
    }
};

// the rest of the code is up to you, but should be limited to a layout similar to this
var id = plugin.getID();

if(id)
    plugin.init(id);
<commit_msg>Update toloka.js<commit_after>/* Web to Plex - Toloka Plugin
 * Aurthor(s) - @chmez (2017)
 */

// REQUIRED [var plugin:object]: The plugin constant, must be a constant
const plugin = {
    // REQUIRED [plugin.url]: this is what you ask Web to Plex access to; currently limited to a single domain
    url: "https://toloka.to/t*",

    // OPTIONAL: this is purely for your code functionality
    getID: () => {
        let links = document.querySelectorAll('.postlink'),
            regex = /^https?\:\/\/(?:w{3}\.)?imdb\.com\/title\/(tt\d+)/i;

        for(let link in links)
            if(regex.test(links[link]))
                return RegExp.$1;
    },

    // REQUIRED [plugin.init]: this is what Web to Plex will call on when the url is detected
    // it will always be fired after the page and Web to Plex have been loaded
    init: (IMDbID) => {
        let title = document.querySelector('.maintitle').textContent.replace(/^[^\/]+\/\s+([^\(]+)\(([\d]{4})/, '$1').trim(),
                // REQUIRED [title:string]
            year = RegExp.$2,
                // PREFERRED [year:number, null, undefined]
            image = document.querySelector('.postbody img').src;
                // OPTIONAL [image:string]

        // REQUIRED [{ type:'movie', 'show'; title:string; year:number; target:'web-to-plex' }]
        // PREFERRED [{ image:string; IMDbID:string; TMDbID:string, number; TVDbID:string, number }]
        window.postMessage({ type: 'movie', title, year, image, IMDbID, target: 'web-to-plex' }, '*');
    }
};

// the rest of the code is up to you, but should be limited to a layout similar to this
let id = plugin.getID();

if(id)
    plugin.init(id);
<|endoftext|>


<commit_before>var init = require('../init/init');
var docs = require('../docs/docs');
var exec = require('child_process').exec;
var Promise = require('bluebird');
var clc = require('cli-color');
var Handlebars = require('handlebars');
var fs = require('fs');
var path = require('path');

var corePackages = require('../pkg/pex-packages-core');
var contribPackages = require('../pkg/pex-packages-contrib');

//just run the command no matter what
function execP(cmd) {
  return function() {
    return new Promise(function(resolve, reject) {
      exec(cmd,
        function (err, stdout, stderr) {
          console.log(err || stdout || stderr);
          resolve(err || stdout || stderr);
      });
    })
  }
}

function logP(msg) {
  return function() {
    console.log(clc.cyan(msg));
    return Promise.resolve(true);
  }
}

function installPexPackages() {
  return Promise.all(corePackages.map(function(pkg) {
    return execP('cd pex-homepage/temp; npm install ' + pkg.name)();
  }))
}

function getExamplesList() {
  return fs.readdirSync('pex-homepage/examples');
}

function getPackageInfo(pkg) {
  var classes = [];
  var version = '0.0.0';
  var homepage = '';
  try {
    var pkgDocsPath = 'pex-homepage/docs/' + pkg.name + '';
    console.log(pkgDocsPath)
    if (fs.existsSync(pkgDocsPath)) {
      classes = fs.readdirSync(pkgDocsPath);
      classes = classes.filter(function(classFile) {
        return path.extname(classFile) == '.html';
      })
      classes = classes.map(function(classFile) {
        var validDocs = true;
        var file = 'pex-homepage/docs/' + pkg.name + '/' + classFile;
        var docHtml = fs.readFileSync(file, 'utf8');
        if (docHtml.indexOf('<h1') == -1) validDocs = false;
        if (docHtml.indexOf('<h2') == -1) validDocs = false;
        return {
          name: classFile.replace('.html', ''),
          validDocs: validDocs
        };
      });
    }
  }
  catch(e) {
    console.log(e.stack)
  }

  try {
    var pkgJson = JSON.parse(fs.readFileSync('pex-homepage/temp/node_modules/' + pkg.name + '/package.json'));
    version = pkgJson.version;
    homepage = pkgJson.homepage;
  }
  catch(e) {
  }

  return {
    name: pkg.name,
    version: version,
    homepage: homepage,
    classes: classes
  }
}

function getProjectsList() {
  var projects = [];
  try {
    projects = JSON.parse(fs.readFileSync('pex-homepage/projects/projects.json'));
    projects.forEach(function(project) {
      if (project.thumb.indexOf('http') == -1) {
        project.thumb = 'projects/' + project.thumb;
      }
    })
  }
  catch(e) {
  }
  console.log('projects', projects);
  return projects;
}

function generateIndexFile() {
  return new Promise(function(resolve, reject) {
    var templateSrc = fs.readFileSync(__dirname + '/templates/index.hbt', 'utf8');
    var template = Handlebars.compile(templateSrc);
    var projects = getProjectsList();
    var examples = getExamplesList();
    var corePackagesInfo = corePackages.map(getPackageInfo);
    var contribPackagesInfo = contribPackages.map(getPackageInfo);

    console.log(contribPackagesInfo)

    var indexHtml = template({ projects: projects, corePackages: corePackagesInfo, contribPackages: contribPackagesInfo, examples: examples })
    fs.writeFileSync('pex-homepage/index.html', indexHtml);
    resolve(true);
  })
}

function generateDocs() {
  return logP('generate docs')()
  .then(logP('cleaning docs'))
  .then(execP('rm -rf pex-homepage/docs'))
  .then(execP('rm -rf pex-homepage/temp/docs'))
  .then(logP('installing pex modules'))
  .then(execP('mkdir -p pex-homepage/temp/node_modules'))
  .then(installPexPackages)
  .then(logP('generating docs'))
  .then(execP('cd pex-homepage/temp; pex docs'))
  .then(logP('moving docs up'))
  .then(execP('mv pex-homepage/temp/docs pex-homepage'))
}

function generateExamples() {
  return logP('generate examples')()
  .then(logP('cleaning examples'))
  .then(execP('rm -rf pex-homepage/examples'))
  .then(execP('rm -rf pex-homepage/temp/pex-examples'))
  .then(logP('downloading examples'))
  .then(execP('git clone http://github.com/vorg/pex-examples/ pex-homepage/temp/pex-examples'))
  .then(logP('building examples (this will take a while...)'))
  .then(execP('cd pex-homepage/temp/pex-examples; npm install; gulp dist'))
  .then(logP('moving examples up'))
  .then(execP('mv pex-homepage/temp/pex-examples/dist/examples pex-homepage'))
}

function generateProjects() {
  return logP('generate projects')()
  .then(logP('cleaning projects'))
  .then(execP('rm -rf pex-homepage/projects'))
  .then(execP('rm -rf pex-homepage/temp/pex-projects'))
  .then(logP('downloading featured project list'))
  .then(execP('git clone http://github.com/vorg/pex-projects/ pex-homepage/temp/pex-projects'))
  .then(logP('moving projects up'))
  .then(execP('mkdir -p pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/assets pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/projects.json pex-homepage/projects'))
}

function generatePage() {
  return logP('generate page')()
  .then(logP('copying assets'))
  .then(execP('cp -r ' + __dirname + '/templates/css pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/js pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/lib pex-homepage'))
  .then(logP('generating index file'))
  .then(generateIndexFile)
  .then(execP('open pex-homepage/index.html'))
}

function clean() {
  return logP('clean')()
  .then(logP('removing temp files'))
  .then(execP('rm -r pex-homepage/temp'))
}

function generate() {
  logP('generate homepage')()
  .then(generateDocs)
  .then(generateExamples)
  .then(generateProjects)
  .then(generatePage)
  .then(clean)
  .then(logP('done all'))
}

module.exports.generate = generate;
module.exports.generateDocs = generateDocs;
module.exports.generateExamples = generateExamples;
module.exports.generateProjects = generateProjects;
module.exports.generatePage = generatePage;
module.exports.generate = generate;<commit_msg>Generating documentation for contrib packages<commit_after>var init = require('../init/init');
var docs = require('../docs/docs');
var exec = require('child_process').exec;
var Promise = require('bluebird');
var clc = require('cli-color');
var Handlebars = require('handlebars');
var fs = require('fs');
var path = require('path');

var corePackages = require('../pkg/pex-packages-core');
var contribPackages = require('../pkg/pex-packages-contrib');

//just run the command no matter what
function execP(cmd) {
  return function() {
    return new Promise(function(resolve, reject) {
      exec(cmd,
        function (err, stdout, stderr) {
          console.log(err || stdout || stderr);
          resolve(err || stdout || stderr);
      });
    })
  }
}

function logP(msg) {
  return function() {
    console.log(clc.cyan(msg));
    return Promise.resolve(true);
  }
}

function installPexPackages() {
  var packages = corePackages.concat(contribPackages);
  return Promise.all(packages.map(function(pkg) {
    return execP('cd pex-homepage/temp; npm install ' + pkg.name)();
  }))
}

function getExamplesList() {
  return fs.readdirSync('pex-homepage/examples');
}

function getPackageInfo(pkg) {
  var classes = [];
  var version = '0.0.0';
  var homepage = '';
  try {
    var pkgDocsPath = 'pex-homepage/docs/' + pkg.name + '';
    console.log(pkgDocsPath)
    if (fs.existsSync(pkgDocsPath)) {
      classes = fs.readdirSync(pkgDocsPath);
      classes = classes.filter(function(classFile) {
        return path.extname(classFile) == '.html';
      })
      classes = classes.map(function(classFile) {
        var validDocs = true;
        var file = 'pex-homepage/docs/' + pkg.name + '/' + classFile;
        var docHtml = fs.readFileSync(file, 'utf8');
        if (docHtml.indexOf('<h1') == -1) validDocs = false;
        if (docHtml.indexOf('<h2') == -1) validDocs = false;
        return {
          name: classFile.replace('.html', ''),
          validDocs: validDocs
        };
      });
    }
  }
  catch(e) {
    console.log(e.stack)
  }

  try {
    var pkgJson = JSON.parse(fs.readFileSync('pex-homepage/temp/node_modules/' + pkg.name + '/package.json'));
    version = pkgJson.version;
    homepage = pkgJson.homepage;
  }
  catch(e) {
  }

  return {
    name: pkg.name,
    version: version,
    homepage: homepage,
    classes: classes
  }
}

function getProjectsList() {
  var projects = [];
  try {
    projects = JSON.parse(fs.readFileSync('pex-homepage/projects/projects.json'));
    projects.forEach(function(project) {
      if (project.thumb.indexOf('http') == -1) {
        project.thumb = 'projects/' + project.thumb;
      }
    })
  }
  catch(e) {
  }
  console.log('projects', projects);
  return projects;
}

function generateIndexFile() {
  return new Promise(function(resolve, reject) {
    var templateSrc = fs.readFileSync(__dirname + '/templates/index.hbt', 'utf8');
    var template = Handlebars.compile(templateSrc);
    var projects = getProjectsList();
    var examples = getExamplesList();
    var corePackagesInfo = corePackages.map(getPackageInfo);
    var contribPackagesInfo = contribPackages.map(getPackageInfo);

    console.log(contribPackagesInfo)

    var indexHtml = template({ projects: projects, corePackages: corePackagesInfo, contribPackages: contribPackagesInfo, examples: examples })
    fs.writeFileSync('pex-homepage/index.html', indexHtml);
    resolve(true);
  })
}

function generateDocs() {
  return logP('generate docs')()
  .then(logP('cleaning docs'))
  .then(execP('rm -rf pex-homepage/docs'))
  .then(execP('rm -rf pex-homepage/temp/docs'))
  .then(logP('installing pex modules'))
  .then(execP('mkdir -p pex-homepage/temp/node_modules'))
  .then(installPexPackages)
  .then(logP('generating docs'))
  .then(execP('cd pex-homepage/temp; pex docs'))
  .then(logP('moving docs up'))
  .then(execP('mv pex-homepage/temp/docs pex-homepage'))
}

function generateExamples() {
  return logP('generate examples')()
  .then(logP('cleaning examples'))
  .then(execP('rm -rf pex-homepage/examples'))
  .then(execP('rm -rf pex-homepage/temp/pex-examples'))
  .then(logP('downloading examples'))
  .then(execP('git clone http://github.com/vorg/pex-examples/ pex-homepage/temp/pex-examples'))
  .then(logP('building examples (this will take a while...)'))
  .then(execP('cd pex-homepage/temp/pex-examples; npm install; gulp dist'))
  .then(logP('moving examples up'))
  .then(execP('mv pex-homepage/temp/pex-examples/dist/examples pex-homepage'))
}

function generateProjects() {
  return logP('generate projects')()
  .then(logP('cleaning projects'))
  .then(execP('rm -rf pex-homepage/projects'))
  .then(execP('rm -rf pex-homepage/temp/pex-projects'))
  .then(logP('downloading featured project list'))
  .then(execP('git clone http://github.com/vorg/pex-projects/ pex-homepage/temp/pex-projects'))
  .then(logP('moving projects up'))
  .then(execP('mkdir -p pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/assets pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/projects.json pex-homepage/projects'))
}

function generatePage() {
  return logP('generate page')()
  .then(logP('copying assets'))
  .then(execP('cp -r ' + __dirname + '/templates/css pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/js pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/lib pex-homepage'))
  .then(logP('generating index file'))
  .then(generateIndexFile)
  .then(execP('open pex-homepage/index.html'))
}

function clean() {
  return logP('clean')()
  .then(logP('removing temp files'))
  .then(execP('rm -r pex-homepage/temp'))
}

function generate() {
  logP('generate homepage')()
  .then(generateDocs)
  .then(generateExamples)
  .then(generateProjects)
  .then(generatePage)
  .then(clean)
  .then(logP('done all'))
}

module.exports.generate = generate;
module.exports.generateDocs = generateDocs;
module.exports.generateExamples = generateExamples;
module.exports.generateProjects = generateProjects;
module.exports.generatePage = generatePage;
module.exports.generate = generate;<|endoftext|>


<commit_before>var init = require('../init/init');
var docs = require('../docs/docs');
var exec = require('child_process').exec;
var Promise = require('bluebird');
var clc = require('cli-color');
var Handlebars = require('handlebars');
var fs = require('fs');
var path = require('path');

var corePackages = require('../pkg/pex-packages-core');
var contribPackages = require('../pkg/pex-packages-contrib');

//just run the command no matter what
function execP(cmd) {
  return function() {
    return new Promise(function(resolve, reject) {
      exec(cmd,
        function (err, stdout, stderr) {
          console.log(err || stdout || stderr);
          resolve(err || stdout || stderr);
      });
    })
  }
}

function logP(msg) {
  return function() {
    console.log(clc.cyan(msg));
    return Promise.resolve(true);
  }
}

function installPexPackages() {
  return Promise.all(corePackages.map(function(pkg) {
    return execP('cd pex-homepage/temp; npm install ' + pkg.name)();
  }))
}

function getExamplesList() {
  return fs.readdirSync('pex-homepage/examples');
}

function getPackageInfo(pkg) {
  var classes = [];
  var version = '0.0.0';
  var homepage = '';
  try {
    var pkgDocsPath = 'pex-homepage/docs/' + pkg.name + '';
    console.log(pkgDocsPath)
    if (fs.existsSync(pkgDocsPath)) {
      classes = fs.readdirSync(pkgDocsPath);
      classes = classes.filter(function(classFile) {
        return path.extname(classFile) == '.html';
      })
      classes = classes.map(function(classFile) {
        var validDocs = true;
        var file = 'pex-homepage/docs/' + pkg.name + '/' + classFile;
        var docHtml = fs.readFileSync(file, 'utf8');
        if (docHtml.indexOf('<h1') == -1) validDocs = false;
        if (docHtml.indexOf('<h2') == -1) validDocs = false;
        return {
          name: classFile.replace('.html', ''),
          validDocs: validDocs
        };
      });
    }
  }
  catch(e) {
    console.log(e.stack)
  }

  try {
    var pkgJson = JSON.parse(fs.readFileSync('pex-homepage/temp/node_modules/' + pkg.name + '/package.json'));
    version = pkgJson.version;
    homepage = pkgJson.homepage;
  }
  catch(e) {
  }

  return {
    name: pkg.name,
    version: version,
    homepage: homepage,
    classes: classes
  }
}

function getProjectsList() {
  var projects = [];
  try {
    projects = JSON.parse(fs.readFileSync('pex-homepage/projects/projects.json'));
    projects.forEach(function(project) {
      if (project.thumb.indexOf('http') == -1) {
        project.thumb = 'projects/' + project.thumb;
      }
    })
  }
  catch(e) {
  }
  console.log('projects', projects);
  return projects;
}

function generateIndexFile() {
  return new Promise(function(resolve, reject) {
    var templateSrc = fs.readFileSync(__dirname + '/templates/index.hbt', 'utf8');
    var template = Handlebars.compile(templateSrc);
    var projects = getProjectsList();
    var examples = getExamplesList();
    var corePackagesInfo = corePackages.map(getPackageInfo);
    var contribPackagesInfo = contribPackages.map(getPackageInfo);

    console.log(contribPackagesInfo)

    var indexHtml = template({ projects: projects, corePackages: corePackagesInfo, contribPackages: contribPackagesInfo, examples: examples })
    fs.writeFileSync('pex-homepage/index.html', indexHtml);
    resolve(true);
  })
}

function generateDocs() {
  return logP('generate docs')()
  .then(logP('cleaning docs'))
  .then(execP('rm -rf pex-homepage/docs'))
  .then(execP('rm -rf pex-homepage/temp/docs'))
  .then(logP('installing pex modules'))
  .then(execP('mkdir -p pex-homepage/temp/node_modules'))
  .then(installPexPackages)
  .then(logP('generating docs'))
  .then(execP('cd pex-homepage/temp; pex docs'))
  .then(logP('moving docs up'))
  .then(execP('mv pex-homepage/temp/docs pex-homepage'))
}

function generateExamples() {
  return logP('generate examples')()
  .then(logP('cleaning examples'))
  .then(execP('rm -rf pex-homepage/examples'))
  .then(execP('rm -rf pex-homepage/temp/pex-examples'))
  .then(logP('downloading examples'))
  .then(execP('git clone http://github.com/vorg/pex-examples/ pex-homepage/temp/pex-examples'))
  .then(logP('building examples'))
  .then(execP('cd pex-homepage/temp/pex-examples; npm install; gulp dist'))
  .then(logP('moving examples up'))
  .then(execP('mv pex-homepage/temp/pex-examples/dist/examples pex-homepage'))
}

function generateProjects() {
  return logP('generate projects')()
  .then(logP('cleaning projects'))
  .then(execP('rm -rf pex-homepage/projects'))
  .then(logP('downloading featured project list'))
  .then(execP('git clone http://github.com/vorg/pex-projects/ pex-homepage/temp/pex-projects'))
  .then(logP('moving projects up'))
  .then(execP('mkdir -p pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/assets pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/projects.json pex-homepage/projects'))
}

function generatePage() {
  return logP('generate page')()
  .then(logP('copying assets'))
  .then(execP('cp -r ' + __dirname + '/templates/css pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/js pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/lib pex-homepage'))
  .then(logP('generating index file'))
  .then(generateIndexFile)
  .then(execP('open pex-homepage/index.html'))
}

function clean() {
  return logP('clean')()
  .then(logP('removing temp files'))
  .then(execP('rm -r pex-homepage/temp'))
}

function generate() {
  logP('generate homepage')()
  .then(generateDocs)
  .then(generateExamples)
  .then(generateProjects)
  .then(generatePage)
  .then(clean)
  .then(logP('done all'))
}

module.exports.generate = generate;
module.exports.generateDocs = generateDocs;
module.exports.generateExamples = generateExamples;
module.exports.generateProjects = generateProjects;
module.exports.generatePage = generatePage;
module.exports.generate = generate;<commit_msg>Added warning about long example build time<commit_after>var init = require('../init/init');
var docs = require('../docs/docs');
var exec = require('child_process').exec;
var Promise = require('bluebird');
var clc = require('cli-color');
var Handlebars = require('handlebars');
var fs = require('fs');
var path = require('path');

var corePackages = require('../pkg/pex-packages-core');
var contribPackages = require('../pkg/pex-packages-contrib');

//just run the command no matter what
function execP(cmd) {
  return function() {
    return new Promise(function(resolve, reject) {
      exec(cmd,
        function (err, stdout, stderr) {
          console.log(err || stdout || stderr);
          resolve(err || stdout || stderr);
      });
    })
  }
}

function logP(msg) {
  return function() {
    console.log(clc.cyan(msg));
    return Promise.resolve(true);
  }
}

function installPexPackages() {
  return Promise.all(corePackages.map(function(pkg) {
    return execP('cd pex-homepage/temp; npm install ' + pkg.name)();
  }))
}

function getExamplesList() {
  return fs.readdirSync('pex-homepage/examples');
}

function getPackageInfo(pkg) {
  var classes = [];
  var version = '0.0.0';
  var homepage = '';
  try {
    var pkgDocsPath = 'pex-homepage/docs/' + pkg.name + '';
    console.log(pkgDocsPath)
    if (fs.existsSync(pkgDocsPath)) {
      classes = fs.readdirSync(pkgDocsPath);
      classes = classes.filter(function(classFile) {
        return path.extname(classFile) == '.html';
      })
      classes = classes.map(function(classFile) {
        var validDocs = true;
        var file = 'pex-homepage/docs/' + pkg.name + '/' + classFile;
        var docHtml = fs.readFileSync(file, 'utf8');
        if (docHtml.indexOf('<h1') == -1) validDocs = false;
        if (docHtml.indexOf('<h2') == -1) validDocs = false;
        return {
          name: classFile.replace('.html', ''),
          validDocs: validDocs
        };
      });
    }
  }
  catch(e) {
    console.log(e.stack)
  }

  try {
    var pkgJson = JSON.parse(fs.readFileSync('pex-homepage/temp/node_modules/' + pkg.name + '/package.json'));
    version = pkgJson.version;
    homepage = pkgJson.homepage;
  }
  catch(e) {
  }

  return {
    name: pkg.name,
    version: version,
    homepage: homepage,
    classes: classes
  }
}

function getProjectsList() {
  var projects = [];
  try {
    projects = JSON.parse(fs.readFileSync('pex-homepage/projects/projects.json'));
    projects.forEach(function(project) {
      if (project.thumb.indexOf('http') == -1) {
        project.thumb = 'projects/' + project.thumb;
      }
    })
  }
  catch(e) {
  }
  console.log('projects', projects);
  return projects;
}

function generateIndexFile() {
  return new Promise(function(resolve, reject) {
    var templateSrc = fs.readFileSync(__dirname + '/templates/index.hbt', 'utf8');
    var template = Handlebars.compile(templateSrc);
    var projects = getProjectsList();
    var examples = getExamplesList();
    var corePackagesInfo = corePackages.map(getPackageInfo);
    var contribPackagesInfo = contribPackages.map(getPackageInfo);

    console.log(contribPackagesInfo)

    var indexHtml = template({ projects: projects, corePackages: corePackagesInfo, contribPackages: contribPackagesInfo, examples: examples })
    fs.writeFileSync('pex-homepage/index.html', indexHtml);
    resolve(true);
  })
}

function generateDocs() {
  return logP('generate docs')()
  .then(logP('cleaning docs'))
  .then(execP('rm -rf pex-homepage/docs'))
  .then(execP('rm -rf pex-homepage/temp/docs'))
  .then(logP('installing pex modules'))
  .then(execP('mkdir -p pex-homepage/temp/node_modules'))
  .then(installPexPackages)
  .then(logP('generating docs'))
  .then(execP('cd pex-homepage/temp; pex docs'))
  .then(logP('moving docs up'))
  .then(execP('mv pex-homepage/temp/docs pex-homepage'))
}

function generateExamples() {
  return logP('generate examples')()
  .then(logP('cleaning examples'))
  .then(execP('rm -rf pex-homepage/examples'))
  .then(execP('rm -rf pex-homepage/temp/pex-examples'))
  .then(logP('downloading examples'))
  .then(execP('git clone http://github.com/vorg/pex-examples/ pex-homepage/temp/pex-examples'))
  .then(logP('building examples (this will take a while...)'))
  .then(execP('cd pex-homepage/temp/pex-examples; npm install; gulp dist'))
  .then(logP('moving examples up'))
  .then(execP('mv pex-homepage/temp/pex-examples/dist/examples pex-homepage'))
}

function generateProjects() {
  return logP('generate projects')()
  .then(logP('cleaning projects'))
  .then(execP('rm -rf pex-homepage/projects'))
  .then(logP('downloading featured project list'))
  .then(execP('git clone http://github.com/vorg/pex-projects/ pex-homepage/temp/pex-projects'))
  .then(logP('moving projects up'))
  .then(execP('mkdir -p pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/assets pex-homepage/projects'))
  .then(execP('mv pex-homepage/temp/pex-projects/projects.json pex-homepage/projects'))
}

function generatePage() {
  return logP('generate page')()
  .then(logP('copying assets'))
  .then(execP('cp -r ' + __dirname + '/templates/css pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/js pex-homepage'))
  .then(execP('cp -r ' + __dirname + '/templates/lib pex-homepage'))
  .then(logP('generating index file'))
  .then(generateIndexFile)
  .then(execP('open pex-homepage/index.html'))
}

function clean() {
  return logP('clean')()
  .then(logP('removing temp files'))
  .then(execP('rm -r pex-homepage/temp'))
}

function generate() {
  logP('generate homepage')()
  .then(generateDocs)
  .then(generateExamples)
  .then(generateProjects)
  .then(generatePage)
  .then(clean)
  .then(logP('done all'))
}

module.exports.generate = generate;
module.exports.generateDocs = generateDocs;
module.exports.generateExamples = generateExamples;
module.exports.generateProjects = generateProjects;
module.exports.generatePage = generatePage;
module.exports.generate = generate;<|endoftext|>


<commit_before>import styled from "styled-components";

export const DetailHeaderContainer = styled.div`
  min-height: ${props => props.height? props.height : '44.2vh'};
  width: 100%;
  /* background: #297AFF; */
  background: ${props => props.bgUrl? `url("${props.bgUrl}")` : "transparent"};
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: none;
  display: flex;
  align-items: center;
  position: relative;
  max-height: 18rem;
  .title {
    font-size: 2rem;
    height: auto;
    color: ${props => props.theme.black.lighten(.15)};
    padding: 1rem 0 3rem 5rem;
    font-weight: 600;
    /* background: rgba(0, 0, 0, .2); */
    width: 100%;

    @media (max-width: 467px) {
      padding: 1rem 1rem 3rem 1rem;
    }
  }

  .title::before {
    color: #FFF;
  }
  .title::before:hover {
    color: red;
  }
`;

export const BottomContainer = styled.div`
  position: absolute;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  flex-direction: row;
  box-sizing: border-box;
  bottom: 1.8rem;
  padding: .5rem;
  color: #969696;

  .it:nth-child(n) {
    margin-left: 1rem;
  }
  .ed {
    display: flex;
    align-items: center;
    transition: .2s all ease-in-out;
    border: .1em solid transparent;
  }
  .ed:hover {
    background: white;
    padding: .1em;
    border: none;
    box-sizing: content-box;
  }
  .it {
    display: flex;
    flex-direction: row;
    cursor: pointer;
  }
  .it .tx {
    margin-left: .2rem;
  }
`;

export const BottomTagsContainer = styled(BottomContainer)`
  padding-right: 2rem;
  bottom: 0;
`;<commit_msg>add padding<commit_after>import styled from "styled-components";

export const DetailHeaderContainer = styled.div`
  min-height: ${props => props.height? props.height : '44.2vh'};
  width: 100%;
  /* background: #297AFF; */
  background: ${props => props.bgUrl? `url("${props.bgUrl}")` : "transparent"};
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: none;
  display: flex;
  align-items: center;
  position: relative;
  max-height: 18rem;
  .title {
    font-size: 2rem;
    height: auto;
    color: ${props => props.theme.black.lighten(.15)};
    padding: 1rem 0 3rem 5rem;
    font-weight: 600;
    /* background: rgba(0, 0, 0, .2); */
    width: 100%;

    @media (max-width: 467px) {
      padding: 1rem 1rem 3rem 1rem;
    }
  }

  .title::before {
    color: #FFF;
  }
  .title::before:hover {
    color: red;
  }
`;

export const BottomContainer = styled.div`
  position: absolute;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  flex-direction: row;
  box-sizing: border-box;
  bottom: 1.8rem;
  padding: .5rem;
  padding-right: 1rem;
  color: #969696;

  .it:nth-child(n) {
    margin-left: 1rem;
  }
  .ed {
    display: flex;
    align-items: center;
    transition: .2s all ease-in-out;
    border: .1em solid transparent;
  }
  .ed:hover {
    background: white;
    padding: .1em;
    border: none;
    box-sizing: content-box;
  }
  .it {
    display: flex;
    flex-direction: row;
    cursor: pointer;
  }
  .it .tx {
    margin-left: .2rem;
  }
`;

export const BottomTagsContainer = styled(BottomContainer)`
  padding-right: 1rem;
  bottom: 0;
`;<|endoftext|>


<commit_before>;(function (name, definition) {
  // this is considered "safe":
  var hasDefine = typeof define === 'function';

  if (hasDefine) {
    // AMD Module or CMD Module
    define(definition);
  } else {
    // Assign to common namespaces or simply the global object (window)
    this[name] = definition();
  }
})('ImagePlaceholder', function() {
  var getFormat = function (format) {
    switch (format) {
      case 'png':
      case 'jpg':
      case 'jpeg':
      case 'gif':
      case 'webp':
      return 'image/' + format;
    }
    return 'image/png';
  };

  var lightCombine = function (options, defaults) {
    var result = {};
    var key;
    for (key in defaults) {
      result[key] = defaults[key];
    }
    for (key in options) {
      result[key] = options[key];
    }
    return result;
  };

  var Placeholder = function (options) {
    var defaults = {
      width: 400,
      height: 400,
      textColor: '#969696',
      backgroundColor: '#cccccc',
      text: '',
      format: 'png'
    };
    if (!(this instanceof Placeholder)) {
      return new Placeholder(options);
    }
    this._options = lightCombine(options, defaults);
    return this;
  };

  Placeholder.prototype.generate = function () {
    var options = this._options;
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    var text = options.text || (options.width + ' x ' + options.height);
    console.log(options);
    var textSize = (Number(options.height) / 10) || 12;
    var result;
    canvas.width = options.width;
    canvas.height = options.height;
    context.fillStyle = options.backgroundColor;
    context.fillRect(0, 0, options.width, options.height);
    context.fillStyle = options.textColor;
    context.font = textSize + 'px Georgia';
    context.textAlign = 'center';
    context.fillText(text, (options.width / 2), (options.height / 2 + options.height / 20));
    result = canvas.toDataURL(getFormat(options.format));
    canvas = null;
    context = null;
    return result;
  };

  var getSource = function (options) {
    var opts;
    if (arguments.length === 2) {
      opts = {
        width: arguments[0],
        height: arguments[1]
      }
    } else if (arguments.length === 3) {
      opts = arguments[2];
      opts.width = arguments[0];
      opts.height = arguments[1];
    } else {
      opts = options;
    }
    return (new Placeholder(opts)).generate();
  };

  return getSource;

});
<commit_msg>optimize<commit_after>;(function (name, definition) {
  // this is considered "safe":
  var hasDefine = typeof define === 'function';

  if (hasDefine) {
    // AMD Module or CMD Module
    define(definition);
  } else {
    // Assign to common namespaces or simply the global object (window)
    this[name] = definition();
  }
})('ImagePlaceholder', function() {
  var getFormat = function (format) {
    switch (format) {
      case 'png':
      case 'jpg':
      case 'jpeg':
      case 'gif':
      case 'webp':
      return 'image/' + format;
    }
    return 'image/png';
  };

  var lightCombine = function (options, defaults) {
    var result = {};
    var key;
    for (key in defaults) {
      result[key] = defaults[key];
    }
    for (key in options) {
      result[key] = options[key];
    }
    return result;
  };

  var Placeholder = function (options) {
    var defaults = {
      width: 400,
      height: 400,
      textColor: '#969696',
      backgroundColor: '#cccccc',
      text: '',
      format: 'png'
    };
    if (!(this instanceof Placeholder)) {
      return new Placeholder(options);
    }
    this._options = lightCombine(options, defaults);
    return this;
  };

  Placeholder.prototype.generate = function () {
    var options = this._options;
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    var text = options.text || (options.width + ' x ' + options.height);
    var textSize;
    var result;
    textSize = (textSize = (Number(options.height) / 10) || 12) < 12 ? 12 : textSize;
    canvas.width = options.width;
    canvas.height = options.height;
    context.fillStyle = options.backgroundColor;
    context.fillRect(0, 0, options.width, options.height);
    context.fillStyle = options.textColor;
    context.font = textSize + 'px Georgia';
    context.textAlign = 'center';
    context.fillText(text, (options.width / 2), (options.height / 2 + textSize / 2));
    result = canvas.toDataURL(getFormat(options.format));
    canvas = null;
    context = null;
    return result;
  };

  var getSource = function (options) {
    var opts;
    if (arguments.length === 2) {
      opts = {
        width: arguments[0],
        height: arguments[1]
      }
    } else if (arguments.length === 3) {
      opts = arguments[2];
      opts.width = arguments[0];
      opts.height = arguments[1];
    } else {
      opts = options;
    }
    return (new Placeholder(opts)).generate();
  };

  return getSource;

});
<|endoftext|>


<commit_before>"use strict";

/**
Import an orthogonal tilemap from
 * Tiled: Map Editor and draw on the screen.

 *
To Do

 *

 *
Image Layer

 *
Ellipse and Polygon Objects

 *

 * @module Import From Tiled
 */

/** @function ImportTilemap
 * @param {Object} file JSON file exported from Tiled. This should be required in a scene enter
 * script and passed to the function.
 * @param {EntityPool} entities EntityPool from game.entities
 */
function ImportTilemap(file, entities) { // eslint-disable-line no-unused-vars

	var tile, image, image_index, tile_pos, cols, tileset, tileset_index = 0;
	var layer, object, entity;

	for (var i = 0; i < file.layers.length; i++) {
		layer = file.layers[i];

		// Render Tile Layers
		if (layer.type == "tilelayer") {
			for (j = 0; j < layer.data.length; j++) {

				// Select tileset index based on firstgid and image index
				// Set image index minus firstgid for positioning math
				for (var k = 0; k < file.tilesets.length; k++) {
					if (layer.data[j] > file.tilesets[k].firstgid) {
						tileset_index = k;
					}
				}
				cols = file.tilesets[tileset_index].imagewidth / file.tilesets[tileset_index].tilewidth;
				image_index = layer.data[j] - file.tilesets[tileset_index].firstgid;
				tileset = file.tilesets[tileset_index];

				if (image_index >= 0) {

					// Create tile and get properties
					tile = entities.create();
					entities.set(tile, "name", "tile");
					entities.set(tile, "tile", true);
					entities.set(tile, "image", { "name": "" });
					entities.set(tile, "position", { "x": 0, "y": 0 });
					image = entities.get(tile, "image");
					tile_pos = entities.get(tile, "position");

					// Position based on index
					tile_pos.x = (j % file.width) * file.tilewidth;
					tile_pos.y = Math.floor(j / file.width) * file.tileheight;

					// Character position z: 1 so anything without background true will layer over player
					tile_pos.z = (layer.properties.Background == "True") ? -1 : 2;

					// Select which "tile" of the tileset image to render
					image.name = tileset.image;
					image.sourceWidth = tileset.tilewidth;
					image.sourceHeight = tileset.tileheight;
					image.destinationWidth = tileset.tilewidth;
					image.destinationHeight = tileset.tileheight;
					image.sourceX = (image_index % cols) * tileset.tilewidth + ((image_index % cols) * tileset.spacing) + tileset.margin;
					image.sourceY = Math.floor(image_index / cols) * tileset.tileheight + (Math.floor(image_index / cols) * tileset.spacing) + tileset.margin;

				}
			}
		}

		/**
		 * @member {Entity} Object Entities
		 *
Create Entity with size and position components

		 *
Collidable: True or False
Add collision component to entity.
		 * Currently collisions are handled as a simulation system in the project.

		 *
Spawn: True or False
Creates an entity with a "spawn" boolean
		 * component allowing you to use game.entities.find("spawn"); to find the spawn point for this map.

		 *
All other properties end up in a "tiledProperties" component to be handled on a per-game basis.
		 */
		// Loop object layer for collisions and spawn point
		if (layer.type == "objectgroup") {
			for (var j = 0; j < layer.objects.length; j++) {
				object = layer.objects[j];
				entity = entities.create();
				entities.set(entity, "size", { "width": object.width, "height": object.height });
				entities.set(entity, "position", { "x": object.x, "y": object.y });
				entities.set(entity, "collisions", []);
				Object.keys(object.properties).forEach(function(key) {
					if (!isNaN(object.properties[key])) {
						object.properties[key] = parseInt(object.properties[key], 10);
					}
					if (new String(object.properties[key]).toLowerCase() == "true" || object.properties[key] == "1") {
						object.properties[key] = true;
					}
					if (new String(object.properties[key]).toLowerCase() == "false" || object.properties[key] == "0") {
						object.properties[key] = false;
					}
					var new_key = new String(key).toLowerCase();
					object.properties[new_key] = object.properties[key];
					delete object.properties[key];
				});

				// Spawn points
				if (object.properties.spawn) {
					entities.set(entity, "spawn", true);
				}

				entities.set(entity, "tiledProperties", object.properties);

			}
		}
	}

	/**
	 * @member {Entity} Container Entity
	 * Created automatically allowing you to use
	 * game.entities.find("container"); to get a constrainPosition ID

	 */
	var map_size = {
		"width": file.width * file.tilewidth,
		"height": file.height * file.tileheight
	};
	var container = entities.create();
	entities.set(container, "name", "container");
	entities.set(container, "container", true);
	entities.set(container, "position", { "x": 0, "y": 0 });
	entities.set(container, "size", map_size);

}

module.exports = ImportTilemap;
<commit_msg>fix bug with single image tilesets and stop lowercasing tiledProperties component properties to fix 2nd loading bug<commit_after>"use strict";

/**
Import an orthogonal tilemap from
 * Tiled: Map Editor and draw on the screen.

 *
To Do

 *

 *
Image Layer

 *
Ellipse and Polygon Objects

 *

 * @module Import From Tiled
 */

/** @function ImportTilemap
 * @param {Object} file JSON file exported from Tiled. This should be required in a scene enter
 * script and passed to the function.
 * @param {EntityPool} entities EntityPool from game.entities
 */
function ImportTilemap(file, entities) { // eslint-disable-line no-unused-vars

	var tile, image, image_index, tile_pos, cols, tileset, tileset_index = 0;
	var layer, object, entity;

	for (var i = 0; i < file.layers.length; i++) {
		layer = file.layers[i];

		// Render Tile Layers
		if (layer.type == "tilelayer") {
			for (j = 0; j < layer.data.length; j++) {

				// Select tileset index based on firstgid and image index
				// Set image index minus firstgid for positioning math
				for (var k = 0; k < file.tilesets.length; k++) {
					if (layer.data[j] >= file.tilesets[k].firstgid) {
						tileset_index = k;
					}
				}
				cols = file.tilesets[tileset_index].imagewidth / file.tilesets[tileset_index].tilewidth;
				image_index = layer.data[j] - file.tilesets[tileset_index].firstgid;
				tileset = file.tilesets[tileset_index];

				if (image_index >= 0) {

					// Create tile and get properties
					tile = entities.create();
					entities.set(tile, "name", "tile");
					entities.set(tile, "tile", true);
					entities.set(tile, "image", { "name": "" });
					entities.set(tile, "position", { "x": 0, "y": 0 });
					image = entities.get(tile, "image");
					tile_pos = entities.get(tile, "position");

					// Position based on index
					tile_pos.x = (j % file.width) * file.tilewidth;
					tile_pos.y = Math.floor(j / file.width) * file.tileheight;

					// Character position z: 1 so anything without background true will layer over player
					tile_pos.z = (layer.properties.Background == "True") ? -1 : 2;

					// Select which "tile" of the tileset image to render
					image.name = tileset.image;
					image.sourceWidth = tileset.tilewidth;
					image.sourceHeight = tileset.tileheight;
					image.destinationWidth = tileset.tilewidth;
					image.destinationHeight = tileset.tileheight;
					image.sourceX = (image_index % cols) * tileset.tilewidth + ((image_index % cols) * tileset.spacing) + tileset.margin;
					if(tileset.tileheight == tileset.imageheight) {
						image.sourceY = 0;
					} else {
						image.sourceY = Math.floor(image_index / cols) * tileset.tileheight + (Math.floor(image_index / cols) * tileset.spacing) + tileset.margin;
					}

				}
			}
		}

		/**
		 * @member {Entity} Object Entities
		 *
Create Entity with size and position components

		 *
Collidable: True or False
Add collision component to entity.
		 * Currently collisions are handled as a simulation system in the project.

		 *
Spawn: True or False
Creates an entity with a "spawn" boolean
		 * component allowing you to use game.entities.find("spawn"); to find the spawn point for this map.

		 *
All other properties end up in a "tiledProperties" component to be handled on a per-game basis.
		 */
		// Loop object layer for collisions and spawn point
		if (layer.type == "objectgroup") {
			for (var j = 0; j < layer.objects.length; j++) {
				object = layer.objects[j];
				entity = entities.create();
				entities.set(entity, "size", { "width": object.width, "height": object.height });
				entities.set(entity, "position", { "x": object.x, "y": object.y });
				entities.set(entity, "collisions", []);
				Object.keys(object.properties).forEach(function(key) {
					if (!isNaN(object.properties[key])) {
						object.properties[key] = parseInt(object.properties[key], 10);
					}
					if (new String(object.properties[key]).toLowerCase() == "true" || object.properties[key] == "1") {
						object.properties[key] = true;
					}
					if (new String(object.properties[key]).toLowerCase() == "false" || object.properties[key] == "0") {
						object.properties[key] = false;
					}
				});

				// Spawn points
				if (object.properties.spawn) {
					entities.set(entity, "spawn", true);
				}

				entities.set(entity, "tiledProperties", object.properties);

			}
		}
	}

	/**
	 * @member {Entity} Container Entity
	 * Created automatically allowing you to use
	 * game.entities.find("container"); to get a constrainPosition ID

	 */
	var map_size = {
		"width": file.width * file.tilewidth,
		"height": file.height * file.tileheight
	};
	var container = entities.create();
	entities.set(container, "name", "container");
	entities.set(container, "container", true);
	entities.set(container, "position", { "x": 0, "y": 0 });
	entities.set(container, "size", map_size);

}

module.exports = ImportTilemap;
<|endoftext|>


<commit_before>var config = require("config");
var Promise = require("bluebird");
var _ = require("lodash");
var request = Promise.promisifyAll(require("request"));
var log = require("../logger");

function getSolrIds(collectionName) {
    var solrConfig = config.get("dbConfig.solr");
    var maxRows = solrConfig.maxRows;
    var reqURL = "http://" + solrConfig.host + ":" + solrConfig.port +
        "/solr/" + collectionName + "/query";
    var reqObj = {
        url: reqURL,
        qs: {q: "id:*", wt: "json", rows: maxRows, fl: 'id'}
    };

    function clientError(e) {
        return e.code >= 400 && e.code < 500;
    }

    return request.getAsync(reqObj)
        .get(1)
        .then(function (body) {
            var docs = JSON.parse(body).response.docs;
            return Promise.resolve(_.pluck(docs, 'id'));
        })
        .catch(clientError, function (e) {
            log.error(e);
            return Promise.reject(e);
        });
}

function insertSet(key, solrCollection, redisClient) {
    return new Promise(function (resolve, reject) {
        getSolrIds(solrCollection)
            .then(function (ids) {
                _.forEach(ids, function (id) {
                    log.info(key + " => " + id);
                    redisClient.sadd(key, id);
                })
                return key;
            })
            .then(function () {
                resolve();
            })
            .catch(function (e) {
                reject(new Error("Error in indexRedis. " + e.message));
            })
    });
}
// Insert the union of id values of all keys into one set that represents the
// entire unique apps in the dataset.
function insertUnion(datasetKey, redisClient) {
    return new Promise(function (resolve, reject) {
        try {
            redisClient.keys('*', function (err, keys) {
                if (err) {
                    reject(new Error("Failed tp find all keys in redis."));
                }
                _.forEach(keys, function (key) {
                    _.forEach(redisClient.smembers(key), function (id) {
                        log.info(key + " => " + id);
                        redisClient.sadd(datasetKey, id);
                    })
                })
                return resolve();
            });

        }
        catch (err) {
            reject(err);
        }
    });
}

module.exports = {insertSet: insertSet, insertUnion: insertUnion};<commit_msg>fix adding keys to redis<commit_after>var config = require("config");
var Promise = require("bluebird");
var _ = require("lodash");
var redis = require("redis");
var request = Promise.promisifyAll(require("request"));
var log = require("../logger");

function getSolrIds(collectionName) {
    var solrConfig = config.get("dbConfig.solr");
    var maxRows = solrConfig.maxRows;
    var reqURL = "http://" + solrConfig.host + ":" + solrConfig.port +
        "/solr/" + collectionName + "/query";
    var reqObj = {
        url: reqURL,
        qs: {q: "id:*", wt: "json", rows: maxRows, fl: 'id'}
    };

    function clientError(e) {
        return e.code >= 400 && e.code < 500;
    }

    return request.getAsync(reqObj)
        .get(1)
        .then(function (body) {
            var docs = JSON.parse(body).response.docs;
            return Promise.resolve(_.pluck(docs, 'id'));
        })
        .catch(clientError, function (e) {
            log.error(e);
            return Promise.reject(e);
        });
}

function insertSolrKeys(key, solrCollection) {
    var redisClient = redis.createClient();
    redisClient.on("error", function (err) {
        log.error("Error " + err);
        throw (err);
    });

    return new Promise(function (resolve, reject) {
        getSolrIds(solrCollection)
            .then(function (ids) {
                _.forEach(ids, function (id) {
                    log.info(key + " => " + id);
                    redisClient.SADD(key, id);
                })
                return key;
            })
            .then(function () {
                redisClient.quit();
                resolve();
            })
            .catch(function (e) {
                redisClient.quit();
                reject(new Error("Error in indexRedis. " + e.message));
            })
    });
}
// Insert the union of id values of all keys into one set that represents the
// entire unique apps in the dataset.
function insertDatasetKeys(datasetKey, keys) {
    var redisPromise = Promise.promisifyAll(redis);
    var redisClient = redisPromise.createClient();
    redisClient.on("error", function (err) {
        log.error("Error " + err);
        throw (err);
    });

    return Promise.map(keys, function (key) {
        return redisClient.SMEMBERSAsync(key)
            .then(function (ids) {
                var promises = [];
                _.forEach(ids, function (id) {
                    log.info(datasetKey + " => " + id);
                    promises.push(redisClient.sadd(datasetKey, id));
                })
                return Promise.all(promises).then(function () {
                    return Promise.resolve();
                }).catch(function (e) {
                    log.error('Failed to add keys to %s. %s', key, e.message);
                    return Promise.reject(e);
                })
            })
    }, {concurrency: 1}).then(function () {
        log.info("All dataset ids have been added to %s redis set.", datasetKey);
        redisClient.quit();
        return Promise.resolve();
    }).catch(function (e) {
        reject(e);
    });
}

module.exports = {
    insertSolrKeys: insertSolrKeys,
    insertDatasetKeys: insertDatasetKeys
};<|endoftext|>


<commit_before><commit_msg>WASM: fix "Missing field" error for lensFlare.<commit_after><|endoftext|>