<commit_before>jQuery('#qrcodeCanvas').qrcode({
  text: "http://jetienne.com/"
});

Dropzone.autoDiscover = false;

function getExtention(fname) {
  return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
}

function pathJoin(parts, sep) {
  var separator = sep || '/';
  var replace = new RegExp(separator + '{1,}', 'g');
  return parts.join(separator).replace(replace, separator);
}

function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = decodeURI(window.location.search).substr(1).match(reg);
  if (r != null) return r[2].replace(/\+/g, ' ');
  return null;
}

var vm = new Vue({
  el: "#app",
  data: {
    user: {
      email: "",
      name: "",
    },
    location: window.location,
    breadcrumb: [],
    showHidden: false,
    previewMode: false,
    preview: {
      filename: '',
      filetype: '',
      filesize: 0,
      contentHTML: '',
    },
    version: "loading",
    mtimeTypeFromNow: false, // or fromNow
    auth: {},
    search: getQueryString("search"),
    files: [{
      name: "loading ...",
      path: "",
      size: "...",
      type: "dir",
    }],
    myDropzone: null,
  },
  computed: {
    computedFiles: function () {
      var that = this;
      that.preview.filename = null;

      var files = this.files.filter(function (f) {
        if (f.name == 'README.md') {
          that.preview.filename = f.name;
        }
        if (!that.showHidden && f.name.slice(0, 1) === '.') {
          return false;
        }
        return true;
      });
      // console.log(this.previewFile)
      if (this.preview.filename) {
        var name = this.preview.filename; // For now only README.md
        console.log(pathJoin([location.pathname, 'README.md']))
        $.ajax({
          url: pathJoin([location.pathname, 'README.md']),
          method: 'GET',
          success: function (res) {
            var converter = new showdown.Converter({
              tables: true,
              omitExtraWLInCodeBlocks: true,
              parseImgDimensions: true,
              simplifiedAutoLink: true,
              literalMidWordUnderscores: true,
              tasklists: true,
              ghCodeBlocks: true,
              smoothLivePreview: true,
              simplifiedAutoLink: true,
              strikethrough: true,
            });

            var html = converter.makeHtml(res);
            that.preview.contentHTML = html;
          },
          error: function (err) {
            console.log(err)
          }
        })
      }

      return files;
    },
  },
  created: function () {
    $.ajax({
      url: "/-/user",
      method: "get",
      dataType: "json",
      success: function (ret) {
        if (ret) {
          this.user.email = ret.email;
          this.user.name = ret.name;
        }
      }.bind(this)
    })
    this.myDropzone = new Dropzone("#upload-form", {
      paramName: "file",
      maxFilesize: 10240,
      addRemoveLinks: true,
      init: function () {
        this.on("uploadprogress", function (file, progress) {
          // console.log("File progress", progress);
        });
        this.on("complete", function (file) {
          console.log("reload file list")
          loadFileList()
        })
      }
    });
  },
  methods: {
    formatTime: function (timestamp) {
      var m = moment(timestamp);
      if (this.mtimeTypeFromNow) {
        return m.fromNow();
      }
      return m.format('YYYY-MM-DD HH:mm:ss');
    },
    toggleHidden: function () {
      this.showHidden = !this.showHidden;
    },
    removeAllUploads: function () {
      this.myDropzone.removeAllFiles();
    },
    parentDirectory: function (path) {
      return path.replace('\\', '/').split('/').slice(0, -1).join('/')
    },
    changeParentDirectory: function (path) {
      var parentDir = this.parentDirectory(path);
      loadFileOrDir(parentDir);
    },
    genInstallURL: function (name, noEncode) {
      var parts = [location.host];
      var pathname = decodeURI(location.pathname);
      if (!name) {
        parts.push(pathname);
      } else if (getExtention(name) == "ipa") {
        parts.push("/-/ipa/link", pathname, name);
      } else {
        parts.push(pathname, name);
      }
      var urlPath = location.protocol + "//" + pathJoin(parts);
      return noEncode ? urlPath : encodeURI(urlPath);
    },
    genQrcode: function (name, title) {
      var urlPath = this.genInstallURL(name, true);
      $("#qrcode-title").html(title || name || location.pathname);
      $("#qrcode-link").attr("href", urlPath);
      $('#qrcodeCanvas').empty().qrcode({
        text: encodeURI(urlPath),
      });

      $("#qrcodeRight a").attr("href", urlPath);
      $("#qrcode-modal").modal("show");
    },
    genDownloadURL: function (f) {
      return location.origin + "/" + f.path;
    },
    shouldHaveQrcode: function (name) {
      return ['apk', 'ipa'].indexOf(getExtention(name)) !== -1;
    },
    genFileClass: function (f) {
      if (f.type == "dir") {
        if (f.name == '.git') {
          return 'fa-git-square';
        }
        return "fa-folder-open";
      }
      var ext = getExtention(f.name);
      switch (ext) {
        case "go":
        case "py":
        case "js":
        case "java":
        case "c":
        case "cpp":
        case "h":
          return "fa-file-code-o";
        case "pdf":
          return "fa-file-pdf-o";
        case "zip":
          return "fa-file-zip-o";
        case "mp3":
        case "wav":
          return "fa-file-audio-o";
        case "jpg":
        case "png":
        case "gif":
        case "jpeg":
        case "tiff":
          return "fa-file-picture-o";
        case "ipa":
        case "dmg":
          return "fa-apple";
        case "apk":
          return "fa-android";
        case "exe":
          return "fa-windows";
      }
      return "fa-file-text-o"
    },
    clickFileOrDir: function (f, e) {
      // TODO: fix here tomorrow
      if (f.type == "file") {
        return true;
      }
      var reqPath = pathJoin([location.pathname, f.name]);
      loadFileOrDir(reqPath);
      e.preventDefault()
    },
    changePath: function (reqPath, e) {
      loadFileOrDir(reqPath);
      e.preventDefault()
    },
    showInfo: function (f) {
      console.log(f);
      $.ajax({
        url: pathJoin(["/-/info", location.pathname, f.name]),
        method: "GET",
        success: function (res) {
          $("#file-info-title").text(f.name);
          $("#file-info-content").text(JSON.stringify(res, null, 4));
          $("#file-info-modal").modal("show");
          // console.log(JSON.stringify(res, null, 4));
        }
      })
    },
    makeDirectory: function () {
      var name = window.prompt("Directory name?")
      console.log(name)
      if (!name) {
        return
      }
      $.ajax({
        url: pathJoin(["/-/mkdir", location.pathname]),
        data: {
          name: name,
        },
        method: "POST",
        success: function (res) {
          console.log(res)
          loadFileList()
        },
        error: function (err) {
          alert(err.responseText);
        }
      })
    },
    deletePathConfirm: function (f, e) {
      e.preventDefault();
      if (!e.altKey) { // skip confirm when alt pressed
        if (!window.confirm("Delete " + f.name + " ?")) {
          return;
        }
      }
      $.ajax({
        url: pathJoin([location.pathname, f.name]),
        method: 'DELETE',
        success: function (res) {
          loadFileList()
        },
        error: function (err) {
          alert(err.responseText);
        }
      });
    },
    updateBreadcrumb: function () {
      var pathname = decodeURI(location.pathname || "/");
      var parts = pathname.split('/');
      this.breadcrumb = [];
      if (pathname == "/") {
        return this.breadcrumb;
      }
      var i = 2;
      for (; i <= parts.length; i += 1) {
        var name = parts[i - 1];
        if (!name) {
          continue;
        }
        var path = parts.slice(0, i).join('/');
        this.breadcrumb.push({
          name: name + (i == parts.length ? ' /' : ''),
          path: path
        })
      }
      return this.breadcrumb;
    },
    loadPreviewFile: function (filepath, e) {
      if (e) {
        e.preventDefault() // may be need a switch
      }
      var that = this;
      $.getJSON(pathJoin(['/-/info', location.pathname]))
        .then(function (res) {
          console.log(res);
          that.preview.filename = res.name;
          that.preview.filesize = res.size;
          return $.ajax({
            url: '/' + res.path,
            dataType: 'text',
          });
        })
        .then(function (res) {
          console.log(res)
          that.preview.contentHTML = '
' + res + '
';
          console.log("Finally")
        })
        .done(function (res) {
          console.log("done", res)
        });
    },
    loadAll: function () {
      // TODO: move loadFileList here
    },
  }
})

window.onpopstate = function (event) {
  if (location.search.match(/\?search=/)) {
    location.reload();
    return;
  }
  loadFileList()
}

function loadFileOrDir(reqPath) {
  window.history.pushState({}, "", reqPath);
  loadFileList(reqPath)
}

function loadFileList(pathname) {
  var pathname = pathname || location.pathname;
  // console.log("load filelist:", pathname)
  if (getQueryString("raw") !== "false") { // not a file preview
    $.ajax({
      url: pathname + "?json=true",
      dataType: "json",
      cache: false,
      success: function (res) {
        res.files = _.sortBy(res.files, function (f) {
          var weight = f.type == 'dir' ? 1000 : 1;
          return -weight * f.mtime;
        })

        vm.files = res.files;
        vm.auth = res.auth;
      },
      error: function (err) {
        console.error(err)
      },
    });

  }

  vm.updateBreadcrumb();
  vm.previewMode = getQueryString("raw") == "false";
  if (vm.previewMode) {
    vm.loadPreviewFile();
  }
}

Vue.filter('fromNow', function (value) {
  return moment(value).fromNow();
})

Vue.filter('formatBytes', function (value) {
  var bytes = parseFloat(value);
  if (bytes < 0) return "-";
  else if (bytes < 1024) return bytes + " B";
  else if (bytes < 1048576) return (bytes / 1024).toFixed(0) + " KB";
  else if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + " MB";
  else return (bytes / 1073741824).toFixed(1) + " GB";
})

$(function () {
  $.scrollUp({
    scrollText: '', // text are defined in css
  });

  // For page first loading
  loadFileList(location.pathname + location.search)

  // update version
  $.getJSON("/-/sysinfo", function (res) {
    vm.version = res.version;
  })

  var clipboard = new Clipboard('.btn');
  clipboard.on('success', function (e) {
    console.info('Action:', e.action);
    console.info('Text:', e.text);
    console.info('Trigger:', e.trigger);
    $(e.trigger)
      .tooltip('show')
      .mouseleave(function () {
        $(this).tooltip('hide');
      })

    e.clearSelection();
  });
});
<commit_msg>fix #58<commit_after>jQuery('#qrcodeCanvas').qrcode({
  text: "http://jetienne.com/"
});

Dropzone.autoDiscover = false;

function getExtention(fname) {
  return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
}

function pathJoin(parts, sep) {
  var separator = sep || '/';
  var replace = new RegExp(separator + '{1,}', 'g');
  return parts.join(separator).replace(replace, separator);
}

function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = decodeURI(window.location.search).substr(1).match(reg);
  if (r != null) return r[2].replace(/\+/g, ' ');
  return null;
}

var vm = new Vue({
  el: "#app",
  data: {
    user: {
      email: "",
      name: "",
    },
    location: window.location,
    breadcrumb: [],
    showHidden: false,
    previewMode: false,
    preview: {
      filename: '',
      filetype: '',
      filesize: 0,
      contentHTML: '',
    },
    version: "loading",
    mtimeTypeFromNow: false, // or fromNow
    auth: {},
    search: getQueryString("search"),
    files: [{
      name: "loading ...",
      path: "",
      size: "...",
      type: "dir",
    }],
    myDropzone: null,
  },
  computed: {
    computedFiles: function () {
      var that = this;
      that.preview.filename = null;

      var files = this.files.filter(function (f) {
        if (f.name == 'README.md') {
          that.preview.filename = f.name;
        }
        if (!that.showHidden && f.name.slice(0, 1) === '.') {
          return false;
        }
        return true;
      });
      // console.log(this.previewFile)
      if (this.preview.filename) {
        var name = this.preview.filename; // For now only README.md
        console.log(pathJoin([location.pathname, 'README.md']))
        $.ajax({
          url: pathJoin([location.pathname, 'README.md']),
          method: 'GET',
          success: function (res) {
            var converter = new showdown.Converter({
              tables: true,
              omitExtraWLInCodeBlocks: true,
              parseImgDimensions: true,
              simplifiedAutoLink: true,
              literalMidWordUnderscores: true,
              tasklists: true,
              ghCodeBlocks: true,
              smoothLivePreview: true,
              simplifiedAutoLink: true,
              strikethrough: true,
            });

            var html = converter.makeHtml(res);
            that.preview.contentHTML = html;
          },
          error: function (err) {
            console.log(err)
          }
        })
      }

      return files;
    },
  },
  created: function () {
    $.ajax({
      url: "/-/user",
      method: "get",
      dataType: "json",
      success: function (ret) {
        if (ret) {
          this.user.email = ret.email;
          this.user.name = ret.name;
        }
      }.bind(this)
    })
    this.myDropzone = new Dropzone("#upload-form", {
      paramName: "file",
      maxFilesize: 10240,
      addRemoveLinks: true,
      init: function () {
        this.on("uploadprogress", function (file, progress) {
          // console.log("File progress", progress);
        });
        this.on("complete", function (file) {
          console.log("reload file list")
          loadFileList()
        })
      }
    });
  },
  methods: {
    formatTime: function (timestamp) {
      var m = moment(timestamp);
      if (this.mtimeTypeFromNow) {
        return m.fromNow();
      }
      return m.format('YYYY-MM-DD HH:mm:ss');
    },
    toggleHidden: function () {
      this.showHidden = !this.showHidden;
    },
    removeAllUploads: function () {
      this.myDropzone.removeAllFiles();
    },
    parentDirectory: function (path) {
      return path.replace('\\', '/').split('/').slice(0, -1).join('/')
    },
    changeParentDirectory: function (path) {
      var parentDir = this.parentDirectory(path);
      loadFileOrDir(parentDir);
    },
    genInstallURL: function (name, noEncode) {
      var parts = [location.host];
      var pathname = decodeURI(location.pathname);
      if (!name) {
        parts.push(pathname);
      } else if (getExtention(name) == "ipa") {
        parts.push("/-/ipa/link", pathname, name);
      } else {
        parts.push(pathname, name);
      }
      var urlPath = location.protocol + "//" + pathJoin(parts);
      return noEncode ? urlPath : encodeURI(urlPath);
    },
    genQrcode: function (name, title) {
      var urlPath = this.genInstallURL(name, true);
      $("#qrcode-title").html(title || name || location.pathname);
      $("#qrcode-link").attr("href", urlPath);
      $('#qrcodeCanvas').empty().qrcode({
        text: encodeURI(urlPath),
      });

      $("#qrcodeRight a").attr("href", urlPath);
      $("#qrcode-modal").modal("show");
    },
    genDownloadURL: function (f) {
      return location.origin + "/" + f.path;
    },
    shouldHaveQrcode: function (name) {
      return ['apk', 'ipa'].indexOf(getExtention(name)) !== -1;
    },
    genFileClass: function (f) {
      if (f.type == "dir") {
        if (f.name == '.git') {
          return 'fa-git-square';
        }
        return "fa-folder-open";
      }
      var ext = getExtention(f.name);
      switch (ext) {
        case "go":
        case "py":
        case "js":
        case "java":
        case "c":
        case "cpp":
        case "h":
          return "fa-file-code-o";
        case "pdf":
          return "fa-file-pdf-o";
        case "zip":
          return "fa-file-zip-o";
        case "mp3":
        case "wav":
          return "fa-file-audio-o";
        case "jpg":
        case "png":
        case "gif":
        case "jpeg":
        case "tiff":
          return "fa-file-picture-o";
        case "ipa":
        case "dmg":
          return "fa-apple";
        case "apk":
          return "fa-android";
        case "exe":
          return "fa-windows";
      }
      return "fa-file-text-o"
    },
    clickFileOrDir: function (f, e) {
      // TODO: fix here tomorrow
      if (f.type == "file") {
        return true;
      }
      var reqPath = pathJoin([location.pathname, f.name]);
      loadFileOrDir(reqPath);
      e.preventDefault()
    },
    changePath: function (reqPath, e) {
      loadFileOrDir(reqPath);
      e.preventDefault()
    },
    showInfo: function (f) {
      console.log(f);
      $.ajax({
        url: pathJoin(["/-/info", location.pathname, f.name]),
        method: "GET",
        success: function (res) {
          $("#file-info-title").text(f.name);
          $("#file-info-content").text(JSON.stringify(res, null, 4));
          $("#file-info-modal").modal("show");
          // console.log(JSON.stringify(res, null, 4));
        }
      })
    },
    makeDirectory: function () {
      var name = window.prompt("Directory name?")
      console.log(name)
      if (!name) {
        return
      }
      $.ajax({
        url: pathJoin(["/-/mkdir", location.pathname]),
        data: {
          name: name,
        },
        method: "POST",
        success: function (res) {
          console.log(res)
          loadFileList()
        },
        error: function (err) {
          alert(err.responseText);
        }
      })
    },
    deletePathConfirm: function (f, e) {
      e.preventDefault();
      if (!e.altKey) { // skip confirm when alt pressed
        if (!window.confirm("Delete " + f.name + " ?")) {
          return;
        }
      }
      $.ajax({
        url: pathJoin([location.pathname, f.name]),
        method: 'DELETE',
        success: function (res) {
          loadFileList()
        },
        error: function (err) {
          alert(err.responseText);
        }
      });
    },
    updateBreadcrumb: function () {
      var pathname = decodeURI(location.pathname || "/");
      var parts = pathname.split('/');
      this.breadcrumb = [];
      if (pathname == "/") {
        return this.breadcrumb;
      }
      var i = 2;
      for (; i <= parts.length; i += 1) {
        var name = parts[i - 1];
        if (!name) {
          continue;
        }
        var path = parts.slice(0, i).join('/');
        this.breadcrumb.push({
          name: name + (i == parts.length ? ' /' : ''),
          path: path
        })
      }
      return this.breadcrumb;
    },
    loadPreviewFile: function (filepath, e) {
      if (e) {
        e.preventDefault() // may be need a switch
      }
      var that = this;
      $.getJSON(pathJoin(['/-/info', location.pathname]))
        .then(function (res) {
          console.log(res);
          that.preview.filename = res.name;
          that.preview.filesize = res.size;
          return $.ajax({
            url: '/' + res.path,
            dataType: 'text',
          });
        })
        .then(function (res) {
          console.log(res)
          that.preview.contentHTML = '
' + res + '
';
          console.log("Finally")
        })
        .done(function (res) {
          console.log("done", res)
        });
    },
    loadAll: function () {
      // TODO: move loadFileList here
    },
  }
})

window.onpopstate = function (event) {
  if (location.search.match(/\?search=/)) {
    location.reload();
    return;
  }
  loadFileList()
}

function loadFileOrDir(reqPath) {
  window.history.pushState({}, "", reqPath);
  loadFileList(reqPath)
}

function loadFileList(pathname) {
  var pathname = pathname || location.pathname;
  // console.log("load filelist:", pathname)
  if (getQueryString("raw") !== "false") { // not a file preview
    let sep = pathname.indexOf("?") === -1 ? "?" : "&"
    $.ajax({
      url: pathname + sep + "json=true",
      dataType: "json",
      cache: false,
      success: function (res) {
        res.files = _.sortBy(res.files, function (f) {
          var weight = f.type == 'dir' ? 1000 : 1;
          return -weight * f.mtime;
        })

        vm.files = res.files;
        vm.auth = res.auth;
      },
      error: function (err) {
        console.error(err)
      },
    });

  }

  vm.updateBreadcrumb();
  vm.previewMode = getQueryString("raw") == "false";
  if (vm.previewMode) {
    vm.loadPreviewFile();
  }
}

Vue.filter('fromNow', function (value) {
  return moment(value).fromNow();
})

Vue.filter('formatBytes', function (value) {
  var bytes = parseFloat(value);
  if (bytes < 0) return "-";
  else if (bytes < 1024) return bytes + " B";
  else if (bytes < 1048576) return (bytes / 1024).toFixed(0) + " KB";
  else if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + " MB";
  else return (bytes / 1073741824).toFixed(1) + " GB";
})

$(function () {
  $.scrollUp({
    scrollText: '', // text are defined in css
  });

  // For page first loading
  loadFileList(location.pathname + location.search)

  // update version
  $.getJSON("/-/sysinfo", function (res) {
    vm.version = res.version;
  })

  var clipboard = new Clipboard('.btn');
  clipboard.on('success', function (e) {
    console.info('Action:', e.action);
    console.info('Text:', e.text);
    console.info('Trigger:', e.trigger);
    $(e.trigger)
      .tooltip('show')
      .mouseleave(function () {
        $(this).tooltip('hide');
      })

    e.clearSelection();
  });
});
<|endoftext|>


<commit_before>var should = require('should');
var gutil = require('gulp-util');
var stylus = require('../');
var fs = require('fs');

// test plugins
var nib = require('nib');

require('mocha');

describe('gulpstylus', function(){
	it('should render stylus .styl to CSS .css', function(done){
		var stylusStream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stylusStream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/expected/normal.css', 'utf8'));
			done();
		});
		stylusStream.write(fakeFile);

	});

	it ('should uitlize nib when possible', function(done){
		var stream = stylus({use: nib()});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/nib-using.styl',
			contents: fs.readFileSync('test/fixtures/nib-using.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/nib-using.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should compress when called', function(done){
		var stream = stylus({compress: true});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/compressed.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should import other .styl files', function(done){
		var stream = stylus({import: __dirname + '/fixtures/one.styl'});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/imported.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should define variables in .styl files', function(done){
		var stream = stylus({define: {'white': '#fff'}});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/define.styl',
			contents: fs.readFileSync('test/fixtures/define.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/define.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it('should skip css files', function(done){
		var stylusStream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/ie8.css',
			contents: fs.readFileSync('test/fixtures/ie8.css')
		});

		stylusStream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/fixtures/ie8.css', 'utf8'));
			done();
		});
		stylusStream.write(fakeFile);

	});

	it('should throw on parse error', function(done) {
	    var stylusStream = stylus();

	    var file = 'test/fixtures/error.styl';

	    var fakeFile = new gutil.File({
	        base: 'test/fixtures',
	        cwd: 'test/',
	        path: file,
	        contents: fs.readFileSync(file)
	    });

        stylusStream.on('error', function(err) {
            should.exist(err);
            err.toString().should.match(/ParseError/);
            done();
        });

        stylusStream.write(fakeFile);
    });
});
<commit_msg>error tests<commit_after>var should = require('should');
var gutil = require('gulp-util');
var stylus = require('../');
var fs = require('fs');

// test plugins
var nib = require('nib');

require('mocha');

describe('gulpstylus', function(){
	it('should render stylus .styl to CSS .css', function(done){
		var stream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/expected/normal.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();

	});

	it ('should uitlize nib when possible', function(done){
		var stream = stylus({use: nib()});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/nib-using.styl',
			contents: fs.readFileSync('test/fixtures/nib-using.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/nib-using.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should compress when called', function(done){
		var stream = stylus({compress: true});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/compressed.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should import other .styl files', function(done){
		var stream = stylus({import: __dirname + '/fixtures/one.styl'});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/normal.styl',
			contents: fs.readFileSync('test/fixtures/normal.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/imported.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it ('should define variables in .styl files', function(done){
		var stream = stylus({define: {'white': '#fff'}});
		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/define.styl',
			contents: fs.readFileSync('test/fixtures/define.styl')
		});

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);

			String(newFile.contents).should.equal(fs.readFileSync('test/expected/define.css', 'utf8'));
			done();
		});

		stream.write(fakeFile);
		stream.end();
	});

	it('should skip css files', function(done){
		var stream = stylus();

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: 'test/fixtures/ie8.css',
			contents: fs.readFileSync('test/fixtures/ie8.css')
		});

		stream.once('data', function(newFile){
			should.exist(newFile);
			should.exist(newFile.contents);
			String(newFile.contents).should.equal(fs.readFileSync('test/fixtures/ie8.css', 'utf8'));
			done();
		});
		stream.write(fakeFile);
		stream.end();

	});

	it('should throw on parse error', function(done) {
		var stream = stylus();

		var file = 'test/fixtures/error.styl';

		var fakeFile = new gutil.File({
			base: 'test/fixtures',
			cwd: 'test/',
			path: file,
			contents: fs.readFileSync(file)
		});

		stream.on('error', function(err) {
			should.exist(err);
			err.toString().should.match(/ParseError/);
			done();
		});
    stream.write(fakeFile);
    stream.end();

    });
});
<|endoftext|>


<commit_before>/**
 * original copyright: Andy Grom (https://github.com/AndyGrom/loadOnDemand)
 * rewrite by: Olivier Combe (https://github.com/ocombe/ocLazyLoad)
 */

(function() {
	'use strict';
	var regModules = ['ng'];

	var ocLazyLoad = angular.module('oc.lazyLoad', ['ng']);

	ocLazyLoad.provider('$ocLazyLoad', ['$controllerProvider', '$provide', '$compileProvider', '$filterProvider', '$injector',
	                                    function($controllerProvider, $provide, $compileProvider, $filterProvider, $injector) {

		                                    var modules = {},
			                                    asyncLoader,
			                                    templates = [],
			                                    providers = {
				                                    $controllerProvider: $controllerProvider,
				                                    $compileProvider: $compileProvider,
				                                    $filterProvider: $filterProvider,
				                                    $provide: $provide, // other things
				                                    $injector: $injector
			                                    };

		                                    this.$get = ['$timeout', '$log', '$q', '$templateCache', '$http', '$rootElement', function($timeout, $log, $q, $templateCache, $http, $rootElement) {
												var instanceInjector;
												//Make this lazy because at the moment that $get() is called the instance
												//injector hasn't been assigned to the rootElement yet:
												providers.getInstanceInjector = function() {
													return (instanceInjector) ? instanceInjector : (instanceInjector = $rootElement.data('$injector'));
												}
			                                    return {
				                                    getModuleConfig: function(name) {
					                                    if(!modules[name]) {
						                                    return null;
					                                    }
					                                    return modules[name];
				                                    },

				                                    setModuleConfig: function(module) {
					                                    modules[module.name] = module;
					                                    return module;
				                                    },

				                                    getModules: function() {
					                                    return regModules;
				                                    },

				                                    getModuleName: function (module) {
					                                    var moduleName;
					                                    if (typeof module === 'string') {
						                                    moduleName = module;
					                                    } else if (typeof module === 'object' && module.hasOwnProperty('name') && typeof module.name === 'string') {
						                                    moduleName = module.name;
					                                    } else {
						                                    moduleName = undefined;
					                                    }
					                                    return moduleName;
				                                    },

				                                    loadTemplateFile: function(urls, config) {
					                                    if(angular.isString(urls)) {
						                                    urls = [urls];
					                                    }
					                                    var promisesList = [];
					                                    angular.forEach(urls, function(url) {
						                                    var deferred = $q.defer();
						                                    promisesList.push(deferred.promise);
						                                    if(templates.indexOf(url) === -1 || (angular.isDefined(config) && config.cache === false)) {
							                                    $http.get(url, config).success(function(data) {
								                                    angular.forEach(angular.element(data), function(node) {
									                                    if(node.nodeName === 'SCRIPT' && node.type === 'text/ng-template') {
										                                    $templateCache.put(node.id, node.innerHTML);
									                                    }
								                                    });
								                                    templates.push(url);
								                                    deferred.resolve();
							                                    }).error(function(data) {
								                                    $log.error('Error load template "' + url + '": ' + data);
							                                    });
						                                    } else {
							                                    deferred.resolve();
						                                    }
					                                    });
					                                    return $q.all(promisesList);
				                                    },

				                                    load: function(module) {
					                                    var self = this,
						                                    config = null,
						                                    moduleCache = [],
						                                    deferred = $q.defer(),
						                                    moduleName,
						                                    errText;

					                                    moduleName = self.getModuleName(module);

					                                    // If this module has been loaded before, re-use it.
					                                    if (moduleExists(moduleName)) {
						                                    moduleCache.push(moduleName);
						                                    deferred.resolve();
						                                    return deferred.promise;
					                                    }

					                                    // Get or Set a configuration depending on what was passed in
					                                    if (typeof module === 'string') {
						                                    config = self.getModuleConfig(module);
					                                    } else if (typeof module === 'object') {
						                                    config = self.setModuleConfig(module);
					                                    }

					                                    if (config === null) {
						                                    errText = 'Module "' + moduleName + '" is not configured, cannot load.';
						                                    $log.error(errText);
						                                    throw errText;
					                                    }

					                                    moduleCache.push = function (value) {
						                                    if (this.indexOf(value) === -1) {
							                                    Array.prototype.push.apply(this, arguments);
						                                    }
					                                    };

					                                    function loadDependencies(module) {
						                                    var moduleName,
							                                    loadedModule,
							                                    requires,
							                                    promisesList = [],
							                                    load_complete;

						                                    moduleName = self.getModuleName(module);
						                                    loadedModule = angular.module(moduleName);
						                                    requires = getRequires(loadedModule);

						                                    angular.forEach(requires, function (requireEntry) {
							                                    var config,
								                                    deferredDep;

							                                    // If no configuration is provided, try and find one from a previous load.
							                                    // If there isn't one, bail and let the normal flow run
							                                    if (typeof requireEntry === 'string') {
								                                    config = self.getModuleConfig(requireEntry);
								                                    if (config === null) {
									                                    moduleCache.push(requireEntry); // We don't know about this module, but something else might, so push it anyway.
									                                    return;
								                                    }
								                                    requireEntry = config;
							                                    }

							                                    // Check if this dependency has been loaded previously or is already in the moduleCache
							                                    if (moduleExists(requireEntry.name) || moduleCache.indexOf(requireEntry.name) !== -1) {
								                                    if (typeof module !== 'string') {
									                                    // The dependency exists, but it's being redefined, not inherited by a simple string reference, raise a warning and ignore the new config.
									                                    // TODO: This could be made smarter. There's no checking here yet to determine if the configurations are actually different.
									                                    $log.warn('Module "', moduleName, '" attempted to redefine configuration for dependency "', requireEntry.name, '"\nExisting:', self.getModuleConfig(requireEntry.name), 'Ignored:', requireEntry);
								                                    }
								                                    return;
							                                    } else if (typeof requireEntry === 'object') {
								                                    // The dependency doesn't exist in the module cache and is a new conifguration, so store and push it.
								                                    self.setModuleConfig(requireEntry);
								                                    moduleCache.push(requireEntry.name);
							                                    }

							                                    // Check if the dependency has any files that need to be loaded. If there are, push a new promise to the promise list.
							                                    if (requireEntry.hasOwnProperty('files') && requireEntry.files.length !== 0) {
								                                    deferredDep = $q.defer();
								                                    if (requireEntry.files) {
									                                    promisesList.push(deferredDep.promise);
									                                    asyncLoader(requireEntry.files, function () {
										                                    loadDependencies(requireEntry).then(function () {
											                                    deferredDep.resolve();
										                                    });
									                                    });
								                                    }
							                                    }
						                                    });

						                                    // Create a wrapper promise to watch the promise list and resolve it once everything is done.
						                                    load_complete = $q.defer();
						                                    $q.all(promisesList).then(function () {
							                                    load_complete.resolve();
						                                    });

						                                    return load_complete.promise;
					                                    }

					                                    asyncLoader(config.files, function () {
						                                    moduleCache.push(moduleName);
						                                    loadDependencies(moduleName).then(function () {
							                                    register(providers, moduleCache, $log);
							                                    $timeout(function () {
								                                    deferred.resolve(config);
							                                    });
						                                    });
					                                    });

					                                    return deferred.promise;
				                                    }
			                                    };
		                                    }];

		                                    this.config = function(config) {
			                                    if(typeof config.asyncLoader === 'undefined') {
				                                    throw('You need to define an async loader such as requireJS or script.js');
			                                    }

			                                    asyncLoader = config.asyncLoader;
			                                    init(angular.element(window.document));

			                                    if(config.loadedModules) {
				                                    var addRegModule = function(loadedModule) {
					                                    if(regModules.indexOf(loadedModule) < 0) {
						                                    regModules.push(loadedModule);
						                                    angular.forEach(angular.module(loadedModule).requires, addRegModule);
					                                    }
				                                    };
				                                    angular.forEach(config.loadedModules, addRegModule);
			                                    }

			                                    if(config.modules) {
				                                    if(angular.isArray(config.modules)) {
					                                    angular.forEach(config.modules, function(moduleConfig) {
						                                    modules[moduleConfig.name] = moduleConfig;
					                                    });
				                                    } else {
					                                    modules[config.modules.name] = config.modules;
				                                    }
			                                    }
		                                    };
	                                    }]);

	ocLazyLoad.directive('ocLazyLoad', ['$http', '$log', '$ocLazyLoad', '$compile', '$timeout', '$templateCache',
	                                    function($http, $log, $ocLazyLoad, $compile, $timeout, $templateCache) {
		                                    return {
			                                    link: function(scope, element, attr) {
				                                    var childScope;
				                                    var onloadExp = scope.$eval(attr.ocLazyLoad).onload || '';

				                                    /**
				                                     * Destroy the current scope of this element and empty the html
				                                     */
				                                    function clearContent() {
					                                    if(childScope) {
						                                    childScope.$destroy();
						                                    childScope = null;
					                                    }
					                                    element.html('');
				                                    }

				                                    /**
				                                     * Load a template from cache or url
				                                     * @param url
				                                     * @param callback
				                                     */
				                                    function loadTemplate(url, callback) {
					                                    var view;

					                                    if(typeof(view = $templateCache.get(url)) !== 'undefined') {
						                                    callback(view);
					                                    } else {
						                                    $http.get(url)
							                                    .success(function(data) {
								                                    $templateCache.put('view:' + url, data);
								                                    callback(data);
							                                    })
							                                    .error(function(data) {
								                                    $log.error('Error load template "' + url + '": ' + data);
							                                    });
					                                    }
				                                    }

				                                    scope.$watch(attr.ocLazyLoad, function(moduleName) {
					                                    if(moduleName) {
						                                    $ocLazyLoad.load(moduleName).then(function(moduleConfig) {
							                                    if(!moduleConfig.template) {
								                                    return;
							                                    }
							                                    loadTemplate(moduleConfig.template, function(template) {
								                                    childScope = scope.$new();
								                                    element.html(template);

								                                    var content = element.contents();
								                                    var linkFn = $compile(content);
								                                    linkFn(childScope);
								                                    childScope.$emit('$includeContentLoaded');
								                                    childScope.$eval(onloadExp);
							                                    });
						                                    });
					                                    } else {
						                                    clearContent();
					                                    }
				                                    });
			                                    }
		                                    };
	                                    }]);

	/**
	 * Get the list of required modules/services/... for this module
	 * @param module
	 * @returns {Array}
	 */
	function getRequires(module) {
		var requires = [];
		angular.forEach(module.requires, function(requireModule) {
			if(regModules.indexOf(requireModule) === -1) {
				requires.push(requireModule);
			}
		});
		return requires;
	}

	/**
	 * Check if a module exists
	 * @param moduleName
	 * @returns {boolean}
	 */
	function moduleExists(moduleName) {
		try {
			angular.module(moduleName);
		} catch(e) {
			if(/No module/.test(e) || (e.message.indexOf('$injector:nomod') > -1)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Register a new module and load it
	 * @param providers
	 * @param registerModules
	 * @param $log
	 * @returns {*}
	 */
	function register(providers, registerModules, $log) {
		if(registerModules) {
			var i, ii, k, invokeQueue, moduleName, moduleFn, invokeArgs, provider, runBlocks = [];
			for(k = registerModules.length - 1; k >= 0; k--) {
				moduleName = registerModules[k];
				if (typeof moduleName !== 'string') {
					moduleName = getModuleName(moduleName);
				}
				if ((!moduleName) || (regModules.indexOf(moduleName) > -1)) {
					continue;
				}
				regModules.push(moduleName);
				moduleFn = angular.module(moduleName);
				runBlocks = runBlocks.concat(moduleFn._runBlocks);
				try {
					for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
						invokeArgs = invokeQueue[i];
						if (angular.isArray(invokeArgs)) {
							if(providers.hasOwnProperty(invokeArgs[0])) {
								provider = providers[invokeArgs[0]];
							} else {
								return $log.error('unsupported provider ' + invokeArgs[0]);
							}
							provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
						}
					}
				} catch(e) {
					if(e.message) {
						e.message += ' from ' + moduleName;
					}
					$log.error(e.message);
					throw e;
				}
				register(providers, moduleFn.requires, $log);
				registerModules.pop();
			}
			var instanceInjector = providers.getInstanceInjector();
			angular.forEach(runBlocks, function(fn) {
				try {
					instanceInjector.invoke(fn);
				} catch(e) {
					if(e.message) {
						e.message += ' from ' + moduleName;
					}
					$log.error(e.message);
				}
			});
		}
		return null;
	}

	function getModuleName(dependencyObject) {
		return (dependencyObject.name) ? dependencyObject.name : null;
	}

	/**
	 * Get the list of existing registered modules
	 * @param element
	 */
	function init(element) {
		var elements = [element],
			appElement,
			module,
			names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
			NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;

		function append(elm) {
			return (elm && elements.push(elm));
		}

		angular.forEach(names, function(name) {
			names[name] = true;
			append(document.getElementById(name));
			name = name.replace(':', '\\:');
			if(element.querySelectorAll) {
				angular.forEach(element.querySelectorAll('.' + name), append);
				angular.forEach(element.querySelectorAll('.' + name + '\\:'), append);
				angular.forEach(element.querySelectorAll('[' + name + ']'), append);
			}
		});

		angular.forEach(elements, function(elm) {
			if(!appElement) {
				var className = ' ' + element.className + ' ';
				var match = NG_APP_CLASS_REGEXP.exec(className);
				if(match) {
					appElement = elm;
					module = (match[2] || '').replace(/\s+/g, ',');
				} else {
					angular.forEach(elm.attributes, function(attr) {
						if(!appElement && names[attr.name]) {
							appElement = elm;
							module = attr.value;
						}
					});
				}
			}
		});

		if(appElement) {
			(function addReg(module) {
				if(regModules.indexOf(module) === -1) {
					regModules.push(module);
					var mainModule = angular.module(module);
					angular.forEach(mainModule.requires, addReg);
				}
			})(module);
		}
	}
})();
<commit_msg>Code style: variable name/semicolon<commit_after>/**
 * original copyright: Andy Grom (https://github.com/AndyGrom/loadOnDemand)
 * rewrite by: Olivier Combe (https://github.com/ocombe/ocLazyLoad)
 */

(function() {
	'use strict';
	var regModules = ['ng'];

	var ocLazyLoad = angular.module('oc.lazyLoad', ['ng']);

	ocLazyLoad.provider('$ocLazyLoad', ['$controllerProvider', '$provide', '$compileProvider', '$filterProvider', '$injector',
	                                    function($controllerProvider, $provide, $compileProvider, $filterProvider, $injector) {

		                                    var modules = {},
			                                    asyncLoader,
			                                    templates = [],
			                                    providers = {
				                                    $controllerProvider: $controllerProvider,
				                                    $compileProvider: $compileProvider,
				                                    $filterProvider: $filterProvider,
				                                    $provide: $provide, // other things
				                                    $injector: $injector
			                                    };

		                                    this.$get = ['$timeout', '$log', '$q', '$templateCache', '$http', '$rootElement', function($timeout, $log, $q, $templateCache, $http, $rootElement) {
												var instanceInjector;
												//Make this lazy because at the moment that $get() is called the instance
												//injector hasn't been assigned to the rootElement yet:
												providers.getInstanceInjector = function() {
													return (instanceInjector) ? instanceInjector : (instanceInjector = $rootElement.data('$injector'));
												};
			                                    return {
				                                    getModuleConfig: function(name) {
					                                    if(!modules[name]) {
						                                    return null;
					                                    }
					                                    return modules[name];
				                                    },

				                                    setModuleConfig: function(module) {
					                                    modules[module.name] = module;
					                                    return module;
				                                    },

				                                    getModules: function() {
					                                    return regModules;
				                                    },

				                                    getModuleName: function (module) {
					                                    var moduleName;
					                                    if (typeof module === 'string') {
						                                    moduleName = module;
					                                    } else if (typeof module === 'object' && module.hasOwnProperty('name') && typeof module.name === 'string') {
						                                    moduleName = module.name;
					                                    } else {
						                                    moduleName = undefined;
					                                    }
					                                    return moduleName;
				                                    },

				                                    loadTemplateFile: function(urls, config) {
					                                    if(angular.isString(urls)) {
						                                    urls = [urls];
					                                    }
					                                    var promisesList = [];
					                                    angular.forEach(urls, function(url) {
						                                    var deferred = $q.defer();
						                                    promisesList.push(deferred.promise);
						                                    if(templates.indexOf(url) === -1 || (angular.isDefined(config) && config.cache === false)) {
							                                    $http.get(url, config).success(function(data) {
								                                    angular.forEach(angular.element(data), function(node) {
									                                    if(node.nodeName === 'SCRIPT' && node.type === 'text/ng-template') {
										                                    $templateCache.put(node.id, node.innerHTML);
									                                    }
								                                    });
								                                    templates.push(url);
								                                    deferred.resolve();
							                                    }).error(function(data) {
								                                    $log.error('Error load template "' + url + '": ' + data);
							                                    });
						                                    } else {
							                                    deferred.resolve();
						                                    }
					                                    });
					                                    return $q.all(promisesList);
				                                    },

				                                    load: function(module) {
					                                    var self = this,
						                                    config = null,
						                                    moduleCache = [],
						                                    deferred = $q.defer(),
						                                    moduleName,
						                                    errText;

					                                    moduleName = self.getModuleName(module);

					                                    // If this module has been loaded before, re-use it.
					                                    if (moduleExists(moduleName)) {
						                                    moduleCache.push(moduleName);
						                                    deferred.resolve();
						                                    return deferred.promise;
					                                    }

					                                    // Get or Set a configuration depending on what was passed in
					                                    if (typeof module === 'string') {
						                                    config = self.getModuleConfig(module);
					                                    } else if (typeof module === 'object') {
						                                    config = self.setModuleConfig(module);
					                                    }

					                                    if (config === null) {
						                                    errText = 'Module "' + moduleName + '" is not configured, cannot load.';
						                                    $log.error(errText);
						                                    throw errText;
					                                    }

					                                    moduleCache.push = function (value) {
						                                    if (this.indexOf(value) === -1) {
							                                    Array.prototype.push.apply(this, arguments);
						                                    }
					                                    };

					                                    function loadDependencies(module) {
						                                    var moduleName,
							                                    loadedModule,
							                                    requires,
							                                    promisesList = [],
							                                    loadComplete;

						                                    moduleName = self.getModuleName(module);
						                                    loadedModule = angular.module(moduleName);
						                                    requires = getRequires(loadedModule);

						                                    angular.forEach(requires, function (requireEntry) {
							                                    var config,
								                                    deferredDep;

							                                    // If no configuration is provided, try and find one from a previous load.
							                                    // If there isn't one, bail and let the normal flow run
							                                    if (typeof requireEntry === 'string') {
								                                    config = self.getModuleConfig(requireEntry);
								                                    if (config === null) {
									                                    moduleCache.push(requireEntry); // We don't know about this module, but something else might, so push it anyway.
									                                    return;
								                                    }
								                                    requireEntry = config;
							                                    }

							                                    // Check if this dependency has been loaded previously or is already in the moduleCache
							                                    if (moduleExists(requireEntry.name) || moduleCache.indexOf(requireEntry.name) !== -1) {
								                                    if (typeof module !== 'string') {
									                                    // The dependency exists, but it's being redefined, not inherited by a simple string reference, raise a warning and ignore the new config.
									                                    // TODO: This could be made smarter. There's no checking here yet to determine if the configurations are actually different.
									                                    $log.warn('Module "', moduleName, '" attempted to redefine configuration for dependency "', requireEntry.name, '"\nExisting:', self.getModuleConfig(requireEntry.name), 'Ignored:', requireEntry);
								                                    }
								                                    return;
							                                    } else if (typeof requireEntry === 'object') {
								                                    // The dependency doesn't exist in the module cache and is a new conifguration, so store and push it.
								                                    self.setModuleConfig(requireEntry);
								                                    moduleCache.push(requireEntry.name);
							                                    }

							                                    // Check if the dependency has any files that need to be loaded. If there are, push a new promise to the promise list.
							                                    if (requireEntry.hasOwnProperty('files') && requireEntry.files.length !== 0) {
								                                    deferredDep = $q.defer();
								                                    if (requireEntry.files) {
									                                    promisesList.push(deferredDep.promise);
									                                    asyncLoader(requireEntry.files, function () {
										                                    loadDependencies(requireEntry).then(function () {
											                                    deferredDep.resolve();
										                                    });
									                                    });
								                                    }
							                                    }
						                                    });

						                                    // Create a wrapper promise to watch the promise list and resolve it once everything is done.
						                                    loadComplete = $q.defer();
						                                    $q.all(promisesList).then(function () {
							                                    loadComplete.resolve();
						                                    });

						                                    return loadComplete.promise;
					                                    }

					                                    asyncLoader(config.files, function () {
						                                    moduleCache.push(moduleName);
						                                    loadDependencies(moduleName).then(function () {
							                                    register(providers, moduleCache, $log);
							                                    $timeout(function () {
								                                    deferred.resolve(config);
							                                    });
						                                    });
					                                    });

					                                    return deferred.promise;
				                                    }
			                                    };
		                                    }];

		                                    this.config = function(config) {
			                                    if(typeof config.asyncLoader === 'undefined') {
				                                    throw('You need to define an async loader such as requireJS or script.js');
			                                    }

			                                    asyncLoader = config.asyncLoader;
			                                    init(angular.element(window.document));

			                                    if(config.loadedModules) {
				                                    var addRegModule = function(loadedModule) {
					                                    if(regModules.indexOf(loadedModule) < 0) {
						                                    regModules.push(loadedModule);
						                                    angular.forEach(angular.module(loadedModule).requires, addRegModule);
					                                    }
				                                    };
				                                    angular.forEach(config.loadedModules, addRegModule);
			                                    }

			                                    if(config.modules) {
				                                    if(angular.isArray(config.modules)) {
					                                    angular.forEach(config.modules, function(moduleConfig) {
						                                    modules[moduleConfig.name] = moduleConfig;
					                                    });
				                                    } else {
					                                    modules[config.modules.name] = config.modules;
				                                    }
			                                    }
		                                    };
	                                    }]);

	ocLazyLoad.directive('ocLazyLoad', ['$http', '$log', '$ocLazyLoad', '$compile', '$timeout', '$templateCache',
	                                    function($http, $log, $ocLazyLoad, $compile, $timeout, $templateCache) {
		                                    return {
			                                    link: function(scope, element, attr) {
				                                    var childScope;
				                                    var onloadExp = scope.$eval(attr.ocLazyLoad).onload || '';

				                                    /**
				                                     * Destroy the current scope of this element and empty the html
				                                     */
				                                    function clearContent() {
					                                    if(childScope) {
						                                    childScope.$destroy();
						                                    childScope = null;
					                                    }
					                                    element.html('');
				                                    }

				                                    /**
				                                     * Load a template from cache or url
				                                     * @param url
				                                     * @param callback
				                                     */
				                                    function loadTemplate(url, callback) {
					                                    var view;

					                                    if(typeof(view = $templateCache.get(url)) !== 'undefined') {
						                                    callback(view);
					                                    } else {
						                                    $http.get(url)
							                                    .success(function(data) {
								                                    $templateCache.put('view:' + url, data);
								                                    callback(data);
							                                    })
							                                    .error(function(data) {
								                                    $log.error('Error load template "' + url + '": ' + data);
							                                    });
					                                    }
				                                    }

				                                    scope.$watch(attr.ocLazyLoad, function(moduleName) {
					                                    if(moduleName) {
						                                    $ocLazyLoad.load(moduleName).then(function(moduleConfig) {
							                                    if(!moduleConfig.template) {
								                                    return;
							                                    }
							                                    loadTemplate(moduleConfig.template, function(template) {
								                                    childScope = scope.$new();
								                                    element.html(template);

								                                    var content = element.contents();
								                                    var linkFn = $compile(content);
								                                    linkFn(childScope);
								                                    childScope.$emit('$includeContentLoaded');
								                                    childScope.$eval(onloadExp);
							                                    });
						                                    });
					                                    } else {
						                                    clearContent();
					                                    }
				                                    });
			                                    }
		                                    };
	                                    }]);

	/**
	 * Get the list of required modules/services/... for this module
	 * @param module
	 * @returns {Array}
	 */
	function getRequires(module) {
		var requires = [];
		angular.forEach(module.requires, function(requireModule) {
			if(regModules.indexOf(requireModule) === -1) {
				requires.push(requireModule);
			}
		});
		return requires;
	}

	/**
	 * Check if a module exists
	 * @param moduleName
	 * @returns {boolean}
	 */
	function moduleExists(moduleName) {
		try {
			angular.module(moduleName);
		} catch(e) {
			if(/No module/.test(e) || (e.message.indexOf('$injector:nomod') > -1)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Register a new module and load it
	 * @param providers
	 * @param registerModules
	 * @param $log
	 * @returns {*}
	 */
	function register(providers, registerModules, $log) {
		if(registerModules) {
			var i, ii, k, invokeQueue, moduleName, moduleFn, invokeArgs, provider, runBlocks = [];
			for(k = registerModules.length - 1; k >= 0; k--) {
				moduleName = registerModules[k];
				if (typeof moduleName !== 'string') {
					moduleName = getModuleName(moduleName);
				}
				if ((!moduleName) || (regModules.indexOf(moduleName) > -1)) {
					continue;
				}
				regModules.push(moduleName);
				moduleFn = angular.module(moduleName);
				runBlocks = runBlocks.concat(moduleFn._runBlocks);
				try {
					for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
						invokeArgs = invokeQueue[i];
						if (angular.isArray(invokeArgs)) {
							if(providers.hasOwnProperty(invokeArgs[0])) {
								provider = providers[invokeArgs[0]];
							} else {
								return $log.error('unsupported provider ' + invokeArgs[0]);
							}
							provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
						}
					}
				} catch(e) {
					if(e.message) {
						e.message += ' from ' + moduleName;
					}
					$log.error(e.message);
					throw e;
				}
				register(providers, moduleFn.requires, $log);
				registerModules.pop();
			}
			var instanceInjector = providers.getInstanceInjector();
			angular.forEach(runBlocks, function(fn) {
				try {
					instanceInjector.invoke(fn);
				} catch(e) {
					if(e.message) {
						e.message += ' from ' + moduleName;
					}
					$log.error(e.message);
				}
			});
		}
		return null;
	}

	function getModuleName(dependencyObject) {
		return (dependencyObject.name) ? dependencyObject.name : null;
	}

	/**
	 * Get the list of existing registered modules
	 * @param element
	 */
	function init(element) {
		var elements = [element],
			appElement,
			module,
			names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
			NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;

		function append(elm) {
			return (elm && elements.push(elm));
		}

		angular.forEach(names, function(name) {
			names[name] = true;
			append(document.getElementById(name));
			name = name.replace(':', '\\:');
			if(element.querySelectorAll) {
				angular.forEach(element.querySelectorAll('.' + name), append);
				angular.forEach(element.querySelectorAll('.' + name + '\\:'), append);
				angular.forEach(element.querySelectorAll('[' + name + ']'), append);
			}
		});

		angular.forEach(elements, function(elm) {
			if(!appElement) {
				var className = ' ' + element.className + ' ';
				var match = NG_APP_CLASS_REGEXP.exec(className);
				if(match) {
					appElement = elm;
					module = (match[2] || '').replace(/\s+/g, ',');
				} else {
					angular.forEach(elm.attributes, function(attr) {
						if(!appElement && names[attr.name]) {
							appElement = elm;
							module = attr.value;
						}
					});
				}
			}
		});

		if(appElement) {
			(function addReg(module) {
				if(regModules.indexOf(module) === -1) {
					regModules.push(module);
					var mainModule = angular.module(module);
					angular.forEach(mainModule.requires, addReg);
				}
			})(module);
		}
	}
})();
<|endoftext|>


<commit_before>app.controller('appCtrl', function($scope, $http, $routeParams, $location, socket, Data) {
    $scope.hash = '';
    $scope.warning = false;
    $scope.warningMessage = '';
    $scope.pincode = '';

    $scope.currStatus = 0;

    /* need id input -> 0, checking id -> 1, waiting for btn -> 2, success -> 3 */
    $scope.sendPin = () => {
      let val = $scope.pincode;
      let isnum = /^\d+$/.test(val);
      if (!isnum) {
        $scope.warning = true;
        $scope.warningMessage = "Invalid Device Number: Device number must only contain numbers.";
      } else {
        $scope.currStatus = 1;
        console.log();
        socket.emit('transferID', {hash: $scope.hash, ID: $scope.pincode});
      }
    };

    socket.on('joinFailure', () => {
        $scope.warning = true;
        $scope.warningMessage = "Invalid Device Number: Device is not registered on the system. Please connect the device to the system first.";
        console.log('No device');
        $scope.currStatus = 0;
        $scope.$apply();

        /* Handle device not currently waiting on connection */
    });

    socket.on('pollWait', (data) => {
        $scope.currStatus = 2;
        $scope.$apply();
        /* Device is on the network, waiting for button presses */
        console.log('Device present, press button');
    });

    /* TODO set statte to 3 when the device button is pressed */

    /* Entry remapping */
    let tmp = $routeParams.hash;

    if (tmp !== 'home') {
        $scope.hash = tmp;
        //socket.emit('joinRoom', {ID: $scope.hash});
        console.log(tmp);
        $location.url('/app/home');
    }
});
<commit_msg>Attempt to remove duplication in socket io listeners<commit_after>app.controller('appCtrl', function($scope, $http, $routeParams, $location, socket, Data) {
    $scope.hash = '';
    $scope.warning = false;
    $scope.warningMessage = '';
    $scope.pincode = '';

    $scope.currStatus = 0;

    /* need id input -> 0, checking id -> 1, waiting for btn -> 2, success -> 3 */
    $scope.sendPin = () => {
      let val = $scope.pincode;
      let isnum = /^\d+$/.test(val);
      if (!isnum) {
        $scope.warning = true;
        $scope.warningMessage = "Invalid Device Number: Device number must only contain numbers.";
      } else {
        $scope.currStatus = 1;
        console.log();
        socket.emit('transferID', {hash: $scope.hash, ID: $scope.pincode});
      }
    };

    function joinFailure() {
        socket.on('joinFailure', () => {
            $scope.warning = true;
            $scope.warningMessage = "Invalid Device Number: Device is not registered on the system. Please connect the device to the system first.";
            console.log('No device');
            $scope.currStatus = 0;
            $scope.$apply();

            /* Handle device not currently waiting on connection */
        });
    }

    socket.removeAllListeners('joinFailure', function() {
        socket.once('joinFailure', joinFailure);
    });

    function pollWait() {
        socket.on('pollWait', (data) => {
            $scope.currStatus = 2;
            $scope.$apply();
            /* Device is on the network, waiting for button presses */
            console.log('Device present, press button');
        });
    }

    socket.removeAllListeners('pollWait', function() {
        socket.once('pollWait', pollWait);

    /* TODO set statte to 3 when the device button is pressed */

    /* Entry remapping */
    let tmp = $routeParams.hash;

    if (tmp !== 'home') {
        $scope.hash = tmp;
        socket.emit('joinRoom', {ID: $scope.hash});
        console.log(tmp);
        $location.url('/app/home');
    }
});
<|endoftext|>


<commit_before>// I'm learning so much here!

var Chunk = function( blocks, position ) {

    this.mesh = null;
    this.blocks = blocks;
    this.position = position;

};

Chunk.prototype.importData = function( data ) {

};

Chunk.prototype.exportData = function() {

};

// Gives all the blocks in this chunk a .chunk property, pointing to this chunk
Chunk.prototype.markBlocks = function() {

    this.forEachBlock( block => {
        block.chunk = this;
    });

};

Chunk.prototype.forEachBlock = function( func ) {

    for ( var x = 0; x < constants.Chunksize; x++ ) {

        for ( var y = 0; y < constants.Chunksize; y++ ) {

            for ( var z = 0; z < constants.Chunksize; z++ ) {

                func( this.blocks[ x ][ y ][ z ] );

            }

        }

    }

}

Chunk.prototype.build = function() {

    // Remove old mesh
    if ( this.mesh ) {
        scene.remove( this.mesh );
    }

    var geometry = new THREE.Geometry();

    var matrix = new THREE.Matrix4();

    var surrounded = true;
    var scope = this;

    var isExternalBlock = function( pos, v, neg ) {

        if ( neg ) {

            if ( scope.position[ v ] === 0 ) return surrounded = false;

            var p = scope.position.clone();
            var cPos = pos.clone();

            p[ v ] -= 1;
            cPos[ v ] = constants.Chunksize - 1;

            if ( !game.world.level.chunks[ p.x ][ p.y ][ p.z ]
                .blocks[ cPos.x ][ cPos.y ][ cPos.z ].id ) {
                    return surrounded = false;
            }
            return true;

        } else {

            if ( scope.position[ v ] === game.world.level.chunkSize[ v ] - 1 ) return surrounded = false;

            var p = scope.position.clone();
            var cPos = pos.clone();

            p[ v ] += 1;
            cPos[ v ] = 0;

            if ( !game.world.level.chunks[ p.x ][ p.y ][ p.z ]
                .blocks[ cPos.x ][ cPos.y ][ cPos.z ].id ) {
                    return surrounded = false;
            }
            return true;

        }

    };

    var isBlock = function( pos, v, val ) {

        if ( val < 0 ) {
            if ( pos[ v ] === 0 ) return isExternalBlock( pos, v, true );
        } else {
            if ( pos[ v ] === constants.Chunksize - 1 ) return isExternalBlock( pos, v, false );
        }

        var p = new THREE.Vector3( pos.x, pos.y, pos.z );
        p[ v ] += val;

        if ( !scope.blocks[ p.x ][ p.y ][ p.z ].id ) {
            return surrounded = false;
        }
        return true;

    };

    for ( var x = 0; x < constants.Chunksize; x++ ) {
        for ( var y = 0; y < constants.Chunksize; y++ ) {
            for ( var z = 0; z < constants.Chunksize; z++ ) {

                var block = this.blocks[ x ][ y ][ z ];

                // Air
                if ( !block.id ) continue;

                surrounded = true;
                var pos = new THREE.Vector3( x, y, z );

                isBlock( pos, 'x', -1 );
                isBlock( pos, 'x', 1 );
                isBlock( pos, 'y', -1 );
                isBlock( pos, 'y', 1 );
                isBlock( pos, 'z', -1 );
                isBlock( pos, 'z', 1 );

                if ( surrounded ) {
                    continue;
                }

                // TODO: Merge only blocks that are visible
                // TODO: Merge only faces that are visible

                matrix.makeTranslation(
                    block.position.x,
                    block.position.y,
                    block.position.z
                );

                geometry.merge(
                    blockdata.Meshes[ block.id ].geometry,
                    matrix
                );

            }
        }
    }

    this.mesh = new THREE.Mesh( geometry, blockdata.ChunkMaterial );
    scene.add( this.mesh );

};
<commit_msg>No longer merge faces that are not visible<commit_after>// I'm learning so much here!

var Chunk = function( blocks, position ) {

    this.mesh = null;
    this.blocks = blocks;
    this.position = position;

};

Chunk.prototype.importData = function( data ) {

};

Chunk.prototype.exportData = function() {

};

// Gives all the blocks in this chunk a .chunk property, pointing to this chunk
Chunk.prototype.markBlocks = function() {

    this.forEachBlock( block => {
        block.chunk = this;
    });

};

Chunk.prototype.forEachBlock = function( func ) {

    for ( var x = 0; x < constants.Chunksize; x++ ) {

        for ( var y = 0; y < constants.Chunksize; y++ ) {

            for ( var z = 0; z < constants.Chunksize; z++ ) {

                func( this.blocks[ x ][ y ][ z ] );

            }

        }

    }

}

Chunk.prototype.build = function() {

    // Remove old mesh
    if ( this.mesh ) {
        scene.remove( this.mesh );
    }

    var geometry = new THREE.Geometry();

    var matrix = new THREE.Matrix4();

    var scope = this;

    var isExternalBlock = function( pos, v, neg ) {

        if ( neg ) {

            if ( scope.position[ v ] === 0 ) return false;

            var p = scope.position.clone();
            var cPos = pos.clone();

            p[ v ] -= 1;
            cPos[ v ] = constants.Chunksize - 1;

            if ( !game.world.level.chunks[ p.x ][ p.y ][ p.z ]
                .blocks[ cPos.x ][ cPos.y ][ cPos.z ].id ) {
                    return false;
            }
            return true;

        } else {

            if ( scope.position[ v ] === game.world.level.chunkSize[ v ] - 1 ) return false;

            var p = scope.position.clone();
            var cPos = pos.clone();

            p[ v ] += 1;
            cPos[ v ] = 0;

            if ( !game.world.level.chunks[ p.x ][ p.y ][ p.z ]
                .blocks[ cPos.x ][ cPos.y ][ cPos.z ].id ) {
                    return false;
            }
            return true;

        }

    };

    var isBlock = function( pos, v, val ) {

        if ( val < 0 ) {
            if ( pos[ v ] === 0 ) return isExternalBlock( pos, v, true );
        } else {
            if ( pos[ v ] === constants.Chunksize - 1 ) return isExternalBlock( pos, v, false );
        }

        var p = new THREE.Vector3( pos.x, pos.y, pos.z );
        p[ v ] += val;

        if ( !scope.blocks[ p.x ][ p.y ][ p.z ].id ) {
            return false;
        }
        return true;

    };

    var adjustGeometry = function( geo, pos ) {

        var toDelete = [ ];

        for ( var i = 0; i < geo.faces.length; i += 2 ) {

            var normal = geo.faces[ i ].normal;

            var v = 'x';
            if ( normal.y ) v = 'y';
            else if ( normal.z ) v = 'z';

            val = normal[ v ];

            // Block already there, may remove now
            if ( isBlock( pos, v, val ) ) {
                toDelete.push( i );
            }

        }

        if ( toDelete.length * 2 == geo.faces.length ) {
            return true;
        }

        for ( var i = 0; i < toDelete.length; i++ ) {
            delete geo.faces[ toDelete[ i ] ];
            delete geo.faces[ toDelete[ i ] + 1 ];
        }

        // uncomment for lolz
        //delete geo.faces[ 5 ];

        geo.faces = geo.faces.filter( v => v );
        geo.elementsNeedUpdate = true;

        return false;

    };

    for ( var x = 0; x < constants.Chunksize; x++ ) {
        for ( var y = 0; y < constants.Chunksize; y++ ) {
            for ( var z = 0; z < constants.Chunksize; z++ ) {

                var block = this.blocks[ x ][ y ][ z ];

                // Air
                if ( !block.id ) continue;

                surrounded = true;
                var pos = new THREE.Vector3( x, y, z );
                var bGeometry = blockdata.Meshes[ block.id ].geometry.clone();

                if ( adjustGeometry( bGeometry, pos ) ) {
                    continue;
                }

                // TODO: Merge only blocks that are visible
                // TODO: Merge only faces that are visible

                matrix.makeTranslation(
                    block.position.x,
                    block.position.y,
                    block.position.z
                );

                geometry.merge(
                    //blockdata.Meshes[ block.id ].geometry,
                    bGeometry,
                    matrix
                );

            }
        }
    }

    this.mesh = new THREE.Mesh( geometry, blockdata.ChunkMaterial );
    scene.add( this.mesh );

};
<|endoftext|>


<commit_before>const jwt = require('jsonwebtoken')
const fetch = require('node-fetch')

function getAuthToken(req) {
  return new Promise(function(resolve, reject) {
    const authHeader = req.get('Authorization')
    if (authHeader === undefined) {
      reject(new Error('No authorization header'))
    }

    if (authHeader.slice(0, 7) !== 'Bearer ') {
      reject(new Error('Malformed authorization header'))
    }
    resolve(authHeader.slice('Bearer '.length))
  })
}

function getPublicKeyURL(accessList, issuer) {
  return accessList[issuer].public_keys_url
}

function issuerInAccessList(accessList, issuer) {
  return issuer in accessList
}

function authenticateAndAuthorize(token, accessList) {
  const decodedToken = jwt.decode(token)
  const issuer = decodedToken.iss

  return new Promise(function(resolve, reject) {
    if (!issuerInAccessList(accessList, issuer)) {
      reject(new Error('Token issuer not authorized'))
    }

    const keyURL = getPublicKeyURL(accessList, issuer)
    fetch(keyURL)
      .then(function(response) { return response.json() })
      .then(function(keys) {
        try {
          const publicKey = keys[decodedToken.signing_key_id]
          const decoded = jwt.verify(token, publicKey)
          resolve(decoded)
        } catch (err) {
          reject(new Error('Token is invalid'))
        }
      })
  })
}

/**
 * Used to wrap an HTTP request handler to verify that the request is authenticated and authorized.
 *
 * Returns a new HTTP request handler that will call `handler` if the request is valid, otherwise
 * send a 401 error code back.
 *
 * The accessList is a map from email to an Object containing public_keys_url.
 *
 * @param {Object} accessList A mapping of valid issuers and URL to load the public keys used by the issuer.
 * @param {Function} handler A normal http request handler taking Request and Result.
 */
function authProtected(accessList, handler) {
  return function(req, res) {
    getAuthToken(req)
      .then(function(token) {
        return authenticateAndAuthorize(token, accessList)
      })
      .then(function() {
        handler(req, res)
      })
      .catch(function(error) {
        res.status(401).json(error.message)
      })
  }
}

module.exports = authProtected
<commit_msg>Inline two function<commit_after>const jwt = require('jsonwebtoken')
const fetch = require('node-fetch')

function getAuthToken(req) {
  return new Promise(function(resolve, reject) {
    const authHeader = req.get('Authorization')
    if (authHeader === undefined) {
      reject(new Error('No authorization header'))
    }

    if (authHeader.slice(0, 7) !== 'Bearer ') {
      reject(new Error('Malformed authorization header'))
    }
    resolve(authHeader.slice('Bearer '.length))
  })
}

function authenticateAndAuthorize(token, accessList) {
  const decodedToken = jwt.decode(token)
  const issuer = decodedToken.iss

  return new Promise(function(resolve, reject) {
    if (!(issuer in accessList)) {
      reject(new Error('Token issuer not authorized'))
    }

    const keyURL = accessList[issuer].public_keys_url
    fetch(keyURL)
      .then(function(response) { return response.json() })
      .then(function(keys) {
        try {
          const publicKey = keys[decodedToken.signing_key_id]
          const decoded = jwt.verify(token, publicKey)
          resolve(decoded)
        } catch (err) {
          reject(new Error('Token is invalid'))
        }
      })
  })
}

/**
 * Used to wrap an HTTP request handler to verify that the request is authenticated and authorized.
 *
 * Returns a new HTTP request handler that will call `handler` if the request is valid, otherwise
 * send a 401 error code back.
 *
 * The accessList is a map from email to an Object containing public_keys_url.
 *
 * @param {Object} accessList A mapping of valid issuers and URL to load the public keys used by the issuer.
 * @param {Function} handler A normal http request handler taking Request and Result.
 */
function authProtected(accessList, handler) {
  return function(req, res) {
    getAuthToken(req)
      .then(function(token) {
        return authenticateAndAuthorize(token, accessList)
      })
      .then(function() {
        handler(req, res)
      })
      .catch(function(error) {
        res.status(401).json(error.message)
      })
  }
}

module.exports = authProtected
<|endoftext|>


<commit_before>Template.addGroup.helpers({
	friends:function(){
		curuser  = Meteor.user();
		friends = [];
		if(curuser){
			if(_.has(curuser,'friend')){
				 friends = curuser.friend;
			}
		}
		return friends;
	}
});
Template.addGroup.events({
	'submit form':function(event,template){
		event.preventDefault();
		groupname = event.target.groupname.value;
		if(groupname === ""){
			sAlert.error('群组名称必填',{position:'bottom-left'});
			return ;
		}
		addselectedfriend = template.$('.selected');
		addselectedfriendids = [];
		if(addselectedfriend.length <=0){

		}else{
			_.each(addselectedfriend,function(val,key){
				id = $(val).data('id');
				username = $(val).text();
				obj = {id:id,username:username}
				addselectedfriendids.push(obj);
			})
		}
		Meteor.apply('groups.create',[groupname,addselectedfriendids],function(err,res){
			if(err){
				sAlert.error('创建群组失败',{position:'bottom-left'});
			}else{
				if(!res){
					sAlert.error('创建群组失败',{position:'bottom-left'});
				}else{
					sAlert.success('创建群组成功,2秒后跳转到首页',{position:'bottom-left'});
					Meteor.setTimeout(function(){
						Router.go('home');
					},2000);
				}
			}
		})

	},
	'click .friends-list':function(event,template){
		event.preventDefault();
		event.target.classList.add('selected')

	},
	'click #add':function(event,template){
		event.preventDefault();
		addselectedfriend = template.$('.selected');
		addselectedfriendids = {};
		_.each(addselectedfriend,function(val,key){
			addselectedfriendids[$(val).data('id')] = $(val).text();
		})
		console.log(addselectedfriendids);
		choose = Session.get('chooseids');
		if(choose){
			_.each(addselectedfriendids,function(val,key){
				console.log('val',val);
				if(_.indexOf(choose,val) == -1){
					choose.push(val);
					template.$('.choose-list').after('
'+val+'
')
				}
			})

		}else{
			choose = [event.target.dataset.id];
			_.each(addselectedfriendids,function(val,key){
				console.log('val1',val);
				if(_.indexOf(choose,val) == -1){
					choose = [];
					choose.push(val);
					template.$('.choose-list:last').after('
'+val+'
')
				}
			})
		}
		Session.set('chooseids',choose);
	},
	'click #del':function(event,template){
		event.preventDefault();
		delselectedfriend = template.$('.delselected');
		delselectedfriendids = {};
		_.each(delselectedfriend,function(val,key){
			delselectedfriendids[$(val).data('id')] = $(val).text();
		})
		console.log(delselectedfriendids);
		choose = Session.get('chooseids');
		if(choose){
			_.each(delselectedfriendids,function(val,key){
				console.log(key)
				if(_.indexOf(choose,val) !== -1){
					choose.pop(val);
					template.$('.friends-list[data-id="'+key+'"]').removeClass('selected');
					template.$('.choose-list[data-id="'+key+'"]').remove();
				}
			})

		}
		Session.set('chooseids',choose);
		template.$('.choose-list[data-id="Kd8GNPq2wHcC3y7T"]')
	},
	'click .choose-list':function(event,template){
		event.preventDefault();
		if(event.target.dataset.id == Meteor.userId()){
			sAlert.error('不能选中自己',{position:'bottom-left'});
		}else{
			event.target.classList.add('delselected')

		}
	}
});
Template.grouplist.onCreated(function(){
	Meteor.subscribe('groups');
})
Template.grouplist.helpers({
	grouplist:function(){
		page = this.page;
		count = group.find({}).count();
		pagesize = 10;
		pagenum = Math.ceil(count/pagesize);
		if(page<=1){
			page=1;
		}
		if(page>=pagenum){
			page= pagenum;
		}
		skip = (page-1)*pagesize;
		userid = Meteor.userId();
		r = group.find({},{sort:{createAt:-1},skip:skip,limit:pagesize,transform(obj){
			if(_.has(obj,'member')){
				obj.nums = obj.member.length+1;
			} else{
				obj.nums = 1;
			}
			return obj;
		}}).fetch();
		console.log(r);
		return r;
	},
	dateFormat:function(date){
		return moment(date).format('YYYY-MM-DD');
	}

})<commit_msg>user grouplist,add momentjs<commit_after>Template.addGroup.helpers({
	friends:function(){
		curuser  = Meteor.user();
		friends = [];
		if(curuser){
			if(_.has(curuser,'friend')){
				 friends = curuser.friend;
			}
		}
		return friends;
	}
});
Template.addGroup.events({
	'submit form':function(event,template){
		event.preventDefault();
		groupname = event.target.groupname.value;
		if(groupname === ""){
			sAlert.error('群组名称必填',{position:'bottom-left'});
			return ;
		}
		addselectedfriend = template.$('.selected');
		addselectedfriendids = [];
		if(addselectedfriend.length <=0){

		}else{
			_.each(addselectedfriend,function(val,key){
				id = $(val).data('id');
				username = $(val).text();
				obj = {id:id,username:username}
				addselectedfriendids.push(obj);
			})
		}
		Meteor.apply('groups.create',[groupname,addselectedfriendids],function(err,res){
			if(err){
				sAlert.error('创建群组失败',{position:'bottom-left'});
			}else{
				if(!res){
					sAlert.error('创建群组失败',{position:'bottom-left'});
				}else{
					sAlert.success('创建群组成功,2秒后跳转到首页',{position:'bottom-left'});
					Meteor.setTimeout(function(){
						Router.go('home');
					},2000);
				}
			}
		})

	},
	'click .friends-list':function(event,template){
		event.preventDefault();
		event.target.classList.add('selected')

	},
	'click #add':function(event,template){
		event.preventDefault();
		addselectedfriend = template.$('.selected');
		addselectedfriendids = {};
		_.each(addselectedfriend,function(val,key){
			addselectedfriendids[$(val).data('id')] = $(val).text();
		})
		console.log(addselectedfriendids);
		choose = Session.get('chooseids');
		if(choose){
			_.each(addselectedfriendids,function(val,key){
				console.log('val',val);
				if(_.indexOf(choose,val) == -1){
					choose.push(val);
					template.$('.choose-list').after('
'+val+'
')
				}
			})

		}else{
			choose = [event.target.dataset.id];
			_.each(addselectedfriendids,function(val,key){
				console.log('val1',val);
				if(_.indexOf(choose,val) == -1){
					choose = [];
					choose.push(val);
					template.$('.choose-list:last').after('
'+val+'
')
				}
			})
		}
		Session.set('chooseids',choose);
	},
	'click #del':function(event,template){
		event.preventDefault();
		delselectedfriend = template.$('.delselected');
		delselectedfriendids = {};
		_.each(delselectedfriend,function(val,key){
			delselectedfriendids[$(val).data('id')] = $(val).text();
		})
		console.log(delselectedfriendids);
		choose = Session.get('chooseids');
		if(choose){
			_.each(delselectedfriendids,function(val,key){
				console.log(key)
				if(_.indexOf(choose,val) !== -1){
					choose.pop(val);
					template.$('.friends-list[data-id="'+key+'"]').removeClass('selected');
					template.$('.choose-list[data-id="'+key+'"]').remove();
				}
			})

		}
		Session.set('chooseids',choose);
		template.$('.choose-list[data-id="Kd8GNPq2wHcC3y7T"]')
	},
	'click .choose-list':function(event,template){
		event.preventDefault();
		if(event.target.dataset.id == Meteor.userId()){
			sAlert.error('不能选中自己',{position:'bottom-left'});
		}else{
			event.target.classList.add('delselected')

		}
	}
});
Template.grouplist.onCreated(function(){
	Meteor.subscribe('groups');
})
Template.grouplist.helpers({
	grouplist:function(){
		page = this.page;
		count = group.find({}).count();
		pagesize = 10;
		pagenum = Math.ceil(count/pagesize);
		if(page<=1){
			page=1;
		}
		if(page>=pagenum){
			page= pagenum;
		}
		skip = (page-1)*pagesize;
		userid = Meteor.userId();
		r = group.find({},{sort:{createAt:-1},skip:skip,limit:pagesize,transform(obj){

			if(_.has(obj,'member')){
				obj.nums = obj.member.length+1;
			} else{
				obj.nums = 1;
			}
			return obj;
		}}).fetch();

		return r;
	},
	dateFormat:function(date){
		return moment(date).format('YYYY-MM-DD');
	}

})<|endoftext|>


<commit_before>$("script[type='math/tex']").replaceWith(
  function(){
    var tex = $(this).text();
    return "" +
           katex.renderToString(tex) +
           "";
});

$("script[type='math/tex; mode=display']").replaceWith(
  function(){
    var tex = $(this).text();
    return "
" +
           katex.renderToString("\\displaystyle "+tex) +
           "
";
});
<commit_msg>Delete katex.js<commit_after><|endoftext|>