<commit_before>const {EditorState} = require("prosemirror-state")
const {schema, eq, doc, blockquote, p, li, ol, ul} = require("prosemirror-test-builder")
const {selFor} = require("prosemirror-state/test/state")
const ist = require("ist")
const {wrapInList, splitListItem, liftListItem, sinkListItem} = require("../dist/schema-list")

function apply(doc, command, result) {
  let state = EditorState.create({doc, selection: selFor(doc)})
  command(state, tr => state = state.apply(tr))
  ist(state.doc, result || doc, eq)
}

describe("wrapInList", () => {
  let wrap = wrapInList(schema.nodes.bullet_list)
  let wrapo = wrapInList(schema.nodes.ordered_list)

  it("can wrap a paragraph", () =>
     apply(doc(p("foo")), wrap, doc(ul(li(p("foo"))))))

  it("can wrap a nested paragraph", () =>
     apply(doc(blockquote(p("foo"))), wrapo, doc(blockquote(ol(li(p("foo")))))))

  it("can wrap multiple paragraphs", () =>
     apply(doc(p("foo"), p("bar"), p("baz")), wrap,
           doc(p("foo"), ul(li(p("bar")), li(p("baz"))))))

  it("doesn't wrap the first paragraph in a list item", () =>
     apply(doc(ul(li(p("foo")))), wrap, null))

  it("doesn't wrap the first para in a different type of list item", () =>
     apply(doc(ol(li(p("foo")))), wrapo, null))

  it("does wrap the second paragraph in a list item", () =>
     apply(doc(ul(li(p("foo"), p("bar")))), wrap, doc(ul(li(p("foo"), ul(li(p("bar"))))))))

  it("joins with the list item above when wrapping its first paragraph", () =>
     apply(doc(ul(li(p("foo")), li(p("bar")), li(p("baz")))), wrapo,
           doc(ul(li(p("foo"), ol(li(p("bar")))), li(p("baz"))))))
})

describe("splitListItem", () => {
  let split = splitListItem(schema.nodes.list_item)

  it("has no effect outside of a list", () =>
     apply(doc(p("foobar")), split, null))

  it("has no effect on the top level", () =>
     apply(doc("", p("foobar")), split, null))

  it("can split a list item", () =>
    apply(doc(ul(li(p("foobar")))), split, doc(ul(li(p("foo")), li(p("bar"))))))

  it("deletes selected content", () =>
     apply(doc(ul(li(p("foobar")))), split,
           doc(ul(li(p("foo")), li(p("r"))))))
})

describe("liftListItem", () => {
  let lift = liftListItem(schema.nodes.list_item)

  it("can lift from a nested list", () =>
     apply(doc(ul(li(p("hello"), ul(li(p("one")), li(p("two")))))), lift,
           doc(ul(li(p("hello")), li(p("one"), ul(li(p("two"))))))))

  it("can lift two items from a nested list", () =>
     apply(doc(ul(li(p("hello"), ul(li(p("one")), li(p("two")))))), lift,
           doc(ul(li(p("hello")), li(p("one")), li(p("two"))))))

  it("can lift two items from a nested three-item list", () =>
     apply(doc(ul(li(p("hello"), ul(li(p("one")), li(p("two")), li(p("three")))))), lift,
           doc(ul(li(p("hello")), li(p("one")), li(p("two"), ul(li(p("three"))))))))

  it("can lift an item out of a list", () =>
     apply(doc(p("a"), ul(li(p("b"))), p("c")), lift,
           doc(p("a"), p("b"), p("c"))))

  it("can lift two items out of a list", () =>
     apply(doc(p("a"), ul(li(p("b")), li(p("c"))), p("d")), lift,
           doc(p("a"), p("b"), p("c"), p("d"))))

  it("can lift three items from the middle of a list", () =>
     apply(doc(ul(li(p("a")), li(p("b")), li(p("c")), li(p("d")), li(p("e")))), lift,
           doc(ul(li(p("a"))), p("b"), p("c"), p("d"), ul(li(p("e"))))))

  it("can lift the first item from a list", () =>
     apply(doc(ul(li(p("a")), li(p("b")), li(p("c")))), lift,
           doc(p("a"), ul(li(p("b")), li(p("c"))))))

  it("can lift the last item from a list", () =>
     apply(doc(ul(li(p("a")), li(p("b")), li(p("c")))), lift,
           doc(ul(li(p("a")), li(p("b"))), p("c"))))
})

describe("sinkListItem", () => {
  let sink = sinkListItem(schema.nodes.list_item)

  it("can wrap a simple item in a list", () =>
     apply(doc(ul(li(p("one")), li(p("two")), li(p("three")))), sink,
           doc(ul(li(p("one"), ul(li(p("two")))), li(p("three"))))))

  it("won't wrap the first item in a sublist", () =>
    apply(doc(ul(li(p("one")), li(p("two")), li(p("three")))), sink, null))

  it("will move an item's content into the item above", () =>
     apply(doc(ul(li(p("one")), li(p("..."), ul(li(p("two")))), li(p("three")))), sink,
           doc(ul(li(p("one")), li(p("..."), ul(li(p("two")), li(p("three"))))))))
})
<commit_msg>Add test for splitting at the end of the list item<commit_after>const {EditorState} = require("prosemirror-state")
const {schema, eq, doc, blockquote, p, li, ol, ul} = require("prosemirror-test-builder")
const {selFor} = require("prosemirror-state/test/state")
const ist = require("ist")
const {wrapInList, splitListItem, liftListItem, sinkListItem} = require("../dist/schema-list")

function apply(doc, command, result) {
  let state = EditorState.create({doc, selection: selFor(doc)})
  command(state, tr => state = state.apply(tr))
  ist(state.doc, result || doc, eq)
}

describe("wrapInList", () => {
  let wrap = wrapInList(schema.nodes.bullet_list)
  let wrapo = wrapInList(schema.nodes.ordered_list)

  it("can wrap a paragraph", () =>
     apply(doc(p("foo")), wrap, doc(ul(li(p("foo"))))))

  it("can wrap a nested paragraph", () =>
     apply(doc(blockquote(p("foo"))), wrapo, doc(blockquote(ol(li(p("foo")))))))

  it("can wrap multiple paragraphs", () =>
     apply(doc(p("foo"), p("bar"), p("baz")), wrap,
           doc(p("foo"), ul(li(p("bar")), li(p("baz"))))))

  it("doesn't wrap the first paragraph in a list item", () =>
     apply(doc(ul(li(p("foo")))), wrap, null))

  it("doesn't wrap the first para in a different type of list item", () =>
     apply(doc(ol(li(p("foo")))), wrapo, null))

  it("does wrap the second paragraph in a list item", () =>
     apply(doc(ul(li(p("foo"), p("bar")))), wrap, doc(ul(li(p("foo"), ul(li(p("bar"))))))))

  it("joins with the list item above when wrapping its first paragraph", () =>
     apply(doc(ul(li(p("foo")), li(p("bar")), li(p("baz")))), wrapo,
           doc(ul(li(p("foo"), ol(li(p("bar")))), li(p("baz"))))))
})

describe("splitListItem", () => {
  let split = splitListItem(schema.nodes.list_item)

  it("has no effect outside of a list", () =>
     apply(doc(p("foobar")), split, null))

  it("has no effect on the top level", () =>
     apply(doc("", p("foobar")), split, null))

  it("can split a list item", () =>
    apply(doc(ul(li(p("foobar")))), split, doc(ul(li(p("foo")), li(p("bar"))))))

  it("can split a list item at the end", () =>
    apply(doc(ul(li(p("foobar")))), split, doc(ul(li(p("foobar")), li(p())))))

  it("deletes selected content", () =>
     apply(doc(ul(li(p("foobar")))), split,
           doc(ul(li(p("foo")), li(p("r"))))))
})

describe("liftListItem", () => {
  let lift = liftListItem(schema.nodes.list_item)

  it("can lift from a nested list", () =>
     apply(doc(ul(li(p("hello"), ul(li(p("one")), li(p("two")))))), lift,
           doc(ul(li(p("hello")), li(p("one"), ul(li(p("two"))))))))

  it("can lift two items from a nested list", () =>
     apply(doc(ul(li(p("hello"), ul(li(p("one")), li(p("two")))))), lift,
           doc(ul(li(p("hello")), li(p("one")), li(p("two"))))))

  it("can lift two items from a nested three-item list", () =>
     apply(doc(ul(li(p("hello"), ul(li(p("one")), li(p("two")), li(p("three")))))), lift,
           doc(ul(li(p("hello")), li(p("one")), li(p("two"), ul(li(p("three"))))))))

  it("can lift an item out of a list", () =>
     apply(doc(p("a"), ul(li(p("b"))), p("c")), lift,
           doc(p("a"), p("b"), p("c"))))

  it("can lift two items out of a list", () =>
     apply(doc(p("a"), ul(li(p("b")), li(p("c"))), p("d")), lift,
           doc(p("a"), p("b"), p("c"), p("d"))))

  it("can lift three items from the middle of a list", () =>
     apply(doc(ul(li(p("a")), li(p("b")), li(p("c")), li(p("d")), li(p("e")))), lift,
           doc(ul(li(p("a"))), p("b"), p("c"), p("d"), ul(li(p("e"))))))

  it("can lift the first item from a list", () =>
     apply(doc(ul(li(p("a")), li(p("b")), li(p("c")))), lift,
           doc(p("a"), ul(li(p("b")), li(p("c"))))))

  it("can lift the last item from a list", () =>
     apply(doc(ul(li(p("a")), li(p("b")), li(p("c")))), lift,
           doc(ul(li(p("a")), li(p("b"))), p("c"))))
})

describe("sinkListItem", () => {
  let sink = sinkListItem(schema.nodes.list_item)

  it("can wrap a simple item in a list", () =>
     apply(doc(ul(li(p("one")), li(p("two")), li(p("three")))), sink,
           doc(ul(li(p("one"), ul(li(p("two")))), li(p("three"))))))

  it("won't wrap the first item in a sublist", () =>
    apply(doc(ul(li(p("one")), li(p("two")), li(p("three")))), sink, null))

  it("will move an item's content into the item above", () =>
     apply(doc(ul(li(p("one")), li(p("..."), ul(li(p("two")))), li(p("three")))), sink,
           doc(ul(li(p("one")), li(p("..."), ul(li(p("two")), li(p("three"))))))))
})
<|endoftext|>


<commit_before>/*global describe, beforeEach, it, after*/
'use strict';

var path = require('path');
var temp = require('temp');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;

describe('Test prompt validations', function () {

  var app;

  after(function () {
    temp.cleanup();
  });

  it('App name has invalid character and should fail', function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'Test App',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;

      app.run({}, function () {
        assert.ok(typeof app.prompt.errors !== 'undefined', 'This should fail if the app name contains a space.');
        assert.ok(app.prompt.errors.length === 1, 'There should be only 1 error.');
        assert.ok(app.prompt.errors[0].name === 'appName', 'The appName property should be wrong.');
        assert.ok(app.prompt.errors[0].message === 'The application name should only consist of the following characters a-z, A-Z and 0-9.', 'The appName property should be wrong.');
        done();
      });
    });
  });
});

describe('node-webkit generator', function () {
  var app;

  after(function () {
    temp.cleanup();
  });

  beforeEach(function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      done();
    });
  });

  it('Creates dot files', function (done) {
    var expected = [
      '.jshintrc',
      '.editorconfig'
    ];

    app.run({}, function () {
      assert.ok(typeof app.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });

  it('Creates main package files', function (done) {
    var expected = [
      // add files you expect to exist here.
      'Gruntfile.js',
      'package.json',
      'bower.json'
    ];

    app.run({}, function () {
      assert.ok(typeof app.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });
});
<commit_msg>#24<commit_after>/*global describe, beforeEach, it, after*/
'use strict';

var path = require('path');
var temp = require('temp');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;
var fs = require('fs-extra');

describe('Test prompt validations', function () {

  var app;

  after(function () {
    temp.cleanup();
  });

  it('App name has invalid character and should fail', function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'Test App',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;

      app.run({}, function () {
        assert.ok(typeof app.prompt.errors !== 'undefined', 'This should fail if the app name contains a space.');
        assert.ok(app.prompt.errors.length === 1, 'There should be only 1 error.');
        assert.ok(app.prompt.errors[0].name === 'appName', 'The appName property should be wrong.');
        assert.ok(app.prompt.errors[0].message === 'The application name should only consist of the following characters a-z, A-Z and 0-9.', 'The appName property should be wrong.');
        done();
      });
    });
  });
});

describe('Test github prompt', function(){
  var app;

  after(function () {
    temp.cleanup();
  });

  it('Should retrieve github information for given name if user exists', function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'JayGray',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      app.run({}, function () {
        assert.ok(typeof app.prompt.errors === 'undefined', 'This should fail if the app name contains a space.');
        assert.ok(app.github, 'This should fail if app.github is set to false.');
        assert.ok(app.githubUser === 'JayGray', 'This should fail if app.githubUser is not "JayGray".');
        assert.ok(app.realname === 'Jörg Weber', 'This should fail if the app.realname is not "Jörg Weber".');
        assert.ok(app.githubUrl === 'https://github.com/JayGray', 'This should fail if the app.githubUrl is not "https://github.com/JayGray".');
        done();
      });
    });
  });

  it('Should skip retrieving github information if given name is default', function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      app.run({}, function () {
        assert.ok(typeof app.prompt.errors === 'undefined', 'This should fail if the app name contains a space.');
        assert.strictEqual(app.github, false, 'This should fail if app.github is set to false.');
        assert.strictEqual(app.githubUser, 'someuser', 'This should fail if app.githubUser is not "someuser".');
        assert.strictEqual(app.realname, void 0, 'This should fail if the app.realname is not "undefined".');
        assert.strictEqual(app.githubUrl, void 0, 'This should fail if the app.githubUrl is not "undefined".');
        done();
      });
    });
  });

  it('Should set app.github to false if given name is not known by github', function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'HopefullyNotExistingUser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      app.run({}, function () {
        assert.ok(typeof app.prompt.errors === 'undefined', 'This should fail if the app name contains a space.');
        assert.strictEqual(app.github, false, 'This should fail if app.github is set to true.');
        assert.strictEqual(app.githubUser, 'HopefullyNotExistingUser', 'This should fail if app.githubUser is not "HopefullyNotExistingUser".');
        assert.strictEqual(app.realname, void 0, 'This should fail if the app.realname is not "undefined".');
        assert.strictEqual(app.githubUrl, void 0, 'This should fail if the app.githubUrl is not "undefined".');
        done();
      });
    });
  });

  it('Should write retrieved github informations correct in package.json', function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'JayGray',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      app.run({}, function () {
        var packageJson = fs.readJsonFileSync('package.json');
        console.log(packageJson);
        assert.equal(packageJson.author.name, 'Jörg Weber', 'Should fail if author name is not "Jörg Weber"');
        assert.equal(packageJson.author.url, 'https://github.com/JayGray', 'Should fail if author url is not "https://github.com/JayGray"');
        assert.equal(packageJson.homepage, 'https://github.com/JayGray/testapp', 'Should fail if homepage is not "https://github.com/JayGray/testapp"');
        assert.equal(packageJson.bugs, 'https://github.com/JayGray/testapp/issues', 'Should fail if bugs url is not "https://github.com/JayGray/testapp"');
        done();
      });
    });
  });
});

describe('Test file creation', function () {
  var app;

  after(function () {
    temp.cleanup();
  });

  beforeEach(function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      done();
    });
  });

  it('Creates dot files', function (done) {
    var expected = [
      '.jshintrc',
      '.editorconfig'
    ];

    app.run({}, function () {
      assert.ok(typeof app.prompt.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });

  it('Creates main package files', function (done) {
    var expected = [
      // add files you expect to exist here.
      'Gruntfile.js',
      'package.json',
      'bower.json'
    ];

    app.run({}, function () {
      assert.ok(typeof app.prompt.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
assert = require('yeoman-generator').assert,
helpers = require('yeoman-generator').test;

describe('yo composer:app', function () {
  before(function (done) {
    helpers.run(path.join(__dirname, '../app'))
      .inDir(path.join(__dirname, '../../tmp'))
      .withOptions({
        'skip-install': true
      })
      .withPrompts({
        ProjectName: 'php-my-super-package',
        githubAccount: 'myGitAccount',
        objectName: 'mySuperPackage'
      })
      .on('end', done);
  });

  it('creates files', function () {
    assert.file([
      'composer.json',
      'README.md',
      'package.json',
      '.editorconfig',
      '.gitattributes',
      '.gitignore',
      'Gruntfile.js',
      'phpunit.xml',
      'travis-ci.xml',
      '.travis.yml'
    ]);
  });
});
<commit_msg>test: use yeoman-assert and yeoman-test<commit_after>'use strict';

var path = require('path'),
assert = require('yeoman-assert'),
helpers = require('yeoman-test');

describe('yo composer:app', function () {
  before(function (done) {
    helpers.run(path.join(__dirname, '../app'))
      .inDir(path.join(__dirname, '../../tmp'))
      .withOptions({
        'skip-install': true
      })
      .withPrompts({
        ProjectName: 'php-my-super-package',
        githubAccount: 'myGitAccount',
        objectName: 'mySuperPackage'
      })
      .on('end', done);
  });

  it('creates files', function () {
    assert.file([
      'composer.json',
      'README.md',
      'package.json',
      '.editorconfig',
      '.gitattributes',
      '.gitignore',
      'Gruntfile.js',
      'phpunit.xml',
      'travis-ci.xml',
      '.travis.yml'
    ]);
  });
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;

describe('sandbox generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('sandbox:app', [
        '../../app'
      ]);

      done();
    }.bind(this));
  });

  it('creates expected project files', function (done) {
    helpers.mockPrompt(this.app, {
      appName: 'myapp',
      features : []
    });

    var expectedFiles = [
      // Add files you expect to exist here
      '.jshintrc',
      '.editorconfig',
      'bower.json',
      'public/index.html',
      'public/scripts/main.js',
      'public/styles/main.css'
    ];

    var expectedContent = [
      ['public/index.html', /<title>myapp<\/title>/],
      ['bower.json', /"name": "myapp"/]
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('should generate an angular app', function (done) {
    helpers.mockPrompt(this.app, {
      appName: 'myapp',
      features: [ 'includeAngular', 'includeLodash', 'includeScss', 'includeNormalizeCss', 'includeBourbon', 'includeNeat' ]
    });

    var expectedFiles = [
      // Add files you expect to exist here
      '.jshintrc',
      '.editorconfig',
      'public/index.html',
      'bower.json',
      'public/scripts/main.js',
      'public/styles/scss/main.scss'
    ];

    var expectedContent = [
      ['public/index.html', /<title>myapp<\/title>/],
      ['bower.json', /"name": "myapp"/],
      ['bower.json', /"angular": "*"/],
      ['bower.json', /"normalize.css": "*"/],
      ['bower.json', /"bourbon": "*"/],
      ['bower.json', /"neat": "*"/],
      ['.jshintrc', /"angular": true/]
    ];

    this.app.options['skip-install'] = false;

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });
});
<commit_msg>update test<commit_after>'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;

describe('sandbox generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('sandbox:app', [
        '../../app'
      ]);

      done();
    }.bind(this));
  });

  it('creates expected project files', function (done) {
    helpers.mockPrompt(this.app, {
      appName: 'myapp',
      basicFeatures : [],
      scssFeatures : []
    });

    var expectedFiles = [
      // Add files you expect to exist here
      '.jshintrc',
      '.editorconfig',
      'bower.json',
      'public/index.html',
      'public/scripts/main.js',
      'public/styles/main.css'
    ];

    var expectedContent = [
      ['public/index.html', /<title>myapp<\/title>/],
      ['bower.json', /"name": "myapp"/]
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });

  it('should generate an angular app', function (done) {
    helpers.mockPrompt(this.app, {
      appName: 'myapp',
      basicFeatures : ['includeAngular', 'includeLodash', 'includeScss', 'includeNormalizeCss'],
      scssFeatures : ['includeBourbon', 'includeNeat']
    });

    var expectedFiles = [
      // Add files you expect to exist here
      '.jshintrc',
      '.editorconfig',
      'public/index.html',
      'bower.json',
      'public/scripts/main.js',
      'public/styles/scss/main.scss'
    ];

    var expectedContent = [
      ['public/index.html', /<title>myapp<\/title>/],
      ['bower.json', /"name": "myapp"/],
      ['bower.json', /"angular": "*"/],
      ['bower.json', /"normalize.css": "*"/],
      ['bower.json', /"bourbon": "*"/],
      ['bower.json', /"neat": "*"/],
      ['.jshintrc', /"angular": true/]
    ];

    this.app.options['skip-install'] = false;

    this.app.run({}, function () {
      helpers.assertFile(expectedFiles);
      helpers.assertFileContent(expectedContent);
      done();
    });
  });
});
<|endoftext|>


<commit_before>/*global describe, beforeEach, it */
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;

describe('back generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('back:app', [
        '../../app'
      ]);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      '../../.travis.yml',
      '../../package.json',
      '../../README.md',
      '../../app/templates/_application.js',
      '../../app/templates/_bower.json',
      '../../app/templates/_content.html',
      '../../app/templates/_ContentController.js',
      '../../app/templates/_ContentController.spec.js',
      '../../app/templates/_gruntfile.js',
      '../../app/templates/_index.html',
      '../../app/templates/_e2e.spec.js',
      '../../app/templates/_package.json',
      '../../app/templates/image_a.jpg',
      '../../app/templates/image_b.jpg',
      '../../app/templates/image_c.jpg',
      '../../app/templates/karma.config.js',
      '../../app/templates/protractor.config.js',
      '../../app/templates/_README.md'
    ];

    helpers.mockPrompt(this.app, {
      'appName'        : true,
      'appDescription' : true,
      'appVersion'     : true
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});<commit_msg>Tests fixed.<commit_after>/*global describe, beforeEach, it */
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;

describe('back generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('back:app', [
        '../../app'
      ]);
      done();
    }.bind(this));
  });

  it('creates expected files', function (done) {
    var expected = [
      '../../.gitignore',
      '../../.travis.yml',
      '../../package.json',
      '../../README.md',
      '../../app/templates/_admin.js',
      '../../app/templates/_config.js',
      '../../app/templates/_database.js',
      '../../app/templates/_example.js',
      '../../app/templates/_gruntfile.js',
      '../../app/templates/_models.js',
      '../../app/templates/_package.json',
      '../../app/templates/_README.md',
      '../../app/templates/_routes.js',
      '../../app/templates/_server.js',
      '../../app/templates/_users.js'
    ];

    helpers.mockPrompt(this.app, {
      'appName'        : true,
      'appDescription' : true,
      'appVersion'     : true
    });
    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFile(expected);
      done();
    });
  });
});<|endoftext|>


<commit_before>var moment = require('moment');
var _ = require('lodash');

module.exports = {
    birth: {
        src: 'dateDeNaissance',
        fn: function(dateDeNaissance) {
            return moment(dateDeNaissance).format('YYYY-MM-DD');
        }
    },
    age: {
        src: 'dateDeNaissance',
        fn: function(dateDeNaissance) {
            return moment().diff(dateDeNaissance, 'years');
        }
    },
    statmarit: {
        src: 'statutMarital',
        values: {
            seul: 2,
            mariage: 1,
            pacs: 5,
            relation_libre: 2
        }
    },
    id: '_id',
    enceinte: 'enceinte',
    ass_precondition_remplie: 'assPreconditionRemplie',
    activite: {
        src: 'situationsPro',
        fn: function(value) {
            var returnValue;
            _.forEach({
                demandeur_emploi: 1,
                etudiant: 2,
                retraite: 3
            }, function(v, k) {
                if (_.find(value, { situation: k })) returnValue = v;
            });
            return returnValue;
        }
    },
    inv: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'handicap' }) ? 1 : 0;
        }
    },
    etu: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'etudiant' }) ? 1 : 0;
        }
    },
    boursier: 'boursier',
    scolarite: {
        fn: function(individu) {
            var values = {
                'inconnue': 0,
                'college': 1,
                'lycee': 2
            };
            return values[individu.scolarite];
        }
    },
    coloc: {
        fn: function(individu, situation) {
            var test = individu.role === 'demandeur' && 'locataire' === situation.logement.type && situation.logement.colocation;
            return test ? 1 : null;
        }
    },

    /* Revenus du patrimoine */
    interets_epargne_sur_livrets: {
        src: 'epargneSurLivret',
        fn: function(value) { return 0.01 * value; },
        default: 0
    },
    epargne_non_remuneree: {
        src: 'epargneSansRevenus',
        default: 0
    },
    valeur_locative_immo_non_loue: {
        src: 'valeurLocativeImmoNonLoue',
        default: 0
    },
    valeur_locative_terrains_non_loue: {
        src: 'valeurLocativeTerrainNonLoue',
        default: 0
    },

    /* Activités non-salarié */
    tns_chiffre_affaires_micro_entreprise: 'caMicroEntreprise',
    tns_autres_revenus: 'autresRevenusTns',
    tns_type_structure: {
      src: 'tnsStructureType',
      values: {
          auto_entrepreneur: 0,
          micro_entreprise: 1
      }
    },
    tns_type_activite: 'tnsActiviteType'
};
<commit_msg>Map inapte_travail<commit_after>var moment = require('moment');
var _ = require('lodash');

module.exports = {
    birth: {
        src: 'dateDeNaissance',
        fn: function(dateDeNaissance) {
            return moment(dateDeNaissance).format('YYYY-MM-DD');
        }
    },
    age: {
        src: 'dateDeNaissance',
        fn: function(dateDeNaissance) {
            return moment().diff(dateDeNaissance, 'years');
        }
    },
    statmarit: {
        src: 'statutMarital',
        values: {
            seul: 2,
            mariage: 1,
            pacs: 5,
            relation_libre: 2
        }
    },
    id: '_id',
    enceinte: 'enceinte',
    ass_precondition_remplie: 'assPreconditionRemplie',
    activite: {
        src: 'situationsPro',
        fn: function(value) {
            var returnValue;
            _.forEach({
                demandeur_emploi: 1,
                etudiant: 2,
                retraite: 3
            }, function(v, k) {
                if (_.find(value, { situation: k })) returnValue = v;
            });
            return returnValue;
        }
    },
    inv: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'handicap' }) ? 1 : 0;
        }
    },
    inapte_travail: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'inapte_travail' }) ? 1 : 0;
        }
    },
    etu: {
        src: 'situationsPro',
        fn: function(situationsPro) {
            return !!_.find(situationsPro, { situation: 'etudiant' }) ? 1 : 0;
        }
    },
    boursier: 'boursier',
    scolarite: {
        fn: function(individu) {
            var values = {
                'inconnue': 0,
                'college': 1,
                'lycee': 2
            };
            return values[individu.scolarite];
        }
    },
    coloc: {
        fn: function(individu, situation) {
            var test = individu.role === 'demandeur' && 'locataire' === situation.logement.type && situation.logement.colocation;
            return test ? 1 : null;
        }
    },

    /* Revenus du patrimoine */
    interets_epargne_sur_livrets: {
        src: 'epargneSurLivret',
        fn: function(value) { return 0.01 * value; },
        default: 0
    },
    epargne_non_remuneree: {
        src: 'epargneSansRevenus',
        default: 0
    },
    valeur_locative_immo_non_loue: {
        src: 'valeurLocativeImmoNonLoue',
        default: 0
    },
    valeur_locative_terrains_non_loue: {
        src: 'valeurLocativeTerrainNonLoue',
        default: 0
    },

    /* Activités non-salarié */
    tns_chiffre_affaires_micro_entreprise: 'caMicroEntreprise',
    tns_autres_revenus: 'autresRevenusTns',
    tns_type_structure: {
      src: 'tnsStructureType',
      values: {
          auto_entrepreneur: 0,
          micro_entreprise: 1
      }
    },
    tns_type_activite: 'tnsActiviteType'
};
<|endoftext|>


<commit_before>enyo.kind({
  name: "WebLetter.AddressToken",
  kind: "WebLetter.Token",
  style: "margin: 0px; padding: 0px;",
  topToken: false,
  components: [
    {kind: "onyx.Groupbox", components: [
      {kind: "onyx.GroupboxHeader", name: "descr"},
      {kind: "WebLetter.TextToken", name: "name", description: "Name", subkey: "name", subToken: true},
      {kind: "WebLetter.TextToken", name: "street", description: "Street", subkey: "street", subToken: true},
      {kind: "WebLetter.TextToken", name: "zip", description: "ZIP Code", subkey: "zip", subToken: true},
      {kind: "WebLetter.TextToken", name: "city", description: "City", subkey: "city", subToken: true}
    ]}],
  getInput: function() {
    var res = this.$.name.getValue()
    + "\\\\"
    + this.$.street.getValue()
    + "\\\\"
    + this.$.zip.getValue()
    + " "
    + this.$.city.getValue();
    return res;
  }
});

<commit_msg>AddressToken: overwrite {enable,disable}Inputs<commit_after>enyo.kind({
  name: "WebLetter.AddressToken",
  kind: "WebLetter.Token",
  style: "margin: 0px; padding: 0px;",
  topToken: false,
  components: [
    {kind: "onyx.Groupbox", components: [
      {kind: "onyx.GroupboxHeader", name: "descr"},
      {kind: "WebLetter.TextToken", name: "name", description: "Name", subkey: "name", subToken: true},
      {kind: "WebLetter.TextToken", name: "street", description: "Street", subkey: "street", subToken: true},
      {kind: "WebLetter.TextToken", name: "zip", description: "ZIP Code", subkey: "zip", subToken: true},
      {kind: "WebLetter.TextToken", name: "city", description: "City", subkey: "city", subToken: true}
    ]}],
  getInput: function() {
    var res = this.$.name.getValue()
    + "\\\\"
    + this.$.street.getValue()
    + "\\\\"
    + this.$.zip.getValue()
    + " "
    + this.$.city.getValue();
    return res;
  },
  enableInputs: function() { },
  disableInputs: function() { }
});

<|endoftext|>


<commit_before>var Lab = require('lab');
var lab = exports.lab = Lab.script();

var describe = lab.describe;
var it = lab.it;
var expect = Lab.expect;

var isEmpty = require('../is-empty');

describe('isEmpty', function () {
  it('should return true for empty', function(done) {
      expect(isEmpty([])).to.be.true;
      expect(isEmpty("")).to.be.true;
      expect(isEmpty(" ")).to.be.true;
      expect(isEmpty({})).to.be.true;
      done();
  });
  it('should return false for non-empty', function(done) {
      expect(isEmpty({x : "y"})).to.be.false;
      expect(isEmpty("a")).to.be.false;
      expect(isEmpty(" a")).to.be.false;
      expect(isEmpty([1])).to.be.false;
      done();
  });
  it('should error when given invalid arguments', function (done) {
      try {
          isEmpty(function() {});
      }
      catch (err) {
          expect(err.message).to.equal('first argument must be a string, object or array');
      }
      try {
          isEmpty();
      }
      catch (err) {
          expect(err.message).to.equal('first argument must be a string, object or array');
      }
      done();
  });
});
<commit_msg>tab fails fixed<commit_after>var Lab = require('lab');
var lab = exports.lab = Lab.script();

var describe = lab.describe;
var it = lab.it;
var expect = Lab.expect;

var isEmpty = require('../is-empty');

describe('isEmpty', function () {
  it('should return true for empty', function(done) {
    expect(isEmpty([])).to.be.true;
    expect(isEmpty("")).to.be.true;
    expect(isEmpty(" ")).to.be.true;
    expect(isEmpty({})).to.be.true;
    done();
  });
  it('should return false for non-empty', function(done) {
    expect(isEmpty({x : "y"})).to.be.false;
    expect(isEmpty("a")).to.be.false;
    expect(isEmpty(" a")).to.be.false;
    expect(isEmpty([1])).to.be.false;
    done();
  });
  it('should error when given invalid arguments', function (done) {
    try {
      isEmpty(function() {});
    }
    catch (err) {
      expect(err.message).to.equal('first argument must be a string, object or array');
    }
    try {
      isEmpty();
    }
    catch (err) {
      expect(err.message).to.equal('first argument must be a string, object or array');
    }
    done();
  });
});
<|endoftext|>


<commit_before>/* global describe */
/* global it */
'use strict';

var TransloaditLib = require('../index');
var optional = require('optional');
var config = optional('./config.json') || {'key': 'random', 'secret': 'random'};
var should = require('should');

describe('TransloadIt.Template Module:', function () {
  describe('Template loading from the global export', function () {
    var a = require('../index')(config);

    it('should create the global export Object', function () {
      a.should.be.an.instanceOf(Object);
    });

    it('should have the `template` Object', function () {
      should.exist(a.template);

      a.template.should.be.an.instanceOf(Object);
    });
  });

  describe('Template loading as a new Object', function () {
    var a = new TransloaditLib.Template(config);

    it('should create the Object', function () {
      a.should.be.an.instanceOf(Object);
    });

    it('should have the `create` Function', function () {
      should.exist(a.create);
    });
  });

  describe('Template loading with just require', function () {
    var a  = require('../index').Template(config);

    it('should create the Object', function () {
      a.should.be.an.instanceOf(Object);
    });

    it('should have the `create` Function', function () {
      should.exist(a.create);
    });
  });

  describe('Template.create method', function () {
    var a = require('../index').Template(config);

    it('should return an error on missing params', function (done) {
      a.create(null, function (err) {
        should.exist(err);

        done();
      });
    });

    it('should return an error on missing template param', function (done) {
      a.create({}, function (err) {
        should.exist(err);

        done();
      });
    });
  });
});
<commit_msg>test-template: retrieve method<commit_after>/* global describe */
/* global it */
'use strict';

var TransloaditLib = require('../index');
var optional = require('optional');
var config = optional('./config.json') || {'key': 'random', 'secret': 'random'};
var should = require('should');

describe('TransloadIt.Template Module:', function () {
  describe('Template loading from the global export', function () {
    var a = require('../index')(config);

    it('should create the global export Object', function () {
      a.should.be.an.instanceOf(Object);
    });

    it('should have the `template` Object', function () {
      should.exist(a.template);

      a.template.should.be.an.instanceOf(Object);
    });
  });

  describe('Template loading as a new Object', function () {
    var a = new TransloaditLib.Template(config);

    it('should create the Object', function () {
      a.should.be.an.instanceOf(Object);
    });

    it('should have the `create` Function', function () {
      should.exist(a.create);
    });
  });

  describe('Template loading with just require', function () {
    var a  = require('../index').Template(config);

    it('should create the Object', function () {
      a.should.be.an.instanceOf(Object);
    });

    it('should have the `create` Function', function () {
      should.exist(a.create);
    });
  });

  describe('Template.create method', function () {
    var a = require('../index').Template(config);

    it('should return an error on missing params', function (done) {
      a.create(null, function (err) {
        should.exist(err);

        done();
      });
    });

    it('should return an error on missing template param', function (done) {
      a.create({}, function (err) {
        should.exist(err);

        done();
      });
    });
  });

  describe('Template.proto.retrieve method', function () {
    var a = require('../index').Template(config);

    it('should return an error on missing templateId', function (done) {
      a.retrieve(null, function (err) {
        should.exist(err);

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


<commit_before>(function (enyo, scope) {
	/**
	* {@link moon.DataGridList} is an {@link enyo.DataGridList} with Moonstone visual
	* styling applied.
	*
	* @class moon.DataGridList
	* @extends enyo.DataGridList
	* @mixes moon.DataListSpotlightSupport
	* @ui
	* @public
	*/
	enyo.kind(
		/** @lends moon.DataGridList.prototype */ {

		/**
		* @private
		*/
		name: 'moon.DataGridList',

		/**
		* @private
		*/
		kind: 'enyo.DataGridList',

		/**
		* @private
		*/
		mixins: ['moon.DataListSpotlightSupport'],

		/**
		* @private
		*/
		noDefer: true,

		/**
		* @private
		*/
		allowTransitions: false,

		/**
		* @private
		*/
		spotlight: true,

		/**
		* @private
		*/
		scrollerOptions: { kind: 'moon.Scroller', vertical:'scroll', horizontal: 'hidden' },

		/**
		* @private
		*/
		handlers: {
			onSpotlightFocus   : 'handleSpotlightFocus',
			onSpotlightBlur    : 'handleSpotlightBlur',
			onSpotlightFocused : 'handleSpotlightFocused'
		},

		/**
		* @private
		*/
		handleSpotlightFocus: function (inSender, inEvent) {
			var c = inEvent.originator;
			if(c !== this.$.scroller) {
				var zIndex = parseInt(enyo.dom.getComputedStyleValue(c.hasNode(), 'z-index'), 10) || 0;
				c.applyStyle('z-index', zIndex + 1);
			}
		},

		/**
		* @private
		*/
		handleSpotlightBlur: function (inSender, inEvent) {
			var c = inEvent.originator;
			if(c !== this.$.scroller) {
				setTimeout(this.bindSafely(function () {
					c.applyStyle('z-index', null);
				}), 0);
			}
		},

		/**
		* @private
		*/
		handleSpotlightFocused: function (inSender, inEvent) {
			if (!enyo.Spotlight.getPointerMode()) {
				if (inEvent.index < this.indexBoundFirstRow) {
					this.$.scroller.scrollToTop();
				} else if (inEvent.index > this.indexBoundLastRow) {
					this.$.scroller.scrollToBottom();
				}
			}
		}
	});

	/**
	* Overload the delegate strategy to incorporate measurements for our scrollers
	* when they are visible.
	*
	* @private
	*/
	(function (enyo, moon) {
		var p = moon.DataGridList.delegates.verticalGrid = enyo.clone(enyo.DataGridList.delegates.verticalGrid);
		enyo.kind.extendMethods(p, {

			/**
			* @method
			* @private
			*/
			refresh: enyo.inherit(function (sup) {
				return function (list) {
					sup.apply(this, arguments);
					list.$.scroller.resize();
				};
			}),

			/**
			* @private
			*/
			scrollToIndex: function (list, i) {
				// This function recurses, so make sure we are scrolling to a valid index,
				// otherwise childForIndex will never return a control
				if ((i < 0) || (i >= list.collection.length)) {
					return;
				}
					// first see if the child is already available to scroll to
				var c = this.childForIndex(list, i),
					// but we also need the page so we can find its position
					p = this.pageForIndex(list, i);
				// if there is no page then the index is bad
				if (p < 0 || p > this.pageCount(list)) { return; }
				// if there isn't one, then we know we need to go ahead and
				// update, otherwise we should be able to use the scroller's
				// own methods to find it
				if (c) {
					// force a synchronous scroll to the control so it won't dupe and
					// re-animate over positions it has already crossed
					list.$.scroller.scrollToControl(c, false, false);
				} else {
					var idx = list.$.page1.index;

					// attempting to line them up in a useful order
					// given the direction from where our current index is
					if (idx < p) {
						list.$.page1.index = p - 1;
						list.$.page2.index = p;
					} else {
						list.$.page1.index = p;
						list.$.page2.index = p + 1;
					}
					list.refresh();

					this.scrollToIndex(list, i);
				}
			},

			/**
			* @method
			* @private
			*/
			reset: enyo.inherit(function (sup) {
				return function (list) {
					sup.apply(this, arguments);
					this.updateMetrics(list);
					list.refresh();
					list.$.scroller.scrollTo(0, 0, false);
				};
			}),

			/**
			* @method
			* @private
			*/
			updateBounds: enyo.inherit(function (sup) {
				return function (list) {
					sup.apply(this, arguments);
					var w = list.boundsCache.width,
						b = list.$.scroller.getScrollBounds(),
						v = list.$.scroller.$.strategy.$.vColumn,
						c = list.$.scroller.$.strategy.$.clientContainer;
					if (v && (list.$.scroller.getVertical() == 'scroll' || (b.height > b.clientHeight))) {
						var cs = enyo.dom.getComputedStyle(c.hasNode());
						list.boundsCache.width = w - (parseInt(cs['padding-right'], 10) + parseInt(cs['padding-left'], 10));
					}
				};
			})
		}, true);
	})(enyo, moon);
})(enyo, this);
<commit_msg>exclude all non-client controls from spotlight handlers<commit_after>(function (enyo, scope) {
	/**
	* {@link moon.DataGridList} is an {@link enyo.DataGridList} with Moonstone visual
	* styling applied.
	*
	* @class moon.DataGridList
	* @extends enyo.DataGridList
	* @mixes moon.DataListSpotlightSupport
	* @ui
	* @public
	*/
	enyo.kind(
		/** @lends moon.DataGridList.prototype */ {

		/**
		* @private
		*/
		name: 'moon.DataGridList',

		/**
		* @private
		*/
		kind: 'enyo.DataGridList',

		/**
		* @private
		*/
		mixins: ['moon.DataListSpotlightSupport'],

		/**
		* @private
		*/
		noDefer: true,

		/**
		* @private
		*/
		allowTransitions: false,

		/**
		* @private
		*/
		spotlight: true,

		/**
		* @private
		*/
		scrollerOptions: { kind: 'moon.Scroller', vertical:'scroll', horizontal: 'hidden' },

		/**
		* @private
		*/
		handlers: {
			onSpotlightFocus   : 'handleSpotlightFocus',
			onSpotlightBlur    : 'handleSpotlightBlur',
			onSpotlightFocused : 'handleSpotlightFocused'
		},

		/**
		* @private
		*/
		handleSpotlightFocus: function (inSender, inEvent) {
			var c = inEvent.originator;
			var isClientControl = this.getClientControls().indexOf(c) >= 0;
			if(isClientControl) {
				var zIndex = parseInt(enyo.dom.getComputedStyleValue(c.hasNode(), 'z-index'), 10) || 0;
				c.applyStyle('z-index', zIndex + 1);
			}
		},

		/**
		* @private
		*/
		handleSpotlightBlur: function (inSender, inEvent) {
			var c = inEvent.originator;
			var isClientControl = this.getClientControls().indexOf(c) >= 0;
			if(isClientControl) {
				setTimeout(this.bindSafely(function () {
					c.applyStyle('z-index', null);
				}), 0);
			}
		},

		/**
		* @private
		*/
		handleSpotlightFocused: function (inSender, inEvent) {
			if (!enyo.Spotlight.getPointerMode()) {
				if (inEvent.index < this.indexBoundFirstRow) {
					this.$.scroller.scrollToTop();
				} else if (inEvent.index > this.indexBoundLastRow) {
					this.$.scroller.scrollToBottom();
				}
			}
		}
	});

	/**
	* Overload the delegate strategy to incorporate measurements for our scrollers
	* when they are visible.
	*
	* @private
	*/
	(function (enyo, moon) {
		var p = moon.DataGridList.delegates.verticalGrid = enyo.clone(enyo.DataGridList.delegates.verticalGrid);
		enyo.kind.extendMethods(p, {

			/**
			* @method
			* @private
			*/
			refresh: enyo.inherit(function (sup) {
				return function (list) {
					sup.apply(this, arguments);
					list.$.scroller.resize();
				};
			}),

			/**
			* @private
			*/
			scrollToIndex: function (list, i) {
				// This function recurses, so make sure we are scrolling to a valid index,
				// otherwise childForIndex will never return a control
				if ((i < 0) || (i >= list.collection.length)) {
					return;
				}
					// first see if the child is already available to scroll to
				var c = this.childForIndex(list, i),
					// but we also need the page so we can find its position
					p = this.pageForIndex(list, i);
				// if there is no page then the index is bad
				if (p < 0 || p > this.pageCount(list)) { return; }
				// if there isn't one, then we know we need to go ahead and
				// update, otherwise we should be able to use the scroller's
				// own methods to find it
				if (c) {
					// force a synchronous scroll to the control so it won't dupe and
					// re-animate over positions it has already crossed
					list.$.scroller.scrollToControl(c, false, false);
				} else {
					var idx = list.$.page1.index;

					// attempting to line them up in a useful order
					// given the direction from where our current index is
					if (idx < p) {
						list.$.page1.index = p - 1;
						list.$.page2.index = p;
					} else {
						list.$.page1.index = p;
						list.$.page2.index = p + 1;
					}
					list.refresh();

					this.scrollToIndex(list, i);
				}
			},

			/**
			* @method
			* @private
			*/
			reset: enyo.inherit(function (sup) {
				return function (list) {
					sup.apply(this, arguments);
					this.updateMetrics(list);
					list.refresh();
					list.$.scroller.scrollTo(0, 0, false);
				};
			}),

			/**
			* @method
			* @private
			*/
			updateBounds: enyo.inherit(function (sup) {
				return function (list) {
					sup.apply(this, arguments);
					var w = list.boundsCache.width,
						b = list.$.scroller.getScrollBounds(),
						v = list.$.scroller.$.strategy.$.vColumn,
						c = list.$.scroller.$.strategy.$.clientContainer;
					if (v && (list.$.scroller.getVertical() == 'scroll' || (b.height > b.clientHeight))) {
						var cs = enyo.dom.getComputedStyle(c.hasNode());
						list.boundsCache.width = w - (parseInt(cs['padding-right'], 10) + parseInt(cs['padding-left'], 10));
					}
				};
			})
		}, true);
	})(enyo, moon);
})(enyo, this);
<|endoftext|>


<commit_before>var assert = require("assert");
var Lib = require("./../ramda");

describe("keys", function() {
    var keys = Lib.keys;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's own keys", function() {
        assert.deepEqual(keys(obj), ['a','b','c','d','e','f']);
    });

    it("should work with hasOwnProperty override", function() {
        assert.deepEqual(keys({
            "hasOwnProperty": false
        }), ["hasOwnProperty"]);
    });

    it("should work for primitives", function() {
        var result = Lib.map(function(val) {
            return Lib.keys(val);
        }, [null, undefined, 55, "", true, false, NaN, Infinity, , []]);
        assert.deepEqual(result, Lib.repeatN([], 10));
    });

    it("does not include the given object's prototype properties", function() {
        assert.deepEqual(keys(cobj), ['a', 'b']);
    });
});

describe("keysIn", function() {
    var keysIn = Lib.keysIn;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's keys", function() {
        assert.deepEqual(keysIn(obj), ['a','b','c','d','e','f']);
    });

    it("includes the given object's prototype properties", function() {
        assert.deepEqual(keysIn(cobj), ['a', 'b', 'x', 'y']);
    });
});

describe("values", function() {
    var values = Lib.values;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    var undef;
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's values", function() {
        assert.deepEqual(values(obj), [100,[1,2,3],{x: 200, y: 300},'D',null,undef]);
        assert.deepEqual(values({
            hasOwnProperty: false
        }), [false]);
    });

    it("does not include the given object's prototype properties", function() {
        assert.deepEqual(values(cobj), [100, 200]);
    });
});

describe("valuesIn", function() {
    var valuesIn = Lib.valuesIn;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's values", function() {
        assert.deepEqual(valuesIn(obj), [100,[1,2,3],{x: 200, y: 300},'D',null,undefined]);
    });

    it("includes the given object's prototype properties", function() {
        assert.deepEqual(valuesIn(cobj), [100, 200, C.prototype.x, 'y']);
    });

    it("should work for primitives", function() {
        var result = Lib.map(function(val) {
            return Lib.values(val);
        }, [null, undefined, 55, "", true, false, NaN, Infinity, , []]);
        assert.deepEqual(result, Lib.repeatN([], 10));
    });
});

<commit_msg>valuesIn and keysIn should work for primitives<commit_after>var assert = require("assert");
var Lib = require("./../ramda");

describe("keys", function() {
    var keys = Lib.keys;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's own keys", function() {
        assert.deepEqual(keys(obj), ['a','b','c','d','e','f']);
    });

    it("should work with hasOwnProperty override", function() {
        assert.deepEqual(keys({
            "hasOwnProperty": false
        }), ["hasOwnProperty"]);
    });

    it("should work for primitives", function() {
        var result = Lib.map(function(val) {
            return Lib.keys(val);
        }, [null, undefined, 55, "", true, false, NaN, Infinity, , []]);
        assert.deepEqual(result, Lib.repeatN([], 10));
    });

    it("does not include the given object's prototype properties", function() {
        assert.deepEqual(keys(cobj), ['a', 'b']);
    });
});

describe("keysIn", function() {
    var keysIn = Lib.keysIn;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's keys", function() {
        assert.deepEqual(keysIn(obj), ['a','b','c','d','e','f']);
    });

    it("includes the given object's prototype properties", function() {
        assert.deepEqual(keysIn(cobj), ['a', 'b', 'x', 'y']);
    });

    it("should work for primitives", function() {
        var result = Lib.map(function(val) {
            return Lib.keys(val);
        }, [null, undefined, 55, "", true, false, NaN, Infinity, , []]);
        assert.deepEqual(result, Lib.repeatN([], 10));
    });
});

describe("values", function() {
    var values = Lib.values;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    var undef;
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's values", function() {
        assert.deepEqual(values(obj), [100,[1,2,3],{x: 200, y: 300},'D',null,undef]);
        assert.deepEqual(values({
            hasOwnProperty: false
        }), [false]);
    });

    it("does not include the given object's prototype properties", function() {
        assert.deepEqual(values(cobj), [100, 200]);
    });

    it("should work for primitives", function() {
        var result = Lib.map(function(val) {
            return Lib.keys(val);
        }, [null, undefined, 55, "", true, false, NaN, Infinity, , []]);
        assert.deepEqual(result, Lib.repeatN([], 10));
    });
});

describe("valuesIn", function() {
    var valuesIn = Lib.valuesIn;
    var obj = {a: 100, b: [1,2,3], c: { x: 200, y: 300}, d: "D", e: null, f: (function(){}())};
    function C() { this.a = 100; this.b = 200; }
    C.prototype.x = function() { return "x"; };
    C.prototype.y = "y";
    var cobj = new C();

    it("returns an array of the given object's values", function() {
        assert.deepEqual(valuesIn(obj), [100,[1,2,3],{x: 200, y: 300},'D',null,undefined]);
    });

    it("includes the given object's prototype properties", function() {
        assert.deepEqual(valuesIn(cobj), [100, 200, C.prototype.x, 'y']);
    });

    it("should work for primitives", function() {
        var result = Lib.map(function(val) {
            return Lib.values(val);
        }, [null, undefined, 55, "", true, false, NaN, Infinity, , []]);
        assert.deepEqual(result, Lib.repeatN([], 10));
    });
});

<|endoftext|>


<commit_before>/* Enyo Platform encapsulation. Include this FIRST in your depends.js.  The
 * first call you make to a function inside it will cause it to perform it's
 * detection (in the setup function).  If you are running in PhoneGap, and your
 * app depends on accurate results in here, make sure that you are not running
 * any code that depends on this module until after the "deviceready" PhoneGap
 * event is fired.
 *
 * This prefers direct access to APIs whenever possible - although you CAN run
 * webOS and WebWorks apps with PhoneGap, I'm trying to avoid going through any
 * extra layers here.
 *
 * If you are deploying to iOS, set a new parameter in your appinfo.json called
 * iTunesAppId to your application id as found in the Apple Dev Portal, for the
 * getReviewURL function
 *
 * PhoneGap iOS can have "OpenAllWhitelistURLsInWebView" set True in
 * PhoneGap.plist to cause a browser window.open() to open in new windows.
 *
 * If you are deploying to BlackBerry's App World, set a new parameter in your
 * appinfo.json called "appWorldId" to your application's id as found in the
 * App World Dev Portal, for the getReviewURL function.
 *
 * To make your browser work in BlackBerry, you'll need to add to config.xml:
 *   <feature id="blackberry.invoke"/>
 *   <feature id="blackberry.invoke.BrowserArguments"/>
 *
 */
enyo.kind({
    name: "Platform",
    kind: "Component",
    statics: {
        setup: function()
        {
            enyo.log("********* Setting up Platform Variables *************");
            enyo.log("window.PalmSystem "+ window.PalmSystem);
            enyo.log("window.blackberry "+ window.blackberry);
            enyo.log("window.PhoneGap "+ window.PhoneGap);
            enyo.log("window.device "+ window.device);
            if(window.device)
                enyo.log("window.device.platform "+ window.device.platform);
            enyo.log("window.chrome "+ window.chrome);

            /* If you include PhoneGap, but you don't wait until the device var
             * is initialized before calling this, we're going to ignore this
             * until the device var is available
             */
            if(window.PhoneGap && !window.device) {
                enyo.log("EnyoPlatform: PhoneGap detected, device not (yet) available. Bailing until next call.");
                return;
            }
            /* Check for systems where we don't have PhoneGap in our
             * requirements first, currently webOS and BlackBerry WebWorks
             * Even if you use PhoneGap on BlackBerry, according to the PhoneGap
             * documentation, it's platform determination code doesn't work
             * properly for at least some models.
             */
            if(typeof window.PalmSystem !== "undefined")
            {
                var deviceInfo = enyo.fetchDeviceInfo();
                this.platform = "webos";
                this.platformVersion = deviceInfo ? parseFloat(deviceInfo.platformVersion) : "unknown";
            }
            else if(typeof blackberry !== "undefined")
            {
                if(typeof PhoneGap !== "undefined")
                {
                    this.platform = "blackberry";
                }
                else
                {
                    this.platform = "webworks";
                }
                /* According to the BlackBerry docs,  to get the version number,
                 * we have to actually make an AJAX request to
                 * http://localhost:8472/blackberry/system/get . Screw that.
                 */
                this.platformVersion = "unknown";
            }
            else if(typeof PhoneGap !== "undefined")
            {
                /* See the PhoneGap Device API documentation for possible
                 * pitfalls.
                 */
                this.platform = device.platform.toLowerCase();
                this.platformVersion = parseFloat(device.version);
            }
            else
            {
                /* Someone with more time on their hands might be interested in
                 * breaking this out to determine various web browsers and their
                 * respective versions.  Not for me at this time.
                 */
                this.platform = "web";
                this.platformVersion = "unknown";
            }
            enyo.log("Platform detected: " + this.platform + " version " + this.platformVersion);
            enyo.log(" ************************************** ");
        },
        /* Should you find yourself in need of the raw platform name */
        getPlatformName: function() { this.platform || this.setup(); return this.platform; },

        /* Platform boolean functions -- return truthy if specific platform */
        isWebOS: function() { this.platform || this.setup(); return this.platform == "webos"; },
        isAndroid: function() { this.platform || this.setup(); return this.platform == "android"; },
        isBlackBerry: function() { this.platform || this.setup(); return this.platform == "blackberry" || this.platform == "webworks" },
        isWebWorks: function() { this.platform || this.setup(); return this.platform == "webworks"; },
        isiOS: function() { this.platform || this.setup(); return this.platform == "iphone"; },
        isMobile: function() { this.platform || this.setup(); return this.platform != "web"; },
        hasFlash: function() {
            this.platform || this.setup();
            return (this.platform == "webos" && this.platformVersion >= 2) ||
                    (this.isBlackBerry()) || // TODO: Version check?
                    (this.platform == "android");
        },

        /* General screen size functions -- tablet vs phone, landscape vs portrait */
        isLargeScreen: function() { return window.innerWidth > 480; },
        isWideScreen: function() { return window.innerWidth > window.innerHeight; },

        /* Platform-supplied UI concerns */
        hasBack: function()
        {
            this.platform || this.setup();
            return this.platform == "android" || (this.platform == "webos" && this.platformVersion < 3);
        },
        hasMenu: function()
        {
            /* You may want to include Android here if you're using a target
             * API of less than 14 (Ice Cream Sandwich)
             */
            /* Blackberry Tablet OS has a standard "swipe down from top bezel" gesture
             * that they use .. should probably consider that here, but I'm not sure
             * if their other platforms have any equivalent
             */
            this.platform || this.setup();
            return this.platform == "webos" || (this.platform == "android" && this.platformVersion < 4);
        },

        /* Platform-specific Audio utility. WebWorks on PlayBook and webOS have
         * great support for HTML5 audio objects. Android's is terrible, so we
         * choose to use the PhoneGap media API there, which is encapsulated in
         * the PlatformSound kind
         */
        useHTMLAudio: function()
        {
            this.platform || this.setup();
            return this.isWebOS() || this.isWebWorks() || !this.isMobile();
        },
        /* Platform Specific Web Browser -- returns a function that should
         * launch the OS's web browser.
         * call: Platform.browser("http://www.google.com/", this)();
         */
        browser: function(url, thisObj)
        {
            this.platform || this.setup();
            if(this.isWebOS())
            {
                return enyo.bind(thisObj, (function(args) {
                    var x = thisObj.createComponent({ name: "AppManService", kind: "PalmService", service: "palm://com.palm.applicationManager/", method: "open" });
                    x.call({ target: url });
                }));
            }
            else if(this.platform == "web" || (this.platform == "android" && parseFloat(this.platformVersion >= 4.0)) )
            {
                /* If web, just open a new tab/window - this also works well in
                 * Android 4.0 - suggest ChildBrowser PhoneGap plugin for other
                 * versions of Android
                 */
                return enyo.bind(thisObj, function(x) { window.open(x, '_blank'); }, url);
            }
            else if(this.isBlackBerry())
            {
                /* If BlackBerry, go through their ridiculous parsing rules */
                /* Make sure you have the invoke and invoke.BrowserArguments
                 * configured in your config.xml.
                 */
                var args = new blackberry.invoke.BrowserArguments(this.blackBerryURLEncode(url));
                return enyo.bind(thisObj, blackberry.invoke.invoke, blackberry.invoke.APP_BROWSER, args);
            }
            else if(typeof PhoneGap !== "undefined" && window.plugins && window.plugins.childBrowser)
            {
                /* If you have the popular childBrowser plugin for PhoneGap */
				/* If you're using iOS, make sure you've called the childBrowser.init first somewhere!! */
                return enyo.bind(thisObj, window.plugins.childBrowser.openExternal, url);
            }
            else if(this.platform == "android" && navigator.app && navigator.app.loadUrl)
            {
                /* If Android < 4.0 and PhoneGap ChildBrowser plugin is not available, then
                 * Assume PhoneGap is loaded, otherwise we wouldn't know it's Android, right */
                return enyo.bind(thisObj, function(x) { navigator.app.loadUrl({ openexternal:true }) }, url);
            }
            else
            {
                /* Fall back to something that could possibly work
                 * One could also make a case for just setting window.location
                 */
                return enyo.bind(thisObj, function(x) { window.open(x, '_blank'); }, url);
            }
        },
        /* A ridiculous function for parsing URLs into something that RIM's
         * BrowserArguments call can deal with "properly", thanks to their
         * forums.
         */
        blackBerryURLEncode: function(address) {
            var encodedAddress = "";
            // URL Encode all instances of ':' in the address
            encodedAddress = address.replace(/:/g, "%3A");
            // Leave the first instance of ':' in its normal form
            encodedAddress = encodedAddress.replace(/%3A/, ":");
            // Escape all instances of '&' in the address
            encodedAddress = encodedAddress.replace(/&/g, "\&");

            if (typeof blackberry !== 'undefined') {
                var args = new blackberry.invoke.BrowserArguments(encodedAddress);
                blackberry.invoke.invoke(blackberry.invoke.APP_BROWSER, args);
            } else {
                // If I am not a BlackBerry device, open link in current browser
                window.location = encodedAddress;
            }
        },
        getReviewURL: function()
        {
            var appInfo;
            var url = "";

            appInfo = enyo.fetchAppInfo();
            if(enyo.isString(appInfo))
                appInfo = JSON.parse(appInfo);

            this.platform || this.setup();
            switch(Platform.platform) {
                case "webos":
                    url = "http://developer.palm.com/appredirect/?packageid=" + appInfo.id;
                    break;
                case "android":
                    /* enyo.fetchAppId() appears unreliable here? */
                    url = "market://details?id=" + appInfo.id;
                    break;
                case "blackberry":  // intentional fallthrough
                case "webworks":
                    url = "http://appworld.blackberry.com/webstore/content/" + appInfo.appWorldId;
                    break;
                case "iphone":
                    url = "itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id="+appInfo.iTunesAppId;
                    break;
            }
            return url;
        }
    }
});

// experimental code that MIGHT work on an implementation where createHTMLNotification actually works.
// PlayBook 2.0, however, is not that place.

/* if(window.webkitNotifications)
{
    enyo.windows.openDashboard = (function(path, name, params, attributes) {
        enyo.log("openDashboard", path);
        if(window.webkitNotifications.checkPermission() == 0) {
	    enyo.log("opening dashboard");
	    var note = window.webkitNotifications.createHTMLNotification(path);
	    attributes = attributes || {};
	    attributes.window = "dashboard";
	    note.enyo = note.enyo || {};
	    note.enyo.windowParams = params || {};
	    note.show();
	}
    });
}*/
<commit_msg>fix enyoplatform with platformsound<commit_after>/* Enyo Platform encapsulation. Include this FIRST in your depends.js.  The
 * first call you make to a function inside it will cause it to perform it's
 * detection (in the setup function).  If you are running in PhoneGap, and your
 * app depends on accurate results in here, make sure that you are not running
 * any code that depends on this module until after the "deviceready" PhoneGap
 * event is fired.
 *
 * This prefers direct access to APIs whenever possible - although you CAN run
 * webOS and WebWorks apps with PhoneGap, I'm trying to avoid going through any
 * extra layers here.
 *
 * If you are deploying to iOS, set a new parameter in your appinfo.json called
 * iTunesAppId to your application id as found in the Apple Dev Portal, for the
 * getReviewURL function
 *
 * PhoneGap iOS can have "OpenAllWhitelistURLsInWebView" set True in
 * PhoneGap.plist to cause a browser window.open() to open in new windows.
 *
 * If you are deploying to BlackBerry's App World, set a new parameter in your
 * appinfo.json called "appWorldId" to your application's id as found in the
 * App World Dev Portal, for the getReviewURL function.
 *
 * To make your browser work in BlackBerry, you'll need to add to config.xml:
 *   <feature id="blackberry.invoke"/>
 *   <feature id="blackberry.invoke.BrowserArguments"/>
 *
 */
enyo.kind({
    name: "Platform",
    kind: "Component",
    statics: {
        setup: function()
        {
            enyo.log("********* Setting up Platform Variables *************");
            enyo.log("window.PalmSystem "+ window.PalmSystem);
            enyo.log("window.blackberry "+ window.blackberry);
            enyo.log("window.PhoneGap "+ window.PhoneGap);
            enyo.log("window.device "+ window.device);
            if(window.device)
                enyo.log("window.device.platform "+ window.device.platform);
            enyo.log("window.chrome "+ window.chrome);

            /* If you include PhoneGap, but you don't wait until the device var
             * is initialized before calling this, we're going to ignore this
             * until the device var is available
             */
            if(window.PhoneGap && !window.device) {
                enyo.log("EnyoPlatform: PhoneGap detected, device not (yet) available. Bailing until next call.");
                return;
            }
            /* Check for systems where we don't have PhoneGap in our
             * requirements first, currently webOS and BlackBerry WebWorks
             * Even if you use PhoneGap on BlackBerry, according to the PhoneGap
             * documentation, it's platform determination code doesn't work
             * properly for at least some models.
             */
            if(typeof window.PalmSystem !== "undefined")
            {
                var deviceInfo = enyo.fetchDeviceInfo();
                this.platform = "webos";
                this.platformVersion = deviceInfo ? parseFloat(deviceInfo.platformVersion) : "unknown";
            }
            else if(typeof blackberry !== "undefined")
            {
                if(typeof PhoneGap !== "undefined")
                {
                    this.platform = "blackberry";
                }
                else
                {
                    this.platform = "webworks";
                }
                /* According to the BlackBerry docs,  to get the version number,
                 * we have to actually make an AJAX request to
                 * http://localhost:8472/blackberry/system/get . Screw that.
                 */
                this.platformVersion = "unknown";
            }
            else if(typeof PhoneGap !== "undefined")
            {
                /* See the PhoneGap Device API documentation for possible
                 * pitfalls.
                 */
                this.platform = device.platform.toLowerCase();
                this.platformVersion = parseFloat(device.version);
            }
            else
            {
                /* Someone with more time on their hands might be interested in
                 * breaking this out to determine various web browsers and their
                 * respective versions.  Not for me at this time.
                 */
                this.platform = "web";
                this.platformVersion = "unknown";
            }
            enyo.log("Platform detected: " + this.platform + " version " + this.platformVersion);
            enyo.log(" ************************************** ");
        },
        /* Should you find yourself in need of the raw platform name */
        getPlatformName: function() { this.platform || this.setup(); return this.platform; },

        /* Platform boolean functions -- return truthy if specific platform */
        isWebOS: function() { this.platform || this.setup(); return this.platform == "webos"; },
        isAndroid: function() { this.platform || this.setup(); return this.platform == "android"; },
        isBlackBerry: function() { this.platform || this.setup(); return this.platform == "blackberry" || this.platform == "webworks" },
        isWebWorks: function() { this.platform || this.setup(); return this.platform == "webworks"; },
        isiOS: function() { this.platform || this.setup(); return this.platform == "iphone"; },
        isMobile: function() { this.platform || this.setup(); return this.platform != "web"; },
        hasFlash: function() {
            this.platform || this.setup();
            return (this.platform == "webos" && this.platformVersion >= 2) ||
                    (this.isBlackBerry()) || // TODO: Version check?
                    (this.platform == "android");
        },

        /* General screen size functions -- tablet vs phone, landscape vs portrait */
        isLargeScreen: function() { return window.innerWidth > 480; },
        isWideScreen: function() { return window.innerWidth > window.innerHeight; },

        /* Platform-supplied UI concerns */
        hasBack: function()
        {
            this.platform || this.setup();
            return this.platform == "android" || (this.platform == "webos" && this.platformVersion < 3);
        },
        hasMenu: function()
        {
            /* You may want to include Android here if you're using a target
             * API of less than 14 (Ice Cream Sandwich)
             */
            /* Blackberry Tablet OS has a standard "swipe down from top bezel" gesture
             * that they use .. should probably consider that here, but I'm not sure
             * if their other platforms have any equivalent
             */
            this.platform || this.setup();
            return this.platform == "webos" || (this.platform == "android" && this.platformVersion < 4);
        },

        /* Platform-specific Audio utility. WebWorks on PlayBook and webOS have
         * great support for HTML5 audio objects. Android's is terrible, so we
         * choose to use the PhoneGap media API there, which is encapsulated in
         * the PlatformSound kind
         */
        useHTMLAudio: function()
        {
            this.platform || this.setup();
            return this.isWebOS() || this.isWebWorks() || !this.isMobile();
        },
        /* Platform Specific Web Browser -- returns a function that should
         * launch the OS's web browser.
         * call: Platform.browser("http://www.google.com/", this)();
         */
        browser: function(url, thisObj)
        {
            this.platform || this.setup();
            if(this.isWebOS())
            {
                return enyo.bind(thisObj, (function(args) {
                    var x = thisObj.createComponent({ name: "AppManService", kind: "PalmService", service: "palm://com.palm.applicationManager/", method: "open" });
                    x.call({ target: url });
                }));
            }
            else if(this.platform == "web" || (this.platform == "android" && parseFloat(this.platformVersion >= 4.0)) )
            {
                /* If web, just open a new tab/window - this also works well in
                 * Android 4.0 - suggest ChildBrowser PhoneGap plugin for other
                 * versions of Android
                 */
                return enyo.bind(thisObj, function(x) { window.open(x, '_blank'); }, url);
            }
            else if(this.isBlackBerry())
            {
                /* If BlackBerry, go through their ridiculous parsing rules */
                /* Make sure you have the invoke and invoke.BrowserArguments
                 * configured in your config.xml.
                 */
                var args = new blackberry.invoke.BrowserArguments(this.blackBerryURLEncode(url));
                return enyo.bind(thisObj, blackberry.invoke.invoke, blackberry.invoke.APP_BROWSER, args);
            }
            else if(typeof PhoneGap !== "undefined" && window.plugins && window.plugins.childBrowser)
            {
                /* If you have the popular childBrowser plugin for PhoneGap */
				/* If you're using iOS, make sure you've called the childBrowser.init first somewhere!! */
                return enyo.bind(thisObj, window.plugins.childBrowser.openExternal, url);
            }
            else if(this.platform == "android" && navigator.app && navigator.app.loadUrl)
            {
                /* If Android < 4.0 and PhoneGap ChildBrowser plugin is not available, then
                 * Assume PhoneGap is loaded, otherwise we wouldn't know it's Android, right */
                return enyo.bind(thisObj, function(x) { navigator.app.loadUrl({ openexternal:true }) }, url);
            }
            else
            {
                /* Fall back to something that could possibly work
                 * One could also make a case for just setting window.location
                 */
                return enyo.bind(thisObj, function(x) { window.open(x, '_blank'); }, url);
            }
        },
        /* A ridiculous function for parsing URLs into something that RIM's
         * BrowserArguments call can deal with "properly", thanks to their
         * forums.
         */
        blackBerryURLEncode: function(address) {
            var encodedAddress = "";
            // URL Encode all instances of ':' in the address
            encodedAddress = address.replace(/:/g, "%3A");
            // Leave the first instance of ':' in its normal form
            encodedAddress = encodedAddress.replace(/%3A/, ":");
            // Escape all instances of '&' in the address
            encodedAddress = encodedAddress.replace(/&/g, "\&");

            if (typeof blackberry !== 'undefined') {
                var args = new blackberry.invoke.BrowserArguments(encodedAddress);
                blackberry.invoke.invoke(blackberry.invoke.APP_BROWSER, args);
            } else {
                // If I am not a BlackBerry device, open link in current browser
                window.location = encodedAddress;
            }
        },
        getReviewURL: function()
        {
            var appInfo;
            var url = "";

            appInfo = enyo.fetchAppInfo();
            if(enyo.isString(appInfo))
                appInfo = JSON.parse(appInfo);

            this.platform || this.setup();
            switch(Platform.platform) {
                case "webos":
                    url = "http://developer.palm.com/appredirect/?packageid=" + appInfo.id;
                    break;
                case "android":
                    /* enyo.fetchAppId() appears unreliable here? */
                    url = "market://details?id=" + appInfo.id;
                    break;
                case "blackberry":  // intentional fallthrough
                case "webworks":
                    url = "http://appworld.blackberry.com/webstore/content/" + appInfo.appWorldId;
                    break;
                case "iphone":
                    url = "itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id="+appInfo.iTunesAppId;
                    break;
            }
            return url;
        }
    }
});

// experimental code that MIGHT work on an implementation where createHTMLNotification actually works.
// PlayBook 2.0, however, is not that place.

/* if(window.webkitNotifications)
{
    enyo.windows.openDashboard = (function(path, name, params, attributes) {
        enyo.log("openDashboard", path);
        if(window.webkitNotifications.checkPermission() == 0) {
	    enyo.log("opening dashboard");
	    var note = window.webkitNotifications.createHTMLNotification(path);
	    attributes = attributes || {};
	    attributes.window = "dashboard";
	    note.enyo = note.enyo || {};
	    note.enyo.windowParams = params || {};
	    note.show();
	}
    });
}*/

/* PlatformSound is an encapsulation for both the HTML5 audio support within
 * webOS and WebWorks, and an extension of some of the abilities of the stock
 * Enyo 1.0 Sound kind.
 */
enyo.kind({
    name: "PlatformSound",
    kind: "Sound",
    position: -1,
    /* Play our sound. If our sound is already playing, restart it */
    published: {
        audioClass: "",
    },
	audioClassChanged: function() {
		if (this.audio) {
			if (this.audioClass) {
				this.audio.setAttribute("x-palm-media-audio-class", this.audioClass);
			}
			else {
				this.audio.removeAttribute("x-palm-media-audio-class");
			}
		}
	},
    play: function() {
        if(!Platform.useHTMLAudio()) {
            if(window.PhoneGap)
                this.media.play();
        } else {
            if (!this.audio.paused) {
                this.audio.currentTime = 0;
            } else {
                this.audio.play();
            }
        }
        this.Paused = false;
        if(!Platform.useHTMLAudio())
        {
            /* The PhoneGap media API does not document it's "MediaProgress"
             * callback, nor does it seem to be supported universally, at least
             * with PhoneGap 1.4.1, so, i'm going to just run a timer to the
             * getCurrentPosition() asynch method, and record it regularly.
             */
            this.Timer = setInterval(enyo.bind(this, this.getMediaPos), 100);
        }
    },
    /* Override the function from the base Enyo 1.0 kind, to add support for
     * the PhoneGap Media callbacks that they provide now
     */
    srcChanged: function() {
        var path = enyo.path.rewrite(this.src);
        if(!Platform.useHTMLAudio()) {
            if(window.PhoneGap)
                this.media = new Media(path, this.MediaSuccess, this.mediaFail, this.mediaStatus, this.mediaProgress);
            else
                enyo.log("*** Don't know how to play media without HTML5 or PhoneGap!", Platform.platform);
        } else {
            this.audio = new Audio();
            this.audio.src = path;
            /* We need to reset the preloadChanged and audioClassChanged attributes
             * as they are only propagated to the underlying audio tag at creation
             * in the original Enyo code
             */
            this.preloadChanged();
            this.audioClassChanged();
        }
    },
    /* Internal callback functions */
    getMediaPos: function(x, y, z) {
        this.media.getCurrentPosition(enyo.bind(this, this.posReceived));
    },
    posReceived: function(x, y, z) {
        this.position = x;
    },
    mediaSuccess: function(x, y, z) {
        enyo.log("mediaSuccess "+ x+ y+ z);
    },
    mediaFail: function(x, y, z) {
        enyo.log("mediaFail "+ x+ y+ z);
    },
    mediaStatus: function(x, y, z) {
        /* Possible Media States, taken from PhoneGap 1.4.1 Android source:
         *  Media.MEDIA_NONE = 0;
         *  Media.MEDIA_STARTING = 1;
         *  Media.MEDIA_RUNNING = 2;
         *  Media.MEDIA_PAUSED = 3;
         *  Media.MEDIA_STOPPED = 4;
         * not really sure what to make of them, so I just note Paused for now.
         */
        if(x == Media.MEDIA_Paused)
            this.Paused = true;
        else
            this.Paused = false;
        enyo.log("mediaStatus"+ x+ y+ z);
    },
    mediaProgress: function(x, y, z) {
        /* This callback specified in the Media constructor doesn't seem to
         * work on Android at the moment?  If you see it working somewhere, you
         * could kill the setInterval in Play on that platform, and record the
         * progress here instead.
         */
        enyo.log("mediaProgress "+ x+ y+ z);
    },
    /* Return the current position of audio playback, HTML5 and PhoneGap both
     * seem to like it as a float down to millisecond resolution
     */
    getCurrentPosition: function() {
        /* I wasn't able to get PhoneGap's media._position to give me a valid
         * location reliably, so we record it from the callback
         */
        return Platform.useHTMLAudio() ? this.audio.currentTime : this.position; /* PhoneGap's media._position doesn't seem to load? */
    },
    /* Returns the duration of the loaded media */
    getDuration: function() {
        return !Platform.useHTMLAudio() ? this.media.getDuration() : this.audio.duration;
    },
    /* Pause playback - calling play should resume */
    pause: function() {
        this.Paused = true;
        clearInterval(this.Timer);
        !Platform.useHTMLAudio() ? this.media.pause() : this.audio.pause();
    },
    /* Forces PhoneGap to release media handles in the OS, they recommend that
     * you call this whenever you stop playback on Android.  Also destroys
     * the component, so you can create a new one when you need more playback.
     */
    release: function() {
        this.pause();
        if(!Platform.useHTMLAudio()) {
            this.media.release();
        }
        this.destroy();
    },
    /* Reposition the media playback from the given location.  HTML5 apparently
     * uses a float with seconds, whereas PhoneGap is looking for an int in
     * milliseconds
     */
    seekTo: function(loc) {
        if(!Platform.useHTMLAudio() ) {
            this.media.seekTo(loc * 1000);
        } else {
            this.audio.currentTime = loc;
        }
    },
    /* Stop playback.  Do not destroy anything.  Next call to play will restart
     * playback from the beginning.
     */
    stop: function() {
        clearInterval(this.Timer);
        if(!Platform.useHTMLAudio() ) {
            this.media.stop();
        } else {
            this.audio.pause();
            this.audio.currentTime = 0;
        }
    }
});<|endoftext|>