<commit_before>// -*- mode: java; c-basic-offset: 2; -*-
// Copyright © 2013-2016 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
/**
 * @license
 * @fileoverview Flydown is an abstract class for a flyout-like dropdown containing blocks.
 *   Unlike a regular flyout, for simplicity it does not support scrolling.
 *   Any non-abstract subclass must provide a flydownBlocksXML_ () method that returns an
 *   XML element whose children are blocks that should appear in the flyout.
 * @author fturbak@wellesley.edu (Lyn Turbak)
 */
'use strict';

goog.provide('AI.Blockly.Flydown');

goog.require('Blockly.Flyout');
goog.require('Blockly.Block');
goog.require('Blockly.Comment');

/**
 * Class for a flydown.
 * @constructor
 */
Blockly.Flydown = function(workspaceOptions) {
  Blockly.Flydown.superClass_.constructor.call(this, workspaceOptions);
  this.dragAngleRange_ = 360;
};
goog.inherits(Blockly.Flydown, Blockly.Flyout);

/**
 * Previous CSS class for this flydown
 * @type {number}
 * @const
 */
Blockly.Flydown.prototype.previousCSSClassName_ = '';

/**
 * Override flyout factor to be smaller for flydowns
 * @type {number}
 * @const
 */
Blockly.Flydown.prototype.VERTICAL_SEPARATION_FACTOR = 1;

/**
 * Creates the flydown's DOM.  Only needs to be called once.  Overrides the flyout createDom method.
 * @param {!String} cssClassName The name of the CSS class for this flydown.
 * @return {!Element} The flydown's SVG group.
 */
Blockly.Flydown.prototype.createDom = function(cssClassName) {
  /*
  <g>
    <path class={cssClassName}/>
    <g></g>
  </g>
  */
  this.previousCSSClassName_ = cssClassName; // Remember class name for later
  this.svgGroup_ = Blockly.utils.createSvgElement('g', {'class': cssClassName}, null);
  this.svgBackground_ = Blockly.utils.createSvgElement('path', {}, this.svgGroup_);
  this.svgGroup_.appendChild(this.workspace_.createDom());
  return this.svgGroup_;
};

/**
 * Set the CSS class of the flydown SVG group. Need to remove previous class if there is one.
 * @param {!String} newCSSClassName The name of the new CSS class replacing the old one
 */
Blockly.Flydown.prototype.setCSSClass = function(newCSSClassName) {
  if (newCSSClassName !== this.previousCSSClassName_) {
    Blockly.utils.removeClass(this.svgGroup_, this.previousCSSClassName_);
    Blockly.utils.addClass(this.svgGroup_, newCSSClassName);
    this.previousCSSClassName_ = newCSSClassName;
  }
}

/**
 * Initializes the Flydown.
 * @param {!Blockly.Workspace} workspace The workspace in which to create new
 *     blocks.
 */
Blockly.Flydown.prototype.init = function(workspace) {
  Blockly.Flyout.prototype.init.call(this, workspace, false); // Flydowns have no scrollbar
}

/**
 * Override the flyout position method to do nothing instead
 * @private
 */
Blockly.Flydown.prototype.position = function() {
  return;
}

/**
 * Show and populate the flydown.
 * @param {!Array|string} xmlList List of blocks to show.
 * @param {!num} x x-position of upper-left corner of flydown
 * @param {!num} y y-position of upper-left corner of flydown
 */
Blockly.Flydown.prototype.showAt = function(xmlList,x,y) {
  Blockly.Events.disable();
  try {
    this.show(xmlList); // invoke flyout method, which adds blocks to flydown and calculates width and height.
  } finally {
    Blockly.Events.enable();
  }
  // this.svgGroup_.setAttribute('transform', 'translate(' + x + ',' + y + ')');
  // Calculate path around flydown blocks. Based on code in flyout position_ method.

  // Start at bottom of top left arc and proceed clockwise
  // Flydown outline shape is symmetric about vertical axis, so no need to differentiate LTR and RTL paths.
  var margin = this.CORNER_RADIUS * this.workspace_.scale;
  var edgeWidth = this.width_ - 2*margin;
  var edgeHeight = this.height_ - 2*margin;
  var path = ['M 0,' + margin];
  path.push('a', margin, margin, 0, 0, 1, margin, -margin); // upper left arc
  path.push('h', edgeWidth);  // top edge
  path.push('a', margin, margin, 0, 0, 1, margin, margin); // upper right arc
  path.push('v', edgeHeight); // right edge
  path.push('a', margin, margin, 0, 0, 1, -margin, margin); // bottom right arc
  path.push('h', -edgeWidth); // bottom edge, drawn backwards
  path.push('a', margin, margin, 0, 0, 1, -margin, -margin); // bottom left arc
  path.push('z'); // complete path by drawing left edge
  this.svgBackground_.setAttribute('d', path.join(' '));
  this.svgGroup_.setAttribute('transform', 'translate(' + x + ', ' + y + ')');
}

/**
 * Compute width and height of Flydown.  Position button under each block.
 * Overrides the reflow method of flyout
 * For RTL: Lay out the blocks right-aligned.
 */
Blockly.Flydown.prototype.reflow = function() {
  this.workspace_.scale = this.targetWorkspace_.scale;
  var scale = this.workspace_.scale;
  var flydownWidth = 0;
  var flydownHeight = 0;
  var margin = this.CORNER_RADIUS * scale;
  var blocks = this.workspace_.getTopBlocks(false);
  for (var i = 0, block; block = blocks[i]; i++) {
    var root = block.getSvgRoot();
    var blockHW = block.getHeightWidth();
    flydownWidth = Math.max(flydownWidth, blockHW.width * scale);
    flydownHeight += blockHW.height * scale;
  }
  flydownWidth += 2*margin + Blockly.BlockSvg.TAB_WIDTH * scale; // TAB_WIDTH is with of plug
  flydownHeight += 2*margin + margin*this.VERTICAL_SEPARATION_FACTOR*(blocks.length - 1) + Blockly.BlockSvg.START_HAT_HEIGHT*scale/2.0;
  if (this.width_ != flydownWidth) {
    for (var j = 0, block; block = blocks[j]; j++) {
      var blockHW = block.getHeightWidth();
      var blockXY = block.getRelativeToSurfaceXY();
      if (this.RTL) {
        // With the FlydownWidth known, right-align the blocks.
        var dx = flydownWidth - margin - scale * (Blockly.BlockSvg.TAB_WIDTH - blockXY.x);
        block.moveBy(dx, 0);
        blockXY.x += dx;
      }
      if (block.flyoutRect_) {
        block.flyoutRect_.setAttribute('width', blockHW.width);
        block.flyoutRect_.setAttribute('height', blockHW.height);
        block.flyoutRect_.setAttribute('x',
            this.RTL ? blockXY.x - blockHW.width : blockXY.x);
        block.flyoutRect_.setAttribute('y', blockXY.y);
      }
    }
    // Record the width for us in showAt method
    this.width_ = flydownWidth;
    this.height_ = flydownHeight;
  }
};

Blockly.Flydown.prototype.onMouseMove_ = function(e) {
  // override Blockly's flyout behavior for moving the flyout.
  return;
};

/**
 * Copy a block from the flyout to the workspace and position it correctly.
 * @param {!Blockly.Block} originBlock The flyout block to copy..
 * @return {!Blockly.Block} The new block in the main workspace.
 * @private
 */
Blockly.Flydown.prototype.placeNewBlock_ = function(originBlock) {
  var targetWorkspace = this.targetWorkspace_;
  var svgRootOld = originBlock.getSvgRoot();
  if (!svgRootOld) {
    throw 'originBlock is not rendered.';
  }
  // Figure out where the original block is on the screen, relative to the upper
  // left corner of the main workspace.
  var scale = this.workspace_.scale;
  var margin = this.CORNER_RADIUS * scale;
  var xyOld = this.workspace_.getSvgXY(svgRootOld);
  //var scrollX = this.svgGroup_.getScreenCTM().e + margin;
  var scrollX = xyOld.x;
  xyOld.x += scrollX / targetWorkspace.scale - scrollX;
  //var scrollY = this.svgGroup_.getScreenCTM().f + margin;
  var scrollY = xyOld.y;
  scale = targetWorkspace.scale;
  xyOld.y += scrollY / scale - scrollY;

  // Create the new block by cloning the block in the flyout (via XML).
  var xml = Blockly.Xml.blockToDom(originBlock);
  var block = Blockly.Xml.domToBlock(xml, targetWorkspace);
  var svgRootNew = block.getSvgRoot();
  if (!svgRootNew) {
    throw 'block is not rendered.';
  }
  // Figure out where the new block got placed on the screen, relative to the
  // upper left corner of the workspace.  This may not be the same as the
  // original block because the flyout's origin may not be the same as the
  // main workspace's origin.
  var xyNew = targetWorkspace.getSvgXY(svgRootNew);
  // Scale the scroll (getSvgXY did not do this).
  xyNew.x +=
      targetWorkspace.scrollX / targetWorkspace.scale - targetWorkspace.scrollX;
  xyNew.y +=
      targetWorkspace.scrollY / targetWorkspace.scale - targetWorkspace.scrollY;
  // If the flyout is collapsible and the workspace can't be scrolled.
  if (targetWorkspace.toolbox_ && !targetWorkspace.scrollbar) {
    xyNew.x += targetWorkspace.toolbox_.getWidth() / targetWorkspace.scale;
    xyNew.y += targetWorkspace.toolbox_.getHeight() / targetWorkspace.scale;
  }

  // Move the new block to where the old block is.
  block.moveBy(xyOld.x - xyNew.x, xyOld.y - xyNew.y);
  return block;
};

Blockly.Flydown.prototype.shouldHide = true;

Blockly.Flydown.prototype.hide = function() {
  if (this.shouldHide) {
    Blockly.Flyout.prototype.hide.call(this);
    Blockly.FieldDropdown.openFieldFlydown_ = null;
  }
  this.shouldHide = true;
}

// Note: nothing additional beyond flyout disposal needs to be done to dispose of a flydown.
<commit_msg>Fix wrong reference to FieldFlydown (was FieldDropdown)<commit_after>// -*- mode: java; c-basic-offset: 2; -*-
// Copyright © 2013-2016 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
/**
 * @license
 * @fileoverview Flydown is an abstract class for a flyout-like dropdown containing blocks.
 *   Unlike a regular flyout, for simplicity it does not support scrolling.
 *   Any non-abstract subclass must provide a flydownBlocksXML_ () method that returns an
 *   XML element whose children are blocks that should appear in the flyout.
 * @author fturbak@wellesley.edu (Lyn Turbak)
 */
'use strict';

goog.provide('AI.Blockly.Flydown');

goog.require('Blockly.Flyout');
goog.require('Blockly.Block');
goog.require('Blockly.Comment');

/**
 * Class for a flydown.
 * @constructor
 */
Blockly.Flydown = function(workspaceOptions) {
  Blockly.Flydown.superClass_.constructor.call(this, workspaceOptions);
  this.dragAngleRange_ = 360;
};
goog.inherits(Blockly.Flydown, Blockly.Flyout);

/**
 * Previous CSS class for this flydown
 * @type {number}
 * @const
 */
Blockly.Flydown.prototype.previousCSSClassName_ = '';

/**
 * Override flyout factor to be smaller for flydowns
 * @type {number}
 * @const
 */
Blockly.Flydown.prototype.VERTICAL_SEPARATION_FACTOR = 1;

/**
 * Creates the flydown's DOM.  Only needs to be called once.  Overrides the flyout createDom method.
 * @param {!String} cssClassName The name of the CSS class for this flydown.
 * @return {!Element} The flydown's SVG group.
 */
Blockly.Flydown.prototype.createDom = function(cssClassName) {
  /*
  <g>
    <path class={cssClassName}/>
    <g></g>
  </g>
  */
  this.previousCSSClassName_ = cssClassName; // Remember class name for later
  this.svgGroup_ = Blockly.utils.createSvgElement('g', {'class': cssClassName}, null);
  this.svgBackground_ = Blockly.utils.createSvgElement('path', {}, this.svgGroup_);
  this.svgGroup_.appendChild(this.workspace_.createDom());
  return this.svgGroup_;
};

/**
 * Set the CSS class of the flydown SVG group. Need to remove previous class if there is one.
 * @param {!String} newCSSClassName The name of the new CSS class replacing the old one
 */
Blockly.Flydown.prototype.setCSSClass = function(newCSSClassName) {
  if (newCSSClassName !== this.previousCSSClassName_) {
    Blockly.utils.removeClass(this.svgGroup_, this.previousCSSClassName_);
    Blockly.utils.addClass(this.svgGroup_, newCSSClassName);
    this.previousCSSClassName_ = newCSSClassName;
  }
}

/**
 * Initializes the Flydown.
 * @param {!Blockly.Workspace} workspace The workspace in which to create new
 *     blocks.
 */
Blockly.Flydown.prototype.init = function(workspace) {
  Blockly.Flyout.prototype.init.call(this, workspace, false); // Flydowns have no scrollbar
}

/**
 * Override the flyout position method to do nothing instead
 * @private
 */
Blockly.Flydown.prototype.position = function() {
  return;
}

/**
 * Show and populate the flydown.
 * @param {!Array|string} xmlList List of blocks to show.
 * @param {!num} x x-position of upper-left corner of flydown
 * @param {!num} y y-position of upper-left corner of flydown
 */
Blockly.Flydown.prototype.showAt = function(xmlList,x,y) {
  Blockly.Events.disable();
  try {
    this.show(xmlList); // invoke flyout method, which adds blocks to flydown and calculates width and height.
  } finally {
    Blockly.Events.enable();
  }
  // this.svgGroup_.setAttribute('transform', 'translate(' + x + ',' + y + ')');
  // Calculate path around flydown blocks. Based on code in flyout position_ method.

  // Start at bottom of top left arc and proceed clockwise
  // Flydown outline shape is symmetric about vertical axis, so no need to differentiate LTR and RTL paths.
  var margin = this.CORNER_RADIUS * this.workspace_.scale;
  var edgeWidth = this.width_ - 2*margin;
  var edgeHeight = this.height_ - 2*margin;
  var path = ['M 0,' + margin];
  path.push('a', margin, margin, 0, 0, 1, margin, -margin); // upper left arc
  path.push('h', edgeWidth);  // top edge
  path.push('a', margin, margin, 0, 0, 1, margin, margin); // upper right arc
  path.push('v', edgeHeight); // right edge
  path.push('a', margin, margin, 0, 0, 1, -margin, margin); // bottom right arc
  path.push('h', -edgeWidth); // bottom edge, drawn backwards
  path.push('a', margin, margin, 0, 0, 1, -margin, -margin); // bottom left arc
  path.push('z'); // complete path by drawing left edge
  this.svgBackground_.setAttribute('d', path.join(' '));
  this.svgGroup_.setAttribute('transform', 'translate(' + x + ', ' + y + ')');
}

/**
 * Compute width and height of Flydown.  Position button under each block.
 * Overrides the reflow method of flyout
 * For RTL: Lay out the blocks right-aligned.
 */
Blockly.Flydown.prototype.reflow = function() {
  this.workspace_.scale = this.targetWorkspace_.scale;
  var scale = this.workspace_.scale;
  var flydownWidth = 0;
  var flydownHeight = 0;
  var margin = this.CORNER_RADIUS * scale;
  var blocks = this.workspace_.getTopBlocks(false);
  for (var i = 0, block; block = blocks[i]; i++) {
    var root = block.getSvgRoot();
    var blockHW = block.getHeightWidth();
    flydownWidth = Math.max(flydownWidth, blockHW.width * scale);
    flydownHeight += blockHW.height * scale;
  }
  flydownWidth += 2*margin + Blockly.BlockSvg.TAB_WIDTH * scale; // TAB_WIDTH is with of plug
  flydownHeight += 2*margin + margin*this.VERTICAL_SEPARATION_FACTOR*(blocks.length - 1) + Blockly.BlockSvg.START_HAT_HEIGHT*scale/2.0;
  if (this.width_ != flydownWidth) {
    for (var j = 0, block; block = blocks[j]; j++) {
      var blockHW = block.getHeightWidth();
      var blockXY = block.getRelativeToSurfaceXY();
      if (this.RTL) {
        // With the FlydownWidth known, right-align the blocks.
        var dx = flydownWidth - margin - scale * (Blockly.BlockSvg.TAB_WIDTH - blockXY.x);
        block.moveBy(dx, 0);
        blockXY.x += dx;
      }
      if (block.flyoutRect_) {
        block.flyoutRect_.setAttribute('width', blockHW.width);
        block.flyoutRect_.setAttribute('height', blockHW.height);
        block.flyoutRect_.setAttribute('x',
            this.RTL ? blockXY.x - blockHW.width : blockXY.x);
        block.flyoutRect_.setAttribute('y', blockXY.y);
      }
    }
    // Record the width for us in showAt method
    this.width_ = flydownWidth;
    this.height_ = flydownHeight;
  }
};

Blockly.Flydown.prototype.onMouseMove_ = function(e) {
  // override Blockly's flyout behavior for moving the flyout.
  return;
};

/**
 * Copy a block from the flyout to the workspace and position it correctly.
 * @param {!Blockly.Block} originBlock The flyout block to copy..
 * @return {!Blockly.Block} The new block in the main workspace.
 * @private
 */
Blockly.Flydown.prototype.placeNewBlock_ = function(originBlock) {
  var targetWorkspace = this.targetWorkspace_;
  var svgRootOld = originBlock.getSvgRoot();
  if (!svgRootOld) {
    throw 'originBlock is not rendered.';
  }
  // Figure out where the original block is on the screen, relative to the upper
  // left corner of the main workspace.
  var scale = this.workspace_.scale;
  var margin = this.CORNER_RADIUS * scale;
  var xyOld = this.workspace_.getSvgXY(svgRootOld);
  //var scrollX = this.svgGroup_.getScreenCTM().e + margin;
  var scrollX = xyOld.x;
  xyOld.x += scrollX / targetWorkspace.scale - scrollX;
  //var scrollY = this.svgGroup_.getScreenCTM().f + margin;
  var scrollY = xyOld.y;
  scale = targetWorkspace.scale;
  xyOld.y += scrollY / scale - scrollY;

  // Create the new block by cloning the block in the flyout (via XML).
  var xml = Blockly.Xml.blockToDom(originBlock);
  var block = Blockly.Xml.domToBlock(xml, targetWorkspace);
  var svgRootNew = block.getSvgRoot();
  if (!svgRootNew) {
    throw 'block is not rendered.';
  }
  // Figure out where the new block got placed on the screen, relative to the
  // upper left corner of the workspace.  This may not be the same as the
  // original block because the flyout's origin may not be the same as the
  // main workspace's origin.
  var xyNew = targetWorkspace.getSvgXY(svgRootNew);
  // Scale the scroll (getSvgXY did not do this).
  xyNew.x +=
      targetWorkspace.scrollX / targetWorkspace.scale - targetWorkspace.scrollX;
  xyNew.y +=
      targetWorkspace.scrollY / targetWorkspace.scale - targetWorkspace.scrollY;
  // If the flyout is collapsible and the workspace can't be scrolled.
  if (targetWorkspace.toolbox_ && !targetWorkspace.scrollbar) {
    xyNew.x += targetWorkspace.toolbox_.getWidth() / targetWorkspace.scale;
    xyNew.y += targetWorkspace.toolbox_.getHeight() / targetWorkspace.scale;
  }

  // Move the new block to where the old block is.
  block.moveBy(xyOld.x - xyNew.x, xyOld.y - xyNew.y);
  return block;
};

Blockly.Flydown.prototype.shouldHide = true;

Blockly.Flydown.prototype.hide = function() {
  if (this.shouldHide) {
    Blockly.Flyout.prototype.hide.call(this);
    Blockly.FieldFlydown.openFieldFlydown_ = null;
  }
  this.shouldHide = true;
}

// Note: nothing additional beyond flyout disposal needs to be done to dispose of a flydown.
<|endoftext|>


<commit_before>import * as Preact from '#preact';
import {BentoIframe} from '../component';

export default {
  title: 'Iframe',
  component: BentoIframe,
};

export const _default = () => {
  return (
    <BentoIframe
      style={{width: 800, height: 600}}
      iframeStyle={{border: '1px solid black'}}
      src="https://www.wikipedia.org/"
      title="Wikipedia"
    ></BentoIframe>
  );
};

export const WithIntersectingIframe = () => {
  return (

      <BentoIframe
        style={{width: 100, height: 100}}
        iframeStyle={{border: '1px solid black'}}
        sandbox="allow-scripts allow-same-origin"
        resizable
        src="/examples/bento/amp-iframe-resizing-example.html"
      >

Placeholder

      </BentoIframe>

The above iframe will not resize and should remain 100x100px

  );
};

WithIntersectingIframe.storyName = 'Resizable iframe in viewport';

export const WithResizableIframe = () => {
  return (

      <BentoIframe
        style={{width: 100, height: 100}}
        iframeStyle={{border: '1px solid black'}}
        sandbox="allow-scripts allow-same-origin"
        resizable
        src="/examples/bento/amp-iframe-resizing-example.html"
      >

Placeholder

      </BentoIframe>

The above iframe should be 300x300px when visible

  );
};

WithResizableIframe.storyName = 'Resizable iframe outside viewport';

export const WithSendIntersectionsPostMessage = () => {
  return (

Placeholder

  );
};

WithSendIntersectionsPostMessage.storyName = 'Send intersections';
<commit_msg>storybook: Iframe --> BentoIframe (#37327)<commit_after>import * as Preact from '#preact';
import {BentoIframe} from '../component';

export default {
  title: 'Iframe',
  component: BentoIframe,
};

export const _default = () => {
  return (
    <BentoIframe
      style={{width: 800, height: 600}}
      iframeStyle={{border: '1px solid black'}}
      src="https://www.wikipedia.org/"
      title="Wikipedia"
    ></BentoIframe>
  );
};

export const WithIntersectingIframe = () => {
  return (

      <BentoIframe
        style={{width: 100, height: 100}}
        iframeStyle={{border: '1px solid black'}}
        sandbox="allow-scripts allow-same-origin"
        resizable
        src="/examples/bento/amp-iframe-resizing-example.html"
      >

Placeholder

      </BentoIframe>

The above iframe will not resize and should remain 100x100px

  );
};

WithIntersectingIframe.storyName = 'Resizable iframe in viewport';

export const WithResizableIframe = () => {
  return (

      <BentoIframe
        style={{width: 100, height: 100}}
        iframeStyle={{border: '1px solid black'}}
        sandbox="allow-scripts allow-same-origin"
        resizable
        src="/examples/bento/amp-iframe-resizing-example.html"
      >

Placeholder

      </BentoIframe>

The above iframe should be 300x300px when visible

  );
};

WithResizableIframe.storyName = 'Resizable iframe outside viewport';

export const WithSendIntersectionsPostMessage = () => {
  return (

      <BentoIframe
        style={{width: 500, height: 500}}
        iframeStyle={{border: '1px solid black'}}
        sandbox="allow-scripts allow-same-origin"
        src="/examples/bento/amp-iframe-send-intersections-example.html"
      >

Placeholder

      </BentoIframe>

  );
};

WithSendIntersectionsPostMessage.storyName = 'Send intersections';
<|endoftext|>


<commit_before>import React from 'react';
import { Cloudinary } from '../views';

const onClick = ({ query, pathname, router }) => (selectionIds, index, e) => {
  if(e.shiftKey) {
    // MULTI
    const selected = (query[`@media`] || '').split(',').filter(x => x);
    selectionIds.forEach((selectionId) => {
      const itemIndex = selected.findIndex(item => item === selectionId);
      if (itemIndex < 0) {
        selected.push(selectionId); // add/select
      } else {
        selected.splice(itemIndex, 1); // remove/deselect
      }
    });
    router.push({ pathname, query: { ...query, '@media': selected.join(',') }});
  } else {
    // SINGLE
    const selected = (query['@media'] || '').split(',').filter(x => x)[0];
    router.push({ pathname, query: { ...query, '@media': selected !== selectionIds[0] ? selectionIds[0] : null } });
  }
};

export default ({ query, pathname, router }) => (
  <Cloudinary
    pdfMode
    selected={(query['@media'] || '').split(',').filter(x => x)}
    onClick={onClick({ query, pathname, router })}
    onSelect={items => console.log(items)} // => Selection-Mode
    onClose={() => router.push({ pathname, query: { ...query, '@media': undefined } })}
  />
);
<commit_msg>fix error in media<commit_after>import React from 'react';
import { Cloudinary } from '../views';

const onClick = ({ query, pathname, router }) => (selectionIds, index, e) => {
  const selected = (query[`@media`] || '').split(',').filter(x => x);

  if(e && e.shiftKey) {
    // MULTI
    selectionIds.forEach((selectionId) => {
      const itemIndex = selected.findIndex(item => item === selectionId);
      if (itemIndex < 0) {
        selected.push(selectionId); // add/select
      } else {
        selected.splice(itemIndex, 1); // remove/deselect
      }
    });
    router.push({ pathname, query: { ...query, '@media': selected.join(',') }});
  } else {
    // SINGLE
    if (selected.length && selected.includes(selectionIds[0])) {
      router.push({ pathname, query: { ...query, '@media': selected.filter(x => x !== selectionIds[0]).join(',') } });
    } else {
      router.push({ pathname, query: { ...query, '@media': selectionIds[0] } });
    }
  }
};

export default ({ query, pathname, router }) => (
  <Cloudinary
    pdfMode
    selected={(query['@media'] || '').split(',').filter(x => x)}
    onClick={onClick({ query, pathname, router })}
    onSelect={items => console.log(items)} // => Selection-Mode
    onClose={() => router.push({ pathname, query: { ...query, '@media': undefined } })}
  />
);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Uploader from './upload/Uploader'
import FileDisplay from './fileDisplay/FileDisplay'
import Affirm from './affirm/Affirm'

class ValueMachine extends Component {
  constructor() {
    super()
    this.state = {
      image: null,
      complete: false,
    }
  }

  setUploadedFile = (file) => {
    const reader = new FileReader()

    reader.onload = (upload) => {
      this.setState({
        image: upload.target.result,
      })
    }

    reader.readAsDataURL(file)
  }

  setComplete = () => {
    this.setState({
      complete: true,
    })
  }

  render() {
    const {image, complete} = this.state
    const valueMachineClass = complete ? 'value-machine value-machine-complete' : 'value-machine'
    return (

        {image === null && !complete
          ? <Uploader onDrop={this.setUploadedFile} />
          : null
        }

        {image !== null && !complete
          ? <FileDisplay image={image} onComplete={this.setComplete} />
          : null
        }

        {complete &&
          <Affirm />
        }

    )
  }
}

export default ValueMachine
<commit_msg>ValueMachine container refactor<commit_after>import React, { Component } from 'react'
import Uploader from './upload/Uploader'
import FileDisplay from './fileDisplay/FileDisplay'
import Affirm from './affirm/Affirm'

class ValueMachine extends Component {
  constructor() {
    super()
    this.state = {
      image: null,
      complete: false,
    }
  }

  setUploadedFile = (file) => {
    const reader = new FileReader()

    reader.onload = (upload) => {
      this.setState({
        image: upload.target.result,
      })
    }

    reader.readAsDataURL(file)
  }

  setComplete = () => {
    this.setState({
      complete: true,
    })
  }

  render() {
    const {image, complete} = this.state
    const valueMachineClass = complete ? 'value-machine value-machine-complete' : 'value-machine'
    return (

        {image === null && !complete &&
          <Uploader onDrop={this.setUploadedFile} />
        }

        {image !== null && !complete &&
          <FileDisplay image={image} onComplete={this.setComplete} />
        }

        {complete &&
          <Affirm />
        }

    )
  }
}

export default ValueMachine
<|endoftext|>


<commit_before>(function (ng) {

  var MILLISECONDS_PER_DAY = 86400000,
      OFFSET_TO_START_WEEK_ON_MONDAY = 1,
      JAN = 0,
      DAYS_PER_WEEK = 7;

  function getFirstDateOfTheYear(date) {
    return new Date(date.getFullYear(), JAN, 1);
  }

  function getFirstDayOfTheYear(date) {
    var firstJan = getFirstDateOfTheYear(date);
    return firstJan.getDay() + OFFSET_TO_START_WEEK_ON_MONDAY;
  }

  function setWeek(date, week) {
    var dayOfTheYear = Math.floor(week * DAYS_PER_WEEK),
        daysSinceFirstJan = dayOfTheYear - getFirstDayOfTheYear(date),
        msSinceFirstJan = daysSinceFirstJan * MILLISECONDS_PER_DAY,
        firstJan = getFirstDateOfTheYear(date),
        ms = firstJan.getTime() + msSinceFirstJan;
    date.setTime(ms);
  }

  function AutoInputValueCtrl($scope, $attrs, $parse) {
    this.$scope = $scope;
    this.$attrs = $attrs;
    if ($attrs.ngModel && $attrs.value) {
      this.val = $attrs.value;
      this.getter = $parse($attrs.ngModel);
      this.setter = this.getter.assign;
      this.update();
    }
  }

  AutoInputValueCtrl.prototype.set = function (value) {
    this.setter(this.$scope, value);
  };

  AutoInputValueCtrl.prototype.update = function () {
    switch (this.$attrs.type) {
      case "button":
      case "file":
      case "hidden":
      case "image":
      case "reset":
      case "submit":
        break;
      case "checkbox":
        this.updateCheckbox();
        break;
      case "number":
      case "range":
        this.updateNumber();
        break;
      case "radio":
        this.updateRadio();
        break;
      case "date":
      case "datetime":
      case "datetime-local":
      case "month":
        this.updateDate();
        break;
      case "time":
        this.updateTime();
        break;
      case "week":
        this.updateWeek();
        break;
      default:
        this.updateText();
    }
  };

  AutoInputValueCtrl.prototype.updateText = function () {
    this.set(this.val);
  };

  AutoInputValueCtrl.prototype.updateRadio = function () {
    if (this.$attrs.selected) {
      this.set(this.val);
    }
  };

  AutoInputValueCtrl.prototype.updateCheckbox = function () {
    this.set(this.$attrs.selected);
  };

  AutoInputValueCtrl.prototype.updateNumber = function () {
    this.set(+this.val);
  };

  AutoInputValueCtrl.prototype.updateDate = function () {
    this.set(new Date(this.val));
  };

  AutoInputValueCtrl.prototype.updateTime = function () {
    var date = new Date(),
        time = this.val.split(/[:\.]/);
    date.setHours.apply(date, time);
    this.set(date);
  };

  AutoInputValueCtrl.prototype.updateWeek = function () {
    var val = this.val.split('-W'),
        year = +val[0],
        week = +val[1],
        date = new Date(year, JAN, 1);
    setWeek(date, week);
    this.set(date);
  };

  function autoInputValueDirective() {
    return {
      restrict: "E",
      controller: ["$scope", "$attrs", "$parse", AutoInputValueCtrl]
    };
  }

  function autoTextareaValueCtrl($scope, $element, $attrs, $parse) {
    if ($attrs.ngModel) {
      var val = $element.val(),
          getter = $parse($attrs.ngModel),
          setter = getter.assign;
      return setter($scope, val);
    }
  }

  function autoTextareaValueDirective() {
    return {
      restrict: "E",
      controller: ["$scope", "$element", "$attrs", "$parse", autoTextareaValueCtrl]
    };
  }

  function autoSelectDirective($parse) {
    return{
      restrict: 'E',
      require: 'select',
      link: function($scope, $element, $attrs) {
        if ($attrs.ngModel) {
          var val = $element.val();
          getter = $parse($attrs.ngModel);
          setter = getter.assign;
          setter($scope, val);
        }
      }
    };
  }

  ng
    .module('auto-value', [])
    .directive('input', autoInputValueDirective)
    .directive('select', ['$parse', autoSelectDirective])
    .directive('textarea', autoTextareaValueDirective);

}(angular));

<commit_msg>Refactor; removing duplicate code.<commit_after>(function (ng) {

  var MILLISECONDS_PER_DAY = 86400000,
      OFFSET_TO_START_WEEK_ON_MONDAY = 1,
      JAN = 0,
      DAYS_PER_WEEK = 7;

  function getFirstDateOfTheYear(date) {
    return new Date(date.getFullYear(), JAN, 1);
  }

  function getFirstDayOfTheYear(date) {
    var firstJan = getFirstDateOfTheYear(date);
    return firstJan.getDay() + OFFSET_TO_START_WEEK_ON_MONDAY;
  }

  function setWeek(date, week) {
    var dayOfTheYear = Math.floor(week * DAYS_PER_WEEK),
        daysSinceFirstJan = dayOfTheYear - getFirstDayOfTheYear(date),
        msSinceFirstJan = daysSinceFirstJan * MILLISECONDS_PER_DAY,
        firstJan = getFirstDateOfTheYear(date),
        ms = firstJan.getTime() + msSinceFirstJan;
    date.setTime(ms);
  }

  function AutoInputValueCtrl($scope, $attrs, $parse) {
    this.$scope = $scope;
    this.$attrs = $attrs;
    if ($attrs.ngModel && $attrs.value) {
      this.val = $attrs.value;
      this.getter = $parse($attrs.ngModel);
      this.setter = this.getter.assign;
      this.update();
    }
  }

  AutoInputValueCtrl.prototype.set = function (value) {
    this.setter(this.$scope, value);
  };

  AutoInputValueCtrl.prototype.update = function () {
    switch (this.$attrs.type) {
      case "button":
      case "file":
      case "hidden":
      case "image":
      case "reset":
      case "submit":
        break;
      case "checkbox":
        this.updateCheckbox();
        break;
      case "number":
      case "range":
        this.updateNumber();
        break;
      case "radio":
        this.updateRadio();
        break;
      case "date":
      case "datetime":
      case "datetime-local":
      case "month":
        this.updateDate();
        break;
      case "time":
        this.updateTime();
        break;
      case "week":
        this.updateWeek();
        break;
      default:
        this.updateText();
    }
  };

  AutoInputValueCtrl.prototype.updateText = function () {
    this.set(this.val);
  };

  AutoInputValueCtrl.prototype.updateRadio = function () {
    if (this.$attrs.selected) {
      this.set(this.val);
    }
  };

  AutoInputValueCtrl.prototype.updateCheckbox = function () {
    this.set(this.$attrs.selected);
  };

  AutoInputValueCtrl.prototype.updateNumber = function () {
    this.set(+this.val);
  };

  AutoInputValueCtrl.prototype.updateDate = function () {
    this.set(new Date(this.val));
  };

  AutoInputValueCtrl.prototype.updateTime = function () {
    var date = new Date(),
        time = this.val.split(/[:\.]/);
    date.setHours.apply(date, time);
    this.set(date);
  };

  AutoInputValueCtrl.prototype.updateWeek = function () {
    var val = this.val.split('-W'),
        year = +val[0],
        week = +val[1],
        date = new Date(year, JAN, 1);
    setWeek(date, week);
    this.set(date);
  };

  function autoInputValueDirective() {
    return {
      restrict: "E",
      controller: ["$scope", "$attrs", "$parse", AutoInputValueCtrl]
    };
  }

  function autoValueDirective($parse) {
    function link($scope, $element, $attrs) {
      if ($attrs.ngModel) {
        var val = $element.val(),
            getter = $parse($attrs.ngModel),
            setter = getter.assign;
        setter($scope, val);
      }
    }
    return {
      restrict: "E",
      link: link
    };
  }

  autoValueDirective.$inject = ['$parse'];

  ng
    .module('auto-value', [])
    .directive('input', autoInputValueDirective)
    .directive('select', autoValueDirective)
    .directive('textarea', autoValueDirective);

}(angular));

<|endoftext|>


<commit_before>// By Luis Perez
// From blog post: http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/

(function() {
  function initNgModules(element) {
      var elements = [element],
          moduleElements = [],
          modules = [],
          names = ['ng:module', 'ng-module', 'x-ng-module', 'data-ng-module', 'ng:modules', 'ng-modules', 'x-ng-modules', 'data-ng-modules'],
          NG_MODULE_CLASS_REGEXP = /\sng[:\-]module[s](:\s*([\w\d_]+);?)?\s/;

      function append(element) {
          element && elements.push(element);
      }

      for(var i = 0; i < names.length; i++) {
          var name = names[i];
          names[i] = true;
          append(document.getElementById(name));
          name = name.replace(':', '\\:');
          if (element.querySelectorAll) {
              var elements2;
              elements2 = element.querySelectorAll('.' + name);
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('.' + name + '\\:');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('[' + name + ']');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);
          }
      }

      for(var i = 0; i < elements.length; i++) {
          var element = elements[i];

          var className = ' ' + element.className + ' ';
          var match = NG_MODULE_CLASS_REGEXP.exec(className);
          if (match) {
              moduleElements.push(element);
              modules.push((match[2] || '').replace(/\s+/g, ','));
          } else {
              if(element.attributes) {
                  for (var attrName in element.attributes) {
                      if(attrName == "length") continue;
                      var attr = { name: attrName, value: element.attributes[attrName].value };

                      if (names[attr.name]) {
                          moduleElements.push(element);
                          modules.push(attr.value);
                      }
                  }
              }
          }
      }

      for(var i = 0; i < moduleElements.length; i++) {
          var moduleElement = moduleElements[i];
          if (typeof(modules[i]) != 'undefined') {
            var moduleList = modules[i].replace(/ /g,'').split(",");
            var initializedModuleList = [];
            for (var j = 0; j < moduleList.length; ++j) {

              try {
                angular.module(moduleList[j]);
                initializedModuleList.push(moduleList[j]);
              } catch (e) {
                console.error(e);
              }
            }
            angular.bootstrap(moduleElement, initializedModuleList);
          }
      }
  }

  angular.element(document).ready(function() {
        initNgModules(document);
  });
})();
<commit_msg>Updating to latest with firefox fix<commit_after>// By Luis Perez
// From blog post: http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/

(function() {
  function initNgModules(element) {
      var elements = [element],
          moduleElements = [],
          modules = [],
          names = ['ng:module', 'ng-module', 'x-ng-module', 'data-ng-module', 'ng:modules', 'ng-modules', 'x-ng-modules', 'data-ng-modules'],
          NG_MODULE_CLASS_REGEXP = /\sng[:\-]module[s](:\s*([\w\d_]+);?)?\s/;

      function append(element) {
          element && elements.push(element);
      }

      for(var i = 0; i < names.length; i++) {
          var name = names[i];
          append(document.getElementById(name));
          name = name.replace(':', '\\:');
          if (element.querySelectorAll) {
              var elements2;
              elements2 = element.querySelectorAll('.' + name);
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('.' + name + '\\:');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('[' + name + ']');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);
          }
      }

      for(var i = 0; i < elements.length; i++) {
          var element = elements[i];

          var className = ' ' + element.className + ' ';
          var match = NG_MODULE_CLASS_REGEXP.exec(className);
          if (match) {
              moduleElements.push(element);
              modules.push((match[2] || '').replace(/\s+/g, ','));
          } else {
              if(element.attributes) {
                  for(var j = 0; j < element.attributes.length; j++) {
                      var attr = element.attributes[j];

                      if (names.indexOf(attr.name) != -1) {
                          moduleElements.push(element);
                          modules.push(attr.value);
                      }
                  }
              }
          }
      }

      for(var i = 0; i < moduleElements.length; i++) {
          var moduleElement = moduleElements[i];
          if (typeof(modules[i]) != 'undefined') {
              var moduleList = modules[i].replace(/ /g,'').split(",");
              var initializedModuleList = [];
              for (var j = 0; j < moduleList.length; ++j) {
                  try {
                      angular.module(moduleList[j]);
                      initializedModuleList.push(moduleList[j]);
                  } catch (e) {
                      console.error(e);
                  }
              }
              angular.bootstrap(moduleElement, initializedModuleList);
          }
      }
  }

  angular.element(document).ready(function() {
        initNgModules(document);
  });
})();
<|endoftext|>


<commit_before>/**
* (C) Copyright IBM Corp. 2016. All Rights Reserved.
*
* 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.
*/

var TRAVIS_JOB_NUMBER = process.env.TRAVIS_JOB_NUMBER;

module.exports = {
  "src_folders": [
    "test/selenium/specs"
  ],
  "page_objects_path": "test/selenium/pageobjects",
  "output_folder": "./reports",
  "selenium": {
    "start_process": true,
    "server_path": "./bin/selenium.jar",
    "host": "127.0.0.1",
    "port": 4444,
    "cli_args": {
      "webdriver.chrome.driver": "./bin/chromedriver"
    }
  },
  "test_settings": {
    "default": {
      "screenshots": {
        "enabled": true,
        "path": './test/selenium/errorShots'
      },
      "globals": {
        "waitForConditionTimeout": 10000
      },
      "desiredCapabilities": {
        "browserName": "chrome"
      }
    },
    "chrome": {
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true
      }
    },
    "travis" : {
      "selenium_host" : "ondemand.saucelabs.com",
      "selenium_port" : 80,
      "username" : "${SAUCE_USERNAME}",
      "access_key" : "${SAUCE_ACCESS_KEY}",
      "use_ssl" : false,
      "silent": false,
      "output" : true,
      "screenshots": {
        "enabled": true,
        "path": './test/selenium/errorShots/travis'
      },
      "globals": {
        "waitForConditionTimeout": 20000
      },
      "desiredCapabilities": {
        // "browserName": "firefox",
        "browserName": "chrome",
        "javascriptEnabled": true,
        "build": `build-${TRAVIS_JOB_NUMBER}`,
        "tunnel-identifier": TRAVIS_JOB_NUMBER,
      },
      "selenium" : {
        "start_process" : false
      }
    }

  }
};
<commit_msg>add chrome driver params<commit_after>/**
* (C) Copyright IBM Corp. 2016. All Rights Reserved.
*
* 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.
*/

var TRAVIS_JOB_NUMBER = process.env.TRAVIS_JOB_NUMBER;

module.exports = {
  "src_folders": [
    "test/selenium/specs"
  ],
  "page_objects_path": "test/selenium/pageobjects",
  "output_folder": "./reports",
  "selenium": {
    "start_process": true,
    "server_path": "./bin/selenium.jar",
    "host": "127.0.0.1",
    "port": 4444,
    "cli_args": {
      "webdriver.chrome.driver": "./bin/chromedriver"
    }
  },
  "test_settings": {
    "default": {
      "screenshots": {
        "enabled": true,
        "path": './test/selenium/errorShots'
      },
      "globals": {
        "waitForConditionTimeout": 10000
      },
      "desiredCapabilities": {
        "browserName": "chrome"
      }
    },
    "chrome": {
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true
      }
    },
    "travis" : {
      "selenium_host" : "ondemand.saucelabs.com",
      "selenium_port" : 80,
      "username" : "${SAUCE_USERNAME}",
      "access_key" : "${SAUCE_ACCESS_KEY}",
      "use_ssl" : false,
      "silent": false,
      "output" : true,
      "screenshots": {
        "enabled": true,
        "path": './test/selenium/errorShots/travis'
      },
      "globals": {
        "waitForConditionTimeout": 20000
      },
      "desiredCapabilities": {
        // "browserName": "firefox",
        "browserName": "chrome",
        "javascriptEnabled": true,
        "databaseEnabled": true,
        "locationContextEnabled": true,
        "applicationCacheEnabled": true,
        "browserConnectionEnabled": true,
        "webStorageEnabled": true,
        "acceptSslCerts": true,
        "rotatable": true,
        "nativeEvents": true,
        "chromeOptions": {
          "args": ["disable-web-security", "ignore-certificate-errors"]
        },
        "build": `build-${TRAVIS_JOB_NUMBER}`,
        "tunnel-identifier": TRAVIS_JOB_NUMBER,
      },
      "selenium" : {
        "start_process" : false
      }
    }

  }
};
<|endoftext|>


<commit_before>var path = require("path");
var ExceptionHandler =  include('base/ExceptionHandler');

class RouteManager {

    constructor(express, rules) {
        this._rules = rules || [];

        Object.keys(this._rules).map(rule => {
            let action = this._rules[rule];
            if (typeof action == 'function') {
                express.get(rule, action);
            } else {
                express.get(rule, function(req, res) {
                    try {
                        app.response = res;
                        app.request = req;

                        let [controllerName, actionName] = action.trim().split(':');
                        let fullControllerName = controllerName.charAt(0).toUpperCase() + controllerName.slice(1);
                        let controller = require(path.resolve('./controllers/', `${fullControllerName}Controller.js`));
                        let controllerInstance = new controller;
                        controllerInstance.runAction(actionName, req, res);
                    } catch(exception) {
                        ExceptionHandler.addException(exception);
                    }
                });
            }
        });
    }

    getClassName() {
        return RouteManager.name;
    }
}

module.exports = RouteManager;
<commit_msg>fix exception handler in anonymous action<commit_after>var path = require("path");
var ExceptionHandler =  include('base/ExceptionHandler');

class RouteManager {

    constructor(express, rules) {
        this._rules = rules || [];

        Object.keys(this._rules).map(rule => {
            let action = this._rules[rule];

            express.get(rule, function(req, res) {
                try {
                    app.response = res;
                    app.request = req;

                    if (typeof action == 'function') {
                        action(req, res);
                    } else {
                        let [controllerName, actionName] = action.trim().split(':');
                        let fullControllerName = controllerName.charAt(0).toUpperCase() + controllerName.slice(1);
                        let controller = require(path.resolve('./controllers/', `${fullControllerName}Controller.js`));
                        let controllerInstance = new controller;
                        controllerInstance.runAction(actionName, req, res);
                    }

                } catch(exception) {
                    ExceptionHandler.addException(exception);
                }
            });
        });
    }

    getClassName() {
        return RouteManager.name;
    }
}

module.exports = RouteManager;
<|endoftext|>


<commit_before>angular.module('ui.bootstrap.carousel', [])

.controller('UibCarouselController', ['$scope', '$element', '$interval', '$animate', function($scope, $element, $interval, $animate) {
  var self = this,
    slides = self.slides = $scope.slides = [],
    SLIDE_DIRECTION = 'uib-slideDirection',
    currentIndex = -1,
    currentInterval, isPlaying;
  self.currentSlide = null;

  var destroyed = false;
  /* direction: "prev" or "next" */
  self.select = $scope.select = function(nextSlide, direction) {
    var nextIndex = $scope.indexOfSlide(nextSlide);
    //Decide direction if it's not given
    if (direction === undefined) {
      direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
    }
    //Prevent this user-triggered transition from occurring if there is already one in progress
    if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) {
      goNext(nextSlide, nextIndex, direction);
    }
  };

  function goNext(slide, index, direction) {
    // Scope has been destroyed, stop here.
    if (destroyed) { return; }

    angular.extend(slide, {direction: direction, active: true});
    angular.extend(self.currentSlide || {}, {direction: direction, active: false});
    if ($animate.enabled($element) && !$scope.$currentTransition &&
      slide.$element && self.slides.length > 1) {
      slide.$element.data(SLIDE_DIRECTION, slide.direction);
      if (self.currentSlide && self.currentSlide.$element) {
        self.currentSlide.$element.data(SLIDE_DIRECTION, slide.direction);
      }

      $scope.$currentTransition = true;
      $animate.on('addClass', slide.$element, function(element, phase) {
        if (phase === 'close') {
          $scope.$currentTransition = null;
          $animate.off('addClass', element);
        }
      });
    }

    self.currentSlide = slide;
    currentIndex = index;

    //every time you change slides, reset the timer
    restartTimer();
  }

  function getSlideByIndex(index) {
    if (angular.isUndefined(slides[index].index)) {
      return slides[index];
    }
    for (var i = 0, l = slides.length; i < l; ++i) {
      if (slides[i].index === index) {
        return slides[i];
      }
    }
  }

  self.getCurrentIndex = function() {
    if (self.currentSlide && angular.isDefined(self.currentSlide.index)) {
      return +self.currentSlide.index;
    }
    return currentIndex;
  };

  /* Allow outside people to call indexOf on slides array */
  $scope.indexOfSlide = function(slide) {
    return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide);
  };

  self.next = $scope.next = function() {
    var newIndex = (self.getCurrentIndex() + 1) % slides.length;

    if (newIndex === 0 && $scope.noWrap()) {
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'next');
  };

  self.prev = $scope.prev = function() {
    var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;

    if ($scope.noWrap() && newIndex === slides.length - 1) {
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'prev');
  };

  $scope.isActive = function(slide) {
     return self.currentSlide === slide;
  };

  $scope.$watch('interval', restartTimer);
  $scope.$watchCollection('slides', resetTransition);
  $scope.$on('$destroy', function() {
    destroyed = true;
    resetTimer();
  });

  function restartTimer() {
    resetTimer();
    var interval = +$scope.interval;
    if (!isNaN(interval) && interval > 0) {
      currentInterval = $interval(timerFn, interval);
    }
  }

  function resetTimer() {
    if (currentInterval) {
      $interval.cancel(currentInterval);
      currentInterval = null;
    }
  }

  function timerFn() {
    var interval = +$scope.interval;
    if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
      $scope.next();
    } else {
      $scope.pause();
    }
  }

  function resetTransition(slides) {
    if (!slides.length) {
      $scope.$currentTransition = null;
    }
  }

  $scope.play = function() {
    if (!isPlaying) {
      isPlaying = true;
      restartTimer();
    }
  };
  $scope.pause = function() {
    if (!$scope.noPause) {
      isPlaying = false;
      resetTimer();
    }
  };

  self.addSlide = function(slide, element) {
    slide.$element = element;
    slides.push(slide);
    //if this is the first slide or the slide is set to active, select it
    if (slides.length === 1 || slide.active) {
      self.select(slides[slides.length - 1]);
      if (slides.length === 1) {
        $scope.play();
      }
    } else {
      slide.active = false;
    }
  };

  self.removeSlide = function(slide) {
    if (angular.isDefined(slide.index)) {
      slides.sort(function(a, b) {
        return +a.index > +b.index;
      });
    }
    //get the index of the slide inside the carousel
    var index = slides.indexOf(slide);
    slides.splice(index, 1);
    if (slides.length > 0 && slide.active) {
      if (index >= slides.length) {
        self.select(slides[index - 1]);
      } else {
        self.select(slides[index]);
      }
    } else if (currentIndex > index) {
      currentIndex--;
    }

    //clean the currentSlide when no more slide
    if (slides.length === 0) {
      self.currentSlide = null;
    }
  };

  $scope.$watch('noTransition', function(noTransition) {
    $animate.enabled($element, !noTransition);
  });
}])

.directive('uibCarousel', function() {
  return {
    transclude: true,
    replace: true,
    controller: 'UibCarouselController',
    controllerAs: 'carousel',
    templateUrl: function(element, attrs) {
      return attrs.templateUrl || 'uib/template/carousel/carousel.html';
    },
    scope: {
      interval: '=',
      noTransition: '=',
      noPause: '=',
      noWrap: '&'
    }
  };
})

.directive('uibSlide', function() {
  return {
    require: '^uibCarousel',
    transclude: true,
    replace: true,
    templateUrl: function(element, attrs) {
      return attrs.templateUrl || 'uib/template/carousel/slide.html';
    },
    scope: {
      active: '=?',
      actual: '=?',
      index: '=?'
    },
    link: function (scope, element, attrs, carouselCtrl) {
      carouselCtrl.addSlide(scope, element);
      //when the scope is destroyed then remove the slide from the current slides array
      scope.$on('$destroy', function() {
        carouselCtrl.removeSlide(scope);
      });

      scope.$watch('active', function(active) {
        if (active) {
          carouselCtrl.select(scope);
        }
      });
    }
  };
})

.animation('.item', ['$animateCss',
function($animateCss) {
  var SLIDE_DIRECTION = 'uib-slideDirection';

  function removeClass(element, className, callback) {
    element.removeClass(className);
    if (callback) {
      callback();
    }
  }

  return {
    beforeAddClass: function(element, className, done) {
      if (className === 'active') {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction === 'next' ? 'left' : 'right';
        var removeClassFn = removeClass.bind(this, element,
          directionClass + ' ' + direction, done);
        element.addClass(direction);

        $animateCss(element, {addClass: directionClass})
          .start()
          .done(removeClassFn);

        return function() {
          stopped = true;
        };
      }
      done();
    },
    beforeRemoveClass: function (element, className, done) {
      if (className === 'active') {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction === 'next' ? 'left' : 'right';
        var removeClassFn = removeClass.bind(this, element, directionClass, done);

        $animateCss(element, {addClass: directionClass})
          .start()
          .done(removeClassFn);

        return function() {
          stopped = true;
        };
      }
      done();
    }
  };
}]);
<commit_msg>chore(carousel): clean up code style<commit_after>angular.module('ui.bootstrap.carousel', [])

.controller('UibCarouselController', ['$scope', '$element', '$interval', '$animate', function($scope, $element, $interval, $animate) {
  var self = this,
    slides = self.slides = $scope.slides = [],
    SLIDE_DIRECTION = 'uib-slideDirection',
    currentIndex = -1,
    currentInterval, isPlaying;
  self.currentSlide = null;

  var destroyed = false;
  /* direction: "prev" or "next" */
  self.select = $scope.select = function(nextSlide, direction) {
    var nextIndex = $scope.indexOfSlide(nextSlide);
    //Decide direction if it's not given
    if (direction === undefined) {
      direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
    }
    //Prevent this user-triggered transition from occurring if there is already one in progress
    if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) {
      goNext(nextSlide, nextIndex, direction);
    }
  };

  function goNext(slide, index, direction) {
    // Scope has been destroyed, stop here.
    if (destroyed) { return; }

    angular.extend(slide, {direction: direction, active: true});
    angular.extend(self.currentSlide || {}, {direction: direction, active: false});
    if ($animate.enabled($element) && !$scope.$currentTransition &&
      slide.$element && self.slides.length > 1) {
      slide.$element.data(SLIDE_DIRECTION, slide.direction);
      if (self.currentSlide && self.currentSlide.$element) {
        self.currentSlide.$element.data(SLIDE_DIRECTION, slide.direction);
      }

      $scope.$currentTransition = true;
      $animate.on('addClass', slide.$element, function(element, phase) {
        if (phase === 'close') {
          $scope.$currentTransition = null;
          $animate.off('addClass', element);
        }
      });
    }

    self.currentSlide = slide;
    currentIndex = index;

    //every time you change slides, reset the timer
    restartTimer();
  }

  function getSlideByIndex(index) {
    if (angular.isUndefined(slides[index].index)) {
      return slides[index];
    }
    for (var i = 0, l = slides.length; i < l; ++i) {
      if (slides[i].index === index) {
        return slides[i];
      }
    }
  }

  self.getCurrentIndex = function() {
    if (self.currentSlide && angular.isDefined(self.currentSlide.index)) {
      return +self.currentSlide.index;
    }
    return currentIndex;
  };

  /* Allow outside people to call indexOf on slides array */
  $scope.indexOfSlide = function(slide) {
    return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide);
  };

  self.next = $scope.next = function() {
    var newIndex = (self.getCurrentIndex() + 1) % slides.length;

    if (newIndex === 0 && $scope.noWrap()) {
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'next');
  };

  self.prev = $scope.prev = function() {
    var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;

    if ($scope.noWrap() && newIndex === slides.length - 1) {
      $scope.pause();
      return;
    }

    return self.select(getSlideByIndex(newIndex), 'prev');
  };

  $scope.isActive = function(slide) {
    return self.currentSlide === slide;
  };

  $scope.$watch('interval', restartTimer);
  $scope.$watchCollection('slides', resetTransition);
  $scope.$on('$destroy', function() {
    destroyed = true;
    resetTimer();
  });

  function restartTimer() {
    resetTimer();
    var interval = +$scope.interval;
    if (!isNaN(interval) && interval > 0) {
      currentInterval = $interval(timerFn, interval);
    }
  }

  function resetTimer() {
    if (currentInterval) {
      $interval.cancel(currentInterval);
      currentInterval = null;
    }
  }

  function timerFn() {
    var interval = +$scope.interval;
    if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
      $scope.next();
    } else {
      $scope.pause();
    }
  }

  function resetTransition(slides) {
    if (!slides.length) {
      $scope.$currentTransition = null;
    }
  }

  $scope.play = function() {
    if (!isPlaying) {
      isPlaying = true;
      restartTimer();
    }
  };
  $scope.pause = function() {
    if (!$scope.noPause) {
      isPlaying = false;
      resetTimer();
    }
  };

  self.addSlide = function(slide, element) {
    slide.$element = element;
    slides.push(slide);
    //if this is the first slide or the slide is set to active, select it
    if (slides.length === 1 || slide.active) {
      self.select(slides[slides.length - 1]);
      if (slides.length === 1) {
        $scope.play();
      }
    } else {
      slide.active = false;
    }
  };

  self.removeSlide = function(slide) {
    if (angular.isDefined(slide.index)) {
      slides.sort(function(a, b) {
        return +a.index > +b.index;
      });
    }
    //get the index of the slide inside the carousel
    var index = slides.indexOf(slide);
    slides.splice(index, 1);
    if (slides.length > 0 && slide.active) {
      if (index >= slides.length) {
        self.select(slides[index - 1]);
      } else {
        self.select(slides[index]);
      }
    } else if (currentIndex > index) {
      currentIndex--;
    }

    //clean the currentSlide when no more slide
    if (slides.length === 0) {
      self.currentSlide = null;
    }
  };

  $scope.$watch('noTransition', function(noTransition) {
    $animate.enabled($element, !noTransition);
  });
}])

.directive('uibCarousel', function() {
  return {
    transclude: true,
    replace: true,
    controller: 'UibCarouselController',
    controllerAs: 'carousel',
    templateUrl: function(element, attrs) {
      return attrs.templateUrl || 'uib/template/carousel/carousel.html';
    },
    scope: {
      interval: '=',
      noTransition: '=',
      noPause: '=',
      noWrap: '&'
    }
  };
})

.directive('uibSlide', function() {
  return {
    require: '^uibCarousel',
    transclude: true,
    replace: true,
    templateUrl: function(element, attrs) {
      return attrs.templateUrl || 'uib/template/carousel/slide.html';
    },
    scope: {
      active: '=?',
      actual: '=?',
      index: '=?'
    },
    link: function (scope, element, attrs, carouselCtrl) {
      carouselCtrl.addSlide(scope, element);
      //when the scope is destroyed then remove the slide from the current slides array
      scope.$on('$destroy', function() {
        carouselCtrl.removeSlide(scope);
      });

      scope.$watch('active', function(active) {
        if (active) {
          carouselCtrl.select(scope);
        }
      });
    }
  };
})

.animation('.item', ['$animateCss',
function($animateCss) {
  var SLIDE_DIRECTION = 'uib-slideDirection';

  function removeClass(element, className, callback) {
    element.removeClass(className);
    if (callback) {
      callback();
    }
  }

  return {
    beforeAddClass: function(element, className, done) {
      if (className === 'active') {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction === 'next' ? 'left' : 'right';
        var removeClassFn = removeClass.bind(this, element,
          directionClass + ' ' + direction, done);
        element.addClass(direction);

        $animateCss(element, {addClass: directionClass})
          .start()
          .done(removeClassFn);

        return function() {
          stopped = true;
        };
      }
      done();
    },
    beforeRemoveClass: function (element, className, done) {
      if (className === 'active') {
        var stopped = false;
        var direction = element.data(SLIDE_DIRECTION);
        var directionClass = direction === 'next' ? 'left' : 'right';
        var removeClassFn = removeClass.bind(this, element, directionClass, done);

        $animateCss(element, {addClass: directionClass})
          .start()
          .done(removeClassFn);

        return function() {
          stopped = true;
        };
      }
      done();
    }
  };
}]);
<|endoftext|>


<commit_before>var $ui = $ui || {};
/**
Create a new carousel component from an unordered list element `<ul>`

HTML:

Slide 1

Slide 2

Slide 3

Javascript:

	$ui.carousel({
		element: document.getElementById('carousel'),
		delay:5000
	});

@class $ui.carousel
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to component
@param [options.value=0] {Number} Starting item index
@param [options.tabindex=0] {Number} Tabindex of component, defaults to the attribute value set on the passed element, or `0`
@param [options.delay=4000] {Number} Delay in `ms` between item changes
@return Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function($ui) {
    $ui.carousel = function(opt) {
        var el = opt.element,
            options = opt.options || [],
            value = opt.value || 0,
            delay = opt.delay || 4000,
            timer = true,
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        if (options.length === 0 && el.nodeName === "UL") {
            for (var i = 0; i < el.children.length; i++) {
                options.push(el.children[i].innerHTML);
            }
        }
        var tpl = "

",
            navEl = [],
            optionEl = [];
        for (var o = 0; o < options.length; o++) {
            optionEl.push($ui.createEl("
" + options[o] + "
"));
            navEl.push($ui.createEl("" + o + ""));
        }
        tpl += "

";

        el.innerHTML = '';
        el = $ui.replaceEl(el, tpl);
        for (o = 0; o < options.length; o++) {
            el.children[0].appendChild(optionEl[o]);
            el.appendChild(navEl[o]);
        }

        function clickHandler(e) {
            obj.val($ui.attribute(e.target, 'data-nav'));
        }
        for (var c in el.children) {
            if ($ui.attribute(el.children[c], 'data-nav')) {
                $ui.bindEvent('click', el.children[c], clickHandler);
            }
        }

        $ui.bindEvent("mousewheel", el, function(e) {
            $ui.preventBubble(e);
            obj.val((e.wheelDelta < 0 || e.detail > 0) ? '-1' : '+1');
        });

        $ui.bindEvent('keydown', el, function(e) {
            if (document.activeElement !== el) {
                return;
            }
            switch (e.keyCode) {
                case 34: //page down
                case 40: //down cursor
                case 37: //left cursor
                    obj.val('-1');
                    $ui.preventBubble(e);
                    break;
                case 33: //page up
                case 32: //spacebar
                case 38: //up cursor
                case 39: //right cursor
                    obj.val('+1');
                    $ui.preventBubble(e);
                    break;
                case 36: //home
                    obj.val(0);
                    $ui.preventBubble(e);
                    break;
                case 35: //end
                    obj.val(options.length - 1);
                    $ui.preventBubble(e);
                    break;
            }
        });
        var oldVal;
        /**
        Gets or sets control item
        @method val
        @param [value] {Number} Item index to set
        @return {Number} Returns current item index
        */
        var obj = {
            0: el,
            val: function(val) {
                val = val.toString();
                if (val === undefined) {
                    return value;
                }
                var inClass = '',
                    outClass = '';
                if (val.indexOf("-") !== -1) {
                    value = value - parseInt(val.replace('-', ''), 0) < 0 ? options.length - 1 : --value;
                    inClass = 'left';
                    outClass = 'right';
                } else if (val.indexOf("+") !== -1) {
                    value = value + parseInt(val.replace('+', ''), 0) > options.length - 1 ? 0 : ++value;
                    inClass = 'right';
                    outClass = 'left';
                } else {
                    value = parseInt(val.replace('=', ''), 0);
                    value = value < 0 ? 0 : value > options.length - 1 ? options.length - 1 : value;
                    if (oldVal !== undefined && value > oldVal) {
                        inClass = 'right';
                        outClass = 'left';
                    } else {
                        inClass = 'left';
                        outClass = 'right';
                    }
                }
                for (o = 0; o < options.length; o++) {
                    if (oldVal !== undefined && oldVal === o) {
                        $ui.addClass(optionEl[o], 'ui-carousel-out-' + outClass);
                    } else if (oldVal !== undefined) {
                        $ui.removeClass(optionEl[o], 'ui-carousel-out-left');
                        $ui.removeClass(optionEl[o], 'ui-carousel-out-right');
                    }
                    if (parseInt(o, 0) === value) {
                        // add the selected class to the current iteration
                        $ui.addClass(optionEl[o], 'ui-selected');
                        $ui.addClass(navEl[o], 'ui-selected');
                        if (oldVal !== undefined) {
                            $ui.addClass(optionEl[o], 'ui-carousel-in-' + inClass);
                        }
                    } else {
                        $ui.removeClass(optionEl[o], 'ui-selected');
                        $ui.removeClass(optionEl[o], 'ui-carousel-in-right');
                        $ui.removeClass(optionEl[o], 'ui-carousel-in-left');
                        $ui.removeClass(navEl[o], 'ui-selected');
                    }
                }
                oldVal = value;
                timer = false;
                return value;
            }
        };
        obj.val(value);

        if (delay) {
            setInterval(function() {
                if (timer) {
                    obj.val('+1');
                }
                timer = true;
            }, delay);
        }

        return obj;
    };
    return $ui;
})($ui);
<commit_msg>Update carousel.js<commit_after>var $ui = $ui || {};
/**
Create a new carousel component from an unordered list element `<ul>`

HTML:

Slide 1

Slide 2

Slide 3

Javascript:

	$ui.carousel({
		element: document.getElementById('carousel'),
		delay:5000
	});

@class $ui.carousel
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to component
@param [options.value=0] {Number} Starting item index
@param [options.tabindex=0] {Number} Tabindex of component, defaults to the attribute value set on the passed element, or `0`
@param [options.delay=4000] {Number} Delay in `ms` between item changes
@return Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function($ui) {
    $ui.carousel = function(opt) {
        var el = opt.element,
            options = opt.options || [],
            value = opt.value || 0,
            delay = opt.delay || 4000,
            timer = true,
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        if (options.length === 0 && el.nodeName === "UL") {
            for (var i = 0; i < el.children.length; i++) {
                options.push(el.children[i].innerHTML);
            }
        }
        var navEl = [],
            optionEl = [];
        for (var o = 0; o < options.length; o++) {
            optionEl.push($ui.createEl($ui.compile('carousel_item', {html:options[o]})));
            navEl.push($ui.createEl($ui.compile('carousel_nav', {index:o})));
        }
		opt=$ui.inputCtrlMeta(opt, 'rating');
        el.innerHTML = '';
        el = $ui.replaceEl(el, $ui.compile('carousel',opt));

        for (o = 0; o < options.length; o++) {
            el.children[0].appendChild(optionEl[o]);
            el.appendChild(navEl[o]);
        }

        function clickHandler(e) {
            obj.val($ui.attribute(e.target, 'data-nav'));
        }
        for (var c in el.children) {
            if ($ui.attribute(el.children[c], 'data-nav')) {
                $ui.bindEvent('click', el.children[c], clickHandler);
            }
        }

        $ui.bindEvent("mousewheel", el, function(e) {
            $ui.preventBubble(e);
            obj.val((e.wheelDelta < 0 || e.detail > 0) ? '-1' : '+1');
        });

        $ui.bindEvent('keydown', el, function(e) {
            if (document.activeElement !== el) {
                return;
            }
            switch (e.keyCode) {
                case 34: //page down
                case 40: //down cursor
                case 37: //left cursor
                    obj.val('-1');
                    $ui.preventBubble(e);
                    break;
                case 33: //page up
                case 32: //spacebar
                case 38: //up cursor
                case 39: //right cursor
                    obj.val('+1');
                    $ui.preventBubble(e);
                    break;
                case 36: //home
                    obj.val(0);
                    $ui.preventBubble(e);
                    break;
                case 35: //end
                    obj.val(options.length - 1);
                    $ui.preventBubble(e);
                    break;
            }
        });
        var oldVal;
        /**
        Gets or sets control item
        @method val
        @param [value] {Number} Item index to set
        @return {Number} Returns current item index
        */
        var obj = {
            0: el,
            val: function(val) {
                val = val.toString();
                if (val === undefined) {
                    return value;
                }
                var inClass = '',
                    outClass = '';
                if (val.indexOf("-") !== -1) {
                    value = value - parseInt(val.replace('-', ''), 0) < 0 ? options.length - 1 : --value;
                    inClass = 'left';
                    outClass = 'right';
                } else if (val.indexOf("+") !== -1) {
                    value = value + parseInt(val.replace('+', ''), 0) > options.length - 1 ? 0 : ++value;
                    inClass = 'right';
                    outClass = 'left';
                } else {
                    value = parseInt(val.replace('=', ''), 0);
                    value = value < 0 ? 0 : value > options.length - 1 ? options.length - 1 : value;
                    if (oldVal !== undefined && value > oldVal) {
                        inClass = 'right';
                        outClass = 'left';
                    } else {
                        inClass = 'left';
                        outClass = 'right';
                    }
                }
                for (o = 0; o < options.length; o++) {
                    if (oldVal !== undefined && oldVal === o) {
                        $ui.addClass(optionEl[o], 'ui-carousel-out-' + outClass);
                    } else if (oldVal !== undefined) {
                        $ui.removeClass(optionEl[o], 'ui-carousel-out-left');
                        $ui.removeClass(optionEl[o], 'ui-carousel-out-right');
                    }
                    if (parseInt(o, 0) === value) {
                        // add the selected class to the current iteration
                        $ui.addClass(optionEl[o], 'ui-selected');
                        $ui.addClass(navEl[o], 'ui-selected');
                        if (oldVal !== undefined) {
                            $ui.addClass(optionEl[o], 'ui-carousel-in-' + inClass);
                        }
                    } else {
                        $ui.removeClass(optionEl[o], 'ui-selected');
                        $ui.removeClass(optionEl[o], 'ui-carousel-in-right');
                        $ui.removeClass(optionEl[o], 'ui-carousel-in-left');
                        $ui.removeClass(navEl[o], 'ui-selected');
                    }
                }
                oldVal = value;
                timer = false;
                return value;
            }
        };
        obj.val(value);

        if (delay) {
            setInterval(function() {
                if (timer) {
                    obj.val('+1');
                }
                timer = true;
            }, delay);
        }

        return obj;
    };
    return $ui;
})($ui);
<|endoftext|>


<commit_before>import React from "react";

const MiddleContainer = (props) => {
  var middleContainerStyle = {
    flex: 2,
    margin: "0.5rem"
  };

  return (

      {props.children}

  );

};

export default MiddleContainer;
<commit_msg>Refactor: Add props destructuring<commit_after>import React from "react";

const MiddleContainer = ({children}) => {
  var middleContainerStyle = {
    flex: 2,
    margin: "0.5rem"
  };

  return (

      {children}

  );

};

export default MiddleContainer;
<|endoftext|>


<commit_before>import theme from '../../theme'

export default {
  highlightedMarkdown: {
    '@global': {
      'b, strong': {
        fontWeight: 500
      },

      // Link styles
      a: {
        textDecoration: 'underline',
        color: theme.textColor,
        '&:hover': {
          isolate: false,
          textDecoration: 'none',
        },
      },

      // Paragraphs
      p: {
        margin: [20, 0],
        '&:first-child': {
          isolate: false,
          marginTop: 0
        },
      },

      // Headings
      'h1, h2, h3, h4': {
        color: theme.titleColor,
        margin: [40, 0],
        fontWeight: 400,
        lineHeight: 1,
        '&:first-child': {
          isolate: false,
          marginTop: 0
        },
      },
      h1: {
        fontSize: 36,
      },
      h2: {
        fontSize: 24,
        margin: [30, 0],
      },
      h3: {
        fontSize: 20,
        margin: [20, 0],
      },
      h4: {
        fontSize: 18,
        margin: [20, 0],
      },

      // Lists
      'ul, ol': {
        margin: [20, 0],
        padding: [0, 0, 0, 25]
      },
      'ul > li': {
        listStyle: 'circle',
      },
      'ol > li': {
        listStyle: 'decimal'
      },
      li: {
        padding: [3, 0],
        '& p': {
          margin: 0
        }
      },

      // Divider
      hr: {
        margin: [20, 0],
        border: 'none',
        background: theme.borderColor,
        height: 1,
        display: 'block',
      },

      // Tables
      table: {
        borderCollapse: 'collapse',
        marginBottom: 20,
      },
      'th, td': {
        padding: [5, 15],
        borderBottom: theme.border(theme.borderColor),
        borderLeft: theme.border(theme.borderColor),
        '&:first-child': {
          isolate: false,
          borderLeft: 'none'
        },
      },
      th: {
        fontWeight: 'bold',
        background: theme.cardColor,
      }
    }
  },
  heading: {
    position: 'relative',
    '&:hover $headingAnchor': {
      isolate: false,
      opacity: 1
    }
  },
  headingAnchor: {
    transition: theme.transition(),
    position: 'absolute',
    top: 0,
    bottom: 0,
    width: 15,
    right: '100%',
    margin: {
      right: 5,
      top: '0.5em'
    },
    opacity: 0
  }
}
<commit_msg>margins, line-height borrowed by github<commit_after>import theme from '../../theme'

export default {
  highlightedMarkdown: {
    '@global': {
      'b, strong': {
        fontWeight: 500
      },

      // Link styles
      a: {
        textDecoration: 'underline',
        color: theme.textColor,
        '&:hover': {
          isolate: false,
          textDecoration: 'none',
        },
      },

      // Paragraphs
      p: {
        margin: [20, 0],
        '&:first-child': {
          isolate: false,
          marginTop: 0
        },
      },

      // Headings
      'h1, h2, h3, h4': {
        color: theme.titleColor,
        margin: [40, 0],
        fontWeight: 400,
        lineHeight: 1.25,
        '&:first-child': {
          isolate: false,
          marginTop: 0
        },
      },
      h1: {
        fontSize: 36,
      },
      h2: {
        fontSize: 24,
        margin: {
          top: 24,
          bottom: 16
        },
      },
      h3: {
        fontSize: 20,
        margin: [20, 0],
      },
      h4: {
        fontSize: 18,
        margin: [20, 0],
      },

      // Lists
      'ul, ol': {
        margin: [20, 0],
        padding: [0, 0, 0, 25]
      },
      'ul > li': {
        listStyle: 'circle',
      },
      'ol > li': {
        listStyle: 'decimal'
      },
      li: {
        padding: [3, 0],
        '& p': {
          margin: 0
        }
      },

      // Divider
      hr: {
        margin: [20, 0],
        border: 'none',
        background: theme.borderColor,
        height: 1,
        display: 'block',
      },

      // Tables
      table: {
        borderCollapse: 'collapse',
        marginBottom: 20,
      },
      'th, td': {
        padding: [5, 15],
        borderBottom: theme.border(theme.borderColor),
        borderLeft: theme.border(theme.borderColor),
        '&:first-child': {
          isolate: false,
          borderLeft: 'none'
        },
      },
      th: {
        fontWeight: 'bold',
        background: theme.cardColor,
      }
    }
  },
  heading: {
    position: 'relative',
    '&:hover $headingAnchor': {
      isolate: false,
      opacity: 1
    }
  },
  headingAnchor: {
    transition: theme.transition(),
    position: 'absolute',
    top: 0,
    bottom: 0,
    width: 15,
    right: '100%',
    margin: {
      right: 5,
      top: '0.5em'
    },
    opacity: 0
  }
}
<|endoftext|>


<commit_before>CKEDITOR.plugins.add( 'mediahelper', {

    icons: 'mediahelper',

    init: function( editor ) {

        var self = this;

        CKEDITOR.dialog.add( 'MediaHelperDialog', function (editor) {

            return {

                title: 'Media Helper',
                minWidth: 400,
                minHeight: 200,

                contents: [

                    // Frame for settings
                    {
                        id: 'frame',
                        label: 'Settings',
                        elements: [

                            // URL
                            {
                                type: 'text',
                                id: 'url',
                                label: 'Video URL',
                                'autofocus': 'autofocus'
                            },

                            // Width
                            {
                                type: 'text',
                                id: 'width',
                                label: 'Width (pixels)'
                            },

                            // Height
                            {
                                type: 'text',
                                id: 'height',
                                label: 'Height (pixels)'
                            },

                            // Autoplay
                            {
                                type: 'checkbox',
                                id: 'autoplay',
                                label: 'Autoplay mode'
                            },

                            // Responsive
                            {
                                type: 'checkbox',
                                id: 'responsive',
                                'default': 'checked',
                                label: 'Responsive mode'
                            },

                            // Embed code
                            {
                                type: 'textarea',
                                id: 'embedcode',
                                label: 'Paste embed code (will ignore other settings)'
                            }

                        // End frame elements
                        ]
                    }

                // End contents
                ],

                onOk: function () {

                    var embedElement = null,
                        embedElementContent = null,
                        embedCode = this.getValueOf('frame', 'embedcode'),
                        responsive = this.getValueOf('frame', 'responsive'),
                        url = this.getValueOf('frame', 'url');

                    // If embed code is put in, and the element does not require responsive mode
                    if (embedCode && !responsive) {
                        editor.insertHtml(embedCode);
                    }

                    else {

                        var contentProps = {
                            styles: {
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                width: '100%',
                                height: '100%'
                            }
                        };

                        // If embedCode is set, use that in an empty div
                        if (embedCode) {
                            embedElementContent = editor.document.createElement('div', contentProps);
                            embedElementContent.setHtml(embedCode);
                        }

                        // Else check value of url fields
                        else if (url) {

                            var width = this.getValueOf('frame', 'width') || 640,
                                height = this.getValueOf('frame', 'height') || 360,
                                autoplay = this.getValueOf('frame', 'autoplay'),
                                videoId = null,
                                attributes = [];

                            // Youtube
                            videoId = url.match(/(\.be\/|v[=\/])([\w\-]{11,})/i);
                            if ( videoId ) {
                                url = '//www.youtube.com/embed/' + videoId[2];
                                if (autoplay) {
                                    attributes.push('autoplay=1');
                                }
                            }

                            // Vimeo
                            videoId = url.match(/vimeo\.com(\/video|\/channels\/.*?)?\/(\d+)/i);
                            if ( videoId ) {
                                url = '//player.vimeo.com/video/' + videoId[2];
                                if (autoplay) {
                                    attributes.push('autoplay=1');
                                }
                            }

                            // Create element
                            contentProps.attributes = {
                                src: url + ( attributes.length ? '?' + attributes.join('&') : '' ),
                                width: parseInt( width ),
                                height: parseInt( height ),
                                frameborder: 0,
                                allowfullscreen: ''
                            };
                            embedElementContent = editor.document.createElement('iframe', contentProps);
                        }

                        // Could not determine type
                        else {
                            alert('No URL or embed code was given');
                            return false;
                        }

                        // Add defining class to element content
                        embedElementContent.addClass( 'media-element-content' );

                        // If responsive, put embed content into container
                        if (responsive) {
                            embedElement = editor.document.createElement('div',
                                {
                                    attributes: {
                                        'class': 'media-element'
                                    },
                                    styles: {
                                        position: 'relative',
                                        'padding-bottom': '56.25%', /* 16:9 */
                                        'padding-top': '25px',
                                        height: 0
                                    }
                                }
                            );
                            embedElementContent.appendTo( embedElement );
                        }

                        // Else set embed element to content
                        else {
                            embedElement = embedElementContent;
                        }

                        // Append embedElement to editor
                        editor.insertElement( embedElement );

                    }

                    return true;
                }

            }

        });

        editor.addCommand( 'mediahelper', new CKEDITOR.dialogCommand( 'MediaHelperDialog', {
            allowedContent: 'div[*],iframe[*],object[*]'
        } ) );

        editor.ui.addButton( 'MediaHelper', {

            label: 'Media Helper',
            command: 'mediahelper',
            toolbar: 'insert'

        });

    }

});
<commit_msg>Made sure correct classes are added Made sure responsive styles are not partially added when not needed<commit_after>CKEDITOR.plugins.add( 'mediahelper', {

    icons: 'mediahelper',

    init: function( editor ) {

        var self = this;

        CKEDITOR.dialog.add( 'MediaHelperDialog', function (editor) {

            return {

                title: 'Media Helper',
                minWidth: 400,
                minHeight: 200,

                contents: [

                    // Frame for settings
                    {
                        id: 'frame',
                        label: 'Settings',
                        elements: [

                            // URL
                            {
                                type: 'text',
                                id: 'url',
                                label: 'Video URL',
                                'autofocus': 'autofocus'
                            },

                            // Width
                            {
                                type: 'text',
                                id: 'width',
                                label: 'Width (pixels)'
                            },

                            // Height
                            {
                                type: 'text',
                                id: 'height',
                                label: 'Height (pixels)'
                            },

                            // Autoplay
                            {
                                type: 'checkbox',
                                id: 'autoplay',
                                label: 'Autoplay mode'
                            },

                            // Responsive
                            {
                                type: 'checkbox',
                                id: 'responsive',
                                'default': 'checked',
                                label: 'Responsive mode'
                            },

                            // Embed code
                            {
                                type: 'textarea',
                                id: 'embedcode',
                                label: 'Paste embed code (will ignore other settings)'
                            }

                        // End frame elements
                        ]
                    }

                // End contents
                ],

                onOk: function () {

                    var embedElement = null,
                        embedElementContent = null,
                        embedCode = this.getValueOf('frame', 'embedcode'),
                        responsive = this.getValueOf('frame', 'responsive'),
                        url = this.getValueOf('frame', 'url');

                    // If embed code is put in, and the element does not require responsive mode
                    if (embedCode && !responsive) {
                        editor.insertHtml(embedCode);
                    }

                    else {

                        var contentProps = {};

                        if (responsive) {
                            contentProps.styles = {
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                width: '100%',
                                height: '100%'
                            };
                        }

                        // If embedCode is set, use that in an empty div
                        if (embedCode) {
                            embedElementContent = editor.document.createElement('div', contentProps);
                            embedElementContent.setHtml(embedCode);
                        }

                        // Else check value of url fields
                        else if (url) {

                            var width = this.getValueOf('frame', 'width') || 640,
                                height = this.getValueOf('frame', 'height') || 360,
                                autoplay = this.getValueOf('frame', 'autoplay'),
                                videoId = null,
                                attributes = [];

                            // Youtube
                            videoId = url.match(/(\.be\/|v[=\/])([\w\-]{11,})/i);
                            if ( videoId ) {
                                url = '//www.youtube.com/embed/' + videoId[2];
                                if (autoplay) {
                                    attributes.push('autoplay=1');
                                }
                            }

                            // Vimeo
                            videoId = url.match(/vimeo\.com(\/video|\/channels\/.*?)?\/(\d+)/i);
                            if ( videoId ) {
                                url = '//player.vimeo.com/video/' + videoId[2];
                                if (autoplay) {
                                    attributes.push('autoplay=1');
                                }
                            }

                            // Create element
                            contentProps.attributes = {
                                src: url + ( attributes.length ? '?' + attributes.join('&') : '' ),
                                width: parseInt( width ),
                                height: parseInt( height ),
                                frameborder: 0,
                                allowfullscreen: ''
                            };

                            embedElementContent = editor.document.createElement('iframe', contentProps);
                        }

                        // Could not determine type
                        else {
                            alert('No URL or embed code was given');
                            return false;
                        }

                        // Add defining class to element content
                        embedElementContent.addClass( 'media-element-content' );

                        // If responsive, put embed content into container
                        if (responsive) {
                            embedElement = editor.document.createElement('div',
                                {
                                    attributes: {
                                        'class': 'media-element'
                                    },
                                    styles: {
                                        position: 'relative',
                                        'padding-bottom': '56.25%', /* 16:9 */
                                        'padding-top': '25px',
                                        height: 0
                                    }
                                }
                            );
                            embedElementContent.appendTo( embedElement );
                        }

                        // Else set embed element to content
                        else {
                            embedElementContent.addClass( 'media-element' );
                            embedElement = embedElementContent;
                        }

                        // Append embedElement to editor
                        editor.insertElement( embedElement );

                    }

                    return true;
                }

            }

        });

        // Command to open dialog
        editor.addCommand( 'mediahelper', new CKEDITOR.dialogCommand( 'MediaHelperDialog', {
            allowedContent: 'div[*],iframe[*],object[*]'
        } ) );

        // Toolbar Button
        editor.ui.addButton( 'MediaHelper', {

            label: 'Media Helper',
            command: 'mediahelper',
            toolbar: 'insert'

        });

    }

});
<|endoftext|>


<commit_before>frappe.ui.form.FormViewers = class FormViewers {
	constructor({ frm, parent }) {
		this.frm = frm;
		this.parent = parent;
		this.parent.tooltip({ title: __('Currently Viewing') });
	}

	refresh() {
		let users = this.frm.get_docinfo()['viewers'];
		let currently_viewing = users.current.filter(user => user != frappe.session.user);
		let avatar_group = frappe.avatar_group(currently_viewing, 5, {'align': 'left', 'overlap': true});
		this.parent.empty().append(avatar_group);
	}
};

frappe.ui.form.FormViewers.set_users = function(data, type) {
	const doctype = data.doctype;
	const docname = data.docname;
	const docinfo = frappe.model.get_docinfo(doctype, docname);

	const past_users = ((docinfo && docinfo[type]) || {}).past || [];
	const users = data.users || [];
	const new_users = users.filter(user => !past_users.includes(user));

	frappe.model.set_docinfo(doctype, docname, type, {
		past: past_users.concat(new_users),
		new: new_users,
		current: users
	});

	if (
		cur_frm &&
		cur_frm.doc &&
		cur_frm.doc.doctype === doctype &&
		cur_frm.doc.name == docname &&
		cur_frm.viewers
	) {
		cur_frm.viewers.refresh(true, type);
	}
};
<commit_msg>fix: Temporarily comment buggy code to avoid confusion<commit_after>frappe.ui.form.FormViewers = class FormViewers {
	constructor({ frm, parent }) {
		this.frm = frm;
		this.parent = parent;
		this.parent.tooltip({ title: __('Currently Viewing') });
	}

	refresh() {
		let users = this.frm.get_docinfo()['viewers'];
		let currently_viewing = users.current.filter(user => user != frappe.session.user);
		let avatar_group = frappe.avatar_group(currently_viewing, 5, {'align': 'left', 'overlap': true});
		// REDESIGN-TODO: fix this
		this.parent.empty(); //.append(avatar_group);
	}
};

frappe.ui.form.FormViewers.set_users = function(data, type) {
	const doctype = data.doctype;
	const docname = data.docname;
	const docinfo = frappe.model.get_docinfo(doctype, docname);

	const past_users = ((docinfo && docinfo[type]) || {}).past || [];
	const users = data.users || [];
	const new_users = users.filter(user => !past_users.includes(user));

	frappe.model.set_docinfo(doctype, docname, type, {
		past: past_users.concat(new_users),
		new: new_users,
		current: users
	});

	if (
		cur_frm &&
		cur_frm.doc &&
		cur_frm.doc.doctype === doctype &&
		cur_frm.doc.name == docname &&
		cur_frm.viewers
	) {
		cur_frm.viewers.refresh(true, type);
	}
};
<|endoftext|>