<commit_before>#!/usr/bin/env node

/**
 * Builds app binaries for OS X, Linux, and Windows.
 */

var config = require('../config')
var cp = require('child_process')
var electronPackager = require('electron-packager')
var fs = require('fs')
var path = require('path')
var pkg = require('../package.json')

var BUILD_NAME = config.APP_NAME + '-v' + config.APP_VERSION

function build () {
  var platform = process.argv[2]
  if (platform === '--darwin') {
    buildDarwin(printDone)
  } else if (platform === '--win32') {
    buildWin32(printDone)
  } else if (platform === '--linux') {
    buildLinux(printDone)
  } else {
    buildDarwin(function (err, buildPath) {
      printDone(err, buildPath)
      buildWin32(function (err, buildPath) {
        printDone(err, buildPath)
        buildLinux(printDone)
      })
    })
  }
}

var all = {
  // Build 64 bit binaries only.
  arch: 'x64',

  // The application source directory.
  dir: config.ROOT_PATH,

  // The release version of the application. Maps to the `ProductVersion` metadata
  // property on Windows, and `CFBundleShortVersionString` on OS X.
  'app-version': pkg.version,

  // Package the application's source code into an archive, using Electron's archive
  // format. Mitigates issues around long path names on Windows and slightly speeds up
  // require().
  asar: true,

  // A glob expression, that unpacks the files with matching names to the
  // "app.asar.unpacked" directory.
  'asar-unpack': 'WebTorrent*',

  // The build version of the application. Maps to the FileVersion metadata property on
  // Windows, and CFBundleVersion on OS X. We're using the short git hash (e.g. 'e7d837e')
  // Windows requires the build version to start with a number :/ so we stick on a prefix
  'build-version': '0-' + cp.execSync('git rev-parse --short HEAD').toString().replace('\n', ''),

  // Pattern which specifies which files to ignore when copying files to create the
  // package(s).
  ignore: /^\/dist|\/(appveyor.yml|AUTHORS|CONTRIBUTORS|bench|benchmark|benchmark\.js|bin|bower\.json|component\.json|coverage|doc|docs|docs\.mli|dragdrop\.min\.js|example|examples|example\.html|example\.js|externs|ipaddr\.min\.js|Makefile|min|minimist|perf|rusha|simplepeer\.min\.js|simplewebsocket\.min\.js|static\/screenshot\.png|test|tests|test\.js|tests\.js|webtorrent\.min\.js|\.[^\/]*|.*\.md|.*\.markdown)$/,

  // The application name.
  name: config.APP_NAME,

  // The base directory where the finished package(s) are created.
  out: path.join(config.ROOT_PATH, 'dist'),

  // Replace an already existing output directory.
  overwrite: true,

  // Runs `npm prune --production` which remove the packages specified in
  // "devDependencies" before starting to package the app.
  prune: true,

  // The Electron version with which the app is built (without the leading 'v')
  version: pkg.devDependencies['electron-prebuilt']
}

var darwin = {
  platform: 'darwin',

  // The bundle identifier to use in the application's plist (OS X only).
  'app-bundle-id': 'io.webtorrent.webtorrent',

  // The application category type, as shown in the Finder via "View" -> "Arrange by
  // Application Category" when viewing the Applications directory (OS X only).
  'app-category-type': 'public.app-category.utilities',

  // The bundle identifier to use in the application helper's plist (OS X only).
  'helper-bundle-id': 'io.webtorrent.webtorrent-helper',

  // Application icon.
  icon: config.APP_ICON + '.icns'
}

var win32 = {
  platform: 'win32',

  // Object hash of application metadata to embed into the executable (Windows only)
  'version-string': {

    // Company that produced the file.
    CompanyName: config.APP_NAME,

    // Copyright notices that apply to the file.
    LegalCopyright: config.APP_COPYRIGHT,

    // Name of the program, displayed to users
    FileDescription: config.APP_NAME,

    // Original name of the file, not including a path. This information enables an
    // application to determine whether a file has been renamed by a user. The format of
    // the name depends on the file system for which the file was created.
    OriginalFilename: 'WebTorrent.exe',

    // Name of the product with which the file is distributed.
    ProductName: config.APP_NAME,

    // Internal name of the file, if one exists, for example, a module name if the file
    // is a dynamic-link library. If the file has no internal name, this string should be
    // the original filename, without extension. This string is required.
    InternalName: config.APP_NAME
  },

  // Application icon.
  icon: config.APP_ICON + '.ico'
}

var linux = {
  platform: 'linux'

  // Note: Application icon for Linux is specified via the BrowserWindow `icon` option.
}

build()

function buildDarwin (cb) {
  var appDmg = require('appdmg')
  var plist = require('plist')
  var sign = require('electron-osx-sign')

  electronPackager(Object.assign({}, all, darwin), function (err, buildPath) {
    if (err) return cb(err)

    var appPath = path.join(buildPath[0], config.APP_NAME + '.app')
    var contentsPath = path.join(appPath, 'Contents')
    var resourcesPath = path.join(contentsPath, 'Resources')
    var infoPlistPath = path.join(contentsPath, 'Info.plist')
    var infoPlist = plist.parse(fs.readFileSync(infoPlistPath, 'utf8'))

    infoPlist.CFBundleDocumentTypes = [
      {
        CFBundleTypeExtensions: [ 'torrent' ],
        CFBundleTypeIconFile: path.basename(config.APP_FILE_ICON) + '.icns',
        CFBundleTypeName: 'BitTorrent Document',
        CFBundleTypeRole: 'Editor',
        LSHandlerRank: 'Owner',
        LSItemContentTypes: [ 'org.bittorrent.torrent' ]
      },
      {
        CFBundleTypeName: 'Any',
        CFBundleTypeOSTypes: [ '****' ],
        CFBundleTypeRole: 'Editor',
        LSHandlerRank: 'Owner',
        LSTypeIsPackage: false
      }
    ]

    infoPlist.CFBundleURLTypes = [
      {
        CFBundleTypeRole: 'Editor',
        CFBundleURLIconFile: path.basename(config.APP_FILE_ICON) + '.icns',
        CFBundleURLName: 'BitTorrent Magnet URL',
        CFBundleURLSchemes: [ 'magnet' ]
      }
    ]

    infoPlist.NSHumanReadableCopyright = config.APP_COPYRIGHT

    fs.writeFileSync(infoPlistPath, plist.build(infoPlist))

    // Copy torrent file icon into app bundle
    cp.execSync(`cp ${config.APP_FILE_ICON + '.icns'} ${resourcesPath}`)

    if (process.platform === 'darwin') {
      /*
       * Sign the app with Apple Developer ID certificate. We sign the app for 2 reasons:
       *   - So the auto-updater (Squirrrel.Mac) can check that app updates are signed by
       *     the same author as the current version.
       *   - So users will not a see a warning about the app coming from an "Unidentified
       *     Developer" when they open it for the first time (OS X Gatekeeper).
       *
       * To sign an OS X app for distribution outside the App Store, the following are
       * required:
       *   - Xcode
       *   - Xcode Command Line Tools (xcode-select --install)
       *   - Membership in the Apple Developer Program
       */
      var signOpts = {
        app: appPath,
        platform: 'darwin',
        verbose: true
      }

      sign(signOpts, function (err) {
        if (err) return cb(err)

        // Create .zip file (used by the auto-updater)
        var zipPath = path.join(buildPath[0], BUILD_NAME + '.zip')
        cp.execSync(`pushd ${buildPath[0]} && zip -r -y ${zipPath} ${config.APP_NAME + '.app'} && popd`)

        // Create a .dmg (OS X disk image) file, for easy user installation.
        var dmgOpts = {
          basepath: config.ROOT_PATH,
          target: path.join(buildPath[0], BUILD_NAME + '.dmg'),
          specification: {
            title: config.APP_NAME,
            icon: config.APP_ICON + '.icns',
            background: path.join(config.STATIC_PATH, 'appdmg.png'),
            'icon-size': 128,
            contents: [
              { x: 122, y: 240, type: 'file', path: appPath },
              { x: 380, y: 240, type: 'link', path: '/Applications' },
              // Hide hidden icons out of view, for users who have hidden files shown.
              // https://github.com/LinusU/node-appdmg/issues/45#issuecomment-153924954
              { x: 50, y: 500, type: 'position', path: '.background' },
              { x: 100, y: 500, type: 'position', path: '.DS_Store' },
              { x: 150, y: 500, type: 'position', path: '.Trashes' },
              { x: 200, y: 500, type: 'position', path: '.VolumeIcon.icns' }
            ]
          }
        }

        var dmg = appDmg(dmgOpts)
        dmg.on('error', cb)
        dmg.on('progress', function (info) {
          if (info.type === 'step-begin') console.log(info.title + '...')
        })
        dmg.on('finish', function (info) {
          cb(null, buildPath)
        })
      })
    }
  })
}

function buildWin32 (cb) {
  electronPackager(Object.assign({}, all, win32), cb)
}

function buildLinux (cb) {
  electronPackager(Object.assign({}, all, linux), cb)
}

function printDone (err, buildPath) {
  if (err) console.error(err.message || err)
  else console.log('Built ' + buildPath[0])
}
<commit_msg>Package: remove optionalDependency "appdmg" from final bundle<commit_after>#!/usr/bin/env node

/**
 * Builds app binaries for OS X, Linux, and Windows.
 */

var config = require('../config')
var cp = require('child_process')
var electronPackager = require('electron-packager')
var fs = require('fs')
var path = require('path')
var pkg = require('../package.json')

var BUILD_NAME = config.APP_NAME + '-v' + config.APP_VERSION

function build () {
  var platform = process.argv[2]
  if (platform === '--darwin') {
    buildDarwin(printDone)
  } else if (platform === '--win32') {
    buildWin32(printDone)
  } else if (platform === '--linux') {
    buildLinux(printDone)
  } else {
    buildDarwin(function (err, buildPath) {
      printDone(err, buildPath)
      buildWin32(function (err, buildPath) {
        printDone(err, buildPath)
        buildLinux(printDone)
      })
    })
  }
}

var all = {
  // Build 64 bit binaries only.
  arch: 'x64',

  // The application source directory.
  dir: config.ROOT_PATH,

  // The release version of the application. Maps to the `ProductVersion` metadata
  // property on Windows, and `CFBundleShortVersionString` on OS X.
  'app-version': pkg.version,

  // Package the application's source code into an archive, using Electron's archive
  // format. Mitigates issues around long path names on Windows and slightly speeds up
  // require().
  asar: true,

  // A glob expression, that unpacks the files with matching names to the
  // "app.asar.unpacked" directory.
  'asar-unpack': 'WebTorrent*',

  // The build version of the application. Maps to the FileVersion metadata property on
  // Windows, and CFBundleVersion on OS X. We're using the short git hash (e.g. 'e7d837e')
  // Windows requires the build version to start with a number :/ so we stick on a prefix
  'build-version': '0-' + cp.execSync('git rev-parse --short HEAD').toString().replace('\n', ''),

  // Pattern which specifies which files to ignore when copying files to create the
  // package(s).
  ignore: /^\/dist|\/(appveyor.yml|.appveyor.yml|appdmg|AUTHORS|CONTRIBUTORS|bench|benchmark|benchmark\.js|bin|bower\.json|component\.json|coverage|doc|docs|docs\.mli|dragdrop\.min\.js|example|examples|example\.html|example\.js|externs|ipaddr\.min\.js|Makefile|min|minimist|perf|rusha|simplepeer\.min\.js|simplewebsocket\.min\.js|static\/screenshot\.png|test|tests|test\.js|tests\.js|webtorrent\.min\.js|\.[^\/]*|.*\.md|.*\.markdown)$/,

  // The application name.
  name: config.APP_NAME,

  // The base directory where the finished package(s) are created.
  out: path.join(config.ROOT_PATH, 'dist'),

  // Replace an already existing output directory.
  overwrite: true,

  // Runs `npm prune --production` which remove the packages specified in
  // "devDependencies" before starting to package the app.
  prune: true,

  // The Electron version with which the app is built (without the leading 'v')
  version: pkg.devDependencies['electron-prebuilt']
}

var darwin = {
  platform: 'darwin',

  // The bundle identifier to use in the application's plist (OS X only).
  'app-bundle-id': 'io.webtorrent.webtorrent',

  // The application category type, as shown in the Finder via "View" -> "Arrange by
  // Application Category" when viewing the Applications directory (OS X only).
  'app-category-type': 'public.app-category.utilities',

  // The bundle identifier to use in the application helper's plist (OS X only).
  'helper-bundle-id': 'io.webtorrent.webtorrent-helper',

  // Application icon.
  icon: config.APP_ICON + '.icns'
}

var win32 = {
  platform: 'win32',

  // Object hash of application metadata to embed into the executable (Windows only)
  'version-string': {

    // Company that produced the file.
    CompanyName: config.APP_NAME,

    // Copyright notices that apply to the file.
    LegalCopyright: config.APP_COPYRIGHT,

    // Name of the program, displayed to users
    FileDescription: config.APP_NAME,

    // Original name of the file, not including a path. This information enables an
    // application to determine whether a file has been renamed by a user. The format of
    // the name depends on the file system for which the file was created.
    OriginalFilename: 'WebTorrent.exe',

    // Name of the product with which the file is distributed.
    ProductName: config.APP_NAME,

    // Internal name of the file, if one exists, for example, a module name if the file
    // is a dynamic-link library. If the file has no internal name, this string should be
    // the original filename, without extension. This string is required.
    InternalName: config.APP_NAME
  },

  // Application icon.
  icon: config.APP_ICON + '.ico'
}

var linux = {
  platform: 'linux'

  // Note: Application icon for Linux is specified via the BrowserWindow `icon` option.
}

build()

function buildDarwin (cb) {
  var appDmg = require('appdmg')
  var plist = require('plist')
  var sign = require('electron-osx-sign')

  electronPackager(Object.assign({}, all, darwin), function (err, buildPath) {
    if (err) return cb(err)

    var appPath = path.join(buildPath[0], config.APP_NAME + '.app')
    var contentsPath = path.join(appPath, 'Contents')
    var resourcesPath = path.join(contentsPath, 'Resources')
    var infoPlistPath = path.join(contentsPath, 'Info.plist')
    var infoPlist = plist.parse(fs.readFileSync(infoPlistPath, 'utf8'))

    infoPlist.CFBundleDocumentTypes = [
      {
        CFBundleTypeExtensions: [ 'torrent' ],
        CFBundleTypeIconFile: path.basename(config.APP_FILE_ICON) + '.icns',
        CFBundleTypeName: 'BitTorrent Document',
        CFBundleTypeRole: 'Editor',
        LSHandlerRank: 'Owner',
        LSItemContentTypes: [ 'org.bittorrent.torrent' ]
      },
      {
        CFBundleTypeName: 'Any',
        CFBundleTypeOSTypes: [ '****' ],
        CFBundleTypeRole: 'Editor',
        LSHandlerRank: 'Owner',
        LSTypeIsPackage: false
      }
    ]

    infoPlist.CFBundleURLTypes = [
      {
        CFBundleTypeRole: 'Editor',
        CFBundleURLIconFile: path.basename(config.APP_FILE_ICON) + '.icns',
        CFBundleURLName: 'BitTorrent Magnet URL',
        CFBundleURLSchemes: [ 'magnet' ]
      }
    ]

    infoPlist.NSHumanReadableCopyright = config.APP_COPYRIGHT

    fs.writeFileSync(infoPlistPath, plist.build(infoPlist))

    // Copy torrent file icon into app bundle
    cp.execSync(`cp ${config.APP_FILE_ICON + '.icns'} ${resourcesPath}`)

    if (process.platform === 'darwin') {
      /*
       * Sign the app with Apple Developer ID certificate. We sign the app for 2 reasons:
       *   - So the auto-updater (Squirrrel.Mac) can check that app updates are signed by
       *     the same author as the current version.
       *   - So users will not a see a warning about the app coming from an "Unidentified
       *     Developer" when they open it for the first time (OS X Gatekeeper).
       *
       * To sign an OS X app for distribution outside the App Store, the following are
       * required:
       *   - Xcode
       *   - Xcode Command Line Tools (xcode-select --install)
       *   - Membership in the Apple Developer Program
       */
      var signOpts = {
        app: appPath,
        platform: 'darwin',
        verbose: true
      }

      sign(signOpts, function (err) {
        if (err) return cb(err)

        // Create .zip file (used by the auto-updater)
        var zipPath = path.join(buildPath[0], BUILD_NAME + '.zip')
        cp.execSync(`pushd ${buildPath[0]} && zip -r -y ${zipPath} ${config.APP_NAME + '.app'} && popd`)

        // Create a .dmg (OS X disk image) file, for easy user installation.
        var dmgOpts = {
          basepath: config.ROOT_PATH,
          target: path.join(buildPath[0], BUILD_NAME + '.dmg'),
          specification: {
            title: config.APP_NAME,
            icon: config.APP_ICON + '.icns',
            background: path.join(config.STATIC_PATH, 'appdmg.png'),
            'icon-size': 128,
            contents: [
              { x: 122, y: 240, type: 'file', path: appPath },
              { x: 380, y: 240, type: 'link', path: '/Applications' },
              // Hide hidden icons out of view, for users who have hidden files shown.
              // https://github.com/LinusU/node-appdmg/issues/45#issuecomment-153924954
              { x: 50, y: 500, type: 'position', path: '.background' },
              { x: 100, y: 500, type: 'position', path: '.DS_Store' },
              { x: 150, y: 500, type: 'position', path: '.Trashes' },
              { x: 200, y: 500, type: 'position', path: '.VolumeIcon.icns' }
            ]
          }
        }

        var dmg = appDmg(dmgOpts)
        dmg.on('error', cb)
        dmg.on('progress', function (info) {
          if (info.type === 'step-begin') console.log(info.title + '...')
        })
        dmg.on('finish', function (info) {
          cb(null, buildPath)
        })
      })
    }
  })
}

function buildWin32 (cb) {
  electronPackager(Object.assign({}, all, win32), cb)
}

function buildLinux (cb) {
  electronPackager(Object.assign({}, all, linux), cb)
}

function printDone (err, buildPath) {
  if (err) console.error(err.message || err)
  else console.log('Built ' + buildPath[0])
}
<|endoftext|>


<commit_before>import { IconChevronDown } from 'dls-icons-vue'
import config from 'veui/managers/config'

config.defaults(
  {
    icons: {
      expand: IconChevronDown,
      collapse: IconChevronDown
    },
    ui: {
      size: {
        values: ['xs', 's', 'm', 'l'],
        inherit: true,
        default: 'm'
      },
      style: {
        values: ['primary', 'basic', 'normal'],
        default: 'basic',
        inherit: true
      },
      role: {
        values: ['text'],
        inherit: true
      }
    },
    parts: {
      search: 'inline'
    }
  },
  'dropdown'
)
<commit_msg>fix: support strong ui for dropdown (#851)<commit_after>import { IconChevronDown } from 'dls-icons-vue'
import config from 'veui/managers/config'

config.defaults(
  {
    icons: {
      expand: IconChevronDown,
      collapse: IconChevronDown
    },
    ui: {
      size: {
        values: ['xs', 's', 'm', 'l'],
        inherit: true,
        default: 'm'
      },
      style: {
        values: ['primary', 'basic', 'normal', 'strong'],
        default: 'basic',
        inherit: true
      },
      role: {
        values: ['text'],
        inherit: true
      }
    },
    parts: {
      search: 'inline'
    }
  },
  'dropdown'
)
<|endoftext|>


<commit_before>'use strict';
/**
 * スクリプトタスク
 * JSファイルをwebpackを使ってコンパイルして出力する
 */

let path = require('path');
let fs = require('fs');
let gulp = require('gulp');
let _ = require('lodash');
let through = require('through2');
let webpack = require('webpack');
let config = require('./config');
let $ = require('./plugins');
let conf;
const FILE_EXT = /\.(ts|js)$/;
/**
 * エントリーの登録
 */
gulp.task('_setEntries', () => {
    conf = require('../webpack.config.js');
    return gulp.src(config.path.js.src)
        .pipe(through.obj(function(file,charset,callback) {
            conf.entry = conf.entry || {};
            let fileName = path.basename(file.path).replace(FILE_EXT,'');
            conf.entry[fileName] = file.path;
            this.push(file);
            callback();
        }));
});

/**
 * webpackコンパイル開始
 * @param watch
 * @returns {*}
 */
function exeWebPack(watch,callback) {
    conf.watch = watch;
    conf.output.path = config.path.js.dest;
    webpack(conf, (err, stats) => {
        if(err) return console.error(err);
        let jsonStats = stats.toJson();
        if(jsonStats.errors.length > 0) {
            jsonStats.errors.forEach((value) => {
                console.error(value);
            });
            return;
        }
        if(jsonStats.warnings.length > 0) {
            jsonStats.warnings.forEach((value) => {
                console.log(value);
            });
        }
        $.browser.reload();
        if (callback) callback();
        callback = null;
    });
}

/**
 * スクリプトコンパイルタスク
 */
gulp.task('script',['_setEntries'], (callback) => {
    return exeWebPack(false,callback);
});

/**
 * スクリプト監視タスク
 */
gulp.task('watchScript',['_setEntries'], (callback) => {
    return exeWebPack(true,callback);
});<commit_msg>productionの際にinline mapが出力されないようにした。<commit_after>'use strict';
/**
 * スクリプトタスク
 * JSファイルをwebpackを使ってコンパイルして出力する
 */

let path = require('path');
let fs = require('fs');
let gulp = require('gulp');
let _ = require('lodash');
let through = require('through2');
let webpack = require('webpack');
let config = require('./config');
let $ = require('./plugins');
let conf;
const FILE_EXT = /\.(ts|js)$/;
/**
 * エントリーの登録
 */
gulp.task('_setEntries', () => {
    conf = require('../webpack.config.js');
    if (config.IS_PRODUCTION) {
        delete conf.devtool;
    }
    return gulp.src(config.path.js.src)
        .pipe(through.obj(function(file,charset,callback) {
            conf.entry = conf.entry || {};
            let fileName = path.basename(file.path).replace(FILE_EXT,'');
            conf.entry[fileName] = file.path;
            this.push(file);
            callback();
        }));
});

/**
 * webpackコンパイル開始
 * @param watch
 * @returns {*}
 */
function exeWebPack(watch,callback) {
    conf.watch = watch;
    conf.output.path = config.path.js.dest;
    webpack(conf, (err, stats) => {
        if(err) return console.error(err);
        let jsonStats = stats.toJson();
        if(jsonStats.errors.length > 0) {
            jsonStats.errors.forEach((value) => {
                console.error(value);
            });
            return;
        }
        if(jsonStats.warnings.length > 0) {
            jsonStats.warnings.forEach((value) => {
                console.log(value);
            });
        }
        $.browser.reload();
        if (callback) callback();
        callback = null;
    });
}

/**
 * スクリプトコンパイルタスク
 */
gulp.task('script',['_setEntries'], (callback) => {
    return exeWebPack(false,callback);
});

/**
 * スクリプト監視タスク
 */
gulp.task('watchScript',['_setEntries'], (callback) => {
    return exeWebPack(true,callback);
});
<|endoftext|>


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

    var getPropertyNS = require('./utils/getPropertyNS');

    return function ($input, options, lang, $field) {
        function setOptions(selectOptions) {
            $input.empty();
            if (list.includeEmpty === null || list.includeEmpty) {
                $input
                    .append($('<option>')
                        //.prop('disabled', true)
                        .val('')
                        .text(MetkaJS.L10N.get('general.selection.empty')));
            }
            $input.append(selectOptions.map(function (option) {
                return $('<option>')
                    .val(option.value)
                    .text(require('./selectInputOptionText')(option));
            }));
            require('./data')(options).onChange(function () {
                var value = require('./data')(options).getByLang(lang);
                if (typeof value !== 'undefined' && $input.children('option[value="' + value + '"]').length) {
                    $input.val(value);
                } else {
                    $input.children().first().prop('selected', true);
                }
                $input.change();
            });
        }

        var key = options.field.key;

        var list = require('./selectionList')(options, key);

        if (!list) {
            return;
        }

        if (list.type === 'REFERENCE') {
            var reference = getPropertyNS(options, 'dataConf.references', list.reference);
            var getOptions = require('./reference').options(key, options, lang, setOptions);
            if (reference && reference.type === 'DEPENDENCY') {
                options.$events.on('data-change-{key}-{lang}'.supplant({
                    key: reference.target,
                    lang: lang
                }), function (e) {
                    getOptions(options.data.fields, reference);
                });
            } else {
                getOptions();
            }
        } else {
            setOptions(list.options);
        }

        var $freeText = require('./inherit')(function (options) {
            return require('./inputField').call($('<div>'), options, 'STRING', lang);
        })(options)({
            horizontal: true,
            title: MetkaJS.L10N.get('fieldTitles.{field}.title'.supplant({
                field: list.freeTextKey
            })),
            field: {
                key: list.freeTextKey
            }
        });

        $field.append($freeText);
        function showFreeText() {
            $freeText.toggle(list.freeText.indexOf(require('./data')(options).getByLang(lang)) !== -1);
        }
        showFreeText();
        $input.change(showFreeText);
    }
});
<commit_msg>Fixed select inputs which don't have freeText option<commit_after>define(function (require) {
    'use strict';

    var getPropertyNS = require('./utils/getPropertyNS');

    return function ($input, options, lang, $field) {
        function setOptions(selectOptions) {
            $input.empty();
            if (list.includeEmpty === null || list.includeEmpty) {
                $input
                    .append($('<option>')
                        //.prop('disabled', true)
                        .val('')
                        .text(MetkaJS.L10N.get('general.selection.empty')));
            }
            $input.append(selectOptions.map(function (option) {
                return $('<option>')
                    .val(option.value)
                    .text(require('./selectInputOptionText')(option));
            }));
            require('./data')(options).onChange(function () {
                var value = require('./data')(options).getByLang(lang);
                if (typeof value !== 'undefined' && $input.children('option[value="' + value + '"]').length) {
                    $input.val(value);
                } else {
                    $input.children().first().prop('selected', true);
                }
                $input.change();
            });
        }

        var key = options.field.key;

        var list = require('./selectionList')(options, key);

        if (!list) {
            return;
        }

        if (list.type === 'REFERENCE') {
            var reference = getPropertyNS(options, 'dataConf.references', list.reference);
            var getOptions = require('./reference').options(key, options, lang, setOptions);
            if (reference && reference.type === 'DEPENDENCY') {
                options.$events.on('data-change-{key}-{lang}'.supplant({
                    key: reference.target,
                    lang: lang
                }), function (e) {
                    getOptions(options.data.fields, reference);
                });
            } else {
                getOptions();
            }
        } else {
            setOptions(list.options);
        }

        if (list.freeTextKey) {
            var $freeText = require('./inherit')(function (options) {
                return require('./inputField').call($('<div>'), options, 'STRING', lang);
            })(options)({
                horizontal: true,
                title: MetkaJS.L10N.get('fieldTitles.{field}.title'.supplant({
                    field: list.freeTextKey
                })),
                field: {
                    key: list.freeTextKey
                }
            });

            $field.append($freeText);
            var showFreeText = function () {
                $freeText.toggle(list.freeText.indexOf(require('./data')(options).getByLang(lang)) !== -1);
            };
            showFreeText();
            $input.change(showFreeText);
        }
    }
});
<|endoftext|>


<commit_before>// React
import React, {PropTypes} from "react";
import {StyleGuidePage} from "orion/guide/layout";
import {Button, Section, SubSection, Spacer, Icon, Notice, VMenuLink} from 'orion/ui/helpers';

export class HelpersPage extends StyleGuidePage {
    sidebar() {
        return (

                <VMenuLink index={true}>← Home</VMenuLink>
                <VMenuLink hash="#helpers">Helper Classes</VMenuLink>

        )
    }

    main() {
        return (

                .l-float-left
                .l-float-right
                .l-clear

                .l-inline

                .l-hidden
                .l-no-margin
                .l-no-padding

                .l-center-txt
                --- only center text
                .l-hidden

                .l-align--abscenter
                --- centers element exactly in the middle of the page both horizontally/vertically
                .l-align--horizontal
                --- centers div only horizontally

        )
    }

}
<commit_msg>Helper Text<commit_after>// React
import React, {PropTypes} from "react";
import {StyleGuidePage} from "orion/guide/layout";
import {Button, Section, SubSection, Spacer, Icon, Notice, VMenuLink} from 'orion/ui/helpers';

export class HelpersPage extends StyleGuidePage {
    sidebar() {
        return (

                <VMenuLink index={true}>← Home</VMenuLink>
                <VMenuLink hash="#helpers">Helper Classes</VMenuLink>

        )
    }

    main() {
        return (

 This is a quick guide for class names used on the style guide. These helpers will eventually be replaced by actual code snippets.

                .l-float-left
                .l-float-right
                .l-clear

                .l-inline

                .l-hidden
                .l-no-margin
                .l-no-padding

                .l-center-txt
                --- only center text
                .l-hidden

                .l-align--abscenter
                --- centers element exactly in the middle of the page both horizontally/vertically
                .l-align--horizontal
                --- centers div only horizontally

        )
    }

}
<|endoftext|>


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

	mare.views.Gallery = Backbone.View.extend({
		// This view controls everything inside the element with class 'gallery'
		el: '.gallery',

		events: {
			'click .media-box'							: 'displayChildDetails',
			'click .bookmark'							: 'toggleBookmark',
			'click .waiting-child-profiles-sort-option'	: 'sortCollection'
		},

		initialize: function() {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// Create a hook to access the gallery template
			var galleryHtml = $('#gallery-template').html();
			// Compile the template to be used during rendering/repainting the gallery
			this.template = Handlebars.compile(galleryHtml);
			// Initialize a subview for the details modal
			mare.views.childDetails = mare.views.childDetails || new mare.views.ChildDetails();
			// Initialize the gallery once we've fetched the child data needed to display the gallery (this doesn't include child details data)
			mare.promises.childrenDataLoaded.done(function() {
				view.collection = mare.collections.children;
			});
		},

		render: function render() {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// The gallery can't render until we have the user permissions and the child data is loaded
			// use the promise bound to both data to delay rendering until we have them
			$.when(mare.promises.permissionsLoaded, mare.promises.childrenDataLoaded).then(function() {
				// Pass the collection data through the gallery template to generate the HTML to be added to the gallery
				var html = view.template(view.collection.toJSON());
				view.$('.profiles-container').html(html);
				// Once the html is rendered to the page, initialize the gallery display plugin
				view.initializeMediaBoxes();
			});
		},

		initializeMediaBoxes: function initializeMediaBoxes() {
			// initialize the photo listing gallery grid
			$('#grid').mediaBoxes({
				boxesToLoadStart: 12,
				boxesToLoad 	: 8,
				sortContainer 	: '#waiting-child-profiles-sort',
				sort: 'a',
				getSortData: {
					name		: '.media-box-name', 		// look in the elements with the class "media-box-name" and sort by the innerHTML value
					age			: '.media-box-age', 		// look in the elements with the class "media-box-age" and sort by the innerHTML value
					dateAdded	: '.media-box-date-added' 	// look in the elements with the class "media-box-date-added" and sort by the innerHTML value
				}
			});
		},

		/* When a child card is clicked, pass the request to the subview in charge of the details modal */
		displayChildDetails: function displayChildDetails(event) {
			mare.views.childDetails.handleGalleryClick(event);
		},

		/* Determine how to handle a click on the bookmark button based on the current state of the bookmark */
		toggleBookmark: function toggleBookmark(e) {
			e.stopPropagation();
			// DOM cache the current target for performance
			var $currentTarget = $(e.currentTarget);
			// Get the child's registration number to match them in the database
			var registrationNumber = $currentTarget.closest('.media-box').data('registration-number');

			// if we are currently saving the users attempt to toggle the bookmark and the server hasn't processed the change yet, ignore the click event
			if( $currentTarget.hasClass('bookmark--disabled') ) {

				return;

			// if the child is currently bookmarked, remove them
			} else if( $currentTarget.hasClass('bookmark--active') ) {

				$currentTarget.addClass('bookmark--disabled');
				this.removeBookmark(registrationNumber, $currentTarget);

			// if the child is not currently bookmarked, add them
			} else {

				$currentTarget.addClass('bookmark--disabled');
				this.addBookmark(registrationNumber, $currentTarget);

			}
		},

		addBookmark: function addBookmark(registrationNumber, $currentTarget) {

			$.ajax({
				url: '/services/add-bookmark',
				type: 'POST',
				data: {
					registrationNumber: registrationNumber
				}
			}).done(function(response) {
				// Once the bookmark has been saved successfully, change the icon, re-enable the bookmark, and show it as active
				$currentTarget.children('.bookmark__icon').removeClass('fa-plus-square-o').addClass('fa-minus-square-o');
				$currentTarget.removeClass('bookmark--disabled');
				$currentTarget.addClass('bookmark--active');

			}).fail(function(err) {
				// TODO: Show an error message to the user
				console.log(err);
			});

		},

		removeBookmark: function removeBookmark(registrationNumber, $currentTarget) {

			$.ajax({
				url: '/services/remove-bookmark',
				type: 'POST',
				data: {
					registrationNumber: registrationNumber
				}
			}).done(function(response) {
				// Once the bookmark has been removed successfully, change the icon, re-enable the bookmark, and show it as inactive
				$currentTarget.children('.bookmark__icon').removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
				$currentTarget.removeClass('bookmark--disabled');
				$currentTarget.removeClass('bookmark--active');

			}).fail(function(err) {
				// TODO: Show an error message to the user
				console.log(err);
			});

		},

		sortGallery: function sortGallery(event) {
			var $currentTarget = $(event.currentTarget);
			var sortBy = $currentTarget.data('sort-by');

			this.collection.reorder(sortBy);
		}

	});
})();<commit_msg>gallery page - update click handler function name<commit_after>(function () {
	'use strict';

	mare.views.Gallery = Backbone.View.extend({
		// This view controls everything inside the element with class 'gallery'
		el: '.gallery',

		events: {
			'click .media-box'							: 'displayChildDetails',
			'click .bookmark'							: 'toggleBookmark',
			'click .waiting-child-profiles-sort-option'	: 'sortGallery'
		},

		initialize: function() {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// Create a hook to access the gallery template
			var galleryHtml = $('#gallery-template').html();
			// Compile the template to be used during rendering/repainting the gallery
			this.template = Handlebars.compile(galleryHtml);
			// Initialize a subview for the details modal
			mare.views.childDetails = mare.views.childDetails || new mare.views.ChildDetails();
			// Initialize the gallery once we've fetched the child data needed to display the gallery (this doesn't include child details data)
			mare.promises.childrenDataLoaded.done(function() {
				view.collection = mare.collections.children;
			});
		},

		render: function render() {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// The gallery can't render until we have the user permissions and the child data is loaded
			// use the promise bound to both data to delay rendering until we have them
			$.when(mare.promises.permissionsLoaded, mare.promises.childrenDataLoaded).then(function() {
				// Pass the collection data through the gallery template to generate the HTML to be added to the gallery
				var html = view.template(view.collection.toJSON());
				view.$('.profiles-container').html(html);
				// Once the html is rendered to the page, initialize the gallery display plugin
				view.initializeMediaBoxes();
			});
		},

		initializeMediaBoxes: function initializeMediaBoxes() {
			// initialize the photo listing gallery grid
			$('#grid').mediaBoxes({
				boxesToLoadStart: 12,
				boxesToLoad 	: 8,
				sortContainer 	: '#waiting-child-profiles-sort',
				sort: 'a',
				getSortData: {
					name		: '.media-box-name', 		// look in the elements with the class "media-box-name" and sort by the innerHTML value
					age			: '.media-box-age', 		// look in the elements with the class "media-box-age" and sort by the innerHTML value
					dateAdded	: '.media-box-date-added' 	// look in the elements with the class "media-box-date-added" and sort by the innerHTML value
				}
			});
		},

		/* When a child card is clicked, pass the request to the subview in charge of the details modal */
		displayChildDetails: function displayChildDetails(event) {
			mare.views.childDetails.handleGalleryClick(event);
		},

		/* Determine how to handle a click on the bookmark button based on the current state of the bookmark */
		toggleBookmark: function toggleBookmark(e) {
			e.stopPropagation();
			// DOM cache the current target for performance
			var $currentTarget = $(e.currentTarget);
			// Get the child's registration number to match them in the database
			var registrationNumber = $currentTarget.closest('.media-box').data('registration-number');

			// if we are currently saving the users attempt to toggle the bookmark and the server hasn't processed the change yet, ignore the click event
			if( $currentTarget.hasClass('bookmark--disabled') ) {

				return;

			// if the child is currently bookmarked, remove them
			} else if( $currentTarget.hasClass('bookmark--active') ) {

				$currentTarget.addClass('bookmark--disabled');
				this.removeBookmark(registrationNumber, $currentTarget);

			// if the child is not currently bookmarked, add them
			} else {

				$currentTarget.addClass('bookmark--disabled');
				this.addBookmark(registrationNumber, $currentTarget);

			}
		},

		addBookmark: function addBookmark(registrationNumber, $currentTarget) {

			$.ajax({
				url: '/services/add-bookmark',
				type: 'POST',
				data: {
					registrationNumber: registrationNumber
				}
			}).done(function(response) {
				// Once the bookmark has been saved successfully, change the icon, re-enable the bookmark, and show it as active
				$currentTarget.children('.bookmark__icon').removeClass('fa-plus-square-o').addClass('fa-minus-square-o');
				$currentTarget.removeClass('bookmark--disabled');
				$currentTarget.addClass('bookmark--active');

			}).fail(function(err) {
				// TODO: Show an error message to the user
				console.log(err);
			});

		},

		removeBookmark: function removeBookmark(registrationNumber, $currentTarget) {

			$.ajax({
				url: '/services/remove-bookmark',
				type: 'POST',
				data: {
					registrationNumber: registrationNumber
				}
			}).done(function(response) {
				// Once the bookmark has been removed successfully, change the icon, re-enable the bookmark, and show it as inactive
				$currentTarget.children('.bookmark__icon').removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
				$currentTarget.removeClass('bookmark--disabled');
				$currentTarget.removeClass('bookmark--active');

			}).fail(function(err) {
				// TODO: Show an error message to the user
				console.log(err);
			});

		},

		sortGallery: function sortGallery(event) {
			var $currentTarget = $(event.currentTarget);
			var sortBy = $currentTarget.data('sort-by');

			this.collection.reorder(sortBy);
		}

	});
})();<|endoftext|>


<commit_before>'use strict';

var config = require('../config'),
    pkg = require('../../package.json'),
    bs = require('bootstrap-sass/package.json'),
    jq = require('jquery/package.json'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    fs = require('fs'),
    path = require('path'),
    dir = require('node-dir'),
    del = require('del'),
    nunjucksRender = require('gulp-nunjucks-render'),
    data = require('gulp-data'),
    watch = require('gulp-watch'),
    notify = require('gulp-notify'),

    dataPaths = {
        css: config.tplCssPath,
        js: config.tplJsPath,
        jsFilename: config.jsFilename
    },
    dataProject = {
        name: config.name,
        version: pkg.version,
        bsversion: bs.version,
        jqversion: jq.version
    },

    srcSgElements = [config.srcPath + '/elements/**/*.{html,json}'],
    srcSgComponents = [config.srcPath + '/components/**/*.{html,json}'],
    srcSgPages = [config.srcPath + '/styleguide/pages/**/*.{html,json}'],
    srcSgIndex = [config.srcPath + '/styleguide/index.html'],
    dest = config.destPath + '/styleguide';

module.exports = function() {

    /**
     * recursively return html files in (sub)dirs
     * @param {string} dirName Directory to walk through.
     * @param {string} ext File extension.
     * @param {function} cb Callback function.
     */
    function getFiles(root, dirName, ext, cb) {
        var retArray = [],
            regex = new RegExp(ext + '$', 'i'),
            fullPath = root + dirName;

        if (fs.existsSync(fullPath)) {
            dir.readFiles(fullPath, {
                match: regex,
                sync: true
            }, function(err, content, next) {
                if (err) { gutil.log(err); }
                next();
            }, function(err, files) {
                if (err) { gutil.log(err); }
                files.forEach(function(file, i) {
                    var cleanPath = file.replace(root, '').substring(1),
                        filePath = path.dirname(cleanPath),
                        type = filePath.split('\\').slice(-1)[0],
                        name = path.basename(file, ext).replace('.min', '');

                    retArray.push({
                        path: cleanPath,
                        type: type,
                        name: name
                    });
                });

                if (typeof cb === 'function') {
                    cb(retArray);
                }
            });
        } else {
            if (typeof cb === 'function') {
                cb(retArray);
            }
        }
    }

    /**
     * returns data object with file info for elements/components
     * @param {object} file File to process
     * @param {function} cb Callback function.
     * @private
     */
    function getDataForFile(file) {
        var type = path.relative('.', file.relative).split('\\')[0],
            name = path.basename(file.relative, '.html');
        return {
            meta: { title: config.name + " - " + type + " - " + name },
            paths: dataPaths,
            name: name,
            type: type,
            extends: true
        };
    }

    /**
     * returns data object with info for pages
     * @param {object} file File to process
     * @param {function} cb Callback function.
     * @private
     */
    function getDataForPage(file) {
        var name = path.basename(file.relative, '.html');
        return {
            meta: { title: config.name + " - " + name },
            paths: dataPaths
        };
    }

    /**
     * Gets data to build styleguide index.
     * @param {function} cb Callback function.
     */
    function getDataForIndex(cb) {

        var elements = [],
            components = [],
            pages = [],
            stylesheets = [];

        getFiles(config.srcPath, '/elements', '.html', function(res) {
            elements = res;
            getFiles(config.srcPath, '/components', '.html', function(res) {
                components = res;
                getFiles(config.srcPath, '/styleguide/pages', '.html', function(res) {
                    pages = res;
                    getFiles(config.destPath, '/css', '.css', function(res) {
                        stylesheets = res;
                        var ret = {
                            meta: { title: config.name },
                            paths: dataPaths,
                            project: dataProject,
                            elements: elements,
                            components: components,
                            pages: pages,
                            stylesheets: stylesheets
                        };
                        cb(ret);
                    });
                });
            });
        });
    }

    /**
     * builds styleguide elements
     */
    gulp.add('styleguide:elements', function(done) {
        getFiles(config.destPath, '/css', '.css', function(res) {
            del.sync([dest + '/elements']);
            gulp.src(srcSgElements)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(function(file) {
                    var ret = getDataForFile(file);
                    ret.stylesheets = res;
                    return ret;
                }))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest + '/elements'));
            done();
        });
    });

    /**
     * builds styleguide components
     */
    gulp.add('styleguide:components', function(done) {
        getFiles(config.destPath, '/css', '.css', function(res) {
            del.sync([dest + '/components']);
            gulp.src(srcSgComponents)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(function(file) {
                    var ret = getDataForFile(file);
                    ret.stylesheets = res;
                    return ret;
                }))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest + '/components'));
            done();
        });
    });

    /**
     * builds styleguide pages
     */
    gulp.add('styleguide:pages', function(done) {
        getFiles(config.destPath, '/css', '.css', function(res) {
            del.sync([dest + '/pages']);
            gulp.src(srcSgPages)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(function(file) {
                    var ret = getDataForPage(file);
                    ret.stylesheets = res;
                    return ret;
                }))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest + '/pages'));
            done();
        });
    });

    /**
     * builds styleguide index
     */
    gulp.add('styleguide:index', function(done) {
        getDataForIndex(function(indexData) {
            gulp.src(srcSgIndex)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(indexData))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest));
            done();
        });
    });

    /**
     * builds all styleguide subtasks
     */
    gulp.add('styleguide:build', [
        'styleguide:clean',
        'styleguide:elements',
        'styleguide:components',
        'styleguide:pages',
        'styleguide:index'
    ]);

    /**
     * cleanup styleguide build
     */
    gulp.add('styleguide:clean', function(done) {
        // cleanup
        del.sync([dest]);
        done();
    });

    /**
     * watch all styleguide changes
     */
    gulp.add('styleguide:watch', function(done) {
        // watch styleguide index changes
        watch(srcSgIndex, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:index', 'server:reload']);
        });

        // watch styleguide element chages
        watch(srcSgElements, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:build', 'server:reload']);
        });

        // watch styleguide component changes
        watch(srcSgComponents, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:build', 'server:reload']);
        });

        // watch styleguide pages changes
        watch(srcSgPages, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:build', 'server:reload']);
        });
    });
};
<commit_msg>Added json mockup support<commit_after>'use strict';

var config = require('../config'),
    pkg = require('../../package.json'),
    bs = require('bootstrap-sass/package.json'),
    jq = require('jquery/package.json'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    fs = require('fs'),
    path = require('path'),
    dir = require('node-dir'),
    del = require('del'),
    nunjucksRender = require('gulp-nunjucks-render'),
    data = require('gulp-data'),
    watch = require('gulp-watch'),
    notify = require('gulp-notify'),

    dataPaths = {
        css: config.tplCssPath,
        js: config.tplJsPath,
        jsFilename: config.jsFilename
    },
    dataProject = {
        name: config.name,
        version: pkg.version,
        bsversion: bs.version,
        jqversion: jq.version
    },

    srcSgElements = [config.srcPath + '/elements/**/*.html'],
    srcSgComponents = [config.srcPath + '/components/**/*.html'],
    srcSgPages = [config.srcPath + '/styleguide/pages/**/*.html'],
    srcSgIndex = [config.srcPath + '/styleguide/index.html'],
    dest = config.destPath + '/styleguide';

module.exports = function() {

    /**
     * recursively return html files in (sub)dirs
     * @param {string} dirName Directory to walk through.
     * @param {string} ext File extension.
     * @param {function} cb Callback function.
     */
    function getFiles(root, dirName, ext, cb) {
        var retArray = [],
            regex = new RegExp(ext + '$', 'i'),
            fullPath = root + dirName;

        if (fs.existsSync(fullPath)) {
            dir.readFiles(fullPath, {
                match: regex,
                sync: true
            }, function(err, content, next) {
                if (err) { gutil.log(err); }
                next();
            }, function(err, files) {
                if (err) { gutil.log(err); }
                files.forEach(function(file, i) {
                    var cleanPath = file.replace(root, '').substring(1),
                        filePath = path.dirname(cleanPath),
                        type = filePath.split('\\').slice(-1)[0],
                        name = path.basename(file, ext).replace('.min', '');

                    retArray.push({
                        path: cleanPath,
                        type: type,
                        name: name
                    });
                });

                if (typeof cb === 'function') {
                    cb(retArray);
                }
            });
        } else {
            if (typeof cb === 'function') {
                cb(retArray);
            }
        }
    }

    /**
     * returns data object with file info for elements/components
     * @param {object} file File to process
     * @param {function} cb Callback function.
     * @private
     */
    function getDataForFile(file) {
        var type = path.relative('.', file.relative).split('\\')[0],
            name = path.basename(file.relative, '.html');
        return {
            meta: { title: config.name + " - " + type + " - " + name },
            paths: dataPaths,
            name: name,
            type: type,
            extends: true
        };
    }

    /**
     * returns data object with info for pages
     * @param {object} file File to process
     * @param {function} cb Callback function.
     * @private
     */
    function getDataForPage(file) {
        var name = path.basename(file.relative, '.html');
        return {
            meta: { title: config.name + " - " + name },
            paths: dataPaths
        };
    }

    /**
     * Gets data to build styleguide index.
     * @param {function} cb Callback function.
     */
    function getDataForIndex(cb) {

        var elements = [],
            components = [],
            pages = [],
            stylesheets = [];

        getFiles(config.srcPath, '/elements', '.html', function(res) {
            elements = res;
            getFiles(config.srcPath, '/components', '.html', function(res) {
                components = res;
                getFiles(config.srcPath, '/styleguide/pages', '.html', function(res) {
                    pages = res;
                    getFiles(config.destPath, '/css', '.css', function(res) {
                        stylesheets = res;
                        var ret = {
                            meta: { title: config.name },
                            paths: dataPaths,
                            project: dataProject,
                            elements: elements,
                            components: components,
                            pages: pages,
                            stylesheets: stylesheets
                        };
                        cb(ret);
                    });
                });
            });
        });
    }

    /**
     * builds styleguide elements
     */
    gulp.add('styleguide:elements', function(done) {
        getFiles(config.destPath, '/css', '.css', function(res) {

            del.sync([dest + '/elements']);

            gulp.src(config.srcPath + '/elements/**/*.json')
                .pipe(gulp.dest(dest + '/elements'));

            gulp.src(srcSgElements)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(function(file) {
                    var ret = getDataForFile(file);
                    ret.stylesheets = res;
                    return ret;
                }))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest + '/elements'));
            done();
        });
    });

    /**
     * builds styleguide components
     */
    gulp.add('styleguide:components', function(done) {
        getFiles(config.destPath, '/css', '.css', function(res) {

            del.sync([dest + '/components']);

            gulp.src(config.srcPath + '/components/**/*.json')
                .pipe(gulp.dest(dest + '/components'));

            gulp.src(srcSgComponents)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(function(file) {
                    var ret = getDataForFile(file);
                    ret.stylesheets = res;
                    return ret;
                }))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest + '/components'));
            done();
        });
    });

    /**
     * builds styleguide pages
     */
    gulp.add('styleguide:pages', function(done) {
        getFiles(config.destPath, '/css', '.css', function(res) {

            del.sync([dest + '/pages']);

            gulp.src(config.srcPath + '/pages/**/*.json')
                .pipe(gulp.dest(dest + '/pages'));

            gulp.src(srcSgPages)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(function(file) {
                    var ret = getDataForPage(file);
                    ret.stylesheets = res;
                    return ret;
                }))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest + '/pages'));
            done();
        });
    });

    /**
     * builds styleguide index
     */
    gulp.add('styleguide:index', function(done) {
        getDataForIndex(function(indexData) {
            gulp.src(srcSgIndex)
                .pipe(plumber(function(error) {
                    gutil.log(error.message);
                    notify().write(error.message);
                    this.emit('end');
                }))
                .pipe(data(indexData))
                .pipe(nunjucksRender({ path: [config.srcPath] }))
                .pipe(gulp.dest(dest));
            done();
        });
    });

    /**
     * builds all styleguide subtasks
     */
    gulp.add('styleguide:build', [
        'styleguide:clean',
        'styleguide:elements',
        'styleguide:components',
        'styleguide:pages',
        'styleguide:index'
    ]);

    /**
     * cleanup styleguide build
     */
    gulp.add('styleguide:clean', function(done) {
        // cleanup
        del.sync([dest]);
        done();
    });

    /**
     * watch all styleguide changes
     */
    gulp.add('styleguide:watch', function(done) {

        // watch styleguide index changes
        watch(srcSgIndex, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:index', 'server:reload']);
        });

        // watch styleguide element chages
        watch(config.srcPath + '/**/*.json', {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:build', 'server:reload']);
        });

        // watch styleguide element chages
        watch(srcSgElements, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:build', 'server:reload']);
        });

        // watch styleguide component changes
        watch(srcSgComponents, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:build', 'server:reload']);
        });

        // watch styleguide pages changes
        watch(srcSgPages, {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styleguide:build', 'server:reload']);
        });
    });
};
<|endoftext|>


<commit_before>'use strict'

var createContext = require('./util/create-context')
var createREGL = require('../../regl')
var tape = require('tape')

tape('test regl.stats', function (t) {
  setTimeout(function () {
    var gl = createContext(16, 16)
    var regl
    var stats

    //
    // Begin Test stats.bufferCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.bufferCount, 0, 'stats.bufferCount==0 at start')

    regl.buffer([1, 2, 3])
    regl.buffer(new Uint16Array([1, 2, 3]))
    regl.buffer(new Float32Array([1, 2, 3, 4]))

    t.equals(stats.bufferCount, 3, 'stats.bufferCount==3 after creating 3 buffers')

    regl.destroy()

    t.equals(stats.bufferCount, 0, 'stats.bufferCount==0 after regl.destroy()')
    //
    // End Test stats.bufferCount
    //

    //
    // Begin Test stats.elementsCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.elementsCount, 0, 'stats.elementsCount==0 at start')

    regl.elements([1, 2, 3])
    regl.elements([[1, 2, 3], [5, 6, 7]])
    regl.elements({
      primitive: 'line loop',
      count: 5,
      data: new Uint8Array([0, 2, 4, 1, 3])
    })

    t.equals(stats.bufferCount, 3, 'stats.elementsCount==3 after creating 3 buffers')

    regl.destroy()

    t.equals(stats.elementsCount, 0, 'stats.elementsCount==0 after regl.destroy()')
    //
    // End Test stats.elementsCount
    //

    //
    // Begin Test stats.framebufferCount
    //

    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.framebufferCount, 0, 'stats.framebufferCount==0 at start')

    regl.framebuffer({radius: 5})
    regl.framebuffer({width: 2, height: 4, depth: false, stencil: false})

    t.equals(stats.framebufferCount, 2, 'stats.framebufferCount==2 after creating 2 buffers')

    regl.destroy()
    t.equals(stats.framebufferCount, 0, 'stats.framebufferCount==0 after regl.destroy()')
    //
    // End Test stats.framebufferCount
    //

    //
    // Begin Test stats.shaderCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.shaderCount, 0, 'stats.shaderCount==0 at start')

    var draw1 = regl({
      frag: `
      precision mediump float;
      void main () { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }`,
      vert: `
      precision mediump float;
      attribute vec2 position;
      void main () {gl_Position = vec4(position, 0, 1); }`,
      attributes: { position: [[-1, 0], [0, -1], [1, 1]] },
      uniforms: { color: [1, 0, 0, 1] },
      count: 3
    })

    var draw2 = regl({
      frag: `
      precision mediump float;
      void main () { gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }`,
      vert: `
      precision mediump float;
      attribute vec2 position;
      void main () {gl_Position = vec4(position, 0, 1); }`,
      attributes: { position: [[-1, 0], [0, -1], [1, 1]] },
      uniforms: { color: [1, 0, 0, 1] },
      count: 3
    })

    // no matter how many times we draw it, we should only have two shaders.
    draw1()
    draw1()

    draw2()
    draw2()

    t.equals(stats.shaderCount, 2, 'stats.shaderCount==2 after creating 2 calls')

    regl.destroy()
    t.equals(stats.shaderCount, 0, 'stats.shaderCount==0 after regl.destroy()')
    //
    // End Test stats.shaderCount
    //

    //
    // Begin Test stats.textureCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.textureCount, 0, 'stats.textureCount==0 at start')

    regl.texture({shape: [16, 16]})
    regl.texture({
      width: 2,
      height: 2,
      data: [
        255, 255, 255, 255, 0, 0, 0, 0,
        255, 0, 255, 255, 0, 0, 255, 255
      ]
    })
    regl.texture([[[0, 255, 0], [255, 0, 0]], [[0, 0, 255], [255, 255, 255]]])
    t.equals(stats.textureCount, 3, 'stats.textureCount==3 after creating 3 textures')

    regl.destroy()
    t.equals(stats.textureCount, 0, 'stats.textureCount==0 after regl.destroy()')
    //
    // End Test stats.textureCount
    //

    //
    // Begin Test stats.cubeCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.cubeCount, 0, 'stats.cubeCount==0 at start')

    regl.cube(16)
    regl.cube(
      [[[255, 0, 0, 255]]],
      [[[0, 255, 0, 255]]],
      [[[0, 0, 255, 255]]],
      [[[0, 0, 0, 255]]],
      [[[255, 255, 0, 255]]],
      [[[0, 255, 255, 255]]])
    regl.cube({
      faces: [
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]],
        [[[0, 0, 255, 255]]],
        [[[0, 0, 0, 255]]],
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]]
      ]
    })

    t.equals(stats.cubeCount, 3, 'stats.cubeCount==3 after creating 3 cubes')

    regl.destroy()
    t.equals(stats.cubeCount, 0, 'stats.cubeCount==0 after regl.destroy()')
    //
    // End Test stats.cubeCount
    //

    //
    // Begin Test stats.renderbufferCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.renderbufferCount, 0, 'stats.renderbufferCount==0 at start')

    regl.renderbuffer()
    regl.renderbuffer({width: 16, height: 16, format: 'rgba4'})
    regl.renderbuffer({width: 2, height: 2, format: 'depth'})
    t.equals(stats.renderbufferCount, 3, 'stats.renderbufferCount==3 after creating 3 renderbuffers')

    regl.destroy()
    t.equals(stats.renderbufferCount, 0, 'stats.renderbufferCount==0 after regl.destroy()')
    //
    // End Test stats.renderbufferCount
    //

    createContext.destroy(gl)
    t.end()
  }, 120)
})
<commit_msg>now it should pass circleci.<commit_after>'use strict'

var createContext = require('./util/create-context')
var createREGL = require('../../regl')
var tape = require('tape')

tape('test regl.stats', function (t) {
  setTimeout(function () {
    var gl = createContext(16, 16)
    var regl
    var stats

    //
    // Begin Test stats.bufferCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.bufferCount, 0, 'stats.bufferCount==0 at start')

    regl.buffer([1, 2, 3])
    regl.buffer(new Uint16Array([1, 2, 3]))
    regl.buffer(new Float32Array([1, 2, 3, 4]))

    t.equals(stats.bufferCount, 3, 'stats.bufferCount==3 after creating 3 buffers')

    regl.destroy()

    t.equals(stats.bufferCount, 0, 'stats.bufferCount==0 after regl.destroy()')
    //
    // End Test stats.bufferCount
    //

    //
    // Begin Test stats.elementsCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.elementsCount, 0, 'stats.elementsCount==0 at start')

    regl.elements([1, 2, 3])
    regl.elements([[1, 2, 3], [5, 6, 7]])
    regl.elements({
      primitive: 'line loop',
      count: 5,
      data: new Uint8Array([0, 2, 4, 1, 3])
    })

    t.equals(stats.bufferCount, 3, 'stats.elementsCount==3 after creating 3 buffers')

    regl.destroy()

    t.equals(stats.elementsCount, 0, 'stats.elementsCount==0 after regl.destroy()')
    //
    // End Test stats.elementsCount
    //

    //
    // Begin Test stats.framebufferCount
    //

    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.framebufferCount, 0, 'stats.framebufferCount==0 at start')

    regl.framebuffer({radius: 5})
    regl.framebuffer({width: 2, height: 4, depth: false, stencil: false})

    t.equals(stats.framebufferCount, 2, 'stats.framebufferCount==2 after creating 2 buffers')

    regl.destroy()
    t.equals(stats.framebufferCount, 0, 'stats.framebufferCount==0 after regl.destroy()')
    //
    // End Test stats.framebufferCount
    //

    //
    // Begin Test stats.shaderCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.shaderCount, 0, 'stats.shaderCount==0 at start')

    var draw1 = regl({
      frag: [
        'precision mediump float;',
        'void main () { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } '
      ].join('\n'),
      vert: [
        'precision mediump float;',
        'attribute vec2 position;',
        'void main () {gl_Position = vec4(position, 0, 1); }'
      ].join('\n'),
      attributes: { position: [[-1, 0], [0, -1], [1, 1]] },
      uniforms: { color: [1, 0, 0, 1] },
      count: 3
    })

    var draw2 = regl({
      frag: `
      precision mediump float;
      void main () { gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }`,
      vert: `
      precision mediump float;
      attribute vec2 position;
      void main () {gl_Position = vec4(position, 0, 1); }`,
      attributes: { position: [[-1, 0], [0, -1], [1, 1]] },
      uniforms: { color: [1, 0, 0, 1] },
      count: 3
    })

    // no matter how many times we draw it, we should only have two shaders.
    draw1()
    draw1()

    draw2()
    draw2()

    t.equals(stats.shaderCount, 2, 'stats.shaderCount==2 after creating 2 calls')

    regl.destroy()
    t.equals(stats.shaderCount, 0, 'stats.shaderCount==0 after regl.destroy()')
    //
    // End Test stats.shaderCount
    //

    //
    // Begin Test stats.textureCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.textureCount, 0, 'stats.textureCount==0 at start')

    regl.texture({shape: [16, 16]})
    regl.texture({
      width: 2,
      height: 2,
      data: [
        255, 255, 255, 255, 0, 0, 0, 0,
        255, 0, 255, 255, 0, 0, 255, 255
      ]
    })
    regl.texture([[[0, 255, 0], [255, 0, 0]], [[0, 0, 255], [255, 255, 255]]])
    t.equals(stats.textureCount, 3, 'stats.textureCount==3 after creating 3 textures')

    regl.destroy()
    t.equals(stats.textureCount, 0, 'stats.textureCount==0 after regl.destroy()')
    //
    // End Test stats.textureCount
    //

    //
    // Begin Test stats.cubeCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.cubeCount, 0, 'stats.cubeCount==0 at start')

    regl.cube(16)
    regl.cube(
      [[[255, 0, 0, 255]]],
      [[[0, 255, 0, 255]]],
      [[[0, 0, 255, 255]]],
      [[[0, 0, 0, 255]]],
      [[[255, 255, 0, 255]]],
      [[[0, 255, 255, 255]]])
    regl.cube({
      faces: [
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]],
        [[[0, 0, 255, 255]]],
        [[[0, 0, 0, 255]]],
        [[[255, 0, 0, 255]]],
        [[[0, 255, 0, 255]]]
      ]
    })

    t.equals(stats.cubeCount, 3, 'stats.cubeCount==3 after creating 3 cubes')

    regl.destroy()
    t.equals(stats.cubeCount, 0, 'stats.cubeCount==0 after regl.destroy()')
    //
    // End Test stats.cubeCount
    //

    //
    // Begin Test stats.renderbufferCount
    //
    regl = createREGL(gl)
    stats = regl.stats

    t.equals(stats.renderbufferCount, 0, 'stats.renderbufferCount==0 at start')

    regl.renderbuffer()
    regl.renderbuffer({width: 16, height: 16, format: 'rgba4'})
    regl.renderbuffer({width: 2, height: 2, format: 'depth'})
    t.equals(stats.renderbufferCount, 3, 'stats.renderbufferCount==3 after creating 3 renderbuffers')

    regl.destroy()
    t.equals(stats.renderbufferCount, 0, 'stats.renderbufferCount==0 after regl.destroy()')
    //
    // End Test stats.renderbufferCount
    //

    createContext.destroy(gl)
    t.end()
  }, 120)
})
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Language Technology Group and Interactive Graphics Systems Group, Technische Universität Darmstadt, Germany
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

define([
    'angular',
    'ngSanitize',
    'ngMaterial'
], function (angular) {
    'use strict';

    angular.module('myApp.document', ['play.routing', 'ngSanitize', 'ngMaterial'])
        .directive('docContent', ['$compile', 'ObserverService', 'EntityService', '_', function($compile, ObserverService, EntityService, _) {
            return {
                restrict: 'E',
                transclude: true,
                //replace: true,
                scope: {
                    // Need to set-up a bi-directional binding in order to pass an object not a string
                    document: '='
                },
                link: function(scope, element, attrs) {
                    // Stores elements that have been removed via the blacklisting for the current document
                    scope.removed = {};

                    var content = scope.document.content;
                    var entities = scope.document.entities;

                    var categoryColors = { 'PER': '#d73027', 'ORG': '#fee090', 'LOC': '#abd9e9', 'MISC': '#4575b4'};

                    scope.addEntityFilter = function(id) {
                        var el = _.find(entities, function(e) { return e.id == id });
                        ObserverService.addItem({ type: 'entity', data: { id: id, description: el.name, item: el.name, type: el.type }});
                    };

                    scope.blacklistFilter = function(id) {
                        EntityService.blacklist([id]);
                        // Remove the highlighting for the given entity
                        scope.removed[id] = true;
                    };

                    scope.renderDoc = function() {
                        var container =  element;
                        var offset = 0;

                        var sortedSpans = entities.sort(function(a, b) { return a.start - b.start; });
                        sortedSpans.forEach(function(e) {
                            var textEntity = content.slice(e.start, e.end);
                            //var fragments = doc.content.slice(offset, e.start).split('/\r|\n/');
                            var fragments = content.slice(offset, e.start).split('\n');

                            fragments.forEach(function(f, i) {
                                container.append(document.createTextNode(f));
                                if(fragments.length > 1 && i != fragments.length - 1) container.append(angular.element('
'));
                            });

                            var highlight = angular.element('');
                            highlight.className = 'highlight-general';

                            highlight.append(document.createTextNode(textEntity));
                            var highlightElement = $compile(highlight)(scope);

                            // Add entity filter buttons
                            var addButtonTemplate = angular.element('<md-button class="md-icon-button entity-menu" ng-click="addEntityFilter(' + e.id +')" ng-hide="removed['+ e.id  +']"><md-icon class="material-icons entity-menu" aria-label="filter">add_circle</md-icon></md-button>');
                            var removeButtonTemplate = angular.element('<md-button class="md-icon-button entity-menu" ng-click="blacklistFilter(' + e.id +')" ng-hide="removed['+ e.id  +']"><md-icon class="material-icons entity-menu" aria-label="filter">remove_circle</md-icon></md-button>');
                            var addButton = $compile(addButtonTemplate)(scope);
                            var removeButton = $compile(removeButtonTemplate)(scope);

                            container.append(highlightElement);
                            container.append(addButton);
                            container.append(removeButton);

                            offset = e.end;
                        });
                        container.append(document.createTextNode(content.slice(offset, content.length)));
                    };

                    // Init component
                    scope.renderDoc();
                }
            };
        }])
        .controller('DocumentController',
            [
                '$scope',
                '$http',
                '$templateRequest',
                '$sce',
                '$timeout',
                'playRoutes',
                '_',
                'sourceShareService',
                'uiShareService',
                'ObserverService',
                function ($scope,
                          $http,
                          $templateRequest,
                          $sce,
                          $timeout,
                          playRoutes,
                          _,
                          sourceShareService,
                          uiShareService,
                          ObserverService) {

                    var self = this;

                    $scope.sourceShared = sourceShareService;
                    $scope.uiShareService = uiShareService;

                    $scope.tabs = $scope.sourceShared.tabs;

                    // Maps from doc id to list of tags
                    $scope.tags = {};
                    $scope.labels = $scope.sourceShared.labels;

                    self.numKeywords = 15;

                    $scope.removeTab = function (tab) {
                        var index = $scope.tabs.indexOf(tab);
                        $scope.tabs.splice(index, 1);
                    };

                    $scope.observer = ObserverService;

                    $scope.observer.subscribeReset(function() {
                        // Remove all open documents when reset is issued, but keep old bindings to the array.
                        $scope.tabs.length = 0;
                        // Update the document labels when collection is changed
                        updateTagLabels();
                    });

                    init();

                    function init() {
                        updateTagLabels();
                    }

                    $scope.retrieveKeywords = function(doc) {
                        var terms =  [];
                        playRoutes.controllers.DocumentController.getKeywordsById(doc.id, self.numKeywords).get().then(function(response) {
                            response.data.forEach(function(t) { return terms.push(t.term); });
                        });
                        return terms;
                    };

                    $scope.transformTag = function(tag, doc) {
                        // If it is an object, it's already a known tag
                        if (angular.isObject(tag)) {
                            return tag;
                        }
                        // Otherwise try to create new tag
                        $scope.addTag({ label: tag }, doc);
                        // Prevent the chip from being added. We add it with an id in
                        // the addTag method above.
                        return null;
                    };

                    function updateTagLabels() {
                        $scope.labels.length = 0;
                        // Fetch all available document labels for auto-complete
                        playRoutes.controllers.DocumentController.getTagLabels().get().then(function(response) {
                            response.data.labels.forEach(function(l) { $scope.labels.push(l); });
                        });
                    }

                    $scope.initTags = function(doc) {
                        $scope.tags[doc.id] = [];
                        playRoutes.controllers.DocumentController.getTagsByDocId(doc.id).get().then(function(response) {
                            response.data.forEach(function(tag) {
                                $scope.tags[doc.id].push({ label: tag.label, id: tag.id });
                            });
                        });
                    };

                    $scope.addTag = function(tag, doc) {
                        // Do not add tag if already present
                        var match = _.findWhere($scope.tags[doc.id], { label: tag.label });
                        if(match) {
                            return;
                        }

                        playRoutes.controllers.DocumentController.addTag(doc.id, tag.label).get().then(function(response) {
                            $scope.tags[doc.id].push({ id: response.data.id , label: tag.label });
                            // Update labels
                            updateTagLabels();
                        });
                    };

                    $scope.removeTag = function(tag) {
                        playRoutes.controllers.DocumentController.removeTagById(tag.id).get().then(function(response) {
                            // Update labels
                            updateTagLabels();
                        });
                    };

                    $scope.querySearch = function(doc, query) {
                        var results = query ? $scope.labels.filter(createFilterFor(query)) : [];
                        return results;
                    };

                    function createFilterFor(query) {
                        var lowercaseQuery = angular.lowercase(query);
                        return function filterFn(label) {
                            return (label.toLowerCase().indexOf(lowercaseQuery) === 0);
                        };
                    }
                }
            ]);
});
<commit_msg>Make interactions in document view simpler<commit_after>/*
 * Copyright (C) 2016 Language Technology Group and Interactive Graphics Systems Group, Technische Universität Darmstadt, Germany
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

define([
    'angular',
    'ngSanitize',
    'ngMaterial'
], function (angular) {
    'use strict';

    angular.module('myApp.document', ['play.routing', 'ngSanitize', 'ngMaterial'])
        .directive('docContent', ['$compile', 'ObserverService', '_', function($compile, ObserverService, _) {
            return {
                restrict: 'E',
                transclude: true,
                //replace: true,
                scope: {
                    // Need to set-up a bi-directional binding in order to pass an object not a string
                    document: '='
                },
                link: function(scope, element, attrs) {
                    var content = scope.document.content;
                    var entities = scope.document.entities;

                    var categoryColors = { 'PER': '#d73027', 'ORG': '#fee090', 'LOC': '#abd9e9', 'MISC': '#4575b4'};

                    scope.addEntityFilter = function(id) {
                        var el = _.find(entities, function(e) { return e.id == id });
                        ObserverService.addItem({ type: 'entity', data: { id: id, description: el.name, item: el.name, type: el.type }});
                    };

                    scope.renderDoc = function() {
                        var container =  element;
                        var offset = 0;

                        var sortedSpans = entities.sort(function(a, b) { return a.start - b.start; });
                        sortedSpans.forEach(function(e) {
                            var textEntity = content.slice(e.start, e.end);
                            var fragments = content.slice(offset, e.start).split('\n');

                            fragments.forEach(function(f, i) {
                                container.append(document.createTextNode(f));
                                if(fragments.length > 1 && i != fragments.length - 1) container.append(angular.element('
'));
                            });

                            var highlight = angular.element('');
                            highlight.className = 'highlight-general';
                            var addFilter = angular.element('');

                            addFilter.append(document.createTextNode(textEntity));
                            highlight.append(addFilter);
                            var highlightElement = $compile(highlight)(scope);
                            container.append(highlightElement);

                            offset = e.end;
                        });
                        container.append(document.createTextNode(content.slice(offset, content.length)));
                    };

                    // Init component
                    scope.renderDoc();
                }
            };
        }])
        .controller('DocumentController',
            [
                '$scope',
                '$http',
                '$templateRequest',
                '$sce',
                '$timeout',
                'playRoutes',
                '_',
                'sourceShareService',
                'uiShareService',
                'ObserverService',
                function ($scope,
                          $http,
                          $templateRequest,
                          $sce,
                          $timeout,
                          playRoutes,
                          _,
                          sourceShareService,
                          uiShareService,
                          ObserverService) {

                    var self = this;

                    $scope.sourceShared = sourceShareService;
                    $scope.uiShareService = uiShareService;

                    $scope.tabs = $scope.sourceShared.tabs;

                    // Maps from doc id to list of tags
                    $scope.tags = {};
                    $scope.labels = $scope.sourceShared.labels;

                    self.numKeywords = 15;

                    $scope.removeTab = function (tab) {
                        var index = $scope.tabs.indexOf(tab);
                        $scope.tabs.splice(index, 1);
                    };

                    $scope.observer = ObserverService;

                    $scope.observer.subscribeReset(function() {
                        // Remove all open documents when reset is issued, but keep old bindings to the array.
                        $scope.tabs.length = 0;
                        // Update the document labels when collection is changed
                        updateTagLabels();
                    });

                    init();

                    function init() {
                        updateTagLabels();
                    }

                    $scope.retrieveKeywords = function(doc) {
                        var terms =  [];
                        playRoutes.controllers.DocumentController.getKeywordsById(doc.id, self.numKeywords).get().then(function(response) {
                            response.data.forEach(function(t) { return terms.push(t.term); });
                        });
                        return terms;
                    };

                    $scope.transformTag = function(tag, doc) {
                        // If it is an object, it's already a known tag
                        if (angular.isObject(tag)) {
                            return tag;
                        }
                        // Otherwise try to create new tag
                        $scope.addTag({ label: tag }, doc);
                        // Prevent the chip from being added. We add it with an id in
                        // the addTag method above.
                        return null;
                    };

                    function updateTagLabels() {
                        $scope.labels.length = 0;
                        // Fetch all available document labels for auto-complete
                        playRoutes.controllers.DocumentController.getTagLabels().get().then(function(response) {
                            response.data.labels.forEach(function(l) { $scope.labels.push(l); });
                        });
                    }

                    $scope.initTags = function(doc) {
                        $scope.tags[doc.id] = [];
                        playRoutes.controllers.DocumentController.getTagsByDocId(doc.id).get().then(function(response) {
                            response.data.forEach(function(tag) {
                                $scope.tags[doc.id].push({ label: tag.label, id: tag.id });
                            });
                        });
                    };

                    $scope.addTag = function(tag, doc) {
                        // Do not add tag if already present
                        var match = _.findWhere($scope.tags[doc.id], { label: tag.label });
                        if(match) {
                            return;
                        }

                        playRoutes.controllers.DocumentController.addTag(doc.id, tag.label).get().then(function(response) {
                            $scope.tags[doc.id].push({ id: response.data.id , label: tag.label });
                            // Update labels
                            updateTagLabels();
                        });
                    };

                    $scope.removeTag = function(tag) {
                        playRoutes.controllers.DocumentController.removeTagById(tag.id).get().then(function(response) {
                            // Update labels
                            updateTagLabels();
                        });
                    };

                    $scope.querySearch = function(doc, query) {
                        var results = query ? $scope.labels.filter(createFilterFor(query)) : [];
                        return results;
                    };

                    function createFilterFor(query) {
                        var lowercaseQuery = angular.lowercase(query);
                        return function filterFn(label) {
                            return (label.toLowerCase().indexOf(lowercaseQuery) === 0);
                        };
                    }
                }
            ]);
});
<|endoftext|>


<commit_before>var ps, pointCloud;
var yRot = 0.0;
var zoomed = -60;

function zoom(amt){
  zoomed += amt * 2 * 1;
}

function pointLight(light){
  var lightName = "lights" + light.id;
  ps.uniformi( lightName + ".isOn", true);
  ps.uniformf( lightName + ".position", light.position);
  ps.uniformi( lightName + ".type", 2);
  ps.uniformf( lightName + ".attenuation", light.attenuation);

  if(light.ambient){ps.uniformf( lightName + ".ambient", light.ambient);}
  if(light.diffuse){ps.uniformf( lightName + ".diffuse", light.diffuse);}
  if(light.specular){ps.uniformf( lightName + ".specular", light.specular);}
}

function render() {
  ps.translate(0, 0, zoomed);
  ps.rotateY(yRot += 0.001);

  var c = pointCloud.getCenter();
  ps.translate(-c[0], -c[1], -c[2]);

  ps.clear();
  ps.render(pointCloud);
}

function start(){
  ps = new PointStream();
  ps.setup(document.getElementById('canvas'));
	ps.background([1, 1, 0.7, 1]);

  var vertShader = ps.getShaderStr("../../shaders/fixed_function.vs");
  var fragShader = ps.getShaderStr("../../shaders/fixed_function.fs");

  var prog = ps.createProgram(vertShader, fragShader);
  ps.useProgram(prog);

  pointLight({id:0, ambient:[.2,.2,.2], diffuse:[.7,.7,.7], attenuation:[1,0,0], position: [0,0,1]});

  ps.onRender = render;
  ps.onMouseScroll = zoom;

  ps.pointSize(8);

  pointCloud = ps.load("../../clouds/mickey_156K_n.psi");
}
<commit_msg>updated psi parser test.<commit_after>var ps, pointCloud;
var yRot = 0.0;
var zoomed = -60;
var prog;

function zoom(amt){
  zoomed += amt * 2 * 1;
}

function pointLight(light){
  var lightName = "lights" + light.id;
  ps.uniformi( lightName + ".isOn", true);
  ps.uniformf( lightName + ".position", light.position);
  ps.uniformi( lightName + ".type", 2);
  ps.uniformf( lightName + ".attenuation", light.attenuation);

  if(light.ambient){ps.uniformf( lightName + ".ambient", light.ambient);}
  if(light.diffuse){ps.uniformf( lightName + ".diffuse", light.diffuse);}
  if(light.specular){ps.uniformf( lightName + ".specular", light.specular);}
}

function render() {
  ps.translate(0, 0, zoomed);
  ps.rotateY(yRot += 0.001);

  var c = pointCloud.getCenter();
  ps.translate(-c[0], -c[1], -c[2]);

  ps.clear();
  ps.render(pointCloud);

  if(!prog && pointCloud.status === 3){
    var vertShader = ps.getShaderStr("../../shaders/fixed_function.vs");
    var fragShader = ps.getShaderStr("../../shaders/fixed_function.fs");

    var prog = ps.createProgram(vertShader, fragShader);
    ps.useProgram(prog);

    pointLight({id:0, ambient:[.2,.2,.2], diffuse:[.7,.7,.7], attenuation:[1,0,0], position: [0,0,1]});
  }
}

function start(){
  ps = new PointStream();
  ps.setup(document.getElementById('canvas'));
	ps.background([1, 1, 0.7, 1]);

  ps.onRender = render;
  ps.onMouseScroll = zoom;

  ps.pointSize(8);

  pointCloud = ps.load("../../clouds/mickey_754K_n.psi");
}
<|endoftext|>