<commit_before>import { createMuiTheme } from '@material-ui/core/styles';
import purple from '@material-ui/core/colors/purple';
import lightBlue from '@material-ui/core/colors/lightBlue';
import green from '@material-ui/core/colors/green';
import {styles} from '@material-ui/core/Typography/Typography';

// A custom theme for this app
const theme = createMuiTheme({
  nprogress: {
    color: '#000',
  },
  link: {
    normal: lightBlue[500],
  },
  palette: {
    primary: {
      light: purple[300],
      main: purple[500],
      dark: purple[700],
    },
    secondary: {
      light: green[300],
      main: green[500],
      dark: green[700],
    },
  },
  typography: {
    fontSize: 14,
    h1: {
      fontSize: '4rem',
    },
    h2: {
      fontSize: '3rem',
    },
    h3: {
      fontSize: '2rem',
    },
  },
});

// Note, the current version of mui export `styles` function to enrich the
// theme typography with additionnal properties like `root` and `gutterBottom`
// Things are changing in the future version of mui (branch `next`), there is
// `TypographyRoot` which we could use or the `typographyClasses` and the
// `getTypographyUtilityClass` properties.
// current: https://github.com/mui-org/material-ui/tree/ae27276980fd6f6950fc7d7ce7e19ab7215b03eb/packages/material-ui/src/Typography
// future: https://github.com/mui-org/material-ui/tree/next/packages/material-ui/src/Typography
// in the end, we dont need much, all the code below for:
// - typography.root: margin: 0
// - typography.gutterBottom: marginBottom: '0.35em'
theme.typography = {
  ...theme.typography,
  ...styles(theme),
}

export default theme;
<commit_msg>docs: add responsive header font size<commit_after>import { createMuiTheme, responsiveFontSizes } from '@material-ui/core/styles';
import purple from '@material-ui/core/colors/purple';
import lightBlue from '@material-ui/core/colors/lightBlue';
import green from '@material-ui/core/colors/green';
import {styles} from '@material-ui/core/Typography/Typography';

// A custom theme for this app
let theme = createMuiTheme({
  nprogress: {
    color: '#000',
  },
  link: {
    normal: lightBlue[500],
  },
  palette: {
    primary: {
      light: purple[300],
      main: purple[500],
      dark: purple[700],
    },
    secondary: {
      light: green[300],
      main: green[500],
      dark: green[700],
    },
  },
  typography: {
    fontSize: 14,
    h1: {
      fontSize: '4rem',
    },
    h2: {
      fontSize: '3rem',
    },
    h3: {
      fontSize: '2rem',
    },
  },
});
theme = responsiveFontSizes(theme);
// Note, the current version of mui export `styles` function to enrich the
// theme typography with additionnal properties like `root` and `gutterBottom`
// Things are changing in the future version of mui (branch `next`), there is
// `TypographyRoot` which we could use or the `typographyClasses` and the
// `getTypographyUtilityClass` properties.
// current: https://github.com/mui-org/material-ui/tree/ae27276980fd6f6950fc7d7ce7e19ab7215b03eb/packages/material-ui/src/Typography
// future: https://github.com/mui-org/material-ui/tree/next/packages/material-ui/src/Typography
// in the end, we dont need much, all the code below for:
// - typography.root: margin: 0
// - typography.gutterBottom: marginBottom: '0.35em'
theme.typography = {
  ...theme.typography,
  ...styles(theme),
}

export default theme;
<|endoftext|>


<commit_before>/**
 * @fileoverview Functions for facilitating the creation of waveforms using the
 *	accompanying waveform.html file.
 *
 * Copyright (c) 2013 Daniel P. Seemuth
 *
 * 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.
 *
 * @author Daniel P. Seemuth
 * @version 0.1.0
 **/

var PROJ_NAME = 'Waveform Editor';
var VERSION = 'v0.2.0';

var START_SIGNALS = 4;
var START_COLS = 8;

var signals = 0;
var cols = 0;
var table;

/**
 * @private
 * Create a TextNode with the given string.
 * @param {string} str Text contents for new node.
 * @return {TextNode} Node containing str.
 */
function text_(str)
{
    return document.createTextNode(str);
}

/**
 * @private
 * Generate the default contents for a new cell.
 * @param {number} rowIndex Zero-based table row index of the cell.
 * @param {number} colIndex Zero-based table col index of the cell.
 * @return {string} Text contents for the cell.
 */
function cellContents_(rowIndex, colIndex)
{
    if (rowIndex == 0) {
	/* Header row: show column index except for name column. */
	if (colIndex == 0) {
	    return ' ';
	} else {
	    return colIndex.toString();
	}

    } else if ((rowIndex % 2) == 1) {
	/* Separator row: blank cells. */
	return ' ';

    } else if (colIndex == 0) {
	/* Signal name column. */
	return 'SIG';

    }

    /* Signal data cell. */
    return Math.floor((Math.random() * 900) + 100).toString();
}

/**
 * @private
 * Set the event callbacks for a new cell.
 * @param {cell} cell Set callbacks for this cell.
 * @param {number} rowIndex Zero-based table row index of the cell.
 * @param {number} colIndex Zero-based table col index of the cell.
 */
function setCellEventCallbacks_(cell, rowIndex, colIndex)
{
    if (rowIndex == 0) {
	/* Header row. */

	if (colIndex > 0) {
	    cell.ondblclick = cell_dblclick;
	}

    } else if (((rowIndex - 1) % 2) == 1) {
	/* Signal row. */
	cell.ondblclick = cell_dblclick;
    }
}

/**
 * @private
 * Set up a new cell (contents, callbacks, style, etc.).
 * @param {cell} cell Set callbacks for this cell.
 * @param {number} rowIndex Zero-based table row index of the cell.
 * @param {number} colIndex Zero-based table col index of the cell.
 */
function setUpCell_(cell, rowIndex, colIndex)
{
    cell.innerHTML = cellContents_(rowIndex, colIndex);

    setCellEventCallbacks_(cell, rowIndex, colIndex);

    cell.style.borderRight = 'thin dotted black';
}

/**
 * @private
 * Add table row at the given row index.
 * @param {number} rowIndex Add row at this index (0 <= rowIndex <= # rows).
 */
function addRow_(rowIndex)
{
    if (rowIndex < 0) {
	throw 'rowIndex too low';
    }

    var row = table.insertRow(rowIndex);
    row.appendChild(text_('\n'));

    /* Add newline before this row. */
    table.tBodies[0].insertBefore(text_('\n'), row);

    /* Add newline after this row. */
    var nextrow = row.nextSibling;
    if (nextrow == null) {
	table.tBodies[0].appendChild(text_('\n'));
    } else {
	table.tBodies[0].insertBefore(text_('\n'), nextrow);
    }

    /* Add columns. */
    for (var c = 0; c < cols; c++) {
	addCell_(rowIndex, c);
    }
}

/**
 * @private
 * Add table cell at the given row and column indices.
 * @param {number} rowIndex Add cell in this row (0 <= rowIndex < # rows).
 * @param {number} colIndex Add cell in this col (0 <= colIndex <= # cells).
 * @return {cell} Cell that was added to the table.
 */
function addCell_(rowIndex, colIndex)
{
    if (rowIndex < 0) {
	throw 'rowIndex too low';
    }

    if (colIndex < 0) {
	throw 'colIndex too low';
    }

    var row = table.rows[rowIndex];
    var cell = row.insertCell(colIndex);

    setUpCell_(cell, rowIndex, colIndex);

    row.appendChild(text_('\n'));

    return cell;
}

/**
 * @private
 * Convert signal index to table row index.
 * @param {number} sigIndex Zero-based signal index.
 * @return {number} Zero-based table row index.
 */
function sigIndexToRowIndex_(sigIndex)
{
    if (sigIndex < 0) {
	throw 'sigIndex too low';
    }

    /* Row 0 is header row, and 2 rows per signal. */
    return 1 + (sigIndex * 2);
}

/**
 * @private
 * Convert table row index to signal index.
 * @param {number} rowIndex Zero-based table row index.
 * @return {number} Zero-based signal index.
 */
function rowIndexToSigIndex_(rowIndex)
{
    if (rowIndex < 1) {
	throw 'rowIndex too low';
    }

    /* Row 0 is header row, and 2 rows per signal. */
    return Math.floor((rowIndex - 1) / 2);
}

/**
 * @private
 * Find the column index for a cell object.
 * @param {cell} cell Cell whose index to find.
 * @return {number} Zero-based column index.
 */
function cellToColIndex_(cell)
{
    var parent_row = cell.parentNode;

    for (var i = 0; i < parent_row.cells.length; i++) {
	if (cell === parent_row.cells[i]) {
	    return i;
	}
    }
    return -1;
}

/**
 * @private
 * Find the row index for a row object.
 * @param {row} row Row whose index to find.
 * @return {number} Zero-based row index.
 */
function rowToRowIndex_(row)
{
    var parent_table = row.parentNode;

    for (var i = 0; i < parent_table.rows.length; i++) {
	if (row === parent_table.rows[i]) {
	    return i;
	}
    }
    return -1;
}

/**
 * Add signal at the given index.
 * @param {number} index Add signal at this index (negative means last).
 */
function addSignal(index)
{
    if (index < 0) {
	index = signals;
    }

    var rowIndex = sigIndexToRowIndex_(index);

    /* Add separator row and signal row. */
    for (var i = 0; i < 2; i++) {
	addRow_(rowIndex + i);
    }

    signals++;
}

/**
 * Delete the signal at the given index.
 * @param {number} index Delete signal at this index (negative means last).
 */
function delSignal(index)
{
    if (signals < 1) {
	/* No signals to delete! */
	return;
    }

    signals--;

    if (index < 0) {
	index = signals;
    }

    var rowIndex = sigIndexToRowIndex_(index);

    for (var i = 0; i < 2; i++) {
	table.deleteRow(rowIndex);
    }
}

/**
 * Add column at the given index.
 * @param {number} index Add column at this index (negative means last).
 */
function addCol(index)
{
    if (index > cols) {
	throw 'index too high';
    }

    if (index < 0) {
	index = cols;
    }

    var regenHeader = (index < cols);	/* Need to regenerate header? */

    var colIndex = index;

    for (var r = 0; r < table.rows.length; r++) {
	addCell_(r, colIndex);
    }

    cols++;

    if (regenHeader) {
	var row = table.rows[0];

	for (var c = 1; c < cols; c++) {
	    row.cells[c].innerHTML = cellContents_(0, c);
	}
    }
}

/**
 * Delete the column at the given index.
 * @param {number} index Delete column at this index (negative means last).
 */
function delCol(index)
{
    if (cols <= 1) {
	/* No non-name columns to delete! */
	return;
    }

    if (index >= cols) {
	throw 'index too high';
    }

    var regenHeader = (index < (cols - 1)); /* Need to regenerate header? */

    cols--;

    if (index < 0) {
	index = cols;
    }

    var colIndex = index;

    for (var r = 0; r < table.rows.length; r++) {
	var row = table.rows[r];

	row.deleteCell(colIndex);
    }

    if (regenHeader) {
	var row = table.rows[0];

	for (var c = 1; c < cols; c++) {
	    row.cells[c].innerHTML = cellContents_(0, c);
	}
    }
}

/**
 * Initialize the editor and waveform grid.
 */
function init()
{
    var version_paragraph = document.getElementById('version');

    version_paragraph.innerHTML = PROJ_NAME.concat(' ', VERSION);

    table = document.getElementById('wftable');

    /* Pre-populate the table. */

    if (table.tBodies.length < 1) {
	table.appendChild(document.createElement('tbody'));
    }

    for (var i = 0; i < START_COLS; i++) {
	addCol(-1);
    }

    /* Add header row. */
    addRow_(0);

    for (var i = 0; i < START_SIGNALS; i++) {
	addSignal(-1);
    }
}

/**
 * Copy the table's HTML into the I/O textarea so the user can copy/paste.
 */
function exportHTML()
{
    var io = document.getElementById('io');
    var text = table.innerHTML.trim().replace(/\n+/g, '\n');
    io.value = text;
}

/**
 * Handle double-click event on a cell.
 */
function cell_dblclick(event) {
    var cell = event.currentTarget;

    if (cell.style.backgroundColor == 'blue') {
	cell.style.backgroundColor = '';
    } else {
	cell.style.backgroundColor = 'blue';
    }
}
<commit_msg>Remove text from signal data cells<commit_after>/**
 * @fileoverview Functions for facilitating the creation of waveforms using the
 *	accompanying waveform.html file.
 *
 * Copyright (c) 2013 Daniel P. Seemuth
 *
 * 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.
 *
 * @author Daniel P. Seemuth
 * @version 0.1.0
 **/

var PROJ_NAME = 'Waveform Editor';
var VERSION = 'v0.2.0';

var START_SIGNALS = 4;
var START_COLS = 8;

var signals = 0;
var cols = 0;
var table;

/**
 * @private
 * Create a TextNode with the given string.
 * @param {string} str Text contents for new node.
 * @return {TextNode} Node containing str.
 */
function text_(str)
{
    return document.createTextNode(str);
}

/**
 * @private
 * Generate the default contents for a new cell.
 * @param {number} rowIndex Zero-based table row index of the cell.
 * @param {number} colIndex Zero-based table col index of the cell.
 * @return {string} Text contents for the cell.
 */
function cellContents_(rowIndex, colIndex)
{
    if (rowIndex == 0) {
	/* Header row: show column index except for name column. */
	if (colIndex == 0) {
	    return ' ';
	} else {
	    return colIndex.toString();
	}

    } else if ((rowIndex % 2) == 1) {
	/* Separator row: blank cells. */
	return ' ';

    } else if (colIndex == 0) {
	/* Signal name column. */
	return 'SIG';

    }

    /* Signal data cell. */
    return '&nbsp';
}

/**
 * @private
 * Set the event callbacks for a new cell.
 * @param {cell} cell Set callbacks for this cell.
 * @param {number} rowIndex Zero-based table row index of the cell.
 * @param {number} colIndex Zero-based table col index of the cell.
 */
function setCellEventCallbacks_(cell, rowIndex, colIndex)
{
    if (rowIndex == 0) {
	/* Header row. */

	if (colIndex > 0) {
	    cell.ondblclick = cell_dblclick;
	}

    } else if (((rowIndex - 1) % 2) == 1) {
	/* Signal row. */
	cell.ondblclick = cell_dblclick;
    }
}

/**
 * @private
 * Set up a new cell (contents, callbacks, style, etc.).
 * @param {cell} cell Set callbacks for this cell.
 * @param {number} rowIndex Zero-based table row index of the cell.
 * @param {number} colIndex Zero-based table col index of the cell.
 */
function setUpCell_(cell, rowIndex, colIndex)
{
    cell.innerHTML = cellContents_(rowIndex, colIndex);

    setCellEventCallbacks_(cell, rowIndex, colIndex);

    cell.style.borderRight = 'thin dotted black';
}

/**
 * @private
 * Add table row at the given row index.
 * @param {number} rowIndex Add row at this index (0 <= rowIndex <= # rows).
 */
function addRow_(rowIndex)
{
    if (rowIndex < 0) {
	throw 'rowIndex too low';
    }

    var row = table.insertRow(rowIndex);
    row.appendChild(text_('\n'));

    /* Add newline before this row. */
    table.tBodies[0].insertBefore(text_('\n'), row);

    /* Add newline after this row. */
    var nextrow = row.nextSibling;
    if (nextrow == null) {
	table.tBodies[0].appendChild(text_('\n'));
    } else {
	table.tBodies[0].insertBefore(text_('\n'), nextrow);
    }

    /* Add columns. */
    for (var c = 0; c < cols; c++) {
	addCell_(rowIndex, c);
    }
}

/**
 * @private
 * Add table cell at the given row and column indices.
 * @param {number} rowIndex Add cell in this row (0 <= rowIndex < # rows).
 * @param {number} colIndex Add cell in this col (0 <= colIndex <= # cells).
 * @return {cell} Cell that was added to the table.
 */
function addCell_(rowIndex, colIndex)
{
    if (rowIndex < 0) {
	throw 'rowIndex too low';
    }

    if (colIndex < 0) {
	throw 'colIndex too low';
    }

    var row = table.rows[rowIndex];
    var cell = row.insertCell(colIndex);

    setUpCell_(cell, rowIndex, colIndex);

    row.appendChild(text_('\n'));

    return cell;
}

/**
 * @private
 * Convert signal index to table row index.
 * @param {number} sigIndex Zero-based signal index.
 * @return {number} Zero-based table row index.
 */
function sigIndexToRowIndex_(sigIndex)
{
    if (sigIndex < 0) {
	throw 'sigIndex too low';
    }

    /* Row 0 is header row, and 2 rows per signal. */
    return 1 + (sigIndex * 2);
}

/**
 * @private
 * Convert table row index to signal index.
 * @param {number} rowIndex Zero-based table row index.
 * @return {number} Zero-based signal index.
 */
function rowIndexToSigIndex_(rowIndex)
{
    if (rowIndex < 1) {
	throw 'rowIndex too low';
    }

    /* Row 0 is header row, and 2 rows per signal. */
    return Math.floor((rowIndex - 1) / 2);
}

/**
 * @private
 * Find the column index for a cell object.
 * @param {cell} cell Cell whose index to find.
 * @return {number} Zero-based column index.
 */
function cellToColIndex_(cell)
{
    var parent_row = cell.parentNode;

    for (var i = 0; i < parent_row.cells.length; i++) {
	if (cell === parent_row.cells[i]) {
	    return i;
	}
    }
    return -1;
}

/**
 * @private
 * Find the row index for a row object.
 * @param {row} row Row whose index to find.
 * @return {number} Zero-based row index.
 */
function rowToRowIndex_(row)
{
    var parent_table = row.parentNode;

    for (var i = 0; i < parent_table.rows.length; i++) {
	if (row === parent_table.rows[i]) {
	    return i;
	}
    }
    return -1;
}

/**
 * Add signal at the given index.
 * @param {number} index Add signal at this index (negative means last).
 */
function addSignal(index)
{
    if (index < 0) {
	index = signals;
    }

    var rowIndex = sigIndexToRowIndex_(index);

    /* Add separator row and signal row. */
    for (var i = 0; i < 2; i++) {
	addRow_(rowIndex + i);
    }

    signals++;
}

/**
 * Delete the signal at the given index.
 * @param {number} index Delete signal at this index (negative means last).
 */
function delSignal(index)
{
    if (signals < 1) {
	/* No signals to delete! */
	return;
    }

    signals--;

    if (index < 0) {
	index = signals;
    }

    var rowIndex = sigIndexToRowIndex_(index);

    for (var i = 0; i < 2; i++) {
	table.deleteRow(rowIndex);
    }
}

/**
 * Add column at the given index.
 * @param {number} index Add column at this index (negative means last).
 */
function addCol(index)
{
    if (index > cols) {
	throw 'index too high';
    }

    if (index < 0) {
	index = cols;
    }

    var regenHeader = (index < cols);	/* Need to regenerate header? */

    var colIndex = index;

    for (var r = 0; r < table.rows.length; r++) {
	addCell_(r, colIndex);
    }

    cols++;

    if (regenHeader) {
	var row = table.rows[0];

	for (var c = 1; c < cols; c++) {
	    row.cells[c].innerHTML = cellContents_(0, c);
	}
    }
}

/**
 * Delete the column at the given index.
 * @param {number} index Delete column at this index (negative means last).
 */
function delCol(index)
{
    if (cols <= 1) {
	/* No non-name columns to delete! */
	return;
    }

    if (index >= cols) {
	throw 'index too high';
    }

    var regenHeader = (index < (cols - 1)); /* Need to regenerate header? */

    cols--;

    if (index < 0) {
	index = cols;
    }

    var colIndex = index;

    for (var r = 0; r < table.rows.length; r++) {
	var row = table.rows[r];

	row.deleteCell(colIndex);
    }

    if (regenHeader) {
	var row = table.rows[0];

	for (var c = 1; c < cols; c++) {
	    row.cells[c].innerHTML = cellContents_(0, c);
	}
    }
}

/**
 * Initialize the editor and waveform grid.
 */
function init()
{
    var version_paragraph = document.getElementById('version');

    version_paragraph.innerHTML = PROJ_NAME.concat(' ', VERSION);

    table = document.getElementById('wftable');

    /* Pre-populate the table. */

    if (table.tBodies.length < 1) {
	table.appendChild(document.createElement('tbody'));
    }

    for (var i = 0; i < START_COLS; i++) {
	addCol(-1);
    }

    /* Add header row. */
    addRow_(0);

    for (var i = 0; i < START_SIGNALS; i++) {
	addSignal(-1);
    }
}

/**
 * Copy the table's HTML into the I/O textarea so the user can copy/paste.
 */
function exportHTML()
{
    var io = document.getElementById('io');
    var text = table.innerHTML.trim().replace(/\n+/g, '\n');
    io.value = text;
}

/**
 * Handle double-click event on a cell.
 */
function cell_dblclick(event) {
    var cell = event.currentTarget;

    if (cell.style.backgroundColor == 'blue') {
	cell.style.backgroundColor = '';
    } else {
	cell.style.backgroundColor = 'blue';
    }
}
<|endoftext|>


<commit_before>import puppeteer from 'puppeteer';
import { toMatchImageSnapshot } from 'jest-image-snapshot';
import { logger } from '@storybook/node-logger';
import { constructUrl } from './url';

expect.extend({ toMatchImageSnapshot });

// We consider taking the full page is a reasonnable default.
const defaultScreenshotOptions = () => ({ fullPage: true });

const noop = () => {};
const asyncNoop = async () => {};

const defaultConfig = {
  storybookUrl: 'http://localhost:6006',
  chromeExecutablePath: undefined,
  getMatchOptions: noop,
  getScreenshotOptions: defaultScreenshotOptions,
  beforeScreenshot: noop,
  getGotoOptions: noop,
  customizePage: asyncNoop,
};

export const imageSnapshot = (customConfig = {}) => {
  const {
    storybookUrl,
    chromeExecutablePath,
    getMatchOptions,
    getScreenshotOptions,
    beforeScreenshot,
    getGotoOptions,
    customizePage,
  } = { ...defaultConfig, ...customConfig };
  let browser; // holds ref to browser. (ie. Chrome)
  let page; // Hold ref to the page to screenshot.

  const testFn = async ({ context }) => {
    const { kind, framework, story } = context;
    if (framework === 'rn') {
      // Skip tests since we de not support RN image snapshots.
      logger.error(
        "It seems you are running imageSnapshot on RN app and it's not supported. Skipping test."
      );

      return;
    }
    const url = constructUrl(storybookUrl, kind, story);

    if (!browser || !page) {
      logger.error(
        `Error when generating image snapshot for test ${kind} - ${story} : It seems the headless browser is not running.`
      );

      throw new Error('no-headless-browser-running');
    }

    expect.assertions(1);

    let image;
    try {
      await customizePage(page);
      await page.goto(url, getGotoOptions({ context, url }));
      await beforeScreenshot(page, { context, url });
      image = await page.screenshot(getScreenshotOptions({ context, url }));
    } catch (e) {
      logger.error(
        `Error when connecting to ${url}, did you start or build the storybook first? A storybook instance should be running or a static version should be built when using image snapshot feature.`,
        e
      );
      throw e;
    }

    expect(image).toMatchImageSnapshot(getMatchOptions({ context, url }));
  };

  testFn.afterAll = () => browser.close();

  testFn.beforeAll = async () => {
    // add some options "no-sandbox" to make it work properly on some Linux systems as proposed here: https://github.com/Googlechrome/puppeteer/issues/290#issuecomment-322851507
    browser = await puppeteer.launch({
      args: ['--no-sandbox ', '--disable-setuid-sandbox'],
      executablePath: chromeExecutablePath,
    });

    page = await browser.newPage();
  };

  return testFn;
};
<commit_msg>Allow specifying an existing browser for storyshots-puppeteer - this is useful for integrating storyshots with a headless Chrome instance running on another machine or in a Docker container.<commit_after>import puppeteer from 'puppeteer';
import { toMatchImageSnapshot } from 'jest-image-snapshot';
import { logger } from '@storybook/node-logger';
import { constructUrl } from './url';

expect.extend({ toMatchImageSnapshot });

// We consider taking the full page is a reasonnable default.
const defaultScreenshotOptions = () => ({ fullPage: true });

const noop = () => {};
const asyncNoop = async () => {};

const defaultConfig = {
  storybookUrl: 'http://localhost:6006',
  chromeExecutablePath: undefined,
  getMatchOptions: noop,
  getScreenshotOptions: defaultScreenshotOptions,
  beforeScreenshot: noop,
  getGotoOptions: noop,
  customizePage: asyncNoop,
  customBrowser: undefined,
};

export const imageSnapshot = (customConfig = {}) => {
  const {
    storybookUrl,
    chromeExecutablePath,
    getMatchOptions,
    getScreenshotOptions,
    beforeScreenshot,
    getGotoOptions,
    customizePage,
    customBrowser,
  } = { ...defaultConfig, ...customConfig };

  let browser; // holds ref to browser. (ie. Chrome)
  let page; // Hold ref to the page to screenshot.

  if (customBrowser) {
    browser = customBrowser;
  }

  const testFn = async ({ context }) => {
    const { kind, framework, story } = context;
    if (framework === 'rn') {
      // Skip tests since we de not support RN image snapshots.
      logger.error(
        "It seems you are running imageSnapshot on RN app and it's not supported. Skipping test."
      );

      return;
    }
    const url = constructUrl(storybookUrl, kind, story);

    if (!browser || !page) {
      logger.error(
        `Error when generating image snapshot for test ${kind} - ${story} : It seems the headless browser is not running.`
      );

      throw new Error('no-headless-browser-running');
    }

    expect.assertions(1);

    let image;
    try {
      await customizePage(page);
      await page.goto(url, getGotoOptions({ context, url }));
      await beforeScreenshot(page, { context, url });
      image = await page.screenshot(getScreenshotOptions({ context, url }));
    } catch (e) {
      logger.error(
        `Error when connecting to ${url}, did you start or build the storybook first? A storybook instance should be running or a static version should be built when using image snapshot feature.`,
        e
      );
      throw e;
    }

    expect(image).toMatchImageSnapshot(getMatchOptions({ context, url }));
  };

  testFn.afterAll = () => {
    if (customBrowser) {
      return page.close();
    }

    return browser.close();
  };

  testFn.beforeAll = async () => {
    if (!browser) {
      // add some options "no-sandbox" to make it work properly on some Linux systems as proposed here: https://github.com/Googlechrome/puppeteer/issues/290#issuecomment-322851507
      browser = await puppeteer.launch({
        args: ['--no-sandbox ', '--disable-setuid-sandbox'],
        executablePath: chromeExecutablePath,
      });
    }

    page = await browser.newPage();
  };

  return testFn;
};
<|endoftext|>


<commit_before>    openerp.website.if_dom_contains('.website_forum', function () {
        $("[data-toggle='popover']").popover();
        $('.karma_required').on('click', function (ev) {
            var karma = $(ev.currentTarget).data('karma');
            if (karma) {
                ev.preventDefault();
                var $warning = $('
'+
                    '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                    karma + ' karma is required to perform this action. You can earn karma by having '+
                            'your answers upvoted by the community.
');
                var vote_alert = $(ev.currentTarget).parent().find("#vote_alert");
                if (vote_alert.length == 0) {
                    $(ev.currentTarget).parent().append($warning);
                }
            }
        });

        $('.vote_up,.vote_down').not('.karma_required').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.data('href'), 'call', {})
                .then(function (data) {
                    if (data['error']){
                        if (data['error'] == 'own_post'){
                            var $warning = $('
'+
                                '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                                'Sorry, you cannot vote for your own posts'+
                                '
');
                        } else if (data['error'] == 'anonymous_user'){
                            var $warning = $('
'+
                                '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                                'Sorry you must be logged to vote'+
                                '
');
                        }
                        vote_alert = $link.parent().find("#vote_alert");
                        if (vote_alert.length == 0) {
                            $link.parent().append($warning);
                        }
                    } else {
                        $link.parent().find("#vote_count").html(data['vote_count']);
                        if (data['user_vote'] == 0) {
                            $link.parent().find(".text-success").removeClass("text-success");
                            $link.parent().find(".text-warning").removeClass("text-warning");
                        } else {
                            if (data['user_vote'] == 1) {
                                $link.addClass("text-success");
                            } else {
                                $link.addClass("text-warning");
                            }
                        }
                    }
                });
        });

        $('.accept_answer').not('.karma_required').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.data('href'), 'call', {}).then(function (data) {
                if (data['error']) {
                    if (data['error'] == 'anonymous_user') {
                        var $warning = $('
'+
                            '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                            'Sorry, anonymous users cannot choose correct answer.'+
                            '
');
                    }
                    correct_answer_alert = $link.parent().find("#correct_answer_alert");
                    if (correct_answer_alert.length == 0) {
                        $link.parent().append($warning);
                    }
                } else {
                    if (data) {
                        $link.addClass("oe_answer_true").removeClass('oe_answer_false');
                    } else {
                        $link.removeClass("oe_answer_true").addClass('oe_answer_false');
                    }
                }
            });
        });

        $('.favourite_question').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.data('href'), 'call', {}).then(function (data) {
                if (data) {
                    $link.addClass("forum_favourite_question")
                } else {
                    $link.removeClass("forum_favourite_question")
                }
            });
        });

        $('.comment_delete').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.parent('form').attr('action'), 'call', {}).then(function (data) {
                $link.parents('.comment').first().remove();
            });
        });

        $('.notification_close').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc("/forum/notification_read", 'call', {
                'notification_id': $link.attr("id")});
        });

        $('.send_validation_email').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc("/forum/send_validation_email", 'call', {
                'forum_id': $link.attr('forum-id'),
            }).then(function (data) {
                if (data) {
                    $('button.validation_email_close').click();
                }
            });
        });

        $('.validated_email_close').on('click', function (ev) {
            openerp.jsonRpc("/forum/validate_email/close", 'call', {});
        });

        $('.js_close_intro').on('click', function (ev) {
            ev.preventDefault();
            document.cookie = "no_introduction_message = false";
            return true;
        });

        $('.link_url').on('change', function (ev) {
            ev.preventDefault();
            var display_error = function(){
                var $warning = $('
'+
                    '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                    'Please enter valid URL. Example: http://www.odoo.com'+
                    '
');
                $link.parent().append($warning);
                $("button#btn_post_your_article")[0].disabled = true;
            };
            var $link = $(ev.currentTarget);
            if ($link.val().search("^http(s?)://.*")) {
                display_error();
            } else {
                openerp.jsonRpc("/forum/get_url_title", 'call', {'url': $link.val()}).then(function (data) {
                    if(data){
                        $("input[name='post_name']")[0].value = data;
                        $('button#btn_post_your_article').prop('disabled', false);
                    }else{
                        display_error();
                    }
                });
            }
        });

        $('input.js_select2').select2({
            tags: true,
            tokenSeparators: [",", " ", "_"],
            maximumInputLength: 35,
            minimumInputLength: 2,
            maximumSelectionSize: 5,
            lastsearch: [],
            createSearchChoice: function (term) {
                if ($(lastsearch).filter(function () { return this.text.localeCompare(term) === 0;}).length === 0) {
                    //check Karma
                    if (parseInt($("#karma").val()) >= parseInt($("#karma_retag").val())) {
                        return {
                            id: "_" + $.trim(term),
                            text: $.trim(term) + ' *',
                            isNew: true,
                        };
                    }
                }
            },
            formatResult: function(term) {
                if (term.isNew) {
                    return 'New ' + _.escape(term.text);
                }
                else {
                    return _.escape(term.text);
                }
            },
            ajax: {
                url: '/forum/get_tags',
                dataType: 'json',
                data: function(term, page) {
                    return {
                        q: term,
                        l: 50
                    };
                },
                results: function(data, page) {
                    var ret = [];
                    _.each(data, function(x) {
                        ret.push({ id: x.id, text: x.name, isNew: false });
                    });
                    lastsearch = ret;
                    return { results: ret };
                }
            },
            // Take default tags from the input value
            initSelection: function (element, callback) {
                var data = [];
                _.each(element.data('init-value'), function(x) {
                    data.push({ id: x.id, text: x.name, isNew: false });
                });
                element.val('');
                callback(data);
            },
        });

        $('textarea.load_editor').each(function () {
            var $textarea = $(this);
            if (!$textarea.val().match(/\S/)) {
                $textarea.val("

");
            }
            var $form = $textarea.closest('form');
            var toolbar = [
                    ['style', ['style']],
                    ['font', ['bold', 'italic', 'underline', 'clear']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']]
                ];
            if (parseInt($("#karma").val()) > 30) {
                toolbar.push(['insert', ['link', 'picture']]);
            }
            $textarea.summernote({
                    height: 150,
                    toolbar: toolbar
                });
            $form.on('click', 'button, .a-submit', function () {
                $textarea.html($form.find('.note-editable').code());
            });
        });
    });

<commit_msg>[FIX] website_forum: fixed issue when voting the vote area was not updated due to typo in JS.<commit_after>    openerp.website.if_dom_contains('.website_forum', function () {
        $("[data-toggle='popover']").popover();
        $('.karma_required').on('click', function (ev) {
            var karma = $(ev.currentTarget).data('karma');
            if (karma) {
                ev.preventDefault();
                var $warning = $('
'+
                    '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                    karma + ' karma is required to perform this action. You can earn karma by having '+
                            'your answers upvoted by the community.
');
                var vote_alert = $(ev.currentTarget).parent().find("#vote_alert");
                if (vote_alert.length == 0) {
                    $(ev.currentTarget).parent().append($warning);
                }
            }
        });

        $('.vote_up,.vote_down').not('.karma_required').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.data('href'), 'call', {})
                .then(function (data) {
                    if (data['error']){
                        if (data['error'] == 'own_post'){
                            var $warning = $('
'+
                                '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                                'Sorry, you cannot vote for your own posts'+
                                '
');
                        } else if (data['error'] == 'anonymous_user'){
                            var $warning = $('
'+
                                '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                                'Sorry you must be logged to vote'+
                                '
');
                        }
                        vote_alert = $link.parent().find("#vote_alert");
                        if (vote_alert.length == 0) {
                            $link.parent().append($warning);
                        }
                    } else {
                        $link.parent().find(".vote_count").html(data['vote_count']);
                        if (data['user_vote'] == 0) {
                            $link.parent().find(".text-success").removeClass("text-success");
                            $link.parent().find(".text-warning").removeClass("text-warning");
                        } else {
                            if (data['user_vote'] == 1) {
                                $link.addClass("text-success");
                            } else {
                                $link.addClass("text-warning");
                            }
                        }
                    }
                });
        });

        $('.accept_answer').not('.karma_required').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.data('href'), 'call', {}).then(function (data) {
                if (data['error']) {
                    if (data['error'] == 'anonymous_user') {
                        var $warning = $('
'+
                            '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                            'Sorry, anonymous users cannot choose correct answer.'+
                            '
');
                    }
                    correct_answer_alert = $link.parent().find("#correct_answer_alert");
                    if (correct_answer_alert.length == 0) {
                        $link.parent().append($warning);
                    }
                } else {
                    if (data) {
                        $link.addClass("oe_answer_true").removeClass('oe_answer_false');
                    } else {
                        $link.removeClass("oe_answer_true").addClass('oe_answer_false');
                    }
                }
            });
        });

        $('.favourite_question').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.data('href'), 'call', {}).then(function (data) {
                if (data) {
                    $link.addClass("forum_favourite_question")
                } else {
                    $link.removeClass("forum_favourite_question")
                }
            });
        });

        $('.comment_delete').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc($link.parent('form').attr('action'), 'call', {}).then(function (data) {
                $link.parents('.comment').first().remove();
            });
        });

        $('.notification_close').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc("/forum/notification_read", 'call', {
                'notification_id': $link.attr("id")});
        });

        $('.send_validation_email').on('click', function (ev) {
            ev.preventDefault();
            var $link = $(ev.currentTarget);
            openerp.jsonRpc("/forum/send_validation_email", 'call', {
                'forum_id': $link.attr('forum-id'),
            }).then(function (data) {
                if (data) {
                    $('button.validation_email_close').click();
                }
            });
        });

        $('.validated_email_close').on('click', function (ev) {
            openerp.jsonRpc("/forum/validate_email/close", 'call', {});
        });

        $('.js_close_intro').on('click', function (ev) {
            ev.preventDefault();
            document.cookie = "no_introduction_message = false";
            return true;
        });

        $('.link_url').on('change', function (ev) {
            ev.preventDefault();
            var display_error = function(){
                var $warning = $('
'+
                    '<button type="button" class="close notification_close" data-dismiss="alert" aria-hidden="true">×</button>'+
                    'Please enter valid URL. Example: http://www.odoo.com'+
                    '
');
                $link.parent().append($warning);
                $("button#btn_post_your_article")[0].disabled = true;
            };
            var $link = $(ev.currentTarget);
            if ($link.val().search("^http(s?)://.*")) {
                display_error();
            } else {
                openerp.jsonRpc("/forum/get_url_title", 'call', {'url': $link.val()}).then(function (data) {
                    if(data){
                        $("input[name='post_name']")[0].value = data;
                        $('button#btn_post_your_article').prop('disabled', false);
                    }else{
                        display_error();
                    }
                });
            }
        });

        $('input.js_select2').select2({
            tags: true,
            tokenSeparators: [",", " ", "_"],
            maximumInputLength: 35,
            minimumInputLength: 2,
            maximumSelectionSize: 5,
            lastsearch: [],
            createSearchChoice: function (term) {
                if ($(lastsearch).filter(function () { return this.text.localeCompare(term) === 0;}).length === 0) {
                    //check Karma
                    if (parseInt($("#karma").val()) >= parseInt($("#karma_retag").val())) {
                        return {
                            id: "_" + $.trim(term),
                            text: $.trim(term) + ' *',
                            isNew: true,
                        };
                    }
                }
            },
            formatResult: function(term) {
                if (term.isNew) {
                    return 'New ' + _.escape(term.text);
                }
                else {
                    return _.escape(term.text);
                }
            },
            ajax: {
                url: '/forum/get_tags',
                dataType: 'json',
                data: function(term, page) {
                    return {
                        q: term,
                        l: 50
                    };
                },
                results: function(data, page) {
                    var ret = [];
                    _.each(data, function(x) {
                        ret.push({ id: x.id, text: x.name, isNew: false });
                    });
                    lastsearch = ret;
                    return { results: ret };
                }
            },
            // Take default tags from the input value
            initSelection: function (element, callback) {
                var data = [];
                _.each(element.data('init-value'), function(x) {
                    data.push({ id: x.id, text: x.name, isNew: false });
                });
                element.val('');
                callback(data);
            },
        });

        $('textarea.load_editor').each(function () {
            var $textarea = $(this);
            if (!$textarea.val().match(/\S/)) {
                $textarea.val("

");
            }
            var $form = $textarea.closest('form');
            var toolbar = [
                    ['style', ['style']],
                    ['font', ['bold', 'italic', 'underline', 'clear']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']]
                ];
            if (parseInt($("#karma").val()) > 30) {
                toolbar.push(['insert', ['link', 'picture']]);
            }
            $textarea.summernote({
                    height: 150,
                    toolbar: toolbar
                });
            $form.on('click', 'button, .a-submit', function () {
                $textarea.html($form.find('.note-editable').code());
            });
        });
    });

<|endoftext|>


<commit_before>/*globals jQuery, FA, _userdata*/

/**
 * Botões de moderação para o SCEditor.
 *
 * @author lffg <https://github.com/lffg>
 * @version 1.0
 */

(function ($) {
  'use strict';

  var buttons = [
    {
      name      : 'Tópico Bloqueado',
      id        : 'topic-block-button',
      text      : 'Olá, o tópico foi bloqueado... [...]',
      topics    : ['*'],
      img       : 'https://i.imgur.com/z5lPhgz.png',
      onlyForMod: true
    }, {
      name        : 'Lista de Ações',
      id          : 'topic-actions-list',
      topics      : ['*'],
      img         : 'https://i.imgur.com/oAGWDdG.png',
      inGroup     : false,
      onlyForAdmin: false,
      children    : [
        { name: 'Ação 1', text: 'Texto da ação 1.', icon: 'fa fa-cog' },
        { name: 'Ação 2', text: 'Texto da ação 2.', icon: 'fa fa-cog' },
        { name: 'Ação 3', text: 'Texto da ação 3.', icon: 'fa fa-cog' }
      ]
    }
  ];

  window.FA = window.FA || {};
  FA.Topic = FA.Topic || {};

  var ModButtons;
  FA.Topic.ModButtons = ModButtons = function (userConfig) {
    var self = this;

    self.userConfig = userConfig;
    self.defaults = {
      name        : undefined,
      id          : '',
      inGroup     : true,
      topics      : ['*'],
      text        : '',
      children    : false,
      img         : undefined,
      onlyForMod  : false,
      onlyForAdmin: false
    };

    self.config = $.extend({}, self.defaults, self.userConfig);

    $.each(self.config, function (key, value) {
      if (key === undefined) {
        throw new Error ('Não foi especificado um: ' + key + ' para o script de botões de moderação.');
      }

      if (value === undefined) {
        throw new Error ('Não foi especificado um valor: ' + value + ' para o script de botões de moderação.');
      }
    });

    self.createStyles();
  };

  ModButtons.prototype.init = function () {
    var self = this;

    if (self.config.onlyForMod && (_userdata.user_level !== 1 && _userdata.user_level !== 2)) {
      return false;
    }

    if (self.config.onlyForAdmin && _userdata.user_level !== 1) {
      return false;
    }

    if (self.config.topics.indexOf('*') === -1) {
      var topicId = parseInt(location.href.replace(/.*\/t(\d+).*|.*\/post\?t=(\d+)&.*/gi, function (string, match1, match2) {
        if (match1 === undefined) {
          return match2;
        }

        return match1;
      }));

      if (self.config.topics.indexOf(topicId) === -1) {
        return false;
      }
    }

    if (Array.isArray(self.config.children) && self.config.children.length >= 1) {
      self.createButton(true);
    } else {
      self.createButton(false);
    }
  };

  /**
   * @param {boolean} isDrop Se for true, significa que o botão tem filhos.
   *                         Caso contrário, o botão não tem filhos.
   */
  ModButtons.prototype.createButton = function (isDrop) {
    var self = this;

    if (!$.sceditor) {
      return false;
    }

    self.$group = $('.sceditor-group:last');
    self.$element = $('<a>', {
      'class'       : 'sceditor-button',
      'unselectable': 'on',
      'title'       : self.config.name,
      'data-id'     : self.config.id,
      'html'        : $('<div>', { 'unselectable': 'on' }).css('background-image', 'url(' + self.config.img + ')').prop('outerHTML')
    });

    switch (isDrop) {
      case true:
        self.$element.attr('data-dropdown', 'true');

        self.createChildren();
        self.documentListen();

        self.$element.on('click', function (event) {
          event.preventDefault();
          event.stopPropagation();

          var $this = $(this);

          var offset = $this.offset();
          var height = $this.height();

          self.$dropdown
            .css('position', 'absolute')
            .css('top', offset.top + height)
            .css('left', offset.left)
            .toggle()
          ;
        });

        break;

      case false:
        self.$element
          .attr('data-dropdown', 'false')
            .attr('data-text', self.config.text)
              .on('click', function (event) {
                self.insertText($(this), event);
              })
        ;

        break;
    }

    if (self.config.inGroup) {
      self.$group.append(self.$element);

      return;
    }

    $('<div>', { 'class': 'sceditor-group' })
      .insertBefore(self.$group)
        .append(self.$element)
    ;
  };

  ModButtons.prototype.createChildren = function () {
    var self = this;

    self.$dropdown = $('<div>', { 'class': 'sceditor-dropdown fa-mod-buttons-prototype-dropdown' });

    $.each(self.config.children, function (index, child) {
      $('<a>', {
        'data-text': child.text,
        'title'    : child.name,
        'html'     : [
          $('<i>', { 'class': child.icon }).prop('outerHTML'),
          $('<span>', { 'text': child.name }).prop('outerHTML')
        ].join('\n')
      })
        .appendTo(self.$dropdown)
          .on('click', function (event) {
            self.insertText($(this), event);

            self.$dropdown.hide();
          })
      ;
    });

    self.$dropdown
      .hide()
        .appendTo('body')
    ;
  };

  /**
   * @param {string} text - Corresponde ao texto que será inserido no editor.
   */
  ModButtons.prototype.insertText = function (context, contextEvent) {
    contextEvent.preventDefault();
    contextEvent.stopPropagation();

    var $this = $(context);

    var $textarea = $('#text_editor_textarea');
    var $sceditor = $textarea.sceditor('instance');

    $sceditor.insertText($this.attr('data-text'));
  };

  ModButtons.prototype.documentListen = function () {
    var self = this;

    self.$dropdown.on('click', function (event) {
      event.stopPropagation();
    });

    $(document).on('click', function (event) {
      self.$dropdown.hide();
    });
  };

  ModButtons.prototype.createStyles = function () {
    $('<style>', {
      'text': [
        '.fa-mod-buttons-prototype-dropdown {',
        '  padding: 0px !important;',
        '  margin-top: 5px !important;',
        '  min-width: 120px;',
        '  max-height: 200px;',
        '  overflow-y: auto;',
        '}',
        '',
        '.fa-mod-buttons-prototype-dropdown > a {',
        '  display: block;',
        '  padding: 8px 10px;',
        '  border-bottom: solid 1px #ddd;',
        '  font-size: 10px;',
        '  cursor: pointer;',
        '}',
        '',
        '.fa-mod-buttons-prototype-dropdown > a:last-child {',
        '  border-bottom: none;',
        '}',
        '',
        '.fa-mod-buttons-prototype-dropdown > a > i {',
        '  font-size: 12px;',
        '  vertical-align: middle;',
        '}'
      ].join('\n')
    }).appendTo('head');
  };

  $(function () {
    $.each(buttons, function () {
      var self = this;

      (new FA.Topic.ModButtons(self)).init();
    });
  });
}(jQuery));
<commit_msg>Correção.<commit_after>/*globals jQuery, FA, _userdata*/

/**
 * Botões de moderação para o SCEditor.
 *
 * @author lffg <https://github.com/lffg>
 * @version 1.0
 */

(function ($) {
  'use strict';

  var buttons = [
    {
      name      : 'Tópico Bloqueado',
      id        : 'topic-block-button',
      text      : 'Olá, o tópico foi bloqueado... [...]',
      topics    : ['*'],
      img       : 'https://i.imgur.com/z5lPhgz.png',
      onlyForMod: true
    }, {
      name        : 'Lista de Ações',
      id          : 'topic-actions-list',
      topics      : ['*'],
      img         : 'https://i.imgur.com/oAGWDdG.png',
      inGroup     : false,
      onlyForAdmin: false,
      children    : [
        { name: 'Ação 1', text: 'Texto da ação 1.', icon: 'fa fa-cog' },
        { name: 'Ação 2', text: 'Texto da ação 2.', icon: 'fa fa-cog' },
        { name: 'Ação 3', text: 'Texto da ação 3.', icon: 'fa fa-cog' }
      ]
    }
  ];

  window.FA = window.FA || {};
  FA.Topic = FA.Topic || {};

  var ModButtons;
  FA.Topic.ModButtons = ModButtons = function (userConfig) {
    var self = this;

    self.userConfig = userConfig;
    self.defaults = {
      name        : undefined,
      id          : '',
      inGroup     : true,
      topics      : ['*'],
      text        : '',
      children    : false,
      img         : undefined,
      onlyForMod  : false,
      onlyForAdmin: false
    };

    self.config = $.extend({}, self.defaults, self.userConfig);

    $.each(self.config, function (key, value) {
      if (key === undefined) {
        throw new Error ('Não foi especificado um: ' + key + ' para o script de botões de moderação.');
      }

      if (value === undefined) {
        throw new Error ('Não foi especificado um valor: ' + value + ' para o script de botões de moderação.');
      }
    });

    self.createStyles();
  };

  ModButtons.prototype.init = function () {
    var self = this;

    if (self.config.onlyForMod && (_userdata.user_level !== 1 && _userdata.user_level !== 2)) {
      return false;
    }

    if (self.config.onlyForAdmin && _userdata.user_level !== 1) {
      return false;
    }

    if (self.config.topics.indexOf('*') === -1) {
      var topicId = parseInt(location.href.replace(/.*\/t(\d+).*|.*\/post\?t=(\d+)&.*/gi, function (string, match1, match2) {
        if (match1 === undefined) {
          return match2;
        }

        return match1;
      }));

      if (self.config.topics.indexOf(topicId) === -1) {
        return false;
      }
    }

    if (Array.isArray(self.config.children) && self.config.children.length >= 1) {
      self.createButton(true);
    } else {
      self.createButton(false);
    }
  };

  /**
   * @param {boolean} isDrop Se for true, significa que o botão tem filhos.
   *                         Caso contrário, o botão não tem filhos.
   */
  ModButtons.prototype.createButton = function (isDrop) {
    var self = this;

    if (!$.sceditor) {
      return false;
    }

    self.$group = $('.sceditor-group:last');
    self.$element = $('<a>', {
      'class'       : 'sceditor-button',
      'unselectable': 'on',
      'title'       : self.config.name,
      'data-id'     : self.config.id,
      'html'        : $('<div>', { 'unselectable': 'on' }).css('background-image', 'url(' + self.config.img + ')').prop('outerHTML')
    });

    switch (isDrop) {
      case true:
        self.$element.attr('data-dropdown', 'true');

        self.createChildren();
        self.documentListen();

        self.$element.on('click', function (event) {
          event.preventDefault();
          event.stopPropagation();

          var $this = $(this);

          var offset = $this.offset();
          var height = $this.height();

          self.$dropdown
            .css('position', 'absolute')
            .css('top', offset.top + height)
            .css('left', offset.left)
            .toggle()
          ;
        });

        break;

      case false:
        self.$element
          .attr('data-dropdown', 'false')
            .attr('data-text', self.config.text)
              .on('click', function (event) {
                self.insertText($(this), event);
              })
        ;

        break;
    }

    if (self.config.inGroup) {
      self.$group.append(self.$element);

      return;
    }

    $('<div>', { 'class': 'sceditor-group' })
      .insertBefore(self.$group)
        .append(self.$element)
    ;
  };

  ModButtons.prototype.createChildren = function () {
    var self = this;

    self.$dropdown = $('<div>', { 'class': 'sceditor-dropdown fa-mod-buttons-prototype-dropdown' });

    $.each(self.config.children, function (index, child) {
      $('<a>', {
        'data-text': child.text,
        'title'    : child.name,
        'html'     : [
          $('<i>', { 'class': child.icon }).prop('outerHTML'),
          $('<span>', { 'text': child.name }).prop('outerHTML')
        ].join('\n')
      })
        .appendTo(self.$dropdown)
          .on('click', function (event) {
            self.insertText($(this), event);

            self.$dropdown.hide();
          })
      ;
    });

    self.$dropdown
      .hide()
        .appendTo('body')
    ;
  };

  /**
   * @param {string} text - Corresponde ao texto que será inserido no editor.
   */
  ModButtons.prototype.insertText = function (context, contextEvent) {
    contextEvent.preventDefault();
    contextEvent.stopPropagation();

    var $this = $(context);

    var $textarea = $('#text_editor_textarea');
    var $sceditor = $textarea.sceditor('instance');

    $sceditor.insertText($this.attr('data-text'));
  };

  ModButtons.prototype.documentListen = function () {
    var self = this;

    self.$dropdown.on('click', function (event) {
      event.stopPropagation();
    });

    $(document).on('click', function (event) {
      self.$dropdown.hide();
    });
  };

  ModButtons.prototype.createStyles = function () {
    $('<style>', {
      'text': [
        '.fa-mod-buttons-prototype-dropdown {',
        '  padding: 0px !important;',
        '  margin-top: 5px !important;',
        '  min-width: 120px;',
        '  max-height: 200px;',
        '  overflow-y: auto;',
        '}',
        '',
        '.fa-mod-buttons-prototype-dropdown > a {',
        '  display: block;',
        '  padding: 8px 10px;',
        '  border-bottom: solid 1px #ddd;',
        '  font-size: 10px;',
        '  cursor: pointer;',
        '}',
        '',
        '.fa-mod-buttons-prototype-dropdown > a:last-child {',
        '  border-bottom: none;',
        '}',
        '',
        '.fa-mod-buttons-prototype-dropdown > a > i {',
        '  font-size: 12px;',
        '  vertical-align: middle;',
        '}'
      ].join('\n')
    }).appendTo('head');
  };

  $(window).on('load', function () {
    $.each(buttons, function () {
      var self = this;

      (new FA.Topic.ModButtons(self)).init();
    });
  });
}(jQuery));
<|endoftext|>


<commit_before>// whatever javascript files you place in this iFEF `folder will be concatenated to a single file in the js library

function test(arg){
	var output = arg || 'fire';
	console.log(output);
}

function delayReload(){
	setTimeout(function(){
		location.reload(true);
	},1000);
}

// Backbone.emulateJSON = true;

var AV = {};

AV.routes = Backbone.Router.extend({

	routes: {
		'': 'index',
	},

	initialize:function(){
		test('init');
		this.post = new AV.post();
		this.get = new AV.get();
		this.sources = new AV.sources();
		this.put = new AV.put();
		this.delete = new AV.delete();
		this.transform = new AV.transform();
		this.witness = new AV.witness();
		this.witnesses = new AV.witnesses();
		this.collection = new Backbone.Collection([
			this.post,
			this.get,
			this.sources,
			this.put,
			this.delete,
			this.transform,
			this.witness,
			this.witnesses
			]);
		this.testerView = new AV.testerView({collection: this.collection});
	},

	index: function() {
		this.testerView.render();
	},

});

AV.testerView = Backbone.View.extend({

	el: '#verb-tests',
	initialize: function(){},
	events: {
		"click button#post" : 'post',
		"click button#get" : 'get',
		"click button#get-srcs" : 'getSRCS',
		"click button#put" : 'put',
		"click button#delete" : 'delete',
		"click button#transform" : 'transform',
		"click button#get-witness" : 'getWTNS',
		"click button#get-witness" : 'getWTNSlist'
	},
	render:function(){
		this.$el.html(
			'
'
			+ '
<button class="btn btn-success" id="post">post</button>
'
			+ '
<button class="btn btn-primary" id="get">get source</button>
'
			+ '
<button class="btn btn-primary" id="get-srcs">get sources</button>
'
			+ '
<button class="btn btn-warning" id="put">put</button>
'
			+ '
<button class="btn btn-danger" id="delete">delete</button>
'
			+ '
<button class="btn btn-success" id="transform">transform</button>
'
			+ '
<button class="btn btn-default" id="get-witness">get witness</button>
'
			+ '
<button class="btn btn-default" id="get-witnesses">get witnesses</button>
'
			+ '
');
		this.$el.find('ul li').css( {'list-style' : 'none', 'margin-bottom' : '5px' });
	},
	post:function(){

		test('post');
		this.collection.models[0].url = '/juxta/source';
		this.collection.models[0].save({

		name: 'post issue debug',
			type: 'raw',
			contentType: 'txt',
			data: 'some test what what'
		},
	{ 	success: function(e){ test('success'); },
	}	);
//		delayReload();
	},

	get:function(){test('get');
		this.collection.models[1].set({id : this.collection.models[1].id + '.json' })
		this.collection.models[1].fetch({
			success:function() { test('success');},
			error:function() { test('not so much');}
		});
	//	delayReload();
	},

	getSRCS:function(){test('get-srcs');
		test('get-ws');
		this.collection.models[2].fetch({
			success: function(e){ test('success'); },
			error: function(e){ test('error'); }
		});
	//	delayReload();
	},

	put:function(){test('put');

		this.collection.models[3].save(
			{
			id: '152',
			name: 'successful put',
			data: 'putted it really I did'
			}
		);

		//delayReload();
	},

	delete:function(){test('delete');
		this.collection.models[4].set({id : 23});
		this.collection.models[4].destroy();

		// delayReload();
	},

	transform: function(){
		test('transform');
		this.collection.models[5].save({

			source: 56,
			finalName: 'new witness'

		});
	},

	getWTNS: function(){
		test('get witnesses');
		this.collection.models[6].fetch({
			success: function(a,b,c) {
				$('#log').append(JSON.stringify(b));
			}
		});
	},

	getWTNSlist: function(){
		test('get witnesses');
		this.collection.models[7].fetch();
	}
});
AV.post = Backbone.Model.extend({
	url: '/juxta/source',
	sync: function(a,b,c){
		b.attributes = [b.attributes];
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.get = Backbone.Model.extend({
	url: '/juxta/source/152.json'

	defaults:{
		name: '',
		type: 'raw',
		contentType: 'txt',
		data: ''
	}
});

AV.get = Backbone.Model.extend({
	url: '/juxta/source/13.json'
});

AV.sources = Backbone.Model.extend({
	url: '/juxta/source.json'
});

AV.put = Backbone.Model.extend({
	urlRoot: '/juxta/source/152',
	defaults:{
		name: '',
		type: 'raw',
		contentType: 'txt',
		data: ''
	},
	sync: function(a,b,c){
		test(c);
		b.attributes = [b.attributes];
		c.emulateJSON = true;
		c.contentType = false;
		c.processData = false;
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.delete = Backbone.Model.extend({
	urlRoot: '/juxta/source',
	defaults:{ id: 8 }
	});

AV.transform = Backbone.Model.extend({

	url: '/juxta/transform',
	defaults: {
		source: '',
		finalName: ''
	}
});

AV.witness = Backbone.Model.extend({
	url: '/juxta/witness/56.json'
});

AV.witnesses = Backbone.Model.extend({
	url: '/juxta/witness.json'
});

var readysetgo = new AV.routes();

$(function(){
  Backbone.history.start();
});
<commit_msg>av_test.js<commit_after>// whatever javascript files you place in this iFEF `folder will be concatenated to a single file in the js library

function test(arg){
	var output = arg || 'fire';
	console.log(output);
}

function delayReload(){
	setTimeout(function(){
		location.reload(true);
	},1000);
}

// Backbone.emulateJSON = true;

var AV = {};

AV.routes = Backbone.Router.extend({

	routes: {
		'': 'index',
	},

	initialize:function(){
		test('init');
		this.post = new AV.post();
		this.get = new AV.get();
		this.sources = new AV.sources();
		this.put = new AV.put();
		this.delete = new AV.delete();
		this.transform = new AV.transform();
		this.witness = new AV.witness();
		this.witnesses = new AV.witnesses();
		this.collection = new Backbone.Collection([
			this.post,
			this.get,
			this.sources,
			this.put,
			this.delete,
			this.transform,
			this.witness,
			this.witnesses
			]);
		this.testerView = new AV.testerView({collection: this.collection});
	},

	index: function() {
		this.testerView.render();
	},

});

AV.testerView = Backbone.View.extend({

	el: '#verb-tests',
	initialize: function(){},
	events: {
		"click button#post" : 'post',
		"click button#get" : 'get',
		"click button#get-srcs" : 'getSRCS',
		"click button#put" : 'put',
		"click button#delete" : 'delete',
		"click button#transform" : 'transform',
		"click button#get-witness" : 'getWTNS',
		"click button#get-witnesses" : 'getWTNSlist'
	},
	render:function(){
		this.$el.html(
			'
'
			+ '
<button class="btn btn-success" id="post">post</button>
'
			+ '
<button class="btn btn-primary" id="get">get source</button>
'
			+ '
<button class="btn btn-primary" id="get-srcs">get sources</button>
'
			+ '
<button class="btn btn-warning" id="put">put</button>
'
			+ '
<button class="btn btn-danger" id="delete">delete</button>
'
			+ '
<button class="btn btn-success" id="transform">transform</button>
'
			+ '
<button class="btn btn-default" id="get-witness">get witness</button>
'
			+ '
<button class="btn btn-default" id="get-witnesses">get witnesses</button>
'
			+ '
');
		this.$el.find('ul li').css( {'list-style' : 'none', 'margin-bottom' : '5px' });
	},
	post:function(){

		test('post');
		this.collection.models[0].url = '/juxta/source';
		this.collection.models[0].save({

		name: 'post issue debug',
			type: 'raw',
			contentType: 'txt',
			data: 'some test what what'
		},
	{ 	success: function(e){ test('success'); },
	}	);
//		delayReload();
	},

	get:function(){test('get');
		this.collection.models[1].set({id : this.collection.models[1].id + '.json' })
		this.collection.models[1].fetch({
			success:function() { test('success');},
			error:function() { test('not so much');}
		});
	//	delayReload();
	},

	getSRCS:function(){test('get-srcs');
		test('get-ws');
		this.collection.models[2].fetch({
			success: function(e){ test('success'); },
			error: function(e){ test('error'); }
		});
	//	delayReload();
	},

	put:function(){test('put');

		this.collection.models[3].save(
			{
			id: '152',
			name: 'successful put',
			data: 'putted it really I did'
			}
		);

		//delayReload();
	},

	delete:function(){test('delete');
		this.collection.models[4].set({id : 23});
		this.collection.models[4].destroy();

		// delayReload();
	},

	transform: function(){
		test('transform');
		this.collection.models[5].save({

			source: 255,
			finalName: 'new witness'

		});
	},

	getWTNS: function(){
		test('get witness');
		this.collection.models[6].fetch({
			success: function(a,b,c) {
				$('#log').append(JSON.stringify(b));
			}
		});
	},

	getWTNSlist: function(){
		test('get witnesses');
		this.collection.models[7].fetch();
	}
});
AV.post = Backbone.Model.extend({
	url: '/juxta/source',
	sync: function(a,b,c){
		b.attributes = [b.attributes];
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.get = Backbone.Model.extend({
	url: '/juxta/source/13.json'
});

AV.sources = Backbone.Model.extend({
	url: '/juxta/source.json'
});

AV.put = Backbone.Model.extend({
	urlRoot: '/juxta/source/152',
	defaults:{
		name: '',
		type: 'raw',
		contentType: 'txt',
		data: ''
	},
	sync: function(a,b,c){
		test(c);
		b.attributes = [b.attributes];
		c.emulateJSON = true;
		c.contentType = false;
		c.processData = false;
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.delete = Backbone.Model.extend({
	urlRoot: '/juxta/source',
	defaults:{ id: 8 }
	});

AV.transform = Backbone.Model.extend({

	url: '/juxta/transform',
	defaults: {
		source: '',
		finalName: ''
	}
});

AV.witness = Backbone.Model.extend({
	url: '/juxta/witness/11'
});

AV.witnesses = Backbone.Model.extend({
	url: '/juxta/witness.json'
});

var readysetgo = new AV.routes();

$(function(){
  Backbone.history.start();
});
<|endoftext|>


<commit_before>(function () {
    var themes = ["red", "blue", "yellow", "green"];
    var randThemeName = themes[(Math.floor(Math.random() * themes.length))];

    document.getElementById("container").className += " theme-" + randThemeName;
}());
<commit_msg>Convert js code to es2015<commit_after>(function () {
    let themes = ["red", "blue", "yellow", "green"];
    let randThemeName = themes[(Math.floor(Math.random() * themes.length))];

    document.getElementById("container").className = "theme-" + randThemeName;
}());
<|endoftext|>


<commit_before>// whatever javascript files you place in this iFEF `folder will be concatenated to a single file in the js library

function test(arg){
	var output = arg || 'fire';
	console.log(output);
}

function delayReload(){
	setTimeout(function(){
		location.reload(true);
	},1000);
}

// Backbone.emulateJSON = true;

var AV = {};

AV.routes = Backbone.Router.extend({

	routes: {
		'': 'index',
	},

	initialize:function(){
		test('init');
		this.post = new AV.post();
		this.get = new AV.get();
		this.sources = new AV.sources();
		this.put = new AV.put();
		this.delete = new AV.delete();
		this.transform = new AV.transform();
		this.witness = new AV.witness();
		this.witnesses = new AV.witnesses();
		this.set = new AV.set();
		this.collection = new Backbone.Collection([
			this.post,
			this.get,
			this.sources,
			this.put,
			this.delete,
			this.transform,
			this.witness,
			this.witnesses,
			this.set
			]);
		this.testerView = new AV.testerView({collection: this.collection});
	},

	index: function() {
		this.testerView.render();
	},

});

AV.testerView = Backbone.View.extend({

	el: '#verb-tests',
	initialize: function(){},
	events: {
		"click button#post" : 'post',
		"click button#get" : 'get',
		"click button#get-srcs" : 'getSRCS',
		"click button#put" : 'put',
		"click button#delete" : 'delete',
		"click button#transform" : 'transform',
		"click button#get-witness" : 'getWTNS',
		"click button#get-witnesses" : 'getWTNSlist',
		"click button#delete-witness" : 'deleteWitness',
		"click button#create-set" : 'createSet'
	},
	render:function(){
		this.$el.html(
			'
'
			+ '
<button class="btn btn-success" id="post">post</button>
'
			+ '
<button class="btn btn-primary" id="get">get source</button>
'
			+ '
<button class="btn btn-primary" id="get-srcs">get sources</button>
'
			+ '
<button class="btn btn-warning" id="put">put</button>
'
			+ '
<button class="btn btn-danger" id="delete">delete</button>
'
			+ '
<button class="btn btn-success" id="transform">transform</button>
'
			+ '
<button class="btn btn-default" id="get-witness">get witness</button>
'
			+ '
<button class="btn btn-default" id="get-witnesses">get witnesses</button>
'
			+ '
<button class="btn btn-default" id="delete-witness">delete witness</button>
'
			+ '
<button class="btn btn-default" id="create-set">create set</button>
'
			+ '
');
		this.$el.find('ul li').css( {'list-style' : 'none', 'margin-bottom' : '5px' });
	},
	post:function(){

		test('post');
		this.collection.models[0].url = '/juxta/source';
		this.collection.models[0].save({

		name: 'post issue debug',
			type: 'raw',
			contentType: 'txt',
			data: 'some test what what'
		},
	{ 	success: function(e){ test('success'); },
	}	);
//		delayReload();
	},

	get:function(){test('get');
		this.collection.models[1].set({id : this.collection.models[1].id + '.json' })
		this.collection.models[1].fetch({
			success:function() { test('success');},
			error:function() { test('not so much');}
		});
	//	delayReload();
	},

	getSRCS:function(){test('get-srcs');
		test('get-ws');
		this.collection.models[2].fetch({
			success: function(e){ test('success'); },
			error: function(e){ test('error'); }
		});
	//	delayReload();
	},

	put:function(){test('put');

		this.collection.models[3].save(
			{
			id: '152',
			name: 'successful put',
			data: 'putted it really I did'
			}
		);

		//delayReload();
	},

	delete:function(){test('delete');
		this.collection.models[4].set({id : 23});
		this.collection.models[4].destroy();

		// delayReload();
	},

	transform: function(){
		test('transform');
		this.collection.models[5].save({

			source: 295,
			finalName: 'aefae witness'

		});
	},

	getWTNS: function(){
		test('get witness');
		this.collection.models[6].set({ id : 11 });
		this.collection.models[6].fetch({
			success: function(a,b,c) {
				$('#log').append(JSON.stringify(b));
			}
		});
	},

	getWTNSlist: function(){
		test('get witnesses');
		this.collection.models[7].fetch();
	},

	deleteWitness: function(){

		test('delete witness')
		this.collection.models[6].set({ id : 11 });
		this.collection.models[6].destroy({

			success: function(a,b,c) {
			$('#log').append(JSON.stringify(b));
			}

		});
	},

	createSet: function(){
		test('create set');
		this.collection.models[8].save({
				name: 'test set',
				witnesses: [12,13,14]
			},
			{
			success: function(a,b,c) {
				$('#log').append(JSON.stringify(b));
			}
		});
	},

});
AV.post = Backbone.Model.extend({
	url: '/juxta/source',
	sync: function(a,b,c){
		b.attributes = [b.attributes];
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.get = Backbone.Model.extend({
	url: '/juxta/source/13.json'
});

AV.sources = Backbone.Model.extend({
	url: '/juxta/source.json'
});

AV.put = Backbone.Model.extend({
	urlRoot: '/juxta/source/152',
	defaults:{
		name: '',
		type: 'raw',
		contentType: 'txt',
		data: ''
	},
	sync: function(a,b,c){
		test(c);
		b.attributes = [b.attributes];
		c.emulateJSON = true;
		c.contentType = false;
		c.processData = false;
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.delete = Backbone.Model.extend({
	urlRoot: '/juxta/source',
	defaults:{ id: 8 }
	});

AV.transform = Backbone.Model.extend({

	url: '/juxta/transform',
	defaults: {
		source: '',
		finalName: ''
	}
});

AV.witness = Backbone.Model.extend({
	urlRoot: '/juxta/witness'
});

AV.witnesses = Backbone.Model.extend({
	url: '/juxta/witness.json'
});

AV.set = Backbone.Model.extend({
	url: '/juxta/set',
	defaults: {
		name: '',
		witnesses: []
	}
});

var readysetgo = new AV.routes();

$(function(){
  Backbone.history.start();
});
<commit_msg>debug create set test<commit_after>// whatever javascript files you place in this iFEF `folder will be concatenated to a single file in the js library

function test(arg){
	var output = arg || 'fire';
	console.log(output);
}

function delayReload(){
	setTimeout(function(){
		location.reload(true);
	},1000);
}

// Backbone.emulateJSON = true;

var AV = {};

AV.routes = Backbone.Router.extend({

	routes: {
		'': 'index',
	},

	initialize:function(){
		test('init');
		this.post = new AV.post();
		this.get = new AV.get();
		this.sources = new AV.sources();
		this.put = new AV.put();
		this.delete = new AV.delete();
		this.transform = new AV.transform();
		this.witness = new AV.witness();
		this.witnesses = new AV.witnesses();
		this.set = new AV.set();
		this.collate = new AV.collate();
		this.collection = new Backbone.Collection([
			this.post,
			this.get,
			this.sources,
			this.put,
			this.delete,
			this.transform,
			this.witness,
			this.witnesses,
			this.set,
			this.collate
			]);
		this.testerView = new AV.testerView({collection: this.collection});
	},

	index: function() {
		this.testerView.render();
	},

});

AV.testerView = Backbone.View.extend({

	el: '#verb-tests',
	initialize: function(){},
	events: {
		"click button#post" : 'post',
		"click button#get" : 'get',
		"click button#get-srcs" : 'getSRCS',
		"click button#put" : 'put',
		"click button#delete" : 'delete',
		"click button#transform" : 'transform',
		"click button#get-witness" : 'getWTNS',
		"click button#get-witnesses" : 'getWTNSlist',
		"click button#delete-witness" : 'deleteWitness',
		"click button#create-set" : 'createSet',
		"click button#collate-set" : 'collateSet'
	},
	render:function(){
		this.$el.html(
			'
'
			+ '
<button class="btn btn-success" id="post">post</button>
'
			+ '
<button class="btn btn-primary" id="get">get source</button>
'
			+ '
<button class="btn btn-primary" id="get-srcs">get sources</button>
'
			+ '
<button class="btn btn-warning" id="put">put</button>
'
			+ '
<button class="btn btn-danger" id="delete">delete</button>
'
			+ '
<button class="btn btn-success" id="transform">transform</button>
'
			+ '
<button class="btn btn-default" id="get-witness">get witness</button>
'
			+ '
<button class="btn btn-default" id="get-witnesses">get witnesses</button>
'
			+ '
<button class="btn btn-default" id="delete-witness">delete witness</button>
'
			+ '
<button class="btn btn-default" id="create-set">create set</button>
',
			+ '
<button class="btn btn-default" id="collate-set">collate set</button>
'
			+ '
');
		this.$el.find('ul li').css( {'list-style' : 'none', 'margin-bottom' : '5px' });
	},
	post:function(){

		test('post');
		this.collection.models[0].url = '/juxta/source';
		this.collection.models[0].save({

		name: 'post issue debug',
			type: 'raw',
			contentType: 'txt',
			data: 'some test what what'
		},
	{ 	success: function(e){ test('success'); },
	}	);
//		delayReload();
	},

	get:function(){test('get');
		this.collection.models[1].set({id : this.collection.models[1].id + '.json' })
		this.collection.models[1].fetch({
			success:function() { test('success');},
			error:function() { test('not so much');}
		});
	//	delayReload();
	},

	getSRCS:function(){test('get-srcs');
		test('get-ws');
		this.collection.models[2].fetch({
			success: function(e){ test('success'); },
			error: function(e){ test('error'); }
		});
	//	delayReload();
	},

	put:function(){test('put');

		this.collection.models[3].save(
			{
			id: '152',
			name: 'successful put',
			data: 'putted it really I did'
			}
		);

		//delayReload();
	},

	delete:function(){test('delete');
		this.collection.models[4].set({id : 23});
		this.collection.models[4].destroy();

		// delayReload();
	},

	transform: function(){
		test('transform');
		this.collection.models[5].save({

			source: 295,
			finalName: 'aefae witness'

		});
	},

	getWTNS: function(){
		test('get witness');
		this.collection.models[6].set({ id : 11 });
		this.collection.models[6].fetch({
			success: function(a,b,c) {
				$('#log').append(JSON.stringify(b));
			}
		});
	},

	getWTNSlist: function(){
		test('get witnesses');
		this.collection.models[7].fetch();
	},

	deleteWitness: function(){

		test('delete witness')
		this.collection.models[6].set({ id : 11 });
		this.collection.models[6].destroy({

			success: function(a,b,c) {
			$('#log').append(JSON.stringify(b));
			}

		});
	},

	createSet: function(){
		test('create set');
		this.collection.models[8].save({
				name: 'test set',
				witnesses: [12,13,14]
			},
			{
			success: function(a,b,c) {
				$('#log').append(JSON.stringify(b));
			}
		});
	},

	collateSet: function(){
		test('collate set');
	},

});
AV.post = Backbone.Model.extend({
	url: '/juxta/source',
	sync: function(a,b,c){
		b.attributes = [b.attributes];
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.get = Backbone.Model.extend({
	url: '/juxta/source/13.json'
});

AV.sources = Backbone.Model.extend({
	url: '/juxta/source.json'
});

AV.put = Backbone.Model.extend({
	urlRoot: '/juxta/source/152',
	defaults:{
		name: '',
		type: 'raw',
		contentType: 'txt',
		data: ''
	},
	sync: function(a,b,c){
		test(c);
		b.attributes = [b.attributes];
		c.emulateJSON = true;
		c.contentType = false;
		c.processData = false;
		return Backbone.sync.apply(this, [a,b,c]);
	}
});

AV.delete = Backbone.Model.extend({
	urlRoot: '/juxta/source',
	defaults:{ id: 8 }
	});

AV.transform = Backbone.Model.extend({

	url: '/juxta/transform',
	defaults: {
		source: '',
		finalName: ''
	}
});

AV.witness = Backbone.Model.extend({
	urlRoot: '/juxta/witness'
});

AV.witnesses = Backbone.Model.extend({
	url: '/juxta/witness.json'
});

AV.set = Backbone.Model.extend({
	url: '/juxta/set',
	defaults: {
		name: '',
		witnesses: []
	}
});

var readysetgo = new AV.routes();

$(function(){
  Backbone.history.start();
});
<|endoftext|>