<commit_before>var b = require('substance-bundler')

b.task('clean', function() {
  b.rm('./dist');
  b.rm('./.test');
  b.rm('./.docs');
  b.rm('./.npm');
});

function _css(DIST) {
  b.copy('*.css', DIST)
  b.copy('packages/**/*.css', DIST)
}

b.task('css', function() {
  _css('dist/')
})

function _browser(DIST, transpileToES5) {
  b.js('./index.es.js', {
    buble: transpileToES5,

    ignore: ['substance-cheerio'],
    commonjs: { include: ['node_modules/lodash/**'] },
    targets: [{
      useStrict: !transpileToES5,
      dest: DIST+'substance.js',
      format: 'umd', moduleName: 'substance', sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    }]
  })
}

b.task('browser:pure', function() {
  _browser('./dist/', false)
})

b.task('browser', function() {
  _browser('./dist/', true)
})

function _server(DIST, transpileToES5) {
  b.js('./index.es.js', {
    buble: transpileToES5,
    commonjs: { include: [
      'node_modules/lodash/**'
    ] },
    external: [ 'substance-cheerio' ],
    targets: [{
      dest: DIST+'substance.cjs.js',
      format: 'cjs', sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    }]
  })
}

b.task('server', function() {
  // for the time being we transpile the cjs bundle
  // so it works in node 4 too
  _server('./dist/', true)
})

var TEST ='.test/'

b.task('test:clean', function() {
  b.rm(TEST)
})

b.task('test:assets', function() {
  // TODO: it would be nice to treat such glob patterns
  // differently, so that we do not need to specify glob root
  b.copy('./node_modules/substance-test/dist/*', TEST, { root: './node_modules/substance-test/dist' })
})

function _testBrowser(transpileToES5) {
  b.js('./test/index.js', {

    buble: transpileToES5,
    ignore: ['substance-cheerio'],
    external: ['substance-test'],
    commonjs: { include: ['node_modules/lodash/**'] },
    targets: [
      { dest: TEST+'tests.js', format: 'umd', moduleName: 'tests' }
    ]
  })
}

b.task('test:browser', function() {
  // buble necessary here, as travis has old browser versions
  _testBrowser(true)
})

b.task('test:browser:pure', function() {
  // Pure ES6, and no buble here, for better dev experience
  _testBrowser(false)
})

b.task('test:server', function() {
  b.js('./test/index.js', {
    // buble necessary here, for nodejs
    buble: true,
    external: ['substance-test'],
    commonjs: {
      include: [
        '/**/lodash/**',
        '/**/substance-cheerio/**'
      ]
    },
    targets: [
      { dest: TEST+'tests.cjs.js', format: 'cjs' },
    ]
  })
})

var NPM = '.npm/'
var NPMDIST = NPM+'dist/'

b.task('npm:clean', function() {
  b.rm(NPM)
})

b.task('npm:copy:js', function() {
  b.copy('index.es.js', NPM)
  b.copy('collab/*.js', NPM)
  b.copy('model/**/*.js', NPM)
  b.copy('packages/**/*.js', NPM)
  b.copy('ui/*.js', NPM)
  b.copy('util/*.js', NPM)
  b.copy('test/*.js', NPM)
})

b.task('npm:copy:css', function() {
  _css(NPM)
  _css(NPMDIST)
})

function _docs(mode, dest) {
  var docgen = require('substance-docgen')
  docgen.bundle(b, {
    src: [
      './*.md',
      './doc/*.md',
      './collab/*.js',
      './model/**/*.js',
      './packages/**/*.js',
      './ui/*.js',
      './util/*.js',
    ],
    dest: dest,
    config: './.docgenrc.js',
    mode: mode // one of: 'source', 'json', 'site' (default: 'json')
  })
}

b.task('docs', function() {
  // creates a data.js file with prebuilt documentation
  // this gives the best trade-off between build and load time
  _docs('json', '.docs/')
})

b.task('npm:docs', function() {
  _docs('site', NPM+'docs/')
})

b.task('npm:js', function() {
  _browser(NPMDIST, true)
  _server(NPMDIST, true)
})

var stuff = [
  'package.json',
  'LICENSE.md',
  'README.md',
  'CHANGELOG.md',
  'make.js'
]
b.task('npm:stuff', function() {
  stuff.forEach(function(f) {
    b.copy(f, NPM)
  })
})

b.task('build', ['clean', 'css', 'browser', 'server'])

b.task('test', ['test:clean', 'test:assets', 'test:browser', 'test:server'])

b.task('npm', ['npm:clean', 'npm:copy:js', 'npm:copy:css', 'npm:docs', 'npm:js', 'npm:stuff'])

b.task('default', ['build'])

// Default dev mode, only browser bundles are made and no ES5 transpilation happens
b.task('dev', ['clean', 'css', 'browser:pure', 'test:assets', 'test:browser:pure' , 'docs'])

// SERVER

// starts a server when CLI argument '-s' is set
b.setServerPort(5550)
b.serve({ static: true, route: '/', folder: 'dist' })
b.serve({ static: true, route: '/test/', folder: '.test' })
b.serve({ static: true, route: '/docs/', folder: '.docs' })
<commit_msg>Include all test related files.<commit_after>var b = require('substance-bundler')

b.task('clean', function() {
  b.rm('./dist');
  b.rm('./.test');
  b.rm('./.docs');
  b.rm('./.npm');
});

function _css(DIST) {
  b.copy('*.css', DIST)
  b.copy('packages/**/*.css', DIST)
}

b.task('css', function() {
  _css('dist/')
})

function _browser(DIST, transpileToES5) {
  b.js('./index.es.js', {
    buble: transpileToES5,

    ignore: ['substance-cheerio'],
    commonjs: { include: ['node_modules/lodash/**'] },
    targets: [{
      useStrict: !transpileToES5,
      dest: DIST+'substance.js',
      format: 'umd', moduleName: 'substance', sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    }]
  })
}

b.task('browser:pure', function() {
  _browser('./dist/', false)
})

b.task('browser', function() {
  _browser('./dist/', true)
})

function _server(DIST, transpileToES5) {
  b.js('./index.es.js', {
    buble: transpileToES5,
    commonjs: { include: [
      'node_modules/lodash/**'
    ] },
    external: [ 'substance-cheerio' ],
    targets: [{
      dest: DIST+'substance.cjs.js',
      format: 'cjs', sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    }]
  })
}

b.task('server', function() {
  // for the time being we transpile the cjs bundle
  // so it works in node 4 too
  _server('./dist/', true)
})

var TEST ='.test/'

b.task('test:clean', function() {
  b.rm(TEST)
})

b.task('test:assets', function() {
  // TODO: it would be nice to treat such glob patterns
  // differently, so that we do not need to specify glob root
  b.copy('./node_modules/substance-test/dist/*', TEST, { root: './node_modules/substance-test/dist' })
})

function _testBrowser(transpileToES5) {
  b.js('./test/index.js', {

    buble: transpileToES5,
    ignore: ['substance-cheerio'],
    external: ['substance-test'],
    commonjs: { include: ['node_modules/lodash/**'] },
    targets: [
      { dest: TEST+'tests.js', format: 'umd', moduleName: 'tests' }
    ]
  })
}

b.task('test:browser', function() {
  // buble necessary here, as travis has old browser versions
  _testBrowser(true)
})

b.task('test:browser:pure', function() {
  // Pure ES6, and no buble here, for better dev experience
  _testBrowser(false)
})

b.task('test:server', function() {
  b.js('./test/index.js', {
    // buble necessary here, for nodejs
    buble: true,
    external: ['substance-test'],
    commonjs: {
      include: [
        '/**/lodash/**',
        '/**/substance-cheerio/**'
      ]
    },
    targets: [
      { dest: TEST+'tests.cjs.js', format: 'cjs' },
    ]
  })
})

var NPM = '.npm/'
var NPMDIST = NPM+'dist/'

b.task('npm:clean', function() {
  b.rm(NPM)
})

b.task('npm:copy:js', function() {
  b.copy('index.es.js', NPM)
  b.copy('collab/*.js', NPM)
  b.copy('model/**/*.js', NPM)
  b.copy('packages/**/*.js', NPM)
  b.copy('ui/*.js', NPM)
  b.copy('util/*.js', NPM)
  b.copy('test/**/*.js', NPM)
})

b.task('npm:copy:css', function() {
  _css(NPM)
  _css(NPMDIST)
})

function _docs(mode, dest) {
  var docgen = require('substance-docgen')
  docgen.bundle(b, {
    src: [
      './*.md',
      './doc/*.md',
      './collab/*.js',
      './model/**/*.js',
      './packages/**/*.js',
      './ui/*.js',
      './util/*.js',
    ],
    dest: dest,
    config: './.docgenrc.js',
    mode: mode // one of: 'source', 'json', 'site' (default: 'json')
  })
}

b.task('docs', function() {
  // creates a data.js file with prebuilt documentation
  // this gives the best trade-off between build and load time
  _docs('json', '.docs/')
})

b.task('npm:docs', function() {
  _docs('site', NPM+'docs/')
})

b.task('npm:js', function() {
  _browser(NPMDIST, true)
  _server(NPMDIST, true)
})

var stuff = [
  'package.json',
  'LICENSE.md',
  'README.md',
  'CHANGELOG.md',
  'make.js'
]
b.task('npm:stuff', function() {
  stuff.forEach(function(f) {
    b.copy(f, NPM)
  })
})

b.task('build', ['clean', 'css', 'browser', 'server'])

b.task('test', ['test:clean', 'test:assets', 'test:browser', 'test:server'])

b.task('npm', ['npm:clean', 'npm:copy:js', 'npm:copy:css', 'npm:docs', 'npm:js', 'npm:stuff'])

b.task('default', ['build'])

// Default dev mode, only browser bundles are made and no ES5 transpilation happens
b.task('dev', ['clean', 'css', 'browser:pure', 'test:assets', 'test:browser:pure' , 'docs'])

// SERVER

// starts a server when CLI argument '-s' is set
b.setServerPort(5550)
b.serve({ static: true, route: '/', folder: 'dist' })
b.serve({ static: true, route: '/test/', folder: '.test' })
b.serve({ static: true, route: '/docs/', folder: '.docs' })
<|endoftext|>


<commit_before>var fis = module.exports = require('fis');

fis.cli.name = "spmx";
fis.cli.info = fis.util.readJSON(__dirname + '/package.json');

fis.config.merge({
    roadmap : {
        path : [
            {
                //一级同名组件，可以引用短路径，比如sea-modules/jquery/juqery.js
                //直接引用为var $ = require('jquery');
                reg : /^\/sea-modules\/([^\/]+)\/\1\.(js|coffee|less|css)$/i,
                //是组件化的，会被jswrapper包装
                isMod : true,
                //less和css文件会做csssprite处理
                useSprite : true,
                //id为文件夹名
                id : '$1'
            },
            {
                //sea-modules目录下的其他文件
                reg : /^\/sea-modules\/(.*)\.(js|coffee|less|css)$/i,
                //是组件化的，会被jswrapper包装
                isMod : true,
                //less和css文件会做csssprite处理
                useSprite : true,
                //id是去掉sea-modules和.js后缀中间的部分
                id : '$1'
            },
            {
                //.mixin.less后缀的文件
                reg : /\.mixin\.less$/,
                //仅当做函数调用，不发布
                release : false
            },
            {
                //其他js、css、coffee、less文件
                reg : /\.(js|coffee|css|less)$/,
                //less和css文件会做csssprite处理
                useSprite : true,
                //不要放到js资源表里
                useMap : false
            },
            {
                //前端模板
                reg : '**.tmpl',
                //当做类html文件处理，可以识别等资源定位标识
                isHtmlLike : true,
                //只是内嵌，不用发布
                release : false
            },
            {
                //map.json没什么用，就不要发布了
                reg : 'map.json',
                release : false
            }
        ],
        ext : {
            //less输出为css文件
            less : 'css',
            //coffee输出为js文件
            coffee : 'js'
        }
    },
    modules : {//fis插件配置
        parser : {
            //.tmpl后缀的文件使用fis-parser-utc插件编译
            tmpl : 'utc',
            //.coffee后缀的文件使用fis-parser-coffee-script插件编译
            coffee : 'coffee-script',
            //.less后缀的文件使用fis-parser-less插件编译
            less : 'less'
        },
        lint : {
            js : 'jshint'
        },
        postpackager : 'seajs'
    },
    settings : {
        parser : {
            'coffee-script' : {
                //不用coffee-script包装作用域
                bare : true
            }
        },
        lint : {
            jshint : {
                //排除对lib和jquery、backbone、underscore的检查
                ignored : [ 'lib/**', /jquery|backbone|underscore/i ],
                //使用中文报错
                i18n : 'zh-CN'
            }
        },
        postprocessor : {
            jswrapper : {
                //用fis的js包装器，更方便书写
                type : 'amd'
            }
        },
        optimizer : {
            'uglify-js' : {
                mangle : {
                    //不要压缩require关键字，否则seajs会识别不了require
                    except : [ 'require' ]
                }
            }
        }
    }
});
<commit_msg>add readme<commit_after>var fis = module.exports = require('fis');

fis.cli.name = "spmx";
fis.cli.info = fis.util.readJSON(__dirname + '/package.json');

fis.config.merge({
    roadmap : {
        path : [
            {
                //一级同名组件，可以引用短路径，比如sea-modules/jquery/juqery.js
                //直接引用为var $ = require('jquery');
                reg : /^\/sea-modules\/([^\/]+)\/\1\.(js|coffee|less|css)$/i,
                //是组件化的，会被jswrapper包装
                isMod : true,
                //less和css文件会做csssprite处理
                useSprite : true,
                //id为文件夹名
                id : '$1'
            },
            {
                //sea-modules目录下的其他文件
                reg : /^\/sea-modules\/(.*)\.(js|coffee|less|css)$/i,
                //是组件化的，会被jswrapper包装
                isMod : true,
                //less和css文件会做csssprite处理
                useSprite : true,
                //id是去掉sea-modules和.js后缀中间的部分
                id : '$1'
            },
            {
                //.mixin.less后缀的文件
                reg : /\.mixin\.less$/,
                //仅当做函数调用，不发布
                release : false
            },
            {
                //其他js、css、coffee、less文件
                reg : /\.(js|coffee|css|less)$/,
                //less和css文件会做csssprite处理
                useSprite : true,
                //不要放到js资源表里
                useMap : false
            },
            {
                //readme文件，不要发布
                reg : /\/readme.md/i,
                release : false
            },
            {
                //前端模板
                reg : '**.tmpl',
                //当做类html文件处理，可以识别等资源定位标识
                isHtmlLike : true,
                //只是内嵌，不用发布
                release : false
            },
            {
                //map.json没什么用，就不要发布了
                reg : 'map.json',
                release : false
            }
        ],
        ext : {
            //less输出为css文件
            less : 'css',
            //coffee输出为js文件
            coffee : 'js'
        }
    },
    modules : {//fis插件配置
        parser : {
            //.tmpl后缀的文件使用fis-parser-utc插件编译
            tmpl : 'utc',
            //.coffee后缀的文件使用fis-parser-coffee-script插件编译
            coffee : 'coffee-script',
            //.less后缀的文件使用fis-parser-less插件编译
            less : 'less'
        },
        lint : {
            js : 'jshint'
        },
        postpackager : 'seajs'
    },
    settings : {
        parser : {
            'coffee-script' : {
                //不用coffee-script包装作用域
                bare : true
            }
        },
        lint : {
            jshint : {
                //排除对lib和jquery、backbone、underscore的检查
                ignored : [ 'lib/**', /jquery|backbone|underscore/i ],
                //使用中文报错
                i18n : 'zh-CN'
            }
        },
        postprocessor : {
            jswrapper : {
                //用fis的js包装器，更方便书写
                type : 'amd'
            }
        },
        optimizer : {
            'uglify-js' : {
                mangle : {
                    //不要压缩require关键字，否则seajs会识别不了require
                    except : [ 'require' ]
                }
            }
        }
    }
});
<|endoftext|>


<commit_before>/**
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/
object.__name__ = str(object.__name__);

for (var x in py_builtins.PY$__exceptions__) {
    py_builtins.PY$__exceptions__.__name__ = str(py_builtins.PY$__exceptions__.__name__);
}

Super.__name = str(Super.__name__);

for (var x in $PY) {
    $PY[x].__name__ = str($PY[x].__name__);
}
<commit_msg> * Fixed 70-name-fixup. It never actually worked in the previous broken state<commit_after>/**
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/
object.PY$__name__ = str(object.PY$__name__);

for (var x in py_builtins.PY$__exceptions__) {
    var name = py_builtins.PY$__exceptions__[x];
    py_builtins[name].PY$__name__ = str(py_builtins[name].PY$__name__);
}

Super.PY$__name__ = str(Super.PY$__name__);

for (x in $PY) {
    $PY[x].PY$__name__ = str($PY[x].PY$__name__);
}
<|endoftext|>


<commit_before>// Web Worker implementation

var $module = (function($B){

var _b_ = $B.builtins

var brython_scripts = ['brython', 'brython_stdlib']

var wclass = $B.make_class("Worker",
    function(worker){
        var res = worker
        res.send = res.postMessage
        return res
    }
)
wclass.__mro__ = [$B.JSObj, _b_.object]

$B.set_func_names(wclass, "browser.worker")

var _Worker = $B.make_class("Worker", function(id, onmessage, onerror){
    var $ = $B.args("__init__", 3, {id: null, onmessage: null, onerror: null},
            ['id', 'onmessage', 'onerror'], arguments,
            {onmessage: _b_.None, onerror: _b_.None}, null, null),
        id = $.id,
        src = $B.webworkers[id]
        if(src === undefined){
            throw _b_.KeyError.$factory(id)
        }
        var script_id = "worker" + $B.UUID(),
            js = __BRYTHON__.imported.javascript.py2js(src,
                script_id),
            header = 'var $locals_' + script_id +' = {}\n';
        brython_scripts.forEach(function(script){
            var url = $B.brython_path + script + ".js?" +
                (new Date()).getTime()
            header += 'importScripts("' + url + '")\n'
        })
        // restore brython_path
        header += '__BRYTHON__.brython_path = "' + $B.brython_path +
            '"\n'
        // restore path for imports (cf. issue #1305)
        header += '__BRYTHON__.path = "' + $B.path +'".split(",")\n'
        // Call brython() to initialize internal Brython values
        header += 'brython(1)\n'
        js = header + js
        var blob = new Blob([js], {type: "application/js"}),
            url = URL.createObjectURL(blob),
            w = new Worker(url),
            res = wclass.$factory(w)
        return res
})

return {
    Worker: _Worker
}

})(__BRYTHON__)
<commit_msg>Improve error reporting in web workers. Related to issues #1942 and #1943.<commit_after>// Web Worker implementation

var $module = (function($B){

var _b_ = $B.builtins

if($B.debug > 2){
    var brython_scripts = [
        'brython_builtins',
        'version_info',
        'python_tokenizer',
        'py_ast',
        'py2js',
        'loaders',
        'py_object',
        'py_type',
        'py_utils',
        'py_sort',
        'py_builtin_functions',
        'py_exceptions',
        'py_range_slice',
        'py_bytes',
        'py_set',
        'js_objects',
        'stdlib_paths',
        'py_import',
        'unicode_data',
        'py_string',
        'py_int',
        'py_long_int',
        'py_float',
        'py_complex',
        'py_dict',
        'py_list',
        'py_generator',
        'py_dom',
        'py_pattern_matching',
        'builtin_modules',
        'async',
        'ast_to_js',
        'symtable',
        'brython_stdlib']

}else{
    var brython_scripts = ['brython', 'brython_stdlib']
}
var wclass = $B.make_class("Worker",
    function(worker){
        var res = worker
        res.send = res.postMessage
        return res
    }
)
wclass.__mro__ = [$B.JSObj, _b_.object]

$B.set_func_names(wclass, "browser.worker")

var _Worker = $B.make_class("Worker", function(id, onmessage, onerror){
    var $ = $B.args("__init__", 3, {id: null, onmessage: null, onerror: null},
            ['id', 'onmessage', 'onerror'], arguments,
            {onmessage: _b_.None, onerror: _b_.None}, null, null),
        id = $.id,
        src = $B.webworkers[id]
        if(src === undefined){
            throw _b_.KeyError.$factory(id)
        }
        var script_id = "worker" + $B.UUID(),
            js = __BRYTHON__.imported.javascript.py2js(src,
                script_id),
            header = 'var $locals_' + script_id +' = {}\n';
        brython_scripts.forEach(function(script){
            var url = $B.brython_path + script + ".js?" +
                (new Date()).getTime()
            header += 'importScripts("' + url + '")\n'
        })
        // restore brython_path
        header += '__BRYTHON__.brython_path = "' + $B.brython_path +
            '"\n'
        // restore path for imports (cf. issue #1305)
        header += '__BRYTHON__.path = "' + $B.path +'".split(",")\n'
        // Call brython() to initialize internal Brython values
        header += `brython($B.debug)\n`
        js = header + js
        js = `try{${js}}catch(err){$B.handle_error(err)}`
        var blob = new Blob([js], {type: "application/js"}),
            url = URL.createObjectURL(blob),
            w = new Worker(url),
            res = wclass.$factory(w)
        return res
})

return {
    Worker: _Worker
}

})(__BRYTHON__)
<|endoftext|>


<commit_before>import { createSelector } from 'reselect';
import compact from 'lodash/compact';
import uniq from 'lodash/uniq';
import concat from 'lodash/concat';
import isEmpty from 'lodash/isEmpty';
import qs from 'query-string';

import WIDGETS from 'pages/country/data/widgets-config.json';

// get list data
const getCategories = state => state.categories || null;
const getCategory = state => state.category || null;
const getAdminLevel = state => state.adminLevel || null;
const getLocation = state => state.location || null;
const getLocationOptions = state => state.locationOptions || null;
const getIndicatorWhitelist = state => state.indicatorWhitelist || null;

// get lists selected
export const getWidgets = createSelector([], () =>
  Object.keys(WIDGETS).map(key => ({
    name: key,
    ...WIDGETS[key]
  }))
);

export const filterWidgetsByCategory = createSelector(
  [getWidgets, getCategory],
  (widgets, category) =>
    widgets.filter(w => w.active && w.config.categories.indexOf(category) > -1)
);

export const checkWidgetNeedsLocations = createSelector(
  [filterWidgetsByCategory, getLocationOptions, getAdminLevel],
  (widgets, locations, adminLevel) => {
    if (isEmpty(locations)) return null;
    const adminCheck = adminLevel === 'country' ? 'regions' : 'subRegions';
    return widgets.filter(
      w =>
        w.config.admins.indexOf(adminLevel) > -1 &&
        (!w.config.locationCheck || locations[adminCheck].length > 1)
    );
  }
);

export const filterWidgets = createSelector(
  [checkWidgetNeedsLocations, getIndicatorWhitelist],
  (widgets, whitelist) => {
    // if (isEmpty(whitelist)) return null;
    const witelistKeys = !isEmpty(whitelist) ? Object.keys(whitelist) : null;
    return widgets.filter(widget => {
      // filter by showIndicators
      let showByIndicators = true;
      if (
        widget.config.showIndicators &&
        widget.config.indicators &&
        whitelist
      ) {
        const totalIndicators = concat(
          widget.config.showIndicators,
          witelistKeys
        ).length;
        const reducedIndicators = uniq(
          concat(widget.config.showIndicators, witelistKeys)
        ).length;
        showByIndicators = totalIndicators !== reducedIndicators;
      }
      // Then check if widget has data for gadm28 (loss or gain)
      const type = widget.config.type;
      // console.log(type);
      const hasData =
        !type ||
        type === 'extent' ||
        type === 'fao' ||
        (whitelist && whitelist.gadm28 && whitelist.gadm28[type]);

      return showByIndicators && hasData;
    });
  }
);

export const getLinks = createSelector(
  [getCategories, getCategory, getLocation],
  (categories, activeCategory, location) =>
    categories.map(category => {
      const locationUrl = compact(
        Object.keys(location.payload).map(key => location.payload[key])
      ).join('/');
      const newQuery = {
        ...location.query,
        category: category.value
      };
      return {
        label: category.label,
        path: `/country/${locationUrl}?${qs.stringify(newQuery)}`,
        active: activeCategory === category.value
      };
    })
);
<commit_msg>remove uneeded comment code<commit_after>import { createSelector } from 'reselect';
import compact from 'lodash/compact';
import uniq from 'lodash/uniq';
import concat from 'lodash/concat';
import isEmpty from 'lodash/isEmpty';
import qs from 'query-string';

import WIDGETS from 'pages/country/data/widgets-config.json';

// get list data
const getCategories = state => state.categories || null;
const getCategory = state => state.category || null;
const getAdminLevel = state => state.adminLevel || null;
const getLocation = state => state.location || null;
const getLocationOptions = state => state.locationOptions || null;
const getIndicatorWhitelist = state => state.indicatorWhitelist || null;

// get lists selected
export const getWidgets = createSelector([], () =>
  Object.keys(WIDGETS).map(key => ({
    name: key,
    ...WIDGETS[key]
  }))
);

export const filterWidgetsByCategory = createSelector(
  [getWidgets, getCategory],
  (widgets, category) =>
    widgets.filter(w => w.active && w.config.categories.indexOf(category) > -1)
);

export const checkWidgetNeedsLocations = createSelector(
  [filterWidgetsByCategory, getLocationOptions, getAdminLevel],
  (widgets, locations, adminLevel) => {
    if (isEmpty(locations)) return null;
    const adminCheck = adminLevel === 'country' ? 'regions' : 'subRegions';
    return widgets.filter(
      w =>
        w.config.admins.indexOf(adminLevel) > -1 &&
        (!w.config.locationCheck || locations[adminCheck].length > 1)
    );
  }
);

export const filterWidgets = createSelector(
  [checkWidgetNeedsLocations, getIndicatorWhitelist],
  (widgets, whitelist) => {
    const witelistKeys = !isEmpty(whitelist) ? Object.keys(whitelist) : null;
    return widgets.filter(widget => {
      // filter by showIndicators
      let showByIndicators = true;
      if (
        widget.config.showIndicators &&
        widget.config.indicators &&
        whitelist
      ) {
        const totalIndicators = concat(
          widget.config.showIndicators,
          witelistKeys
        ).length;
        const reducedIndicators = uniq(
          concat(widget.config.showIndicators, witelistKeys)
        ).length;
        showByIndicators = totalIndicators !== reducedIndicators;
      }
      // Then check if widget has data for gadm28 (loss or gain)
      const type = widget.config.type;
      const hasData =
        !type ||
        type === 'extent' ||
        type === 'fao' ||
        (whitelist && whitelist.gadm28 && whitelist.gadm28[type]);

      return showByIndicators && hasData;
    });
  }
);

export const getLinks = createSelector(
  [getCategories, getCategory, getLocation],
  (categories, activeCategory, location) =>
    categories.map(category => {
      const locationUrl = compact(
        Object.keys(location.payload).map(key => location.payload[key])
      ).join('/');
      const newQuery = {
        ...location.query,
        category: category.value
      };
      return {
        label: category.label,
        path: `/country/${locationUrl}?${qs.stringify(newQuery)}`,
        active: activeCategory === category.value
      };
    })
);
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2013  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// WidgetModel, WidgetView, and WidgetManager
//============================================================================
/**
 * Base Widget classes
 * @module IPython
 * @namespace IPython
 * @submodule widget
 */

(function () {
    "use strict";

    // Use require.js 'define' method so that require.js is intelligent enough to
    // syncronously load everything within this file when it is being 'required'
    // elsewhere.
    define(["underscore",
             "backbone",
            ], function (underscore, backbone) {

        // Backbone.sync method must be in widgetmanager.js file instead of
        // widget.js so it can be overwritten for different contexts.
        Backbone.sync = function (method, model, options) {
            var result = model._handle_sync(method, options);
            if (options.success) {
                options.success(result);
            }
        };

        //--------------------------------------------------------------------
        // WidgetManager class
        //--------------------------------------------------------------------
        var WidgetManager = function () {
            this.comm_manager = null;
            this._model_types = {}; /* Dictionary of model type names
                                      (target_name) and model types. */
            this._view_types = {}; /* Dictionary of view names and view types. */
            this._models = {}; /* Dictionary of model ids and model instances */
        };

        WidgetManager.prototype.attach_comm_manager = function (comm_manager) {
            this.comm_manager = comm_manager;

            // Register already-registered widget model types with the comm manager.
            for (var widget_model_name in this._model_types) {
                // TODO: Should not be a for.
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
        };

        WidgetManager.prototype.register_widget_model = function (widget_model_name, widget_model_type) {
            // Register the widget with the comm manager.  Make sure to pass this object's context
            // in so `this` works in the call back.
            if (this.comm_manager !== null) {
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
            this._model_types[widget_model_name] = widget_model_type;
        };

        WidgetManager.prototype.register_widget_view = function (widget_view_name, widget_view_type) {
            this._view_types[widget_view_name] = widget_view_type;
        };

        WidgetManager.prototype.display_view = function(msg_id, model) {
            var cell = this.get_msg_cell(msg_id);
            if (cell === null) {
                console.log("Could not determine where the display" +
                    " message was from.  Widget will not be displayed");
            } else {
                var view = this.create_view(model);
                if (view !== undefined
                    && cell.widget_subarea !== undefined
                    && cell.widget_subarea !== null) {

                    view.cell = cell;
                    cell.widget_area.show();
                    cell.widget_subarea.append(view.$el);
                }
            }
        },

        WidgetManager.prototype.create_view = function(model, options) {
            var view_name = model.get('view_name');
            var ViewType = this._view_types[view_name];
            if (ViewType !== undefined && ViewType !== null) {
                var parameters = {model: model, options: options};
                var view = new ViewType(parameters);
                view.render();
                model.views.push(view);
                model.on('destroy', view.remove, view);
                return view;
            }
        },

        WidgetManager.prototype.get_msg_cell = function (msg_id) {
            var cell = null;
            // First, check to see if the msg was triggered by cell execution.
            if (IPython.notebook !== undefined && IPython.notebook !== null) {
                cell = IPython.notebook.get_msg_cell(msg_id);
            }
            if (cell !== null) {
                return cell
            }
            // Second, check to see if a get_cell callback was defined
            // for the message.  get_cell callbacks are registered for
            // widget messages, so this block is actually checking to see if the
            // message was triggered by a widget.
            var kernel = null;
            if (this.comm_manager !== null) {
                kernel = this.comm_manager.kernel;
            }
            if (kernel !== undefined && kernel !== null) {
                var callbacks = kernel.get_callbacks_for_msg(msg_id);
                if (callbacks !== undefined &&
                    callbacks.iopub !== undefined &&
                    callbacks.iopub.get_cell !== undefined) {

                    return callbacks.iopub.get_cell();
                }
            }

            // Not triggered by a cell or widget (no get_cell callback
            // exists).
            return null;
        };

        WidgetManager.prototype.callbacks = function (view) {
            // callback handlers specific a view
            var callbacks = {};
            var cell = view.cell;
            if (cell !== null) {
                // Try to get output handlers
                var handle_output = null;
                var handle_clear_output = null;
                if (cell.output_area !== undefined && cell.output_area !== null) {
                    handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
                    handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
                }

                // Create callback dict using what is known
                var that = this;
                callbacks = {
                    iopub : {
                        output : handle_output,
                        clear_output : handle_clear_output,

                        status : function (msg) {
                            view.model._handle_status(msg, that.callbacks(view));
                        },

                        // Special function only registered by widget messages.
                        // Allows us to get the cell for a message so we know
                        // where to add widgets if the code requires it.
                        get_cell : function () {
                            return cell;
                        },
                    },
                };
            }
            return callbacks;
        };

        WidgetManager.prototype.get_model = function (model_id) {
            var model = this._models[model_id];
            if (model !== undefined && model.id == model_id) {
                return model;
            }
            return null;
        };

        WidgetManager.prototype._handle_comm_open = function (comm, msg) {
            var widget_type_name = msg.content.target_name;
            var widget_model = new this._model_types[widget_type_name](this, comm.comm_id, comm);
            this._models[comm.comm_id] = widget_model; // comm_id == model_id
        };

        //--------------------------------------------------------------------
        // Init code
        //--------------------------------------------------------------------
        IPython.WidgetManager = WidgetManager;
        if (IPython.widget_manager === undefined || IPython.widget_manager === null) {
            IPython.widget_manager = new WidgetManager();
        }

        return IPython.widget_manager;
    });
}());
<commit_msg>Make widget views work with new keyboard manager.<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2013  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// WidgetModel, WidgetView, and WidgetManager
//============================================================================
/**
 * Base Widget classes
 * @module IPython
 * @namespace IPython
 * @submodule widget
 */

(function () {
    "use strict";

    // Use require.js 'define' method so that require.js is intelligent enough to
    // syncronously load everything within this file when it is being 'required'
    // elsewhere.
    define(["underscore",
             "backbone",
            ], function (underscore, backbone) {

        // Backbone.sync method must be in widgetmanager.js file instead of
        // widget.js so it can be overwritten for different contexts.
        Backbone.sync = function (method, model, options) {
            var result = model._handle_sync(method, options);
            if (options.success) {
                options.success(result);
            }
        };

        //--------------------------------------------------------------------
        // WidgetManager class
        //--------------------------------------------------------------------
        var WidgetManager = function () {
            this.comm_manager = null;
            this._model_types = {}; /* Dictionary of model type names
                                      (target_name) and model types. */
            this._view_types = {}; /* Dictionary of view names and view types. */
            this._models = {}; /* Dictionary of model ids and model instances */
        };

        WidgetManager.prototype.attach_comm_manager = function (comm_manager) {
            this.comm_manager = comm_manager;

            // Register already-registered widget model types with the comm manager.
            for (var widget_model_name in this._model_types) {
                // TODO: Should not be a for.
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
        };

        WidgetManager.prototype.register_widget_model = function (widget_model_name, widget_model_type) {
            // Register the widget with the comm manager.  Make sure to pass this object's context
            // in so `this` works in the call back.
            if (this.comm_manager !== null) {
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
            this._model_types[widget_model_name] = widget_model_type;
        };

        WidgetManager.prototype.register_widget_view = function (widget_view_name, widget_view_type) {
            this._view_types[widget_view_name] = widget_view_type;
        };

        WidgetManager.prototype.display_view = function(msg_id, model) {
            var cell = this.get_msg_cell(msg_id);
            if (cell === null) {
                console.log("Could not determine where the display" +
                    " message was from.  Widget will not be displayed");
            } else {
                var view = this.create_view(model);
                if (view !== undefined
                    && cell.widget_subarea !== undefined
                    && cell.widget_subarea !== null) {

                    view.cell = cell;
                    cell.widget_area.show();
                    cell.widget_subarea.append(view.$el);
                }
            }
        },

        WidgetManager.prototype.create_view = function(model, options) {
            var view_name = model.get('view_name');
            var ViewType = this._view_types[view_name];
            if (ViewType !== undefined && ViewType !== null) {
                var parameters = {model: model, options: options};
                var view = new ViewType(parameters);
                view.render();
                IPython.keyboard_manager.register_events(view.$el);
                model.views.push(view);
                model.on('destroy', view.remove, view);
                return view;
            }
        },

        WidgetManager.prototype.get_msg_cell = function (msg_id) {
            var cell = null;
            // First, check to see if the msg was triggered by cell execution.
            if (IPython.notebook !== undefined && IPython.notebook !== null) {
                cell = IPython.notebook.get_msg_cell(msg_id);
            }
            if (cell !== null) {
                return cell
            }
            // Second, check to see if a get_cell callback was defined
            // for the message.  get_cell callbacks are registered for
            // widget messages, so this block is actually checking to see if the
            // message was triggered by a widget.
            var kernel = null;
            if (this.comm_manager !== null) {
                kernel = this.comm_manager.kernel;
            }
            if (kernel !== undefined && kernel !== null) {
                var callbacks = kernel.get_callbacks_for_msg(msg_id);
                if (callbacks !== undefined &&
                    callbacks.iopub !== undefined &&
                    callbacks.iopub.get_cell !== undefined) {

                    return callbacks.iopub.get_cell();
                }
            }

            // Not triggered by a cell or widget (no get_cell callback
            // exists).
            return null;
        };

        WidgetManager.prototype.callbacks = function (view) {
            // callback handlers specific a view
            var callbacks = {};
            var cell = view.cell;
            if (cell !== null) {
                // Try to get output handlers
                var handle_output = null;
                var handle_clear_output = null;
                if (cell.output_area !== undefined && cell.output_area !== null) {
                    handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
                    handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
                }

                // Create callback dict using what is known
                var that = this;
                callbacks = {
                    iopub : {
                        output : handle_output,
                        clear_output : handle_clear_output,

                        status : function (msg) {
                            view.model._handle_status(msg, that.callbacks(view));
                        },

                        // Special function only registered by widget messages.
                        // Allows us to get the cell for a message so we know
                        // where to add widgets if the code requires it.
                        get_cell : function () {
                            return cell;
                        },
                    },
                };
            }
            return callbacks;
        };

        WidgetManager.prototype.get_model = function (model_id) {
            var model = this._models[model_id];
            if (model !== undefined && model.id == model_id) {
                return model;
            }
            return null;
        };

        WidgetManager.prototype._handle_comm_open = function (comm, msg) {
            var widget_type_name = msg.content.target_name;
            var widget_model = new this._model_types[widget_type_name](this, comm.comm_id, comm);
            this._models[comm.comm_id] = widget_model; // comm_id == model_id
        };

        //--------------------------------------------------------------------
        // Init code
        //--------------------------------------------------------------------
        IPython.WidgetManager = WidgetManager;
        if (IPython.widget_manager === undefined || IPython.widget_manager === null) {
            IPython.widget_manager = new WidgetManager();
        }

        return IPython.widget_manager;
    });
}());
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare",
	"dojo/_base/kernel",
	"dojo/fx",
	"dijit/TitlePane",
	"./PortletSettings",
	"./PortletDialogSettings"
	], function(declare, kernel, fx, TitlePane, PortletSettings, PortletDialogSettings){

	kernel.experimental("dojox.widget.Portlet");

	return declare("dojox.widget.Portlet", [TitlePane, dijit._Container],{
		// summary:
		//		A container widget that is designed to be contained
		//		in a dojox.layout.GridContainer. Child widgets can insert
		//		an icon into the title bar of the Portlet, which when
		//		clicked, executes the "toggle" method of the child widget.
		//		A child widget must specify the attribute
		//		"portletIconClass", and the optional class
		//		"portletIconHoverClass", as well as the
		//		"toggle" function.

		// resizeChildren: Boolean
		//		If true, when the Portlet is resized, any child widgets
		//		with a 'resize' method have that method called.
		resizeChildren: true,

		// closable: Boolean
		//		If true, a close button is placed in the title bar,
		//		and the Portlet can be hidden. If false, the Portlet
		//		cannot be closed.
		closable: true,

		// _parents: Array
		//		 An array of all the StackContainer widgets that this Portlet
		//		is contained in.	These are used to determine if the portlet
		//		is visible or not.
		_parents: null,

		// _size: Object
		//		Cache of the previous size of the portlet, used to determine
		//		if the size has changed and if the child widgets should be
		//		resized.
		_size: null,

		// dragRestriction: Boolean
		//		To remove the drag capability.
		dragRestriction : false,

		buildRendering: function(){
			this.inherited(arguments);

			// Hide the portlet until it is fully constructed.
			dojo.style(this.domNode, "visibility", "hidden");
		},

		postCreate: function(){
			this.inherited(arguments);

			// Add the portlet classes
			dojo.addClass(this.domNode, "dojoxPortlet");
			dojo.removeClass(this.arrowNode, "dijitArrowNode");
			dojo.addClass(this.arrowNode, "dojoxPortletIcon dojoxArrowDown");
			dojo.addClass(this.titleBarNode, "dojoxPortletTitle");
			dojo.addClass(this.hideNode, "dojoxPortletContentOuter");

			// Choose the class to add depending on if the portlet is draggable or not.
			dojo.addClass(this.domNode, "dojoxPortlet-" + (!this.dragRestriction ? "movable" : "nonmovable"));

			var _this = this;
			if(this.resizeChildren){
				// If children should be resized	when the portlet size changes,
				// listen for items being dropped, when the window is resized,
				// or when another portlet's size changes.

				this.subscribe("/dnd/drop", function(){_this._updateSize();});

				this.subscribe("/Portlet/sizechange", function(widget){_this.onSizeChange(widget);});
				this.connect(window, "onresize", function(){_this._updateSize();});

				// Subscribe to all possible child-selection events that could affect this
				// portlet
				var doSelectSubscribe = dojo.hitch(this, function(id, lastId){
					var widget = dijit.byId(id);
					if(widget.selectChild){
						var s = this.subscribe(id + "-selectChild", function(child){
							var n = _this.domNode.parentNode;

							while(n){
								if(n == child.domNode){

									// Only fire this once, as the widget is now visible
									// at least once, so child measurements should be accurate.
									_this.unsubscribe(s);
									_this._updateSize();
									break;
								}
								n = n.parentNode;
							}
						});

						// Record the StackContainer and child widget that this portlet
						// is in, so it can figure out whether or not it is visible.
						// If it is not visible, it will not update it's size dynamically.
						var child = dijit.byId(lastId);
						if(widget && child){
							_this._parents.push({parent: widget, child: child});
						}
					}
				});
				var lastId;
				this._parents = [];

				// Find all parent widgets, and if they are StackContainers,
				// subscribe to their selectChild method calls.
				for(var p = this.domNode.parentNode; p != null; p = p.parentNode){
					var id = p.getAttribute ? p.getAttribute("widgetId") : null;
					if(id){
						doSelectSubscribe(id, lastId);
						lastId = id;
					}
				}
			}

			// Prevent clicks on icons from causing a drag to start.
			this.connect(this.titleBarNode, "onmousedown", function(evt){
				if (dojo.hasClass(evt.target, "dojoxPortletIcon")) {
					dojo.stopEvent(evt);
					return false;
				}
				return true;
			});

			// Inform all portlets that the size of this one has changed,
			// and therefore perhaps they have too
			this.connect(this._wipeOut, "onEnd", function(){_this._publish();});
			this.connect(this._wipeIn, "onEnd", function(){_this._publish();});

			if(this.closable){
				this.closeIcon = this._createIcon("dojoxCloseNode", "dojoxCloseNodeHover", dojo.hitch(this, "onClose"));
				dojo.style(this.closeIcon, "display", "");
			}
		},

		startup: function(){
			if(this._started){return;}

			var children = this.getChildren();
			this._placeSettingsWidgets();

			// Start up the children
			dojo.forEach(children, function(child){
				try{
					if(!child.started && !child._started){
						child.startup()
					}
				}
				catch(e){
					console.log(this.id + ":" + this.declaredClass, e);
				}
			});

			this.inherited(arguments);

			//this._updateSize();
			dojo.style(this.domNode, "visibility", "visible");
		},

		_placeSettingsWidgets: function(){
			// summary:
			//		Checks all the children to see if they are instances
			//		of dojox.widget.PortletSettings. If they are,
			//		create an icon for them in the title bar which when clicked,
			//		calls their toggle() method.

			dojo.forEach(this.getChildren(), dojo.hitch(this, function(child){
				if(child.portletIconClass && child.toggle && !child.attr("portlet")){
					this._createIcon(child.portletIconClass, child.portletIconHoverClass, dojo.hitch(child, "toggle"));
					dojo.place(child.domNode, this.containerNode, "before");
					child.attr("portlet", this);
					this._settingsWidget = child;
				}
			}));
		},

		_createIcon: function(clazz, hoverClazz, fn){
			// summary:
			//		creates an icon in the title bar.

			var icon = dojo.create("div",{
				"class": "dojoxPortletIcon " + clazz,
				"waiRole": "presentation"
			});
			dojo.place(icon, this.arrowNode, "before");

			this.connect(icon, "onclick", fn);

			if(hoverClazz){
				this.connect(icon, "onmouseover", function(){
					dojo.addClass(icon, hoverClazz);
				});
				this.connect(icon, "onmouseout", function(){
					dojo.removeClass(icon, hoverClazz);
				});
			}
			return icon;
		},

		onClose: function(evt){
			// summary:
			//		Hides the portlet. Note that it does not
			//		persist this, so it is up to the client to
			//		listen to this method and persist the closed state
			//		in their own way.
			dojo.style(this.domNode, "display", "none");
		},

		onSizeChange: function(widget){
			// summary:
			//		Updates the Portlet size if any other Portlet
			//		changes its size.
			if(widget == this){
				return;
			}
			this._updateSize();
		},

		_updateSize: function(){
			// summary:
			//		Updates the size of all child widgets.
			if(!this.open || !this._started || !this.resizeChildren){
				return;
			}

			if(this._timer){
				clearTimeout(this._timer);
			}
			// Delay applying the size change in case the size
			// changes very frequently, for performance reasons.
			this._timer = setTimeout(dojo.hitch(this, function(){
				var size ={
					w: dojo.style(this.domNode, "width"),
					h: dojo.style(this.domNode, "height")
				};

				// If the Portlet is in a StackWidget, and it is not
				// visible, do not update the size, as it could
				// make child widgets miscalculate.
				for(var i = 0; i < this._parents.length; i++){
					var p = this._parents[i];
					var sel = p.parent.selectedChildWidget
					if(sel && sel != p.child){
						return;
					}
				}

				if(this._size){
					// If the size of the portlet hasn't changed, don't
					// resize the children, as this can be expensive
					if(this._size.w == size.w && this._size.h == size.h){
						return;
					}
				}
				this._size = size;

				var fns = ["resize", "layout"];
				this._timer = null;
				var kids = this.getChildren();

				dojo.forEach(kids, function(child){
					for(var i = 0; i < fns.length; i++){
						if(dojo.isFunction(child[fns[i]])){
							try{
								child[fns[i]]();
							} catch(e){
								console.log(e);
							}
							break;
						}
					}
				});
				this.onUpdateSize();
			}), 100);
		},

		onUpdateSize: function(){
			// summary:
			//		Stub function called when the size is changed.
		},

		_publish: function(){
			// summary:
			//		Publishes an event that all other portlets listen to.
			//		This causes them to update their child widgets if their
			//		size has changed.
			dojo.publish("/Portlet/sizechange",[this]);
		},

		_onTitleClick: function(evt){
			if(evt.target == this.arrowNode){
				this.inherited(arguments);
			}
		},

		addChild: function(child){
			// summary:
			//		Adds a child widget to the portlet.
			this._size = null;
			this.inherited(arguments);

			if(this._started){
				this._placeSettingsWidgets();
				this._updateSize();
			}
			if(this._started && !child.started && !child._started){
				child.startup();
			}
		},

		destroyDescendants: function(/*Boolean*/ preserveDom){
			this.inherited(arguments);
			if(this._settingsWidget){
				this._settingsWidget.destroyRecursive(preserveDom);
			}
		},

		destroy: function(){
			if(this._timer){
				clearTimeout(this._timer);
			}
			this.inherited(arguments);
		},

		_setCss: function(){
			this.inherited(arguments);
			dojo.style(this.arrowNode, "display", this.toggleable ? "":"none");
		}
	});
});<commit_msg>Refs #14227 #15517 replace deprecated attr method<commit_after>define([
	"dojo/_base/declare",
	"dojo/_base/kernel",
	"dojo/fx",
	"dijit/TitlePane",
	"./PortletSettings",
	"./PortletDialogSettings"
	], function(declare, kernel, fx, TitlePane, PortletSettings, PortletDialogSettings){

	kernel.experimental("dojox.widget.Portlet");

	return declare("dojox.widget.Portlet", [TitlePane, dijit._Container],{
		// summary:
		//		A container widget that is designed to be contained
		//		in a dojox.layout.GridContainer. Child widgets can insert
		//		an icon into the title bar of the Portlet, which when
		//		clicked, executes the "toggle" method of the child widget.
		//		A child widget must specify the attribute
		//		"portletIconClass", and the optional class
		//		"portletIconHoverClass", as well as the
		//		"toggle" function.

		// resizeChildren: Boolean
		//		If true, when the Portlet is resized, any child widgets
		//		with a 'resize' method have that method called.
		resizeChildren: true,

		// closable: Boolean
		//		If true, a close button is placed in the title bar,
		//		and the Portlet can be hidden. If false, the Portlet
		//		cannot be closed.
		closable: true,

		// _parents: Array
		//		 An array of all the StackContainer widgets that this Portlet
		//		is contained in.	These are used to determine if the portlet
		//		is visible or not.
		_parents: null,

		// _size: Object
		//		Cache of the previous size of the portlet, used to determine
		//		if the size has changed and if the child widgets should be
		//		resized.
		_size: null,

		// dragRestriction: Boolean
		//		To remove the drag capability.
		dragRestriction : false,

		buildRendering: function(){
			this.inherited(arguments);

			// Hide the portlet until it is fully constructed.
			dojo.style(this.domNode, "visibility", "hidden");
		},

		postCreate: function(){
			this.inherited(arguments);

			// Add the portlet classes
			dojo.addClass(this.domNode, "dojoxPortlet");
			dojo.removeClass(this.arrowNode, "dijitArrowNode");
			dojo.addClass(this.arrowNode, "dojoxPortletIcon dojoxArrowDown");
			dojo.addClass(this.titleBarNode, "dojoxPortletTitle");
			dojo.addClass(this.hideNode, "dojoxPortletContentOuter");

			// Choose the class to add depending on if the portlet is draggable or not.
			dojo.addClass(this.domNode, "dojoxPortlet-" + (!this.dragRestriction ? "movable" : "nonmovable"));

			var _this = this;
			if(this.resizeChildren){
				// If children should be resized	when the portlet size changes,
				// listen for items being dropped, when the window is resized,
				// or when another portlet's size changes.

				this.subscribe("/dnd/drop", function(){_this._updateSize();});

				this.subscribe("/Portlet/sizechange", function(widget){_this.onSizeChange(widget);});
				this.connect(window, "onresize", function(){_this._updateSize();});

				// Subscribe to all possible child-selection events that could affect this
				// portlet
				var doSelectSubscribe = dojo.hitch(this, function(id, lastId){
					var widget = dijit.byId(id);
					if(widget.selectChild){
						var s = this.subscribe(id + "-selectChild", function(child){
							var n = _this.domNode.parentNode;

							while(n){
								if(n == child.domNode){

									// Only fire this once, as the widget is now visible
									// at least once, so child measurements should be accurate.
									_this.unsubscribe(s);
									_this._updateSize();
									break;
								}
								n = n.parentNode;
							}
						});

						// Record the StackContainer and child widget that this portlet
						// is in, so it can figure out whether or not it is visible.
						// If it is not visible, it will not update it's size dynamically.
						var child = dijit.byId(lastId);
						if(widget && child){
							_this._parents.push({parent: widget, child: child});
						}
					}
				});
				var lastId;
				this._parents = [];

				// Find all parent widgets, and if they are StackContainers,
				// subscribe to their selectChild method calls.
				for(var p = this.domNode.parentNode; p != null; p = p.parentNode){
					var id = p.getAttribute ? p.getAttribute("widgetId") : null;
					if(id){
						doSelectSubscribe(id, lastId);
						lastId = id;
					}
				}
			}

			// Prevent clicks on icons from causing a drag to start.
			this.connect(this.titleBarNode, "onmousedown", function(evt){
				if (dojo.hasClass(evt.target, "dojoxPortletIcon")) {
					dojo.stopEvent(evt);
					return false;
				}
				return true;
			});

			// Inform all portlets that the size of this one has changed,
			// and therefore perhaps they have too
			this.connect(this._wipeOut, "onEnd", function(){_this._publish();});
			this.connect(this._wipeIn, "onEnd", function(){_this._publish();});

			if(this.closable){
				this.closeIcon = this._createIcon("dojoxCloseNode", "dojoxCloseNodeHover", dojo.hitch(this, "onClose"));
				dojo.style(this.closeIcon, "display", "");
			}
		},

		startup: function(){
			if(this._started){return;}

			var children = this.getChildren();
			this._placeSettingsWidgets();

			// Start up the children
			dojo.forEach(children, function(child){
				try{
					if(!child.started && !child._started){
						child.startup()
					}
				}
				catch(e){
					console.log(this.id + ":" + this.declaredClass, e);
				}
			});

			this.inherited(arguments);

			//this._updateSize();
			dojo.style(this.domNode, "visibility", "visible");
		},

		_placeSettingsWidgets: function(){
			// summary:
			//		Checks all the children to see if they are instances
			//		of dojox.widget.PortletSettings. If they are,
			//		create an icon for them in the title bar which when clicked,
			//		calls their toggle() method.

			dojo.forEach(this.getChildren(), dojo.hitch(this, function(child){
				if(child.portletIconClass && child.toggle && !child.get("portlet")){
					this._createIcon(child.portletIconClass, child.portletIconHoverClass, dojo.hitch(child, "toggle"));
					dojo.place(child.domNode, this.containerNode, "before");
					child.set("portlet", this);
					this._settingsWidget = child;
				}
			}));
		},

		_createIcon: function(clazz, hoverClazz, fn){
			// summary:
			//		creates an icon in the title bar.

			var icon = dojo.create("div",{
				"class": "dojoxPortletIcon " + clazz,
				"waiRole": "presentation"
			});
			dojo.place(icon, this.arrowNode, "before");

			this.connect(icon, "onclick", fn);

			if(hoverClazz){
				this.connect(icon, "onmouseover", function(){
					dojo.addClass(icon, hoverClazz);
				});
				this.connect(icon, "onmouseout", function(){
					dojo.removeClass(icon, hoverClazz);
				});
			}
			return icon;
		},

		onClose: function(evt){
			// summary:
			//		Hides the portlet. Note that it does not
			//		persist this, so it is up to the client to
			//		listen to this method and persist the closed state
			//		in their own way.
			dojo.style(this.domNode, "display", "none");
		},

		onSizeChange: function(widget){
			// summary:
			//		Updates the Portlet size if any other Portlet
			//		changes its size.
			if(widget == this){
				return;
			}
			this._updateSize();
		},

		_updateSize: function(){
			// summary:
			//		Updates the size of all child widgets.
			if(!this.open || !this._started || !this.resizeChildren){
				return;
			}

			if(this._timer){
				clearTimeout(this._timer);
			}
			// Delay applying the size change in case the size
			// changes very frequently, for performance reasons.
			this._timer = setTimeout(dojo.hitch(this, function(){
				var size ={
					w: dojo.style(this.domNode, "width"),
					h: dojo.style(this.domNode, "height")
				};

				// If the Portlet is in a StackWidget, and it is not
				// visible, do not update the size, as it could
				// make child widgets miscalculate.
				for(var i = 0; i < this._parents.length; i++){
					var p = this._parents[i];
					var sel = p.parent.selectedChildWidget
					if(sel && sel != p.child){
						return;
					}
				}

				if(this._size){
					// If the size of the portlet hasn't changed, don't
					// resize the children, as this can be expensive
					if(this._size.w == size.w && this._size.h == size.h){
						return;
					}
				}
				this._size = size;

				var fns = ["resize", "layout"];
				this._timer = null;
				var kids = this.getChildren();

				dojo.forEach(kids, function(child){
					for(var i = 0; i < fns.length; i++){
						if(dojo.isFunction(child[fns[i]])){
							try{
								child[fns[i]]();
							} catch(e){
								console.log(e);
							}
							break;
						}
					}
				});
				this.onUpdateSize();
			}), 100);
		},

		onUpdateSize: function(){
			// summary:
			//		Stub function called when the size is changed.
		},

		_publish: function(){
			// summary:
			//		Publishes an event that all other portlets listen to.
			//		This causes them to update their child widgets if their
			//		size has changed.
			dojo.publish("/Portlet/sizechange",[this]);
		},

		_onTitleClick: function(evt){
			if(evt.target == this.arrowNode){
				this.inherited(arguments);
			}
		},

		addChild: function(child){
			// summary:
			//		Adds a child widget to the portlet.
			this._size = null;
			this.inherited(arguments);

			if(this._started){
				this._placeSettingsWidgets();
				this._updateSize();
			}
			if(this._started && !child.started && !child._started){
				child.startup();
			}
		},

		destroyDescendants: function(/*Boolean*/ preserveDom){
			this.inherited(arguments);
			if(this._settingsWidget){
				this._settingsWidget.destroyRecursive(preserveDom);
			}
		},

		destroy: function(){
			if(this._timer){
				clearTimeout(this._timer);
			}
			this.inherited(arguments);
		},

		_setCss: function(){
			this.inherited(arguments);
			dojo.style(this.arrowNode, "display", this.toggleable ? "":"none");
		}
	});
});<|endoftext|>


<commit_before>GLClient.controller('AdminCtrl',
    ['$scope', '$rootScope', '$http', '$route', '$location', 'Admin', 'Node', 'GLCache', 'CONSTANTS',
function($scope, $rootScope, $http, $route, $location, Admin, Node, GLCache, CONSTANTS) {

  $scope.email_regexp = CONSTANTS.email_regexp;
  $scope.https_regexp = CONSTANTS.https_regexp;
  $scope.http_or_https_regexp = CONSTANTS.http_or_https_regexp;
  $scope.timezones = CONSTANTS.timezones;

  // XXX this should actually be defined per controller
  // otherwise every time you open a new page the button appears enabled
  // because such item is !=
  $scope.master = {};

  // XXX convert this to a directive
  // This is used for setting the current menu in the sidebar
  var current_menu = $location.path().split('/').slice(-1);
  $scope.active = {};
  $scope.active[current_menu] = "active";

  $scope.admin = new Admin();

  $scope.languages_enabled_edit = {};
  $scope.languages_enabled_selector = {};

  function CollapseLanguages($scope) {
    $scope.isCollapsed = false;
  }

  Node.get(function(node) {
    $scope.languages_supported = {};
    $scope.languages_enabled = [];
    $scope.languages_enabled_selector = [];
    $.each(node.languages_supported, function(idx) {
      var code = node.languages_supported[idx]['code'];
      $scope.languages_supported[code] = node.languages_supported[idx]['name'];
      if ($.inArray(code, node.languages_enabled) != -1) {
        $scope.languages_enabled[code] = node.languages_supported[idx]['name'];
        $scope.languages_enabled_selector.push({"name": node.languages_supported[idx]['name'],"code": code});
      }
    });

    $scope.$watch('languages_enabled', function(){
      if ($scope.languages_enabled) {
        $scope.languages_enabled_edit = {};
        $.each($scope.languages_supported, function(lang){
          $scope.languages_enabled_edit[lang] = lang in $scope.languages_enabled;
        });
      }

    });

    $scope.$watch('languages_enabled_edit', function() {
      if ($scope.languages_enabled) {
        var languages_enabled_selector = [];
        var change_default = false;
        var language_selected = $scope.admin.node.default_language;
        if (! $scope.languages_enabled_edit[$scope.admin.node.default_language]) {
          change_default = true;
        }

        $.each($scope.languages_supported, function(lang) {
          if ($scope.languages_enabled_edit[lang]) {
            languages_enabled_selector.push({'name': $scope.languages_supported[lang], 'code': lang});

            if (change_default === true) {
              language_selected = lang;
              change_default = false;
            }
          }
        });

        var languages_enabled = [];
        $.each($scope.languages_enabled_edit, function(lang, enabled) {
          if (enabled) {
            languages_enabled.push(lang);
          }
        });

        $scope.admin.node.default_language = language_selected;
        $scope.admin.node.languages_enabled = languages_enabled;

        $scope.languages_enabled_selector = languages_enabled_selector;

      }
    });
  });

  // We need to have a special function for updating the node since we need to add old_password and password attribute
  // if they are not present
  $scope.updateNode = function(node) {

    if (node.password === undefined)
      node.password = "";
    if (node.check_password === undefined)
      node.password = "";
    if (node.old_password === undefined)
      node.old_password = "";

    var cb = function() {
      $rootScope.$broadcast("REFRESH");
    }

    $scope.update(node, cb);
  }

}]);

GLClient.controller('AdminPasswordCtrl', ['$scope', 'changePasswordWatcher',
                    function($scope, changePasswordWatcher) {
    changePasswordWatcher($scope, "admin.node.old_password",
        "admin.node.password", "admin.node.check_password");
}]);

GLClient.controller('AdminFileUploadCtrl', ['$scope', '$http', function($scope, $http){

    $scope.random = Math.round(Math.random()*1000000);

    $scope.uploadfile = false;

    $scope.fileSelected = false;
    $scope.markFileSelected = function () {
      $scope.fileSelected = true;
    };

    $scope.openUploader = function () {
      $scope.uploadfile = true;
    };

    $scope.closeUploader = function () {
      $scope.uploadfile = $scope.fileSelected = false;
    };

    $scope.receiverImgUrl = function () {
      return "/admin/staticfiles/" + $scope.receiver.id;
    };

    $scope.receiverImgReloadUrl = function() {
      return "/static/" + $scope.receiver.id + ".png?" + $scope.random;
    }

}]);

GLClient.controller('AdminContentCtrl', ['$scope', '$http', 'StaticFiles', 'DefaultAppdata',
  function($scope, $http, StaticFiles, DefaultAppdata){
  $scope.tabs = [
    {
      title:"Main Configuration",
      template: "views/admin/content/tab1.html",
      ctrl: TabCtrl
    },
    {
      title:"Theme Customization",
      template: "views/admin/content/tab2.html",
      ctrl: TabCtrl
    },
    {
      title: "Translation Customization",
      template: "views/admin/content/tab3.html",
      ctrl: TabCtrl
    }
  ];

  $scope.install_default_fields = function () {

    DefaultAppdata.get(function (res) {

      $http.post('/admin/appdata', res).success(function (response) {

      });

    });
  };

  $scope.update_static_files = function () {
    var updated_staticfiles = StaticFiles.query(function () {
      $scope.staticfiles = updated_staticfiles;
    });
  };

  $scope.uploadfinished = function () {
    $scope.update_static_files();
  };

  $scope.perform_delete = function (url) {
    $http['delete'](url).success(function (response) {
      $scope.update_static_files();
    });
  };

  $scope.update_static_files();

}]);

GLClient.controller('AdminMailCtrl', ['$scope', '$http', function($scope, $http){
  $scope.tabs = [
    {
      title:"Main Configuration",
      template:"views/admin/mail/tab1.html",
      ctrl: TabCtrl
    },
    {
      title:"Plaintext Notification Templates",
      template:"views/admin/mail/tab2.html",
      ctrl: TabCtrl
    },
    {
      title:"Encrypted Notification Templates",
      template:"views/admin/mail/tab3.html",
      ctrl: TabCtrl
    }
  ];
}]);

GLClient.controller('AdminAdvancedCtrl', ['$scope', '$http', '$modal',
                    function($scope, $http, $modal){
  $scope.tabs = [
    {
      title:"Main Configuration",
      template:"views/admin/advanced/tab1.html",
      ctrl: TabCtrl
    },
    {
      title:"Tor2web Settings",
      template:"views/admin/advanced/tab2.html",
      ctrl: TabCtrl
    }
  ];
  $scope.open_modal_allow_unencrypted = function() {
    if ($scope.admin.node.allow_unencrypted)
      return;
    var modalInstance = $modal.open({
      templateUrl: 'views/partials/disable_encryption.html',
      controller: 'DisableEncryptionCtrl',
    });

    modalInstance.result.then(function(result){
      $scope.admin.node.allow_unencrypted = result;
    });
  };

}]);

ConfirmableDialogCtrl = ['$scope', '$modalInstance', 'object', function($scope, $modalInstance, object) {
  $scope.object = object;

  $scope.ok = function () {
    $modalInstance.close($scope.object);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
}];
<commit_msg>languages_enabled edit need to be watched with objectequality=true<commit_after>GLClient.controller('AdminCtrl',
    ['$scope', '$rootScope', '$http', '$route', '$location', 'Admin', 'Node', 'GLCache', 'CONSTANTS',
function($scope, $rootScope, $http, $route, $location, Admin, Node, GLCache, CONSTANTS) {

  $scope.email_regexp = CONSTANTS.email_regexp;
  $scope.https_regexp = CONSTANTS.https_regexp;
  $scope.http_or_https_regexp = CONSTANTS.http_or_https_regexp;
  $scope.timezones = CONSTANTS.timezones;

  // XXX this should actually be defined per controller
  // otherwise every time you open a new page the button appears enabled
  // because such item is !=
  $scope.master = {};

  // XXX convert this to a directive
  // This is used for setting the current menu in the sidebar
  var current_menu = $location.path().split('/').slice(-1);
  $scope.active = {};
  $scope.active[current_menu] = "active";

  $scope.admin = new Admin();

  $scope.languages_enabled_edit = {};
  $scope.languages_enabled_selector = {};

  function CollapseLanguages($scope) {
    $scope.isCollapsed = false;
  }

  Node.get(function(node) {
    $scope.languages_supported = {};
    $scope.languages_enabled = [];
    $scope.languages_enabled_selector = [];
    $.each(node.languages_supported, function(idx) {
      var code = node.languages_supported[idx]['code'];
      $scope.languages_supported[code] = node.languages_supported[idx]['name'];
      if ($.inArray(code, node.languages_enabled) != -1) {
        $scope.languages_enabled[code] = node.languages_supported[idx]['name'];
        $scope.languages_enabled_selector.push({"name": node.languages_supported[idx]['name'],"code": code});
      }
    });

    $scope.$watch('languages_enabled', function(){
      if ($scope.languages_enabled) {
        $scope.languages_enabled_edit = {};
        $.each($scope.languages_supported, function(lang){
          $scope.languages_enabled_edit[lang] = lang in $scope.languages_enabled;
        });
      }

    }, true);

    $scope.$watch('languages_enabled_edit', function() {
      if ($scope.languages_enabled) {
        var languages_enabled_selector = [];
        var change_default = false;
        var language_selected = $scope.admin.node.default_language;
        if (! $scope.languages_enabled_edit[$scope.admin.node.default_language]) {
          change_default = true;
        }

        $.each($scope.languages_supported, function(lang) {
          if ($scope.languages_enabled_edit[lang]) {
            languages_enabled_selector.push({'name': $scope.languages_supported[lang], 'code': lang});

            if (change_default === true) {
              language_selected = lang;
              change_default = false;
            }
          }
        });

        var languages_enabled = [];
        $.each($scope.languages_enabled_edit, function(lang, enabled) {
          if (enabled) {
            languages_enabled.push(lang);
          }
        });

        $scope.admin.node.default_language = language_selected;
        $scope.admin.node.languages_enabled = languages_enabled;

        $scope.languages_enabled_selector = languages_enabled_selector;

      }
    }, true);
  });

  // We need to have a special function for updating the node since we need to add old_password and password attribute
  // if they are not present
  $scope.updateNode = function(node) {

    if (node.password === undefined)
      node.password = "";
    if (node.check_password === undefined)
      node.password = "";
    if (node.old_password === undefined)
      node.old_password = "";

    var cb = function() {
      $rootScope.$broadcast("REFRESH");
    }

    $scope.update(node, cb);
  }

}]);

GLClient.controller('AdminPasswordCtrl', ['$scope', 'changePasswordWatcher',
                    function($scope, changePasswordWatcher) {
    changePasswordWatcher($scope, "admin.node.old_password",
        "admin.node.password", "admin.node.check_password");
}]);

GLClient.controller('AdminFileUploadCtrl', ['$scope', '$http', function($scope, $http){

    $scope.random = Math.round(Math.random()*1000000);

    $scope.uploadfile = false;

    $scope.fileSelected = false;
    $scope.markFileSelected = function () {
      $scope.fileSelected = true;
    };

    $scope.openUploader = function () {
      $scope.uploadfile = true;
    };

    $scope.closeUploader = function () {
      $scope.uploadfile = $scope.fileSelected = false;
    };

    $scope.receiverImgUrl = function () {
      return "/admin/staticfiles/" + $scope.receiver.id;
    };

    $scope.receiverImgReloadUrl = function() {
      return "/static/" + $scope.receiver.id + ".png?" + $scope.random;
    }

}]);

GLClient.controller('AdminContentCtrl', ['$scope', '$http', 'StaticFiles', 'DefaultAppdata',
  function($scope, $http, StaticFiles, DefaultAppdata){
  $scope.tabs = [
    {
      title:"Main Configuration",
      template: "views/admin/content/tab1.html",
      ctrl: TabCtrl
    },
    {
      title:"Theme Customization",
      template: "views/admin/content/tab2.html",
      ctrl: TabCtrl
    },
    {
      title: "Translation Customization",
      template: "views/admin/content/tab3.html",
      ctrl: TabCtrl
    }
  ];

  $scope.install_default_fields = function () {

    DefaultAppdata.get(function (res) {

      $http.post('/admin/appdata', res).success(function (response) {

      });

    });
  };

  $scope.update_static_files = function () {
    var updated_staticfiles = StaticFiles.query(function () {
      $scope.staticfiles = updated_staticfiles;
    });
  };

  $scope.uploadfinished = function () {
    $scope.update_static_files();
  };

  $scope.perform_delete = function (url) {
    $http['delete'](url).success(function (response) {
      $scope.update_static_files();
    });
  };

  $scope.update_static_files();

}]);

GLClient.controller('AdminMailCtrl', ['$scope', '$http', function($scope, $http){
  $scope.tabs = [
    {
      title:"Main Configuration",
      template:"views/admin/mail/tab1.html",
      ctrl: TabCtrl
    },
    {
      title:"Plaintext Notification Templates",
      template:"views/admin/mail/tab2.html",
      ctrl: TabCtrl
    },
    {
      title:"Encrypted Notification Templates",
      template:"views/admin/mail/tab3.html",
      ctrl: TabCtrl
    }
  ];
}]);

GLClient.controller('AdminAdvancedCtrl', ['$scope', '$http', '$modal',
                    function($scope, $http, $modal){
  $scope.tabs = [
    {
      title:"Main Configuration",
      template:"views/admin/advanced/tab1.html",
      ctrl: TabCtrl
    },
    {
      title:"Tor2web Settings",
      template:"views/admin/advanced/tab2.html",
      ctrl: TabCtrl
    }
  ];
  $scope.open_modal_allow_unencrypted = function() {
    if ($scope.admin.node.allow_unencrypted)
      return;
    var modalInstance = $modal.open({
      templateUrl: 'views/partials/disable_encryption.html',
      controller: 'DisableEncryptionCtrl',
    });

    modalInstance.result.then(function(result){
      $scope.admin.node.allow_unencrypted = result;
    });
  };

}]);

ConfirmableDialogCtrl = ['$scope', '$modalInstance', 'object', function($scope, $modalInstance, object) {
  $scope.object = object;

  $scope.ok = function () {
    $modalInstance.close($scope.object);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
}];
<|endoftext|>


<commit_before>export default {
  navigatorButton: "[data-test-id='Navigator'] [data-test-id='Button']",
  navigationDrawerLoginButton: "[data-test-id='NavDrawerLoginButton']",
  navigationDrawerEntry: "[data-test-id='NavDrawer'] [data-test-id='Ripple'] span",
  shopLogo: "[data-test-id='Navigator'] img[alt='TestAutomation']",
  imageSliderImage1: "[data-test-id='Slider']:nth-child(2)  img[data-test-id='withoutLink']",
  imageSliderImage2: "[data-test-id='Slider']:nth-child(3)  img[data-test-id='withoutLink']",
  imageWidgetWithLink1: "[data-test-id='imageWidget: /category/3537']",
  productSliderProduct1: "[data-test-id='Slider'] [data-test-id='link: /item/393239']",
  liveShoppingWidgetWithExpectedProduct: "[data-test-id='liveShoppingWidget'] [data-test-id='link: /item/393132']",
  productGridWidgetFirstProduct: "[data-test-id='productGrid'] [data-test-id='link: /item/393939']",
  productListWidgetFirstProduct: "[data-test-id='productList'] [data-test-id='link: /item/393939']",
  categoryListWidgetFirstProduct: "[data-test-id='categoryList'] [data-test-id='link: /category/3537']",
  allProductCategory: "[data-test-id='link: /category/3733']",
  allProductsCategoryTitle: "[data-test-id='title: 4. all products']",
  filterButton: "[data-test-id='filterBar'] [data-test-id='filterButton']",
  backButton: "[data-test-id='backButton']",
  searchButton: "[data-test-id='SearchButton']",
  sortingDropDown: "[data-test-id='sorting']",
  viewSwitch: "[data-test-id='viewSwitch']",
  productWithManyProps4GridViewImage: "[data-test-id='productGrid'] img[alt='Product with many Properties - 4 -']",
  productWithManyProps4GridViewName: "[style='display: block;'] [data-test-id='productGrid'] [data-test-id='Productname: Product with many Properties - 4 -']",
  productWithManyProps4GridViewFavButton: "[data-test-id='link: /item/393939'] [data-test-id='favorites'] [data-test-id='button']",
  productWithManyProps4GridViewPrice: "[data-test-id='productGrid'] [data-test-id='link: /item/393939'] [data-test-id='minPrice: 0 price: 199 currency: EUR']",
  productWithManyProps4ListViewImage: "[data-test-id='productList'] img[alt='Product with many Properties - 4 -']",
  productWithManyProps4ListViewName: "[data-test-id='productList'] [data-test-id='Productname: Product with many Properties - 4 -']",
  productWithManyProps4ListViewPrice: "[data-test-id='productList'] [data-test-id='link: /item/393939'] [data-test-id='minPrice: 0 price: 199 currency: EUR']",
  productWithStrikePrice4GridViewStrikePrice: "[data-test-id='productGrid'] [data-test-id='link: /item/31303634'] [data-test-id='strikedPrice: 10']",
  productWithStrikePrice4GridViewDiscountBadge: "[data-test-id='productGrid'] [data-test-id='link: /item/31303634'] [data-test-id='-1%']",
  productWithStrikePrice4GridViewPrice: "[data-test-id='productGrid'] [data-test-id='link: /item/31303634'] [data-test-id='minPrice: 0 price: 9.95 currency: EUR']",
  productWithStrikePrice4listViewStrikePrice: "[data-test-id='productList'] [data-test-id='link: /item/31303634'] [data-test-id='strikedPrice: 10']",
  productWithStrikePrice4ListViewDiscountBadge: "[data-test-id='productList'] [data-test-id='link: /item/31303634'] [data-test-id='-1%']",
  productWithStrikePrice4ListViewPrice: "[data-test-id='productList'] [data-test-id='link: /item/31303634'] [data-test-id='minPrice: 0 price: 9.95 currency: EUR']",
  productWithRating4GridViewRatingStars: "[data-test-id='productGrid'] [data-test-id='link: /item/393430'] [data-test-id='ratedStars: 5']",
  productWithRating4ListViewRatingStars: "[data-test-id='productList'] [data-test-id='link: /item/393430'] [data-test-id='ratedStars: 5']",
  productWithManyProps4ProductPageImage: "[data-test-id='product: Product with many Properties - 4 -'] [data-test-id='image']",
  productWithManyProps4ProductPagName: "[data-test-id='name: Product with many Properties - 4 -']",
  productWithManyProps4ProductPageTitle: "[data-test-id='title: Product with many Properties - 4 -']",
  productWithManyProps4ProductPageAvailabilityText: "[data-test-id='availabilityText: In stock']",
  productWithManufacturerPropManufacturerProp: "[data-test-id='manufacturer: supa dupa Company']",
  productWithManufacturerPropManufacturerPropList: "[data-test-id='property: supa dupa Company']",
  productWithManufacturerPropProductDetailPagePrice: "[data-test-id='minPrice: 0 price: 5 currency: EUR']",
  productWithManufactruerPropProductDetailPageDescription: "[data-test-id='Product with manufacture prop']",
  addToCartButton: "[data-test-id='AddToCartButton']",
  favoriteButton: "[data-test-id='favoriteButton']",
  ReviewSection: "[data-test-id='reviewSection']",
  taxDisclaimer: "[data-test-id='taxDisclaimer']",
  writeReviewButton: "[data-test-id='writeReview']",
  variantsPicker: "[data-test-id='variantsPicker']",
  variantPickerColor: "[data-test-id='Color']",
  variantPickerShoeSize: "[data-test-id='Shoe size']",
  optionsPicker: "[data-test-id='optionsPicker']",
  optionPickerBallColor: "[data-test-id='Ball color']",
  optionPickerGlow: "[data-test-id='glow']",
  ratingStars: "[data-test-id='ratedStarsAverage']",
  productWithRating3Review1Title: "[data-test-id='reviewTitle: test2']",
  productWithRating3Review2Title: "[data-test-id='reviewTitle: test3']",
  showAllReviewsButton: "[data-test-id='showAllReviewsButton']",
  productWithBasePrice1basePrice: "[data-test-id='priceInfo: €10.00 / 1 kg']",
  productWithStrikePrice4StrikePrice: "[data-test-id='strikedPrice: 10']",
};
<commit_msg>PWA-334 fix for fav button selector<commit_after>export default {
  navigatorButton: "[data-test-id='Navigator'] [data-test-id='Button']",
  navigationDrawerLoginButton: "[data-test-id='NavDrawerLoginButton']",
  navigationDrawerEntry: "[data-test-id='NavDrawer'] [data-test-id='Ripple'] span",
  shopLogo: "[data-test-id='Navigator'] img[alt='TestAutomation']",
  imageSliderImage1: "[data-test-id='Slider']:nth-child(2)  img[data-test-id='withoutLink']",
  imageSliderImage2: "[data-test-id='Slider']:nth-child(3)  img[data-test-id='withoutLink']",
  imageWidgetWithLink1: "[data-test-id='imageWidget: /category/3537']",
  productSliderProduct1: "[data-test-id='Slider'] [data-test-id='link: /item/393239']",
  liveShoppingWidgetWithExpectedProduct: "[data-test-id='liveShoppingWidget'] [data-test-id='link: /item/393132']",
  productGridWidgetFirstProduct: "[data-test-id='productGrid'] [data-test-id='link: /item/393939']",
  productListWidgetFirstProduct: "[data-test-id='productList'] [data-test-id='link: /item/393939']",
  categoryListWidgetFirstProduct: "[data-test-id='categoryList'] [data-test-id='link: /category/3537']",
  allProductCategory: "[data-test-id='link: /category/3733']",
  allProductsCategoryTitle: "[data-test-id='title: 4. all products']",
  filterButton: "[data-test-id='filterBar'] [data-test-id='filterButton']",
  backButton: "[data-test-id='backButton']",
  searchButton: "[data-test-id='SearchButton']",
  sortingDropDown: "[data-test-id='sorting']",
  viewSwitch: "[data-test-id='viewSwitch']",
  productWithManyProps4GridViewImage: "[data-test-id='productGrid'] img[alt='Product with many Properties - 4 -']",
  productWithManyProps4GridViewName: "[style='display: block;'] [data-test-id='productGrid'] [data-test-id='Productname: Product with many Properties - 4 -']",
  productWithManyProps4GridViewFavButton: "[data-test-id='link: /item/393939'] [data-test-id='favorites'] [data-test-id='favoriteButton']",
  productWithManyProps4GridViewPrice: "[data-test-id='productGrid'] [data-test-id='link: /item/393939'] [data-test-id='minPrice: 0 price: 199 currency: EUR']",
  productWithManyProps4ListViewImage: "[data-test-id='productList'] img[alt='Product with many Properties - 4 -']",
  productWithManyProps4ListViewName: "[data-test-id='productList'] [data-test-id='Productname: Product with many Properties - 4 -']",
  productWithManyProps4ListViewPrice: "[data-test-id='productList'] [data-test-id='link: /item/393939'] [data-test-id='minPrice: 0 price: 199 currency: EUR']",
  productWithStrikePrice4GridViewStrikePrice: "[data-test-id='productGrid'] [data-test-id='link: /item/31303634'] [data-test-id='strikedPrice: 10']",
  productWithStrikePrice4GridViewDiscountBadge: "[data-test-id='productGrid'] [data-test-id='link: /item/31303634'] [data-test-id='-1%']",
  productWithStrikePrice4GridViewPrice: "[data-test-id='productGrid'] [data-test-id='link: /item/31303634'] [data-test-id='minPrice: 0 price: 9.95 currency: EUR']",
  productWithStrikePrice4listViewStrikePrice: "[data-test-id='productList'] [data-test-id='link: /item/31303634'] [data-test-id='strikedPrice: 10']",
  productWithStrikePrice4ListViewDiscountBadge: "[data-test-id='productList'] [data-test-id='link: /item/31303634'] [data-test-id='-1%']",
  productWithStrikePrice4ListViewPrice: "[data-test-id='productList'] [data-test-id='link: /item/31303634'] [data-test-id='minPrice: 0 price: 9.95 currency: EUR']",
  productWithRating4GridViewRatingStars: "[data-test-id='productGrid'] [data-test-id='link: /item/393430'] [data-test-id='ratedStars: 5']",
  productWithRating4ListViewRatingStars: "[data-test-id='productList'] [data-test-id='link: /item/393430'] [data-test-id='ratedStars: 5']",
  productWithManyProps4ProductPageImage: "[data-test-id='product: Product with many Properties - 4 -'] [data-test-id='image']",
  productWithManyProps4ProductPagName: "[data-test-id='name: Product with many Properties - 4 -']",
  productWithManyProps4ProductPageTitle: "[data-test-id='title: Product with many Properties - 4 -']",
  productWithManyProps4ProductPageAvailabilityText: "[data-test-id='availabilityText: In stock']",
  productWithManufacturerPropManufacturerProp: "[data-test-id='manufacturer: supa dupa Company']",
  productWithManufacturerPropManufacturerPropList: "[data-test-id='property: supa dupa Company']",
  productWithManufacturerPropProductDetailPagePrice: "[data-test-id='minPrice: 0 price: 5 currency: EUR']",
  productWithManufactruerPropProductDetailPageDescription: "[data-test-id='Product with manufacture prop']",
  addToCartButton: "[data-test-id='AddToCartButton']",
  favoriteButton: "[data-test-id='favoriteButton']",
  ReviewSection: "[data-test-id='reviewSection']",
  taxDisclaimer: "[data-test-id='taxDisclaimer']",
  writeReviewButton: "[data-test-id='writeReview']",
  variantsPicker: "[data-test-id='variantsPicker']",
  variantPickerColor: "[data-test-id='Color']",
  variantPickerShoeSize: "[data-test-id='Shoe size']",
  optionsPicker: "[data-test-id='optionsPicker']",
  optionPickerBallColor: "[data-test-id='Ball color']",
  optionPickerGlow: "[data-test-id='glow']",
  ratingStars: "[data-test-id='ratedStarsAverage']",
  productWithRating3Review1Title: "[data-test-id='reviewTitle: test2']",
  productWithRating3Review2Title: "[data-test-id='reviewTitle: test3']",
  showAllReviewsButton: "[data-test-id='showAllReviewsButton']",
  productWithBasePrice1basePrice: "[data-test-id='priceInfo: €10.00 / 1 kg']",
  productWithStrikePrice4StrikePrice: "[data-test-id='strikedPrice: 10']",
};
<|endoftext|>