<commit_before>module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        clean: {
            build: ['build']
        },

        browserify: {
            standalone: {
                dest: './build/entropy.js',
                src: [ './src/entropy.js' ],
                options: {
                    browserifyOptions: {
                        standalone: 'Entropy'
                    }
                }
            }
        },

        uglify: {
            options: {
                banner: '/**\n* <%= pkg.name %> <%= pkg.version %> - framework for making games and not only games in entity system manner - build: <%= grunt.template.today("yyyy-mm-dd") %>\n*\n* @author       Tymoteusz Dzienniak <tymoteusz.dzienniak@outlook.com>\n* @license      {@link https://github.com/RainPhilosopher/Entropy/blob/master/LICENSE|MIT License}\n*/\n',
                //       + '"use strict";',
                mangle: true,
                sourceMap: true,
                sourceMapName: 'build/entropy.map.js'
                //wrap: true
            },
            build: {
                files: {
                  'build/entropy.min.js': ['./build/entropy.js']
                }
            }
        },

        yuidoc: {
            compile: {
                name: 'Entropy',
                description: '<%= pkg.description %>',
                version: '<%= pkg.version %>',
                logo: '../entropy.png',
                options: {
                    paths: ['./src', './plugins'],
                    outdir: './docs'
                }
            }
        },

        qunit: {
            all: ['test/*.html']
        }
    });

    // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');

    // Default task(s).
    grunt.registerTask('default', ['clean', 'browserify', 'uglify', 'yuidoc']);

};
<commit_msg>Refined build process<commit_after>module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        clean: {
            build: ['build']
        },

        browserify: {
            core: {
                dest: './build/entropy.js',
                src: [ './src/entropy.js' ],
                options: {
                    browserifyOptions: {
                        standalone: 'Entropy'
                    }
                }
            },
            plugins: {
                dest: './build/entropy-plugins.js',
                src: [ './plugins/index.js' ]
            }
        },

        uglify: {
            core: {
                options: {
                    banner: '/**\n* <%= pkg.name %> <%= pkg.version %> - framework for making games and not only games in entity system manner - build: <%= grunt.template.today("yyyy-mm-dd") %>\n*\n* @author       Tymoteusz Dzienniak <tymoteusz.dzienniak@outlook.com>\n* @license      {@link https://github.com/RainPhilosopher/Entropy/blob/master/LICENSE|MIT License}\n*/\n',
                    //       + '"use strict";',
                    mangle: true,
                    sourceMap: true,
                    sourceMapName: 'build/entropy.map.js'
                    //wrap: true
                },
                files: {
                  'build/entropy.min.js': ['./build/entropy.js']
                }
            },
            plugins: {
                options: {
                    banner: '/**\n* <%= pkg.name %> <%= pkg.version %> - framework for making games and not only games in entity system manner - build: <%= grunt.template.today("yyyy-mm-dd") %>\n*\n* @author       Tymoteusz Dzienniak <tymoteusz.dzienniak@outlook.com>\n* @license      {@link https://github.com/RainPhilosopher/Entropy/blob/master/LICENSE|MIT License}\n*/\n',
                    //       + '"use strict";',
                    mangle: true,
                    sourceMap: true,
                    sourceMapName: 'build/entropy-plugins.map.js'
                    //wrap: true
                },
                files: {
                  'build/entropy-plugins.min.js': ['./build/entropy-plugins.js']
                }
            }
        },

        yuidoc: {
            compile: {
                name: 'Entropy',
                description: '<%= pkg.description %>',
                version: '<%= pkg.version %>',
                logo: '../entropy.png',
                options: {
                    paths: ['./src', './plugins'],
                    outdir: './docs'
                }
            }
        }
    });

    // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');

    // Default task(s).
    grunt.registerTask('build-core', ['clean', 'browserify:core', 'uglify:core']);
    grunt.registerTask('build-plugins', ['browserify:plugins', 'uglify:plugins']);
    grunt.registerTask('build-docs', ['yuidoc']);
    grunt.registerTask('build', ['build-core', 'build-plugins', 'build-docs']);

};
<|endoftext|>


<commit_before>'use strict'

const { ApolloServer } = require('apollo-server-lambda')

const config = require('./utils/config')
const connect = require('./utils/connect')
const fullyQualifiedDomainNames = require('./utils/fullyQualifiedDomainNames')
const createApolloServer = require('./utils/createApolloServer')
const { createServerlessContext } = require('./utils/createContext')

if (config.dbUrl == null) {
	throw new Error('MongoDB connection URI missing in environment')
}

connect(config.dbUrl)

const apolloServer = createApolloServer(ApolloServer, {
	context: createServerlessContext,
})

const origin = (origin, callback) => {
	if (config.autoOrigin === true) {
		fullyQualifiedDomainNames()
			.then((names) => {
				console.log('Got qualified domains', names)
				return callback(
					null,
					names.flatMap((name) => [ `http://${ name }`, `https://${ names }`, name ]),
				)
			})
			.catch((error) => callback(error, false))
		return
	}

	if (config.allowOrigin === '*') {
		callback(null, true)
		return
	}

	if (config.allowOrigin != null) {
		callback(null, config.allowOrigin.split(','))
		return
	}

	callback(null, false)
	return
}

exports.handler = (event, context) => {
	// Set request context which is missing on Vercel
	// https://stackoverflow.com/questions/71360059/apollo-server-lambda-unable-to-determine-event-source-based-on-event
	if (event.requestContext == null) event.requestContext = context

	const handler = apolloServer.createHandler({
		expressGetMiddlewareOptions: {
			cors: {
				origin,
				credentials: true,
				methods: 'GET,POST,PATCH,OPTIONS',
				allowedHeaders: 'Content-Type, Authorization, Time-Zone',
			},
		},
	})

	const response = handler(event, context)
	response.then((value) => console.log('Response', value))
	return response
}<commit_msg>fix: typo in returned domains<commit_after>'use strict'

const { ApolloServer } = require('apollo-server-lambda')

const config = require('./utils/config')
const connect = require('./utils/connect')
const fullyQualifiedDomainNames = require('./utils/fullyQualifiedDomainNames')
const createApolloServer = require('./utils/createApolloServer')
const { createServerlessContext } = require('./utils/createContext')

if (config.dbUrl == null) {
	throw new Error('MongoDB connection URI missing in environment')
}

connect(config.dbUrl)

const apolloServer = createApolloServer(ApolloServer, {
	context: createServerlessContext,
})

const origin = (origin, callback) => {
	if (config.autoOrigin === true) {
		fullyQualifiedDomainNames()
			.then((names) => {
				console.log('Got qualified domains', names)
				return callback(
					null,
					names.flatMap((name) => [ `http://${ name }`, `https://${ name }`, name ]),
				)
			})
			.catch((error) => callback(error, false))
		return
	}

	if (config.allowOrigin === '*') {
		callback(null, true)
		return
	}

	if (config.allowOrigin != null) {
		callback(null, config.allowOrigin.split(','))
		return
	}

	callback(null, false)
	return
}

exports.handler = (event, context) => {
	// Set request context which is missing on Vercel
	// https://stackoverflow.com/questions/71360059/apollo-server-lambda-unable-to-determine-event-source-based-on-event
	if (event.requestContext == null) event.requestContext = context

	const handler = apolloServer.createHandler({
		expressGetMiddlewareOptions: {
			cors: {
				origin,
				credentials: true,
				methods: 'GET,POST,PATCH,OPTIONS',
				allowedHeaders: 'Content-Type, Authorization, Time-Zone',
			},
		},
	})

	const response = handler(event, context)
	response.then((value) => console.log('Response', value))
	return response
}<|endoftext|>


<commit_before>// Generated on 2014-04-17 using generator-angular 0.8.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  grunt.loadNpmTasks('grunt-bump');
  grunt.loadNpmTasks('grunt-version');
  grunt.loadNpmTasks('grunt-contrib-sass');

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },

    version: {
      options: {
        pkg: 'package.json'
      },
      update: {
        options: {
          prefix: 'var version\\s+=\\s+[\'"]'
        },
        src: ['app/scripts/initializers/modules.js']
      },
    },

    bump: {
      options: {
        files: ['package.json'],
        updateConfigs: [],
        commit: true,
        push: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json', 'app/scripts/initializers/modules.js'], // '-a' for all files
        createTag: true,
        tagName: 'v%VERSION%',
        tagMessage: 'Version %VERSION%',
        pushTo: 'origin'
        // gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' // options to use with '$ git describe'
      }
    },

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['bowerInstall']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,**/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: true
        }
      },
      jsTest: {
        files: ['test/spec/{,**/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      sass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['sass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ]
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,**/}*.js'
      ],
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,**/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    bowerInstall: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath: '<%= yeoman.app %>/',
        exclude: [/cryptojs/, /bootstrap\-sass\-official/]
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: '<%= yeoman.app %>/bower_components/'
      }
    },

    sass: {
      dist: {
        options: {
          loadPath: '<%= yeoman.app %>/styles/ui-kit',
          style: 'expanded'
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/styles',
          src: ['*.scss'],
          dest: '<%= yeoman.app %>/styles',
          ext: '.css'
        }]
      }
    },

    // // Compiles Sass to CSS and generates necessary files if requested
    // compass: {
    //   options: {
    //     sassDir: '<%= yeoman.app %>/styles',
    //     cssDir: '<%= yeoman.app %>/styles',//'.tmp/styles',
    //     generatedImagesDir: '.tmp/images/generated',
    //     imagesDir: '<%= yeoman.app %>/images',
    //     javascriptsDir: '<%= yeoman.app %>/scripts',
    //     fontsDir: '<%= yeoman.app %>/styles/fonts',
    //     importPath: ['<%= yeoman.app %>/bower_components', '<%= yeoman.app %>/styles/ui-kit'],
    //     httpImagesPath: '/images',
    //     httpGeneratedImagesPath: '/images/generated',
    //     httpFontsPath: '/styles/fonts',
    //     relativeAssets: false,
    //     assetCacheBuster: false,
    //     raw: 'Sass::Script::Number.precision = 10\n'
    //   },
    //   dist: {
    //     options: {
    //       generatedImagesDir: '<%= yeoman.dist %>/images/generated'
    //     }
    //   },
    //   server: {
    //     options: {
    //       debugInfo: true
    //     }
    //   }
    // },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            // '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat'/*, 'uglifyjs'*/],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>']
      }
    },

    // The following *-min tasks produce minified files in the dist folder
    cssmin: {
      options: {
        root: '<%= yeoman.app %>'
      }
    },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ngmin tries to make the code safe for minification automatically by
    // using the Angular long form for dependency injection. It doesn't work on
    // things like resolve or inject so those have to be done manually.
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,**/}*.html',
            'scripts/directives/templates/{,**/}*.html',
            'images/{,**/}*',
            'fonts/*',
            'i18n/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'sass'
      ],
      test: [
        'sass'
      ],
      dist: [
        'sass',
        'imagemin',
        'svgmin'
      ]
    },

    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%= yeoman.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'bowerInstall',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('patch', [
    'bump-only:patch',
    'version:update',
    'bump-commit'
  ]);

  grunt.registerTask('minor', [
    'bump-only:minor',
    'version:update',
    'bump-commit'
  ]);

  grunt.registerTask('major', [
    'bump-only:major',
    'version:update',
    'bump-commit'
  ]);

  grunt.registerTask('build', [
    'newer:jshint',
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'concat',
    'ngmin',
    'copy:dist',
    'cssmin',
    // 'uglify',
    'rev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>chore(grunt): ignore bowerInstall<commit_after>// Generated on 2014-04-17 using generator-angular 0.8.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  grunt.loadNpmTasks('grunt-bump');
  grunt.loadNpmTasks('grunt-version');
  grunt.loadNpmTasks('grunt-contrib-sass');

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },

    version: {
      options: {
        pkg: 'package.json'
      },
      update: {
        options: {
          prefix: 'var version\\s+=\\s+[\'"]'
        },
        src: ['app/scripts/initializers/modules.js']
      },
    },

    bump: {
      options: {
        files: ['package.json'],
        updateConfigs: [],
        commit: true,
        push: true,
        commitMessage: 'Release v%VERSION%',
        commitFiles: ['package.json', 'app/scripts/initializers/modules.js'], // '-a' for all files
        createTag: true,
        tagName: 'v%VERSION%',
        tagMessage: 'Version %VERSION%',
        pushTo: 'origin'
        // gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' // options to use with '$ git describe'
      }
    },

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['bowerInstall']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,**/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: true
        }
      },
      jsTest: {
        files: ['test/spec/{,**/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      sass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['sass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ]
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,**/}*.js'
      ],
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,**/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    bowerInstall: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath: '<%= yeoman.app %>/',
        exclude: [/cryptojs/, /bootstrap\-sass\-official/]
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: '<%= yeoman.app %>/bower_components/'
      }
    },

    sass: {
      dist: {
        options: {
          loadPath: '<%= yeoman.app %>/styles/ui-kit',
          style: 'expanded'
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/styles',
          src: ['*.scss'],
          dest: '<%= yeoman.app %>/styles',
          ext: '.css'
        }]
      }
    },

    // // Compiles Sass to CSS and generates necessary files if requested
    // compass: {
    //   options: {
    //     sassDir: '<%= yeoman.app %>/styles',
    //     cssDir: '<%= yeoman.app %>/styles',//'.tmp/styles',
    //     generatedImagesDir: '.tmp/images/generated',
    //     imagesDir: '<%= yeoman.app %>/images',
    //     javascriptsDir: '<%= yeoman.app %>/scripts',
    //     fontsDir: '<%= yeoman.app %>/styles/fonts',
    //     importPath: ['<%= yeoman.app %>/bower_components', '<%= yeoman.app %>/styles/ui-kit'],
    //     httpImagesPath: '/images',
    //     httpGeneratedImagesPath: '/images/generated',
    //     httpFontsPath: '/styles/fonts',
    //     relativeAssets: false,
    //     assetCacheBuster: false,
    //     raw: 'Sass::Script::Number.precision = 10\n'
    //   },
    //   dist: {
    //     options: {
    //       generatedImagesDir: '<%= yeoman.dist %>/images/generated'
    //     }
    //   },
    //   server: {
    //     options: {
    //       debugInfo: true
    //     }
    //   }
    // },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            // '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat'/*, 'uglifyjs'*/],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>']
      }
    },

    // The following *-min tasks produce minified files in the dist folder
    cssmin: {
      options: {
        root: '<%= yeoman.app %>'
      }
    },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ngmin tries to make the code safe for minification automatically by
    // using the Angular long form for dependency injection. It doesn't work on
    // things like resolve or inject so those have to be done manually.
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,**/}*.html',
            'scripts/directives/templates/{,**/}*.html',
            'images/{,**/}*',
            'fonts/*',
            'i18n/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'sass'
      ],
      test: [
        'sass'
      ],
      dist: [
        'sass',
        'imagemin',
        'svgmin'
      ]
    },

    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%= yeoman.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      // 'bowerInstall',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('patch', [
    'bump-only:patch',
    'version:update',
    'bump-commit'
  ]);

  grunt.registerTask('minor', [
    'bump-only:minor',
    'version:update',
    'bump-commit'
  ]);

  grunt.registerTask('major', [
    'bump-only:major',
    'version:update',
    'bump-commit'
  ]);

  grunt.registerTask('build', [
    'newer:jshint',
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'concat',
    'ngmin',
    'copy:dist',
    'cssmin',
    // 'uglify',
    'rev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>$('div#main-menu a').each(function () {
    if ($(this)[0].pathname == window.location.pathname) {
        $(this).addClass('active').removeAttr('href');
        return false;
    }
});

$('div#account-dropdown').removeClass('simple').dropdown();
<commit_msg>Add nested pages to active<commit_after>$('div#main-menu a').each(function () {

    let cur_path = window.location.pathname.split('/')[1],
        a_path = $(this)[0].pathname.split('/')[1];

    if (cur_path === a_path) {
        $(this).addClass('active').removeAttr('href');
        return false;
    }
});

$('div#main-menu .dropdown').removeClass('simple').dropdown();

<|endoftext|>


<commit_before>/*
  Copyright 2010-2017 BusinessCode GmbH, Germany

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
"use strict";
bcdui.core.HTML2XMLDataProvider = bcdui._migPjs._classCreate(bcdui.core.DataProvider,
    /**
     * @lends bcdui.core.HTML2XMLDataProvider.prototype
     */
    {

      /**
       * @constructs
       * @extends bcdui.core.DataProvider
       * @param {Object} args
       * @param {String} args.id
       * @param {String} args.name
       * @param {(String|HTMLElement)} args.idOrElement
       *
       */
      initialize: function(/* object */ args)
      {
          bcdui.log.isTraceEnabled() && bcdui.log.trace("HTML2XMLDataProvider init");
          bcdui.core.DataProvider.call( this, {
            id: args.id,
            name: args.name
          });

          this.waitingForUncomittedChanges = new bcdui.core.status.WaitingForUncomittedChanges();
          this.transformedStatus = new bcdui.core.status.TransformedStatus();

          this.doc = null;
          this.idOrElement = args.idOrElement;
      },

      /**
       * @private
       */
      _createModelDocument:function()
      {
        bcdui.log.isTraceEnabled() && bcdui.log.trace("this.idOrElement:"+this.idOrElement);
        var rElement = bcdui._migPjs._$(this.idOrElement);
        this.doc = bcdui.core.browserCompatibility.newDOMDocument();
        var root = this.doc.createElement("Items");
        var tabId =  "tab_" + (rElement.get(0).id || bcdui.factory.objectRegistry.generateTemporaryIdInScope("tab_"));
        root.setAttribute("id", tabId);
        root.setAttribute("defaultVisibleId", (rElement.attr("defaultVisibleId")==null || rElement.attr("defaultVisibleId") == "")?"FIRST":rElement.attr("defaultVisibleId"));

        this.doc.appendChild(root);

        rElement.children().each(function(i, element) {// all children of idOrElement
          jQuery(element).addClass("bcdTabItem");
          var e = this.doc.documentElement.appendChild(this.doc.createElement("Item"));
          e.setAttribute("id", "tab_"+element.id);
          e.setAttribute("caption", (element.getAttribute("caption")==null)?"":element.getAttribute("caption"));
          e.setAttribute("enabled", (element.getAttribute("enabled")==null)?"":element.getAttribute("enabled"));
          e.setAttribute("toolTip", (element.getAttribute("toolTip")==null)?"":element.getAttribute("toolTip"));
          e.setAttribute("onclick", (element.getAttribute("onclick")==null)?"":element.getAttribute("onclick"));
        }.bind(this));

      },

      /**
       * @private
       */
      _executeImpl: function()
        {
          this._createModelDocument();
          var newStatus = this._uncommitedWrites ? this.waitingForUncomittedChanges : this.getReadyStatus();
          this.setStatus(newStatus);
        },

      getData: function()
        {
          return this.doc;
        },

      /**
       * @return {status}
       */
      getReadyStatus: function()
        {
          return this.transformedStatus;
        }
    }
);

/**
 * XSLT creates ul li li /ul for TABs
 * gets as parameter root html element where are content DIVs/HTML elements defined
 * parsed the HTML element to get count of Tabs, captions, references to content elements, may be some defult settings (width, height, position ...)
 *
 * sample:
 *

 *

 *

 *

 *

 *
 * than after parsing creates such UL
 *

 *

 *

 *

 *

 *
 */
/**
 * A namespace for the BCD-UI tab widget.
 * @namespace bcdui.widget.tab
 * @private
 */
bcdui.util.namespace("bcdui.widget.tab",
/** @lends bcdui.widget.tab */
{
    /**
     * @param {Object} args
     * @param {Object} args.id:                  - tab id
     * @param {Object} args.rendererUrl          - URL to renderer xslt stylesheet
     * @param {Object} args.rendererId           - renderer id
     * @param {Object} args.handlerJsClassName   - Tab menu handler variable name, default bcdui.widget.tab
     * @param {Object} args.targetHTMLElementId  - target where HTML content to paste to
     * @param {Object} args.idOrElement          - id of/or HTML element where tabs are defined
     * @param {Object} args.isPersistent         - use guiStatus:PersistentSettings or guiStatus:ClientSettings
     * @private
     *
     */
    init:function(args)
    {

      var settingsNode = args.isPersistent ? "PersistentSettings" : "ClientSettings";

      var dataProvider = new bcdui.core.HTML2XMLDataProvider( {
        id:          args.id + "_innerModel"
      , name:        args.id + "_innerModel"
      , idOrElement:  bcdui._migPjs._$(args.idOrElement).get(0)
      });
      dataProvider.execute();

      // read settings from GUIstatus doc, if exists XPath - takes it, if no - set default to visible
      var tabId = dataProvider.getData().selectSingleNode("/Items/@id").nodeValue;
      var guiStatusTabXPath = "/*/guiStatus:" + settingsNode + "/Selected/Tab[@id = '" + tabId +"']";

      // register listener which shows/hides the selected tab
      bcdui.wkModels.guiStatus.onChange({
          onlyOnce: false
        , trackingXPath: guiStatusTabXPath
        , callback: bcdui.widget.tab._syncActiveTab.bind(undefined, tabId, args.targetHTMLElementId, args.idOrElement, settingsNode)
      });

      // determine activeTab (either from guiStatus or (initially from model with items defaultVisibleId attribute)
      var xpath = guiStatusTabXPath + "/Active[text() != '']";
      var activeTab = bcdui.wkModels.guiStatus.read(xpath, "");
      if (activeTab == "") {
        var contId = dataProvider.getData().selectSingleNode("/Items/@defaultVisibleId").nodeValue;
        if(contId && contId == "FIRST") {
          contId = dataProvider.getData().selectSingleNode("/Items/Item[1]/@id").nodeValue;
          contId = contId.replace('tab_',''); // thus we have tabId here
        }
        if (contId)
          activeTab = "tab_" + contId;
      }
      // in case we have an active tab, initially show/hide single (not yet initialized) containers and set active Tab in guiStatus
      if (activeTab != "") {
        jQuery.makeArray(dataProvider.queryNodes("/Items/Item/@id")).forEach(function(container) {
          var conId = jQuery("#" + container.nodeValue.replace('tab_', ''));
          if (container.nodeValue != activeTab)
            conId.hide();
          else
            conId.show();
        });
      }

      // create tabs menu renderer
      var _rendererUrl = (args.rendererUrl) ? args.rendererUrl : "/bcdui/js/widget/tab/tab.xslt";
      var _handlerVariableName = (args.handlerJsClassName)?args.handlerJsClassName:"bcdui.widget.tab";
      var renderer = new bcdui.core.Renderer({
          id: ("bcdRenderer_" + args.id)
        , chain: bcdui.util.url.resolveToFullURLPathWithCurrentURL(_rendererUrl)
        , inputModel: dataProvider
        , parameters: { contextPath: bcdui.contextPath, handlerVariableName: _handlerVariableName, settingsNode: settingsNode }
        , targetHtml: args.targetHTMLElementId
      });
      // initially sync
      renderer.onceReady(function(){
        bcdui.core.createElementWithPrototype(bcdui.wkModels.guiStatus.getData(), guiStatusTabXPath + "/Active").text = activeTab;
        bcdui.widget.tab._syncActiveTab(tabId, args.targetHTMLElementId, args.idOrElement, settingsNode);
      });
    },

    /**
     * displays active tab according to guiStatus setting
     * @private
     */
    _syncActiveTab : function(tabId, targetHTMLElementId, defTabId, settingsNode){

      var activeTab = bcdui.wkModels.guiStatus.read("/*/guiStatus:"+settingsNode+"/Selected/Tab[@id = '" + tabId+"']/Active", "");
      // an existing client settings entry does not necessarily mean the object exists already
      if (jQuery("#" + activeTab).length == 0)
        return;

      // set/remove active css class
      var tabs = jQuery("#" + activeTab).closest("ul").find(" > li a");
      tabs.removeClass("bcdActive");
      jQuery("#" + activeTab).addClass("bcdActive");

      tabs.each(function(i,e) {
        var conId = e.id.replace('tab_','');
        if (jQuery(e).hasClass("bcdActive")) {
          jQuery("#" + conId).show();
          jQuery("#" + conId).trigger("bcd:widget.tab.show");
        }
        else {
          jQuery("#" + conId).hide();
          jQuery("#" + conId).trigger("bcd:widget.tab.hide");
        }
      });
    },

    /**
     * A click on a tab happened, remember id in guiStatus
     */
    handleTabAction:function(event, settingsNode) {
      var e = jQuery(event.target);
      var elId = e.attr("id");
      var xpath= "/*/guiStatus:"+settingsNode+"/Selected/Tab[@id='" + e.attr("parentId") + "']/Active";
      if (bcdui.wkModels.guiStatus.read(xpath, elId) == elId)
        return null;// clicked on the same tab
      bcdui.wkModels.guiStatus.write(xpath, elId, true);
    },

    /**
     * Set default parameters
     * @param {HTMLElement} htmlElement The element the tab is based on.
     * @private
     */
    _adjustDefaultParameters: function(HTMLElement) {}
  }
);// end of namespace
<commit_msg>Client/Widget, tab package, better check for existing active tab<commit_after>/*
  Copyright 2010-2017 BusinessCode GmbH, Germany

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
"use strict";
bcdui.core.HTML2XMLDataProvider = bcdui._migPjs._classCreate(bcdui.core.DataProvider,
    /**
     * @lends bcdui.core.HTML2XMLDataProvider.prototype
     */
    {

      /**
       * @constructs
       * @extends bcdui.core.DataProvider
       * @param {Object} args
       * @param {String} args.id
       * @param {String} args.name
       * @param {(String|HTMLElement)} args.idOrElement
       *
       */
      initialize: function(/* object */ args)
      {
          bcdui.log.isTraceEnabled() && bcdui.log.trace("HTML2XMLDataProvider init");
          bcdui.core.DataProvider.call( this, {
            id: args.id,
            name: args.name
          });

          this.waitingForUncomittedChanges = new bcdui.core.status.WaitingForUncomittedChanges();
          this.transformedStatus = new bcdui.core.status.TransformedStatus();

          this.doc = null;
          this.idOrElement = args.idOrElement;
      },

      /**
       * @private
       */
      _createModelDocument:function()
      {
        bcdui.log.isTraceEnabled() && bcdui.log.trace("this.idOrElement:"+this.idOrElement);
        var rElement = bcdui._migPjs._$(this.idOrElement);
        this.doc = bcdui.core.browserCompatibility.newDOMDocument();
        var root = this.doc.createElement("Items");
        var tabId =  "tab_" + (rElement.get(0).id || bcdui.factory.objectRegistry.generateTemporaryIdInScope("tab_"));
        root.setAttribute("id", tabId);
        root.setAttribute("defaultVisibleId", (rElement.attr("defaultVisibleId")==null || rElement.attr("defaultVisibleId") == "")?"FIRST":rElement.attr("defaultVisibleId"));

        this.doc.appendChild(root);

        rElement.children().each(function(i, element) {// all children of idOrElement
          jQuery(element).addClass("bcdTabItem");
          var e = this.doc.documentElement.appendChild(this.doc.createElement("Item"));
          e.setAttribute("id", "tab_"+element.id);
          e.setAttribute("caption", (element.getAttribute("caption")==null)?"":element.getAttribute("caption"));
          e.setAttribute("enabled", (element.getAttribute("enabled")==null)?"":element.getAttribute("enabled"));
          e.setAttribute("toolTip", (element.getAttribute("toolTip")==null)?"":element.getAttribute("toolTip"));
          e.setAttribute("onclick", (element.getAttribute("onclick")==null)?"":element.getAttribute("onclick"));
        }.bind(this));

      },

      /**
       * @private
       */
      _executeImpl: function()
        {
          this._createModelDocument();
          var newStatus = this._uncommitedWrites ? this.waitingForUncomittedChanges : this.getReadyStatus();
          this.setStatus(newStatus);
        },

      getData: function()
        {
          return this.doc;
        },

      /**
       * @return {status}
       */
      getReadyStatus: function()
        {
          return this.transformedStatus;
        }
    }
);

/**
 * XSLT creates ul li li /ul for TABs
 * gets as parameter root html element where are content DIVs/HTML elements defined
 * parsed the HTML element to get count of Tabs, captions, references to content elements, may be some defult settings (width, height, position ...)
 *
 * sample:
 *

 *

 *

 *

 *

 *
 * than after parsing creates such UL
 *

 *

 *

 *

 *

 *
 */
/**
 * A namespace for the BCD-UI tab widget.
 * @namespace bcdui.widget.tab
 * @private
 */
bcdui.util.namespace("bcdui.widget.tab",
/** @lends bcdui.widget.tab */
{
    /**
     * @param {Object} args
     * @param {Object} args.id:                  - tab id
     * @param {Object} args.rendererUrl          - URL to renderer xslt stylesheet
     * @param {Object} args.rendererId           - renderer id
     * @param {Object} args.handlerJsClassName   - Tab menu handler variable name, default bcdui.widget.tab
     * @param {Object} args.targetHTMLElementId  - target where HTML content to paste to
     * @param {Object} args.idOrElement          - id of/or HTML element where tabs are defined
     * @param {Object} args.isPersistent         - use guiStatus:PersistentSettings or guiStatus:ClientSettings
     * @private
     *
     */
    init:function(args)
    {

      var settingsNode = args.isPersistent ? "PersistentSettings" : "ClientSettings";

      var dataProvider = new bcdui.core.HTML2XMLDataProvider( {
        id:          args.id + "_innerModel"
      , name:        args.id + "_innerModel"
      , idOrElement:  bcdui._migPjs._$(args.idOrElement).get(0)
      });
      dataProvider.execute();

      // read settings from GUIstatus doc, if exists XPath - takes it, if no - set default to visible
      var tabId = dataProvider.getData().selectSingleNode("/Items/@id").nodeValue;
      var guiStatusTabXPath = "/*/guiStatus:" + settingsNode + "/Selected/Tab[@id = '" + tabId +"']";

      // register listener which shows/hides the selected tab
      bcdui.wkModels.guiStatus.onChange({
          onlyOnce: false
        , trackingXPath: guiStatusTabXPath
        , callback: bcdui.widget.tab._syncActiveTab.bind(undefined, tabId, args.targetHTMLElementId, args.idOrElement, settingsNode)
      });

      // determine activeTab (either from guiStatus or (initially from model with items defaultVisibleId attribute)
      var xpath = guiStatusTabXPath + "/Active[text() != '']";
      var activeTab = bcdui.wkModels.guiStatus.read(xpath, "");
      if (activeTab == "") {
        var contId = dataProvider.getData().selectSingleNode("/Items/@defaultVisibleId").nodeValue;
        if(contId && contId == "FIRST") {
          contId = dataProvider.getData().selectSingleNode("/Items/Item[1]/@id").nodeValue;
          contId = contId.replace('tab_',''); // thus we have tabId here
        }
        if (contId)
          activeTab = "tab_" + contId;
      }
      // in case we have an active tab, initially show/hide single (not yet initialized) containers and set active Tab in guiStatus
      if (activeTab != "") {
        jQuery.makeArray(dataProvider.queryNodes("/Items/Item/@id")).forEach(function(container) {
          var conId = jQuery("#" + container.nodeValue.replace('tab_', ''));
          if (container.nodeValue != activeTab)
            conId.hide();
          else
            conId.show();
        });
      }

      // create tabs menu renderer
      var _rendererUrl = (args.rendererUrl) ? args.rendererUrl : "/bcdui/js/widget/tab/tab.xslt";
      var _handlerVariableName = (args.handlerJsClassName)?args.handlerJsClassName:"bcdui.widget.tab";
      var renderer = new bcdui.core.Renderer({
          id: ("bcdRenderer_" + args.id)
        , chain: bcdui.util.url.resolveToFullURLPathWithCurrentURL(_rendererUrl)
        , inputModel: dataProvider
        , parameters: { contextPath: bcdui.contextPath, handlerVariableName: _handlerVariableName, settingsNode: settingsNode }
        , targetHtml: args.targetHTMLElementId
      });
      // initially sync
      renderer.onceReady(function(){
        bcdui.core.createElementWithPrototype(bcdui.wkModels.guiStatus.getData(), guiStatusTabXPath + "/Active").text = activeTab;
        bcdui.widget.tab._syncActiveTab(tabId, args.targetHTMLElementId, args.idOrElement, settingsNode);
      });
    },

    /**
     * displays active tab according to guiStatus setting
     * @private
     */
    _syncActiveTab : function(tabId, targetHTMLElementId, defTabId, settingsNode){

      var activeTab = bcdui.wkModels.guiStatus.read("/*/guiStatus:"+settingsNode+"/Selected/Tab[@id = '" + tabId+"']/Active", "");
      // an existing client settings entry does not necessarily mean the object exists already
      if (activeTab == "" || jQuery("#" + activeTab).length == 0)
        return;

      // set/remove active css class
      var tabs = jQuery("#" + activeTab).closest("ul").find(" > li a");
      tabs.removeClass("bcdActive");
      jQuery("#" + activeTab).addClass("bcdActive");

      tabs.each(function(i,e) {
        var conId = e.id.replace('tab_','');
        if (jQuery(e).hasClass("bcdActive")) {
          jQuery("#" + conId).show();
          jQuery("#" + conId).trigger("bcd:widget.tab.show");
        }
        else {
          jQuery("#" + conId).hide();
          jQuery("#" + conId).trigger("bcd:widget.tab.hide");
        }
      });
    },

    /**
     * A click on a tab happened, remember id in guiStatus
     */
    handleTabAction:function(event, settingsNode) {
      var e = jQuery(event.target);
      var elId = e.attr("id");
      var xpath= "/*/guiStatus:"+settingsNode+"/Selected/Tab[@id='" + e.attr("parentId") + "']/Active";
      if (bcdui.wkModels.guiStatus.read(xpath, elId) == elId)
        return null;// clicked on the same tab
      bcdui.wkModels.guiStatus.write(xpath, elId, true);
    },

    /**
     * Set default parameters
     * @param {HTMLElement} htmlElement The element the tab is based on.
     * @private
     */
    _adjustDefaultParameters: function(HTMLElement) {}
  }
);// end of namespace
<|endoftext|>


<commit_before>class Emergency extends pso2tools_module{
    constructor(app){
        super(app);
    }

    static getEmergencyInfo(){
        var sourceURI = "http://pso2.jp/players/boost/";
        var req = new XMLHttpRequest();
        req.open("GET",sourceURI);
        req.addEventListener("readystatechange",function(e){
            if(e.target.readyState === 4){
                if(e.target.status != 200){
                    return;
                }
                var parser = new DOMParser();
                var content = parser.parseFromString(e.target.responseText,"text/html");
                var emerList = [];
                var timeOffset = -((new Date).getTimezoneOffset() + 540);    // + n minutes from Tokyo Time to Local Time
                const weekday = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]
                const day = [
                    "wednesday1",
                    "thursday",
                    "friday",
                    "saturday",
                    "sunday",
                    "monday",
                    "tuesday",
                    "wednesday2"
                ]
                var dayTbl = {}
                var crossMonth = false; // Point the 1st day of the month.
                day.forEach(function(el,i){
                    dayTbl[el] = parseInt(content.querySelector("th.day-"+el).innerText.match(/(\d*)/g)[2]);    // Hope they won't change this LOL
                    if(!crossMonth)
                        crossMonth = (dayTbl[el] < (dayTbl[day[i-1]]|0)?el:false);
                });

                var today = weekday[(new Date).getDay()]

                if(today == "wednesday"){
                    today = today + (((new Date()).getHours()+(timeOffset/60))>16?"2":"1");
                }

                content.querySelectorAll("div.event-emergency").forEach((i)=>{
                    var name = i.querySelector("span").innerText;
                    var eday = i.parentNode.className.split("-")[1];
                    var time = i.parentNode.parentNode.className;
                    time = Number(time.split(/[\D*]/).filter((el)=>el != "").join(""));

                    var datetime = new Date();
                    datetime.setDate(dayTbl[eday]);
                    if(crossMonth && (new Date()).getDate()>15 && (day.indexOf(eday) >= day.indexOf(crossMonth))){
                        datetime.setMonth(datetime.getMonth() + 1);
                    }else{
                        if(crossMonth && (new Date()).getDate() < 15 && (day.indexOf(eday) < day.indexOf(crossMonth))){
                            datetime.setMonth(datetime.getMonth() - 1);
                        }
                    }
                    datetime.setHours(parseInt(time/100));
                    datetime.setMinutes((time % 100) + timeOffset);
                    datetime.setSeconds(0);
                    datetime.setMilliseconds(0);

                    if(datetime < (new Date()).setMinutes((new Date()).getMinutes()-30)){
                        return;
                    }

                    emerList.push({name:name,time:datetime});
                })

                emerList.sort(function(el1, el2){
                    return el1.time - el2.time;
                });

                //Rendering
                var emerElem = []
                emerList.forEach(function(el,i){
                    emerElem.push(
{el.name}	{el.time.toLocaleString()}
);
                })
                ReactDOM.unmountComponentAtNode(document.getElementById("Emergency_TimeTable"));
                ReactDOM.render(

{emerElem}

,document.getElementById("Emergency_TimeTable"));
            }
        });
        req.addEventListener("error",function(){
            alert("Connection to Internet required!");
        })
        req.send();
    }

    renderTab(){
        var content =

<button onClick={Emergency.getEmergencyInfo}>{"Get Emergency Time Table"}</button>

        return {content:content,label:"Emergency"}
    }
}<commit_msg>Added: Arks League is now included in emergency module<commit_after>class Emergency extends pso2tools_module{
    constructor(app){
        super(app);
        var css = `
        tr.event-emergency:hover {
            background: #800;
        }
        tr.event-emergency {
            background: #500;
        }
        tr.event-league:hover {
            background: #c80;
        }
        tr.event-league {
            background: #960;
        }`;
        var style = document.createElement("style")
        style.type = "text/css"
        style.appendChild(document.createTextNode(css));
        document.head.appendChild(style);
    }

    static getEmergencyInfo(){
        var sourceURI = "http://pso2.jp/players/boost/";
        var req = new XMLHttpRequest();
        req.open("GET",sourceURI);
        req.addEventListener("readystatechange",function(e){
            if(e.target.readyState === 4){
                if(e.target.status != 200){
                    return;
                }
                var parser = new DOMParser();
                var content = parser.parseFromString(e.target.responseText,"text/html");
                var emerList = [];
                var timeNow = new Date();
                var timeOffset = -(timeNow.getTimezoneOffset() + 540);    // + n minutes from Tokyo Time to Local Time

                content.querySelectorAll("div.event-emergency, div.event-league").forEach((i)=>{
                    var time, startT, endT, st_Mo, st_D, st_H, st_Mi,en_Mo, en_D, en_H, en_Mi;
                    [time, startT, endT] = i.querySelector("strong.start").parentNode.innerText.match(/(.*)～(.*)/);
                    [st_Mo, st_D, st_H, st_Mi] = startT.match(/(\d{2})/g).map((e)=>{return parseInt(e)});
                    [en_Mo, en_D, en_H, en_Mi] = endT.match(/(\d{2})/g).map((e)=>{return parseInt(e)});

                    var endTime = new Date();
                    if(endTime.getMonth() == 12 && (en_Mo == 1)){
                        endTime.setFullYear(endTime.getFullYear() + 1);
                    }
                    endTime.setMonth(en_Mo-1);
                    endTime.setDate(en_D);
                    endTime.setHours(en_H);
                    endTime.setMinutes(en_Mi + timeOffset);
                    endTime.setSeconds(0);
                    endTime.setMilliseconds(0);

                    if(endTime < timeNow){
                        return;
                    }

                    var startTime = new Date();
                    if(startTime.getMonth() == 12 && (st_Mo == 1)){
                        startTime.setFullYear(startTime.getFullYear() + 1);
                    }
                    startTime.setMonth(st_Mo-1);
                    startTime.setDate(st_D);
                    startTime.setHours(st_H);
                    startTime.setMinutes(st_Mi + timeOffset);
                    startTime.setSeconds(0);
                    startTime.setMilliseconds(0);

                    var eventTypeStr = i.querySelector("dt").innerText;

                    var eventContent = i.querySelectorAll("dd")[1].innerText

                    var newEvent = {start:startTime, end: endTime, class: i.className.match(/event-\w*/)[0], typeStr: eventTypeStr, content:eventContent}

                    if(emerList.find(function(el){return (el.class == newEvent.class) && (el.start.getTime() == newEvent.start.getTime())})==null)
                        emerList.push(newEvent);
                })

                emerList.sort(function(el1, el2){
                    return el1.start - el2.start;
                });

                //Rendering
                var emerElem = []
                emerList.forEach(function(el,i){
                    emerElem.push(
{el.typeStr}	{el.content}	{el.start.toLocaleString()}	{"~"}	{el.end.toLocaleString()}
);
                })
                ReactDOM.unmountComponentAtNode(document.getElementById("Emergency_TimeTable"));
                ReactDOM.render(

{emerElem}

,document.getElementById("Emergency_TimeTable"));
            }
        });
        req.addEventListener("error",function(){
            alert("Connection to Internet required!");
        })
        req.send();
    }

    renderTab(){
        var content =

<button onClick={Emergency.getEmergencyInfo}>{"Get Event Time Table"}</button>

        return {content:content,label:"Event"}
    }
}<|endoftext|>


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

  angular
    .module('dolmen', [
      'ngAnimate',
      'ngCookies',
      'ngTouch',
      'ngSanitize',
      'restangular',
      'ui.router',
      'ui.bootstrap',
      'firebase',
      'xeditable'
      //'dolmen.services',
      //'dolmen.login',
    ]
  );

})();
<commit_msg>defined Firebase url in main module to start refactoring code<commit_after>(function() {
  'use strict';

  angular
    .module('dolmen', [
      'ngAnimate',
      'ngCookies',
      'ngTouch',
      'ngSanitize',
      'restangular',
      'ui.router',
      'ui.bootstrap',
      'firebase',
      'xeditable'
      //'dolmen.services',
      //'dolmen.login',
    ]
  ).constant( 'FIREBASE_APP', 'https://dolmen.firebase.io.com/users' );
})();
<|endoftext|>


<commit_before>/**
 * Copyright 2015-2019 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "/web_modules/lit-element.js";
import UtilsNew from "../../../utilsNew.js";
import "./../../commons/view/detail-tabs.js";
import GridCommons from "../../commons/grid-commons.js";
import VariantInterpreterGridFormatter from "../../variant/interpretation/variant-interpreter-grid-formatter.js";
import VariantGridFormatter from "../../variant/variant-grid-formatter.js";

export default class RgaIndividualFamily extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            individual: {
                type: Object
            },
            active: {
                type: Boolean
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);
        this._config = this.getDefaultConfig();
        this.gridId = this._prefix + "KnockoutIndividualFamGrid";
        this.tableDataMap = {};
        this.individual = null;
        this.wip = false;
    }

    connectedCallback() {
        super.connectedCallback();
        this.gridCommons = new GridCommons(this.gridId, this, this._config);

    }

    async updated(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
        }

        if ((changedProperties.has("individual") || changedProperties.has("active")) && this.active) {
            this.prepareData();
            this.renderTable();
        }

        if (changedProperties.has("config")) {
            this._config = {...this.getDefaultConfig(), ...this.config};
        }
    }

    async prepareData() {
        if (this.individual) {
            try {
                // motherId: "115000155", fatherId: "115000154"
                // motherSampleId:LP3000021-DNA_B04
                // fatherSampleId:LP3000018-DNA_A03

                this.sampleIds = [
                    this.individual.sampleId,
                    this.individual.fatherSampleId2,
                    this.individual.motherSampleId
                ];
                console.error("this.sampleIds", this.sampleIds)

                /**
                 * this.tableDataMap is the full list of unique variants per individual
                 */
                if (UtilsNew.isEmpty(this.tableDataMap)) {
                    for (const gene of this.individual.genes) {
                        for (const transcript of gene.transcripts) {
                            for (const variant of transcript.variants) {
                                this.tableDataMap[variant.id] = {
                                    ...variant,
                                    geneName: gene.name
                                };
                            }
                        }
                    }
                    this.variantIds = Object.keys(this.tableDataMap);
                    this.tableDataLn = this.variantIds.length;
                }

            } catch (e) {

            }
        }

    }

    /**
     * Queries variant WS only for the subset defined by startVariant and endVariant.
     */
    async getVariantInfo(sampleIds, startVariant, endVariant) {
        // formatter: VariantInterpreterGridFormatter.sampleGenotypeFormatter,
        try {
            const slicedVariant = this.variantIds.slice(startVariant, endVariant);
            if (slicedVariant.length && sampleIds.length) {
                const params = {
                    study: this.opencgaSession.study.fqn,
                    id: slicedVariant.join(","),
                    includeSample: sampleIds.join(",")
                };
                return await this.opencgaSession.opencgaClient.variants().query(params);
            } else {
                console.error("params error");
            }

        } catch (e) {
            UtilsNew.notifyError(e);
        }

    }

    /**
     * update tableData with new variant data (it happens on pagination)
     */
    updateTableData(tableDataMap, variantData) {
        const _tableDataMap = tableDataMap;
        variantData.forEach(variant => {
            _tableDataMap[variant.id].variantData = variant;
        });
        return Object.values(_tableDataMap);
    }

    renderTable() {
        this.table = $("#" + this.gridId);
        this.table.bootstrapTable("destroy");
        this.table.bootstrapTable({
            columns: this._initTableColumns(),
            sidePagination: "server",
            uniqueId: "id",
            pagination: true,
            // pageSize: this._config.pageSize,
            // pageList: this._config.pageList,
            paginationVAlign: "both",
            // formatShowingRows: this.gridCommons.formatShowingRows,
            gridContext: this,
            formatLoadingMessage: () => "
<loading-spinner></loading-spinner>
",
            ajax: async params => {
                try {
                    const pageNumber = this.table.bootstrapTable("getOptions").pageNumber || this.table.bootstrapTable("getOptions").pageNumber === 1;
                    const pageSize = this.table.bootstrapTable("getOptions").pageSize;
                    const startVariant = pageNumber * pageSize - pageSize;
                    const endVariant = pageNumber * pageSize;
                    const variantResponse = await this.getVariantInfo(this.sampleIds, startVariant, endVariant);
                    this.tableData = this.updateTableData(this.tableDataMap, variantResponse.getResults());
                    params.success({
                        total: this.tableDataLn,
                        rows: this.tableData.slice(startVariant, endVariant)
                    });
                } catch (e) {
                    console.error(e);
                    params.error(e);
                }
            },
            onClickRow: (row, selectedElement, field) => {
            },
            onLoadSuccess: data => {
                // this is not triggered in case of static data
            },
            onLoadError: (e, restResponse) => this.gridCommons.onLoadError(e, restResponse),
            onPostBody: () => UtilsNew.initTooltip(this),
            onPageChange: (number, size) => {
                console.error("page change", number, size);
            }
        });
    }

    geneFormatter(value, row) {
        return value.length ? (value.length > 20 ? `${value.length} genes` : value.map(gene => gene.name)) : "-";
    }

    _initTableColumns() {
        return [
            [
                {
                    title: "id",
                    field: "id",
                    rowspan: 2,
                    formatter: (value, row, index) => row.chromosome ? VariantGridFormatter.variantFormatter(value, row, index, this.opencgaSession.project.organism.assembly) : value
                },
                {
                    title: "Gene",
                    field: "geneName",
                    rowspan: 2
                    // formatter: this.geneFormatter
                },
                {
                    title: "Knockout Type",
                    field: "knockoutType",
                    rowspan: 2
                    /* formatter: row => {
                        this.table.bootstrapTable("updateRow", {index: 1, row: {id: "123"}});
                    }*/
                },
                {
                    title: "Proband
" + this.sampleIds[0],
                    field: "",
                    colspan: 2
                },
                {
                    title: "Mother
" + this.sampleIds[1],
                    field: "id",
                    colspan: 2
                },
                {
                    title: "Father
" + this.sampleIds[2],
                    field: "",
                    colspan: 2
                }
            ],
            [
                {
                    title: "GT",
                    field: "variantData",
                    formatter: value => this.gtFormatter(value, 0)
                },
                {
                    title: "Filter",
                    field: "filter",
                    formatter: filters => {
                        if (filters) {
                            return filters.split(/[,;]/).map(filter => `<span class="badge">${filter}</span>`).join("");
                        }
                    }
                },
                {
                    title: "GT",
                    field: "variantData",
                    formatter: value => this.gtFormatter(value, 1)
                },
                {
                    title: "Filter",
                    field: "filter",
                    formatter: filters => {
                        if (filters) {
                            return filters.split(/[,;]/).map(filter => `<span class="badge">${filter}</span>`).join("");
                        }
                    }
                },
                {
                    title: "GT",
                    field: "variantData",
                    formatter: value => this.gtFormatter(value, 2)
                },
                {
                    title: "Filter",
                    field: "filter",
                    formatter: filters => {
                        if (filters) {
                            return filters.split(/[,;]/).map(filter => `<span class="badge">${filter}</span>`).join("");
                        }
                    }
                }
            ]
        ];
    }

    gtFormatter(value, sampleIndex) {
        console.error("value?.studies?.[0]", value?.studies?.[0])
        if (value?.studies?.[0]?.sampleDataKeys.length) {
            const gtIndex = value.studies[0].sampleDataKeys.indexOf("GT");
            // console.log("gtIndex", gtIndex)
            if (~gtIndex) {
                // console.log("gtIndex", gtIndex)
                // console.log("sampleGT", value.studies[0].samples[sampleIndex])
                return value.studies[0].samples?.[sampleIndex].data[gtIndex];
            }
        }
    }

    getDefaultConfig() {
        return {
            title: "Individual"

        };
    }

    render() {
        if (this.wip) {
            return html`<div class="alert alert-warning"><i class="fas fa-3x fa-info-circle align-middle"></i> WIP </div>`;
        }
        return html`

        `;
    }

}

customElements.define("rga-individual-family", RgaIndividualFamily);
<commit_msg>rga-individual-family.js: filterFormatter and gtFormatter fixed #118<commit_after>/**
 * Copyright 2015-2019 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "/web_modules/lit-element.js";
import UtilsNew from "../../../utilsNew.js";
import "./../../commons/view/detail-tabs.js";
import GridCommons from "../../commons/grid-commons.js";
import VariantInterpreterGridFormatter from "../../variant/interpretation/variant-interpreter-grid-formatter.js";
import VariantGridFormatter from "../../variant/variant-grid-formatter.js";

export default class RgaIndividualFamily extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            individual: {
                type: Object
            },
            active: {
                type: Boolean
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);
        this._config = this.getDefaultConfig();
        this.gridId = this._prefix + "KnockoutIndividualFamGrid";
        this.tableDataMap = {};
        this.individual = null;
        this.wip = false;
    }

    connectedCallback() {
        super.connectedCallback();
        this.gridCommons = new GridCommons(this.gridId, this, this._config);

    }

    async updated(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
        }

        if ((changedProperties.has("individual") || changedProperties.has("active")) && this.active) {
            this.prepareData();
            this.renderTable();
        }

        if (changedProperties.has("config")) {
            this._config = {...this.getDefaultConfig(), ...this.config};
        }
    }

    async prepareData() {
        if (this.individual) {
            try {
                // motherId: "115000155", fatherId: "115000154"
                // motherSampleId:LP3000021-DNA_B04
                // fatherSampleId:LP3000018-DNA_A03

                this.sampleIds = [
                    this.individual.sampleId,
                    this.individual.fatherSampleId,
                    this.individual.motherSampleId
                ];
                // in case fatherSampleId is missing, the response studies[].samples[] of variants().query() would contains only 2 entries
                this.motherSampleIndx = this.individual.fatherSampleId && this.individual.motherSampleId ? 2 : 1;

                /**
                 * this.tableDataMap is the full list of unique variants per individual
                 */
                if (UtilsNew.isEmpty(this.tableDataMap)) {
                    for (const gene of this.individual.genes) {
                        for (const transcript of gene.transcripts) {
                            for (const variant of transcript.variants) {
                                this.tableDataMap[variant.id] = {
                                    ...variant,
                                    geneName: gene.name
                                };
                            }
                        }
                    }
                    this.variantIds = Object.keys(this.tableDataMap);
                    this.tableDataLn = this.variantIds.length;
                }

            } catch (e) {

            }
        }

    }

    /**
     * Queries variant WS only for the subset defined by startVariant and endVariant.
     */
    async getVariantInfo(sampleIds, startVariant, endVariant) {
        // formatter: VariantInterpreterGridFormatter.sampleGenotypeFormatter,
        try {
            const slicedVariant = this.variantIds.slice(startVariant, endVariant);
            if (slicedVariant.length && sampleIds.length) {
                const params = {
                    study: this.opencgaSession.study.fqn,
                    id: slicedVariant.join(","),
                    includeSample: sampleIds.join(",")
                };
                return await this.opencgaSession.opencgaClient.variants().query(params);
            } else {
                console.error("params error");
            }

        } catch (e) {
            UtilsNew.notifyError(e);
        }

    }

    /**
     * update tableData with new variant data (it happens on pagination)
     */
    updateTableData(tableDataMap, variantData) {
        const _tableDataMap = tableDataMap;
        variantData.forEach(variant => {
            _tableDataMap[variant.id].variantData = variant;
        });
        return Object.values(_tableDataMap);
    }

    renderTable() {
        this.table = $("#" + this.gridId);
        this.table.bootstrapTable("destroy");
        this.table.bootstrapTable({
            columns: this._initTableColumns(),
            sidePagination: "server",
            uniqueId: "id",
            pagination: true,
            // pageSize: this._config.pageSize,
            // pageList: this._config.pageList,
            paginationVAlign: "both",
            // formatShowingRows: this.gridCommons.formatShowingRows,
            gridContext: this,
            formatLoadingMessage: () => "
<loading-spinner></loading-spinner>
",
            ajax: async params => {
                try {
                    const pageNumber = this.table.bootstrapTable("getOptions").pageNumber || this.table.bootstrapTable("getOptions").pageNumber === 1;
                    const pageSize = this.table.bootstrapTable("getOptions").pageSize;
                    const startVariant = pageNumber * pageSize - pageSize;
                    const endVariant = pageNumber * pageSize;
                    const variantResponse = await this.getVariantInfo(this.sampleIds, startVariant, endVariant);
                    this.tableData = this.updateTableData(this.tableDataMap, variantResponse.getResults());
                    params.success({
                        total: this.tableDataLn,
                        rows: this.tableData.slice(startVariant, endVariant)
                    });
                } catch (e) {
                    console.error(e);
                    params.error(e);
                }
            },
            onClickRow: (row, selectedElement, field) => {
            },
            onLoadSuccess: data => {
                // this is not triggered in case of static data
            },
            onLoadError: (e, restResponse) => this.gridCommons.onLoadError(e, restResponse),
            onPostBody: () => UtilsNew.initTooltip(this),
            onPageChange: (number, size) => {
                console.error("page change", number, size);
            }
        });
    }

    geneFormatter(value, row) {
        return value.length ? (value.length > 20 ? `${value.length} genes` : value.map(gene => gene.name)) : "-";
    }

    _initTableColumns() {
        return [
            [
                {
                    title: "id",
                    field: "id",
                    rowspan: 2,
                    formatter: (value, row, index) => row.chromosome ? VariantGridFormatter.variantFormatter(value, row, index, this.opencgaSession.project.organism.assembly) : value
                },
                {
                    title: "Gene",
                    field: "geneName",
                    rowspan: 2
                    // formatter: this.geneFormatter
                },
                {
                    title: "Knockout Type",
                    field: "knockoutType",
                    rowspan: 2
                    /* formatter: row => {
                        this.table.bootstrapTable("updateRow", {index: 1, row: {id: "123"}});
                    }*/
                },
                {
                    title: "Proband
" + this.sampleIds[0],
                    field: "",
                    colspan: 2
                },
                {
                    title: "Father
" + this.sampleIds[1],
                    field: "id",
                    colspan: 2,
                    visible: !!this.sampleIds[1]
                },
                {
                    title: "Mother
" + this.sampleIds[2],
                    field: "",
                    colspan: 2,
                    visible: !!this.sampleIds[2]
                }
            ],
            [
                // proband
                {
                    title: "GT",
                    field: "variantData",
                    formatter: value => this.gtFormatter(value, 0)
                },
                {
                    title: "Filter",
                    field: "variantData",
                    formatter: value => this.filterFormatter(value, 0)
                },
                // father
                {
                    title: "GT",
                    field: "variantData",
                    visible: !!this.sampleIds[1],
                    formatter: value => this.gtFormatter(value, 1)
                },
                {
                    title: "Filter",
                    field: "variantData",
                    visible: !!this.sampleIds[1],
                    formatter: value => this.filterFormatter(value, 1)

                },
                // mother
                {
                    title: "GT",
                    field: "variantData",
                    visible: !!this.sampleIds[2],
                    formatter: value => this.gtFormatter(value, this.motherSampleIndx)
                },
                {
                    title: "Filter",
                    field: "variantData",
                    visible: !!this.sampleIds[2],
                    formatter: value => this.filterFormatter(value, this.motherSampleIndx)

                }
            ]
        ];
    }

    filterFormatter(value, sampleIndex) {
        const fileIndex = value?.studies?.[0]?.samples?.[sampleIndex]?.fileIndex;
        if (fileIndex !== undefined) {
            return `<span class="badge">${value?.studies?.[0]?.files[fileIndex].data.FILTER}</span>`;
        }
    }

    gtFormatter(value, sampleIndex) {
        if (value?.studies?.[0]?.sampleDataKeys.length) {
            const gtIndex = value.studies[0].sampleDataKeys.indexOf("GT");
            if (~gtIndex) {
                return value.studies[0].samples?.[sampleIndex]?.data?.[gtIndex];
            }
        }
    }

    getDefaultConfig() {
        return {
            title: "Individual"
        };
    }

    render() {
        if (this.wip) {
            return html`<div class="alert alert-warning"><i class="fas fa-3x fa-info-circle align-middle"></i> WIP </div>`;
        }
        return html`

        `;
    }

}

customElements.define("rga-individual-family", RgaIndividualFamily);
<|endoftext|>


<commit_before>/* @flow weak */
export default function assignStyles(base, ...extendingStyles) {
  for (let i = 0, len = extendingStyles.length; i < len; ++i) {
    const style = extendingStyles[i]

    for (const property in style) {
      const value = style[property]
      const baseValue = base[property]

      if (baseValue instanceof Object) {
        if (Array.isArray(baseValue)) {
          const normalizedValue = [].concat(value)
          base[property] = [...baseValue, ...value]
          continue
        }

        if (value instanceof Object && !Array.isArray(value)) {
          base[property] = assignStyles({}, baseValue, value)
          continue
        }
      }

      base[property] = value
    }
  }

  return base
}
<commit_msg>fixed assign style<commit_after>/* @flow weak */
export default function assignStyles(base, ...extendingStyles) {
  for (let i = 0, len = extendingStyles.length; i < len; ++i) {
    const style = extendingStyles[i]

    for (const property in style) {
      const value = style[property]
      const baseValue = base[property]

      if (baseValue instanceof Object) {
        if (Array.isArray(baseValue)) {
          if (Array.isArray(value)) {
            base[property] = [...baseValue, ...value]
          } else {
            base[property] = [...baseValue, value]
          }
          continue
        }

        if (value instanceof Object && !Array.isArray(value)) {
          base[property] = assignStyles({}, baseValue, value)
          continue
        }
      }

      base[property] = value
    }
  }

  return base
}
<|endoftext|>


<commit_before>export default {
  lang: 'vi',
  label: {
    clear: 'Xóa hết',
    ok: 'OK',
    cancel: 'Hủy',
    close: 'Đóng',
    set: 'Thiết đặt',
    select: 'Chọn',
    reset: 'Đặt lại',
    remove: 'Gỡ bỏ',
    update: 'Cập nhật',
    create: 'Tạo',
    search: 'Tìm kiếm',
    filter: 'Bộ lọc',
    refresh: 'Làm mới'
  },
  date: {
    days: 'Chủ Nhật_Thứ Hai_Thứ Ba_Thứ Tư_Thứ Năm_Thứ Sáu_Thứ Bảy'.split('_'),
    daysShort: 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
    months: 'Tháng Một_Tháng Hai_Tháng Ba_Tháng Tư_Tháng Năm_Tháng Sáu_Tháng Bảy_Tháng Tám_Tháng Chín_Tháng Mười_Tháng Mười Một_Tháng Mười Hai'.split('_'),
    monthsShort: 'Th1_Th2_Th3_Th4_Th5_Th6_Th7_Th8_Th9_Th10_Th11_Th12'.split('_'),
    firstDayOfWeek: 0, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: false
  },
  pullToRefresh: {
    pull: 'Kéo xuống để làm mới',
    release: 'Thả ra để làm mới',
    refresh: 'Đang làm mới'
  },
  table: {
    noData: 'Không có dữ liệu',
    noResults: 'Không tìm thấy kết quả',
    loading: 'Đang tải',
    selectedRows: function (rows) {
      return rows === 1
        ? '1 hàng đã chọn.'
        : (rows === 0 ? 'Không có hàng nào' : rows) + ' hàng đã chọn.'
    },
    rowsPerPage: 'Hàng trên mỗi trang:',
    allRows: 'Tất cả',
    pagination: function (start, end, total) {
      return start + '-' + end + ' của ' + total
    },
    columns: 'Cột'
  },
  editor: {
    url: 'URL',
    bold: 'Đậm',
    italic: 'Nghiêng',
    strikethrough: 'Gạch giữa',
    underline: 'Gạch dưới',
    unorderedList: 'Danh sách không theo thứ tự',
    orderedList: 'Danh sách theo thứ tự',
    subscript: 'Chỉ số dưới',
    superscript: 'Chỉ số trên',
    hyperlink: 'Liên kết',
    toggleFullscreen: 'Điều chỉnh chế độ toàn màn hình',
    quote: 'Trích dẫn',
    left: 'Căn trái',,
    center: 'Căn giữa',
    right: 'Căn phải',
    justify: 'Căn đều 2 bên',
    print: 'In',
    outdent: 'Giảm lề',
    indent: 'Tăng lề',
    removeFormat: 'Xóa định dạng',
    formatting: 'Định dạng',
    fontSize: 'Kích cỡ phông',
    align: 'Căn chỉnh',
    hr: 'Chèn Quy Tắc Ngang',
    undo: 'Hoàn tác',
    redo: 'Làm lại',
    header1: 'Tiêu đề 1',
    header2: 'Tiêu đề 2',
    header3: 'Tiêu đề 3',
    header4: 'Tiêu đề 4',
    header5: 'Tiêu đề 5',
    header6: 'Tiêu đề 6',
    paragraph: 'Đoạn',
    code: 'Mã',
    size1: 'Rất nhỏ',
    size2: 'Nhỏ vừa',
    size3: 'Thường',
    size4: 'To vừa',
    size5: 'To',
    size6: 'Rất To',
    size7: 'Tối đa',
    defaultFont: 'Phông mặc định'
  },
  tree: {
    noNodes: 'Không có nốt nào có sẵn',
    noResults: 'Không tìm thấy các nốt'
  }
}
<commit_msg>fix: Vietnamese i18n file<commit_after>export default {
  lang: 'vi',
  label: {
    clear: 'Xóa hết',
    ok: 'OK',
    cancel: 'Hủy',
    close: 'Đóng',
    set: 'Thiết đặt',
    select: 'Chọn',
    reset: 'Đặt lại',
    remove: 'Gỡ bỏ',
    update: 'Cập nhật',
    create: 'Tạo',
    search: 'Tìm kiếm',
    filter: 'Bộ lọc',
    refresh: 'Làm mới'
  },
  date: {
    days: 'Chủ Nhật_Thứ Hai_Thứ Ba_Thứ Tư_Thứ Năm_Thứ Sáu_Thứ Bảy'.split('_'),
    daysShort: 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
    months: 'Tháng Một_Tháng Hai_Tháng Ba_Tháng Tư_Tháng Năm_Tháng Sáu_Tháng Bảy_Tháng Tám_Tháng Chín_Tháng Mười_Tháng Mười Một_Tháng Mười Hai'.split('_'),
    monthsShort: 'Th1_Th2_Th3_Th4_Th5_Th6_Th7_Th8_Th9_Th10_Th11_Th12'.split('_'),
    firstDayOfWeek: 0, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: false
  },
  pullToRefresh: {
    pull: 'Kéo xuống để làm mới',
    release: 'Thả ra để làm mới',
    refresh: 'Đang làm mới'
  },
  table: {
    noData: 'Không có dữ liệu',
    noResults: 'Không tìm thấy kết quả',
    loading: 'Đang tải',
    selectedRows: function (rows) {
      return rows === 1
        ? '1 hàng đã chọn.'
        : (rows === 0 ? 'Không có hàng nào' : rows) + ' hàng đã chọn.'
    },
    rowsPerPage: 'Hàng trên mỗi trang:',
    allRows: 'Tất cả',
    pagination: function (start, end, total) {
      return start + '-' + end + ' của ' + total
    },
    columns: 'Cột'
  },
  editor: {
    url: 'URL',
    bold: 'Đậm',
    italic: 'Nghiêng',
    strikethrough: 'Gạch giữa',
    underline: 'Gạch dưới',
    unorderedList: 'Danh sách không theo thứ tự',
    orderedList: 'Danh sách theo thứ tự',
    subscript: 'Chỉ số dưới',
    superscript: 'Chỉ số trên',
    hyperlink: 'Liên kết',
    toggleFullscreen: 'Điều chỉnh chế độ toàn màn hình',
    quote: 'Trích dẫn',
    left: 'Căn trái',
    center: 'Căn giữa',
    right: 'Căn phải',
    justify: 'Căn đều 2 bên',
    print: 'In',
    outdent: 'Giảm lề',
    indent: 'Tăng lề',
    removeFormat: 'Xóa định dạng',
    formatting: 'Định dạng',
    fontSize: 'Kích cỡ phông',
    align: 'Căn chỉnh',
    hr: 'Chèn Quy Tắc Ngang',
    undo: 'Hoàn tác',
    redo: 'Làm lại',
    header1: 'Tiêu đề 1',
    header2: 'Tiêu đề 2',
    header3: 'Tiêu đề 3',
    header4: 'Tiêu đề 4',
    header5: 'Tiêu đề 5',
    header6: 'Tiêu đề 6',
    paragraph: 'Đoạn',
    code: 'Mã',
    size1: 'Rất nhỏ',
    size2: 'Nhỏ vừa',
    size3: 'Thường',
    size4: 'To vừa',
    size5: 'To',
    size6: 'Rất To',
    size7: 'Tối đa',
    defaultFont: 'Phông mặc định'
  },
  tree: {
    noNodes: 'Không có nốt nào có sẵn',
    noResults: 'Không tìm thấy các nốt'
  }
}
<|endoftext|>