<commit_before>'use strict';

angular.module('app')
    .controller('rgiCommentsCtrl', function (
        $scope,
        rgiDialogFactory,
        rgiIdentitySrvc,
        rgiAnswerMethodSrvc,
        rgiQuestionMethodSrvc,
        rgiNotifier
    ) {
        $scope.current_user = rgiIdentitySrvc.currentUser;

        $scope.submitComment = function () {
            var current_user = rgiIdentitySrvc.currentUser,
                new_comment_data = {
                    content: $scope.update.new_comment,
                    author: current_user._id,
                    date: new Date().toISOString()
                },
                new_update_data = $scope.update;

            if(!new_comment_data.content) {
                rgiNotifier.error('You must include a comment before submitting!');
            } else {
                new_update_data.comments.push(new_comment_data);

                if (new_update_data.status === 'assigned' && !$scope.current_user.isSupervisor()) {
                    new_update_data.status = 'saved';
                }

                var saveComment;

                if($scope.$parent.page_type === 'answer') {
                    saveComment = rgiAnswerMethodSrvc.updateAnswer;
                } else if($scope.$parent.page_type === 'question') {
                    saveComment = rgiQuestionMethodSrvc.updateQuestion;
                }

                if(saveComment === undefined) {
                    rgiNotifier.error('Unrecognized page format!');
                } else {
                    saveComment(new_update_data).then(function () {
                        rgiNotifier.notify('Comment added');
                        $scope.update.new_comment = undefined;
                    }, function (reason) {
                        rgiNotifier.error(reason);
                    });
                }
            }
        };

        $scope.isAuthor = function(comment) {
            var currentUserId = $scope.current_user._id;
            return comment.author._id ? (comment.author._id === currentUserId) : (comment.author === currentUserId);
        };

        $scope.editComment = function (comment) {
            rgiDialogFactory.commentEdit($scope.update, comment);
        };

        $scope.deleteComment = function(comment) {
            rgiDialogFactory.deleteComment($scope, comment);
        };
    });
<commit_msg>show author details for a just submitted comment<commit_after>'use strict';

angular.module('app')
    .controller('rgiCommentsCtrl', function (
        $scope,
        rgiDialogFactory,
        rgiIdentitySrvc,
        rgiAnswerMethodSrvc,
        rgiQuestionMethodSrvc,
        rgiNotifier
    ) {
        $scope.current_user = rgiIdentitySrvc.currentUser;

        $scope.submitComment = function () {
            var new_comment_data = {
                    content: $scope.update.new_comment,
                    author: $scope.current_user._id,
                    date: new Date().toISOString()
                },
                new_update_data = $scope.update;

            if(!new_comment_data.content) {
                rgiNotifier.error('You must include a comment before submitting!');
            } else {
                new_update_data.comments.push(new_comment_data);

                if (new_update_data.status === 'assigned' && !$scope.current_user.isSupervisor()) {
                    new_update_data.status = 'saved';
                }

                var saveComment;

                if($scope.$parent.page_type === 'answer') {
                    saveComment = rgiAnswerMethodSrvc.updateAnswer;
                } else if($scope.$parent.page_type === 'question') {
                    saveComment = rgiQuestionMethodSrvc.updateQuestion;
                }

                if(saveComment === undefined) {
                    rgiNotifier.error('Unrecognized page format!');
                } else {
                    saveComment(new_update_data).then(function () {
                        rgiNotifier.notify('Comment added');
                        $scope.update.new_comment = undefined;
                        new_update_data.comments[new_update_data.comments.length - 1].author = $scope.current_user;
                    }, function (reason) {
                        rgiNotifier.error(reason);
                    });
                }
            }
        };

        $scope.isAuthor = function(comment) {
            var currentUserId = $scope.current_user._id;
            return comment.author._id ? (comment.author._id === currentUserId) : (comment.author === currentUserId);
        };

        $scope.editComment = function (comment) {
            rgiDialogFactory.commentEdit($scope.update, comment);
        };

        $scope.deleteComment = function(comment) {
            rgiDialogFactory.deleteComment($scope, comment);
        };
    });
<|endoftext|>


<commit_before>YesnoRepresentation.prototype = Object.create(Phaser.Text.prototype);
YesnoRepresentation.prototype.constructor = YesnoRepresentation;

/**
 * Yes - No representation.
 * @param {boolean} yes - True is yes, false is no.
 * @param {number} x - X position.
 * @param {number} y - Y position.
 * @param {number} size - Font size of the representation (default 50).
 * @param {string} color - The color of the representation (default '#000000').
 * @return {Object} Itself.
 */
function YesnoRepresentation (yes, x, y, size, color) {
	size = size || 50;
	color = color || '#000000';

	Phaser.Text.call(this, game, x+size, y+size, (yes ? 'y' : 'n'), {
		font: size + 'pt ' + GLOBAL.FONT,
		fill: color,
		stroke: color,
		strokeThickness: 3
	}); // Parent constructor.
	this.anchor.set(0.5);

	return this;
}<commit_msg>Yes-No representation now with sprites<commit_after>YesnoRepresentation.prototype = Object.create(Phaser.Sprite.prototype);
YesnoRepresentation.prototype.constructor = YesnoRepresentation;

/**
 * Yes - No representation.
 * @param {boolean} yes - True is yes, false is no.
 * @param {number} x - X position.
 * @param {number} y - Y position.
 * @param {number} size - Font size of the representation (default 50).
 * @return {Object} Itself.
 */
function YesnoRepresentation (yes, x, y, size) {
	size = size || 50;
	var typ = yes ? 'yes' : 'no';

	Phaser.Sprite.call(this, game, x, y, 'objects', typ + 1);
	this.width = size;
	this.height = size;

	this.animations.add('cycle', [typ + 1, typ + 2, typ + 1, typ + 3, typ + 1], 5, true).play();

	return this;
}<|endoftext|>


<commit_before>const PACKAGE_FILENAME = '../package.json';

const package = require(PACKAGE_FILENAME);
const oldVersion = package.version;
const version = oldVersion.split('.');

function exec (cmd) {
  const proc = childProcess.exec(cmd);
  proc.stdout.on('data', console.log.bind(console));
  proc.stderr.on('data', console.error.bind(console));
}

if (!package.ci) {
  version[2]++;

} else {
  if (package.ci.bump == 'major') {
    version[0]++;
    version[1] = version[2] = 0;
  } else if (package.ci.bump = 'minor') {
    version[1]++;
    version[2] = 0;
  } else {
    version[2]++;
  }

  delete package.ci;
}

package.version = version.join('.');
const output = JSON.stringify(package, null, '\t');

require('fs').writeFile(__dirname + '/' + PACKAGE_FILENAME, output, function (err) {
  if (err) {
    throw(err);
  }

  exec('git add ./package.json');
  exec('git commit -m "Bumps version to ' + package.version + '"');
  exec('git push');

  console.log('Bumped version: ' + oldVersion + ' -> ' + package.version);
});
<commit_msg>Adds dependency to bump version.<commit_after>const childProcess = require('child_process');

const PACKAGE_FILENAME = '../package.json';

const package = require(PACKAGE_FILENAME);
const oldVersion = package.version;
const version = oldVersion.split('.');

function exec (cmd) {
  const proc = childProcess.exec(cmd);
  proc.stdout.on('data', console.log.bind(console));
  proc.stderr.on('data', console.error.bind(console));
}

if (!package.ci) {
  version[2]++;

} else {
  if (package.ci.bump == 'major') {
    version[0]++;
    version[1] = version[2] = 0;
  } else if (package.ci.bump = 'minor') {
    version[1]++;
    version[2] = 0;
  } else {
    version[2]++;
  }

  delete package.ci;
}

package.version = version.join('.');
const output = JSON.stringify(package, null, '\t');

require('fs').writeFile(__dirname + '/' + PACKAGE_FILENAME, output, function (err) {
  if (err) {
    throw(err);
  }

  exec('git add ./package.json');
  exec('git commit -m "Bumps version to ' + package.version + '"');
  exec('git push');

  console.log('Bumped version: ' + oldVersion + ' -> ' + package.version);
});
<|endoftext|>


<commit_before>let gulp = require('gulp')
let path = require('path')
let tap = require('gulp-tap')
let compile = require('./scripts/mp/index')
let fs = require('fs')
let compileWxss = require('./scripts/mp/wxss')
var prettier = require('prettier')

const WXCOMPONENT_ENV = 'WXCOMPONENT';

gulp.task('components', ['copy'], () => {
  const isWxComponent = process.env.NODE_ENV === WXCOMPONENT_ENV;
  const src = isWxComponent ? 'src/mp/components/**/*.js' : 'src/mp/components/*/*.js'; // 判断是否微信组件

  return gulp
    .src(src)
    .pipe(
      tap(file => {
        let dir = isWxComponent ? file.path.replace('.js', '') : path.dirname(file.path)
        let arr = dir.split(/\\|\//)
        let name = arr[arr.length-1]
        let preName = arr[arr.length-2];

        try{
          if(path.basename(file.path) == name+'.js') {
            let filePathComponentDomStr = fileComponentDom(file.path);
            let contentPath = isWxComponent ? dir : dir + '/' + name;
            let wxml = fs.readFileSync(contentPath + '.wxml', 'utf8')
            let js = fs.readFileSync(contentPath + '.js', 'utf8')
            let json = require(contentPath + '.json')
            let importStr = json2import(json, dir)
            let hyperscript = compile(wxml)

            // 判断组件下面是不是压缩过
            if(js.includes('webpackBootstrap')){
              return
            }

            file.contents = Buffer.concat([
              Buffer.from(
                `${importStr}import componentCss from './${name}.wxss'
  import { h, WeElement, rpx } from 'omi'
  import { setData } from ${isWxComponent && preName === 'components' ? "'../../utils/set-data'" : "'../../../utils/set-data'"}

    `
              ),
              Buffer.from(
                file.contents
                  .toString()
                  .replace('Component({',
                  `const mpOption = function () {
    return ({`)+`
  }`),
              Buffer.from(`
  class Element extends WeElement {
    static props = mpOption().properties

    data = mpOption().data

    render = render

    css = css

    beforeRender() {}

    beforeUpdate() {}

    afterUpdate() {}

    install = function() {
      this.properties = this.props
      Object.assign(this.data, JSON.parse(JSON.stringify(this.props)))
      this._mpOption = mpOption()
      this._mpOption.created && this._mpOption.created.call(this)
      Object.keys(this._mpOption.methods).forEach(key => {
        if(typeof this._mpOption.methods[key] === 'function'){
          this[key] = this._mpOption.methods[key].bind(this)
        }
      })
    }

    uninstall = mpOption().detached || function() {}

    installed = function() {
      this._mpOption.attached && this._mpOption.attached.call(this)
      this._mpOption.ready && this._mpOption.ready.call(this)
    }

    adoptedCallback = mpOption().moved || function() {}

    triggerEvent = function(name, data) {
      this.fire(name, data)
    }

    setData = setData
  }

  function css() {
    return rpx(componentCss)
  }

  ${prettier.format(hyperscript, { parser: "babel" })}

  customElements.define('${filePathComponentDomStr}', Element)
            `)
            ])
          }
        }catch(e){}
      })
    )
    .pipe(gulp.dest('src/mp/components/'))
})

gulp.task('copy', () => {
  return gulp.src('src-mp/**/*').pipe(gulp.dest('src/mp'))
})

gulp.task('pages', ['copy'], () => {
  return gulp
    .src('src/mp/pages/*/*.js')
    .pipe(
      tap(file => {
        let dir = path.dirname(file.path)
        let arr = dir.split(/\\|\//)
        let name = arr[arr.length-1]
        if(path.basename(file.path) == name+'.js') {
          let wxml = fs.readFileSync(dir + '/' + name + '.wxml', 'utf8')
          let json = require(dir + '/' + name + '.json')
          let hyperscript = compile(replaceWxmlComponentHtml(dir, wxml,json))

          let importStr = json2import(json, dir)
          file.contents = Buffer.concat([
            Buffer.from(
              `${importStr}import appCss from '../../app.wxss'
import pageCss from './${name}.wxss'
import { h, WeElement, rpx } from 'omi'
import { setData } from '../../../utils/set-data'

  `
            ),
            Buffer.from(
              file.contents
                .toString()
                .replace('Page({',
`const mpOption = function () {
  return ({`)+`
}`
            ),
            Buffer.from(`
class Element extends WeElement {
  data = mpOption().data

  render = render

  css = css

  beforeRender() {}

  beforeUpdate() {}

  afterUpdate() {}

  install() {
    this.properties = this.props
    Object.assign(this.data, JSON.parse(JSON.stringify(this.props)))
    this._mpOption = mpOption()
    Object.keys(this._mpOption).forEach(key => {
      if (typeof this._mpOption[key] === 'function') {
        Element.prototype[key] = this._mpOption[key].bind(this)
      }
    })
  }

  uninstall = mpOption().onUnload || function() {}

  installed = function() {
    this._mpOption.onLoad && this._mpOption.onLoad.call(this, route.query)
    this._mpOption.onReady && this._mpOption.onReady.call(this, route.query)

    this._mpOption.onReachBottom && wx._bindReachBottom(this._mpOption.onReachBottom, this)
  }

  setData = setData
}

function css() {
  return rpx(appCss + pageCss)
}

${prettier.format(hyperscript, { parser: "babel" })}

customElements.define('we-${name}', Element)
          `)
          ])
        }
      })
    )
    .pipe(gulp.dest('src/mp/pages/'))
})

gulp.task('appjs', ['copy'], () => {
  return gulp
    .src('src-mp/app.js')
    .pipe(
      tap(file => {
        let list = walk('src-mp/pages')
        file.contents = Buffer.concat([
          file.contents,
          Buffer.from(list2require(list))
        ])
      })
    )
    .pipe(gulp.dest('src/mp'))
})

gulp.task('copyThen', () => {
  gulp.src('src-mp/**/*').pipe(gulp.dest('src/mp')).on('end', function(){
    gulp.start(['components', 'app-wxss', 'pages-wxss', 'components-wxss', 'pages', 'appjs', 'route'])
  })
})

gulp.task('watch', () => {
  gulp.watch('src-mp/**/*', () => {
    gulp.start('copyThen')
  })
})

gulp.task('route', ['copy'], (cb) => {
  let json = require('./src/mp/app.json')
  //fs.unlinkSync('./src/index.js')

  fs.writeFile('./src/index.js', `import 'omi-router'
import { routeUpdate } from './utils/mp'
import './mp/app'

const root = document.querySelector('#root')

route('*', evt => {
  title('index')
  routeUpdate(<we-index />, 'we-index', evt.byNative, root)
})

${route(json.pages)}

window.onscroll = function(){
  root.childNodes.forEach(child => {
    if(child.style.display !== 'none'){
      child._preScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
    }
  })
}

function title(value) {
  document.title = value
}
    `, cb);

})

function route(arr) {
  let result = []
  arr.forEach(item => {
    const name = item.split('/')[1]
    result.push(`route('${item.replace('pages', '..')}', evt => {
  title('${name}')
  routeUpdate(<we-${name} />, 'we-${name}', evt.byNative, root)
})
`)
  })
  return result.join('\r\n')
}

// 打包生成web component 转换统一src 路径
function fileComponentDom(filePth) {
  let filePathArray = filePth.replace(__dirname, '').replace('.js', '').split('/');
  filePathArray.shift();

  return 'wx-h5-' + filePathArray.join('-');
}

// 组件转换绝对路径 不再需要依赖强匹配目录文件夹
function replaceComponentOnPath(tag, str, tagName) {
  const reg = new RegExp(`<(${tag})(?=\\s)|<(\\/${tag})>`, 'g');

  return str.replace(reg, function(match, $1, $2) {
      if ($1) {
          return '<' + tagName;
      }
      return '</' + tagName + '>'
  });
}

// 匹配转换html 转换 目录文件夹名字
function replaceWxmlComponentHtml(dir, html,json) {
  Object.keys(json.usingComponents).forEach((key, i) => {
    html = replaceComponentOnPath(
      key,
      html,
      fileComponentDom(path.join(dir, json.usingComponents[key]))
    );
  })

  return html;
}

function json2import(json, dir) {
  let arr = []
  if (json.usingComponents) {

    Object.keys(json.usingComponents).forEach(key => {
      let usingArry = path.resolve(dir, json.usingComponents[key]).split('/');
      usingArry.pop();
      let wxssPath = '';

      try{
        let indexWsxx = [...usingArry, 'index.wxss'].join('/');
        fs.statSync(indexWsxx);
        wxssPath = json.usingComponents[key];
      }catch(e){

      }

      try{
        let keyWsxx = [...usingArry, key + '.wxss'].join('/');
        fs.statSync(keyWsxx);
        wxssPath = keyWsxx;
      }catch(e){

      }

      wxssPath && arr.push(`import '${wxssPath}'`)

      // let wxml = fs.readFileSync(wxssPath, 'utf8')
      // console.log(Buffer.from(compileWxss(wxml)))

      // arr.push(Buffer.from(compileWxss(wxml)))
      arr.push(`import '${json.usingComponents[key]}'`)
    })
  }
  return arr.join('\r\n') + '\r\n'
}

function list2require(list) {
  return (
    '\r\n' +
    list
      .map(item => {
        return `require('./pages/${item}/${item}')`
      })
      .join('\r\n')
  )
}

function walk(path) {
  let dirList = fs.readdirSync(path)
  let fileList = []
  dirList.forEach(item => {
    if (fs.statSync(path + '/' + item).isDirectory()) {
      fileList.push(item)
    }
  })

  return fileList
}

gulp.task('pages-wxss', ['copy'], () => {
  return gulp
    .src('src/mp/pages/*/*.wxss')
    .pipe(
      tap(file => {
        file.contents = Buffer.from(compileWxss(file.contents.toString()))

      })
    )
    .pipe(gulp.dest('src/mp/pages/'))
})

gulp.task('components-wxss', ['copy'], () => {
  return gulp
    .src('src/mp/components/*/*.wxss')
    .pipe(
      tap(file => {
        file.contents = Buffer.from(compileWxss(file.contents.toString()))

      })
    )
    .pipe(gulp.dest('src/mp/components/'))
})

gulp.task('app-wxss', ['copy'], () => {
  return gulp
    .src('src-mp/app.wxss')
    .pipe(
      tap(file => {
        file.contents = Buffer.from(compileWxss(file.contents.toString()))

      })
    )
    .pipe(gulp.dest('src/mp'))
})

gulp.task('default', ['copy', 'components', 'app-wxss', 'pages-wxss', 'components-wxss', 'pages', 'appjs', 'route', 'watch'])
<commit_msg>增加默认打包命令<commit_after>let gulp = require('gulp')
let path = require('path')
let tap = require('gulp-tap')
let compile = require('./scripts/mp/index')
let fs = require('fs')
let compileWxss = require('./scripts/mp/wxss')
var prettier = require('prettier')

const WXCOMPONENT_ENV = 'WXCOMPONENT';

gulp.task('components', ['copy'], () => {
  const isWxComponent = process.env.NODE_ENV === WXCOMPONENT_ENV;
  const src = isWxComponent ? 'src/mp/components/**/*.js' : 'src/mp/components/*/*.js'; // 判断是否微信组件

  return gulp
    .src(src)
    .pipe(
      tap(file => {
        let dir = isWxComponent ? file.path.replace('.js', '') : path.dirname(file.path)
        let arr = dir.split(/\\|\//)
        let name = arr[arr.length-1]
        let preName = arr[arr.length-2];

        try{
          if(path.basename(file.path) == name+'.js') {
            let filePathComponentDomStr = fileComponentDom(file.path);
            let contentPath = isWxComponent ? dir : dir + '/' + name;
            let wxml = fs.readFileSync(contentPath + '.wxml', 'utf8')
            let js = fs.readFileSync(contentPath + '.js', 'utf8')
            let json = require(contentPath + '.json')
            let importStr = json2import(json, dir)
            let hyperscript = compile(wxml)

            // 判断组件下面是不是压缩过
            if(js.includes('webpackBootstrap')){
              return
            }

            file.contents = Buffer.concat([
              Buffer.from(
                `${importStr}import componentCss from './${name}.wxss'
  import { h, WeElement, rpx } from 'omi'
  import { setData } from ${isWxComponent && preName === 'components' ? "'../../utils/set-data'" : "'../../../utils/set-data'"}

    `
              ),
              Buffer.from(
                file.contents
                  .toString()
                  .replace('Component({',
                  `const mpOption = function () {
    return ({`)+`
  }`),
              Buffer.from(`
  class Element extends WeElement {
    static props = mpOption().properties

    data = mpOption().data

    render = render

    css = css

    beforeRender() {}

    beforeUpdate() {}

    afterUpdate() {}

    install = function() {
      this.properties = this.props
      Object.assign(this.data, JSON.parse(JSON.stringify(this.props)))
      this._mpOption = mpOption()
      this._mpOption.created && this._mpOption.created.call(this)
      Object.keys(this._mpOption.methods).forEach(key => {
        if(typeof this._mpOption.methods[key] === 'function'){
          this[key] = this._mpOption.methods[key].bind(this)
        }
      })
    }

    uninstall = mpOption().detached || function() {}

    installed = function() {
      this._mpOption.attached && this._mpOption.attached.call(this)
      this._mpOption.ready && this._mpOption.ready.call(this)
    }

    adoptedCallback = mpOption().moved || function() {}

    triggerEvent = function(name, data) {
      this.fire(name, data)
    }

    setData = setData
  }

  function css() {
    return rpx(componentCss)
  }

  ${prettier.format(hyperscript, { parser: "babel" })}

  customElements.define('${filePathComponentDomStr}', Element)
            `)
            ])
          }
        }catch(e){}
      })
    )
    .pipe(gulp.dest('src/mp/components/'))
})

gulp.task('copy', () => {
  return gulp.src('src-mp/**/*').pipe(gulp.dest('src/mp'))
})

gulp.task('pages', ['copy'], () => {
  return gulp
    .src('src/mp/pages/*/*.js')
    .pipe(
      tap(file => {
        let dir = path.dirname(file.path)
        let arr = dir.split(/\\|\//)
        let name = arr[arr.length-1]
        if(path.basename(file.path) == name+'.js') {
          let wxml = fs.readFileSync(dir + '/' + name + '.wxml', 'utf8')
          let json = require(dir + '/' + name + '.json')
          let hyperscript = compile(replaceWxmlComponentHtml(dir, wxml,json))

          let importStr = json2import(json, dir)
          file.contents = Buffer.concat([
            Buffer.from(
              `${importStr}import appCss from '../../app.wxss'
import pageCss from './${name}.wxss'
import { h, WeElement, rpx } from 'omi'
import { setData } from '../../../utils/set-data'

  `
            ),
            Buffer.from(
              file.contents
                .toString()
                .replace('Page({',
`const mpOption = function () {
  return ({`)+`
}`
            ),
            Buffer.from(`
class Element extends WeElement {
  data = mpOption().data

  render = render

  css = css

  beforeRender() {}

  beforeUpdate() {}

  afterUpdate() {}

  install() {
    this.properties = this.props
    Object.assign(this.data, JSON.parse(JSON.stringify(this.props)))
    this._mpOption = mpOption()
    Object.keys(this._mpOption).forEach(key => {
      if (typeof this._mpOption[key] === 'function') {
        Element.prototype[key] = this._mpOption[key].bind(this)
      }
    })
  }

  uninstall = mpOption().onUnload || function() {}

  installed = function() {
    this._mpOption.onLoad && this._mpOption.onLoad.call(this, route.query)
    this._mpOption.onReady && this._mpOption.onReady.call(this, route.query)

    this._mpOption.onReachBottom && wx._bindReachBottom(this._mpOption.onReachBottom, this)
  }

  setData = setData
}

function css() {
  return rpx(appCss + pageCss)
}

${prettier.format(hyperscript, { parser: "babel" })}

customElements.define('we-${name}', Element)
          `)
          ])
        }
      })
    )
    .pipe(gulp.dest('src/mp/pages/'))
})

gulp.task('appjs', ['copy'], () => {
  return gulp
    .src('src-mp/app.js')
    .pipe(
      tap(file => {
        let list = walk('src-mp/pages')
        file.contents = Buffer.concat([
          file.contents,
          Buffer.from(list2require(list))
        ])
      })
    )
    .pipe(gulp.dest('src/mp'))
})

gulp.task('copyThen', () => {
  gulp.src('src-mp/**/*').pipe(gulp.dest('src/mp')).on('end', function(){
    gulp.start(['components', 'app-wxss', 'pages-wxss', 'components-wxss', 'pages', 'appjs', 'route'])
  })
})

gulp.task('watch', () => {
  gulp.watch('src-mp/**/*', () => {
    gulp.start('copyThen')
  })
})

gulp.task('route', ['copy'], (cb) => {
  let json = require('./src/mp/app.json')
  //fs.unlinkSync('./src/index.js')

  fs.writeFile('./src/index.js', `import 'omi-router'
import { routeUpdate } from './utils/mp'
import './mp/app'

const root = document.querySelector('#root')

route('*', evt => {
  title('index')
  routeUpdate(<we-index />, 'we-index', evt.byNative, root)
})

${route(json.pages)}

window.onscroll = function(){
  root.childNodes.forEach(child => {
    if(child.style.display !== 'none'){
      child._preScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
    }
  })
}

function title(value) {
  document.title = value
}
    `, cb);

})

function route(arr) {
  let result = []
  arr.forEach(item => {
    const name = item.split('/')[1]
    result.push(`route('${item.replace('pages', '..')}', evt => {
  title('${name}')
  routeUpdate(<we-${name} />, 'we-${name}', evt.byNative, root)
})
`)
  })
  return result.join('\r\n')
}

// 打包生成web component 转换统一src 路径
function fileComponentDom(filePth) {
  let filePathArray = filePth.replace(__dirname, '').replace('.js', '').split('/');
  filePathArray.shift();

  return 'wx-h5-' + filePathArray.join('-');
}

// 组件转换绝对路径 不再需要依赖强匹配目录文件夹
function replaceComponentOnPath(tag, str, tagName) {
  const reg = new RegExp(`<(${tag})(?=\\s)|<(\\/${tag})>`, 'g');

  return str.replace(reg, function(match, $1, $2) {
      if ($1) {
          return '<' + tagName;
      }
      return '</' + tagName + '>'
  });
}

// 匹配转换html 转换 目录文件夹名字
function replaceWxmlComponentHtml(dir, html,json) {
  Object.keys(json.usingComponents).forEach((key, i) => {
    html = replaceComponentOnPath(
      key,
      html,
      fileComponentDom(path.join(dir, json.usingComponents[key]))
    );
  })

  return html;
}

function json2import(json, dir) {
  let arr = []
  if (json.usingComponents) {

    Object.keys(json.usingComponents).forEach(key => {
      let usingArry = path.resolve(dir, json.usingComponents[key]).split('/');
      usingArry.pop();
      let wxssPath = '';

      try{
        let indexWsxx = [...usingArry, 'index.wxss'].join('/');
        fs.statSync(indexWsxx);
        wxssPath = json.usingComponents[key];
      }catch(e){

      }

      try{
        let keyWsxx = [...usingArry, key + '.wxss'].join('/');
        fs.statSync(keyWsxx);
        wxssPath = keyWsxx;
      }catch(e){

      }

      wxssPath && arr.push(`import '${wxssPath}'`)

      // let wxml = fs.readFileSync(wxssPath, 'utf8')
      // console.log(Buffer.from(compileWxss(wxml)))

      // arr.push(Buffer.from(compileWxss(wxml)))
      arr.push(`import '${json.usingComponents[key]}'`)
    })
  }
  return arr.join('\r\n') + '\r\n'
}

function list2require(list) {
  return (
    '\r\n' +
    list
      .map(item => {
        return `require('./pages/${item}/${item}')`
      })
      .join('\r\n')
  )
}

function walk(path) {
  let dirList = fs.readdirSync(path)
  let fileList = []
  dirList.forEach(item => {
    if (fs.statSync(path + '/' + item).isDirectory()) {
      fileList.push(item)
    }
  })

  return fileList
}

gulp.task('pages-wxss', ['copy'], () => {
  return gulp
    .src('src/mp/pages/*/*.wxss')
    .pipe(
      tap(file => {
        file.contents = Buffer.from(compileWxss(file.contents.toString()))

      })
    )
    .pipe(gulp.dest('src/mp/pages/'))
})

gulp.task('components-wxss', ['copy'], () => {
  return gulp
    .src('src/mp/components/*/*.wxss')
    .pipe(
      tap(file => {
        file.contents = Buffer.from(compileWxss(file.contents.toString()))

      })
    )
    .pipe(gulp.dest('src/mp/components/'))
})

gulp.task('app-wxss', ['copy'], () => {
  return gulp
    .src('src-mp/app.wxss')
    .pipe(
      tap(file => {
        file.contents = Buffer.from(compileWxss(file.contents.toString()))

      })
    )
    .pipe(gulp.dest('src/mp'))
})

gulp.task('default', ['copy', 'components', 'app-wxss', 'pages-wxss', 'components-wxss', 'pages', 'appjs', 'route', 'watch'])
gulp.task('build', ['copy', 'components', 'app-wxss', 'pages-wxss', 'components-wxss', 'pages', 'appjs', 'route'])
<|endoftext|>


<commit_before>(function () {
    'use strict';

    /*jslint
        browser: true
    */
    /*global
        L, reqwest
    */

    var map;

    function arrowMarker(location) {
        var direction = (location.direction || 0) - 135;
        var tooltip = location.datetime.toTimeString().slice(0, 8);
        tooltip += getTooltip(location.delta);

        return L.marker(location.coordinates, {
            icon: L.divIcon({
                iconSize: [16, 16],
                html: '

',
                className: 'just-arrow',
            })
        }).bindTooltip(tooltip);

    }

    var circleMarkerOptions = {
        radius: 2,
        fillColor: '#000',
        fillOpacity: 1,
        weight: 0,
    };

    var date = document.getElementById('date').value;

    function closeMap() {
        if (lastRequest) {
            lastRequest.abort();
        }
        window.location.hash = ''; // triggers hashchange event
    }

    window.onkeydown = function(event) {
        if (event.keyCode === 27) { // esc
            closeMap();
        }
    };

    var lastRequest;

    window.onhashchange = maybeOpenMap;

    function getTooltip(delta) {
        if (delta) {
            var tooltip = 'About ';
            if (delta > 0) {
                tooltip += delta;
            } else {
                tooltip += delta * -1;
            }
            tooltip += ' minute';
            if (delta !== 1 && delta !== -1) {
                tooltip += 's';
            }
            if (delta > 0) {
                tooltip += ' early';
            } else {
                tooltip += ' late';
            }
            return '
' + tooltip;
        } else if (delta === 0) {
            return '
On time';
        } else {
            return '';
        }
    }

    var stops, locations, rovingTooltipMarker;

    function showStopOnMap() {
        var stop = stops[this.rowIndex - 1];

        map.eachLayer(function(layer) {
            if (layer.options.pane === 'tooltipPane') layer.removeFrom(map);
        });

        if (!stop.coordinates) {
            return;
        }

        var min = 1000, nearest, location, distance;

        for (var i = 0; i < locations.length; i++) {
            location = locations[i];
            distance = stop.coordinates.distanceTo(location.coordinates);
            if (distance < min) {
                min = distance;
                nearest = location;
            }
        }

        if (nearest) {
            var popup = nearest.datetime.toTimeString().slice(0, 8);
            popup += getTooltip(nearest.delta);

            if (!rovingTooltipMarker) {
                rovingTooltipMarker = L.circleMarker(nearest.coordinates, circleMarkerOptions).addTo(map);
            } else {
                rovingTooltipMarker.setLatLng(nearest.coordinates);
            }
            rovingTooltipMarker.bindTooltip(popup).openTooltip();
        }
    }

    function maybeOpenMap() {
        var journey = window.location.hash.slice(1);

        if (journey) {
            var element = document.getElementById(journey);
        }

        if (!element) {
            return;
        }

        if (lastRequest) {
            lastRequest.abort();
        }

        if (map) {
            map.remove();
            map = null;
        }

        reqwest('/' + journey + '.json', function(response) {
            var i;

            for (i = 0; i < response.locations.length; i++) {
                var location = response.locations[i];
                location.coordinates = L.latLng(location.coordinates[1], location.coordinates[0]);
                location.datetime = new Date(location.datetime);
            }

            if (response.stops) {
                var tripElement = document.createElement('div');
                tripElement.className = 'trip';
                element.appendChild(tripElement);

                var table = document.createElement('table');
                table.className = 'trip-timetable';
                var thead = document.createElement('thead');
                thead.innerHTML = '
Stop	Timetable
';
                table.appendChild(thead);

                var tbody = document.createElement('tbody');
                var tr, stop, time;
                for (i = 0; i < response.stops.length; i++) {
                    tr = document.createElement('tr');
                    stop = response.stops[i];
                    if (stop.minor) {
                        tr.className = 'minor';
                    }
                    time = stop.aimed_departure_time || stop.aimed_arrival_time || '';
                    tr.innerHTML = '' + stop.name + '	' + time + '	';
                    tbody.appendChild(tr);

                    if (stop.coordinates) {
                        stop.coordinates = L.latLng(stop.coordinates[1], stop.coordinates[0]);
                    }
                }
                table.appendChild(tbody);
                tripElement.appendChild(table);
            }

            var mapContainer = element.querySelector('.map');
            if (!mapContainer) {
                mapContainer = document.createElement('div');
                mapContainer.className = 'map';
                element.appendChild(mapContainer);
            }

            map = L.map(mapContainer);

            window.bustimes.doTileLayer(map);

            L.control.locate().addTo(map);

            var line = [],
                previousCoordinates,
                previousTimestamp,
                previousMarkerCoordinates,
                previousDroppedLocation;

            response.locations.forEach(function(location) {
                var timestamp = location.datetime.getTime();

                var coordinates = location.coordinates;

                line.push(coordinates);

                if (previousCoordinates) {
                    var time = timestamp - previousTimestamp;

                    if (time) {
                        if (previousMarkerCoordinates.distanceTo(location.coordinates) > 100) {
                            if (previousDroppedLocation) {
                                arrowMarker(previousDroppedLocation).addTo(map);
                            }
                            previousDroppedLocation = null;
                            arrowMarker(location).addTo(map);
                            previousMarkerCoordinates = location.coordinates;
                        } else {
                            // not moved far from the last marker
                            previousDroppedLocation = location;
                        }

                        // add a marker every minute
                        if (time < 6000000) {  // less than 10 minutes
                            var latDistance = coordinates.lat - previousCoordinates.lat;
                            var lngDistance = coordinates.lng - previousCoordinates.lng;
                            var latSpeed = latDistance / time;  // really velocity
                            var lngSpeed = lngDistance / time;

                            var minute = Math.ceil(previousTimestamp / 60000) * 60000 - previousTimestamp;
                            for (; minute <= time; minute += 60000) {
                                L.circleMarker(L.latLng(
                                    previousCoordinates.lat + latSpeed * minute,
                                    previousCoordinates.lng + lngSpeed * minute
                                ), circleMarkerOptions).addTo(map);
                            }
                        }
                    }
                } else {
                    arrowMarker(location).addTo(map);
                    previousMarkerCoordinates = location.coordinates;
                }

                previousCoordinates = coordinates;
                previousTimestamp = timestamp;
            });
            if (previousDroppedLocation) {
                arrowMarker(previousDroppedLocation).addTo(map);
            }

            if (response.stops) {
                stops = response.stops;
                locations = response.locations;
                for (i = 0; i < tbody.children.length; i++) {
                    tr = tbody.children[i];
                    tr.addEventListener('mouseover', showStopOnMap);
                    tr.addEventListener('touchstart', showStopOnMap);
                }
            }

            line = L.polyline(line, {
                weight: 4,
                color: '#87f',
                opacity: .5
            });
            line.addTo(map);

            var bounds = line.getBounds();

            map.fitBounds(bounds, {
                maxZoom: 14
            }).setMaxBounds(bounds.pad(.5));
        });
    }

    window.addEventListener('load', maybeOpenMap);

    function handleClick(event) {
        window.history.replaceState(null, null, '?date=' + date + event.target.hash);
        maybeOpenMap();
    }

    var links = document.querySelectorAll('a[href^="#journeys/"]');
    for (var i = links.length - 1; i >= 0; i -= 1) {
        links[i].addEventListener('click', handleClick);
    }

})();
<commit_msg>history.js: rename some variables<commit_after>(function () {
    'use strict';

    /*jslint
        browser: true
    */
    /*global
        L, reqwest
    */

    var map;

    function arrowMarker(location) {
        var direction = (location.direction || 0) - 135;
        var tooltip = location.datetime.toTimeString().slice(0, 8);
        tooltip += getTooltip(location.delta);

        return L.marker(location.coordinates, {
            icon: L.divIcon({
                iconSize: [16, 16],
                html: '

',
                className: 'just-arrow',
            })
        }).bindTooltip(tooltip);

    }

    var circleMarkerOptions = {
        radius: 2,
        fillColor: '#000',
        fillOpacity: 1,
        weight: 0,
    };

    var date = document.getElementById('date').value;

    function closeMap() {
        if (lastRequest) {
            lastRequest.abort();
        }
        window.location.hash = ''; // triggers hashchange event
    }

    window.onkeydown = function(event) {
        if (event.keyCode === 27) { // esc
            closeMap();
        }
    };

    var lastRequest;

    window.onhashchange = maybeOpenMap;

    function getTooltip(delta) {
        if (delta) {
            var tooltip = 'About ';
            if (delta > 0) {
                tooltip += delta;
            } else {
                tooltip += delta * -1;
            }
            tooltip += ' minute';
            if (delta !== 1 && delta !== -1) {
                tooltip += 's';
            }
            if (delta > 0) {
                tooltip += ' early';
            } else {
                tooltip += ' late';
            }
            return '
' + tooltip;
        } else if (delta === 0) {
            return '
On time';
        } else {
            return '';
        }
    }

    var stops, locations, rovingTooltipMarker;

    function showStopOnMap() {
        var stop = stops[this.rowIndex - 1];

        map.eachLayer(function(layer) {
            if (layer.options.pane === 'tooltipPane') layer.removeFrom(map);
        });

        if (!stop.coordinates) {
            return;
        }

        var min = 1000, nearest, location, distance;

        for (var i = 0; i < locations.length; i++) {
            location = locations[i];
            distance = stop.coordinates.distanceTo(location.coordinates);
            if (distance < min) {
                min = distance;
                nearest = location;
            }
        }

        if (nearest) {
            var popup = nearest.datetime.toTimeString().slice(0, 8);
            popup += getTooltip(nearest.delta);

            if (!rovingTooltipMarker) {
                rovingTooltipMarker = L.circleMarker(nearest.coordinates, circleMarkerOptions).addTo(map);
            } else {
                rovingTooltipMarker.setLatLng(nearest.coordinates);
            }
            rovingTooltipMarker.bindTooltip(popup).openTooltip();
        }
    }

    function maybeOpenMap() {
        var journey = window.location.hash.slice(1);

        if (journey) {
            var element = document.getElementById(journey);
        }

        if (!element) {
            return;
        }

        if (lastRequest) {
            lastRequest.abort();
        }

        if (map) {
            map.remove();
            map = null;
        }

        reqwest('/' + journey + '.json', function(response) {
            var i;

            for (i = 0; i < response.locations.length; i++) {
                var location = response.locations[i];
                location.coordinates = L.latLng(location.coordinates[1], location.coordinates[0]);
                location.datetime = new Date(location.datetime);
            }

            if (response.stops) {
                var tripElement = document.createElement('div');
                tripElement.className = 'trip';
                element.appendChild(tripElement);

                var table = document.createElement('table');
                table.className = 'trip-timetable';
                var thead = document.createElement('thead');
                thead.innerHTML = '
Stop	Timetable
';
                table.appendChild(thead);

                var tbody = document.createElement('tbody');
                var tr, stop, time;
                for (i = 0; i < response.stops.length; i++) {
                    tr = document.createElement('tr');
                    stop = response.stops[i];
                    if (stop.minor) {
                        tr.className = 'minor';
                    }
                    time = stop.aimed_departure_time || stop.aimed_arrival_time || '';
                    tr.innerHTML = '' + stop.name + '	' + time + '	';
                    tbody.appendChild(tr);

                    if (stop.coordinates) {
                        stop.coordinates = L.latLng(stop.coordinates[1], stop.coordinates[0]);
                    }
                }
                table.appendChild(tbody);
                tripElement.appendChild(table);
            }

            var mapContainer = element.querySelector('.map');
            if (!mapContainer) {
                mapContainer = document.createElement('div');
                mapContainer.className = 'map';
                element.appendChild(mapContainer);
            }

            map = L.map(mapContainer);

            window.bustimes.doTileLayer(map);

            L.control.locate().addTo(map);

            var line = [],
                previousCoordinates,
                previousTimestamp,
                previousMarkerCoordinates,
                previousSkippedLocation;

            response.locations.forEach(function(location) {
                var timestamp = location.datetime.getTime();

                var coordinates = location.coordinates;

                line.push(coordinates);

                if (previousCoordinates) {
                    var time = timestamp - previousTimestamp;

                    if (time) {
                        if (previousMarkerCoordinates.distanceTo(location.coordinates) > 100) {
                            // vehicle has moved far enough
                            if (previousSkippedLocation) {
                                // mark the end of the stationary period
                                arrowMarker(previousSkippedLocation).addTo(map);
                                previousSkippedLocation = null;
                            }
                            arrowMarker(location).addTo(map);
                            previousMarkerCoordinates = location.coordinates;
                        } else {
                            // vehicle has barely moved
                            previousSkippedLocation = location;
                        }

                        // add a marker every minute
                        if (time < 6000000) {  // less than 10 minutes
                            var latDistance = coordinates.lat - previousCoordinates.lat;
                            var lngDistance = coordinates.lng - previousCoordinates.lng;
                            var latSpeed = latDistance / time;  // really velocity
                            var lngSpeed = lngDistance / time;

                            var minute = Math.ceil(previousTimestamp / 60000) * 60000 - previousTimestamp;
                            for (; minute <= time; minute += 60000) {
                                L.circleMarker(L.latLng(
                                    previousCoordinates.lat + latSpeed * minute,
                                    previousCoordinates.lng + lngSpeed * minute
                                ), circleMarkerOptions).addTo(map);
                            }
                        }
                    }
                } else {
                    arrowMarker(location).addTo(map);
                    previousMarkerCoordinates = location.coordinates;
                }

                previousCoordinates = coordinates;
                previousTimestamp = timestamp;
            });
            if (previousSkippedLocation) {
                arrowMarker(previousSkippedLocation).addTo(map);
            }

            if (response.stops) {
                stops = response.stops;
                locations = response.locations;
                for (i = 0; i < tbody.children.length; i++) {
                    tr = tbody.children[i];
                    tr.addEventListener('mouseover', showStopOnMap);
                    tr.addEventListener('touchstart', showStopOnMap);
                }
            }

            line = L.polyline(line, {
                weight: 4,
                color: '#87f',
                opacity: .5
            });
            line.addTo(map);

            var bounds = line.getBounds();

            map.fitBounds(bounds, {
                maxZoom: 14
            }).setMaxBounds(bounds.pad(.5));
        });
    }

    window.addEventListener('load', maybeOpenMap);

    function handleClick(event) {
        window.history.replaceState(null, null, '?date=' + date + event.target.hash);
        maybeOpenMap();
    }

    var links = document.querySelectorAll('a[href^="#journeys/"]');
    for (var i = links.length - 1; i >= 0; i -= 1) {
        links[i].addEventListener('click', handleClick);
    }

})();
<|endoftext|>


<commit_before>/* exported configureTripKeyForPath, getTripKeyFromUrl, setProgressBar */
/**
* Sets Progress Bar to correct location based on the page number
* @param {int} pageNumber
*/
function setProgressBar(pageNumber){
  let ul = document.getElementById("progressbar");
  let items = ul.getElementsByTagName("li");
  for(let i=0; i < pageNumber;i++){
    items[i].className = 'active';
  }
}

/**
 * Go through url to retrieve the trip key. If the trip key is null,
 * redirects the user to the page where they can make a new trip
 * and have a valid trip key to reference.
 * @return String of trip key
 */
function getTripKeyFromUrl() {
  const url = new URLSearchParams(location.search).get('tripKey');
  if(url === null) {
    alert("tripKey not created! Create a new trip.");
    window.location.href = '/index.html';
    return "";
  } else {
    return url;
  }
}

/**
 * Uses the trip key passed in to create a modified path from
 * the path parameter.
 * @param {String} tripKey unique value for a trip
 * @param {String} path to send tripKey across
 * @return String of path with tripKey in query params
 */
function configureTripKeyForPath(tripKey, path) {
  return path + "?" + new URLSearchParams({tripKey}).toString();
}
<commit_msg>Remove changes and apply in another PR<commit_after>/* exported configureTripKeyForPath, getTripKeyFromUrl, setProgressBar */
/**
* Sets Progress Bar to correct location based on the page number
* @param {int} pageNumber
*/
function setProgressBar(pageNumber){
  let ul = document.getElementById("progressbar");
  let items = ul.getElementsByTagName("li");
  for(let i=0; i < pageNumber;i++){
    items[i].className = 'active';
  }
}

/**
 * Go through url to retrieve the trip key.
 * @return String of trip key
 */
function getTripKeyFromUrl() {
  return new URLSearchParams(location.search).get('tripKey');
}

/**
 * Uses the trip key passed in to create a modified path from
 * the path parameter. If the trip key is null, redirects the
 * user to the page where they can make a new trip and have
 * a valid trip key to reference.
 * @param {String} tripKey unique value for a trip
 * @param {String} path to send tripKey across
 * @return String of path with tripKey in query params
 */
function configureTripKeyForPath(tripKey, path) {
  if(tripKey === null) {
    // Send back to page where a trip can be made
    alert("tripKey not created! Create a new trip.");
    window.location.href = '/index.html';
    return "";
  } else {
    return path + "?" + new URLSearchParams({tripKey}).toString();
  }
}
<|endoftext|>


<commit_before>function tag(strings, ...values){
	if( values[0] < 10 ){
		values[0] = "0"+values[0];
	}
	if( values[1] < 10 ){
		values[1] = "0"+values[1];
	}
	if( values[2] < 10 ){
		values[2] = "0"+values[2];
	}
	return `${values[0]}:${values[1]}:${values[2]}`;
}

var MyDate = function( date ){
	this.date = new Date( date );
	var timeString = function() {
		return tag`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
	};

	var addDate = function(units, interval) {
			  var ret = new Date(date); //don't change original date
			  var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
			  switch(interval.toLowerCase()) {
			    case 'year'   :  ret.setFullYear(ret.getFullYear() + units); checkRollover();  break;
			    case 'quarter':  ret.setMonth(ret.getMonth() + 3*units); checkRollover();  break;
			    case 'month'  :  ret.setMonth(ret.getMonth() + units); checkRollover();  break;
			    case 'week'   :  ret.setDate(ret.getDate() + 7*units);  break;
			    case 'day'    :  ret.setDate(ret.getDate() + units);  break;
			    case 'hour'   :  ret.setTime(ret.getTime() + units*3600000);  break;
			    case 'minute' :  ret.setTime(ret.getTime() + units*60000);  break;
			    case 'second' :  ret.setTime(ret.getTime() + units*1000);  break;
			    default       :  ret = undefined;  break;
			  }
			  date = ret;
	};

	return{
		data: this.date,
		toString: timeString,
		acrescenta: addDate
	}
}

var Timer = function( horasDeTrabalho ){
	this.counter;
	this.aviso = new Notify();
	this.horas = horasDeTrabalho.split(':')[0];
	this.minutos = horasDeTrabalho.split(':')[1];
	this.segundos = 0;
	this.countdown = {horas,minutos,segundos};
	var timeString = function() {
		return tag`${countdown.horas}:${countdown.minutos}:${countdown.segundos}`;
	};
	var countdown = function(element){
		if( countdown.segundos == 0 ){
			countdown.segundos = 60;
			countdown.minutos--;
		}else{
			countdown.segundos--;
		}

		if( countdown.minutos = 0 ){
			countdown.minutos = 60;
			countdown.horas--;
			let corpo = "Já se passaram" + horas - countdown.horas + " horas!";
			let titulo = "DING DONG!";
			let icone = "img/ic_alarm_on_black_48dp_2x.png";
			aviso.create( corpo, icone, titulo );
			aviso.send();
		}

		if( countdown.horas = 0 ){
			let corpo = "faltam" + countdown.minutos + "minutos para você ir embora!!";
			let titulo = "DING DONG!";
			let icone = "img/ic_alarm_on_black_48dp_2x.png";
			aviso.create( corpo, icone, titulo );
			aviso.send();
		}

		if( countdown.minutos == 0 && countdown.horas == 0 ){
			stopTimer();
		}

		element.textContent = timeString();
	}

	var startTimer = function(element ,interval){
		console.info( timeString() );
		counter = setInterval(function(){
			countdown( element );
		}, interval);
	}

	var stopTimer = function(){
		clearInterval( counter );
	}

	return{
		start: startTimer,
		stop: stopTimer
	}

}<commit_msg>loging<commit_after>function tag(strings, ...values){
	if( values[0] < 10 ){
		values[0] = "0"+values[0];
	}
	if( values[1] < 10 ){
		values[1] = "0"+values[1];
	}
	if( values[2] < 10 ){
		values[2] = "0"+values[2];
	}
	return `${values[0]}:${values[1]}:${values[2]}`;
}

var MyDate = function( date ){
	this.date = new Date( date );
	var timeString = function() {
		return tag`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
	};

	var addDate = function(units, interval) {
			  var ret = new Date(date); //don't change original date
			  var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
			  switch(interval.toLowerCase()) {
			    case 'year'   :  ret.setFullYear(ret.getFullYear() + units); checkRollover();  break;
			    case 'quarter':  ret.setMonth(ret.getMonth() + 3*units); checkRollover();  break;
			    case 'month'  :  ret.setMonth(ret.getMonth() + units); checkRollover();  break;
			    case 'week'   :  ret.setDate(ret.getDate() + 7*units);  break;
			    case 'day'    :  ret.setDate(ret.getDate() + units);  break;
			    case 'hour'   :  ret.setTime(ret.getTime() + units*3600000);  break;
			    case 'minute' :  ret.setTime(ret.getTime() + units*60000);  break;
			    case 'second' :  ret.setTime(ret.getTime() + units*1000);  break;
			    default       :  ret = undefined;  break;
			  }
			  date = ret;
	};

	return{
		data: this.date,
		toString: timeString,
		acrescenta: addDate
	}
}

var Timer = function( horasDeTrabalho ){
	console.debug( horasDeTrabalho );
	this.counter;
	this.aviso = new Notify();
	this.horas = horasDeTrabalho.split(':')[0];
	this.minutos = horasDeTrabalho.split(':')[1];
	this.segundos = 0;
	this.countdown = {horas,minutos,segundos};
	var timeString = function() {
		return tag`${countdown.horas}:${countdown.minutos}:${countdown.segundos}`;
	};
	var countdown = function(element){
		if( countdown.segundos == 0 ){
			countdown.segundos = 60;
			countdown.minutos--;
		}else{
			countdown.segundos--;
		}

		if( countdown.minutos = 0 ){
			countdown.minutos = 60;
			countdown.horas--;
			let corpo = "Já se passaram" + horas - countdown.horas + " horas!";
			let titulo = "DING DONG!";
			let icone = "img/ic_alarm_on_black_48dp_2x.png";
			aviso.create( corpo, icone, titulo );
			aviso.send();
		}

		if( countdown.horas = 0 ){
			let corpo = "faltam" + countdown.minutos + "minutos para você ir embora!!";
			let titulo = "DING DONG!";
			let icone = "img/ic_alarm_on_black_48dp_2x.png";
			aviso.create( corpo, icone, titulo );
			aviso.send();
		}

		if( countdown.minutos == 0 && countdown.horas == 0 ){
			stopTimer();
		}

		element.textContent = timeString();
	}

	var startTimer = function(element ,interval){
		console.info( timeString() );
		counter = setInterval(function(){
			countdown( element );
		}, interval);
	}

	var stopTimer = function(){
		clearInterval( counter );
	}

	console.debug( this );

	return{
		start: startTimer,
		stop: stopTimer
	}

}<|endoftext|>


<commit_before>Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
Components.utils.import("resource://cck2/CCK2.jsm");
var gAustralis = false;
try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  gAustralis = true;
} catch(e) {}

(function () {
  var temp = {};
  Cu.import("resource://cck2/Preferences.jsm", temp);
  var Preferences = temp.Preferences;
  let scope = {};
  Services.scriptloader.loadSubScript("chrome://cck2/content/util.js", scope);
  let {E, hide, remove, disable, errorCritical} = scope;

  var config;

  function onPageLoad(event) {
    try {
      var doc = event.target;
      var win = doc.defaultView;
      if (!doc.location) {
        return;
      }
      /* Remove the sync button from about:home */
      if ((config && config.disableSync) &&
         /^about:home/.test(doc.location.href)) {
        remove(E("sync", doc));
      }
      /* Remove the addons button from about:home */
      if ((config && config.disableAddonsManager) &&
         /^about:home/.test(doc.location.href)) {
        remove(E("addons", doc));
      }
      /* Remove the addons button from about:home */
      if ((config && config.removeSnippets) &&
         /^about:home/.test(doc.location.href)) {
        var snippets = E("snippets", doc);
        if (snippets) {
          snippets.style.display = "none";
        }
      }
      /* Remove the reset button from about:support */
      if ((config && config.disableResetFirefox) &&
         /^about:support/.test(doc.location.href)) {
        remove(E("reset-box", doc));
      }

      /* If health reporter upload is locked, remove the activation widget */
      if (Preferences.locked("datareporting.healthreport.uploadEnabled", false)) {
        if (/^https:\/\/fhr.cdn.mozilla.net\//.test(doc.location.href)) {
          var activationWidget = event.target.querySelector(".activationWidget");
          if (activationWidget) {
            remove(activationWidget);
          }
        }
      }
    } catch (e) {
      errorCritical(e);
    }
  }

  function disableSync() {
    window.XULBrowserWindow.inContentWhitelist =
      window.XULBrowserWindow.inContentWhitelist.filter(function(element) {
        return element != "about:sync-progress";
      })
    if (gSyncUI) {
      var mySyncUI = {
        init: function() {
          return;
        },
        initUI: function() {
          return;
        },
        updateUI: function() {
          hide(E("sync-setup-state"));
          hide(E("sync-syncnow-state"));
          hide(E("sync-setup"));
          hide(E("sync-syncnowitem"));
        }
      }
      gSyncUI = mySyncUI;
    }
    if (gAustralis) {
      CustomizableUI.destroyWidget("sync-button");
      CustomizableUI.removeWidgetFromArea("sync-button");
    }
    var toolbox = document.getElementById("navigator-toolbox");
    if (toolbox && toolbox.palette) {
      element = toolbox.palette.querySelector("#sync-button");
      if (element) {
        element.parentNode.removeChild(element);
      }
    }
    hide(E("sync-setup-state"));
    hide(E("sync-syncnow-state"));
    hide(E("sync-setup"));
    hide(E("sync-syncnowitem"));
  }

  function disablePrivateBrowsing() {
    disable(E("Tools:PrivateBrowsing"));
    hide(E("menu_newPrivateWindow"));
    // Because this is on a context menu, we can't use "hidden"
    if (E("context-openlinkprivate"))
      E("context-openlinkprivate").setAttribute("style", "display: none;");
    hide(E("appmenu_privateBrowsing"));
    hide(E("appmenu_newPrivateWindow"));
    hide(E("privateBrowsingItem"));
    if (gAustralis) {
      CustomizableUI.destroyWidget("privatebrowsing-button")
    }
  }

  function disableAddonsManager() {
    window.XULBrowserWindow.inContentWhitelist =
      window.XULBrowserWindow.inContentWhitelist.filter(function(element) {
        return element != "about:addons";
      })
    hide(E("appmenu_addons"));
    hide(E("menu_openAddons"));
    disable(E("Tools:Addons"));
    if (gAustralis) {
      CustomizableUI.destroyWidget("add-ons-button")
    }
  }

  function removeDeveloperTools() {
    hide(E("developer-button"));
    hide(E("webDeveloperMenu"));
    // Need to delay this because devtools is created dynamically
    window.setTimeout(function() {
      var devtoolsKeyset = document.getElementById("devtoolsKeyset");
      if (devtoolsKeyset) {
        for (var i = 0; i < devtoolsKeyset.childNodes.length; i++) {
          devtoolsKeyset.childNodes[i].removeAttribute("command");
        }
      }
    }, 0);
    try {
      document.getElementById("Tools:ResponsiveUI").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:Scratchpad").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:BrowserConsole").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:BrowserToolbox").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevAppsMgr").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevToolbar").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevToolbox").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevToolbarFocus").removeAttribute("oncommand");
    } catch (e) {}
    if (gAustralis) {
      CustomizableUI.destroyWidget("developer-button")
    }
  }

  function disableErrorConsole() {
    document.getElementById("Tools:ErrorConsole").removeAttribute("oncommand");
  }

  function onPanelShowing(event) {
    hide(E("PanelUI-fxa-status"));

  }

  function startup()
  {
    try {
      window.removeEventListener("load", startup, false);
      window.XULBrowserWindow.inContentWhitelist =
        window.XULBrowserWindow.inContentWhitelist.filter(function(element) {
          return element != "about:preferences";
        })

      var configs = CCK2.getConfigs();
      for (var id in configs) {
        config = configs[id];
        if (config.disablePrivateBrowsing &&
            PrivateBrowsingUtils.isWindowPrivate(window)) {
          window.setTimeout(function() {
            Services.prompt.alert(window, "Private Browsing", "Private Browsing has been disabled by your administrator");
            window.close();
          }, 0, false);
        }
        if (config.disablePrivateBrowsing) {
          disablePrivateBrowsing();
        }
        if (config.disableSync) {
          disableSync();
        }
        E("appcontent").addEventListener("DOMContentLoaded", onPageLoad, false);

        if (config.disableAddonsManager) {
          disableAddonsManager();
        }
        if (config.removeDeveloperTools) {
          Services.tm.mainThread.dispatch(function() {
            removeDeveloperTools();
          }, Ci.nsIThread.DISPATCH_NORMAL);
        }
        if (config.disableErrorConsole) {
          disableErrorConsole();
        }
        if (config.removeSafeModeMenu) {
          hide(E("helpSafeMode"));
          try {
            hide(E("appmenu_safeMode"));
          } catch (e) {}
        }
        if (config.titlemodifier) {
          document.getElementById("main-window").setAttribute("titlemodifier", config.titlemodifier);
        }
        if (config.removeSetDesktopBackground) {
          // Because this is on a context menu, we can't use "hidden"
          if (E("context-setDesktopBackground"))
            E("context-setDesktopBackground").setAttribute("style", "display: none;");
          }
        if (config.hiddenUI) {
          for (var i=0; i < config.hiddenUI.length; i++) {
            var uiElements = document.querySelectorAll(config.hiddenUI[i]);
            // Don't use .hidden since it doesn't work sometimes
            var style = document.getElementById("cck2-hidden-style");
            if (!style) {
              style = document.createElementNS("http://www.w3.org/1999/xhtml", "style");
              style.setAttribute("id", "cck2-hidden-style");
              style.setAttribute("type", "text/css");
              document.getElementById("main-window").appendChild(style);
            }
            style.textContent = style.textContent + config.hiddenUI[i] + "{display: none !important;}";
            if (!uiElements || uiElements.length == 0) {
              continue;
            }
            for (var j=0; j < uiElements.length; j++) {
              var uiElement = uiElements[j];
              if (uiElement.nodeName == "menuitem") {
                uiElement.removeAttribute("key");
                uiElement.removeAttribute("oncommand");
                if (uiElement.hasAttribute("command")) {
                  var commandId = uiElement.getAttribute("command");
                  uiElement.removeAttribute("command");
                  var command = document.getElementById(commandId);
                  command.removeAttribute("oncommand");
                  var keys = document.querySelectorAll("key[command='" + commandId + "']")
                  for (var k=0; k < keys.length; k++) {
                    keys[k].removeAttribute("command");
                  }
                }
              }
            }
          }
        }
        if (config.helpMenu) {
          // We need to run this function on a delay, because we won't know
          // if the about menu is hidden for mac until after it is run.
          Services.tm.mainThread.dispatch(function() {
            var helpMenuPopup = document.getElementById("menu_HelpPopup");
            var menuitem = document.createElement("menuitem");
            menuitem.setAttribute("label", config.helpMenu.label);
            if ("accesskey" in config.helpMenu) {
              menuitem.setAttribute("accesskey", config.helpMenu.accesskey);
            }
            menuitem.setAttribute("oncommand", "openUILink(" + config.helpMenu.url.quote() + ");");
            menuitem.setAttribute("onclick", "checkForMiddleClick(this, event);");
            if (!E("aboutName") || E("aboutName").hidden) {
              // Mac
              helpMenuPopup.appendChild(menuitem);
            } else {
              helpMenuPopup.insertBefore(menuitem, E("aboutName"));
              helpMenuPopup.insertBefore(document.createElement("menuseparator"),
                                                E("aboutName"));
            }
          }, Ci.nsIThread.DISPATCH_NORMAL);
          var appMenuHelpMenuPopup = document.getElementById("appmenu_helpMenupopup");
          if (appMenuHelpMenuPopup) {
            var menuitem = document.createElement("menuitem");
            menuitem.setAttribute("label", config.helpMenu.label);
            menuitem.setAttribute("url", config.helpMenu.url);
            menuitem.addEventListener("command", function(event) {
              openUILink(this.getAttribute("url"), event, false, true);
            })
            menuitem.addEventListener("click", function(event) {
              checkForMiddleClick(this, event);
            }, false);
            appMenuHelpMenuPopup.insertBefore(menuitem, E("appmenu_about"));
            appMenuHelpMenuPopup.insertBefore(document.createElement("menuseparator"),
                                              E("appmenu_about"));
          }
        }
        if (config.firstrun || config.upgrade) {
          if (config.displayBookmarksToolbar || (config.bookmarks && config.bookmarks.toolbar)) {
            E("PersonalToolbar").collapsed = false;
            E("PersonalToolbar").setAttribute("collapsed", "false");
            document.persist("PersonalToolbar", "collapsed");
          }
          if (config.displayMenuBar) {
            if (typeof updateAppButtonDisplay != "undefined") {
              E("toolbar-menubar").setAttribute("autohide", "false");
              document.persist("toolbar-menubar", "autohide")
              updateAppButtonDisplay();
            }
            if (gAustralis) {
              CustomizableUI.setToolbarVisibility("toolbar-menubar", "true");
            }

          }
          config.firstrun = false;
          config.upgrade = false;
        }
      }
      var panelUIPopup = document.getElementById("PanelUI-popup");
      if (panelUIPopup) {
        document.getElementById("PanelUI-popup").addEventListener("popupshowing", onPanelShowing, false);
      }
    } catch (e) {
      errorCritical(e);
    }
  }

  function shutdown()
  {
    window.removeEventListener("unload", shutdown, false);
    var appcontent = E("appcontent");
    if (appcontent) {
       appcontent.removeEventListener("DOMContentLoaded", onPageLoad, false);
    }
    var panelUIPopup = document.getElementById("PanelUI-popup");
    if (panelUIPopup) {
      document.getElementById("PanelUI-popup").removeEventListener("popupshowing", onPanelShowing, false);
    }
  }

  window.addEventListener("load", startup, false);
  window.addEventListener("unload", shutdown, false);
})();
<commit_msg>Extra code to remove helpmenu items<commit_after>Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
Components.utils.import("resource://cck2/CCK2.jsm");
var gAustralis = false;
try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  gAustralis = true;
} catch(e) {}

(function () {
  var temp = {};
  Cu.import("resource://cck2/Preferences.jsm", temp);
  var Preferences = temp.Preferences;
  let scope = {};
  Services.scriptloader.loadSubScript("chrome://cck2/content/util.js", scope);
  let {E, hide, remove, disable, errorCritical} = scope;

  var config;

  function onPageLoad(event) {
    try {
      var doc = event.target;
      var win = doc.defaultView;
      if (!doc.location) {
        return;
      }
      /* Remove the sync button from about:home */
      if ((config && config.disableSync) &&
         /^about:home/.test(doc.location.href)) {
        remove(E("sync", doc));
      }
      /* Remove the addons button from about:home */
      if ((config && config.disableAddonsManager) &&
         /^about:home/.test(doc.location.href)) {
        remove(E("addons", doc));
      }
      /* Remove the addons button from about:home */
      if ((config && config.removeSnippets) &&
         /^about:home/.test(doc.location.href)) {
        var snippets = E("snippets", doc);
        if (snippets) {
          snippets.style.display = "none";
        }
      }
      /* Remove the reset button from about:support */
      if ((config && config.disableResetFirefox) &&
         /^about:support/.test(doc.location.href)) {
        remove(E("reset-box", doc));
      }

      /* If health reporter upload is locked, remove the activation widget */
      if (Preferences.locked("datareporting.healthreport.uploadEnabled", false)) {
        if (/^https:\/\/fhr.cdn.mozilla.net\//.test(doc.location.href)) {
          var activationWidget = event.target.querySelector(".activationWidget");
          if (activationWidget) {
            remove(activationWidget);
          }
        }
      }
    } catch (e) {
      errorCritical(e);
    }
  }

  function disableSync() {
    window.XULBrowserWindow.inContentWhitelist =
      window.XULBrowserWindow.inContentWhitelist.filter(function(element) {
        return element != "about:sync-progress";
      })
    if (gSyncUI) {
      var mySyncUI = {
        init: function() {
          return;
        },
        initUI: function() {
          return;
        },
        updateUI: function() {
          hide(E("sync-setup-state"));
          hide(E("sync-syncnow-state"));
          hide(E("sync-setup"));
          hide(E("sync-syncnowitem"));
        }
      }
      gSyncUI = mySyncUI;
    }
    if (gAustralis) {
      CustomizableUI.destroyWidget("sync-button");
      CustomizableUI.removeWidgetFromArea("sync-button");
    }
    var toolbox = document.getElementById("navigator-toolbox");
    if (toolbox && toolbox.palette) {
      element = toolbox.palette.querySelector("#sync-button");
      if (element) {
        element.parentNode.removeChild(element);
      }
    }
    hide(E("sync-setup-state"));
    hide(E("sync-syncnow-state"));
    hide(E("sync-setup"));
    hide(E("sync-syncnowitem"));
  }

  function disablePrivateBrowsing() {
    disable(E("Tools:PrivateBrowsing"));
    hide(E("menu_newPrivateWindow"));
    // Because this is on a context menu, we can't use "hidden"
    if (E("context-openlinkprivate"))
      E("context-openlinkprivate").setAttribute("style", "display: none;");
    hide(E("appmenu_privateBrowsing"));
    hide(E("appmenu_newPrivateWindow"));
    hide(E("privateBrowsingItem"));
    if (gAustralis) {
      CustomizableUI.destroyWidget("privatebrowsing-button")
    }
  }

  function disableAddonsManager() {
    window.XULBrowserWindow.inContentWhitelist =
      window.XULBrowserWindow.inContentWhitelist.filter(function(element) {
        return element != "about:addons";
      })
    hide(E("appmenu_addons"));
    hide(E("menu_openAddons"));
    disable(E("Tools:Addons"));
    if (gAustralis) {
      CustomizableUI.destroyWidget("add-ons-button")
    }
  }

  function removeDeveloperTools() {
    hide(E("developer-button"));
    hide(E("webDeveloperMenu"));
    // Need to delay this because devtools is created dynamically
    window.setTimeout(function() {
      var devtoolsKeyset = document.getElementById("devtoolsKeyset");
      if (devtoolsKeyset) {
        for (var i = 0; i < devtoolsKeyset.childNodes.length; i++) {
          devtoolsKeyset.childNodes[i].removeAttribute("command");
        }
      }
    }, 0);
    try {
      document.getElementById("Tools:ResponsiveUI").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:Scratchpad").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:BrowserConsole").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:BrowserToolbox").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevAppsMgr").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevToolbar").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevToolbox").removeAttribute("oncommand");
    } catch (e) {}
    try {
      document.getElementById("Tools:DevToolbarFocus").removeAttribute("oncommand");
    } catch (e) {}
    if (gAustralis) {
      CustomizableUI.destroyWidget("developer-button")
    }
  }

  function disableErrorConsole() {
    document.getElementById("Tools:ErrorConsole").removeAttribute("oncommand");
  }

  function onPanelShowing(event) {
    hide(E("PanelUI-fxa-status"));

  }

  function startup()
  {
    try {
      window.removeEventListener("load", startup, false);
      // Replace setReportPhishingMenu so we can catch errors
      var origSetReportPhishingMenu = gSafeBrowsing.setReportPhishingMenu;
      gSafeBrowsing.setReportPhishingMenu = function() {
        try {
          origSetReportPhishingMenu();
        } catch (e) {}
      }
      window.XULBrowserWindow.inContentWhitelist =
        window.XULBrowserWindow.inContentWhitelist.filter(function(element) {
          return element != "about:preferences";
        })

      var configs = CCK2.getConfigs();
      for (var id in configs) {
        config = configs[id];
        if (config.disablePrivateBrowsing &&
            PrivateBrowsingUtils.isWindowPrivate(window)) {
          window.setTimeout(function() {
            Services.prompt.alert(window, "Private Browsing", "Private Browsing has been disabled by your administrator");
            window.close();
          }, 0, false);
        }
        if (config.disablePrivateBrowsing) {
          disablePrivateBrowsing();
        }
        if (config.disableSync) {
          disableSync();
        }
        E("appcontent").addEventListener("DOMContentLoaded", onPageLoad, false);

        if (config.disableAddonsManager) {
          disableAddonsManager();
        }
        if (config.removeDeveloperTools) {
          Services.tm.mainThread.dispatch(function() {
            removeDeveloperTools();
          }, Ci.nsIThread.DISPATCH_NORMAL);
        }
        if (config.disableErrorConsole) {
          disableErrorConsole();
        }
        if (config.removeSafeModeMenu) {
          hide(E("helpSafeMode"));
          try {
            hide(E("appmenu_safeMode"));
          } catch (e) {}
        }
        if (config.titlemodifier) {
          document.getElementById("main-window").setAttribute("titlemodifier", config.titlemodifier);
        }
        if (config.removeSetDesktopBackground) {
          // Because this is on a context menu, we can't use "hidden"
          if (E("context-setDesktopBackground"))
            E("context-setDesktopBackground").setAttribute("style", "display: none;");
          }
        if (config.hiddenUI) {
          for (var i=0; i < config.hiddenUI.length; i++) {
            var uiElements = document.querySelectorAll(config.hiddenUI[i]);
            // Don't use .hidden since it doesn't work sometimes
            var style = document.getElementById("cck2-hidden-style");
            if (!style) {
              style = document.createElementNS("http://www.w3.org/1999/xhtml", "style");
              style.setAttribute("id", "cck2-hidden-style");
              style.setAttribute("type", "text/css");
              document.getElementById("main-window").appendChild(style);
            }
            style.textContent = style.textContent + config.hiddenUI[i] + "{display: none !important;}";
            if (!uiElements || uiElements.length == 0) {
              continue;
            }
            for (var j=0; j < uiElements.length; j++) {
              var uiElement = uiElements[j];
              if (uiElement.nodeName == "menuitem") {
                uiElement.removeAttribute("key");
                uiElement.removeAttribute("oncommand");
                if (uiElement.hasAttribute("command")) {
                  var commandId = uiElement.getAttribute("command");
                  uiElement.removeAttribute("command");
                  var command = document.getElementById(commandId);
                  command.removeAttribute("oncommand");
                  var keys = document.querySelectorAll("key[command='" + commandId + "']")
                  for (var k=0; k < keys.length; k++) {
                    keys[k].removeAttribute("command");
                  }
                }
              }
              // Horrible hack to work around the crappy Australis help menu
              // Items on the menu always show up in the Australis menu, so we have to remove them.
              if (uiElements[j].parentNode.id == "menu_HelpPopup") {
                uiElements[j].parentNode.removeChild(uiElements[j]);
              }
            }
          }
        }
        if (config.helpMenu) {
          // We need to run this function on a delay, because we won't know
          // if the about menu is hidden for mac until after it is run.
          Services.tm.mainThread.dispatch(function() {
            var helpMenuPopup = document.getElementById("menu_HelpPopup");
            var menuitem = document.createElement("menuitem");
            menuitem.setAttribute("label", config.helpMenu.label);
            if ("accesskey" in config.helpMenu) {
              menuitem.setAttribute("accesskey", config.helpMenu.accesskey);
            }
            menuitem.setAttribute("oncommand", "openUILink(" + config.helpMenu.url.quote() + ");");
            menuitem.setAttribute("onclick", "checkForMiddleClick(this, event);");
            if (!E("aboutName") || E("aboutName").hidden) {
              // Mac
              helpMenuPopup.appendChild(menuitem);
            } else {
              helpMenuPopup.insertBefore(menuitem, E("aboutName"));
              helpMenuPopup.insertBefore(document.createElement("menuseparator"),
                                                E("aboutName"));
            }
          }, Ci.nsIThread.DISPATCH_NORMAL);
          var appMenuHelpMenuPopup = document.getElementById("appmenu_helpMenupopup");
          if (appMenuHelpMenuPopup) {
            var menuitem = document.createElement("menuitem");
            menuitem.setAttribute("label", config.helpMenu.label);
            menuitem.setAttribute("url", config.helpMenu.url);
            menuitem.addEventListener("command", function(event) {
              openUILink(this.getAttribute("url"), event, false, true);
            })
            menuitem.addEventListener("click", function(event) {
              checkForMiddleClick(this, event);
            }, false);
            appMenuHelpMenuPopup.insertBefore(menuitem, E("appmenu_about"));
            appMenuHelpMenuPopup.insertBefore(document.createElement("menuseparator"),
                                              E("appmenu_about"));
          }
        }
        if (config.firstrun || config.upgrade) {
          if (config.displayBookmarksToolbar || (config.bookmarks && config.bookmarks.toolbar)) {
            E("PersonalToolbar").collapsed = false;
            E("PersonalToolbar").setAttribute("collapsed", "false");
            document.persist("PersonalToolbar", "collapsed");
          }
          if (config.displayMenuBar) {
            if (typeof updateAppButtonDisplay != "undefined") {
              E("toolbar-menubar").setAttribute("autohide", "false");
              document.persist("toolbar-menubar", "autohide")
              updateAppButtonDisplay();
            }
            if (gAustralis) {
              CustomizableUI.setToolbarVisibility("toolbar-menubar", "true");
            }

          }
          config.firstrun = false;
          config.upgrade = false;
        }
      }
      var panelUIPopup = document.getElementById("PanelUI-popup");
      if (panelUIPopup) {
        document.getElementById("PanelUI-popup").addEventListener("popupshowing", onPanelShowing, false);
      }
    } catch (e) {
      errorCritical(e);
    }
  }

  function shutdown()
  {
    window.removeEventListener("unload", shutdown, false);
    var appcontent = E("appcontent");
    if (appcontent) {
       appcontent.removeEventListener("DOMContentLoaded", onPageLoad, false);
    }
    var panelUIPopup = document.getElementById("PanelUI-popup");
    if (panelUIPopup) {
      document.getElementById("PanelUI-popup").removeEventListener("popupshowing", onPanelShowing, false);
    }
  }

  window.addEventListener("load", startup, false);
  window.addEventListener("unload", shutdown, false);
})();
<|endoftext|>