<commit_before>import {EventEmitter} from './utils.js';

export var UI = {};

UI.setTitle = function (topic) {
    document.title = "MQTT Wall" + (topic ? (" for " + topic) : "");
};

UI.toast = function (message, type = "info", persistent = false) {
    var toast = $("
")
        .text(message)
        .addClass(type)
        .hide()
        .appendTo("#toast")
        .fadeIn();

    if (persistent != true) {
        toast.delay(5000).slideUp().queue(function () { this.remove(); });
    } else {
        $(" – reload")
            .find("a").click(function () { location.reload(); }).end()
            .appendTo(toast);
    }
};

export class MessageLine {

    constructor(topic){
        this.topic = topic;
        this.counter = 0;
        this.isNew = true;
        this.init();
    }

    init() {
        this.$root = $("
");

        var header = $("").appendTo(this.$root);

        $("
")
            .text(this.topic)
            .appendTo(header);

        if (window.config.showCounter) {
            this.$counterMark = $("0")
                .appendTo(header);
        }

        this.$retainMark = $("R")
            .appendTo(header);

        this.$payload = $("
").appendTo(this.$root);
    }

    set isRetained(value) {
        this.$retainMark[value ? 'show' : 'hide']();
    }

    set isSystemPayload(value) {
        this.$payload.toggleClass("sys", value);
    }

    highlight(line = false) {
        (line ? this.$root : this.$payload)
            .stop()
            .css({backgroundColor: "#0CB0FF"})
            .animate({backgroundColor: "#fff"}, 2000);
    }

    update(payload, retained) {
        this.counter ++;
        this.isRetained = retained;

        if (this.$counterMark) {
            this.$counterMark.text(this.counter);
        }

        if (payload == "")
        {
            payload = "NULL";
            this.isSystemPayload = true;
        }
        else
        {
            this.isSystemPayload = false;
        }

        this.$payload.text(payload);
        this.highlight(this.isNew);

        if (this.isNew) {
            this.isNew = false;
        }
    }
}

export class MessageContainer {

    constructor($parent) {
        this.sort = 'Alphabetically';
        this.$parent = $parent;
        this.init();
    }

    init() {
        this.reset();
    }

    reset() {
        this.lines = {};
        this.topics = [];
        this.$parent.html("");
    }

    update (topic, payload, retained) {

        if (!this.lines[topic]) {

            var line = new MessageLine(topic, this.$parent);

            this[`addLine${this.sort}`](line);
            this.lines[topic] = line;
        }

        this.lines[topic].update(payload, retained);
    }

    addLineAlphabetically (line) {

        if (this.topics.length == 0)
        {
            this.addLineChronologically(line);
            return;
        }

        var topic = line.topic;

        this.topics.push(topic);
        this.topics.sort();

        var n = this.topics.indexOf(topic);

        if (n == 0){
            this.$parent.prepend(line.$root);
            return;
        }

        var prev = this.topics[n - 1];
        line.$root.insertAfter(this.lines[prev].$root);
    }

    addLineChronologically (line) {
        this.topics.push(line.topic);
        this.$parent.append(line.$root);
    }
}

MessageContainer.SORT_APLHA = "Alphabetically";
MessageContainer.SORT_CHRONO = "Chronologically";

export class Footer {

    set clientId(value) {
        $("#status-client").text(value);
    }

    set host(value) {
        $("#status-host").text("ws://" + value);
    }

    set state(value) {
        var className = ["connecting", "connected", "fail"];
        var text = ["connecting...", "connected", "not connected"];

        $("#status-state").removeClass().addClass(className[value]);
        $("#status-state span").text(text[value]);
    }
}

export class Toolbar extends EventEmitter {

    constructor (parent) {
        super();

        this.$parent = parent;
        this.$topic = parent.find("#topic");

        this.initEventHandlers();
        this.initDefaultTopic();
    }

    initEventHandlers () {
        let inhibitor = false;

        this.$topic.keyup((e) => {
            if(e.which === 13) { // ENTER
                this.$topic.blur();
            }

            if (e.keyCode === 27) { // ESC
                inhibitor = true;
                this.$topic.blur();
            }
        });

        this.$topic.focus((e) => {
            inhibitor = false;
        });

        this.$topic.blur((e) => {
            if (inhibitor) {
                this.updateUi(); // revert changes
            } else {
                this.inputChanged();
            }
        });
    }

    inputChanged () {
        this._topic = this.$topic.val();
        this.emit("topic", this._topic);
    }

    initDefaultTopic () {
        // URL hash
        if (location.hash !== "") {
            this._topic = location.hash.substr(1);
        } else {
            this._topic = config.defaultTopic || "/#";
        }

        this.updateUi();
    }

    updateUi () {
        this.$topic.val(this._topic);
    }

    get topic () {
        return this._topic;
    }

    set topic (value) {
        this._topic = value;
        this.updateUi();
        this.emit("topic", value);
    }
}<commit_msg>Detect situation when topic stays same (#24)<commit_after>import {EventEmitter} from './utils.js';

export var UI = {};

UI.setTitle = function (topic) {
    document.title = "MQTT Wall" + (topic ? (" for " + topic) : "");
};

UI.toast = function (message, type = "info", persistent = false) {
    var toast = $("
")
        .text(message)
        .addClass(type)
        .hide()
        .appendTo("#toast")
        .fadeIn();

    if (persistent != true) {
        toast.delay(5000).slideUp().queue(function () { this.remove(); });
    } else {
        $(" – reload")
            .find("a").click(function () { location.reload(); }).end()
            .appendTo(toast);
    }
};

export class MessageLine {

    constructor(topic){
        this.topic = topic;
        this.counter = 0;
        this.isNew = true;
        this.init();
    }

    init() {
        this.$root = $("
");

        var header = $("").appendTo(this.$root);

        $("
")
            .text(this.topic)
            .appendTo(header);

        if (window.config.showCounter) {
            this.$counterMark = $("0")
                .appendTo(header);
        }

        this.$retainMark = $("R")
            .appendTo(header);

        this.$payload = $("
").appendTo(this.$root);
    }

    set isRetained(value) {
        this.$retainMark[value ? 'show' : 'hide']();
    }

    set isSystemPayload(value) {
        this.$payload.toggleClass("sys", value);
    }

    highlight(line = false) {
        (line ? this.$root : this.$payload)
            .stop()
            .css({backgroundColor: "#0CB0FF"})
            .animate({backgroundColor: "#fff"}, 2000);
    }

    update(payload, retained) {
        this.counter ++;
        this.isRetained = retained;

        if (this.$counterMark) {
            this.$counterMark.text(this.counter);
        }

        if (payload == "")
        {
            payload = "NULL";
            this.isSystemPayload = true;
        }
        else
        {
            this.isSystemPayload = false;
        }

        this.$payload.text(payload);
        this.highlight(this.isNew);

        if (this.isNew) {
            this.isNew = false;
        }
    }
}

export class MessageContainer {

    constructor($parent) {
        this.sort = 'Alphabetically';
        this.$parent = $parent;
        this.init();
    }

    init() {
        this.reset();
    }

    reset() {
        this.lines = {};
        this.topics = [];
        this.$parent.html("");
    }

    update (topic, payload, retained) {

        if (!this.lines[topic]) {

            var line = new MessageLine(topic, this.$parent);

            this[`addLine${this.sort}`](line);
            this.lines[topic] = line;
        }

        this.lines[topic].update(payload, retained);
    }

    addLineAlphabetically (line) {

        if (this.topics.length == 0)
        {
            this.addLineChronologically(line);
            return;
        }

        var topic = line.topic;

        this.topics.push(topic);
        this.topics.sort();

        var n = this.topics.indexOf(topic);

        if (n == 0){
            this.$parent.prepend(line.$root);
            return;
        }

        var prev = this.topics[n - 1];
        line.$root.insertAfter(this.lines[prev].$root);
    }

    addLineChronologically (line) {
        this.topics.push(line.topic);
        this.$parent.append(line.$root);
    }
}

MessageContainer.SORT_APLHA = "Alphabetically";
MessageContainer.SORT_CHRONO = "Chronologically";

export class Footer {

    set clientId(value) {
        $("#status-client").text(value);
    }

    set host(value) {
        $("#status-host").text("ws://" + value);
    }

    set state(value) {
        var className = ["connecting", "connected", "fail"];
        var text = ["connecting...", "connected", "not connected"];

        $("#status-state").removeClass().addClass(className[value]);
        $("#status-state span").text(text[value]);
    }
}

export class Toolbar extends EventEmitter {

    constructor (parent) {
        super();

        this.$parent = parent;
        this.$topic = parent.find("#topic");

        this.initEventHandlers();
        this.initDefaultTopic();
    }

    initEventHandlers () {
        let inhibitor = false;

        this.$topic.keyup((e) => {
            if(e.which === 13) { // ENTER
                this.$topic.blur();
            }

            if (e.keyCode === 27) { // ESC
                inhibitor = true;
                this.$topic.blur();
            }
        });

        this.$topic.focus((e) => {
            inhibitor = false;
        });

        this.$topic.blur((e) => {
            if (inhibitor) {
                this.updateUi(); // revert changes
            } else {
                this.inputChanged();
            }
        });
    }

    inputChanged () {
        var newTopic = this.$topic.val();

        if (newTopic === this._topic) {
            return;
        }

        this._topic = newTopic;
        this.emit("topic", newTopic);
    }

    initDefaultTopic () {
        // URL hash
        if (location.hash !== "") {
            this._topic = location.hash.substr(1);
        } else {
            this._topic = config.defaultTopic || "/#";
        }

        this.updateUi();
    }

    updateUi () {
        this.$topic.val(this._topic);
    }

    get topic () {
        return this._topic;
    }

    set topic (value) {
        this._topic = value;
        this.updateUi();
        this.emit("topic", value);
    }
}<|endoftext|>


<commit_before>/**
 * Plugin activation tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { deactivatePlugin, activatePlugin } from '@wordpress/e2e-test-utils';
import { useRequestInterception } from '../utils';

describe( 'Plugin Activation Notice', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().match( '/google-site-kit/v1/data/' ) ) {
				request.respond( { status: 200 } );
			} else {
				request.continue();
			}
		} );
	} );
	describe( 'When Javascript is enabled', () => {
		// Ensure Site Kit is disabled before running each test as it's enabled by default.
		beforeEach( async () => {
			await deactivatePlugin( 'google-site-kit' );
		} );

		afterEach( async () => {
			await activatePlugin( 'google-site-kit' );
		} );

		describe( 'using Proxy auth', () => {
			beforeEach( async () => {
				await activatePlugin( 'e2e-tests-proxy-credentials-plugin' );
			} );
			afterEach( async () => {
				await deactivatePlugin( 'e2e-tests-proxy-credentials-plugin' );
			} );
			it( 'Should be displayed', async () => {
				await activatePlugin( 'google-site-kit' );
				await page.waitForSelector( '.googlesitekit-activation__title' );
				await expect( page ).toMatchElement( '.googlesitekit-activation__title', { text: /Congratulations, the Site Kit plugin is now activated./i } );
			} );
			it( 'Should not display noscript notice', async () => {
				await activatePlugin( 'google-site-kit' );

				await expect( page ).not.toMatchElement( '.googlesitekit-noscript' );

				await deactivatePlugin( 'google-site-kit' );
			} );
		} );
		describe( 'using GCP auth', () => {
			beforeEach( async () => {
				await activatePlugin( 'e2e-tests-gcp-credentials-plugin' );
			} );
			afterEach( async () => {
				await deactivatePlugin( 'e2e-tests-gcp-credentials-plugin' );
			} );
			it( 'Should lead you to the setup wizard with GCP auth', async () => {
				await activatePlugin( 'google-site-kit' );

				await page.waitForSelector( '.googlesitekit-activation' );

				await expect( page ).toMatchElement( '.googlesitekit-start-setup', { text: 'Start setup' } );

				await page.click( '.googlesitekit-start-setup' );
				await page.waitForSelector( '.googlesitekit-wizard-step__title' );

				// Ensure we're on the first step.
				await expect( page ).toMatchElement( '.googlesitekit-wizard-progress-step__number--inprogress', { text: '1' } );

				await deactivatePlugin( 'google-site-kit' );
			} );
		} );
	} );

	describe( 'When Javascript is disabled', () => {
		beforeEach( async () => {
			await deactivatePlugin( 'google-site-kit' );
		} );

		afterEach( async () => {
			await activatePlugin( 'google-site-kit' );
		} );

		it( 'Should not display plugin html', async () => {
			// Disabling JavaScript in `beforeEach` breaks utility functions.
			// Each test without JavaScript must use
			// `await page.setJavaScriptEnabled( false );` and
			// `await page.setJavaScriptEnabled( true );` in the test itself.
			await page.setJavaScriptEnabled( false );
			await activatePlugin( 'google-site-kit' );

			await expect( page ).toMatchElement( '[id^=js-googlesitekit-]', { visible: false } );
			await expect( page ).not.toMatchElement( '.googlesitekit-activation__title' );

			await deactivatePlugin( 'google-site-kit' );
			await page.setJavaScriptEnabled( true );
		} );

		it( 'Should display noscript notice', async () => {
			await page.setJavaScriptEnabled( false );
			await activatePlugin( 'google-site-kit' );

			await expect( page ).toMatchElement(
				'.googlesitekit-noscript__text',
				{ text: /The Site Kit by Google plugin requires JavaScript to be enabled in your browser./i },
				{ visible: true }
			);

			await deactivatePlugin( 'google-site-kit' );
			await page.setJavaScriptEnabled( true );
		} );
	} );
} );
<commit_msg>Update plugin-activation test to wait for compatibility checks.<commit_after>/**
 * Plugin activation tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { deactivatePlugin, activatePlugin } from '@wordpress/e2e-test-utils';
import { useRequestInterception, createWaitForFetchRequests } from '../utils';

describe( 'plugin activation notice', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().match( '/google-site-kit/v1/data/' ) ) {
				request.respond( { status: 200 } );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		// Ensure Site Kit is disabled before running each test as it's enabled by default.
		await deactivatePlugin( 'google-site-kit' );
	} );

	afterAll( async () => {
		await activatePlugin( 'google-site-kit' );
	} );

	const matrix = {
		shouldBeDisplayed: async () => {
			const waitForFetchRequests = createWaitForFetchRequests();
			await activatePlugin( 'google-site-kit' );

			await page.waitForSelector( '.googlesitekit-activation__title' );

			await expect( page ).toMatchElement( '.googlesitekit-activation__title', { text: /Congratulations, the Site Kit plugin is now activated./i } );

			await waitForFetchRequests(); // Wait for compatibility checks to finish.
		},
		shouldNotDisplayNoScriptNotice: async () => {
			const waitForFetchRequests = createWaitForFetchRequests();
			await activatePlugin( 'google-site-kit' );

			await expect( page ).not.toMatchElement( '.googlesitekit-noscript' );

			await waitForFetchRequests(); // Wait for compatibility checks to finish.
		},
	};

	describe( 'using proxy auth', () => {
		beforeAll( async () => {
			await activatePlugin( 'e2e-tests-proxy-credentials-plugin' );
		} );

		afterAll( async () => {
			await deactivatePlugin( 'e2e-tests-proxy-credentials-plugin' );
		} );

		it( 'should be displayed', matrix.shouldBeDisplayed );

		it( 'should not display noscript notice', matrix.shouldNotDisplayNoScriptNotice );
	} );

	describe( 'using GCP auth', () => {
		beforeAll( async () => {
			await activatePlugin( 'e2e-tests-gcp-credentials-plugin' );
		} );

		afterAll( async () => {
			await deactivatePlugin( 'e2e-tests-gcp-credentials-plugin' );
		} );

		it( 'should be displayed', matrix.shouldBeDisplayed );

		it( 'should not display noscript notice', matrix.shouldNotDisplayNoScriptNotice );

		it( 'should lead you to the setup wizard with GCP auth', async () => {
			const waitForFetchRequests = createWaitForFetchRequests();

			await activatePlugin( 'google-site-kit' );

			await page.waitForSelector( '.googlesitekit-activation__title' );

			await expect( page ).toMatchElement( '.googlesitekit-start-setup', { text: 'Start setup' } );

			await waitForFetchRequests(); // Wait for compatibility checks to finish.

			await page.click( '.googlesitekit-start-setup' );
			await page.waitForSelector( '.googlesitekit-wizard-step__title' );

			// Ensure we're on the first step.
			await expect( page ).toMatchElement( '.googlesitekit-wizard-progress-step__number--inprogress', { text: '1' } );
		} );
	} );
} );
<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2018 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Node.js script to run JsUnit tests in Chrome, via webdriver.
 */
var webdriverio = require('webdriverio');

module.exports = runMochaTestsInBrowser;

/**
 * Runs the Mocha tests in this directory in Chrome. It uses webdriverio to
 * launch Chrome and load index.html. Outputs a summary of the test results
 * to the console.
 * @return 0 on success, 1 on failure.
 */
async function runMochaTestsInBrowser() {
  var options = {
      capabilities: {
          browserName: 'chrome'
      }
  };

  var url = 'file://' + __dirname + '/index.html';
  console.log('Starting webdriverio...');
  const browser = await webdriverio.remote(options);
  console.log('Initialized.\nLoading url: ' + url);
  await browser.url(url);

  await browser.waitUntil(async () => {
    var elem = await browser.$('#failureCount');
    var text = await elem.getAttribute('tests_failed');
    return text != 'unset';
  })

  const elem = await browser.$('#failureCount')
  const numOfFailure = await elem.getAttribute('tests_failed');

  console.log('============Blockly Mocha Test Summary=================');
  console.log(numOfFailure);
  console.log(numOfFailure + ' tests failed');
  console.log('============Blockly Mocha Test Summary=================');
  if (parseInt(numOfFailure) !== 0) {
    await browser.deleteSession();
    return 1;
  }
  await browser.deleteSession();
  return 0;
}

if (require.main === module) {
  runMochaTestsInBrowser().catch(e => {
    console.error(e);
    process.exit(1);
  }).then(function(result) {
    if (result) {
      console.log('Mocha tests failed');
      process.exit(1);
    } else {
      console.log('Mocha tests passed');
      process.exit(0);
    }
  });
}
<commit_msg>Update comments<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2019 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Node.js script to run Mocha tests in Chrome, via webdriver.
 */
var webdriverio = require('webdriverio');

module.exports = runMochaTestsInBrowser;

/**
 * Runs the Mocha tests in this directory in Chrome. It uses webdriverio to
 * launch Chrome and load index.html. Outputs a summary of the test results
 * to the console.
 * @return 0 on success, 1 on failure.
 */
async function runMochaTestsInBrowser() {
  var options = {
      capabilities: {
          browserName: 'chrome'
      }
  };

  var url = 'file://' + __dirname + '/index.html';
  console.log('Starting webdriverio...');
  const browser = await webdriverio.remote(options);
  console.log('Initialized.\nLoading url: ' + url);
  await browser.url(url);

  await browser.waitUntil(async () => {
    var elem = await browser.$('#failureCount');
    var text = await elem.getAttribute('tests_failed');
    return text != 'unset';
  })

  const elem = await browser.$('#failureCount')
  const numOfFailure = await elem.getAttribute('tests_failed');

  console.log('============Blockly Mocha Test Summary=================');
  console.log(numOfFailure);
  console.log(numOfFailure + ' tests failed');
  console.log('============Blockly Mocha Test Summary=================');
  if (parseInt(numOfFailure) !== 0) {
    await browser.deleteSession();
    return 1;
  }
  await browser.deleteSession();
  return 0;
}

if (require.main === module) {
  runMochaTestsInBrowser().catch(e => {
    console.error(e);
    process.exit(1);
  }).then(function(result) {
    if (result) {
      console.log('Mocha tests failed');
      process.exit(1);
    } else {
      console.log('Mocha tests passed');
      process.exit(0);
    }
  });
}
<|endoftext|>


<commit_before>import {
  moduleForComponent,
  test
} from 'ember-qunit';

import Ember from 'ember';

moduleForComponent('split-child', 'SplitChildComponent', {
  // specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
});

test('it renders', function(assert) {
  assert.expect(2);

  // creates the component instance
  var component;

  Ember.run(function(){
    component = this.subject();
  }.bind(this));

  assert.equal(component._state, 'preRender');

  // appends the component to the page
  this.append();
  assert.equal(component._state, 'inDOM');
});
<commit_msg>Fix for travis-ci<commit_after>import {
  moduleForComponent,
  test
} from 'ember-qunit';

import Ember from 'ember';

moduleForComponent('split-child', 'SplitChildComponent', {
  // specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
});

test('it renders', function(assert) {
  assert.expect(2);

  // creates the component instance
  var component;
  var self = this;

  Ember.run(function(){
    component = self.subject();
  });

  assert.equal(component._state, 'preRender');

  // appends the component to the page
  this.append();
  assert.equal(component._state, 'inDOM');
});
<|endoftext|>


<commit_before><commit_msg>Remove newline<commit_after><|endoftext|>


<commit_before>const APP_VERSION = require("./package.json").version;
const PROFILE = process.env.PROFILE || 'dev';
const profileConfig = require('./webpack-profiles.config')[PROFILE];

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');

const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const NoEmitOnErrorsPlugin = require('webpack/lib/NoEmitOnErrorsPlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const ChunkHashPlugin = require('webpack-chunk-hash');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const { AotPlugin } = require('@ngtools/webpack');
const ENABLE_AOT = profileConfig.production;

const PATHS = { };
PATHS.root         = path.join(__dirname, './');
PATHS.dist         = path.join(PATHS.root, `dist/${PROFILE}`);
PATHS.node_modules = path.join(PATHS.root, 'node_modules');
PATHS.app          = path.join(PATHS.root, 'app');

const baseOutputName = `[name]-${APP_VERSION}-[chunkhash:12]`;
const extractCSS = new ExtractTextPlugin({
   filename: `${baseOutputName}.css`
});

const isInPath = (module, p, ignores) => {
   let inPath = false;
   if (module.userRequest) {
      inPath = (module.userRequest.indexOf(p) === 0);

      // Vérification des ignores
      if (inPath && ignores) {
         let hasIgnore = ignores.some((ignore) => {
            return (module.userRequest.indexOf(path.join(p, ignore)) === 0);
         });

         inPath = (hasIgnore ? false : inPath);
      }
   }

   return inPath;
};

let config = {
   devtool: false,

   entry: {
      'polyfills': path.join(PATHS.app, 'polyfills.ts'),
      'main': path.join(PATHS.app, 'main.ts')
   },

   output: {
      path: PATHS.dist,
      publicPath: '',
      filename: `${baseOutputName}.js`
   },

   resolve: {
      modules: ['node_modules'],
      extensions: ['.ts', '.js'],
      alias: {
         'app': PATHS.app
      }
   },

   module: {
      rules: [
         {
            test: /\.ts$/,
            loaders: ['@ngtools/webpack'],
            exclude: [/\.(spec|e2e)\.ts$/]
         },

         {
            test: /\.s?css$/,
            loader: extractCSS.extract({
               fallback: 'style-loader',
               use: ['css-loader', 'sass-loader']
            }),
            exclude: [/\.component\.s?css$/]
         },

         {
            test: /\.s?css$/,
            loaders: ['to-string-loader', 'css-loader', 'sass-loader'],
            include: [/\.component\.s?css$/]
         },

         { test: /\.json/, loader: 'json-loader' },
         { test: /\.html$/, loader: 'html-loader' },

         {
            test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'file-loader',
            query: {
               name: `[path][name].[ext]`
            }
         }
      ]
   },

   plugins: [
      new NoEmitOnErrorsPlugin(),
      new ChunkHashPlugin(),

      new DefinePlugin({
         PROFILE_CONFIG: JSON.stringify(profileConfig)
      }),

      // Plugin AOT pour Angular
      new AotPlugin({
         tsConfigPath: './tsconfig.json',
         mainPath: "app/main.ts",
         skipCodeGeneration: !ENABLE_AOT // AOT really happens here (false = enabled)
      }),

      // Permet de séparer le code applicatif des librairies externes
      new CommonsChunkPlugin({
         name: 'vendor-modules',
         chunks: ['main'],
         minChunks: (module) => isInPath(module, PATHS.node_modules, ['@angular'])
      }),

      // Sortir Angular hors du vendor-modules
      new CommonsChunkPlugin({
         name: 'vendor-angular',
         chunks: ['vendor-modules', 'main'],
         minChunks: (module) => isInPath(module, path.join(PATHS.node_modules, '@angular'))
      }),

      // Faire un fichier pour les polyfills
      new CommonsChunkPlugin({
         name: 'polyfills'
      }),

      // Faire un fichier pour la partie "webpack" (manifest)
      new CommonsChunkPlugin({
         name: 'manifest',
         minChunks: Infinity
      }),

      extractCSS,

      // Recopier tout sauf ce qui est déjà pris en compte
      new CopyWebpackPlugin([
         // Copie de la config avec un search-replace
         {
            from: 'app/resources/config/*.json',
            to: '',
            transform: (content) => {
               // Regex permettant de remplacer tous les @{xxx} par ce qui se trouve dans le profileConfig
               return content.toString().replace(/@\{(\w*?)}/g, (match, p1) => profileConfig[p1]);
            }
         },

         {
            from: 'app',
            to: 'app',
            ignore: ['*.ts', '*.scss', '*.css', '*.html']
         }
      ]),

      new HtmlWebpackPlugin({
         filename: 'index.html',
         template: 'app/index.html',
         favicon: 'app/favicon.png',
         inject: true,
         minify: false
      })
   ],

   stats: {
      colors: true,
      hash: false,
      version: false,
      assets: true,
      cached: false,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false,
      chunkOrigins: false,
      reasons: false,
      source: false,
      maxModules: 0
   }

};

if ('dev' === PROFILE) {
   config = merge(config, {
      devtool: 'cheap-module-eval-source-map',

      devServer: {
         port: 3000,
         inline: false,
         hot: false,
         stats: config.stats
      }
   });
}

else {
   config = merge(config, {
      plugins: [
         new ProgressPlugin(),
         new CleanWebpackPlugin([PATHS.dist], { root: PATHS.root }),

         new UglifyJsPlugin({
            comments: false,
            beautify: false,
            sourceMap: false,
            mangle: {
               screw_ie8: true,
               keep_fnames: true
            },
            compress: {
               screw_ie8: true,
               warnings: false
            }
         })
      ]
   });
}

module.exports = config;
<commit_msg>webpack config<commit_after>const APP_VERSION = require("./package.json").version;
const PROFILE = process.env.PROFILE || 'dev';
const profileConfig = require('./webpack-profiles.config')[PROFILE];

const path = require('path');
const merge = require('webpack-merge');

const NoEmitOnErrorsPlugin = require('webpack/lib/NoEmitOnErrorsPlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const ChunkHashPlugin = require('webpack-chunk-hash');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const { AotPlugin } = require('@ngtools/webpack');
const ENABLE_AOT = true; //profileConfig.production;

const PATHS = { };
PATHS.root         = path.join(__dirname, './');
PATHS.dist         = path.join(PATHS.root, `dist/${PROFILE}`);
PATHS.node_modules = path.join(PATHS.root, 'node_modules');
PATHS.app          = path.join(PATHS.root, 'app');

const baseOutputName = `[name]-${APP_VERSION}-[chunkhash:12]`;
const extractCSS = new ExtractTextPlugin({
   filename: `${baseOutputName}.css`
});

const isInPath = (module, p, ignores) => {
   let inPath = false;
   if (module.userRequest) {
      inPath = (module.userRequest.indexOf(p) === 0);

      // Vérification des ignores
      if (inPath && ignores) {
         let hasIgnore = ignores.some((ignore) => {
            return (module.userRequest.indexOf(path.join(p, ignore)) === 0);
         });

         inPath = (hasIgnore ? false : inPath);
      }
   }

   return inPath;
};

let config = {
   devtool: false,

   entry: {
      'polyfills': path.join(PATHS.app, 'polyfills.ts'),
      'main': path.join(PATHS.app, 'main.ts')
   },

   output: {
      path: PATHS.dist,
      publicPath: '',
      filename: `${baseOutputName}.js`
   },

   resolve: {
      modules: ['node_modules'],
      extensions: ['.ts', '.js'],
      alias: {
         'app': PATHS.app
      }
   },

   module: {
      rules: [
         {
            test: /\.ts$/,
            loaders: ['@ngtools/webpack'],
            exclude: [/\.(spec|e2e)\.ts$/]
         },

         {
            test: /\.s?css$/,
            loader: extractCSS.extract({
               fallback: 'style-loader',
               use: ['css-loader', 'sass-loader']
            }),
            exclude: [/\.component\.s?css$/]
         },

         {
            test: /\.s?css$/,
            loaders: ['to-string-loader', 'css-loader', 'sass-loader'],
            include: [/\.component\.s?css$/]
         },

         { test: /\.json/, loader: 'json-loader' },
         { test: /\.html$/, loader: 'html-loader' },

         {
            test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'file-loader',
            query: {
               name: `[path][name].[ext]`
            }
         }
      ]
   },

   plugins: [
      new NoEmitOnErrorsPlugin(),
      new ChunkHashPlugin(),

      new DefinePlugin({
         PROFILE_CONFIG: JSON.stringify(profileConfig)
      }),

      // Plugin AOT pour Angular
      new AotPlugin({
         tsConfigPath: './tsconfig.json',
         mainPath: "app/main.ts",
         skipCodeGeneration: !ENABLE_AOT // AOT really happens here (false = enabled)
      }),

      // Permet de séparer le code applicatif des librairies externes
      new CommonsChunkPlugin({
         name: 'vendor',
         chunks: ['main'],
         minChunks: (module) => isInPath(module, PATHS.node_modules, ['@angular'])
      }),

      // Sortir Angular hors du vendor-modules
      new CommonsChunkPlugin({
         name: 'angular',
         chunks: ['vendor', 'main'],
         minChunks: (module) => isInPath(module, path.join(PATHS.node_modules, '@angular'))
      }),

      // Faire un fichier pour la partie "webpack" (manifest)
      new CommonsChunkPlugin({
         name: 'manifest',
         minChunks: null
      }),

      extractCSS,

      // Recopier tout sauf ce qui est déjà pris en compte
      new CopyWebpackPlugin([
         // Copie de la config avec un search-replace
         {
            from: 'app/resources/config/*.json',
            to: '',
            transform: (content) => {
               // Regex permettant de remplacer tous les @{xxx} par ce qui se trouve dans le profileConfig
               return content.toString().replace(/@\{(\w*?)}/g, (match, p1) => profileConfig[p1]);
            }
         },

         {
            from: 'app',
            to: 'app',
            ignore: ['*.ts', '*.scss', '*.css', '*.html']
         }
      ]),

      new HtmlWebpackPlugin({
         filename: 'index.html',
         template: 'app/index.html',
         favicon: 'app/favicon.png',
         inject: true,
         minify: false
      })

   ],

   stats: {
      colors: true,
      hash: false,
      version: false,
      assets: true,
      cached: false,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false,
      chunkOrigins: false,
      reasons: false,
      source: false,
      maxModules: 0
   }

};

if ('dev' === PROFILE) {
   config = merge(config, {
      devtool: 'cheap-module-eval-source-map',

      devServer: {
         port: 3000,
         inline: false,
         hot: false,
         stats: config.stats
      }
   });
}

else {
   config = merge(config, {
      plugins: [
         new ProgressPlugin(),
         new CleanWebpackPlugin([PATHS.dist], { root: PATHS.root }),

         new UglifyJsPlugin({
            comments: false,
            beautify: false,
            sourceMap: false,
            mangle: {
               screw_ie8: true,
               keep_fnames: true
            },
            compress: {
               screw_ie8: true,
               warnings: false
            }
         })
      ]
   });
}

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

function filterTodos (model, currentPath, options) {
  options = options || {};

  var activeTodos = model.todos.filter(function (todo) {
    return !todo.completed;
  });
  var completedTodos = model.todos.filter(function (todo) {
    return todo.completed;
  });

  if (options.counts) {
    model.activeTodosCount = activeTodos.length;
    model.completedTodosCount = completedTodos.length;
  }

  switch (currentPath) {
    case 'active':
      model.todos = activeTodos;
      break;
    case 'completed':
      model.todos = completedTodos;
      break;
  }
}

module.exports = filterTodos;
<commit_msg>refactor todos filtering<commit_after>'use strict';

function filterTodos (model, currentPath, options) {
  options = options || {};

  var completedTodos = [];
  var activeTodos = [];

  model.todos.forEach(function (todo) {
    if (todo.completed) {
      completedTodos.push(todo);
    } else {
      activeTodos.push(todo);
    }
  });

  if (options.counts) {
    model.activeTodosCount = activeTodos.length;
    model.completedTodosCount = completedTodos.length;
  }

  if (currentPath === 'completed') {
    model.todos = completedTodos;
  } else if (currentPath === 'active') {
    model.todos = activeTodos;
  }
}

module.exports = filterTodos;
<|endoftext|>


<commit_before>import React from 'react';

import { styled } from '@storybook/theming';

const Heading = styled.span(({ theme }) => ({
  display: 'block',
  letterSpacing: '0.35em',
  textTransform: 'uppercase',
  fontWeight: theme.typography.weight.black,
  fontSize: theme.typography.size.s1 - 1,
  lineHeight: '24px',
  color: theme.color.mediumdark,
}));

const Subheading = props => <Heading {...props} />;

export default Subheading;
<commit_msg>Change SidebarSubheading to div instead of span<commit_after>import React from 'react';

import { styled } from '@storybook/theming';

const Heading = styled.div(({ theme }) => ({
  letterSpacing: '0.35em',
  textTransform: 'uppercase',
  fontWeight: theme.typography.weight.black,
  fontSize: theme.typography.size.s1 - 1,
  lineHeight: '24px',
  color: theme.color.mediumdark,
}));

const Subheading = props => <Heading {...props} />;

export default Subheading;
<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const merge = require('webpack-merge')
const { VueLoaderPlugin } = require('vue-loader')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

module.exports = (config, target = { chrome: 52, firefox: 48 }) => {
  const bubleOptions = {
    target,
    objectAssign: 'Object.assign',
    transforms: {
      forOf: false,
      modules: false
    }
  }

  const baseConfig = {
    resolve: {
      alias: {
        src: path.resolve(__dirname, '../src'),
        views: path.resolve(__dirname, '../src/devtools/views'),
        components: path.resolve(__dirname, '../src/devtools/components')
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          loader: 'buble-loader',
          exclude: /node_modules|vue\/dist|vuex\/dist/,
          options: bubleOptions
        },
        {
          test: /\.vue$/,
          loader: 'vue-loader',
          options: {
            compilerOptions: {
              preserveWhitespace: false
            },
            transpileOptions: bubleOptions
          }
        },
        {
          test: /\.css$/,
          use: [
            'vue-style-loader',
            'css-loader'
          ]
        },
        {
          test: /\.styl(us)?$/,
          use: [
            'vue-style-loader',
            'css-loader',
            'stylus-loader'
          ]
        },
        {
          test: /\.(png|woff2)$/,
          loader: 'url-loader?limit=0'
        }
      ]
    },
    performance: {
      hints: false
    },
    plugins: [
      new VueLoaderPlugin(),
      ...(process.env.VUE_DEVTOOL_TEST ? [] : [new FriendlyErrorsPlugin()]),
      new webpack.DefinePlugin({
        'process.env': {
          CHANNEL: JSON.stringify(process.env.CHANNEL || 'stable')
        }
      })
    ],
    devServer: {
      port: process.env.PORT
    }
  }

  if (process.env.NODE_ENV === 'production') {
    const UglifyPlugin = require('uglifyjs-webpack-plugin')
    baseConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: '"production"'
        }
      }),
      new UglifyPlugin()
    )
  }

  return merge(baseConfig, config)
}
<commit_msg>fix: process env<commit_after>const path = require('path')
const webpack = require('webpack')
const merge = require('webpack-merge')
const { VueLoaderPlugin } = require('vue-loader')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

module.exports = (config, target = { chrome: 52, firefox: 48 }) => {
  const bubleOptions = {
    target,
    objectAssign: 'Object.assign',
    transforms: {
      forOf: false,
      modules: false
    }
  }

  const baseConfig = {
    resolve: {
      alias: {
        src: path.resolve(__dirname, '../src'),
        views: path.resolve(__dirname, '../src/devtools/views'),
        components: path.resolve(__dirname, '../src/devtools/components')
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          loader: 'buble-loader',
          exclude: /node_modules|vue\/dist|vuex\/dist/,
          options: bubleOptions
        },
        {
          test: /\.vue$/,
          loader: 'vue-loader',
          options: {
            compilerOptions: {
              preserveWhitespace: false
            },
            transpileOptions: bubleOptions
          }
        },
        {
          test: /\.css$/,
          use: [
            'vue-style-loader',
            'css-loader'
          ]
        },
        {
          test: /\.styl(us)?$/,
          use: [
            'vue-style-loader',
            'css-loader',
            'stylus-loader'
          ]
        },
        {
          test: /\.(png|woff2)$/,
          loader: 'url-loader?limit=0'
        }
      ]
    },
    performance: {
      hints: false
    },
    plugins: [
      new VueLoaderPlugin(),
      ...(process.env.VUE_DEVTOOL_TEST ? [] : [new FriendlyErrorsPlugin()]),
      new webpack.DefinePlugin({
        'process.env.CHANNEL': JSON.stringify(process.env.CHANNEL || 'stable')
      })
    ],
    devServer: {
      port: process.env.PORT
    }
  }

  if (process.env.NODE_ENV === 'production') {
    const UglifyPlugin = require('uglifyjs-webpack-plugin')
    baseConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
      }),
      new UglifyPlugin()
    )
  }

  return merge(baseConfig, config)
}
<|endoftext|>


<commit_before>// FL-04-Mar-2013 Created
// FL-24-Oct-2013 Changed

/*
function clearTextview()
function updateTextview( record_id, data )
function writeTextview( record_id, data )
*/

function clearTextview()
{
	// close all tabs but the first 2
//	var tabs = dijit.byId( "articleContainer" ).getChildren();
//	for( var tab = 2; tab < tabs.length; tab++ )
//	{ dijit.byId( "articleContainer" ).closeChild( tabs[ tab ] ); }

	if( dojo.byId( "record" ) == undefined )
	{ return; }
	else
	{ dojo.byId( "record" ).innerHTML = ""; }		// clear text
}

function updateTextview( collection, record_id, data, documentObj )
{
	console.log( "updateTextview(): " + record_id );
	var record_id_ocr = record_id + ":ocr";

	var config = getConfig();
	var senthlight = config[ "sentiment" ][ "highlight" ];
	if( senthlight === true )		// highlight text content
	{
		xtas.postWaiting(
			"process/",
			{
				content: {
					collections: collection,	// xTAS wants collections, not collection
					id: record_id,
					methods: "sentiment"
				},
				handleAs: "json"
			},
			function( sentdata )
			{
				if( typeof( sentdata ) === "string" && !( sentdata == null || sentdata.length == 0 ) )
				{ sentdata = dojo.fromJson( sentdata ); }

				if( sentdata.status === "ok" )
				{
					var word_sents = sentdata.result;
					dojo.forEach( word_sents, function( word_sent )
					{
						// the results may contain duplicate words
						var word = word_sent[ 0 ];
						// \b as word separator not supported by this RegExp() ?
						var re = new RegExp( "("+word+")", "gi" );	// g: global, i: case-insensitive
					//	console.log( re );
						var sentiment = word_sent[ 1 ];
						if( sentiment.split( "" )[ 0 ] === "+" )
						{
						//	console.log( word + ": " + sentiment + " green" );
							data = data.replace( re, "$1".bold().fontcolor("green") );
						}
						else if( sentiment.split( "" )[ 0 ] === "-" )
						{
						//	console.log( word + ": " + sentiment + " red" );
							data = data.replace( re, "$1".bold().fontcolor("red") );
						}
					//	else
					//	{ console.log( word + ": " + sentiment + " ?" ); }
					});
				//	dojo.byId( "record" ).innerHTML = data.replace( /<(\/?)title>/g, "<$1b>" );
					writeTextview( record_id, data, documentObj );
				}
			}
		);
	}
	else	// update article text view without highlighting
	{ writeTextview( record_id, data, documentObj ); }
} // updateTextview()

function writeTextview( record_id, data, documentObj )
{
	console.log( "writeTextview() " + record_id);

    article_text = documentObj.text_content.replace('\n\n\n', '

');

	dojo.byId( "record" ).innerHTML = ""+documentObj.article_dc_title+"
"+article_text;
}

// [eof]
<commit_msg>Fix replacing newlines with breaks in OCR text<commit_after>// FL-04-Mar-2013 Created
// FL-24-Oct-2013 Changed

/*
function clearTextview()
function updateTextview( record_id, data )
function writeTextview( record_id, data )
*/

function clearTextview()
{
	// close all tabs but the first 2
//	var tabs = dijit.byId( "articleContainer" ).getChildren();
//	for( var tab = 2; tab < tabs.length; tab++ )
//	{ dijit.byId( "articleContainer" ).closeChild( tabs[ tab ] ); }

	if( dojo.byId( "record" ) == undefined )
	{ return; }
	else
	{ dojo.byId( "record" ).innerHTML = ""; }		// clear text
}

function updateTextview( collection, record_id, data, documentObj )
{
	console.log( "updateTextview(): " + record_id );
	var record_id_ocr = record_id + ":ocr";

	var config = getConfig();
	var senthlight = config[ "sentiment" ][ "highlight" ];
	if( senthlight === true )		// highlight text content
	{
		xtas.postWaiting(
			"process/",
			{
				content: {
					collections: collection,	// xTAS wants collections, not collection
					id: record_id,
					methods: "sentiment"
				},
				handleAs: "json"
			},
			function( sentdata )
			{
				if( typeof( sentdata ) === "string" && !( sentdata == null || sentdata.length == 0 ) )
				{ sentdata = dojo.fromJson( sentdata ); }

				if( sentdata.status === "ok" )
				{
					var word_sents = sentdata.result;
					dojo.forEach( word_sents, function( word_sent )
					{
						// the results may contain duplicate words
						var word = word_sent[ 0 ];
						// \b as word separator not supported by this RegExp() ?
						var re = new RegExp( "("+word+")", "gi" );	// g: global, i: case-insensitive
					//	console.log( re );
						var sentiment = word_sent[ 1 ];
						if( sentiment.split( "" )[ 0 ] === "+" )
						{
						//	console.log( word + ": " + sentiment + " green" );
							data = data.replace( re, "$1".bold().fontcolor("green") );
						}
						else if( sentiment.split( "" )[ 0 ] === "-" )
						{
						//	console.log( word + ": " + sentiment + " red" );
							data = data.replace( re, "$1".bold().fontcolor("red") );
						}
					//	else
					//	{ console.log( word + ": " + sentiment + " ?" ); }
					});
				//	dojo.byId( "record" ).innerHTML = data.replace( /<(\/?)title>/g, "<$1b>" );
					writeTextview( record_id, data, documentObj );
				}
			}
		);
	}
	else	// update article text view without highlighting
	{ writeTextview( record_id, data, documentObj ); }
} // updateTextview()

function writeTextview( record_id, data, documentObj )
{
	console.log( "writeTextview() " + record_id);

    article_text = documentObj.text_content.replace(/\n\n/g, "

");

	dojo.byId( "record" ).innerHTML = ""+documentObj.article_dc_title+"
"+article_text;
}

// [eof]
<|endoftext|>


<commit_before>$(function() {

  // Groups (like 'java' and 'scala') represent groups of 'switchable' content, either in tabs or in regular text.
  // The catalog of groups can be defined in the sbt parameters to initialize the group.

  var groupCookie = "paradoxGroups";
  var cookieTg = getCookie(groupCookie);
  var currentGroups = {};

  var catalog = {}
  var supergroupByGroup = {};

  if(cookieTg != "")
    currentGroups = JSON.parse(cookieTg);

  // http://www.w3schools.com/js/js_cookies.asp
  function setCookie(cname,cvalue,exdays) {
    if(!exdays) exdays = 365;
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

  // http://www.w3schools.com/js/js_cookies.asp
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  $(".supergroup").each(function() {
    var supergroup = $(this).attr('name').toLowerCase();
    var groups = $(this).find(".group");

    var current = currentGroups[supergroup];
    if (!current) {
      current = "group-" + groups.first().text().toLowerCase();
      currentGroups[supergroup] = current;
    }

    catalog[supergroup] = [];

    groups.each(function() {
      var group = "group-" + $(this).text().toLowerCase();
      catalog[supergroup].push(group);
      supergroupByGroup[group] = supergroup;
      if(group == current) {
        switchToGroup(supergroup, this.value);
      } else {
        $("span." + group).hide()
      }
    });

    $(this).on("change", function() {
      switchToGroup(supergroup, this.value);
    });
  });

  $("dl").has("dd > pre").each(function() {
    var dl = $(this);
    dl.addClass("tabbed");
    var dts = dl.find("dt");
    dts.each(function(i) {
      var dt = $(this);
      dt.html("" + dt.text() + "");
    });
    var dds = dl.find("dd");
    dds.each(function(i) {
      var dd = $(this);
      dd.hide();
      if (dd.find("blockquote").length) {
        dd.addClass("has-note");
      }
    });

    var current;
    for (var supergroup in currentGroups) {
      dts.each(function() {
        var dt = $(this);
        var pre = dt.next("dd").find("pre");
        if(pre.hasClass(currentGroups[supergroup]))
          current = dt.addClass("current");
      });
    }

    if(!current)
      current = dts.first().addClass("current");
    var currentContent = current.next("dd").addClass("current").show();
    dts.first().addClass("first");
    dts.last().addClass("last");
    dl.css("height", current.height() + currentContent.height());
  });

  $("dl.tabbed dt a").click(function(e){
    e.preventDefault();
    var currentDt = $(this).parent("dt");
    var currentDl = currentDt.parent("dl");

    var currentGroup = groupOf(currentDt);

    if(!currentGroup) {
      currentDl.find(".current").removeClass("current").next("dd").removeClass("current").hide();
      currentDt.addClass("current");
      var currentContent = currentDt.next("dd").addClass("current").show();
      currentDl.css("height", currentDt.height() + currentContent.height());
    } else {
      var supergroup = supergroupByGroup[currentGroup]
      if (supergroup) {
        switchToGroup(supergroup, currentGroup);
      } else {
        switchToTab(currentDt);
      }
    }
  });

  function switchToGroup(supergroup, group) {
    currentGroups[supergroup] = group;
    setCookie(groupCookie, JSON.stringify(currentGroups));

    // Dropdown switcher:
    $("select")
      .has("option[value=" + group +"]")
      .val(group);

    // Inline snippets:
    for (var i = 0; i < catalog[supergroup].length; i++) {
      var peer = catalog[supergroup][i];
      if (peer == group) {
        $("span." + group).show();
      } else {
        $("span." + peer).hide();
      }
    }

    // Tabbed snippets:
    $("dl").has("dd > pre").each(function() {
      var dl = $(this);
      dl.find("dt").each(function() {
        var dt = $(this);
        var pre = dt.next("dd").find("pre");
        if(pre.hasClass(group)) {
          switchToTab(dt);
        }
      });
    });
  }

  function switchToTab(dt) {
    var dl = dt.parent("dl");
    dl.find(".current").removeClass("current").next("dd").removeClass("current").hide();
    dt.addClass("current");
    var currentContent = dt.next("dd").addClass("current").show();
    dl.css("height", dt.height() + currentContent.height());
  }

  function groupOf(elem) {
    var currentClasses = elem.next("dd").find("pre").attr("class").split(' ');
    var regex = new RegExp("^group-.*");
    for(var i = 0; i < currentClasses.length; i++) {
      if(regex.test(currentClasses[i])) {
        return currentClasses[i];
      }
    }
  }
});
<commit_msg>Also switch tabs which are not code snippets<commit_after>$(function() {

  // Groups (like 'java' and 'scala') represent groups of 'switchable' content, either in tabs or in regular text.
  // The catalog of groups can be defined in the sbt parameters to initialize the group.

  var groupCookie = "paradoxGroups";
  var cookieTg = getCookie(groupCookie);
  var currentGroups = {};

  var catalog = {}
  var supergroupByGroup = {};

  if(cookieTg != "")
    currentGroups = JSON.parse(cookieTg);

  // http://www.w3schools.com/js/js_cookies.asp
  function setCookie(cname,cvalue,exdays) {
    if(!exdays) exdays = 365;
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

  // http://www.w3schools.com/js/js_cookies.asp
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  $("dl").has("dd > pre").each(function() {
    var dl = $(this);
    dl.addClass("tabbed");
    var dts = dl.find("dt");
    dts.each(function(i) {
      var dt = $(this);
      dt.html("" + dt.text() + "");
    });
    var dds = dl.find("dd");
    dds.each(function(i) {
      var dd = $(this);
      dd.hide();
      if (dd.find("blockquote").length) {
        dd.addClass("has-note");
      }
    });

    // Default to the first tab, for grouped tabs switch again later
    switchToTab(dts.first());

    dts.first().addClass("first");
    dts.last().addClass("last");
  });

  $(".supergroup").each(function() {
    var supergroup = $(this).attr('name').toLowerCase();
    var groups = $(this).find(".group");

    var current = currentGroups[supergroup];
    if (!current) {
      current = "group-" + groups.first().text().toLowerCase();
      currentGroups[supergroup] = current;
    }

    catalog[supergroup] = [];

    groups.each(function() {
      var group = "group-" + $(this).text().toLowerCase();
      catalog[supergroup].push(group);
      supergroupByGroup[group] = supergroup;
    });

    switchToGroup(supergroup, current);

    $(this).on("change", function() {
      switchToGroup(supergroup, this.value);
    });
  });

  $("dl.tabbed dt a").click(function(e){
    e.preventDefault();
    var currentDt = $(this).parent("dt");
    var currentDl = currentDt.parent("dl");

    var currentGroup = groupOf(currentDt);

    var supergroup = supergroupByGroup[currentGroup]
    if (supergroup) {
      switchToGroup(supergroup, currentGroup);
    } else {
      switchToTab(currentDt);
    }
  });

  function switchToGroup(supergroup, group) {
    currentGroups[supergroup] = group;
    setCookie(groupCookie, JSON.stringify(currentGroups));

    // Dropdown switcher:
    $("select")
      .has("option[value=" + group +"]")
      .val(group);

    // Inline snippets:
    for (var i = 0; i < catalog[supergroup].length; i++) {
      var peer = catalog[supergroup][i];
      if (peer == group) {
        $("span." + group).show();
      } else {
        $("span." + peer).hide();
      }
    }

    // Tabbed snippets:
    $("dl.tabbed").each(function() {
      var dl = $(this);
      dl.find("dt").each(function() {
        var dt = $(this);
        if(groupOf(dt) == group) {
          switchToTab(dt);
        }
      });
    });
  }

  function switchToTab(dt) {
    var dl = dt.parent("dl");
    dl.find(".current").removeClass("current").next("dd").removeClass("current").hide();
    dt.addClass("current");
    var currentContent = dt.next("dd").addClass("current").show();
    dl.css("height", dt.height() + currentContent.height());
  }

  function groupOf(elem) {
    var classAttribute = elem.next("dd").find("pre").attr("class");
    if (classAttribute) {
      var currentClasses = classAttribute.split(' ');
      var regex = new RegExp("^group-.*");
      for(var i = 0; i < currentClasses.length; i++) {
        if(regex.test(currentClasses[i])) {
          return currentClasses[i];
        }
      }
    }

    // No class found? Then use the tab title
    return "group-" + elem.find('a').text().toLowerCase();
  }
});
<|endoftext|>


<commit_before>/*
 * mobile support unit tests
 */

(function( $ ) {
	$.testHelper = {
		// This function takes sets of files to load asynchronously. Each set will be loaded after
		// the previous set has completed loading. That is, each require and it's dependencies in a
		// set will be loaded asynchronously, but each set will be run in serial.
		asyncLoad: function( seq ) {
			require({
				baseUrl: "../../../js"
			});

			function loadSeq( seq, i ){
				if( !seq[i] ){
					QUnit.start();
					return;
				}

				require( seq[i], function() {
					loadSeq(seq, i + 1);
				});
			}

			// stop qunit from running the tests until everything is in the page
			QUnit.config.autostart = false;

			loadSeq( seq, 0 );
		},

		excludeFileProtocol: function(callback){
			var message = "Tests require script reload and cannot be run via file: protocol";

			if (location.protocol == "file:") {
				test(message, function(){
					ok(false, message);
				});
			} else {
				callback();
			}
		},

		// TODO prevent test suite loads when the browser doesn't support push state
		// and push-state false is defined.
		setPushStateFor: function( libs ) {
			if( $.support.pushState && location.search.indexOf( "push-state" ) >= 0 ) {
				$.support.pushState = false;
			}

			$.each(libs, function(i, l) {
				$( "<script>", { src: l }).appendTo("head");
			});
		},

		reloads: {},

		reloadLib: function(libName){
			if(this.reloads[libName] === undefined) {
				this.reloads[libName] = {
					lib: $("script[src$='" + libName + "']"),
					count: 0
				};
			}

			var lib = this.reloads[libName].lib.clone(),
				src = lib.attr('src');

			//NOTE append "cache breaker" to force reload
			lib.attr('src', src + "?" + this.reloads[libName].count++);
			$("body").append(lib);
		},

		rerunQunit: function(){
			var self = this;
			QUnit.init();
			$("script:not([src*='.\/'])").each(function(i, elem){
				var src = elem.src.split("/");
				self.reloadLib(src[src.length - 1]);
			});
			QUnit.start();
		},

		alterExtend: function(extraExtension){
			var extendFn = $.extend;

			$.extend = function(object, extension){
				// NOTE extend the object as normal
				var result = extendFn.apply(this, arguments);

				// NOTE add custom extensions
				result = extendFn(result, extraExtension);
				return result;
			};
		},

		hideActivePageWhenComplete: function() {
			if( $('#qunit-testresult').length > 0 ) {
				$('.ui-page-active').css('display', 'none');
			} else {
				setTimeout($.testHelper.hideActivePageWhenComplete, 500);
			}
		},

		openPage: function(hash){
			location.href = location.href.split('#')[0] + hash;
		},

		sequence: function(fns, interval){
			$.each(fns, function(i, fn){
				setTimeout(fn, i * interval);
			});
		},

		pageSequence: function(fns){
			this.eventSequence("pagechange", fns);
		},

		eventSequence: function(event, fns, timedOut){
			var fn = fns.shift(),
					self = this;

			if( fn === undefined ) return;

			// if a pagechange or defined event is never triggered
			// continue in the sequence to alert possible failures
			var warnTimer = setTimeout(function(){
				self.eventSequence(event, fns, true);
			}, 2000);

			// bind the recursive call to the event
			$.mobile.pageContainer.one(event, function(){
				clearTimeout(warnTimer);

				// Let the current stack unwind before we fire off the next item in the sequence.
				// TODO setTimeout(self.pageSequence, 0, [fns, event]);
				setTimeout(function(){ self.eventSequence(event, fns); }, 0);
			});

			// invoke the function which should, in some fashion,
			// trigger the defined event
			fn(timedOut);
		},

		decorate: function(opts){
			var thisVal = opts.self || window;

			return function(){
				var returnVal;
				opts.before && opts.before.apply(thisVal, arguments);
				returnVal = opts.fn.apply(thisVal, arguments);
				opts.after && opts.after.apply(thisVal, arguments);

				return returnVal;
			};
		},

		assertUrlLocation: function( args ) {
			var parts = $.mobile.path.parseUrl( location.href ),
				pathnameOnward = location.href.replace( parts.domain, "" );

			if( $.support.pushState ) {
				same( pathnameOnward, args.hashOrPush || args.push, args.report );
			} else {
				same( parts.hash, "#" + (args.hashOrPush || args.hash), args.report );
			}
		}
	};
})(jQuery);
<commit_msg>Changed reloadLib to use requirejs' context. That process being async it now returns a $.Deferred<commit_after>/*
 * mobile support unit tests
 */

(function( $ ) {
	$.testHelper = {
		// This function takes sets of files to load asynchronously. Each set will be loaded after
		// the previous set has completed loading. That is, each require and it's dependencies in a
		// set will be loaded asynchronously, but each set will be run in serial.
		asyncLoad: function( seq ) {
			require({
				baseUrl: "../../../js"
			});

			function loadSeq( seq, i ){
				if( !seq[i] ){
					QUnit.start();
					return;
				}

				require( seq[i], function() {
					loadSeq(seq, i + 1);
				});
			}

			// stop qunit from running the tests until everything is in the page
			QUnit.config.autostart = false;

			loadSeq( seq, 0 );
		},

		excludeFileProtocol: function(callback){
			var message = "Tests require script reload and cannot be run via file: protocol";

			if (location.protocol == "file:") {
				test(message, function(){
					ok(false, message);
				});
			} else {
				callback();
			}
		},

		// TODO prevent test suite loads when the browser doesn't support push state
		// and push-state false is defined.
		setPushStateFor: function( libs ) {
			if( $.support.pushState && location.search.indexOf( "push-state" ) >= 0 ) {
				$.support.pushState = false;
			}

			$.each(libs, function(i, l) {
				$( "<script>", { src: l }).appendTo("head");
			});
		},

		reloads: {},

		reloadLib: function(libName){
			var deferred = $.Deferred();
			if(this.reloads[libName] === undefined) {
				this.reloads[libName] = {
					count: 0
				};
			}

			require(
				{
					baseUrl: "../../../js",
					context: libName+"_"+this.reloads[libName].count++
				}, [libName],
				function() {
					deferred.resolve();
				}
			);

			return deferred;
		},

		rerunQunit: function(){
			var self = this;
			QUnit.init();
			$("script:not([src*='.\/'])").each(function(i, elem){
				var src = elem.src.split("/");
				self.reloadLib(src[src.length - 1]);
			});
			QUnit.start();
		},

		alterExtend: function(extraExtension){
			var extendFn = $.extend;

			$.extend = function(object, extension){
				// NOTE extend the object as normal
				var result = extendFn.apply(this, arguments);

				// NOTE add custom extensions
				result = extendFn(result, extraExtension);
				return result;
			};
		},

		hideActivePageWhenComplete: function() {
			if( $('#qunit-testresult').length > 0 ) {
				$('.ui-page-active').css('display', 'none');
			} else {
				setTimeout($.testHelper.hideActivePageWhenComplete, 500);
			}
		},

		openPage: function(hash){
			location.href = location.href.split('#')[0] + hash;
		},

		sequence: function(fns, interval){
			$.each(fns, function(i, fn){
				setTimeout(fn, i * interval);
			});
		},

		pageSequence: function(fns){
			this.eventSequence("pagechange", fns);
		},

		eventSequence: function(event, fns, timedOut){
			var fn = fns.shift(),
					self = this;

			if( fn === undefined ) return;

			// if a pagechange or defined event is never triggered
			// continue in the sequence to alert possible failures
			var warnTimer = setTimeout(function(){
				self.eventSequence(event, fns, true);
			}, 2000);

			// bind the recursive call to the event
			$.mobile.pageContainer.one(event, function(){
				clearTimeout(warnTimer);

				// Let the current stack unwind before we fire off the next item in the sequence.
				// TODO setTimeout(self.pageSequence, 0, [fns, event]);
				setTimeout(function(){ self.eventSequence(event, fns); }, 0);
			});

			// invoke the function which should, in some fashion,
			// trigger the defined event
			fn(timedOut);
		},

		decorate: function(opts){
			var thisVal = opts.self || window;

			return function(){
				var returnVal;
				opts.before && opts.before.apply(thisVal, arguments);
				returnVal = opts.fn.apply(thisVal, arguments);
				opts.after && opts.after.apply(thisVal, arguments);

				return returnVal;
			};
		},

		assertUrlLocation: function( args ) {
			var parts = $.mobile.path.parseUrl( location.href ),
				pathnameOnward = location.href.replace( parts.domain, "" );

			if( $.support.pushState ) {
				same( pathnameOnward, args.hashOrPush || args.push, args.report );
			} else {
				same( parts.hash, "#" + (args.hashOrPush || args.hash), args.report );
			}
		}
	};
})(jQuery);
<|endoftext|>


<commit_before>/**
 * jQuery plugin laquu.
 *
 * @Auth    Nully
 * @Url
 * @Make    10/04/26(Mon)
 * @Version  2.0.0
 * @License MIT Lincense
 * The MIT License
 *
 * Copyright (c) 2010 - 2013 <copyright Nully>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
(function($, _w){
    "use strict";

    var L = $.laquu = function() {
        // L.forge(this, arguments);
    };

    $.extend(L, {
        version: '2.0.0',
        device: {
            isIE: navigator.userAgent.match(/msie/),
            isAndroid: navigator.userAgent.match(/Android/),
            isAndoirdMobile: navigator.userAgent.match(/Android(.*?)Mobile/),
            isiPhone: navigator.userAgent.match(/iPhone/),
            isiPod: navigator.userAgent.match(/iPod/),
            isiPad: navigator.userAgent.match(/iPad/)
        },
        /**
         * 絶対パスへ変換する
         *
         * @param p string
         */
        toAbsPath: function(p) {
            var _ = document.createElement("span").innerHTML = '';
            return _.firstChild.href;
        },
        /**
         * 中身を展開する（デバッグ用）
         */
        dump: function() {
            if(console && console.log) {
                console.log(arguments);
            }
        },
        /**
         * 空関数
         */
        empty: function() {},
        /**
         * 例外を投げる
         * @param msg string メッセージ
         */
        error: function(msg) {
            throw msg;
        },
        /**
         * 警告文を表示する
         * @param msg string メッセージ
         */
        notice: function(msg) {
            alert(msg);
        },
        /**
         * Laquuプラグインを構築する
         */
        forge: function(fn, op) {
            L.accordion.call(this, op);
            // L.accordion.apply(this, arguments);
        },
        accordion: function(option) {
            var options = $.extend({
                selected: false,
                currentClass: "current",
                speed: 300,
                easing: "swing",
                onHide: L.empty,
                onShow: L.empty
            }, option || {}),
            $t = $(this),
            targets = $t.find("a[href^=#]"),
            panels;
            targets.each(function() {
                var $p = $($(this).attr("href")).hide();
                panels ? (panels = panels.add($p)) : panels = $p;
            }).click(function(ev){
                var hash = ev.currentTarget.hash,
                    panel = $(hash);

                if(panel.is(":visible"))
                    return ev.preventDefault();

                // クラスを除去する
                targets.removeClass(options.currentClass).filter("[href="+ hash +"]").addClass(options.currentClass).end();

                // パネルの開閉
                panels.not(hash).slideUp({
                    duration: options.speed,
                    easing: options.easing,
                    complete: $.isFunction(options.onHide) ? options.onHide: L.empty
                }).end().filter(hash).slideDown({
                    duration: options.speed,
                    easing: options.easing,
                    complete: $.isFunction(options.onShow) ? options.onShow: L.empty
                });
                ev.preventDefault();
            });

			if(options.selected != false && typeof options.selected == "number") {
				$(targets.get(options.selected)).trigger("click");
            }
            else {
				$(targets.get(0)).trigger("click");
            }
        }
    });

    /**
     * Laquuの実行
     *
     * @param fn string 実行するプラグイン名
     * @param options Object プラグインのオプション
     * @return jQuery Object
     */
    $.fn.laquu = function(fn, options) {
        L.forge.apply(this, arguments);
        return this;
    };
})(jQuery, this);

<commit_msg>コメントドキュメントを追加<commit_after>/**
 * jQuery plugin laquu.
 *
 * @Auth    Nully
 * @Url
 * @Make    10/04/26(Mon)
 * @Version  2.0.0
 * @License MIT Lincense
 * The MIT License
 *
 * Copyright (c) 2010 - 2013 <copyright Nully>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
(function($, _w){
    "use strict";

    var L = $.laquu = function() {
        // L.forge(this, arguments);
    };

    $.extend(L, {
        version: '2.0.0',
        device: {
            isIE: navigator.userAgent.match(/msie/),
            isAndroid: navigator.userAgent.match(/Android/),
            isAndoirdMobile: navigator.userAgent.match(/Android(.*?)Mobile/),
            isiPhone: navigator.userAgent.match(/iPhone/),
            isiPod: navigator.userAgent.match(/iPod/),
            isiPad: navigator.userAgent.match(/iPad/)
        },
        /**
         * 絶対パスへ変換する
         *
         * @param p string
         */
        toAbsPath: function(p) {
            var _ = document.createElement("span").innerHTML = '';
            return _.firstChild.href;
        },
        /**
         * 中身を展開する（デバッグ用）
         */
        dump: function() {
            if(console && console.log) {
                console.log(arguments);
            }
        },
        /**
         * 空関数
         */
        empty: function() {},
        /**
         * 例外を投げる
         * @param msg string メッセージ
         */
        error: function(msg) {
            throw msg;
        },
        /**
         * 警告文を表示する
         * @param msg string メッセージ
         */
        notice: function(msg) {
            alert(msg);
        },
        /**
         * Laquuプラグインを構築する
         */
        forge: function(fn, op) {
            L.accordion.call(this, op);
            // L.accordion.apply(this, arguments);
        },
        /**
         * アコーディオンプラグイン
         *
         * @param option Object
         *        selected: bool or int    洗濯済みパネル
         *        currentClass: string     洗濯済みクラス
         *        speed: int               アニメーションスピード
         *        easing: string           アニメーションのイージング
         *        onHide: function         消えた際のコールバック関数
         *        onShow: function         表示された際のコールバック関数
         */
        accordion: function(option) {
            var options = $.extend({
                selected: false,
                currentClass: "current",
                speed: 300,
                easing: "swing",
                onHide: L.empty,
                onShow: L.empty
            }, option || {}),
            $t = $(this),
            targets = $t.find("a[href^=#]"),
            panels;
            targets.each(function() {
                var $p = $($(this).attr("href")).hide();
                panels ? (panels = panels.add($p)) : panels = $p;
            }).click(function(ev){
                var hash = ev.currentTarget.hash,
                    panel = $(hash);

                if(panel.is(":visible"))
                    return ev.preventDefault();

                // クラスを除去する
                targets.removeClass(options.currentClass).filter("[href="+ hash +"]").addClass(options.currentClass).end();

                // パネルの開閉
                panels.not(hash).slideUp({
                    duration: options.speed,
                    easing: options.easing,
                    complete: $.isFunction(options.onHide) ? options.onHide: L.empty
                }).end().filter(hash).slideDown({
                    duration: options.speed,
                    easing: options.easing,
                    complete: $.isFunction(options.onShow) ? options.onShow: L.empty
                });
                ev.preventDefault();
            });

			if(options.selected != false && typeof options.selected == "number") {
				$(targets.get(options.selected)).trigger("click");
            }
            else {
				$(targets.get(0)).trigger("click");
            }
        }
    });

    /**
     * Laquuの実行
     *
     * @param fn string 実行するプラグイン名
     * @param options Object プラグインのオプション
     * @return jQuery Object
     */
    $.fn.laquu = function(fn, options) {
        L.forge.apply(this, arguments);
        return this;
    };
})(jQuery, this);

<|endoftext|>


<commit_before><commit_msg>updates<commit_after><|endoftext|>


<commit_before>'use strict';
var fx = require('./fx');
var input = require('./input');
var monster = require('./monster');
var params = require('./params');
var props = require('./props');
var player = require('./player');
var shots = require('./shots');

// All other tiles in 1-64 are solid, but these kill you.
var OUCH_TILES = [
	// Water
	41, 49, 57,
	// Lava
	23, 24, 31, 32,
];

function Level() {
	this.gStartInfo = null;
	this.gInput = null;
	this.gPlayer = null;
	this.gTiles = null;
	this.gProps = null;
	this.gMonsters = null;
	this.gShots = null;
	this.gFx = null;
	this.gUi = null;
	this.gPaused = false;
}

Level.prototype.init = function(startInfo) {
	this.gInput = input.getKeys();
	this.gStartInfo = startInfo;
	this.gPaused = false;
};

var haveCommonAssets = false;
function loadCommonAssets() {
	if (haveCommonAssets) {
		return;
	}
	haveCommonAssets = true;
	var x, s, uris, i;
	var images = PATH_MAP.images;
	for (x in images) {
		game.load.image(x, 'images/' + images[x]);
	}
	var spritesheets = PATH_MAP.spritesheets;
	for (x in spritesheets) {
		s = spritesheets[x];
		game.load.spritesheet(x, 'images/' + s.path, s.w, s.h);
	}
	var sfx = PATH_MAP.sfx;
	for (x in sfx) {
		s = sfx[x];
		uris = [];
		for (i = 0; i < s.length; i++) {
			uris.push('sfx/' + s[i]);
		}
		game.load.audio(x, uris);
	}
}

Level.prototype.preload = function() {
	loadCommonAssets();
	game.load.tilemap(
		this.gStartInfo.level,
		'levels/' + PATH_MAP.levels[this.gStartInfo.level],
		null,
		Phaser.Tilemap.TILED_JSON);
};

Level.prototype.create = function() {
	var i;

	game.renderer.renderSession.roundPixels = true;
	game.antialias = false;
	game.stage.smoothed = false;
	game.physics.startSystem(Phaser.Physics.ARCADE);

	var map = game.add.tilemap(this.gStartInfo.level);
	map.addTilesetImage('tiles', 'tiles');
	this.gTiles = map.createLayer('Main');
	this.gTiles.resizeWorld();
	var collide = [];
	for (i = 1; i <= 64; i++) {
		if (OUCH_TILES.indexOf(i) < 0) {
			collide.push(i)
		}
	}
	map.setCollision(collide, true, 'Main', true);

	var propsetIdx = map.getTilesetIndex('props');
	if (!propsetIdx) {
		console.error('No prop tileset');
		return;
	}
	var propGid = map.tilesets[propsetIdx].firstgid;

	this.gProps = new props.Props(this);
	this.gMonsters = new monster.Monsters(this);
	this.gPlayer = new player.Player(this);
	this.gShots = new shots.Shots(this);
	this.gFx = new fx.Fx(this);
	this.gUi = game.add.group();

	var playerPos = new Phaser.Point(64, 64);
	var olayer = map.objects.Default;
	if (!olayer) {
		console.log('No "Default" object layer');
		return;
	}
	for (i = 0; i < olayer.length; i++) {
		var info = olayer[i];
		if (typeof info.gid == 'number') {
			this.gProps.spawn(info.gid - propGid, info);
			continue;
		}
		if (info.type in params.MONSTERS) {
			this.gMonsters.spawn(info);
			continue;
		}
		switch (info.type) {
		case 'Player':
			playerPos.set(info.x + info.width / 2, info.y + info.height / 2);
			break;
		default:
			console.error('Unknown object type: ' + info.type);
			break;
		}
	}
	if (!this.gProps.spawnPlayerFromDoor(this.gStartInfo.prevLevel)) {
		this.gPlayer.spawn(playerPos);
	}
};

Level.prototype.spawnPlayer = function(obj) {
	this.gPlayer.spawn(obj);
};

Level.prototype.update = function() {
	input.update();
	if (!this.gPaused) {
		this.gProps.update();
		this.gPlayer.update();
		this.gMonsters.update();
		this.gShots.update();
		this.gFx.update();
	}
};

// Set whether level action is paused.
// Does not pause tweens.
Level.prototype.setPaused = function(flag) {
	flag = !!flag;
	if (flag == this.gPaused) {
		return;
	}
	game.physics.arcade.isPaused = flag;
	this.gPaused = flag;
};

// Change the current level.
Level.prototype.changeLevel = function(target) {
	this.state.restart(true, false, {
		level: target
	});
};

module.exports.Level = Level;
<commit_msg>Add missing semicolon<commit_after>'use strict';
var fx = require('./fx');
var input = require('./input');
var monster = require('./monster');
var params = require('./params');
var props = require('./props');
var player = require('./player');
var shots = require('./shots');

// All other tiles in 1-64 are solid, but these kill you.
var OUCH_TILES = [
	// Water
	41, 49, 57,
	// Lava
	23, 24, 31, 32,
];

function Level() {
	this.gStartInfo = null;
	this.gInput = null;
	this.gPlayer = null;
	this.gTiles = null;
	this.gProps = null;
	this.gMonsters = null;
	this.gShots = null;
	this.gFx = null;
	this.gUi = null;
	this.gPaused = false;
}

Level.prototype.init = function(startInfo) {
	this.gInput = input.getKeys();
	this.gStartInfo = startInfo;
	this.gPaused = false;
};

var haveCommonAssets = false;
function loadCommonAssets() {
	if (haveCommonAssets) {
		return;
	}
	haveCommonAssets = true;
	var x, s, uris, i;
	var images = PATH_MAP.images;
	for (x in images) {
		game.load.image(x, 'images/' + images[x]);
	}
	var spritesheets = PATH_MAP.spritesheets;
	for (x in spritesheets) {
		s = spritesheets[x];
		game.load.spritesheet(x, 'images/' + s.path, s.w, s.h);
	}
	var sfx = PATH_MAP.sfx;
	for (x in sfx) {
		s = sfx[x];
		uris = [];
		for (i = 0; i < s.length; i++) {
			uris.push('sfx/' + s[i]);
		}
		game.load.audio(x, uris);
	}
}

Level.prototype.preload = function() {
	loadCommonAssets();
	game.load.tilemap(
		this.gStartInfo.level,
		'levels/' + PATH_MAP.levels[this.gStartInfo.level],
		null,
		Phaser.Tilemap.TILED_JSON);
};

Level.prototype.create = function() {
	var i;

	game.renderer.renderSession.roundPixels = true;
	game.antialias = false;
	game.stage.smoothed = false;
	game.physics.startSystem(Phaser.Physics.ARCADE);

	var map = game.add.tilemap(this.gStartInfo.level);
	map.addTilesetImage('tiles', 'tiles');
	this.gTiles = map.createLayer('Main');
	this.gTiles.resizeWorld();
	var collide = [];
	for (i = 1; i <= 64; i++) {
		if (OUCH_TILES.indexOf(i) < 0) {
			collide.push(i);
		}
	}
	map.setCollision(collide, true, 'Main', true);

	var propsetIdx = map.getTilesetIndex('props');
	if (!propsetIdx) {
		console.error('No prop tileset');
		return;
	}
	var propGid = map.tilesets[propsetIdx].firstgid;

	this.gProps = new props.Props(this);
	this.gMonsters = new monster.Monsters(this);
	this.gPlayer = new player.Player(this);
	this.gShots = new shots.Shots(this);
	this.gFx = new fx.Fx(this);
	this.gUi = game.add.group();

	var playerPos = new Phaser.Point(64, 64);
	var olayer = map.objects.Default;
	if (!olayer) {
		console.log('No "Default" object layer');
		return;
	}
	for (i = 0; i < olayer.length; i++) {
		var info = olayer[i];
		if (typeof info.gid == 'number') {
			this.gProps.spawn(info.gid - propGid, info);
			continue;
		}
		if (info.type in params.MONSTERS) {
			this.gMonsters.spawn(info);
			continue;
		}
		switch (info.type) {
		case 'Player':
			playerPos.set(info.x + info.width / 2, info.y + info.height / 2);
			break;
		default:
			console.error('Unknown object type: ' + info.type);
			break;
		}
	}
	if (!this.gProps.spawnPlayerFromDoor(this.gStartInfo.prevLevel)) {
		this.gPlayer.spawn(playerPos);
	}
};

Level.prototype.spawnPlayer = function(obj) {
	this.gPlayer.spawn(obj);
};

Level.prototype.update = function() {
	input.update();
	if (!this.gPaused) {
		this.gProps.update();
		this.gPlayer.update();
		this.gMonsters.update();
		this.gShots.update();
		this.gFx.update();
	}
};

// Set whether level action is paused.
// Does not pause tweens.
Level.prototype.setPaused = function(flag) {
	flag = !!flag;
	if (flag == this.gPaused) {
		return;
	}
	game.physics.arcade.isPaused = flag;
	this.gPaused = flag;
};

// Change the current level.
Level.prototype.changeLevel = function(target) {
	this.state.restart(true, false, {
		level: target
	});
};

module.exports.Level = Level;
<|endoftext|>