<commit_before>module.exports = function(grunt) {
    'use strict';

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

        less: {
            development: {
                files: {
                    'dist/css/main.css': 'less/*.less'
                },
                plugins: [
                    new (require('less-plugin-autoprefix'))({browsers: ['last 2 versions']}),
                    new (require('less-plugin-clean-css'))()
                ]
            }
        },

        copy: {
            lib: {
                files: [
                    {expand: true, cwd: 'public/', src: ['**'], dest: 'dist/'}
                ]
            },
            main: {
                src: 'src/main.html',
                dest: 'dist/index.html'
            }
        },

        webpack: {
            myConfig: {
                entry: './src/main.jsx',
                output: {
                    path: './dist/js/',
                    filename: 'main.js'
                },
                stats: {
                    colors: true
                },
                module: {
                    loaders: [
                        {
                            test: /\.jsx?$/,
                            exclude: /(node_modules)/,
                            loaders: ['babel']
                        }
                    ]
                }
            }
        },

        uglify: {
            build: {
                src: 'dist/js/main.js',
                dest: 'dist/js/main.min.js'
            }
        },

        cssmin: {
            build: {
                files: {
                    'dist/css/main.min.css': ['dist/css/main.css']
                }
            }
        },

        flow: {
            options: {
                style: 'color'
            },
            files: {}
        },

        watch: {
            less: {
                files: ['less/**'],
                tasks: ['less']
            },
            js: {
                files: ['src/**.jsx', 'src/**.js'],
                tasks: ['flow', 'webpack']
            },
            html: {
                files: ['src/*.html', 'public/**'],
                tasks: ['copy']
            }
        }

    });

// 3. Where we tell Grunt we plan to use this plug-in.

    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-webpack');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-flow');

// 4. Where we tell Grunt what to do when we type 'grunt' into the terminal.

    grunt.registerTask('default', ['less', 'webpack', 'copy']);

    grunt.registerTask('build', ['less', 'webpack', 'copy']);

    grunt.registerTask('build-production', ['empty-build-directory', 'less', 'cssmin', 'webpack', 'uglify', 'copy', 'use-minified']);

// 5. Custom Tasks

    grunt.registerTask('empty-build-directory', 'Empties the build directory', function() {

        var fs = require('fs-extra');

        var buildFolderPath = 'dist';

        try {
            fs.emptyDirSync(buildFolderPath);
        } catch(e) {
            grunt.log.error(e.message);
            return false;
        }

    });

    grunt.registerTask('use-minified', 'Update index.html to use minified files.', function() {

        var path = require('path'),
            fs = require('fs');

        var indexPath = path.join('dist', 'index.html');

        var indexHTML = '';

        // Read dist/index.html as text

        try {
            indexHTML = fs.readFileSync(indexPath, 'utf8');
        } catch(e) {
            grunt.log.error(e.message);
            return false;
        }

        // Find script tag for main.js

        var mainJSPatt = /(<script[^>]+src=[^>]+)(?:main\.js)([^<>]+>)/;

        if(!mainJSPatt.test(indexHTML)) {
            grunt.log.error('Unable to find script tag for main.js in dist/index.html');
            return false;
        }

        // Replace main.js with main.min.js

        indexHTML = indexHTML.replace(mainJSPatt, '$1main.min.js$2');

        // Find link tag for main.css

        var mainCSSPatt = /(<link[^>]+href=[^>]+)(?:main\.css)([^<>]+>)/;

        if(!mainCSSPatt.test(indexHTML)) {
            grunt.log.error('Unable to find link tag for main.css in dist/index.html');
            return false;
        }

        // Replace main.css with main.min.css

        indexHTML = indexHTML.replace(mainCSSPatt, '$1main.min.css$2');

        // Write the new index.html file

        try {
            fs.writeFileSync(indexPath, indexHTML, {encoding: 'utf8'});
        } catch(e) {
            grunt.log.error(e.message);
            return false;
        }

    });

};
<commit_msg>Updated gruntfile<commit_after>module.exports = function(grunt) {
    'use strict';

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

        less: {
            development: {
                files: {
                    'dist/css/main.css': 'less/*.less'
                },
                plugins: [
                    new (require('less-plugin-autoprefix'))({browsers: ['last 2 versions']}),
                    new (require('less-plugin-clean-css'))()
                ]
            }
        },

        copy: {
            lib: {
                files: [
                    {expand: true, cwd: 'public/', src: ['**'], dest: 'dist/'}
                ]
            },
            main: {
                src: 'src/main.html',
                dest: 'dist/index.html'
            }
        },

        webpack: {
            myConfig: {
                entry: './src/main.jsx',
                output: {
                    path: './dist/js/',
                    filename: 'main.js'
                },
                stats: {
                    colors: true
                },
                module: {
                    loaders: [
                        {
                            test: /\.jsx?$/,
                            exclude: /(node_modules)/,
                            loaders: ['babel']
                        }
                    ]
                }
            }
        },

        uglify: {
            build: {
                src: 'dist/js/main.js',
                dest: 'dist/js/main.min.js'
            }
        },

        cssmin: {
            build: {
                files: {
                    'dist/css/main.min.css': ['dist/css/main.css']
                }
            }
        },

        flow: {
            options: {
                style: 'color'
            },
            files: {}
        },

        watch: {
            less: {
                files: ['less/**'],
                tasks: ['less']
            },
            js: {
                files: ['src/**.js'],
                tasks: ['webpack']
            },
            html: {
                files: ['src/main.html', 'public/**'],
                tasks: ['copy']
            }
        }

    });

// 3. Where we tell Grunt we plan to use this plug-in.

    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-webpack');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-flow');

// 4. Where we tell Grunt what to do when we type 'grunt' into the terminal.

    grunt.registerTask('default', ['less', 'webpack', 'copy']);

    grunt.registerTask('build', ['less', 'webpack', 'copy']);

    grunt.registerTask('build-production', ['empty-build-directory', 'less', 'cssmin', 'webpack', 'uglify', 'copy', 'use-minified']);

// 5. Custom Tasks

    grunt.registerTask('empty-build-directory', 'Empties the build directory', function() {

        var fs = require('fs-extra');

        var buildFolderPath = 'dist';

        try {
            fs.emptyDirSync(buildFolderPath);
        } catch(e) {
            grunt.log.error(e.message);
            return false;
        }

    });

    grunt.registerTask('use-minified', 'Update index.html to use minified files.', function() {

        var path = require('path'),
            fs = require('fs');

        var indexPath = path.join('dist', 'index.html');

        var indexHTML = '';

        // Read dist/index.html as text

        try {
            indexHTML = fs.readFileSync(indexPath, 'utf8');
        } catch(e) {
            grunt.log.error(e.message);
            return false;
        }

        // Find script tag for main.js

        var mainJSPatt = /(<script[^>]+src=[^>]+)(?:main\.js)([^<>]+>)/;

        if(!mainJSPatt.test(indexHTML)) {
            grunt.log.error('Unable to find script tag for main.js in dist/index.html');
            return false;
        }

        // Replace main.js with main.min.js

        indexHTML = indexHTML.replace(mainJSPatt, '$1main.min.js$2');

        // Find link tag for main.css

        var mainCSSPatt = /(<link[^>]+href=[^>]+)(?:main\.css)([^<>]+>)/;

        if(!mainCSSPatt.test(indexHTML)) {
            grunt.log.error('Unable to find link tag for main.css in dist/index.html');
            return false;
        }

        // Replace main.css with main.min.css

        indexHTML = indexHTML.replace(mainCSSPatt, '$1main.min.css$2');

        // Write the new index.html file

        try {
            fs.writeFileSync(indexPath, indexHTML, {encoding: 'utf8'});
        } catch(e) {
            grunt.log.error(e.message);
            return false;
        }

    });

};
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

    var srcDir = __dirname + '/';
    var pkg = grunt.file.readJSON('package.json');

    // check arguments
    // Project configuration.
    grunt.initConfig({
        pkg: pkg,
        copy: {
            build: {
                files: [
                    // copy files to build directory
                    //{ expand: true, src: ['*.png', 'io-package.json', 'package.json', 'lib/**', 'admin/**', '!**/*.ts', 'README.md'], dest: 'build/' }
                ]
            },
            deployTestInstance: {
                files: [
                    // copy files to build directory
                    { expand: true, cwd: '', src: ['**', '!src/**', '!node_modules/**'], dest: '../ioBroker/node_modules/iobroker.yahka/' }
                ]

            }
        },

        clean: {
             build: [], //['build/**/*.*'],
             ts_nodeModules: []//['build/node_modules']
        },

        ts: {
            build: {
                tsconfig: true
            }
        },

        exec: {
            refreshIOBroker: {
                cwd: '../iobroker/',
                command: 'iobroker.bat upload yahka'
            },
            NPMPublish: {
                cwd: 'build',
                command: 'npm publish'
            },
            NPMBeta: {
                cwd: 'build',
                command: 'npm publish --tag beta'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-ts');
    grunt.loadNpmTasks('grunt-exec');

    grunt.registerTask('buildOnly', [
        'clean:build',
        'ts:build',
        'clean:ts_nodeModules',
        'replace',
        'copy:build'
    ]);
    grunt.registerTask('replace', function () {
        var file = require('fs').readFileSync('./admin/yahka.admin.js');
        file = file.toString().replace('Object.defineProperty(exports, "__esModule", { value: true });', '').replace('var $ = require("jquery");', '');
        require('fs').writeFileSync('./admin/yahka.admin.js', file);
    });

    grunt.registerTask('DeployToTest', [
        'copy:deployTestInstance',
        'exec:refreshIOBroker'
    ]);

    grunt.registerTask('BuildAndDeployToTest', [
        'clean:build',
        'ts:build',
        'clean:ts_nodeModules',
        'replace',
        'copy:build',
        'copy:deployTestInstance',
        'exec:refreshIOBroker'
    ]);

    grunt.registerTask('NPMPublish', [
        'clean:build',
        'ts:build',
        'clean:ts_nodeModules',
        'replace',
        'copy:build',
        'exec:NPMPublish'
    ])

    grunt.registerTask('NPMBeta', [
        'clean:build',
        'ts:build',
        'clean:ts_nodeModules',
        'replace',
        'copy:build',
        'exec:NPMBeta'
    ])
};<commit_msg>Improved Gruntfile<commit_after>'use strict';

module.exports = function(grunt) {

    var srcDir = __dirname + '/';
    var pkg = grunt.file.readJSON('package.json');

    // check arguments
    // Project configuration.
    grunt.initConfig({
        pkg: pkg,
        copy: {
            build: {
                files: [
                ]
            },
            deployTestInstance: {
                files: [
                    // copy files to build directory
                    { expand: true, cwd: '', src: ['**', '!src/**', '!node_modules/**'], dest: '../ioBroker/node_modules/iobroker.yahka/' }
                ]

            }
        },

        clean: {
                build: ['yahka.*.js', 'main.js', 'admin/yahka.*.js']
        },

        ts: {
            build: {
                tsconfig: true
            }
        },

        exec: {
            refreshIOBroker: {
                cwd: '../iobroker/',
                command: 'iobroker.bat upload yahka'
            },
            NPMPublish: {
                cwd: 'build',
                command: 'npm publish'
            },
            NPMBeta: {
                cwd: 'build',
                command: 'npm publish --tag beta'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-ts');
    grunt.loadNpmTasks('grunt-exec');

    grunt.registerTask('buildOnly', [
        'clean:build',
        'ts:build',
        'replace',
        'copy:build'
    ]);
    grunt.registerTask('replace', function () {
        var file = require('fs').readFileSync('./admin/yahka.admin.js');
        file = file.toString().replace('Object.defineProperty(exports, "__esModule", { value: true });', '').replace('var $ = require("jquery");', '');
        require('fs').writeFileSync('./admin/yahka.admin.js', file);
    });

    grunt.registerTask('DeployToTest', [
        'copy:deployTestInstance',
        'exec:refreshIOBroker'
    ]);

    grunt.registerTask('BuildAndDeployToTest', [
        'clean:build',
        'ts:build',
        'replace',
        'copy:build',
        'copy:deployTestInstance',
        'exec:refreshIOBroker'
    ]);

    grunt.registerTask('NPMPublish', [
        'clean:build',
        'ts:build',
        'replace',
        'copy:build',
        'exec:NPMPublish'
    ])

    grunt.registerTask('NPMBeta', [
        'clean:build',
        'ts:build',
        'replace',
        'copy:build',
        'exec:NPMBeta'
    ])
};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */
module.exports = function(grunt) {
  var readManifest = require('../tools/loader/readManifest.js');
  var Polymer = readManifest('build.json');

  grunt.initConfig({
    'wct-test': {
      local: {
        options: {remote: false},
      },
      remote: {
        options: {remote: true},
      },
    },
    'wct-sauce-tunnel': {
      default: {},
    },
    copy: {
      Polymer: {
        src: 'layout.html',
        dest: 'dist/layout.html'
      }
    },
    concat: {
      Polymer: {
        options: {
          nonull: true
        },
        files: {
          'dist/polymer.js': readManifest('build.json')
        }
      }
    },
    uglify: {
      options: {
        nonull: true
      },
      Polymer: {
        options: {
          beautify: {
            ascii_only: true,
          },
          banner: grunt.file.read('banner.txt') + '// @version: <%= buildversion %>'
        },
        files: {
          'dist/polymer.min.js': 'dist/polymer.js'
        }
      }
    },
    audit: {
      polymer: {
        options: {
          repos: [
            '../polymer-expressions',
            '../polymer-gestures',
            '../polymer'
          ]
        },
        files: {
          'dist/build.log': ['dist/polymer.js', 'dist/polymer.min.js', 'dist/layout.html']
        }
      }
    },
    'string-replace': {
      polymer: {
        files: {
          'dist/polymer-versioned.js': 'src/polymer.js'
        },
        options: {
          replacements: [
            {
              pattern: 'master',
              replacement: '<%= buildversion %>'
            }
          ]
        }
      }
    },
    pkg: grunt.file.readJSON('package.json')
  });

  grunt.loadTasks('../tools/tasks');
  // plugins
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-audit');
  grunt.loadNpmTasks('grunt-string-replace');
  grunt.loadNpmTasks('web-component-tester');

  grunt.registerTask('default', ['minify']);
  grunt.registerTask('minify', ['version', 'string-replace', 'concat', 'uglify', 'copy', 'audit']);
  grunt.registerTask('test', ['wct-test:local']);
  grunt.registerTask('test-remote', ['wct-test:remote']);
  grunt.registerTask('test-buildbot', ['test']);
  grunt.registerTask('release', function() {
    grunt.option('release', true);
    grunt.task.run('minify');
    grunt.task.run('audit');
  });
};
<commit_msg>copy bower.json, not package.json<commit_after>/*
 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */
module.exports = function(grunt) {
  var readManifest = require('../tools/loader/readManifest.js');
  var Polymer = readManifest('build.json');

  grunt.initConfig({
    'wct-test': {
      local: {
        options: {remote: false},
      },
      remote: {
        options: {remote: true},
      },
    },
    'wct-sauce-tunnel': {
      default: {},
    },
    copy: {
      Polymer: {
        src: ['layout.html', 'bower.json'],
        dest: 'dist/'
      }
    },
    concat: {
      Polymer: {
        options: {
          nonull: true
        },
        files: {
          'dist/polymer.js': readManifest('build.json')
        }
      }
    },
    uglify: {
      options: {
        nonull: true
      },
      Polymer: {
        options: {
          beautify: {
            ascii_only: true,
          },
          banner: grunt.file.read('banner.txt') + '// @version: <%= buildversion %>'
        },
        files: {
          'dist/polymer.min.js': 'dist/polymer.js'
        }
      }
    },
    audit: {
      polymer: {
        options: {
          repos: [
            '../polymer-expressions',
            '../polymer-gestures',
            '../polymer'
          ]
        },
        files: {
          'dist/build.log': ['dist/polymer.js', 'dist/polymer.min.js', 'dist/layout.html']
        }
      }
    },
    'string-replace': {
      polymer: {
        files: {
          'dist/polymer-versioned.js': 'src/polymer.js'
        },
        options: {
          replacements: [
            {
              pattern: 'master',
              replacement: '<%= buildversion %>'
            }
          ]
        }
      }
    },
    pkg: grunt.file.readJSON('package.json')
  });

  grunt.loadTasks('../tools/tasks');
  // plugins
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-audit');
  grunt.loadNpmTasks('grunt-string-replace');
  grunt.loadNpmTasks('web-component-tester');

  grunt.registerTask('default', ['minify']);
  grunt.registerTask('minify', ['version', 'string-replace', 'concat', 'uglify', 'copy', 'audit']);
  grunt.registerTask('test', ['wct-test:local']);
  grunt.registerTask('test-remote', ['wct-test:remote']);
  grunt.registerTask('test-buildbot', ['test']);
  grunt.registerTask('release', function() {
    grunt.option('release', true);
    grunt.task.run('minify');
    grunt.task.run('audit');
  });
};
<|endoftext|>


<commit_before>// Gruntfile.js
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
      sass: {
        files: 'scss/**/*.scss',
        tasks: ['build']
      },
      eslint: {
        files: 'js/**/*.js',
        tasks: ['eslint']
      },
      jekyll: {
        files: ['docs/**/*.*', 'scss/**/**/*.scss'],
        tasks: ['docs-build']
      }
    },
    clean: {
      grunticon: ['dist/assets/icons/ui', 'dist/assets/icons/thematic'],
      svg: ['icons/ui/dist']
    },
    pure_grids: {
      responsive: {
        dest: 'scss/modules/_grid-units.scss',
        options: {
          units: [5,12,24],
          includeOldIEWidths: false,
          mediaQueries: {
            sm: 'screen and (min-width: 36.5em)', //584px
            md: 'screen and (min-width: 48em)', //768px
            lg: 'screen and (min-width: 64em)', //1024px
            xl: 'screen and (min-width: 75em)'  //1200px
          },
          selectorPrefix: '.unit-'
        }
      }
    },
    sass: {
      options: {
        outputStyle: 'expanded',
        sourceMap: true,
        indentedSyntax: true,
        sassDir: 'scss',
        cssDir: 'dist/css'
      },
      dev: {
        files: [{
          expand: true,
          cwd: 'scss/',
          src: ['*.scss'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      },
      dist: {
        options: {
          sourceMap: false
        },
        files: [{
          expand: true,
          cwd: 'scss/',
          src: ['*.scss'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      },
      docs: {
        files: {
          'docs/css/main.css': 'docs/_sass/main.scss'
        }
      },
      docsDist: {
        options: {
          sourceMap: false
        },
        files: {
          'docs/css/main.css': 'docs/_sass/main.scss'
        }
      }
    },
    postcss: {
      options: {
        processors: [
          require('autoprefixer')({ browsers: ['last 2 version'] })
        ],
        map: {
          inline: false,
        }
      },
      dist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'dist/css/*.css'
      },
      dev: {
        src: 'dist/css/*.css'
      },
      docs: {
        src: 'docs/css/*.css'
      },
      docsDist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'docs/css/*.css'
      }
    },
    grunticon: {
      ui: {
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: ['*.svg'],
          dest: 'dist/assets/icons/ui'
        }],
        options: {
          dynamicColorOnly: true,
          colors: {
            light: '#ffffff',
            dark: '#000000'
          },
          datasvgcss: 'ui-icons.svg.css',
          datapngcss: 'ui-icons.png.css',
          urlpngcss: 'ui-icons.fallback.css'
        }
      },
      thematic: {
        files: [{
          expand: true,
          cwd: 'icons/thematic',
          src: ['*.svg'],
          dest: 'dist/assets/icons/thematic'
        }],
        options: {
          datasvgcss: 'thematic-icons.svg.css',
          datapngcss: 'thematic-icons.png.css',
          urlpngcss: 'thematic-icons.fallback.css',
          cssprefix: '.thematic-'
        }
      }
    },
    svgtoolkit: {
      light: {
        options: {
          generatePNGs: false,
          colorize: '#ffffff'
        },
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: '*.svg',
          dest: 'icons/ui/dist/light'
        }]
      },
      dark: {
        options: {
          generatePNGs: false,
          colorize: '#232323'
        },
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: '*.svg',
          dest: 'icons/ui/dist/dark'
        }]
      },
      primary: {
        options: {
          generatePNGs: false,
          colorize: '#2A93FC'
        },
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: '*.svg',
          dest: 'icons/ui/dist/primary'
        }]
      }
    },
    datauri: {
      light: {
        options: {
          classPrefix: 'icon-light-',
          usePlaceholder: true
        },
        files: [{
          src: 'icons/ui/dist/light/**/*.svg',
          dest: 'scss/modules/icons/_icons-light.scss'
        }]
      },
      dark: {
        options: {
          classPrefix: 'icon-dark-',
          usePlaceholder: true
        },
        files: [{
          src: 'icons/ui/dist/dark/**/*.svg',
          dest: 'scss/modules/icons/_icons-dark.scss'
        }]
      },
      primary: {
        options: {
          classPrefix: 'icon-primary-',
          usePlaceholder: true
        },
        files: [{
          src: 'icons/ui/dist/primary/**/*.svg',
          dest: 'scss/modules/icons/_icons-primary.scss'
        }]
      }
    },
    jekyll: {
      dev: {
        options: {
          src: './docs',
          config: './docs/_config-dev.yml',
          dest: './dist/docs'
        }
      },
      dist: {
        options: {
          src: './docs',
          config: './docs/_config.yml',
          dest: './dist/docs'
        }
      }
    },
    eslint: {
      options: {
        config: '.eslintrc.json',
        force: true
      },
      all: ['js/**/*.js']
    },
    sasslint: {
      options: {
        config: '.sass-lint.yml',
      },
      target: ['scss/**/*.scss']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-grunticon');
  grunt.loadNpmTasks('grunt-datauri');
  grunt.loadNpmTasks('grunt-jekyll');
  grunt.loadNpmTasks('grunt-postcss');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-sass-lint');
  grunt.loadNpmTasks('grunt-svg-toolkit');
  grunt.loadNpmTasks('grunt-pure-grids');
  grunt.loadNpmTasks('eslint-grunt');

  // Build SVGs and SCSS
  grunt.registerTask('gen-svg', ['clean:svg', 'svgtoolkit', 'datauri', 'clean:svg']);
  // Build Grunticon Icons
  grunt.registerTask('gen-icons', ['clean:grunticon', 'grunticon']);
  // Build WFP UI Docs
  grunt.registerTask('docs-build', ['sasslint', 'sass:docs', 'postcss:docs', 'gen-icons', 'jekyll:dev']);
  // Build dist-ready WFP UI Docs
  grunt.registerTask('docs-dist', ['sasslint', 'sass:docsDist', 'postcss:docsDist', 'gen-icons', 'jekyll:dist']);
  // Build WFP UI
  grunt.registerTask('build', ['eslint', 'gen-svg', 'sasslint', 'sass:dev', 'postcss:dev']);
  // Build a dist-ready WFP UI
  grunt.registerTask('dist', ['gen-svg', 'gen-icons', 'sass:dist', 'postcss:dist']);
  // Set default grunt task to `dist`
  grunt.registerTask('default', ['dist']);
};
<commit_msg>Update local Grunt task for building `docs`<commit_after>// Gruntfile.js
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
      sass: {
        files: 'scss/**/*.scss',
        tasks: ['build']
      },
      eslint: {
        files: 'js/**/*.js',
        tasks: ['eslint']
      },
      docs: {
        files: ['docs/**/*.*', 'scss/**/**/*.scss'],
        tasks: ['docs']
      }
    },
    clean: {
      grunticon: ['dist/assets/icons/ui', 'dist/assets/icons/thematic'],
      svg: ['icons/ui/dist']
    },
    pure_grids: {
      responsive: {
        dest: 'scss/modules/_grid-units.scss',
        options: {
          units: [5,12,24],
          includeOldIEWidths: false,
          mediaQueries: {
            sm: 'screen and (min-width: 36.5em)', //584px
            md: 'screen and (min-width: 48em)', //768px
            lg: 'screen and (min-width: 64em)', //1024px
            xl: 'screen and (min-width: 75em)'  //1200px
          },
          selectorPrefix: '.unit-'
        }
      }
    },
    sass: {
      options: {
        outputStyle: 'expanded',
        sourceMap: true,
        indentedSyntax: true,
        sassDir: 'scss',
        cssDir: 'dist/css'
      },
      dev: {
        files: [{
          expand: true,
          cwd: 'scss/',
          src: ['*.scss'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      },
      dist: {
        options: {
          sourceMap: false
        },
        files: [{
          expand: true,
          cwd: 'scss/',
          src: ['*.scss'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      },
      docs: {
        files: {
          'docs/css/main.css': 'docs/_sass/main.scss'
        }
      },
      docsDist: {
        options: {
          sourceMap: false
        },
        files: {
          'docs/css/main.css': 'docs/_sass/main.scss'
        }
      }
    },
    postcss: {
      options: {
        processors: [
          require('autoprefixer')({ browsers: ['last 2 version'] })
        ],
        map: {
          inline: false,
        }
      },
      dist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'dist/css/*.css'
      },
      dev: {
        src: 'dist/css/*.css'
      },
      docs: {
        src: 'docs/css/*.css'
      },
      docsDist: {
        options: {
          processors: [ require('cssnano')() ],
          map: false
        },
        src: 'docs/css/*.css'
      }
    },
    grunticon: {
      ui: {
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: ['*.svg'],
          dest: 'dist/assets/icons/ui'
        }],
        options: {
          dynamicColorOnly: true,
          colors: {
            light: '#ffffff',
            dark: '#000000'
          },
          datasvgcss: 'ui-icons.svg.css',
          datapngcss: 'ui-icons.png.css',
          urlpngcss: 'ui-icons.fallback.css'
        }
      },
      thematic: {
        files: [{
          expand: true,
          cwd: 'icons/thematic',
          src: ['*.svg'],
          dest: 'dist/assets/icons/thematic'
        }],
        options: {
          datasvgcss: 'thematic-icons.svg.css',
          datapngcss: 'thematic-icons.png.css',
          urlpngcss: 'thematic-icons.fallback.css',
          cssprefix: '.thematic-'
        }
      }
    },
    svgtoolkit: {
      light: {
        options: {
          generatePNGs: false,
          colorize: '#ffffff'
        },
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: '*.svg',
          dest: 'icons/ui/dist/light'
        }]
      },
      dark: {
        options: {
          generatePNGs: false,
          colorize: '#232323'
        },
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: '*.svg',
          dest: 'icons/ui/dist/dark'
        }]
      },
      primary: {
        options: {
          generatePNGs: false,
          colorize: '#2A93FC'
        },
        files: [{
          expand: true,
          cwd: 'icons/ui/src',
          src: '*.svg',
          dest: 'icons/ui/dist/primary'
        }]
      }
    },
    datauri: {
      light: {
        options: {
          classPrefix: 'icon-light-',
          usePlaceholder: true
        },
        files: [{
          src: 'icons/ui/dist/light/**/*.svg',
          dest: 'scss/modules/icons/_icons-light.scss'
        }]
      },
      dark: {
        options: {
          classPrefix: 'icon-dark-',
          usePlaceholder: true
        },
        files: [{
          src: 'icons/ui/dist/dark/**/*.svg',
          dest: 'scss/modules/icons/_icons-dark.scss'
        }]
      },
      primary: {
        options: {
          classPrefix: 'icon-primary-',
          usePlaceholder: true
        },
        files: [{
          src: 'icons/ui/dist/primary/**/*.svg',
          dest: 'scss/modules/icons/_icons-primary.scss'
        }]
      }
    },
    jekyll: {
      dev: {
        options: {
          src: './docs',
          config: './docs/_config-dev.yml',
          dest: './dist/docs'
        }
      },
      dist: {
        options: {
          src: './docs',
          config: './docs/_config.yml',
          dest: './dist/docs'
        }
      }
    },
    eslint: {
      options: {
        config: '.eslintrc.json',
        force: true
      },
      all: ['js/**/*.js']
    },
    sasslint: {
      options: {
        config: '.sass-lint.yml',
      },
      target: ['scss/**/*.scss']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-grunticon');
  grunt.loadNpmTasks('grunt-datauri');
  grunt.loadNpmTasks('grunt-jekyll');
  grunt.loadNpmTasks('grunt-postcss');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-sass-lint');
  grunt.loadNpmTasks('grunt-svg-toolkit');
  grunt.loadNpmTasks('grunt-pure-grids');
  grunt.loadNpmTasks('eslint-grunt');

  // Build SVGs and SCSS
  grunt.registerTask('gen-svg', ['clean:svg', 'svgtoolkit', 'datauri', 'clean:svg']);
  // Build Grunticon Icons
  grunt.registerTask('gen-icons', ['clean:grunticon', 'grunticon']);
  // Build WFP UI Docs locally
  grunt.registerTask('docs', ['sasslint', 'sass:docs', 'postcss:docs', 'jekyll:dev']);
  // Build WFP UI Docs
  grunt.registerTask('docs-build', ['sasslint', 'sass:docs', 'postcss:docs', 'gen-icons', 'jekyll:dev']);
  // Build dist-ready WFP UI Docs
  grunt.registerTask('docs-dist', ['sasslint', 'sass:docsDist', 'postcss:docsDist', 'gen-icons', 'jekyll:dist']);
  // Build WFP UI
  grunt.registerTask('build', ['eslint', 'gen-svg', 'sasslint', 'sass:dev', 'postcss:dev']);
  // Build a dist-ready WFP UI
  grunt.registerTask('dist', ['gen-svg', 'gen-icons', 'sass:dist', 'postcss:dist']);
  // Set default grunt task to `dist`
  grunt.registerTask('default', ['dist']);
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

module.exports = function(grunt) {
  'use strict';

  var lyriaOrigin = 'src/**/*.js';
  var generatedFiles = 'generated/**/*.js';

  var testFolder = fs.readdirSync('test/spec');
  var templateObject = {};
  testFolder.forEach(function(elem) {
    var extension = path.extname(elem);
    var base = elem.split(extension)[0];

    templateObject[base] = {
      engine: 'handlebars',
      src: 'test/templates/browser.html',
      dest: 'test/browser/' + base + '.html',
      variables: {
        script: 'spec/' + base,
        title: base.charAt(0).toUpperCase() + base.slice(1)
      }
    };
  });

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    amd_tamer: {
      options: {
        base: 'src/',
        namespace: 'lyria'
      },
      scripts: {
        src: [lyriaOrigin, generatedFiles],
        dest: 'dist/js/<%= pkg.name %>.js'
      }
    },
    concat: {
      styles: {
        src: ['dist/css/*.css'],
        dest: 'dist/css/<%= pkg.name %>.css'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        report: 'gzip'
      },
      dist: {
        files: {
          'dist/js/<%= pkg.name %>.min.js': ['<%= amd_tamer.scripts.dest %>']
        }
      }
    },
    cssmin: {
      minify: {
        expand: true,
        cwd: 'dist/css/',
        src: ['*.css', '!*.min.css'],
        dest: 'dist/css/min',
        ext: '.min.css'
      }
    },
    jshint: {
      files: ['gruntfile.js', lyriaOrigin, 'test/**/*.js'],
      options: grunt.file.readJSON('.jshintrc')
    },
    yuidoc: {
      compile: {
        name: '<%= pkg.name %>',
        description: '<%= pkg.description %>',
        version: '<%= pkg.version %>',
        url: '<%= pkg.homepage %>',
        options: {
          linkNatives: true,
          paths: 'src/',
          outdir: 'doc/api'
        }
      }
    },
    stylus: {
      options: {
        paths: ['stylus'],
        urlfunc: 'embedurl',
        import: ['nib']
      },
      compile: {
        options: {
          compress: false,
        },
        files: [{
          expand: true,
          cwd: 'stylus/',
          src: ['**/*.styl'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      }
    },
    handlebars: {
      options: {
        namespace: 'lyria/template/list',
      },
      compile: {
        files: {
          'generated/templates.js': ['templates/*.html']
        }
      }
    },
    changelog: {
      all: {
        options: {
          before: '1 year ago',
          fixRegex: /^(.*)Fixes #\d+:?(.*)$/gim
        }
      }
    },
    clean: ['dist', 'generated', 'test/browser'],
    dependo: {
      options: {
        format: 'amd'
      },
      all: {
        options: {
          targetPath: 'src',
          outputPath: './doc/dependencies'
        }
      }
    },
    plato: {
      all: {
        options: {
          jshint: grunt.file.readJSON('.jshintrc'),
          complexity: {
            logicalor: false,
            switchcase: false,
            forin: true,
            trycatch: true
          }
        },
        files: {
          'doc/reports/': ['src/**/*.js', 'test/**/*.js', 'gruntfile.js']
        }
      }
    },
    connect: {
      test: {
        options: {
          port: 9001
        }
      }
    },
    template: templateObject,
    mocha: {
      options: {
        log: true,
        reporter: 'Spec'
      },
      all: {
        src: ['test/browser/**/*.html']
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      all: {
        src: ['dist/css/*.css']
      }
    },
    bumper: {
      options: {
      files: ['package.json', 'bower.json'],
      tasks: ['default', 'doc'],
      commitMessage: 'Release %VERSION%',
      tagName: '%VERSION%',
      tagMessage: 'Version %VERSION%'
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadTasks('./tasks');

  grunt.registerTask('test', 'Lints and unit tests', ['jshint', 'csslint', 'template', 'mocha']);
  grunt.registerTask('doc', 'Generated documentation', ['yuidoc', 'dependo', 'plato']);
  grunt.registerTask('default', 'Default task', ['clean', 'handlebars', 'stylus', 'concat', 'amd_tamer', 'test', 'uglify', 'cssmin']);

};
<commit_msg>Yuidoc to JsDoc property<commit_after>var fs = require('fs');
var path = require('path');

module.exports = function(grunt) {
  'use strict';

  var lyriaOrigin = 'src/**/*.js';
  var generatedFiles = 'generated/**/*.js';

  var testFolder = fs.readdirSync('test/spec');
  var templateObject = {};
  testFolder.forEach(function(elem) {
    var extension = path.extname(elem);
    var base = elem.split(extension)[0];

    templateObject[base] = {
      engine: 'handlebars',
      src: 'test/templates/browser.html',
      dest: 'test/browser/' + base + '.html',
      variables: {
        script: 'spec/' + base,
        title: base.charAt(0).toUpperCase() + base.slice(1)
      }
    };
  });

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    amd_tamer: {
      options: {
        base: 'src/',
        namespace: 'lyria'
      },
      scripts: {
        src: [lyriaOrigin, generatedFiles],
        dest: 'dist/js/<%= pkg.name %>.js'
      }
    },
    concat: {
      styles: {
        src: ['dist/css/*.css'],
        dest: 'dist/css/<%= pkg.name %>.css'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        report: 'gzip'
      },
      dist: {
        files: {
          'dist/js/<%= pkg.name %>.min.js': ['<%= amd_tamer.scripts.dest %>']
        }
      }
    },
    cssmin: {
      minify: {
        expand: true,
        cwd: 'dist/css/',
        src: ['*.css', '!*.min.css'],
        dest: 'dist/css/min',
        ext: '.min.css'
      }
    },
    jshint: {
      files: ['gruntfile.js', lyriaOrigin, 'test/**/*.js'],
      options: grunt.file.readJSON('.jshintrc')
    },
    jsdoc: {
      options: {
        lenient: true
      },
      compile: {
        src: ['src/**/*.js', 'README.md'],
        dest: 'doc/api',
      }
    },
    stylus: {
      options: {
        paths: ['stylus'],
        urlfunc: 'embedurl',
        import: ['nib']
      },
      compile: {
        options: {
          compress: false,
        },
        files: [{
          expand: true,
          cwd: 'stylus/',
          src: ['**/*.styl'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      }
    },
    handlebars: {
      options: {
        namespace: 'lyria/template/list',
      },
      compile: {
        files: {
          'generated/templates.js': ['templates/*.html']
        }
      }
    },
    changelog: {
      all: {
        options: {
          before: '1 year ago',
          fixRegex: /^(.*)Fixes #\d+:?(.*)$/gim
        }
      }
    },
    clean: ['dist', 'generated', 'test/browser'],
    dependo: {
      options: {
        format: 'amd'
      },
      all: {
        options: {
          targetPath: 'src',
          outputPath: './doc/dependencies'
        }
      }
    },
    plato: {
      all: {
        options: {
          jshint: grunt.file.readJSON('.jshintrc'),
          complexity: {
            logicalor: false,
            switchcase: false,
            forin: true,
            trycatch: true
          }
        },
        files: {
          'doc/reports/': ['src/**/*.js', 'test/**/*.js', 'gruntfile.js']
        }
      }
    },
    connect: {
      test: {
        options: {
          port: 9001
        }
      }
    },
    template: templateObject,
    mocha: {
      options: {
        log: true,
        reporter: 'Spec'
      },
      all: {
        src: ['test/browser/**/*.html']
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      all: {
        src: ['dist/css/*.css']
      }
    },
    bumper: {
      options: {
      files: ['package.json', 'bower.json'],
      tasks: ['default', 'doc'],
      commitMessage: 'Release %VERSION%',
      tagName: '%VERSION%',
      tagMessage: 'Version %VERSION%'
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadTasks('./tasks');

  grunt.registerTask('test', 'Lints and unit tests', ['jshint', 'csslint', 'template', 'mocha']);
  grunt.registerTask('doc', 'Generated documentation', ['yuidoc', 'dependo', 'plato']);
  grunt.registerTask('default', 'Default task', ['clean', 'handlebars', 'stylus', 'concat', 'amd_tamer', 'test', 'uglify', 'cssmin']);

};
<|endoftext|>


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

  var lyriaOrigin = 'src/**/*.js';
  var generatedFiles = 'generated/**/*.js';

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat_sourcemap: {
      options: {
        sourcesContent: true,
        sourceRoot: '/'
      },
      scripts: {
        src: [lyriaOrigin, generatedFiles],
        dest: 'dist/js/<%= pkg.name %>.js'
      }
    },
    concat: {
      styles: {
        src: ['dist/css/*.css'],
        dest: 'dist/css/<%= pkg.name %>.css'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        report: 'gzip'
      },
      dist: {
        files: {
          'dist/js/<%= pkg.name %>.min.js': ['<%= concat_sourcemap.scripts.dest %>']
        }
      }
    },
    cssmin: {
      minify: {
        expand: true,
        cwd: 'dist/css/',
        src: ['*.css', '!*.min.css'],
        dest: 'dist/css/min',
        ext: '.min.css'
      }
    },
    jshint: {
      files: ['gruntfile.js', lyriaOrigin, 'test/**/*.js'],
      options: grunt.file.readJSON('.jshintrc')
    },
    yuidoc: {
      compile: {
        name: '<%= pkg.name %>',
        description: '<%= pkg.description %>',
        version: '<%= pkg.version %>',
        url: '<%= pkg.homepage %>',
        options: {
          linkNatives: true,
          paths: 'src/',
          outdir: 'doc/api'
        }
      }
    },
    stylus: {
      options: {
        paths: ['stylus'],
        urlfunc: 'embedurl',
        import: ['nib']
      },
      compile: {
        options: {
          compress: false,
        },
        files: [{
          expand: true,
          cwd: 'stylus/',
          src: ['**/*.styl'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      }
    },
    handlebars: {
      options: {
        namespace: 'lyria/template/list',
      },
      compile: {
        files: {
          'generated/templates.js': ['templates/*.html']
        }
      }
    },
    clean: ['dist', 'generated'],
    dependo: {
      targetPath: 'src',
      outputPath: './doc/dependencies',
      format: 'amd'
    },
    plato: {
      all: {
        options: {
          jshint: grunt.file.readJSON('.jshintrc'),
          complexity: {
            logicalor: false,
            switchcase: false,
            forin: true,
            trycatch: true
          }
        },
        files: {
          'doc/reports/': ['src/**/*.js', 'test/**/*.js', 'gruntfile.js']
        }
      }
    },
    connect: {
      test: {
        options: {
          port: 9001
        }
      }
    },
    mocha: {
      all: {
        options: {
          reporter: 'Spec',
          log: true
        },
        src: ['test/*.html']
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadTasks('./tasks');

  grunt.registerTask('test', 'Lints and unit tests', ['jshint']);
  grunt.registerTask('doc', 'Generated documentation', ['yuidoc', 'dependo', 'plato']);
  grunt.registerTask('default', 'Default task', ['clean', 'handlebars', 'stylus', 'concat', 'concat_sourcemap', 'test', 'uglify', 'cssmin', 'doc']);

};
<commit_msg>Updated grunt mocha task<commit_after>module.exports = function(grunt) {

  var lyriaOrigin = 'src/**/*.js';
  var generatedFiles = 'generated/**/*.js';

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat_sourcemap: {
      options: {
        sourcesContent: true,
        sourceRoot: '/'
      },
      scripts: {
        src: [lyriaOrigin, generatedFiles],
        dest: 'dist/js/<%= pkg.name %>.js'
      }
    },
    concat: {
      styles: {
        src: ['dist/css/*.css'],
        dest: 'dist/css/<%= pkg.name %>.css'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("dd-mm-yyyy") %> */\n',
        report: 'gzip'
      },
      dist: {
        files: {
          'dist/js/<%= pkg.name %>.min.js': ['<%= concat_sourcemap.scripts.dest %>']
        }
      }
    },
    cssmin: {
      minify: {
        expand: true,
        cwd: 'dist/css/',
        src: ['*.css', '!*.min.css'],
        dest: 'dist/css/min',
        ext: '.min.css'
      }
    },
    jshint: {
      files: ['gruntfile.js', lyriaOrigin, 'test/**/*.js'],
      options: grunt.file.readJSON('.jshintrc')
    },
    yuidoc: {
      compile: {
        name: '<%= pkg.name %>',
        description: '<%= pkg.description %>',
        version: '<%= pkg.version %>',
        url: '<%= pkg.homepage %>',
        options: {
          linkNatives: true,
          paths: 'src/',
          outdir: 'doc/api'
        }
      }
    },
    stylus: {
      options: {
        paths: ['stylus'],
        urlfunc: 'embedurl',
        import: ['nib']
      },
      compile: {
        options: {
          compress: false,
        },
        files: [{
          expand: true,
          cwd: 'stylus/',
          src: ['**/*.styl'],
          dest: 'dist/css/',
          ext: '.css'
        }]
      }
    },
    handlebars: {
      options: {
        namespace: 'lyria/template/list',
      },
      compile: {
        files: {
          'generated/templates.js': ['templates/*.html']
        }
      }
    },
    clean: ['dist', 'generated'],
    dependo: {
      targetPath: 'src',
      outputPath: './doc/dependencies',
      format: 'amd'
    },
    plato: {
      all: {
        options: {
          jshint: grunt.file.readJSON('.jshintrc'),
          complexity: {
            logicalor: false,
            switchcase: false,
            forin: true,
            trycatch: true
          }
        },
        files: {
          'doc/reports/': ['src/**/*.js', 'test/**/*.js', 'gruntfile.js']
        }
      }
    },
    connect: {
      test: {
        options: {
          port: 9001
        }
      }
    },
    mocha: {
      options: {
        log: true,
        reporter: 'Spec'
      },
      all: {
        src: ['test/*.html']
      }
    }
  });

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadTasks('./tasks');

  grunt.registerTask('test', 'Lints and unit tests', ['jshint']);
  grunt.registerTask('doc', 'Generated documentation', ['yuidoc', 'dependo', 'plato']);
  grunt.registerTask('default', 'Default task', ['clean', 'handlebars', 'stylus', 'concat', 'concat_sourcemap', 'test', 'uglify', 'cssmin', 'doc']);

};
<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { isPresent } from '@ember/utils';
import { dropTask, restartableTask } from 'ember-concurrency-decorators';

export default class CurriculumInventorySequenceBlockOverviewComponent extends Component {
  @service intl;
  @service store;
  @tracked academicLevel;
  @tracked academicLevels;
  @tracked childSequenceOrder;
  @tracked course;
  @tracked description;
  @tracked duration;
  @tracked endDate;
  @tracked isEditingDatesAndDuration = false;
  @tracked isEditingMinMax = false;
  @tracked isManagingSessions = false;
  @tracked linkableCourses = [];
  @tracked maximum = 0;
  @tracked minimum = 0;
  @tracked orderInSequence;
  @tracked orderInSequenceOptions = [];
  @tracked parent;
  @tracked report;
  @tracked required;
  @tracked sessions = [];
  @tracked startDate;

  @restartableTask
  *load(element, [sequenceBlock]) {
    this.report = yield sequenceBlock.report;
    this.parent = yield sequenceBlock.parent;
    this.academicLevels = (yield this.report.academicLevels).toArray();
    this.isInOrderedSequence = false;
    this.orderInSequenceOptions = [];
    if (isPresent(this.parent) && this.parent.isOrdered) {
      this.isInOrderedSequence = true;
      const siblings = yield this.parent.children;
      for (let i = 0, n = (siblings.toArray().length); i < n; i++) {
        const num = i + 1;
        this.orderInSequenceOptions.push(num);
      }
    }
    this.linkedSessions = yield sequenceBlock.sessions;
    this.academicLevel = yield sequenceBlock.academicLevel;
    this.required = sequenceBlock.required.toString();
    this.duration = sequenceBlock.duration;
    this.startDate = sequenceBlock.startDate;
    this.endDate = sequenceBlock.endDate;
    this.childSequenceOrder = sequenceBlock.childSequenceOrder.toString();
    this.orderInSequence = sequenceBlock.orderInSequence;
    this.description = sequenceBlock.description;
    this.course = yield sequenceBlock.course;
    this.minimum = sequenceBlock.minimum;
    this.maximum = sequenceBlock.maximum;
    this.sessions = yield this.getSessions(this.course);
    this.linkableCourses = yield this.getLinkableCourses(this.report, this.course);
  }

  get requiredLabel() {
    switch (this.required) {
    case '1':
      return this.intl.t('general.required');
    case '2':
      return this.intl.t('general.optionalElective');
    case '3':
      return this.intl.t('general.requiredInTrack');
    default:
      return null;
    }
  }

  get isElective() {
    return '2' === this.required;
  }

  get isSelective() {
    if (this.isElective) {
      return false;
    }
    const minimum = parseInt(this.minimum, 10);
    const maximum = parseInt(this.maximum, 10);
    return minimum > 0 && minimum !== maximum;
  }

  get childSequenceOrderLabel() {
    switch (this.childSequenceOrder) {
    case '1':
      return this.intl.t('general.ordered');
    case '2':
      return this.intl.t('general.unordered');
    case '3':
      return this.intl.t('general.parallel');
    default:
      return null;
    }
  }

  /**
   * Returns a list of courses that can be linked to this sequence block.
   */
  async getLinkableCourses(report, course) {
    if (!report) {
      return [];
    }
    const program = await report.program;
    const schoolId = program.belongsTo('school').id();
    const allLinkableCourses = await this.store.query('course', {
      filters: {
        published: true,
        school: [schoolId],
        year: report.get('year')
      }
    });
    const linkedCourses = await report.linkedCourses;
    // Filter out all courses that are linked to (sequence blocks in) this report.
    const linkableCourses = allLinkableCourses.filter((course) => {
      return !linkedCourses.includes(course);
    });
    // Always add the currently linked course to this list, if existent.
    if (isPresent(course)) {
      linkableCourses.pushObject(course);
    }

    return linkableCourses;
  }

  /**
   * Returns a list of published sessions that belong to a given course.
   */
  async getSessions(course) {
    if (! course) {
      return [];
    }
    const sessions = await this.store.query('session', {
      filters: {
        course: course.get('id'),
        published: true
      },
    });
    return sessions.toArray();
  }

  @dropTask
  *changeRequired() {
    this.args.sequenceBlock.set('required', parseInt(this.required, 10));
    if ('2' === this.required) {
      this.args.sequenceBlock.set('minimum', 0);
    }
    yield this.args.sequenceBlock.save();
  }

  @action
  setRequired(required) {
    this.required = required;
    if ('2' === required) {
      this.minimum = 0;
    } else {
      this.minimum = this.args.sequenceBlock.get('minimum');
    }
  }

  @action
  revertRequiredChanges() {
    this.required = this.args.sequenceBlock.get('required').toString();
    this.minimum = this.args.sequenceBlock.get('minimum');
  }

  @dropTask
  *saveCourse() {
    const oldCourse = yield this.args.sequenceBlock.course;
    if (oldCourse !== this.course) {
      this.args.sequenceBlock.set('sessions', []);
      this.args.sequenceBlock.set('excludedSessions', []);
    }
    this.args.sequenceBlock.set('course', this.course);
    yield this.args.sequenceBlock.save();
  }

  @action
  async revertCourseChanges() {
    this.course = await this.args.sequenceBlock.get('course');
  }

  @dropTask()
  *changeTrack(value) {
    this.args.sequenceBlock.set('track', value);
    yield this.args.sequenceBlock.save();
  }

  @dropTask()
  *saveDescription() {
    this.args.sequenceBlock.set('description', this.description);
    yield this.args.sequenceBlock.save();
  }

  @action
  revertDescriptionChanges() {
    this.description = this.args.sequenceBlock.get('description');
  }

  @dropTask
  *changeChildSequenceOrder() {
    this.args.sequenceBlock.set('childSequenceOrder', parseInt(this.childSequenceOrder, 10));
    const savedBlock = yield this.args.sequenceBlock.save();
    const children = yield savedBlock.get('children');
    yield children.invoke('reload');
  }

  @action
  revertChildSequenceOrderChanges() {
    this.childSequenceOrder = this.args.sequenceBlock.get('childSequenceOrder').toString();
  }

  @dropTask
  *changeAcademicLevel() {
    this.args.sequenceBlock.set('academicLevel', this.academicLevel);
    yield this.args.sequenceBlock.save();
  }

  @action
  setAcademicLevel(event) {
    const id = event.target.value;
    this.academicLevel = this.academicLevels.findBy('id', id);
  }

  @action
  revertAcademicLevelChanges() {
    this.academicLevel = this.args.sequenceBlock.academicLevel;
  }

  @dropTask
  *changeOrderInSequence() {
    this.args.sequenceBlock.set('orderInSequence', this.orderInSequence);
    const savedBlock = yield this.args.sequenceBlock.save();
    const parent = yield savedBlock.get('parent');
    const children = yield parent.get('children');
    yield children.invoke('reload');
  }

  @action
  revertOrderInSequenceChanges() {
    this.orderInSequence = this.args.sequenceBlock.get('orderInSequence');
  }

  @dropTask
  *changeDatesAndDuration(start, end, duration) {
    this.args.sequenceBlock.set('startDate', start);
    this.args.sequenceBlock.set('endDate', end);
    this.args.sequenceBlock.set('duration', duration);
    yield this.args.sequenceBlock.save();
    this.isEditingDatesAndDuration = false;
  }

  @action
  editDatesAndDuration() {
    this.isEditingDatesAndDuration = true;
  }

  @action
  cancelDateAndDurationEditing() {
    this.isEditingDatesAndDuration = false;
  }

  @dropTask
  *changeMinMax(minimum, maximum) {
    this.args.sequenceBlock.set('minimum', minimum);
    this.args.sequenceBlock.set('maximum', maximum);
    yield this.args.sequenceBlock.save();
    this.isEditingMinMax = false;
  }

  @action
  editMinMax() {
    this.isEditingMinMax = true;
  }

  @action
  cancelMinMaxEditing() {
    this.args.sequenceBlock.set('isEditingMinMax', false);
    this.minimum = this.args.sequenceBlock.get('minimum');
    this.maximum = this.args.sequenceBlock.get('maximum');
  }

  @action
  toggleManagingSessions() {
    this.isManagingSessions = !this.isManagingSessions;
  }

  @action
  cancelManagingSessions() {
    this.isManagingSessions = false;
  }

  @dropTask
  *changeSessions(sessions, excludedSessions) {
    this.args.sequenceBlock.set('sessions', sessions);
    this.args.sequenceBlock.set('excludedSessions', excludedSessions);
    yield this.args.sequenceBlock.save();
    this.isManagingSessions = false;
  }

  @action
  updateCourse(event) {
    const value = event.target.value;
    if (! value) {
      this.course = null;
    } else {
      this.course = this.linkableCourses.findBy('id', value);
    }
  }

  @action
  changeDescription(event) {
    this.description = event.target.value;
  }

  @action
  updateOrderInSequence(event) {
    this.orderInSequence = event.target.value;
  }
}

<commit_msg>Correctly track property<commit_after>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { isPresent } from '@ember/utils';
import { dropTask, restartableTask } from 'ember-concurrency-decorators';

export default class CurriculumInventorySequenceBlockOverviewComponent extends Component {
  @service intl;
  @service store;
  @tracked academicLevel;
  @tracked academicLevels;
  @tracked childSequenceOrder;
  @tracked course;
  @tracked description;
  @tracked duration;
  @tracked endDate;
  @tracked isEditingDatesAndDuration = false;
  @tracked isEditingMinMax = false;
  @tracked isManagingSessions = false;
  @tracked linkableCourses = [];
  @tracked maximum = 0;
  @tracked minimum = 0;
  @tracked isInOrderedSequence;
  @tracked orderInSequence;
  @tracked orderInSequenceOptions = [];
  @tracked parent;
  @tracked report;
  @tracked required;
  @tracked sessions = [];
  @tracked startDate;

  @restartableTask
  *load(element, [sequenceBlock]) {
    this.report = yield sequenceBlock.report;
    this.parent = yield sequenceBlock.parent;
    this.academicLevels = (yield this.report.academicLevels).toArray();
    this.isInOrderedSequence = false;
    this.orderInSequenceOptions = [];
    if (isPresent(this.parent) && this.parent.isOrdered) {
      this.isInOrderedSequence = true;
      const siblings = yield this.parent.children;
      for (let i = 0, n = (siblings.toArray().length); i < n; i++) {
        const num = i + 1;
        this.orderInSequenceOptions.push(num);
      }
    }
    this.linkedSessions = yield sequenceBlock.sessions;
    this.academicLevel = yield sequenceBlock.academicLevel;
    this.required = sequenceBlock.required.toString();
    this.duration = sequenceBlock.duration;
    this.startDate = sequenceBlock.startDate;
    this.endDate = sequenceBlock.endDate;
    this.childSequenceOrder = sequenceBlock.childSequenceOrder.toString();
    this.orderInSequence = sequenceBlock.orderInSequence;
    this.description = sequenceBlock.description;
    this.course = yield sequenceBlock.course;
    this.minimum = sequenceBlock.minimum;
    this.maximum = sequenceBlock.maximum;
    this.sessions = yield this.getSessions(this.course);
    this.linkableCourses = yield this.getLinkableCourses(this.report, this.course);
  }

  get requiredLabel() {
    switch (this.required) {
    case '1':
      return this.intl.t('general.required');
    case '2':
      return this.intl.t('general.optionalElective');
    case '3':
      return this.intl.t('general.requiredInTrack');
    default:
      return null;
    }
  }

  get isElective() {
    return '2' === this.required;
  }

  get isSelective() {
    if (this.isElective) {
      return false;
    }
    const minimum = parseInt(this.minimum, 10);
    const maximum = parseInt(this.maximum, 10);
    return minimum > 0 && minimum !== maximum;
  }

  get childSequenceOrderLabel() {
    switch (this.childSequenceOrder) {
    case '1':
      return this.intl.t('general.ordered');
    case '2':
      return this.intl.t('general.unordered');
    case '3':
      return this.intl.t('general.parallel');
    default:
      return null;
    }
  }

  /**
   * Returns a list of courses that can be linked to this sequence block.
   */
  async getLinkableCourses(report, course) {
    if (!report) {
      return [];
    }
    const program = await report.program;
    const schoolId = program.belongsTo('school').id();
    const allLinkableCourses = await this.store.query('course', {
      filters: {
        published: true,
        school: [schoolId],
        year: report.get('year')
      }
    });
    const linkedCourses = await report.linkedCourses;
    // Filter out all courses that are linked to (sequence blocks in) this report.
    const linkableCourses = allLinkableCourses.filter((course) => {
      return !linkedCourses.includes(course);
    });
    // Always add the currently linked course to this list, if existent.
    if (isPresent(course)) {
      linkableCourses.pushObject(course);
    }

    return linkableCourses;
  }

  /**
   * Returns a list of published sessions that belong to a given course.
   */
  async getSessions(course) {
    if (! course) {
      return [];
    }
    const sessions = await this.store.query('session', {
      filters: {
        course: course.get('id'),
        published: true
      },
    });
    return sessions.toArray();
  }

  @dropTask
  *changeRequired() {
    this.args.sequenceBlock.set('required', parseInt(this.required, 10));
    if ('2' === this.required) {
      this.args.sequenceBlock.set('minimum', 0);
    }
    yield this.args.sequenceBlock.save();
  }

  @action
  setRequired(required) {
    this.required = required;
    if ('2' === required) {
      this.minimum = 0;
    } else {
      this.minimum = this.args.sequenceBlock.get('minimum');
    }
  }

  @action
  revertRequiredChanges() {
    this.required = this.args.sequenceBlock.get('required').toString();
    this.minimum = this.args.sequenceBlock.get('minimum');
  }

  @dropTask
  *saveCourse() {
    const oldCourse = yield this.args.sequenceBlock.course;
    if (oldCourse !== this.course) {
      this.args.sequenceBlock.set('sessions', []);
      this.args.sequenceBlock.set('excludedSessions', []);
    }
    this.args.sequenceBlock.set('course', this.course);
    yield this.args.sequenceBlock.save();
  }

  @action
  async revertCourseChanges() {
    this.course = await this.args.sequenceBlock.get('course');
  }

  @dropTask()
  *changeTrack(value) {
    this.args.sequenceBlock.set('track', value);
    yield this.args.sequenceBlock.save();
  }

  @dropTask()
  *saveDescription() {
    this.args.sequenceBlock.set('description', this.description);
    yield this.args.sequenceBlock.save();
  }

  @action
  revertDescriptionChanges() {
    this.description = this.args.sequenceBlock.get('description');
  }

  @dropTask
  *changeChildSequenceOrder() {
    this.args.sequenceBlock.set('childSequenceOrder', parseInt(this.childSequenceOrder, 10));
    const savedBlock = yield this.args.sequenceBlock.save();
    const children = yield savedBlock.get('children');
    yield children.invoke('reload');
  }

  @action
  revertChildSequenceOrderChanges() {
    this.childSequenceOrder = this.args.sequenceBlock.get('childSequenceOrder').toString();
  }

  @dropTask
  *changeAcademicLevel() {
    this.args.sequenceBlock.set('academicLevel', this.academicLevel);
    yield this.args.sequenceBlock.save();
  }

  @action
  setAcademicLevel(event) {
    const id = event.target.value;
    this.academicLevel = this.academicLevels.findBy('id', id);
  }

  @action
  revertAcademicLevelChanges() {
    this.academicLevel = this.args.sequenceBlock.academicLevel;
  }

  @dropTask
  *changeOrderInSequence() {
    this.args.sequenceBlock.set('orderInSequence', this.orderInSequence);
    const savedBlock = yield this.args.sequenceBlock.save();
    const parent = yield savedBlock.get('parent');
    const children = yield parent.get('children');
    yield children.invoke('reload');
  }

  @action
  revertOrderInSequenceChanges() {
    this.orderInSequence = this.args.sequenceBlock.get('orderInSequence');
  }

  @dropTask
  *changeDatesAndDuration(start, end, duration) {
    this.args.sequenceBlock.set('startDate', start);
    this.args.sequenceBlock.set('endDate', end);
    this.args.sequenceBlock.set('duration', duration);
    yield this.args.sequenceBlock.save();
    this.isEditingDatesAndDuration = false;
  }

  @action
  editDatesAndDuration() {
    this.isEditingDatesAndDuration = true;
  }

  @action
  cancelDateAndDurationEditing() {
    this.isEditingDatesAndDuration = false;
  }

  @dropTask
  *changeMinMax(minimum, maximum) {
    this.args.sequenceBlock.set('minimum', minimum);
    this.args.sequenceBlock.set('maximum', maximum);
    yield this.args.sequenceBlock.save();
    this.isEditingMinMax = false;
  }

  @action
  editMinMax() {
    this.isEditingMinMax = true;
  }

  @action
  cancelMinMaxEditing() {
    this.args.sequenceBlock.set('isEditingMinMax', false);
    this.minimum = this.args.sequenceBlock.get('minimum');
    this.maximum = this.args.sequenceBlock.get('maximum');
  }

  @action
  toggleManagingSessions() {
    this.isManagingSessions = !this.isManagingSessions;
  }

  @action
  cancelManagingSessions() {
    this.isManagingSessions = false;
  }

  @dropTask
  *changeSessions(sessions, excludedSessions) {
    this.args.sequenceBlock.set('sessions', sessions);
    this.args.sequenceBlock.set('excludedSessions', excludedSessions);
    yield this.args.sequenceBlock.save();
    this.isManagingSessions = false;
  }

  @action
  updateCourse(event) {
    const value = event.target.value;
    if (! value) {
      this.course = null;
    } else {
      this.course = this.linkableCourses.findBy('id', value);
    }
  }

  @action
  changeDescription(event) {
    this.description = event.target.value;
  }

  @action
  updateOrderInSequence(event) {
    this.orderInSequence = event.target.value;
  }
}
<|endoftext|>


<commit_before>define(['app', 'lodash', 'moment', 'json!./schema-name.json', 'components/scbd-angularjs-services/services/locale'],
function (app, _, moment, scbdSchemaDetails, schemaShortName) {

  app.directive("translationUrl", ['$browser', function($browser){
    return {
      restrict : 'A',
      link :  function($scope, $element, $attrs){

        var lastPath;
        // console.log($attrs.ngClick);
        if(!$attrs.ngClick){
          $attrs.$observe('href', function(){
            // console.log($attrs)
            var langRegex 			= new RegExp('^\/(ar|en|es|fr|ru|zh)(\/|$)');
            var externalUrlRegex 	= new RegExp('^(http|https|mailto)');
            var startWithRegex	 	= new RegExp('^\/');
            var startWithAPIRegex         = new RegExp('^\/api\/v20');

            if(lastPath != $attrs.href && !langRegex.test($attrs.href) && !startWithAPIRegex.test($attrs.href)
            && startWithRegex.test($attrs.href)){
              lastPath = $browser.baseHref() + $attrs.href.replace(/^\//, '');
              $attrs.$set('href', lastPath);
            };
          })
        }
      }
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter('nospace', function () {
    return function (value) {
      return (!value) ? '' : value.replace(/[\s]/g, '');
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("yesno", function () {
    return function (boolValue) {
      return boolValue ? "Yes" : "No";
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("formatDate", ["$filter", function ($filter) {
    return function (date, formart) {
      if (formart === undefined)
        formart = 'DD MMM YYYY';

      return $filter("moment")(date, 'format',formart);
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("formatDateWithTime", ["$filter", function ($filter) {
    return function (date, formart) {
      if (formart === undefined)
        formart = 'DD MMM YYYY HH:mm';

      return $filter("moment")(date, 'format',formart);
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter('moment', [function() {

        return function(datetime, method, arg1, arg2, arg3) {
            return moment.utc(datetime)[method](arg1, arg2, arg3);
        };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("formatDateWithUtc", ['$filter', function ($filter) {

    return function (date, formart) {
      if (formart === undefined)
        formart = 'DD MMM YYYY';

      return $filter("moment")(date, 'format',formart);

    };
  }]);
  //============================================================
  //
  //
  //
  //============================================================
  app.filter("stringToJSON", function () {
    return function (strValue) {
      return JSON.parse(strValue);
    };
  });

  app.filter('range', function () {
    return function (input, total) {
      total = parseInt(total);
      for (var i = 0; i < total; i++)
        input.push(i);
      return input;
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("languageLongName", [function () {

    return function (language) {

      if (language == "ar") return "Arabic";
      if (language == "en") return "English";
      if (language == "es") return "Spanish";
      if (language == "fr") return "French";
      if (language == "ru") return "Russian";
      if (language == "zh") return "Chinese";

      return language;
    };
  }]);
  //============================================================
  //
  //
  //
  //============================================================
  app.filter("orderPromiseBy", ["$q", "$filter", function ($q, $filter) {
    return function (promise, expression, reverse) {
      return $q.when(promise).then(function (collection) {
        return $filter("orderBy")(collection, expression, reverse);
      });
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("markdown", ["$window", "htmlUtility", function ($window, html) {
    return function (srcText) {
      return srcText;
      if (!$window.marked) //if markdown is not install then return escaped html! to be safe!
        return "
" + html.encode(srcText) + "
";
      return $window.marked(srcText, {
        sanitize: true
      });
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("truncate", function () {
    return function (text, maxSize, suffix) {

      if (!maxSize)
        return text;

      if (!suffix)
        suffix = "";

      if (!text)
        return "".su;

      if (text.length > maxSize)
        text = text.substr(0, maxSize) + suffix;

      return text;
    };
  });

  app.filter('groupBy', ["underscore", "$parse", function (_, $parse) {
    var cacheMap = {};
    return _.memoize(function (items, field) {
      var getter = $parse(field);
      return _.groupBy(items, function (item) {
        return getter(item);
      });
    });
  }]);

  app.filter('to_trusted', function ($sce) {
    return function (html) {
      return $sce.trustAsHtml(html);
    };
  });

  app.filter("toTrusted", ["$sce", function ($sce) {
    return function (value) {
      return $sce.trustAsHtml(value);
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("term", ["$http", '$filter', 'locale', function ($http, $filter, websiteLocale) {
    var cacheMap = {};

    return function (term, locale) {

      if (!term)
        return "";

      if (term && angular.isString(term))
        term = {
          identifier: term
        };

      if(locale && _.isArray(locale))
        locale = websiteLocale;
      locale = locale || "en";

      if (cacheMap[term.identifier])
        return $filter("lstring")(cacheMap[term.identifier].title, locale) +
          (term.customValue ? (' ('+$filter("lstring")(term.customValue, locale) + ')') : '');

      cacheMap[term.identifier] = $http.get("/api/v2013/thesaurus/terms?termCode=" + encodeURIComponent(term.identifier), {
        cache: true
      }).then(function (result) {

        cacheMap[term.identifier] = result.data;

        return $filter("lstring")(cacheMap[term.identifier].title, locale)+
          (term.customValue ? (' ('+$filter("lstring")(term.customValue, locale) + ')') : '');

      }).catch(function () {

        cacheMap[term.identifier] = term.identifier;

        return term.identifier;

      });
    };
  }]);

  app.filter("lstring", function () {
    return function (ltext, locale) {

      if(angular.isNumber(ltext)) //is number to handle generic implementation of NR
        return ltext;

      if (!ltext)
        return "";

      if (angular.isString(ltext))
        return ltext;

      var sText;

      if (!sText && locale)
        sText = ltext[locale];

      if (!sText)
        sText = ltext.en;

      if (!sText) {

        var normalized = normalizeText(ltext)
        if(normalized[locale])
          return normalized[locale];

        for (var key in ltext) {
          sText = ltext[key];
          if (sText)
            break;
        }
      }

      return sText || "";
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("schemaName", ['realm', 'locale', '$filter', function(realm, locale, $filter) {

		return function( schema ) {

			if(!schema)return schema;

      var data = ((realm.schemas[schema]||{}).title||{});

      if(!data)
        data = scbdSchemaDetails[schema];

      var result = $filter('lstring')(data, locale);

      if(!result || result == '')
        result = schema;//legacy

      return result;

		};
	}]);

  //============================================================
	//
	//
	//
	//============================================================
	app.filter("schemaShortName", ['realm', function(realm) {
		return function( schema ) {
			return schemaShortName(realm, schema);
		};
	}]);
	app.filter("urlSchemaShortName", ['realm', function(realm) {

		return function( schema ) {
			return schemaShortName(realm, schema);
		};
  }]);

  function schemaShortName(realm, schema) {

    if(!schema)
      return schema;

      var result = (realm.schemas[schema]||{}).shortCode;

      return result || (scbdSchemaDetails[schema]||{}).shortCode || schema;
  }

  //============================================================
	//
	//
	//
	//============================================================
	app.filter("mapSchema", ['realm', function(realm) {

		return function( schema ) {
			if(!schema)
				return schema;

      var realmSchema = _.findKey(realm.schemas, {shortCode: schema.toUpperCase()})
      if(realmSchema)
        return realmSchema;

      realmSchema = _.findKey(scbdSchemaDetails, {shortCode: schema.toUpperCase()})

      return realmSchema || schema;
		};
	}]);

  app.filter("lstringLocale", ['locale', function(defaultLocale) {
    return function(ltext, locale) {

      if(locale && _.isArray(locale))
        locale = defaultLocale;

      locale = locale || defaultLocale;

      if(!ltext)
        return locale;

      if(typeof(ltext) == 'string')
        return locale;

      if(ltext[locale])
        return locale;

      if(ltext[defaultLocale])
              return defaultLocale;

      if(ltext.en)
        return 'en';

      if(ltext.fr) return 'fr';
      if(ltext.es) return 'es';
      if(ltext.ru) return 'ru';
      if(ltext.ar) return 'ar';
      if(ltext.zh) return 'zh';

      for(var key in ltext) {
        if(ltext[key])
            return key;
      }

      return locale;
    };
  }]);

  app.filter("direction", ['$filter', function($filter) {
    return function(text, locale) {

          locale = $filter('lstringLocale')(text, locale);

          return $filter('localeDirection')(locale);
    };
  }]);

  app.filter("localeDirection", ['locale', function(defaultLocale) {
    return function(locale) {
          return (locale||defaultLocale) == 'ar' ? 'rtl' : 'ltr';
      };
  }]);

  app.filter("encode", function(){
    return function(val) {
      return encodeURIComponent(val);
    };
  });

  function normalizeText(text) {

		if(!text) return null;

		var entry = { ar: text.ar, en: text.en, es: text.es, fr: text.fr, ru: text.ru, zh: text.zh };

		if(!entry.en) entry.en = entry.fr;
		if(!entry.en) entry.en = entry.es;
		if(!entry.en) entry.en = entry.ru;
		if(!entry.en) entry.en = entry.ar;
		if(!entry.en) entry.en = entry.zh;

		if(!entry.fr) entry.fr = entry.en;
		if(!entry.es) entry.es = entry.en;
		if(!entry.ru) entry.ru = entry.en;
		if(!entry.ar) entry.ar = entry.en;
		if(!entry.zh) entry.zh = entry.en;

    return entry;
  }
});
<commit_msg>apply moment only when date is available<commit_after>define(['app', 'lodash', 'moment', 'json!./schema-name.json', 'components/scbd-angularjs-services/services/locale'],
function (app, _, moment, scbdSchemaDetails, schemaShortName) {

  app.directive("translationUrl", ['$browser', function($browser){
    return {
      restrict : 'A',
      link :  function($scope, $element, $attrs){

        var lastPath;
        // console.log($attrs.ngClick);
        if(!$attrs.ngClick){
          $attrs.$observe('href', function(){
            // console.log($attrs)
            var langRegex 			= new RegExp('^\/(ar|en|es|fr|ru|zh)(\/|$)');
            var externalUrlRegex 	= new RegExp('^(http|https|mailto)');
            var startWithRegex	 	= new RegExp('^\/');
            var startWithAPIRegex         = new RegExp('^\/api\/v20');

            if(lastPath != $attrs.href && !langRegex.test($attrs.href) && !startWithAPIRegex.test($attrs.href)
            && startWithRegex.test($attrs.href)){
              lastPath = $browser.baseHref() + $attrs.href.replace(/^\//, '');
              $attrs.$set('href', lastPath);
            };
          })
        }
      }
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter('nospace', function () {
    return function (value) {
      return (!value) ? '' : value.replace(/[\s]/g, '');
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("yesno", function () {
    return function (boolValue) {
      return boolValue ? "Yes" : "No";
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("formatDate", ["$filter", function ($filter) {
    return function (date, formart) {
      if (formart === undefined)
        formart = 'DD MMM YYYY';
        return $filter("moment")(date, 'format',formart);
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("formatDateWithTime", ["$filter", function ($filter) {
    return function (date, formart) {
      if (formart === undefined)
        formart = 'DD MMM YYYY HH:mm';

      return $filter("moment")(date, 'format',formart);
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter('moment', [function() {

        return function(datetime, method, arg1, arg2, arg3) {
            if(datetime)
              return moment.utc(datetime)[method](arg1, arg2, arg3);
        };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("formatDateWithUtc", ['$filter', function ($filter) {

    return function (date, formart) {
      if (formart === undefined)
        formart = 'DD MMM YYYY';

      return $filter("moment")(date, 'format',formart);

    };
  }]);
  //============================================================
  //
  //
  //
  //============================================================
  app.filter("stringToJSON", function () {
    return function (strValue) {
      return JSON.parse(strValue);
    };
  });

  app.filter('range', function () {
    return function (input, total) {
      total = parseInt(total);
      for (var i = 0; i < total; i++)
        input.push(i);
      return input;
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("languageLongName", [function () {

    return function (language) {

      if (language == "ar") return "Arabic";
      if (language == "en") return "English";
      if (language == "es") return "Spanish";
      if (language == "fr") return "French";
      if (language == "ru") return "Russian";
      if (language == "zh") return "Chinese";

      return language;
    };
  }]);
  //============================================================
  //
  //
  //
  //============================================================
  app.filter("orderPromiseBy", ["$q", "$filter", function ($q, $filter) {
    return function (promise, expression, reverse) {
      return $q.when(promise).then(function (collection) {
        return $filter("orderBy")(collection, expression, reverse);
      });
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("markdown", ["$window", "htmlUtility", function ($window, html) {
    return function (srcText) {
      return srcText;
      if (!$window.marked) //if markdown is not install then return escaped html! to be safe!
        return "
" + html.encode(srcText) + "
";
      return $window.marked(srcText, {
        sanitize: true
      });
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("truncate", function () {
    return function (text, maxSize, suffix) {

      if (!maxSize)
        return text;

      if (!suffix)
        suffix = "";

      if (!text)
        return "".su;

      if (text.length > maxSize)
        text = text.substr(0, maxSize) + suffix;

      return text;
    };
  });

  app.filter('groupBy', ["underscore", "$parse", function (_, $parse) {
    var cacheMap = {};
    return _.memoize(function (items, field) {
      var getter = $parse(field);
      return _.groupBy(items, function (item) {
        return getter(item);
      });
    });
  }]);

  app.filter('to_trusted', function ($sce) {
    return function (html) {
      return $sce.trustAsHtml(html);
    };
  });

  app.filter("toTrusted", ["$sce", function ($sce) {
    return function (value) {
      return $sce.trustAsHtml(value);
    };
  }]);

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("term", ["$http", '$filter', 'locale', function ($http, $filter, websiteLocale) {
    var cacheMap = {};

    return function (term, locale) {

      if (!term)
        return "";

      if (term && angular.isString(term))
        term = {
          identifier: term
        };

      if(locale && _.isArray(locale))
        locale = websiteLocale;
      locale = locale || "en";

      if (cacheMap[term.identifier])
        return $filter("lstring")(cacheMap[term.identifier].title, locale) +
          (term.customValue ? (' ('+$filter("lstring")(term.customValue, locale) + ')') : '');

      cacheMap[term.identifier] = $http.get("/api/v2013/thesaurus/terms?termCode=" + encodeURIComponent(term.identifier), {
        cache: true
      }).then(function (result) {

        cacheMap[term.identifier] = result.data;

        return $filter("lstring")(cacheMap[term.identifier].title, locale)+
          (term.customValue ? (' ('+$filter("lstring")(term.customValue, locale) + ')') : '');

      }).catch(function () {

        cacheMap[term.identifier] = term.identifier;

        return term.identifier;

      });
    };
  }]);

  app.filter("lstring", function () {
    return function (ltext, locale) {

      if(angular.isNumber(ltext)) //is number to handle generic implementation of NR
        return ltext;

      if (!ltext)
        return "";

      if (angular.isString(ltext))
        return ltext;

      var sText;

      if (!sText && locale)
        sText = ltext[locale];

      if (!sText)
        sText = ltext.en;

      if (!sText) {

        var normalized = normalizeText(ltext)
        if(normalized[locale])
          return normalized[locale];

        for (var key in ltext) {
          sText = ltext[key];
          if (sText)
            break;
        }
      }

      return sText || "";
    };
  });

  //============================================================
  //
  //
  //
  //============================================================
  app.filter("schemaName", ['realm', 'locale', '$filter', function(realm, locale, $filter) {

		return function( schema ) {

			if(!schema)return schema;

      var data = ((realm.schemas[schema]||{}).title||{});

      if(!data)
        data = scbdSchemaDetails[schema];

      var result = $filter('lstring')(data, locale);

      if(!result || result == '')
        result = schema;//legacy

      return result;

		};
	}]);

  //============================================================
	//
	//
	//
	//============================================================
	app.filter("schemaShortName", ['realm', function(realm) {
		return function( schema ) {
			return schemaShortName(realm, schema);
		};
	}]);
	app.filter("urlSchemaShortName", ['realm', function(realm) {

		return function( schema ) {
			return schemaShortName(realm, schema);
		};
  }]);

  function schemaShortName(realm, schema) {

    if(!schema)
      return schema;

      var result = (realm.schemas[schema]||{}).shortCode;

      return result || (scbdSchemaDetails[schema]||{}).shortCode || schema;
  }

  //============================================================
	//
	//
	//
	//============================================================
	app.filter("mapSchema", ['realm', function(realm) {

		return function( schema ) {
			if(!schema)
				return schema;

      var realmSchema = _.findKey(realm.schemas, {shortCode: schema.toUpperCase()})
      if(realmSchema)
        return realmSchema;

      realmSchema = _.findKey(scbdSchemaDetails, {shortCode: schema.toUpperCase()})

      return realmSchema || schema;
		};
	}]);

  app.filter("lstringLocale", ['locale', function(defaultLocale) {
    return function(ltext, locale) {

      if(locale && _.isArray(locale))
        locale = defaultLocale;

      locale = locale || defaultLocale;

      if(!ltext)
        return locale;

      if(typeof(ltext) == 'string')
        return locale;

      if(ltext[locale])
        return locale;

      if(ltext[defaultLocale])
              return defaultLocale;

      if(ltext.en)
        return 'en';

      if(ltext.fr) return 'fr';
      if(ltext.es) return 'es';
      if(ltext.ru) return 'ru';
      if(ltext.ar) return 'ar';
      if(ltext.zh) return 'zh';

      for(var key in ltext) {
        if(ltext[key])
            return key;
      }

      return locale;
    };
  }]);

  app.filter("direction", ['$filter', function($filter) {
    return function(text, locale) {

          locale = $filter('lstringLocale')(text, locale);

          return $filter('localeDirection')(locale);
    };
  }]);

  app.filter("localeDirection", ['locale', function(defaultLocale) {
    return function(locale) {
          return (locale||defaultLocale) == 'ar' ? 'rtl' : 'ltr';
      };
  }]);

  app.filter("encode", function(){
    return function(val) {
      return encodeURIComponent(val);
    };
  });

  function normalizeText(text) {

		if(!text) return null;

		var entry = { ar: text.ar, en: text.en, es: text.es, fr: text.fr, ru: text.ru, zh: text.zh };

		if(!entry.en) entry.en = entry.fr;
		if(!entry.en) entry.en = entry.es;
		if(!entry.en) entry.en = entry.ru;
		if(!entry.en) entry.en = entry.ar;
		if(!entry.en) entry.en = entry.zh;

		if(!entry.fr) entry.fr = entry.en;
		if(!entry.es) entry.es = entry.en;
		if(!entry.ru) entry.ru = entry.en;
		if(!entry.ar) entry.ar = entry.en;
		if(!entry.zh) entry.zh = entry.en;

    return entry;
  }
});
<|endoftext|>