<commit_before>/* Tests the streaming xhr without stubbing anything. Really just a test that
*  we've got the interface of the in-browser XHR object pinned down  */

(function(){

   AsyncTestCase("testStreamingXhr", {

      // shorten the waiting time before a test fails. Default 30s is too long:
      setUp: function(){
         jstestdriver.plugins.async.CallbackPool.TIMEOUT = ASYNC_TEST_TIMEOUT;
      },

      testCanAjaxInASmallKnownFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // in practice, since we're running on an internal network and this is a small file,
            // we'll probably only get one callback
            streamingXhr(
               '/test/test/json/smallestPossible.json',
               callbacks.add(function(nextDrip){
                  combinedResult += nextDrip;
               })
            );
         });

         queue.call("check we got the json back", function(){
            assertEquals('{}', combinedResult);
         });
      },

      testCanAjaxInAVeryLargeFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            var parsedResult = JSON.parse(combinedResult);

            // as per the name, should have 20,000 records in that file:
            assertEquals(20000, parsedResult.result.length);
         });
      },

      testCanAjaxInAStreamingFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               cacheBustUrl('/stream/tenSlowNumbers'),

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            try{
               var parsedResult = JSON.parse(combinedResult);
            } catch(e) {
               fail('could not parse json "' + combinedResult + '" because ' + e
                   + ' this might happen if the browsers are connecting directly'
                   + ' to jstd instead of through the proxy'
                   );
            }

            // as per the name, should have 20,000 records in that file:
            assertEquals([0,1,2,3,4,5,6,7,8,9], parsedResult);
         });
      },

      testDoesntCallbackWithoutNewData: function(queue) {

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  if( nextDrip.length === 0 ) {
                     fail('zero-length drip received');
                  }
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // we're done
               callbacks.noop()
            )
         });

      },

      testAjaxingOverStreamingHttpGivesMultipleCallbacks: function(queue) {

         var numberOfProgressCallbacks = 0;

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               cacheBustUrl('/stream/tenSlowNumbers'),

               function onProgress( drip ){
                  console.log('I got a drip', drip, numberOfProgressCallbacks);
                  numberOfProgressCallbacks++;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got multiple callbacks", function(){

            if( numberOfProgressCallbacks < 10)(
               fail("I had " + numberOfProgressCallbacks + " progress callback(s), should have" +
                   " had at least 10")
            );
         });
      }
   });

   function cacheBustUrl(url) {
      var now = Date.now? Date.now() : new Date().valueOf();

      return url + '/cacheBusted/' + now + '.txt';
   }

})();<commit_msg>improve error msg<commit_after>/* Tests the streaming xhr without stubbing anything. Really just a test that
*  we've got the interface of the in-browser XHR object pinned down  */

(function(){

   AsyncTestCase("testStreamingXhr", {

      // shorten the waiting time before a test fails. Default 30s is too long:
      setUp: function(){
         jstestdriver.plugins.async.CallbackPool.TIMEOUT = ASYNC_TEST_TIMEOUT;
      },

      testCanAjaxInASmallKnownFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // in practice, since we're running on an internal network and this is a small file,
            // we'll probably only get one callback
            streamingXhr(
               '/test/test/json/smallestPossible.json',
               callbacks.add(function(nextDrip){
                  combinedResult += nextDrip;
               })
            );
         });

         queue.call("check we got the json back", function(){
            assertEquals('{}', combinedResult);
         });
      },

      testCanAjaxInAVeryLargeFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            var parsedResult = JSON.parse(combinedResult);

            // as per the name, should have 20,000 records in that file:
            assertEquals(20000, parsedResult.result.length);
         });
      },

      testCanAjaxInAStreamingFileWithoutMissingAny: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               cacheBustUrl('/stream/tenSlowNumbers'),

               function(nextDrip){
                  combinedResult += nextDrip;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            try{
               var parsedResult = JSON.parse(combinedResult);
            } catch(e) {
               fail('could not parse json "' + combinedResult + '" because ' + e
                   + ' this might happen if the browsers are connecting directly'
                   + ' to jstd instead of through the proxy'
                   );
            }

            // as per the name, should have 20,000 records in that file:
            assertEquals([0,1,2,3,4,5,6,7,8,9], parsedResult);
         });
      },

      testDoesntCallbackWithoutNewData: function(queue) {

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               '/test/test/json/twentyThousandRecords.json',

               function(nextDrip){
                  if( nextDrip.length === 0 ) {
                     fail('zero-length drip received');
                  }
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // we're done
               callbacks.noop()
            )
         });

      },

      testAjaxingOverStreamingHttpGivesMultipleCallbacks: function(queue) {

         var numberOfProgressCallbacks = 0;

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr(
               cacheBustUrl('/stream/tenSlowNumbers'),

               function onProgress( drip ){
                  console.log('I got a drip', drip, numberOfProgressCallbacks);
                  numberOfProgressCallbacks++;
               },

               // callback for when the stream is complete. we register this just so that jstd knows
               // when to move onto the next queuer
               callbacks.noop()
            )
         });

         queue.call("check we got multiple callbacks", function(){

            // realistically, should have had 10 or 20, but this isn't deterministic so
            // 3 is enough to indicate the results didn't all arrive in one big blob.
            if( numberOfProgressCallbacks < 3)(
               fail("I had " + numberOfProgressCallbacks + " progress callback(s), should have" +
                   " had at least 3. If this doesn't test the browser's XHR might not support" +
                   " reading partial responses")
            );
         });
      }
   });

   function cacheBustUrl(url) {
      var now = Date.now? Date.now() : new Date().valueOf();

      return url + '/cacheBusted/' + now + '.txt';
   }

})();<|endoftext|>


<commit_before>/**
* @jest-environment node
*
* Theese test checks that the examples installs with packages from npm,
* that they build, the dev server runs as expected and is reachable at port 3000
*/
'use strict';
//
//
//
// require('leaked-handles').set({
//     fullStack: true, // use full stack traces
//     timeout: 30000, // run every 30 seconds instead of 5.
//     debugSockets: true // pretty print tcp thrown exceptions.
// });

const puppeteer = require('puppeteer');
const terminate = require('terminate');

const assert = require('assert');
const os = require('os');
const fs = require('fs-extra');
const rfs = require('fs');
const execa = require('execa');
const util = require('util');
const glob = util.promisify(require('glob'));

const path = require("path");
const copy = require('recursive-copy');
const mkdtemp = util.promisify(fs.mkdtemp);
const mkdtempTpl = path.join(os.tmpdir(), 'example-');

const directoryExists = (dirPath) => fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
const fileExists = (dirPath) => fs.existsSync(dirPath);

const rootDir = path.join(path.resolve(__dirname), '..', '..');
const testArtifactsDir = path.join(rootDir, 'test-artifacts');

const silent = !process.env.NOISY_TESTS;
const stdio = 'pipe';

const useCra = process.env.NPM_TAG !== 'development';

const use_package_manager = typeof process.env.PACKAGE_MANAGER === 'undefined' ? 'default' : process.env.PACKAGE_MANAGER;

const package_manager = use_package_manager === 'default' ? 'yarn' : use_package_manager;

const cra_package_manager = use_package_manager === 'default' ? false : use_package_manager;

const install_deps_args = package_manager === 'yarn' ?
[ "install", "--ignore-engines" ] :
[ "install" ];

const add_webpack_deps_args = package_manager === 'yarn' ?
[ "add", "--dev", `${process.env.WEBPACK_DEPS}`, "--ignore-engines" ] :
[ "install", "--save-dev", `${process.env.WEBPACK_DEPS}` ];

const use_npm_tag = typeof process.env.NPM_TAG === 'undefined' ? '' : `@${process.env.NPM_TAG}`;

const writeLogs = true;

let examples =
    { simple: [
      { example: 'basic', path: 'examples/basic' },
      { example: 'basic-spa', path: 'examples/basic-spa' },
      {
        example: 'with-custom-babel-config',
        path: 'examples/with-custom-babel-config'
      },
      {
        example: 'with-custom-devserver-options',
        path: 'examples/with-custom-devserver-options'
      },
      {
        example: 'with-custom-environment-variables',
        path: 'examples/with-custom-environment-variables'
      },
      {
        example: 'with-custom-target-babel-config',
        path: 'examples/with-custom-target-babel-config'
      },
      {
        example: 'with-custom-webpack-config',
        path: 'examples/with-custom-webpack-config'
      },
      { example: 'with-eslint', path: 'examples/with-eslint' },
      {
        example: 'with-experimental-refresh',
        path: 'examples/with-experimental-refresh'
      },
      {
        example: 'with-firebase-functions',
        path: 'examples/with-firebase-functions'
      },
      { example: 'with-heroku', path: 'examples/with-heroku' },
      { example: 'with-hyperapp', path: 'examples/with-hyperapp' },
      { example: 'with-inferno', path: 'examples/with-inferno' },
      {
        example: 'with-jest-snapshots',
        path: 'examples/with-jest-snapshots'
      },
      {
        example: 'with-jsconfig-paths',
        path: 'examples/with-jsconfig-paths'
      },
      { example: 'with-jsxstyle', path: 'examples/with-jsxstyle' },
      { example: 'with-koa', path: 'examples/with-koa' },
      { example: 'with-less', path: 'examples/with-less' },
      {
        example: 'with-loadable-components',
        path: 'examples/with-loadable-components'
      },
      { example: 'with-material-ui', path: 'examples/with-material-ui' },
      { example: 'with-mdx', path: 'examples/with-mdx' },
      { example: 'with-now', path: 'examples/with-now' },
      { example: 'with-now-v2', path: 'examples/with-now-v2' },
      { example: 'with-polka', path: 'examples/with-polka' },
      { example: 'with-preact', path: 'examples/with-preact' },
      {
        example: 'with-promise-config',
        path: 'examples/with-promise-config'
      },
      {
        example: 'with-react-native-web',
        path: 'examples/with-react-native-web'
      },
      { example: 'with-react-router', path: 'examples/with-react-router' },
      {
        example: 'with-react-server-components',
        path: 'examples/with-react-server-components'
      },
      { example: 'with-redux', path: 'examples/with-redux' },
      { example: 'with-scss', path: 'examples/with-scss' },
      { example: 'with-scss-options', path: 'examples/with-scss-options' },
      {
        example: 'with-single-exposed-port',
        path: 'examples/with-single-exposed-port'
      },
      {
        example: 'with-styled-components',
        path: 'examples/with-styled-components'
      },
      { example: 'with-svelte', path: 'examples/with-svelte' },
      { example: 'with-tailwindcss', path: 'examples/with-tailwindcss' },
      { example: 'with-typescript', path: 'examples/with-typescript' },
      {
        example: 'with-typescript-plugin',
        path: 'examples/with-typescript-plugin'
      },
      {
        example: 'with-vendor-bundle',
        path: 'examples/with-vendor-bundle'
      },
      { example: 'with-vue', path: 'examples/with-vue' },
      { example: 'with-vue-router', path: 'examples/with-vue-router' },
      {
        example: 'with-webpack-public-path',
        path: 'examples/with-webpack-public-path'
      }
    ], complex: [
    { example: 'with-monorepo', path: 'examples/with-monorepo' }, // test timing ssues
    {
      example: 'with-module-federation', // test timing ssues
      path: 'examples/with-module-federation'
    },
    { example: 'with-reason-react', path: 'examples/with-reason-react' }, // test timing ssues
    {
      example: 'with-typeorm-graphql', // test timing ssues
      path: 'examples/with-typeorm-graphql'
    },
    // { example: 'with-elm', path: 'examples/with-elm' }, // requires elm binary
    // {
    //   example: 'with-devcert-https', // may not be possible to test
    //   path: 'examples/with-devcert-https'
    // }
  ]
};

let browser;
let page;

beforeAll(async function(done) {
  browser = await puppeteer.launch({ headless: process.env.HEADLESS !== "false"  });
  page = await browser.newPage();
  await fs.ensureDir(testArtifactsDir);
  // const res = await glob('examples/*')
  // examples=res.map(ex=>({example: ex.split('/')[1], path: ex}))
  // console.log(examples)
  done();
});

afterAll(async function(done) {
  await browser.close();
  await new Promise((r) => setTimeout(r, 3000));
  done();
});
Object.keys(examples).forEach((exampleType) => {

  describe(`tests for ${exampleType} isomorphic examples`, () => {

    examples[exampleType].forEach(exampleinfo => {
      const example=exampleinfo.example;

      describe(`tests for the ${example} example`, () => {
        let tempDir;
        let craDir;
        let razzleMeta;

        beforeAll(async function(done) {

          razzleMeta = JSON.parse(await fs.readFile(
            path.join(rootDir, exampleinfo.path, 'package.json'))).razzle_meta||{};

          mkdtemp(mkdtempTpl, (err, directory) => {
            tempDir = directory;
            craDir = path.join(directory, 'example');

            if (!useCra) {
              copy(path.join(rootDir, exampleinfo.path), tempDir, { dot: true },async function(error, results) {
                if (error) {
                  console.error('Copy failed: ' + error);
                } else {
                  // console.info('Copied ' + results.length + ' files');
                }
                done();
              })
            } else {
              done();
            }
          })
        });

        afterAll(async function(done) {
          fs.remove(tempDir, err => {
            assert(!err)
            done();
          });
        });

        jest.setTimeout(300000);

        it(`should install packages`, async function(done) {
          if (!useCra) {
            const subprocess = execa(package_manager,
              install_deps_args,
              {stdio: stdio, cwd: tempDir, all: writeLogs })

            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-${package_manager}-install.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped install packages");
            done();
          }
        }, 300000);

        it(`should run create-razzle-app successfully`, async function(done) {

          if (useCra) {
            const subprocess = execa("npx", [
              `create-razzle-app${use_npm_tag}`,,
              cra_package_manager && `--${cra_package_manager}`,
              "--verbose",
              "--example",
              example,
              "example"
            ].filter(x=>x), {stdio: stdio, cwd: tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-create-razzle-app.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(async ({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped run create-razzle-app successfully");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should use specific webpack and html-webpack-plugin`, async function(done) {
          if (process.env.WEBPACK_DEPS && !razzleMeta.forceWebpack) {
            const subprocess = execa(package_manager,
              add_webpack_deps_args
            , {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-add-deps.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped use specific webpack and html-webpack-plugin");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should build successfully`, async function(done) {
          const subprocess = execa(package_manager, ["build", "--noninteractive"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-build.txt`));
            subprocess.all.pipe(write);
          }

          subprocess.then(({exitCode})=>{
            assert.equal(exitCode, 0)
            done();
          })
          await subprocess;
        }, 300000);

        jest.setTimeout(300000);

        it(`should start devserver and exit`, async function(done) {

          const subprocess = execa(package_manager, ["start"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-start.txt`));
            subprocess.all.pipe(write);
          }

          let resolved = false;
          let timer;

          await new Promise(async (r) =>{
            console.info(`${package_manager} start for ${example} `);
            const waitForData = data => {
              if (data.toString().includes('Server-side HMR Enabled!') || data.toString().includes('> SPA Started on port')) {
                resolved = true;
                subprocess.off('data', waitForData)
                clearTimeout(timer);
                r();
              }
            }
            timer = setTimeout(function() {
              if (!resolved) {
                subprocess.off('data', waitForData)
                r();
              }
            }, 15000)
            subprocess.stdout.on('data', waitForData);
          })
          if (razzleMeta.yarnStartDelay) {
            await new Promise((r) => setTimeout(r, razzleMeta.yarnStartDelay));
          }
          if (resolved) {
            await page.goto(`${razzleMeta.protocol||'http'}://localhost:${razzleMeta.port||'3000'}/`);
            await page.screenshot({ path: path.join(testArtifactsDir, `${example}.png`) });
          }

          await new Promise((r) => setTimeout(r, 2000));

          terminate(subprocess.pid, 'SIGINT', { timeout: 3000 }, async () => {
            terminate(subprocess.pid);
            assert.ok(resolved, `yarn start for ${example} failed`);
            done();
          });

        }, 300000);

      });
    });
  });

});
<commit_msg>Update isomorphic-examples.test.js<commit_after>/**
* @jest-environment node
*
* Theese test checks that the examples installs with packages from npm,
* that they build, the dev server runs as expected and is reachable at port 3000
*/
'use strict';
//
//
//
// require('leaked-handles').set({
//     fullStack: true, // use full stack traces
//     timeout: 30000, // run every 30 seconds instead of 5.
//     debugSockets: true // pretty print tcp thrown exceptions.
// });

const puppeteer = require('puppeteer');
const terminate = require('terminate');

const assert = require('assert');
const os = require('os');
const fs = require('fs-extra');
const rfs = require('fs');
const execa = require('execa');
const util = require('util');
const glob = util.promisify(require('glob'));

const path = require("path");
const copy = require('recursive-copy');
const mkdtemp = util.promisify(fs.mkdtemp);
const mkdtempTpl = path.join(os.tmpdir(), 'example-');

const directoryExists = (dirPath) => fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
const fileExists = (dirPath) => fs.existsSync(dirPath);

const rootDir = path.join(path.resolve(__dirname), '..', '..');
const testArtifactsDir = path.join(rootDir, 'test-artifacts');

const silent = !process.env.NOISY_TESTS;
const stdio = 'pipe';

const useCra = process.env.NPM_TAG !== 'development';

const use_package_manager = typeof process.env.PACKAGE_MANAGER === 'undefined' ? 'default' : process.env.PACKAGE_MANAGER;

const package_manager = use_package_manager === 'default' ? 'yarn' : use_package_manager;

const cra_package_manager = use_package_manager === 'default' ? false : use_package_manager;

const install_deps_args = package_manager === 'yarn' ?
[ "install", "--ignore-engines" ] :
[ "install" ];

const webpack_deps = typeof process.env.WEBPACK_DEPS !== 'undefined' ? process.env.WEBPACK_DEPS.split(' ') : false;

const add_webpack_deps_args = package_manager === 'yarn' ?
[ "add", "--dev" ].concat(webpack_deps).concat([ "--ignore-engines" ]) :
[ "install", "--save-dev"].concat(webpack_deps);

const use_npm_tag = typeof process.env.NPM_TAG === 'undefined' ? '' : `@${process.env.NPM_TAG}`;

const writeLogs = true;

let examples =
    { simple: [
      { example: 'basic', path: 'examples/basic' },
      { example: 'basic-spa', path: 'examples/basic-spa' },
      {
        example: 'with-custom-babel-config',
        path: 'examples/with-custom-babel-config'
      },
      {
        example: 'with-custom-devserver-options',
        path: 'examples/with-custom-devserver-options'
      },
      {
        example: 'with-custom-environment-variables',
        path: 'examples/with-custom-environment-variables'
      },
      {
        example: 'with-custom-target-babel-config',
        path: 'examples/with-custom-target-babel-config'
      },
      {
        example: 'with-custom-webpack-config',
        path: 'examples/with-custom-webpack-config'
      },
      { example: 'with-eslint', path: 'examples/with-eslint' },
      {
        example: 'with-experimental-refresh',
        path: 'examples/with-experimental-refresh'
      },
      {
        example: 'with-firebase-functions',
        path: 'examples/with-firebase-functions'
      },
      { example: 'with-heroku', path: 'examples/with-heroku' },
      { example: 'with-hyperapp', path: 'examples/with-hyperapp' },
      { example: 'with-inferno', path: 'examples/with-inferno' },
      {
        example: 'with-jest-snapshots',
        path: 'examples/with-jest-snapshots'
      },
      {
        example: 'with-jsconfig-paths',
        path: 'examples/with-jsconfig-paths'
      },
      { example: 'with-jsxstyle', path: 'examples/with-jsxstyle' },
      { example: 'with-koa', path: 'examples/with-koa' },
      { example: 'with-less', path: 'examples/with-less' },
      {
        example: 'with-loadable-components',
        path: 'examples/with-loadable-components'
      },
      { example: 'with-material-ui', path: 'examples/with-material-ui' },
      { example: 'with-mdx', path: 'examples/with-mdx' },
      { example: 'with-now', path: 'examples/with-now' },
      { example: 'with-now-v2', path: 'examples/with-now-v2' },
      { example: 'with-polka', path: 'examples/with-polka' },
      { example: 'with-preact', path: 'examples/with-preact' },
      {
        example: 'with-promise-config',
        path: 'examples/with-promise-config'
      },
      {
        example: 'with-react-native-web',
        path: 'examples/with-react-native-web'
      },
      { example: 'with-react-router', path: 'examples/with-react-router' },
      {
        example: 'with-react-server-components',
        path: 'examples/with-react-server-components'
      },
      { example: 'with-redux', path: 'examples/with-redux' },
      { example: 'with-scss', path: 'examples/with-scss' },
      { example: 'with-scss-options', path: 'examples/with-scss-options' },
      {
        example: 'with-single-exposed-port',
        path: 'examples/with-single-exposed-port'
      },
      {
        example: 'with-styled-components',
        path: 'examples/with-styled-components'
      },
      { example: 'with-svelte', path: 'examples/with-svelte' },
      { example: 'with-tailwindcss', path: 'examples/with-tailwindcss' },
      { example: 'with-typescript', path: 'examples/with-typescript' },
      {
        example: 'with-typescript-plugin',
        path: 'examples/with-typescript-plugin'
      },
      {
        example: 'with-vendor-bundle',
        path: 'examples/with-vendor-bundle'
      },
      { example: 'with-vue', path: 'examples/with-vue' },
      { example: 'with-vue-router', path: 'examples/with-vue-router' },
      {
        example: 'with-webpack-public-path',
        path: 'examples/with-webpack-public-path'
      }
    ], complex: [
    { example: 'with-monorepo', path: 'examples/with-monorepo' }, // test timing ssues
    {
      example: 'with-module-federation', // test timing ssues
      path: 'examples/with-module-federation'
    },
    { example: 'with-reason-react', path: 'examples/with-reason-react' }, // test timing ssues
    {
      example: 'with-typeorm-graphql', // test timing ssues
      path: 'examples/with-typeorm-graphql'
    },
    // { example: 'with-elm', path: 'examples/with-elm' }, // requires elm binary
    // {
    //   example: 'with-devcert-https', // may not be possible to test
    //   path: 'examples/with-devcert-https'
    // }
  ]
};

let browser;
let page;

beforeAll(async function(done) {
  browser = await puppeteer.launch({ headless: process.env.HEADLESS !== "false"  });
  page = await browser.newPage();
  await fs.ensureDir(testArtifactsDir);
  // const res = await glob('examples/*')
  // examples=res.map(ex=>({example: ex.split('/')[1], path: ex}))
  // console.log(examples)
  done();
});

afterAll(async function(done) {
  await browser.close();
  await new Promise((r) => setTimeout(r, 3000));
  done();
});
Object.keys(examples).forEach((exampleType) => {

  describe(`tests for ${exampleType} isomorphic examples`, () => {

    examples[exampleType].forEach(exampleinfo => {
      const example=exampleinfo.example;

      describe(`tests for the ${example} example`, () => {
        let tempDir;
        let craDir;
        let razzleMeta;

        beforeAll(async function(done) {

          razzleMeta = JSON.parse(await fs.readFile(
            path.join(rootDir, exampleinfo.path, 'package.json'))).razzle_meta||{};

          mkdtemp(mkdtempTpl, (err, directory) => {
            tempDir = directory;
            craDir = path.join(directory, 'example');

            if (!useCra) {
              copy(path.join(rootDir, exampleinfo.path), tempDir, { dot: true },async function(error, results) {
                if (error) {
                  console.error('Copy failed: ' + error);
                } else {
                  // console.info('Copied ' + results.length + ' files');
                }
                done();
              })
            } else {
              done();
            }
          })
        });

        afterAll(async function(done) {
          fs.remove(tempDir, err => {
            assert(!err)
            done();
          });
        });

        jest.setTimeout(300000);

        it(`should install packages`, async function(done) {
          if (!useCra) {
            const subprocess = execa(package_manager,
              install_deps_args,
              {stdio: stdio, cwd: tempDir, all: writeLogs })

            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-${package_manager}-install.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped install packages");
            done();
          }
        }, 300000);

        it(`should run create-razzle-app successfully`, async function(done) {

          if (useCra) {
            const subprocess = execa("npx", [
              `create-razzle-app${use_npm_tag}`,,
              cra_package_manager && `--${cra_package_manager}`,
              "--verbose",
              "--example",
              example,
              "example"
            ].filter(x=>x), {stdio: stdio, cwd: tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-create-razzle-app.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(async ({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped run create-razzle-app successfully");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should use specific webpack and html-webpack-plugin`, async function(done) {
          if (webpack_deps && !razzleMeta.forceWebpack) {
            console.log(`Installing ${webpack_deps.join(' ')} using ${package_manager}`);
            const subprocess = execa(package_manager,
              add_webpack_deps_args
            , {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-add-deps.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped use specific webpack and html-webpack-plugin");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should build successfully`, async function(done) {
          const subprocess = execa(package_manager, ["build", "--noninteractive"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-build.txt`));
            subprocess.all.pipe(write);
          }

          subprocess.then(({exitCode})=>{
            assert.equal(exitCode, 0)
            done();
          })
          await subprocess;
        }, 300000);

        jest.setTimeout(300000);

        it(`should start devserver and exit`, async function(done) {

          const subprocess = execa(package_manager, ["start"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-start.txt`));
            subprocess.all.pipe(write);
          }

          let resolved = false;
          let timer;

          await new Promise(async (r) =>{
            console.info(`${package_manager} start for ${example} `);
            const waitForData = data => {
              if (data.toString().includes('Server-side HMR Enabled!') || data.toString().includes('> SPA Started on port')) {
                resolved = true;
                subprocess.off('data', waitForData)
                clearTimeout(timer);
                r();
              }
            }
            timer = setTimeout(function() {
              if (!resolved) {
                subprocess.off('data', waitForData)
                r();
              }
            }, 15000)
            subprocess.stdout.on('data', waitForData);
          })
          if (razzleMeta.yarnStartDelay) {
            await new Promise((r) => setTimeout(r, razzleMeta.yarnStartDelay));
          }
          if (resolved) {
            await page.goto(`${razzleMeta.protocol||'http'}://localhost:${razzleMeta.port||'3000'}/`);
            await page.screenshot({ path: path.join(testArtifactsDir, `${example}.png`) });
          }

          await new Promise((r) => setTimeout(r, 2000));

          terminate(subprocess.pid, 'SIGINT', { timeout: 3000 }, async () => {
            terminate(subprocess.pid);
            assert.ok(resolved, `yarn start for ${example} failed`);
            done();
          });

        }, 300000);

      });
    });
  });

});
<|endoftext|>


<commit_before>// test ConstantNode
var assert = require('assert');
var approx = require('../../../tools/approx');
var math = require('../../../index');
var bigmath = require('../../../index').create({number: 'BigNumber'});
var Node = math.expression.node.Node;
var ConstantNode = math.expression.node.ConstantNode;
var SymbolNode = math.expression.node.SymbolNode;
var Fraction = require('../../../lib/type/fraction/Fraction');

describe('ConstantNode', function() {

  it ('should create a ConstantNode', function () {
    var a = new ConstantNode(3);
    assert(a instanceof Node);
    assert.equal(a.type, 'ConstantNode');
    // TODO: extensively test each of the supported types

    assert.strictEqual(new ConstantNode(3).value, 3);
    assert.strictEqual(new ConstantNode('hello').value, 'hello');
    assert.strictEqual(new ConstantNode(true).value, true);
    assert.strictEqual(new ConstantNode(false).value, false);
    assert.strictEqual(new ConstantNode(null).value, null);
    assert.strictEqual(new ConstantNode(undefined).value, undefined);
  });

  it ('should have isConstantNode', function () {
    var node = new ConstantNode(1);
    assert(node.isConstantNode);
  });

  it ('should throw an error when calling without new operator', function () {
    assert.throws(function () {ConstantNode(3)}, SyntaxError);
  });

  it ('should compile a ConstantNode', function () {
    var expr = new ConstantNode(2.3).compile();
    assert.strictEqual(expr.eval(), 2.3);

    expr = new ConstantNode(2.3).compile();
    assert.strictEqual(expr.eval(), 2.3);

    expr = new ConstantNode('hello').compile();
    assert.strictEqual(expr.eval(), 'hello');

    expr = new ConstantNode(true).compile();
    assert.strictEqual(expr.eval(), true);

    expr = new ConstantNode(undefined).compile();
    assert.strictEqual(expr.eval(), undefined);

    expr = new ConstantNode(null).compile();
    assert.strictEqual(expr.eval(), null);

  });

  it ('should compile a ConstantNode with bigmath', function () {
    var constantNode = bigmath.parse('2.3');
    assert.ok(constantNode.isConstantNode);
    var expr = constantNode.compile();
    assert.deepEqual(expr.eval(), new bigmath.type.BigNumber(2.3));
  });

  it ('should find a ConstantNode', function () {
    var a = new ConstantNode(2);
    assert.deepEqual(a.filter(function (node) {return node instanceof ConstantNode}),  [a]);
    assert.deepEqual(a.filter(function (node) {return node instanceof SymbolNode}), []);
  });

  it ('should leave quotes in strings as is (no escaping)', function () {
    assert.strictEqual( new ConstantNode('"+foo+"').compile().eval(), '"+foo+"')
    assert.strictEqual( new ConstantNode('\\"escaped\\"').compile().eval(), '\\"escaped\\"')
  });

  it ('should find a ConstantNode', function () {
    var a = new ConstantNode(2);
    assert.deepEqual(a.filter(function (node) {return node instanceof ConstantNode}),  [a]);
    assert.deepEqual(a.filter(function (node) {return node instanceof SymbolNode}), []);
  });

  it ('should run forEach on a ConstantNode', function () {
    var a = new ConstantNode(2);
    a.forEach(function () {
      assert.ok(false, 'should not execute, constant has no childs')
    });
  });

  it ('should map a ConstantNode', function () {
    var a = new ConstantNode(2);
    var b = a.map(function () {
      assert.ok(false, 'should not execute, constant has no childs')
    });

    assert.notStrictEqual(b, a);
    assert.deepEqual(b, a);
  });

  it ('should transform a ConstantNode', function () {
    var a = new ConstantNode(2);
    var b = new ConstantNode(3);
    var c = a.transform(function (node) {
      return node instanceof ConstantNode && node.value == '2' ? b : node;
    });
    assert.deepEqual(c,  b);

    // no match should leave the node as is
    var d = a.transform(function (node) {
      return node instanceof ConstantNode && node.value == '99' ? b : node;
    });
    assert.notStrictEqual(d, a);
    assert.deepEqual(d,  a);
  });

  it ('should clone a ConstantNode', function () {
    var a = new ConstantNode(2);
    var b = a.clone();

    assert(b instanceof ConstantNode);
    assert.deepEqual(a, b);
    assert.notStrictEqual(a, b);
    assert.equal(a.value, b.value);
    assert.equal(a.valueType, b.valueType);
  });

  it ('test equality another Node', function () {
    var a = new ConstantNode(2);

    assert.strictEqual(a.equals(null), false);
    assert.strictEqual(a.equals(undefined), false);
    assert.strictEqual(a.equals(new ConstantNode(2)), true);
    assert.strictEqual(a.equals(new ConstantNode(3)), false);
    assert.strictEqual(a.equals(new ConstantNode('2')), false);
    assert.strictEqual(a.equals(new SymbolNode('2')), false);
    assert.strictEqual(a.equals({value:2}), false);
  });

  it ('should stringify a ConstantNode', function () {
    assert.equal(new ConstantNode(3).toString(), '3');
    assert.deepEqual(new ConstantNode(3).toString(), '3');
    assert.deepEqual(new ConstantNode(math.bignumber('1e500')).toString(), '1e+500');
    assert.deepEqual(new ConstantNode(math.fraction(2,3)).toString(), '2/3');
    assert.equal(new ConstantNode('hi').toString(), '"hi"');
    assert.equal(new ConstantNode(true).toString(), 'true');
    assert.equal(new ConstantNode(false).toString(), 'false');
    assert.equal(new ConstantNode(undefined).toString(), 'undefined');
    assert.equal(new ConstantNode(null).toString(), 'null');
  });

  it ('should stringify a ConstantNode with custom toString', function () {
    //Also checks if the custom functions get passed on to the children
    var customFunction = function (node, options) {
      if (node.type === 'ConstantNode') {
        return 'const(' + node.value + ')'
      }
    };

    var n = new ConstantNode(1);

    assert.equal(n.toString({handler: customFunction}), 'const(1)');
  });

  it ('should LaTeX a ConstantNode', function () {
    assert.equal(new ConstantNode(3).toTex(), '3');
    assert.deepEqual(new ConstantNode(3).toTex(), '3');
    assert.deepEqual(new ConstantNode(math.bignumber('3')).toTex(), '3');
    assert.equal(new ConstantNode('hi').toTex(), '\\mathtt{"hi"}');
    assert.equal(new ConstantNode(true).toTex(), 'true');
    assert.equal(new ConstantNode(false).toTex(), 'false');
    assert.equal(new ConstantNode(undefined).toTex(), 'undefined');
    assert.equal(new ConstantNode(null).toTex(), 'null');
  });

  it ('should LaTeX a ConstantNode in exponential notation', function () {
    var n = new ConstantNode(1e10);
    assert.equal(n.toTex(), '1\\cdot10^{+10}');
  });

  it ('should LaTeX a ConstantNode with custom toTex', function () {
    //Also checks if the custom functions get passed on to the children
    var customFunction = function (node, options) {
      if (node.type === 'ConstantNode') {
        return 'const\\left(' + node.value + '\\right)'
      }
    };

    var n = new ConstantNode(1);

    assert.equal(n.toTex({handler: customFunction}), 'const\\left(1\\right)');
  });

  it ('should LaTeX a ConstantNode with a fraction', function () {
    var positive = new ConstantNode(new math.type.Fraction(1.5));
    var negative = new ConstantNode(new math.type.Fraction(-1.5));

    assert.equal(positive.toTex(), '\\frac{3}{2}');
    assert.equal(negative.toTex(), '-\\frac{3}{2}');
  });

  it('should escape strings in toTex', function () {
    var n = new ConstantNode('space tab\tunderscore_bla$/', 'string');

    assert.equal(n.toTex(), '\\mathtt{"space~tab\\qquad{}underscore\\_bla\\$/"}');
  });

});
<commit_msg>Updated unit test in ConstantNode<commit_after>// test ConstantNode
var assert = require('assert');
var approx = require('../../../tools/approx');
var math = require('../../../index');
var bigmath = require('../../../index').create({number: 'BigNumber'});
var Node = math.expression.node.Node;
var ConstantNode = math.expression.node.ConstantNode;
var SymbolNode = math.expression.node.SymbolNode;
var Fraction = require('../../../lib/type/fraction/Fraction');

describe('ConstantNode', function() {

  it ('should create a ConstantNode', function () {
    var a = new ConstantNode(3);
    assert(a instanceof Node);
    assert.equal(a.type, 'ConstantNode');
    // TODO: extensively test each of the supported types

    assert.strictEqual(new ConstantNode(3).value, 3);
    assert.strictEqual(new ConstantNode('hello').value, 'hello');
    assert.strictEqual(new ConstantNode(true).value, true);
    assert.strictEqual(new ConstantNode(false).value, false);
    assert.strictEqual(new ConstantNode(null).value, null);
    assert.strictEqual(new ConstantNode(undefined).value, undefined);
  });

  it ('should have isConstantNode', function () {
    var node = new ConstantNode(1);
    assert(node.isConstantNode);
  });

  it ('should throw an error when calling without new operator', function () {
    assert.throws(function () {ConstantNode(3)}, SyntaxError);
  });

  it ('should compile a ConstantNode', function () {
    var expr = new ConstantNode(2.3).compile();
    assert.strictEqual(expr.eval(), 2.3);

    expr = new ConstantNode(2.3).compile();
    assert.strictEqual(expr.eval(), 2.3);

    expr = new ConstantNode('hello').compile();
    assert.strictEqual(expr.eval(), 'hello');

    expr = new ConstantNode(true).compile();
    assert.strictEqual(expr.eval(), true);

    expr = new ConstantNode(undefined).compile();
    assert.strictEqual(expr.eval(), undefined);

    expr = new ConstantNode(null).compile();
    assert.strictEqual(expr.eval(), null);

  });

  it ('should compile a ConstantNode with bigmath', function () {
    var constantNode = bigmath.parse('2.3');
    assert.ok(constantNode.isConstantNode);
    var expr = constantNode.compile();
    assert.deepEqual(expr.eval(), new bigmath.type.BigNumber(2.3));
  });

  it ('should find a ConstantNode', function () {
    var a = new ConstantNode(2);
    assert.deepEqual(a.filter(function (node) {return node instanceof ConstantNode}),  [a]);
    assert.deepEqual(a.filter(function (node) {return node instanceof SymbolNode}), []);
  });

  it ('should leave quotes in strings as is (no escaping)', function () {
    assert.strictEqual( new ConstantNode('"+foo+"').compile().eval(), '"+foo+"')
    assert.strictEqual( new ConstantNode('\\"escaped\\"').compile().eval(), '\\"escaped\\"')
  });

  it ('should find a ConstantNode', function () {
    var a = new ConstantNode(2);
    assert.deepEqual(a.filter(function (node) {return node instanceof ConstantNode}),  [a]);
    assert.deepEqual(a.filter(function (node) {return node instanceof SymbolNode}), []);
  });

  it ('should run forEach on a ConstantNode', function () {
    var a = new ConstantNode(2);
    a.forEach(function () {
      assert.ok(false, 'should not execute, constant has no childs')
    });
  });

  it ('should map a ConstantNode', function () {
    var a = new ConstantNode(2);
    var b = a.map(function () {
      assert.ok(false, 'should not execute, constant has no childs')
    });

    assert.notStrictEqual(b, a);
    assert.deepEqual(b, a);
  });

  it ('should transform a ConstantNode', function () {
    var a = new ConstantNode(2);
    var b = new ConstantNode(3);
    var c = a.transform(function (node) {
      return node instanceof ConstantNode && node.value == '2' ? b : node;
    });
    assert.deepEqual(c,  b);

    // no match should leave the node as is
    var d = a.transform(function (node) {
      return node instanceof ConstantNode && node.value == '99' ? b : node;
    });
    assert.notStrictEqual(d, a);
    assert.deepEqual(d,  a);
  });

  it ('should clone a ConstantNode', function () {
    var a = new ConstantNode(2);
    var b = a.clone();

    assert(b instanceof ConstantNode);
    assert.deepEqual(a, b);
    assert.notStrictEqual(a, b);
    assert.equal(a.value, b.value);
    assert.equal(a.valueType, b.valueType);
  });

  it ('test equality another Node', function () {
    var a = new ConstantNode(2);

    assert.strictEqual(a.equals(null), false);
    assert.strictEqual(a.equals(undefined), false);
    assert.strictEqual(a.equals(new ConstantNode(2)), true);
    assert.strictEqual(a.equals(new ConstantNode(3)), false);
    assert.strictEqual(a.equals(new ConstantNode('2')), false);
    assert.strictEqual(a.equals(new SymbolNode('2')), false);
    assert.strictEqual(a.equals({value:2}), false);
  });

  it ('should stringify a ConstantNode', function () {
    assert.equal(new ConstantNode(3).toString(), '3');
    assert.deepEqual(new ConstantNode(3).toString(), '3');
    assert.deepEqual(new ConstantNode(math.bignumber('1e500')).toString(), '1e+500');
    assert.deepEqual(new ConstantNode(math.fraction(2,3)).toString(), '2/3');
    assert.equal(new ConstantNode('hi').toString(), '"hi"');
    assert.equal(new ConstantNode(true).toString(), 'true');
    assert.equal(new ConstantNode(false).toString(), 'false');
    assert.equal(new ConstantNode(undefined).toString(), 'undefined');
    assert.equal(new ConstantNode(null).toString(), 'null');
  });

  it ('should stringify a ConstantNode with custom toString', function () {
    //Also checks if the custom functions get passed on to the children
    var customFunction = function (node, options) {
      if (node.type === 'ConstantNode') {
        return 'const(' + node.value + ')'
      }
    };

    var n = new ConstantNode(1);

    assert.equal(n.toString({handler: customFunction}), 'const(1)');
  });

  it ('should LaTeX a ConstantNode', function () {
    assert.equal(new ConstantNode(3).toTex(), '3');
    assert.deepEqual(new ConstantNode(3).toTex(), '3');
    assert.deepEqual(new ConstantNode(math.bignumber('3')).toTex(), '3');
    assert.equal(new ConstantNode('hi').toTex(), '\\mathtt{"hi"}');
    assert.equal(new ConstantNode(true).toTex(), 'true');
    assert.equal(new ConstantNode(false).toTex(), 'false');
    assert.equal(new ConstantNode(undefined).toTex(), 'undefined');
    assert.equal(new ConstantNode(null).toTex(), 'null');
  });

  it ('should LaTeX a ConstantNode in exponential notation', function () {
    var n = new ConstantNode(1e10);
    assert.equal(n.toTex(), '1\\cdot10^{+10}');
  });

  it ('should LaTeX a ConstantNode with custom toTex', function () {
    //Also checks if the custom functions get passed on to the children
    var customFunction = function (node, options) {
      if (node.type === 'ConstantNode') {
        return 'const\\left(' + node.value + '\\right)'
      }
    };

    var n = new ConstantNode(1);

    assert.equal(n.toTex({handler: customFunction}), 'const\\left(1\\right)');
  });

  it ('should LaTeX a ConstantNode with a fraction', function () {
    var positive = new ConstantNode(new math.type.Fraction(1.5));
    var negative = new ConstantNode(new math.type.Fraction(-1.5));

    assert.equal(positive.toTex(), '\\frac{3}{2}');
    assert.equal(negative.toTex(), '-\\frac{3}{2}');
  });

  it('should escape strings in toTex', function () {
    var n = new ConstantNode('space tab\tunderscore_bla$/');

    assert.equal(n.toTex(), '\\mathtt{"space~tab\\qquad{}underscore\\_bla\\$/"}');
  });

});
<|endoftext|>


<commit_before>import defaultOptions from '../../config.json'

const COMPONENT_TYPES = {
  pure: 'PureComponent',
  class: 'Component',
}

function generateReactImport(componentType) {
  return `import React${componentType !== 'stateless' ? `, { ${COMPONENT_TYPES[componentType]} }` : ''} from 'react'`
}

function generateComponentMethods(componentMethods) {
  if (componentMethods.length === 0) {
    return null
  }
  let methods = ''
  componentMethods.forEach((method) => {
    methods += `\n\xa0\xa0\xa0\xa0${method}(){}\n`
  })
  return methods
}

function generateImports(
  COMPONENT_NAME,
  componentType,
  { cssExtension = defaultOptions.cssExtension, styleFileName }
) {
  return `${generateReactImport(componentType)}
import PropTypes from 'prop-types'
${cssExtension ? `import styles from './${styleFileName}.${cssExtension}'` : ''}`
}

function generateClassComponent(
  COMPONENT_NAME,
  componentType,
  {
    cssExtension = defaultOptions.cssExtension,
    componentMethods = defaultOptions.componentMethods,
    styleFileName,
  }
) {
  return `${generateImports(COMPONENT_NAME, componentType, {
    cssExtension,
    styleFileName,
  })}

class ${COMPONENT_NAME} extends ${COMPONENT_TYPES[componentType]} {
    constructor(props) {
        super(props)
    }
    ${generateComponentMethods(componentMethods)}
    render() {
        return (

        );
    }
}

${COMPONENT_NAME}.propTypes = {}

${COMPONENT_NAME}.defaultProps = {}

export default ${COMPONENT_NAME}
`
}

export { generateClassComponent, generateImports }
<commit_msg>Fix generateComponentMethods that print null when is empty<commit_after>import defaultOptions from '../../config.json'

const COMPONENT_TYPES = {
  pure: 'PureComponent',
  class: 'Component',
}

function generateReactImport(componentType) {
  return `import React${
    componentType !== 'stateless' ? `, { ${COMPONENT_TYPES[componentType]} }` : ''
  } from 'react'`
}

/**
 * Create the concatenation of methods string that will be injected into class and pure components
 * @param {Array} componentMethods
 * @return {String} methods
 */
function generateComponentMethods(componentMethods) {
  if (componentMethods.length === 0) {
    return ''
  }

  return componentMethods.reduce((acc, method) => {
    const methods = `${acc}\n\xa0\xa0\xa0\xa0${method}(){}\n`

    return methods
  }, '')
}

function generateImports(
  COMPONENT_NAME,
  componentType,
  { cssExtension = defaultOptions.cssExtension, styleFileName }
) {
  return `${generateReactImport(componentType)}
import PropTypes from 'prop-types'
${cssExtension ? `import styles from './${styleFileName}.${cssExtension}'` : ''}`
}

function generateClassComponent(
  COMPONENT_NAME,
  componentType,
  {
    cssExtension = defaultOptions.cssExtension,
    componentMethods = defaultOptions.componentMethods,
    styleFileName,
  }
) {
  return `${generateImports(COMPONENT_NAME, componentType, {
    cssExtension,
    styleFileName,
  })}

class ${COMPONENT_NAME} extends ${COMPONENT_TYPES[componentType]} {
    constructor(props) {
        super(props)
    }
    ${generateComponentMethods(componentMethods)}
    render() {
        return (

        );
    }
}

${COMPONENT_NAME}.propTypes = {}

${COMPONENT_NAME}.defaultProps = {}

export default ${COMPONENT_NAME}
`
}

export { generateClassComponent, generateImports }
<|endoftext|>


<commit_before>var quotes = [
    'Oh god how did this get here I am not good with computer.',
    'Hello everybody! I hope you have a good day!',
    'uggghhhh..... What\'s with all this /green/???',
    'Green is my favorite color 0.0',
    'Hm.... I wonder where all my friends are...',
    'Chara just wished that I have a good time!',
    'Dang! It didn\'t work!',
    'Just little old me~',
    'I wonder what happened...',
    'I hope Charat works today!',
];

jQuery.fn.exists = function(){return this.length>0;}

function cmobile() {
    if (navigator.userAgent.indexOf('Android')!=-1 || navigator.userAgent.indexOf('iPhone')!=-1 || navigator.userAgent.indexOf('Nintendo 3DS')!=-1 || navigator.userAgent.indexOf('Nintendo DSi')!=-1 || window.innerWidth<=630) {
        return true;
    } else {
        return false;
    }
}

function screenCheck() {
    if (cmobile()){
        $(document.body).addClass('mobile');
        $(document.body).removeClass('nobile');
    } else if (window.innerWidth<=950){
        $(document.body).addClass('nobile');
        $(document.body).removeClass('mobile');
    } else  {
        $(document.body).removeClass('mobile');
        $(document.body).removeClass('nobile');
    }
}

function heightAdjust() {
    if (!$('body.mobile').exists() && !$('body.nobile').exists() && $('#typing-quirks .replacementContainer').exists()) {
        leftHeight = $('#char_left').height();
        centerHeight = $('#char_center').height()-$('#typing-quirks .replacementContainer').height();
        $('#typing-quirks .replacementContainer').height(leftHeight-centerHeight);
    } else {
        $('#typing-quirks .replacementContainer').height(178);
    }
}

$(document).ready(function() {
    screenCheck();
    heightAdjust();
    $(window).resize(function() {
        screenCheck();
        heightAdjust();
    });

    var quote = quotes[Math.floor(Math.random()*quotes.length)];
    $('#quote').html(quote);
    if(navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false) {
        $('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />');
    }

    /* Topbar Menu */
    $('div.body').click(function() {
        $(document.body).removeClass('menu');
    });
    $('#toptitle').click(function(e) {
        if (!$('body.menu').exists(e)) {
            e.preventDefault();
            $(document.body).delay(10).addClass('menu');
        }
    });
    $('#toptitle, #topmenu').hover(
        function() {
            $(document.body).addClass('menu');
        }, function() {
            $(document.body).removeClass('menu');
        }
    );
});

$(window).load(function() {

});<commit_msg>replacement containe window load undo<commit_after>var quotes = [
    'Oh god how did this get here I am not good with computer.',
    'Hello everybody! I hope you have a good day!',
    'uggghhhh..... What\'s with all this /green/???',
    'Green is my favorite color 0.0',
    'Hm.... I wonder where all my friends are...',
    'Chara just wished that I have a good time!',
    'Dang! It didn\'t work!',
    'Just little old me~',
    'I wonder what happened...',
    'I hope Charat works today!',
];

jQuery.fn.exists = function(){return this.length>0;}

function cmobile() {
    if (navigator.userAgent.indexOf('Android')!=-1 || navigator.userAgent.indexOf('iPhone')!=-1 || navigator.userAgent.indexOf('Nintendo 3DS')!=-1 || navigator.userAgent.indexOf('Nintendo DSi')!=-1 || window.innerWidth<=630) {
        return true;
    } else {
        return false;
    }
}

function screenCheck() {
    if (cmobile()){
        $(document.body).addClass('mobile');
        $(document.body).removeClass('nobile');
    } else if (window.innerWidth<=950){
        $(document.body).addClass('nobile');
        $(document.body).removeClass('mobile');
    } else  {
        $(document.body).removeClass('mobile');
        $(document.body).removeClass('nobile');
    }
}

function heightAdjust() {
    if (!$('body.mobile').exists() && !$('body.nobile').exists() && $('#typing-quirks .replacementContainer').exists()) {
        leftHeight = $('#char_left').height();
        centerHeight = $('#char_center').height()-$('#typing-quirks .replacementContainer').height();
        $('#typing-quirks .replacementContainer').height(leftHeight-centerHeight);
    } else {
        $('#typing-quirks .replacementContainer').height(178);
    }
}

$(document).ready(function() {
    var quote = quotes[Math.floor(Math.random()*quotes.length)];
    $('#quote').html(quote);
    if(navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false) {
        $('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />');
    }

    /* Topbar Menu */
    $('div.body').click(function() {
        $(document.body).removeClass('menu');
    });
    $('#toptitle').click(function(e) {
        if (!$('body.menu').exists(e)) {
            e.preventDefault();
            $(document.body).delay(10).addClass('menu');
        }
    });
    $('#toptitle, #topmenu').hover(
        function() {
            $(document.body).addClass('menu');
        }, function() {
            $(document.body).removeClass('menu');
        }
    );
});

$(window).load(function() {
    screenCheck();
    heightAdjust();
    $(window).resize(function() {
        screenCheck();
        heightAdjust();
    });
});<|endoftext|>


<commit_before>/**
 * Menu entry for the "vertical navigation"
 *
 * @param {Object} config
 * @extends Ext.Panel
 * @xtype modx-menu-entry
 */
MODx.menuEntry = function(config) {
    config = config || {};

    Ext.applyIf(config, {
        collapsible: true
        ,collapsed: true
        ,stateful: true
        ,cls: 'menu-section'
        ,titleCollapse: true
        ,hideCollapseTool: true
        ,layout: {
            type: 'card'
            ,deferredRender: true
        }
        ,autoEl: {
            tag: 'li'
        }
        ,headerCfg: {
            tag: 'a'
            ,href: 'javascript:;'
            ,tabindex: 1
            //,'data-qtip': 'Test'
            ,title: config.description || ''
        }
        ,headerCssClass: 'x-panel-header'
        ,stateEvents: ['collapse', 'expand']
    });
    MODx.menuEntry.superclass.constructor.call(this, config);
    this.on('afterrender', this.onAfterRender, this);
};
Ext.extend(MODx.menuEntry, Ext.Panel, {
    onCollapse : function(doAnim, animArg) {
        MODx.menuEntry.superclass.onCollapse.call(this, doAnim, animArg);
        // Force layout to have no active item
        this.getLayout().setActiveItem(null);
    }
    ,onExpand: function(doAnim, animArg) {
        MODx.menuEntry.superclass.onExpand.call(this, doAnim, animArg);
        // Force layout to display its item
        this.getLayout().setActiveItem(0);
    }
    ,getState: function() {
        // Menu attributes to save/restore for the state manager
        return {
            collapsed: this.collapsed
        };
    }

    ,onAfterRender: function(me) {
        if (!me.collapsed) {
            me.getLayout().setActiveItem(0);
        }
    }
});
Ext.reg('modx-menu-entry', MODx.menuEntry);

// PoC to use border layout
MODx.menuBorder = function(config) {
    config = config || {};

    Ext.applyIf(config, {
        test: true
    });
    MODx.menuBorder.superclass.constructor.call(this, config);
};
Ext.extend(MODx.menuBorder, MODx.menuEntry, {
    onCollapse : function(doAnim, animArg) {
        var center = Ext.getCmp('center-nav');
        center.hide();
        center.removeAll();

        //Ext.defer(function() {
            //if (center.items.items.length < 1) {
                var west = Ext.getCmp('modx-leftbar-tabs');
                west.setWidth('50px');
                west.doLayout();
        Ext.getCmp('modx-layout').doLayout();
            //}
       // }, 250);

        MODx.menuEntry.superclass.onCollapse.call(this, doAnim, animArg);
    }
    ,onExpand: function(doAnim, animArg) {
        var center = Ext.getCmp('center-nav');
        center.removeAll();

        // Collapse all expanded
        var nav = Ext.getCmp('nav-one');
        nav.items.each(function(item) {
            if (item.id !== this.id && !item.collapsed && typeof item.collapse === 'function') {
                console.log('item to be collapsed', item);
                item.collapse();
                //item.fireEvent('collapse');
            }
        }, this);

        center.add(this.initialConfig.items);

        var west = Ext.getCmp('modx-leftbar-tabs');
        west.setWidth('230px');

        center.doLayout();
        center.show();

        west.doLayout();
        Ext.getCmp('modx-layout').doLayout();

        MODx.menuEntry.superclass.onExpand.call(this, doAnim, animArg);
    }

    ,onAfterRender: function(me) {
        if (!me.collapsed) {
            me.on('collapse', function(elem) {
                console.log('collapsed, so expand again!');
                elem.expand();
                elem.collapsed = false;
            }, me, {single: true});

            me.collapse();
        }
    }
});
Ext.reg('modx-menu-border-entry', MODx.menuBorder);

var useBorder = false;

// Override MODx.Layout to support vertical navigation
Ext.override(MODx.Layout, {

    getWest: function(config) {
        var items = [];

        this.handleLeftScroll();

        if (MODx.perm.resource_tree) {
            items.push(this.handleRecord({
                title: _('resources')
                ,titleTpl: '{title}'
                ,stateId: 'nav-resource-tree'
                ,defaults: {
                    remoteToolbar: false
                    ,tbar: {
                        hidden: true
                    }
                    ,useDefaultToolbar: false
                }
                ,items: [{
                    xtype: 'modx-tree-resource'
                    ,id: 'modx-resource-tree'
                }]
            }));
            config.showTree = true;
        }
        if (MODx.perm.element_tree) {
            items.push(this.handleRecord({
                title: _('elements')
                ,titleTpl: '{title}'
                ,stateId: 'nav-element-tree'
                ,defaults: {
                    remoteToolbar: false
                    ,tbar: {
                        hidden: true
                    }
                    ,useDefaultToolbar: false
                }
                ,items: [{
                    xtype: 'modx-tree-element'
                    ,id: 'modx-tree-element'
                }]
            }));
            config.showTree = true;
        }
        if (MODx.perm.file_tree) {
            items.push(this.handleRecord({
                title: _('files')
                ,titleTpl: '{title}'
                ,stateId: 'nav-file-tree'
                ,defaults: {
                    remoteToolbar: false
                    ,tbar: {
                        hidden: true
                    }
                    ,useDefaultToolbar: false
                }
                ,items: [{
                    xtype: 'modx-panel-filetree'
                    ,id: 'modx-file-tree'
                }]
            }));
            config.showTree = true;
        }

        var content = {
            region: 'west'
            ,applyTo: 'modx-leftbar'
            ,id: 'modx-leftbar-tabs'
            ,stateId: this.getStateKey('modx-leftbar-tabs')
            ,split: true
            // @TODO : make use of original config (MODx.Layout), requires some PR
            ,width: 310
            ,autoScroll: true
            ,unstyled: true
            ,collapseMode: 'mini'
            ,useSplitTips: true
            ,monitorResize: true
            ,layout: 'anchor'
            ,items: items
            ,defaultType: 'modx-menu-entry'
            ,minSize: 195
            ,bodyCfg: {
                tag: 'ul'
            }
            ,listeners: {
                beforestatesave: this.onBeforeStateSave
                ,scope: this
            }
            ,getState: function() {
                return {
                    collapsed: this.collapsed
                    ,width: this.width
                };
            }
        };

        if (useBorder) {
            Ext.apply(content, {
                minSize: 50
                ,layout: 'border'
                ,defaultType: 'panel'
                ,items: [{
                    region: 'west'
                    ,items: items
                    ,defaultType: 'modx-menu-border-entry'
                    ,width: '50px'
                    ,id: 'nav-one'
                    //,collapsed: false
                    //,split: false
                    //,layout: 'fit'
                    //,autohide: false
                    ,stateful: false
                },{
                    region: 'center'
                    //,hidden: true
                    //,layout: 'fit'
                    //,xtype: 'container'
                    //,cls: 'x-panel-body'
                    ,items: []
                    ,id: 'center-nav'
                    //,width: 0
                    ,stateful: false
                }]
            });

            console.log('content', content);
        }

        return content;
    }

    /**
     * Dirty hack to handle scrollbar in left region
     */
    ,handleLeftScroll: function() {
        var c = Ext.get('modx-leftbar');
        c.on('DOMSubtreeModified', function(vent, elem, options) {
            Ext.defer(function() {
                this.getLeftBar().doLayout();
                // Schedule again
                this.handleLeftScroll();
            }, 150, this);
        }, this, {
            single: true
        });
    }
    /**
     * Wrapper method to get the navigation container
     *
     * @returns {Ext.Panel}
     */
    ,getLeftBar: function() {
        var nav = Ext.getCmp('modx-leftbar-tabs');
        if (useBorder) {
            nav = Ext.getCmp('nav-one');
        }
        if (nav) {
            return nav;
        }
    }
    /**
     * Handle menu entries addition
     *
     * @param {Object|Array} items
     */
    ,addToLeftBar: function(items) {
        var nav = this.getLeftBar();
        if (nav && items) {
            if (Ext.isObject(items)) {
                items = this.handleRecord(items);
            } else {
                Ext.each(items, function(item, idx) {
                    items[idx] = this.handleRecord(item);
                }, this);
            }

            nav.add(items);
            this.onAfterLeftBarAdded(nav, items);
        }
    }

    /**
     * Convenient method to place the given records at the given position
     *
     * @param {Number} index
     * @param {Object|Array} items
     */
    ,addToLeftBarAt: function(index, items) {
        var nav = this.getLeftBar();
        if (nav && items) {

            if (Ext.isObject(items)) {
                items = this.handleRecord(items);
            } else {
                Ext.each(items, function(item, idx) {
                    items[idx] = this.handleRecord(item);
                }, this);
            }

            Ext.each(items, function(item, idx) {
                nav.insert(index, item);
                index += 1;
            }, this);

            this.onAfterLeftBarAdded(nav, items);
        }
    }

    /**
     * Format a single menu entry to fit the stying
     *
     * @param {Object} config
     *
     * @returns {Object}
     */
    ,handleRecord: function(config) {
        if (!config.titleTpl) {
            // Default tpl
            config.titleTpl = '{title}';
        }
        if (config.title && config.titleTpl) {
            config.title = new Ext.XTemplate(config.titleTpl).apply({
                title: config.title
            });
        }
        if (config.stateId) {
            config.stateId = this.getStateKey(config.stateId);
        }

        return config;
    }
    /**
     * Compute state keys for Ext.State.Manager, to be theme related
     *
     * @param {String} key
     *
     * @returns {string}
     */
    ,getStateKey: function(key) {
        return 'theme-' + MODx.config.manager_theme + '-' + key;
    }

    /**
     * Force navigation container to be re-rendered after adding some elements in
     *
     * @param {Ext.Panel} nav
     * @param {Object|Array} items
     */
    ,_onAfterLeftBarAdded: function(nav, items) {
        nav.doLayout();
    }

    /**
     * Override to prevent error caused by not existing tab panel
     *
     * @see MODx.Layout#onBeforeStateSave
     *
     * @param {Ext.Component} component
     * @param {Object} state
     */
    ,onBeforeStateSave: function(component, state) {
        return;
        var collapsed = state.collapsed;
        if (collapsed && !this.stateSave) {
            this.stateSave = true;
            return false;
        }
        if (!collapsed) {
            var wrap = Ext.get('modx-leftbar').down('div');
            if (!wrap.isVisible()) {
                // Set the "masking div" to visible
                wrap.setVisible(true);
            }
        }
    }
});
<commit_msg>Again some tests with border layout<commit_after>/**
 * Menu entry for the "vertical navigation"
 *
 * @param {Object} config
 * @extends Ext.Panel
 * @xtype modx-menu-entry
 */
MODx.menuEntry = function(config) {
    config = config || {};

    Ext.applyIf(config, {
        collapsible: true
        ,collapsed: true
        ,stateful: true
        ,cls: 'menu-section'
        ,titleCollapse: true
        ,hideCollapseTool: true
        ,layout: {
            type: 'card'
            ,deferredRender: true
        }
        ,autoEl: {
            tag: 'li'
        }
        ,headerCfg: {
            tag: 'a'
            ,href: 'javascript:;'
            ,tabindex: 1
            //,'data-qtip': 'Test'
            ,title: config.description || ''
        }
        ,headerCssClass: 'x-panel-header'
        ,stateEvents: ['collapse', 'expand']
    });
    MODx.menuEntry.superclass.constructor.call(this, config);
    this.on('afterrender', this.onAfterRender, this);
};
Ext.extend(MODx.menuEntry, Ext.Panel, {
    onCollapse : function(doAnim, animArg) {
        MODx.menuEntry.superclass.onCollapse.call(this, doAnim, animArg);
        // Force layout to have no active item
        this.getLayout().setActiveItem(null);
    }
    ,onExpand: function(doAnim, animArg) {
        MODx.menuEntry.superclass.onExpand.call(this, doAnim, animArg);
        // Force layout to display its item
        this.getLayout().setActiveItem(0);
    }
    ,getState: function() {
        // Menu attributes to save/restore for the state manager
        return {
            collapsed: this.collapsed
        };
    }

    ,onAfterRender: function(me) {
        if (!me.collapsed) {
            me.getLayout().setActiveItem(0);
        }
    }
});
Ext.reg('modx-menu-entry', MODx.menuEntry);

// PoC to use border layout
MODx.menuBorder = function(config) {
    config = config || {};

    Ext.applyIf(config, {
        test: true
    });
    MODx.menuBorder.superclass.constructor.call(this, config);
};
Ext.extend(MODx.menuBorder, MODx.menuEntry, {
    onCollapse : function(doAnim, animArg) {
        this.animate('50px');

        MODx.menuEntry.superclass.onCollapse.call(this, doAnim, animArg);

        var center = Ext.getCmp('center-nav');
        //center.hide();
        center.removeAll();

    }
    ,onExpand: function(doAnim, animArg) {
        var center = Ext.getCmp('center-nav');
        center.removeAll();

        // Collapse all expanded
        var nav = Ext.getCmp('nav-one');
        nav.items.each(function(item) {
            if (item.id !== this.id && !item.collapsed && typeof item.collapse === 'function') {
                console.log('item to be collapsed', item);
                item.collapse();
                //item.fireEvent('collapse');
            }
        }, this);

        center.add(this.initialConfig.items);

        this.animate('230px', true);

        MODx.menuEntry.superclass.onExpand.call(this, doAnim, animArg);
    }

    ,animate: function(width) {
        var west = Ext.getCmp('modx-leftbar-tabs')
            ,center = Ext.getCmp('center-nav');

        west.setWidth(width);

        //west.doLayout();
        Ext.getCmp('modx-layout').doLayout();
    }

    ,onAfterRender: function(me) {
        if (!me.collapsed) {
            me.on('collapse', function(elem) {
                console.log('collapsed, so expand again!');
                elem.expand();
                elem.collapsed = false;
            }, me, {single: true});

            me.collapse();
        }
    }
});
Ext.reg('modx-menu-border-entry', MODx.menuBorder);

var useBorder = false;

// Override MODx.Layout to support vertical navigation
Ext.override(MODx.Layout, {

    getWest: function(config) {
        var items = [];

        this.handleLeftScroll();

        if (MODx.perm.resource_tree) {
            items.push(this.handleRecord({
                title: _('resources')
                ,titleTpl: '{title}'
                ,stateId: 'nav-resource-tree'
                ,defaults: {
                    remoteToolbar: false
                    ,tbar: {
                        hidden: true
                    }
                    ,useDefaultToolbar: false
                }
                ,items: [{
                    xtype: 'modx-tree-resource'
                    ,id: 'modx-resource-tree'
                }]
            }));
            config.showTree = true;
        }
        if (MODx.perm.element_tree) {
            items.push(this.handleRecord({
                title: _('elements')
                ,titleTpl: '{title}'
                ,stateId: 'nav-element-tree'
                ,defaults: {
                    remoteToolbar: false
                    ,tbar: {
                        hidden: true
                    }
                    ,useDefaultToolbar: false
                }
                ,items: [{
                    xtype: 'modx-tree-element'
                    ,id: 'modx-tree-element'
                }]
            }));
            config.showTree = true;
        }
        if (MODx.perm.file_tree) {
            items.push(this.handleRecord({
                title: _('files')
                ,titleTpl: '{title}'
                ,stateId: 'nav-file-tree'
                ,defaults: {
                    remoteToolbar: false
                    ,tbar: {
                        hidden: true
                    }
                    ,useDefaultToolbar: false
                }
                ,items: [{
                    xtype: 'modx-panel-filetree'
                    ,id: 'modx-file-tree'
                }]
            }));
            config.showTree = true;
        }

        var content = {
            region: 'west'
            ,applyTo: 'modx-leftbar'
            ,id: 'modx-leftbar-tabs'
            ,stateId: this.getStateKey('modx-leftbar-tabs')
            ,split: true
            // @TODO : make use of original config (MODx.Layout), requires some PR
            ,width: 310
            ,autoScroll: true
            ,unstyled: true
            ,collapseMode: 'mini'
            ,useSplitTips: true
            ,monitorResize: true
            ,layout: 'anchor'
            ,items: items
            ,defaultType: 'modx-menu-entry'
            ,minSize: 195
            ,bodyCfg: {
                tag: 'ul'
            }
            ,listeners: {
                beforestatesave: this.onBeforeStateSave
                ,scope: this
            }
            ,getState: function() {
                return {
                    collapsed: this.collapsed
                    ,width: this.width
                };
            }
        };

        if (useBorder) {
            Ext.apply(content, {
                minSize: 50
                ,layout: 'border'
                ,defaultType: 'panel'
                //,split: false
                ,items: [{
                    region: 'west'
                    ,items: items
                    ,defaultType: 'modx-menu-border-entry'
                    ,width: '50px'
                    ,id: 'nav-one'
                    //,collapsed: false
                    //,split: false
                    //,layout: 'fit'
                    //,autohide: false
                    ,stateful: false
                },{
                    region: 'center'
                    //,hidden: true
                    //,layout: 'fit'
                    //,xtype: 'container'
                    //,cls: 'x-panel-body'
                    ,items: []
                    ,id: 'center-nav'
                    //,width: 180
                    ,stateful: false
                    //,split: true
                }]
            });

            console.log('content', content);
        }

        return content;
    }

    /**
     * Dirty hack to handle scrollbar in left region
     */
    ,handleLeftScroll: function() {
        var c = Ext.get('modx-leftbar');
        c.on('DOMSubtreeModified', function(vent, elem, options) {
            Ext.defer(function() {
                this.getLeftBar().doLayout();
                // Schedule again
                this.handleLeftScroll();
            }, 150, this);
        }, this, {
            single: true
        });
    }
    /**
     * Wrapper method to get the navigation container
     *
     * @returns {Ext.Panel}
     */
    ,getLeftBar: function() {
        var nav = Ext.getCmp('modx-leftbar-tabs');
        if (useBorder) {
            nav = Ext.getCmp('nav-one');
        }
        if (nav) {
            return nav;
        }
    }
    /**
     * Handle menu entries addition
     *
     * @param {Object|Array} items
     */
    ,addToLeftBar: function(items) {
        var nav = this.getLeftBar();
        if (nav && items) {
            if (Ext.isObject(items)) {
                items = this.handleRecord(items);
            } else {
                Ext.each(items, function(item, idx) {
                    items[idx] = this.handleRecord(item);
                }, this);
            }

            nav.add(items);
            this.onAfterLeftBarAdded(nav, items);
        }
    }

    /**
     * Convenient method to place the given records at the given position
     *
     * @param {Number} index
     * @param {Object|Array} items
     */
    ,addToLeftBarAt: function(index, items) {
        var nav = this.getLeftBar();
        if (nav && items) {

            if (Ext.isObject(items)) {
                items = this.handleRecord(items);
            } else {
                Ext.each(items, function(item, idx) {
                    items[idx] = this.handleRecord(item);
                }, this);
            }

            Ext.each(items, function(item, idx) {
                nav.insert(index, item);
                index += 1;
            }, this);

            this.onAfterLeftBarAdded(nav, items);
        }
    }

    /**
     * Format a single menu entry to fit the stying
     *
     * @param {Object} config
     *
     * @returns {Object}
     */
    ,handleRecord: function(config) {
        if (!config.titleTpl) {
            // Default tpl
            config.titleTpl = '{title}';
        }
        if (config.title && config.titleTpl) {
            config.title = new Ext.XTemplate(config.titleTpl).apply({
                title: config.title
            });
        }
        if (config.stateId) {
            config.stateId = this.getStateKey(config.stateId);
        }

        return config;
    }
    /**
     * Compute state keys for Ext.State.Manager, to be theme related
     *
     * @param {String} key
     *
     * @returns {string}
     */
    ,getStateKey: function(key) {
        return 'theme-' + MODx.config.manager_theme + '-' + key;
    }

    /**
     * Force navigation container to be re-rendered after adding some elements in
     *
     * @param {Ext.Panel} nav
     * @param {Object|Array} items
     */
    ,_onAfterLeftBarAdded: function(nav, items) {
        nav.doLayout();
    }

    /**
     * Override to prevent error caused by not existing tab panel
     *
     * @see MODx.Layout#onBeforeStateSave
     *
     * @param {Ext.Component} component
     * @param {Object} state
     */
    ,onBeforeStateSave: function(component, state) {
        return;
        var collapsed = state.collapsed;
        if (collapsed && !this.stateSave) {
            this.stateSave = true;
            return false;
        }
        if (!collapsed) {
            var wrap = Ext.get('modx-leftbar').down('div');
            if (!wrap.isVisible()) {
                // Set the "masking div" to visible
                wrap.setVisible(true);
            }
        }
    }
});
<|endoftext|>


<commit_before>var get = Ember.get, set = Ember.set;
var env;
var responses, fakeServer;

module('integration/specs/urls-for-resource-collections', {
  setup: function() {
    fakeServer = stubServer();

    responses = {
      posts_not_compound: {
        data: {
          type: 'posts',
          id: '1',
          title: 'Rails is Omakase',
          links: {
            comments: {
              type: 'comments',
              ids: ['2', '3']
            }
          }
        }
      },
      comments_2: {
        data: {
          type: 'comments',
          'id': '2',
          'title': 'good article',
          'body': 'ideal for my startup'
        }
      },
      comments_3: {
        data: {
          type: 'comments',
          id: '3',
          title: 'bad article',
          body: "doesn't run Crysis"
        }
      },
      underscore_resource: {
        data: {
          type: 'some_resource',
          id: '1',
          title: 'wow'
        }
      }
    };

    env = setupStore(setModels());
    env.store.modelFor('post');
    env.store.modelFor('comment');
  },

  teardown: function() {
    Ember.run(env.store, 'destroy');
    shutdownFakeServer(fakeServer);
  }
});

asyncTest('GET /posts/1 calls later GET /comments/2,3 when Posts has async comments', function() {
  var models = setModels({
    commentAsync: true
  });
  env = setupStore(models);

  fakeServer.get('/posts/1', responses.posts_not_compound);
  fakeServer.get('/comments/2', responses.comments_2);
  fakeServer.get('/comments/3', responses.comments_3);

  Em.run(function() {
    env.store.find('post', '1').then(function(record) {
      equal(record.get('id'), '1', 'id is correct');
      equal(record.get('title'), 'Rails is Omakase', 'title is correct');

      record.get('comments').then(function(comments) {
        var comment1 = comments.objectAt(0);
        var comment2 = comments.objectAt(1);

        equal(comments.get('length'), 2, 'there are 2 comments');

        equal(comment1.get('title'), 'good article', 'comment1 title');
        equal(comment1.get('body'), 'ideal for my startup', 'comment1 body');
        equal(comment2.get('title'), 'bad article', 'comment2 title');
        equal(comment2.get('body'), "doesn't run Crysis", 'comment2 body');
        start();
      });
    });
  });
});

asyncTest('GET /some_resource, not camelCase', function() {
  var models = setModels({
    commentAsync: true
  });
  env = setupStore(models);

  fakeServer.get('/some_resources/1', responses.underscore_resource);

  Em.run(function() {
    env.store.find('someResource', '1').then(function(record) {
      equal(record.get('id'), '1', 'id is correct');
      equal(record.get('title'), 'wow', 'title is correct');
      start();
    });
  });
});
<commit_msg>Chaning to force URLs to be dasherized<commit_after>var get = Ember.get, set = Ember.set;
var env;
var responses, fakeServer;

module('integration/specs/urls-for-resource-collections', {
  setup: function() {
    fakeServer = stubServer();

    responses = {
      posts_not_compound: {
        data: {
          type: 'posts',
          id: '1',
          title: 'Rails is Omakase',
          links: {
            comments: {
              type: 'comments',
              ids: ['2', '3']
            }
          }
        }
      },
      comments_2: {
        data: {
          type: 'comments',
          'id': '2',
          'title': 'good article',
          'body': 'ideal for my startup'
        }
      },
      comments_3: {
        data: {
          type: 'comments',
          id: '3',
          title: 'bad article',
          body: "doesn't run Crysis"
        }
      },
      underscore_resource: {
        data: {
          type: 'some_resource',
          id: '1',
          title: 'wow'
        }
      }
    };

    env = setupStore(setModels());
    env.store.modelFor('post');
    env.store.modelFor('comment');
  },

  teardown: function() {
    Ember.run(env.store, 'destroy');
    shutdownFakeServer(fakeServer);
  }
});

asyncTest('GET /posts/1 calls later GET /comments/2,3 when Posts has async comments', function() {
  var models = setModels({
    commentAsync: true
  });
  env = setupStore(models);

  fakeServer.get('/posts/1', responses.posts_not_compound);
  fakeServer.get('/comments/2', responses.comments_2);
  fakeServer.get('/comments/3', responses.comments_3);

  Em.run(function() {
    env.store.find('post', '1').then(function(record) {
      equal(record.get('id'), '1', 'id is correct');
      equal(record.get('title'), 'Rails is Omakase', 'title is correct');

      record.get('comments').then(function(comments) {
        var comment1 = comments.objectAt(0);
        var comment2 = comments.objectAt(1);

        equal(comments.get('length'), 2, 'there are 2 comments');

        equal(comment1.get('title'), 'good article', 'comment1 title');
        equal(comment1.get('body'), 'ideal for my startup', 'comment1 body');
        equal(comment2.get('title'), 'bad article', 'comment2 title');
        equal(comment2.get('body'), "doesn't run Crysis", 'comment2 body');
        start();
      });
    });
  });
});

asyncTest('GET /some-resource, not camelCase, dasherized', function() {
  var models = setModels({
    commentAsync: true
  });
  env = setupStore(models);

  fakeServer.get('/some-resources/1', responses.underscore_resource);

  Em.run(function() {
    env.store.find('someResource', '1').then(function(record) {
      equal(record.get('id'), '1', 'id is correct');
      equal(record.get('title'), 'wow', 'title is correct');
      start();
    });
  });
});
<|endoftext|>


<commit_before>var LEADERBOARD_FINAL_DIALOG_ID = "leaderboard_final_dialog";

Template.leaderboard.onCreated(function onCreated() {
	this.show_survey_button = new ReactiveVar(false);
});

Template.leaderboard.onRendered(function onRendered() {
	Logs.log("Open leaderboard");
});

// Helpers for leaderboard template
Template.leaderboard.helpers({
	/**
	 * List of players
	 * @return {[Player]} List with all players
	 */
	players() {
		console.log("player list");
		var list = Players.findSortByTotalScore();
		return list;
	},
	/**
	 * Increment the given num by 1
	 * @param  {Int} num number to increment
	 * @return {Int}     num + 1
	 */
	incremented(num) {
		return num + 1;
	},
	/**
	 * Check if the given index is in polePosition (first, second, third position)
	 * @param  {Int} index index to check
	 * @return {Boolean}       If the index is in pole position range
	 */
	polePosition(index) {
		return index < 3;
	},
	isCurrentPlayer(player) {
		if (!player) {
			return false;
		}

		var user = Meteor.user();
		if (user._id == player.userId) {
			return true;
		} else {
			return false;
		}
	},
	/**
	 * Returns if it is the fully gamified environment or not
	 * @return {Boolean} True, if the environment is full, or False if it's minimal
	 */
	isFullEnvironment() {
		var FULLY_GAMIFIED = true;
		var publicSettings = Meteor.settings.public;
		if (!publicSettings.ENVIRONMENT || publicSettings.ENVIRONMENT.FULL == undefined) {
			FULLY_GAMIFIED = true;
		} else {
			FULLY_GAMIFIED = publicSettings.ENVIRONMENT.FULL;
		}
		return FULLY_GAMIFIED;
	},
	/**
	 * Check if the survey button must be showed or not
	 * @return {Boolean} If it's debug environment or user already filled the final survey
	 */
	showSurveyButton() {
		var instance = Template.instance();
		// Check if is in debug
		Meteor.call("isDebug", function(err, response) {
			if (response) {
				instance.show_survey_button.set(true);
				return;
			}

			var res = !userDoneSurvey(SURVEY_CERTAINTY_EFFECT_KEY) && !userDoneSurvey(SURVEY_REFLECTION_EFFECT_KEY);
			instance.show_survey_button.set(res);
		});

		return instance.show_survey_button.get();
	},
	leaderboardFinalDialogTitle() {
		return TAPi18n.__("leaderboard.final_dialog.title");
	},
	leaderboardFinalDialogMessage() {
		return TAPi18n.__("leaderboard.final_dialog.message");
	},
	leaderboardFinalDialogClose() {
		return TAPi18n.__("leaderboard.final_dialog.close");
	}
});

Template.leaderboard.events({
	/**
	 * Click event on survey button
	 */
	'click #leaderboard-survey-button' (event, instance) {
		var doneSurvey = userDoneSurvey(SURVEY_CERTAINTY_EFFECT_KEY) || userDoneSurvey(SURVEY_REFLECTION_EFFECT_KEY);
		if (doneSurvey) {
			Blaze._globalHelpers.showDialog(LEADERBOARD_FINAL_DIALOG_ID);
		} else {
			Router.go('survey', {
				_bias: SURVEY_CERTAINTY_EFFECT_KEY
			});
		}
	},
	/**
	 * Close button of final dialog clicked
	 */
	'click #leaderboard_final_close_button' (event, instance) {
		Blaze._globalHelpers.closeDialog(LEADERBOARD_FINAL_DIALOG_ID);
		Router.go('welcome');
	}
});<commit_msg>Leaderboard bug fix<commit_after>var LEADERBOARD_FINAL_DIALOG_ID = "leaderboard_final_dialog";

Template.leaderboard.onCreated(function onCreated() {
	this.show_survey_button = new ReactiveVar(false);
});

Template.leaderboard.onRendered(function onRendered() {
	Logs.log("Open leaderboard");
});

// Helpers for leaderboard template
Template.leaderboard.helpers({
	/**
	 * List of players
	 * @return {[Player]} List with all players
	 */
	players() {
		console.log("player list");
		var list = Players.findSortByTotalScore();
		return list;
	},
	/**
	 * Increment the given num by 1
	 * @param  {Int} num number to increment
	 * @return {Int}     num + 1
	 */
	incremented(num) {
		return num + 1;
	},
	/**
	 * Check if the given index is in polePosition (first, second, third position)
	 * @param  {Int} index index to check
	 * @return {Boolean}       If the index is in pole position range
	 */
	polePosition(index) {
		return index < 3;
	},
	isCurrentPlayer(player) {
		if (!player) {
			return false;
		}

		var user = Meteor.user();
		if (user._id == player.userId) {
			return true;
		} else {
			return false;
		}
	},
	/**
	 * Returns if it is the fully gamified environment or not
	 * @return {Boolean} True, if the environment is full, or False if it's minimal
	 */
	isFullEnvironment() {
		var FULLY_GAMIFIED = true;
		var publicSettings = Meteor.settings.public;
		if (!publicSettings.ENVIRONMENT || publicSettings.ENVIRONMENT.FULL == undefined) {
			FULLY_GAMIFIED = true;
		} else {
			FULLY_GAMIFIED = publicSettings.ENVIRONMENT.FULL;
		}
		return FULLY_GAMIFIED;
	},
	/**
	 * Check if the survey button must be showed or not
	 * @return {Boolean} If it's debug environment or user already filled the final survey
	 */
	showSurveyButton() {
		var instance = Template.instance();
		// Check if is in debug
		Meteor.call("isDebug", function(err, response) {
			if (response) {
				instance.show_survey_button.set(true);
				return;
			}

			// If user must play memory or fill framing survey, hide button
			if(!userDoneMemoryGame() || !userDoneSurvey(SURVEY_FRAMING_EFFECT_KEY)){
				instance.show_survey_button.set(false);
				return;
			}

			var res = !userDoneSurvey(SURVEY_CERTAINTY_EFFECT_KEY) && !userDoneSurvey(SURVEY_REFLECTION_EFFECT_KEY);
			instance.show_survey_button.set(res);
		});

		return instance.show_survey_button.get();
	},
	leaderboardFinalDialogTitle() {
		return TAPi18n.__("leaderboard.final_dialog.title");
	},
	leaderboardFinalDialogMessage() {
		return TAPi18n.__("leaderboard.final_dialog.message");
	},
	leaderboardFinalDialogClose() {
		return TAPi18n.__("leaderboard.final_dialog.close");
	}
});

Template.leaderboard.events({
	/**
	 * Click event on survey button
	 */
	'click #leaderboard-survey-button' (event, instance) {
		var doneSurvey = userDoneSurvey(SURVEY_CERTAINTY_EFFECT_KEY) || userDoneSurvey(SURVEY_REFLECTION_EFFECT_KEY);
		if (doneSurvey) {
			Blaze._globalHelpers.showDialog(LEADERBOARD_FINAL_DIALOG_ID);
		} else {
			Router.go('survey', {
				_bias: SURVEY_CERTAINTY_EFFECT_KEY
			});
		}
	},
	/**
	 * Close button of final dialog clicked
	 */
	'click #leaderboard_final_close_button' (event, instance) {
		Blaze._globalHelpers.closeDialog(LEADERBOARD_FINAL_DIALOG_ID);
		Router.go('welcome');
	}
});<|endoftext|>