<commit_before>import React, { Component } from "react";
import ReactDOM from "react-dom";

import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import AvPause from "@material-ui/icons/pause";
import AvPlayArrow from "@material-ui/icons/PlayArrow";
import AvReplay from "@material-ui/icons/replay";
import { formatMilliseconds } from "../core/time";

class Remaining extends Component {
  constructor(props, context) {
    super(props);
    this.internalTimer = {
      startNew: opts => {
        this.props.timer.startNew(opts);
      },
      onTick: ms => {
        this.props.timer.onTick(ms);
      },
      stopActive: () => {
        this.props.timer.stopActive();
      }
    };
    this.state = {
      allottedMilliseconds: props.allottedMilliseconds || 0,
      remainingMilliseconds: props.allottedMilliseconds || 0,
      started: false
    };

    this.start = this.start.bind(this);
    this.pause = this.pause.bind(this);
    this.restart = this.restart.bind(this);
    this.renderStateMilliseconds = this.renderStateMilliseconds.bind(this);
    this.renderPlaybackButton = this.renderPlaybackButton.bind(this);
    this.finish = this.finish.bind(this);
    this.tick = this.tick.bind(this);
    this.hasFreshAllottedMilliseconds = this.hasFreshAllottedMilliseconds.bind(
      this
    );
    this.height = "24px";
  }
  componentWillReceiveProps(newProps) {
    this.initiateStartFromNewPropsIfNecessary(newProps);
  }
  hasFreshAllottedMilliseconds(props) {
    if (props.allottedMilliseconds === undefined) return false;
    if (props.allottedMilliseconds <= 0) return false;
    if (props.allottedMilliseconds != this.state.allottedMilliseconds) {
      return true;
    }
    if (props.started) return true;
    return false;
  }

  initiateStartFromNewPropsIfNecessary(newProps) {
    if (this.hasFreshAllottedMilliseconds(newProps)) {
      this.setState(
        {
          allottedMilliseconds: newProps.allottedMilliseconds,
          remainingMilliseconds: newProps.allottedMilliseconds
        },
        () => {
          // Prevents going to sleep when dragged to the
          // beginning but not yet released
          if (newProps.started) {
            this.start();
          } else {
            this.pause();
          }
        }
      );
    }
  }
  tick(milliseconds) {
    this.setState({
      remainingMilliseconds: milliseconds
    });
  }
  start() {
    let remaining = this.state.remainingMilliseconds;
    if (remaining === 0) {
      remaining = this.state.allottedMilliseconds;
    }
    this.setState({
      remainingMilliseconds: remaining,
      started: true
    });
    this.internalTimer.startNew({
      callback: this.finish,
      milliseconds: remaining,
      tickInterval: 1000,
      onTick: this.tick
    });
  }
  pause() {
    this.setState({
      started: false
    });
    this.internalTimer.stopActive();
  }
  restart() {
    this.pause();
    this.setState(
      {
        remainingMilliseconds: this.state.allottedMilliseconds
      },
      () => {
        this.start();
      }
    );
  }
  finish() {
    this.setState(
      {
        remainingMilliseconds: this.state.allottedMilliseconds,
        started: false
      },
      () => {
        this.pause();
        this.props.onFinished();
      }
    );
  }
  renderStateMilliseconds() {
    return (

        {formatMilliseconds(this.state.remainingMilliseconds)}

    );
  }
  render() {
    const buttonStyle = {
      color: this.props.theme.palette.text.secondary,
      height: this.height,
      width: this.height
    };
    const iconStyle = {
      height: this.height,
      width: this.height,
      margin: "0",
      padding: "0",
      position: "absolute"
    };
    return (

        <Typography
          color="textSecondary"
          style={{
            padding: "0",
            margin: "0",
            position: "relative",
            width: "80px",
            margin: "0 auto",
            height: this.height,
            whiteSpace: "nowrap"
          }}
        >
          {this.renderPlaybackButton(buttonStyle, iconStyle)}
          {this.renderStateMilliseconds()}
          {this.renderRestartButton(buttonStyle, iconStyle)}
        </Typography>

    );
  }
  renderRestartButton(buttonStyle, iconStyle) {
    const disabled =
      this.state.started ||
      this.state.remainingMilliseconds === this.state.allottedMilliseconds;
    const containerStyle = {
      position: "absolute",
      right: "-30px",
      top: "0",
      display: "inline-block",
      o
    };
    const button = (
      <IconButton
        id="restart"
        tooltip="Restart"
        onClick={this.restart}
        style={buttonStyle}
      >
        <AvReplay style={iconStyle} />
      </IconButton>
    );
    return {button};
  }
  renderPlaybackButton(buttonStyle, iconStyle) {
    const isStarted = this.state.started;
    let button;
    if (isStarted) {
      button = (
        <IconButton
          id="pause"
          tooltip="Pause"
          onClick={this.pause}
          style={buttonStyle}
        >
          <AvPause style={iconStyle} />
        </IconButton>
      );
    } else {
      button = (
        <IconButton
          id="start"
          tooltip="Start"
          onClick={this.start}
          style={buttonStyle}
        >
          <AvPlayArrow style={iconStyle} />
        </IconButton>
      );
    }
    const containerStyle = {
      position: "absolute",
      left: "-30px",
      top: "0",
      display: "inline-block"
    };
    return {button};
  }
}

Remaining.defaultProps = {
  onFinished: () => {}
};

export default Remaining;
<commit_msg>Fix syntax error<commit_after>import React, { Component } from "react";
import ReactDOM from "react-dom";

import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import AvPause from "@material-ui/icons/pause";
import AvPlayArrow from "@material-ui/icons/PlayArrow";
import AvReplay from "@material-ui/icons/replay";
import { formatMilliseconds } from "../core/time";

class Remaining extends Component {
  constructor(props, context) {
    super(props);
    this.internalTimer = {
      startNew: opts => {
        this.props.timer.startNew(opts);
      },
      onTick: ms => {
        this.props.timer.onTick(ms);
      },
      stopActive: () => {
        this.props.timer.stopActive();
      }
    };
    this.state = {
      allottedMilliseconds: props.allottedMilliseconds || 0,
      remainingMilliseconds: props.allottedMilliseconds || 0,
      started: false
    };

    this.start = this.start.bind(this);
    this.pause = this.pause.bind(this);
    this.restart = this.restart.bind(this);
    this.renderStateMilliseconds = this.renderStateMilliseconds.bind(this);
    this.renderPlaybackButton = this.renderPlaybackButton.bind(this);
    this.finish = this.finish.bind(this);
    this.tick = this.tick.bind(this);
    this.hasFreshAllottedMilliseconds = this.hasFreshAllottedMilliseconds.bind(
      this
    );
    this.height = "24px";
  }
  componentWillReceiveProps(newProps) {
    this.initiateStartFromNewPropsIfNecessary(newProps);
  }
  hasFreshAllottedMilliseconds(props) {
    if (props.allottedMilliseconds === undefined) return false;
    if (props.allottedMilliseconds <= 0) return false;
    if (props.allottedMilliseconds != this.state.allottedMilliseconds) {
      return true;
    }
    if (props.started) return true;
    return false;
  }

  initiateStartFromNewPropsIfNecessary(newProps) {
    if (this.hasFreshAllottedMilliseconds(newProps)) {
      this.setState(
        {
          allottedMilliseconds: newProps.allottedMilliseconds,
          remainingMilliseconds: newProps.allottedMilliseconds
        },
        () => {
          // Prevents going to sleep when dragged to the
          // beginning but not yet released
          if (newProps.started) {
            this.start();
          } else {
            this.pause();
          }
        }
      );
    }
  }
  tick(milliseconds) {
    this.setState({
      remainingMilliseconds: milliseconds
    });
  }
  start() {
    let remaining = this.state.remainingMilliseconds;
    if (remaining === 0) {
      remaining = this.state.allottedMilliseconds;
    }
    this.setState({
      remainingMilliseconds: remaining,
      started: true
    });
    this.internalTimer.startNew({
      callback: this.finish,
      milliseconds: remaining,
      tickInterval: 1000,
      onTick: this.tick
    });
  }
  pause() {
    this.setState({
      started: false
    });
    this.internalTimer.stopActive();
  }
  restart() {
    this.pause();
    this.setState(
      {
        remainingMilliseconds: this.state.allottedMilliseconds
      },
      () => {
        this.start();
      }
    );
  }
  finish() {
    this.setState(
      {
        remainingMilliseconds: this.state.allottedMilliseconds,
        started: false
      },
      () => {
        this.pause();
        this.props.onFinished();
      }
    );
  }
  renderStateMilliseconds() {
    return (

        {formatMilliseconds(this.state.remainingMilliseconds)}

    );
  }
  render() {
    const buttonStyle = {
      color: this.props.theme.palette.text.secondary,
      height: this.height,
      width: this.height
    };
    const iconStyle = {
      height: this.height,
      width: this.height,
      margin: "0",
      padding: "0",
      position: "absolute"
    };
    return (

        <Typography
          color="textSecondary"
          style={{
            padding: "0",
            margin: "0",
            position: "relative",
            width: "80px",
            margin: "0 auto",
            height: this.height,
            whiteSpace: "nowrap"
          }}
        >
          {this.renderPlaybackButton(buttonStyle, iconStyle)}
          {this.renderStateMilliseconds()}
          {this.renderRestartButton(buttonStyle, iconStyle)}
        </Typography>

    );
  }
  renderRestartButton(buttonStyle, iconStyle) {
    const disabled =
      this.state.started ||
      this.state.remainingMilliseconds === this.state.allottedMilliseconds;
    const containerStyle = {
      position: "absolute",
      right: "-30px",
      top: "0",
      display: "inline-block"
    };
    const button = (
      <IconButton
        id="restart"
        tooltip="Restart"
        onClick={this.restart}
        style={buttonStyle}
      >
        <AvReplay style={iconStyle} />
      </IconButton>
    );
    return {button};
  }
  renderPlaybackButton(buttonStyle, iconStyle) {
    const isStarted = this.state.started;
    let button;
    if (isStarted) {
      button = (
        <IconButton
          id="pause"
          tooltip="Pause"
          onClick={this.pause}
          style={buttonStyle}
        >
          <AvPause style={iconStyle} />
        </IconButton>
      );
    } else {
      button = (
        <IconButton
          id="start"
          tooltip="Start"
          onClick={this.start}
          style={buttonStyle}
        >
          <AvPlayArrow style={iconStyle} />
        </IconButton>
      );
    }
    const containerStyle = {
      position: "absolute",
      left: "-30px",
      top: "0",
      display: "inline-block"
    };
    return {button};
  }
}

Remaining.defaultProps = {
  onFinished: () => {}
};

export default Remaining;
<|endoftext|>


<commit_before>import _ from 'lodash';
import NestedComponent from '../_classes/nested/NestedComponent';

export default class TabsComponent extends NestedComponent {
  static schema(...extend) {
    return NestedComponent.schema({
      label: 'Tabs',
      type: 'tabs',
      input: false,
      key: 'tabs',
      persistent: false,
      components: [
        {
          label: 'Tab 1',
          key: 'tab1',
          components: [],
        },
      ],
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Tabs',
      group: 'layout',
      icon: 'folder-o',
      weight: 50,
      documentation: 'http://help.form.io/userguide/#tabs',
      schema: TabsComponent.schema(),
    };
  }

  get defaultSchema() {
    return TabsComponent.schema();
  }

  get schema() {
    const schema = super.schema;
    // We need to clone this because the builder uses the "components" reference and this would reset that reference.
    const components = _.cloneDeep(this.component.components);
    schema.components = components.map((tab, index) => {
      if (index === this.currentTab) {
        tab.components = this.tabs[index].map((component) => component.schema);
      }
      return tab;
    });

    return schema;
  }

  get tabKey() {
    return `tab-${this.key}`;
  }

  get tabLikey() {
    return `tabLi-${this.key}`;
  }

  get tabLinkKey() {
    return `tabLink-${this.key}`;
  }

  constructor(...args) {
    super(...args);
    this.currentTab = 0;
    this.noField = true;
  }

  init() {
    this.components = [];
    this.tabs = [];
    _.each(this.component.components, (tab, index) => {
      this.tabs[index] = [];
      // Initialize empty tabs.
      tab.components = tab.components || [];
      _.each(tab.components, (comp) => {
        const component = this.createComponent(comp);
        component.tab = index;
        this.tabs[index].push(component);
      });
    });
  }

  render() {
    return super.render(this.renderTemplate('tab', {
      tabKey: this.tabKey,
      tabLikey: this.tabLikey,
      tabLinkKey: this.tabLinkKey,
      currentTab: this.currentTab,
      tabComponents: this.tabs.map(tab => this.renderComponents(tab))
    }, (this.options.flatten ? 'flat' : 'form')));
  }

  attach(element) {
    this.loadRefs(element, { [this.tabLinkKey]: 'multiple', [this.tabKey]: 'multiple', [this.tabLikey]: 'multiple' });
    const superAttach = super.attach(element);
    this.refs[this.tabLinkKey].forEach((tabLink, index) => {
      this.addEventListener(tabLink, 'click', (event) => {
        event.preventDefault();
        this.setTab(index);
      });
    });
    this.refs[this.tabKey].forEach((tab, index) => {
      this.attachComponents(tab, this.tabs[index], this.component.components[index].components);
    });
    return superAttach;
  }

  detach(all) {
    super.detach(all);
  }

  /**
   * Set the current tab.
   *
   * @param index
   */
  setTab(index) {
    if (
      !this.tabs ||
      !this.tabs[index] ||
      !this.refs[this.tabKey] ||
      !this.refs[this.tabKey][index]
    ) {
      return;
    }

    this.currentTab = index;

    _.each(this.refs[this.tabKey], (tab) => {
      this.removeClass(tab, 'formio-tab-panel-active');
      tab.style.display = 'none';
    });
    this.addClass(this.refs[this.tabKey][index], 'formio-tab-panel-active');
    this.refs[this.tabKey][index].style.display = 'block';

    _.each(this.refs[this.tabLinkKey], (tabLink, tabIndex) => {
      if (this.refs[this.tabLinkKey][tabIndex]) {
        this.removeClass(tabLink, 'formio-tab-link-active');
      }
      if (this.refs[this.tabLikey][tabIndex]) {
        this.removeClass(this.refs[this.tabLikey][tabIndex], 'formio-tab-link-container-active');
      }
    });
    if (this.refs[this.tabLikey][index]) {
      this.addClass(this.refs[this.tabLikey][index], 'formio-tab-link-container-active');
    }
    if (this.refs[this.tabLinkKey][index]) {
      this.addClass(this.refs[this.tabLinkKey][index], 'formio-tab-link-active');
    }
    this.triggerChange();
  }
}
<commit_msg>Remove unnecessary if statement<commit_after>import _ from 'lodash';
import NestedComponent from '../_classes/nested/NestedComponent';

export default class TabsComponent extends NestedComponent {
  static schema(...extend) {
    return NestedComponent.schema({
      label: 'Tabs',
      type: 'tabs',
      input: false,
      key: 'tabs',
      persistent: false,
      components: [
        {
          label: 'Tab 1',
          key: 'tab1',
          components: [],
        },
      ],
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Tabs',
      group: 'layout',
      icon: 'folder-o',
      weight: 50,
      documentation: 'http://help.form.io/userguide/#tabs',
      schema: TabsComponent.schema(),
    };
  }

  get defaultSchema() {
    return TabsComponent.schema();
  }

  get schema() {
    const schema = super.schema;
    // We need to clone this because the builder uses the "components" reference and this would reset that reference.
    const components = _.cloneDeep(this.component.components);
    schema.components = components.map((tab, index) => {
      tab.components = this.tabs[index].map((component) => component.schema);
      return tab;
    });

    return schema;
  }

  get tabKey() {
    return `tab-${this.key}`;
  }

  get tabLikey() {
    return `tabLi-${this.key}`;
  }

  get tabLinkKey() {
    return `tabLink-${this.key}`;
  }

  constructor(...args) {
    super(...args);
    this.currentTab = 0;
    this.noField = true;
  }

  init() {
    this.components = [];
    this.tabs = [];
    _.each(this.component.components, (tab, index) => {
      this.tabs[index] = [];
      // Initialize empty tabs.
      tab.components = tab.components || [];
      _.each(tab.components, (comp) => {
        const component = this.createComponent(comp);
        component.tab = index;
        this.tabs[index].push(component);
      });
    });
  }

  render() {
    return super.render(this.renderTemplate('tab', {
      tabKey: this.tabKey,
      tabLikey: this.tabLikey,
      tabLinkKey: this.tabLinkKey,
      currentTab: this.currentTab,
      tabComponents: this.tabs.map(tab => this.renderComponents(tab))
    }, (this.options.flatten ? 'flat' : 'form')));
  }

  attach(element) {
    this.loadRefs(element, { [this.tabLinkKey]: 'multiple', [this.tabKey]: 'multiple', [this.tabLikey]: 'multiple' });
    const superAttach = super.attach(element);
    this.refs[this.tabLinkKey].forEach((tabLink, index) => {
      this.addEventListener(tabLink, 'click', (event) => {
        event.preventDefault();
        this.setTab(index);
      });
    });
    this.refs[this.tabKey].forEach((tab, index) => {
      this.attachComponents(tab, this.tabs[index], this.component.components[index].components);
    });
    return superAttach;
  }

  detach(all) {
    super.detach(all);
  }

  /**
   * Set the current tab.
   *
   * @param index
   */
  setTab(index) {
    if (
      !this.tabs ||
      !this.tabs[index] ||
      !this.refs[this.tabKey] ||
      !this.refs[this.tabKey][index]
    ) {
      return;
    }

    this.currentTab = index;

    _.each(this.refs[this.tabKey], (tab) => {
      this.removeClass(tab, 'formio-tab-panel-active');
      tab.style.display = 'none';
    });
    this.addClass(this.refs[this.tabKey][index], 'formio-tab-panel-active');
    this.refs[this.tabKey][index].style.display = 'block';

    _.each(this.refs[this.tabLinkKey], (tabLink, tabIndex) => {
      if (this.refs[this.tabLinkKey][tabIndex]) {
        this.removeClass(tabLink, 'formio-tab-link-active');
      }
      if (this.refs[this.tabLikey][tabIndex]) {
        this.removeClass(this.refs[this.tabLikey][tabIndex], 'formio-tab-link-container-active');
      }
    });
    if (this.refs[this.tabLikey][index]) {
      this.addClass(this.refs[this.tabLikey][index], 'formio-tab-link-container-active');
    }
    if (this.refs[this.tabLinkKey][index]) {
      this.addClass(this.refs[this.tabLinkKey][index], 'formio-tab-link-active');
    }
    this.triggerChange();
  }
}
<|endoftext|>


<commit_before>import $ from 'dom7';
import Utils from '../../utils/utils';

const Tab = {
  show(...args) {
    const app = this;
    let tabEl;
    let tabLinkEl;
    let animate;
    let tabRoute;
    if (args.length === 1 && args[0].constructor === Object) {
      tabEl = args[0].tabEl;
      tabLinkEl = args[0].tabLinkEl;
      animate = args[0].animate;
      tabRoute = args[0].tabRoute;
    } else {
      [tabEl, tabLinkEl, animate, tabRoute] = args;
      if (typeof args[1] === 'boolean') {
        [tabEl, animate, tabLinkEl, tabRoute] = args;
        if (args.length > 2 && tabLinkEl.constructor === Object) {
          [tabEl, animate, tabRoute, tabLinkEl] = args;
        }
      }
    }
    if (typeof animate === 'undefined') animate = true;

    const $newTabEl = $(tabEl);

    if ($newTabEl.length === 0 || $newTabEl.hasClass('tab-active')) {
      return {
        $newTabEl,
        newTabEl: $newTabEl[0],
      };
    }

    let $tabLinkEl;
    if (tabLinkEl) $tabLinkEl = $(tabLinkEl);

    const $tabsEl = $newTabEl.parent('.tabs');
    if ($tabsEl.length === 0) {
      return {
        $newTabEl,
        newTabEl: $newTabEl[0],
      };
    }

    // Release swipeouts in hidden tabs
    if (app.swipeout) app.swipeout.allowOpen = true;

    // Animated tabs
    const tabsChangedCallbacks = [];

    function onTabsChanged(callback) {
      tabsChangedCallbacks.push(callback);
    }
    function tabsChanged() {
      tabsChangedCallbacks.forEach((callback) => {
        callback();
      });
    }

    let animated = false;

    if ($tabsEl.parent().hasClass('tabs-animated-wrap')) {
      $tabsEl.parent()[animate ? 'removeClass' : 'addClass']('not-animated');

      const transitionDuration = parseFloat($tabsEl.css('transition-duration').replace(',', '.'));
      if (animate && transitionDuration) {
        $tabsEl.transitionEnd(tabsChanged);
        animated = true;
      }

      const tabsTranslate = (app.rtl ? $newTabEl.index() : -$newTabEl.index()) * 100;
      $tabsEl.transform(`translate3d(${tabsTranslate}%,0,0)`);
    }

    // Swipeable tabs
    if ($tabsEl.parent().hasClass('tabs-swipeable-wrap') && app.swiper) {
      const swiper = $tabsEl.parent()[0].swiper;
      if (swiper && swiper.activeIndex !== $newTabEl.index()) {
        animated = true;
        swiper
          .once('slideChangeTransitionEnd', () => {
            tabsChanged();
          })
          .slideTo($newTabEl.index(), animate ? undefined : 0);
      }
    }

    // Remove active class from old tabs
    const $oldTabEl = $tabsEl.children('.tab-active');
    $oldTabEl
      .removeClass('tab-active')
      .trigger('tab:hide');
    app.emit('tabHide', $oldTabEl[0]);

    // Trigger 'show' event on new tab
    $newTabEl
      .addClass('tab-active')
      .trigger('tab:show');
    app.emit('tabShow', $newTabEl[0]);

    // Find related link for new tab
    if (!$tabLinkEl) {
      // Search by id
      if (typeof tabEl === 'string') $tabLinkEl = $(`.tab-link[href="${tabEl}"]`);
      else $tabLinkEl = $(`.tab-link[href="#${$newTabEl.attr('id')}"]`);
      // Search by data-tab
      if (!$tabLinkEl || ($tabLinkEl && $tabLinkEl.length === 0)) {
        $('[data-tab]').each((index, el) => {
          if ($newTabEl.is($(el).attr('data-tab'))) $tabLinkEl = $(el);
        });
      }
      if (tabRoute && (!$tabLinkEl || ($tabLinkEl && $tabLinkEl.length === 0))) {
        $tabLinkEl = $(`[data-route-tab-id="${tabRoute.route.tab.id}"]`);
        if ($tabLinkEl.length === 0) {
          $tabLinkEl = $(`.tab-link[href="${tabRoute.url}"]`);
        }
      }
      if ($tabLinkEl.length > 1 && $newTabEl.parents('.page').length) {
        // eslint-disable-next-line
        $tabLinkEl = $tabLinkEl.filter((index, tabLinkElement) => {
          return $(tabLinkElement).parents('.page')[0] === $newTabEl.parents('.page')[0];
        });
      }
    }
    if ($tabLinkEl.length > 0) {
      // Find related link for old tab
      let $oldTabLinkEl;
      if ($oldTabEl && $oldTabEl.length > 0) {
        // Search by id
        const oldTabId = $oldTabEl.attr('id');
        if (oldTabId) $oldTabLinkEl = $(`.tab-link[href="#${oldTabId}"]`);
        // Search by data-tab
        if (!$oldTabLinkEl || ($oldTabLinkEl && $oldTabLinkEl.length === 0)) {
          $('[data-tab]').each((index, tabLinkElement) => {
            if ($oldTabEl.is($(tabLinkElement).attr('data-tab'))) $oldTabLinkEl = $(tabLinkElement);
          });
        }
        if (!$oldTabLinkEl || ($oldTabLinkEl && $oldTabLinkEl.length === 0)) {
          $oldTabLinkEl = $tabLinkEl.siblings('.tab-link-active');
        }
      } else if (tabRoute) {
        $oldTabLinkEl = $tabLinkEl.siblings('.tab-link-active');
      }

      if ($oldTabLinkEl && $oldTabLinkEl.length > 1 && $oldTabEl && $oldTabEl.parents('.page').length) {
        // eslint-disable-next-line
        $oldTabLinkEl = $oldTabLinkEl.filter((index, tabLinkElement) => {
          return $(tabLinkElement).parents('.page')[0] === $oldTabEl.parents('.page')[0];
        });
      }

      if ($oldTabLinkEl && $oldTabLinkEl.length > 0) $oldTabLinkEl.removeClass('tab-link-active');

      // Update links' classes
      if ($tabLinkEl && $tabLinkEl.length > 0) {
        $tabLinkEl.addClass('tab-link-active');
        // Material Highlight
        if (app.theme === 'md' && app.toolbar) {
          const $tabbarEl = $tabLinkEl.parents('.tabbar, .tabbar-labels');
          if ($tabbarEl.length > 0) {
            app.toolbar.setHighlight($tabbarEl);
          }
        }
      }
    }
    return {
      $newTabEl,
      newTabEl: $newTabEl[0],
      $oldTabEl,
      oldTabEl: $oldTabEl[0],
      onTabsChanged,
      animated,
    };
  },
};
export default {
  name: 'tabs',
  create() {
    const app = this;
    Utils.extend(app, {
      tab: {
        show: Tab.show.bind(app),
      },
    });
  },
  clicks: {
    '.tab-link': function tabLinkClick($clickedEl, data = {}) {
      const app = this;
      if (($clickedEl.attr('href') && $clickedEl.attr('href').indexOf('#') === 0) || $clickedEl.attr('data-tab')) {
        app.tab.show({
          tabEl: data.tab || $clickedEl.attr('href'),
          tabLinkEl: $clickedEl,
          animate: data.animate,
        });
      }
    },
  },
};
<commit_msg>Fix routable tab links in navbar<commit_after>import $ from 'dom7';
import Utils from '../../utils/utils';

const Tab = {
  show(...args) {
    const app = this;
    let tabEl;
    let tabLinkEl;
    let animate;
    let tabRoute;
    if (args.length === 1 && args[0].constructor === Object) {
      tabEl = args[0].tabEl;
      tabLinkEl = args[0].tabLinkEl;
      animate = args[0].animate;
      tabRoute = args[0].tabRoute;
    } else {
      [tabEl, tabLinkEl, animate, tabRoute] = args;
      if (typeof args[1] === 'boolean') {
        [tabEl, animate, tabLinkEl, tabRoute] = args;
        if (args.length > 2 && tabLinkEl.constructor === Object) {
          [tabEl, animate, tabRoute, tabLinkEl] = args;
        }
      }
    }
    if (typeof animate === 'undefined') animate = true;

    const $newTabEl = $(tabEl);

    if ($newTabEl.length === 0 || $newTabEl.hasClass('tab-active')) {
      return {
        $newTabEl,
        newTabEl: $newTabEl[0],
      };
    }

    let $tabLinkEl;
    if (tabLinkEl) $tabLinkEl = $(tabLinkEl);

    const $tabsEl = $newTabEl.parent('.tabs');
    if ($tabsEl.length === 0) {
      return {
        $newTabEl,
        newTabEl: $newTabEl[0],
      };
    }

    // Release swipeouts in hidden tabs
    if (app.swipeout) app.swipeout.allowOpen = true;

    // Animated tabs
    const tabsChangedCallbacks = [];

    function onTabsChanged(callback) {
      tabsChangedCallbacks.push(callback);
    }
    function tabsChanged() {
      tabsChangedCallbacks.forEach((callback) => {
        callback();
      });
    }

    let animated = false;

    if ($tabsEl.parent().hasClass('tabs-animated-wrap')) {
      $tabsEl.parent()[animate ? 'removeClass' : 'addClass']('not-animated');

      const transitionDuration = parseFloat($tabsEl.css('transition-duration').replace(',', '.'));
      if (animate && transitionDuration) {
        $tabsEl.transitionEnd(tabsChanged);
        animated = true;
      }

      const tabsTranslate = (app.rtl ? $newTabEl.index() : -$newTabEl.index()) * 100;
      $tabsEl.transform(`translate3d(${tabsTranslate}%,0,0)`);
    }

    // Swipeable tabs
    if ($tabsEl.parent().hasClass('tabs-swipeable-wrap') && app.swiper) {
      const swiper = $tabsEl.parent()[0].swiper;
      if (swiper && swiper.activeIndex !== $newTabEl.index()) {
        animated = true;
        swiper
          .once('slideChangeTransitionEnd', () => {
            tabsChanged();
          })
          .slideTo($newTabEl.index(), animate ? undefined : 0);
      }
    }

    // Remove active class from old tabs
    const $oldTabEl = $tabsEl.children('.tab-active');
    $oldTabEl
      .removeClass('tab-active')
      .trigger('tab:hide');
    app.emit('tabHide', $oldTabEl[0]);

    // Trigger 'show' event on new tab
    $newTabEl
      .addClass('tab-active')
      .trigger('tab:show');
    app.emit('tabShow', $newTabEl[0]);

    // Find related link for new tab
    if (!$tabLinkEl) {
      // Search by id
      if (typeof tabEl === 'string') $tabLinkEl = $(`.tab-link[href="${tabEl}"]`);
      else $tabLinkEl = $(`.tab-link[href="#${$newTabEl.attr('id')}"]`);
      // Search by data-tab
      if (!$tabLinkEl || ($tabLinkEl && $tabLinkEl.length === 0)) {
        $('[data-tab]').each((index, el) => {
          if ($newTabEl.is($(el).attr('data-tab'))) $tabLinkEl = $(el);
        });
      }
      if (tabRoute && (!$tabLinkEl || ($tabLinkEl && $tabLinkEl.length === 0))) {
        $tabLinkEl = $(`[data-route-tab-id="${tabRoute.route.tab.id}"]`);
        if ($tabLinkEl.length === 0) {
          $tabLinkEl = $(`.tab-link[href="${tabRoute.url}"]`);
        }
      }
      if ($tabLinkEl.length > 1 && $newTabEl.parents('.page').length) {
        // eslint-disable-next-line
        $tabLinkEl = $tabLinkEl.filter((index, tabLinkElement) => {
          return $(tabLinkElement).parents('.page')[0] === $newTabEl.parents('.page')[0];
        });
        if (app.theme === 'ios' && $tabLinkEl.length === 0 && tabRoute) {
          const $pageEl = $newTabEl.parents('.page');
          const $navbarEl = $(app.navbar.getElByPage($pageEl));
          $tabLinkEl = $navbarEl.find(`[data-route-tab-id="${tabRoute.route.tab.id}"]`);
          if ($tabLinkEl.length === 0) {
            $tabLinkEl = $navbarEl.find(`.tab-link[href="${tabRoute.url}"]`);
          }
        }
      }
    }
    if ($tabLinkEl.length > 0) {
      // Find related link for old tab
      let $oldTabLinkEl;
      if ($oldTabEl && $oldTabEl.length > 0) {
        // Search by id
        const oldTabId = $oldTabEl.attr('id');
        if (oldTabId) $oldTabLinkEl = $(`.tab-link[href="#${oldTabId}"]`);
        // Search by data-tab
        if (!$oldTabLinkEl || ($oldTabLinkEl && $oldTabLinkEl.length === 0)) {
          $('[data-tab]').each((index, tabLinkElement) => {
            if ($oldTabEl.is($(tabLinkElement).attr('data-tab'))) $oldTabLinkEl = $(tabLinkElement);
          });
        }
        if (!$oldTabLinkEl || ($oldTabLinkEl && $oldTabLinkEl.length === 0)) {
          $oldTabLinkEl = $tabLinkEl.siblings('.tab-link-active');
        }
      } else if (tabRoute) {
        $oldTabLinkEl = $tabLinkEl.siblings('.tab-link-active');
      }

      if ($oldTabLinkEl && $oldTabLinkEl.length > 1 && $oldTabEl && $oldTabEl.parents('.page').length) {
        // eslint-disable-next-line
        $oldTabLinkEl = $oldTabLinkEl.filter((index, tabLinkElement) => {
          return $(tabLinkElement).parents('.page')[0] === $oldTabEl.parents('.page')[0];
        });
      }

      if ($oldTabLinkEl && $oldTabLinkEl.length > 0) $oldTabLinkEl.removeClass('tab-link-active');

      // Update links' classes
      if ($tabLinkEl && $tabLinkEl.length > 0) {
        $tabLinkEl.addClass('tab-link-active');
        // Material Highlight
        if (app.theme === 'md' && app.toolbar) {
          const $tabbarEl = $tabLinkEl.parents('.tabbar, .tabbar-labels');
          if ($tabbarEl.length > 0) {
            app.toolbar.setHighlight($tabbarEl);
          }
        }
      }
    }
    return {
      $newTabEl,
      newTabEl: $newTabEl[0],
      $oldTabEl,
      oldTabEl: $oldTabEl[0],
      onTabsChanged,
      animated,
    };
  },
};
export default {
  name: 'tabs',
  create() {
    const app = this;
    Utils.extend(app, {
      tab: {
        show: Tab.show.bind(app),
      },
    });
  },
  clicks: {
    '.tab-link': function tabLinkClick($clickedEl, data = {}) {
      const app = this;
      if (($clickedEl.attr('href') && $clickedEl.attr('href').indexOf('#') === 0) || $clickedEl.attr('data-tab')) {
        app.tab.show({
          tabEl: data.tab || $clickedEl.attr('href'),
          tabLinkEl: $clickedEl,
          animate: data.animate,
        });
      }
    },
  },
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import Component from '../_classes/component/Component';
import Components from '../Components';
import NestedComponent from '../_classes/nested/NestedComponent';
import Node from './Node';
import NativePromise from 'native-promise-only';

export default class TreeComponent extends NestedComponent {
  static schema(...extend) {
    return NestedComponent.schema({
      label: 'Tree',
      key: 'tree',
      type: 'tree',
      clearOnHide: true,
      input: true,
      tree: true,
      components: [],
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Tree',
      icon: 'indent',
      group: 'data',
      weight: 40,
      schema: TreeComponent.schema(),
    };
  }

  constructor(...args) {
    super(...args);
    this.type = 'tree';
  }

  get emptyValue() {
    return {};
  }

  get viewComponents() {
    if (!this.viewComponentsInstantiated) {
      this.viewComponentsInstantiated = true;
      this._viewComponents = this.createComponents({});
    }

    return this._viewComponents;
  }

  init() {
    if (this.builderMode) {
      return super.init();
    }

    this.components = [];
    this.componentOptions = {
      ...this.options,
      parent: this,
      root: this.root || this,
    };
    this.setRoot();
    this.viewComponentsInstantiated = false;
    this._viewComponents = [];
  }

  destroy() {
    super.destroy();

    if (!this.builderMode) {
      this.removeComponents(this._viewComponents);
    }
  }

  createComponents(data, node) {
    const components = this.componentComponents.map(
      (component) => Components.create(component, this.componentOptions, data),
    );

    if (node) {
      this.checkNode(this.data, node);
    }

    return components;
  }

  removeComponents(components) {
    return components.map((component) => component.destroy());
  }

  render() {
    if (this.builderMode) {
      return super.render();
    }

    return super.render(this.renderTree(this.tree));
  }

  renderTree(node = {}, odd = true) {
    const childNodes = (node.hasChildren && !node.collapsed)
      ? this.renderChildNodes(node.children, !odd)
      : [];
    const content = node.changing
      ? this.renderEdit(node)
      : this.renderView(node);

    return this.renderTemplate('tree', {
      odd,
      childNodes,
      content,
      node,
    });
  }

  renderChildNodes(nodes = [], odd) {
    return nodes.map((node) => this.renderTree(node, odd));
  }

  renderEdit(node = {}) {
    return this.renderTemplate('treeEdit', {
      children: this.renderComponents(node.components),
      node,
    });
  }

  renderView(node = {}) {
    return this.renderTemplate('treeView', {
      values: this.viewComponents.map((component) => {
        component.data = node.data;
        component.checkComponentConditions(node.data);
        return component.getView(component.dataValue);
      }),
      nodeData: node.data,
      node,
    });
  }

  attach(element) {
    if (this.builderMode) {
      return super.attach(element);
    }

    this.loadRefs(element, {
      root: 'single',
    });

    return NativePromise.all([
      super.attach(element),
      this.attachNode(this.refs.root, this.tree),
    ]);
  }

  attachNode(element, node) {
    if (!element) {
      return NativePromise.resolve();
    }

    let componentsPromise = NativePromise.resolve();
    let childrenPromise = NativePromise.resolve();

    node.refs = _.reduce(
      element.children,
      (refs, child) => (
        child.hasAttribute('ref')
          ? {
            ...refs,
            [child.getAttribute('ref')]: child,
          }
          : refs
      ),
      {},
    );

    if (node.refs.content) {
      this.attachActions(node);
      componentsPromise = this.attachComponents(node);
    }

    if (node.refs.childNodes) {
      childrenPromise = this.attachChildren(node);
    }

    return NativePromise.all([
      componentsPromise,
      childrenPromise,
    ]);
  }

  attachActions(node) {
    this.loadRefs.call(node, node.refs.content, {
      addChild: 'single',
      cancelNode: 'single',
      editNode: 'single',
      removeNode: 'single',
      revertNode: 'single',
      saveNode: 'single',
      toggleNode: 'single',
    });

    if (node.refs.addChild) {
      this.addEventListener(node.refs.addChild, 'click', () => {
        this.addChild(node);
      });
    }

    if (node.refs.cancelNode) {
      this.addEventListener(node.refs.cancelNode, 'click', () => {
        this.cancelNode(node);
      });
    }

    if (node.refs.editNode) {
      this.addEventListener(node.refs.editNode, 'click', () => {
        this.editNode(node);
      });
    }

    if (node.refs.removeNode) {
      this.addEventListener(node.refs.removeNode, 'click', () => {
        this.removeNode(node);
      });
    }

    if (node.refs.revertNode) {
      this.addEventListener(node.refs.revertNode, 'click', () => {
        this.revertNode(node);
      });
    }

    if (node.refs.saveNode) {
      this.addEventListener(node.refs.saveNode, 'click', () => {
        this.saveNode(node);
      });
    }

    if (node.refs.toggleNode) {
      this.addEventListener(node.refs.toggleNode, 'click', () => {
        this.toggleNode(node);
      });
    }
  }

  attachComponents(node, ...args) {
    if (this.builderMode) {
      return super.attachComponents.call(this, node, ...args);
    }

    this.loadRefs.call(node, node.refs.content, {
      nodeEdit: 'single',
    });

    return node.refs.nodeEdit
      ? super.attachComponents(node.refs.nodeEdit, node.components)
      : NativePromise.resolve();
  }

  attachChildren(node) {
    const childElements = node.refs.childNodes.children;

    return NativePromise.all(
      _.map(
        childElements,
        (childElement, index) => this.attachNode(childElement, node.children[index]),
      ),
    );
  }

  setValue(value) {
    const changed = this.updateValue(value);
    this.setRoot();
    return changed;
  }

  addChild(parent) {
    if (this.options.readOnly || parent.new) {
      return;
    }

    this.hook('tree.addChild', {
      parent,
      component: this,
    }, () => {
      const child = parent.addChild();
      this.redraw();

      return child;
    });
  }

  cancelNode(node) {
    if (this.options.readOnly) {
      return;
    }

    this.hook('tree.cancelNode', {
      node,
      component: this,
    }, () => {
      if (node.isRoot) {
        this.removeRoot();
      }
      else {
        node.cancel();
        this.redraw();
      }

      return node;
    });
  }

  editNode(node) {
    if (this.options.readOnly || node.new) {
      return;
    }

    this.hook('tree.editNode', {
      node,
      component: this,
    }, () => {
      node.edit();
      this.redraw();

      return node;
    });
  }

  removeNode(node) {
    if (this.options.readOnly || node.new) {
      return;
    }

    this.hook('tree.removeNode', {
      node,
      component: this,
    }, () => {
      if (node.isRoot) {
        this.removeRoot();
      }
      else {
        node.remove();
        this.updateTree();
      }

      return node;
    });
  }

  revertNode(node) {
    if (this.options.readOnly || !node.revertAvailable) {
      return;
    }

    this.hook('tree.revertNode', {
      node,
      component: this,
    }, () => {
      node.revert();
      this.updateTree();

      return node;
    });
  }

  saveNode(node) {
    if (this.options.readOnly) {
      return;
    }

    this.hook('tree.saveNode', {
      node,
      component: this,
    }, () => {
      node.save();
      this.updateTree();

      return node;
    });
  }

  toggleNode(node) {
    this.hook('tree.toggleNode', {
      node,
      component: this,
    }, () => {
      node.collapsed = !node.collapsed;
      this.redraw();

      return node;
    });
  }

  removeRoot() {
    if (this.options.readOnly) {
      return;
    }

    this.dataValue = this.defaultValue;
    this.setRoot();
    this.redraw();
  }

  setRoot() {
    const value = this.dataValue;
    this.tree = new Node(null, value, {
      isNew: !value.data,
      createComponents: this.createComponents.bind(this),
      checkNode: this.checkNode.bind(this, this.data),
      removeComponents: this.removeComponents,
    });
    this.hook('tree.setRoot', {
      root: this.tree,
      component: this,
    });
  }

  getValue() {
    return this.dataValue;
  }

  updateTree() {
    this.updateValue(this.tree.value);
    this.redraw();
  }

  checkData(data, flags, row) {
    return this.checkNode(data, this.tree, flags, row);
  }

  checkNode(data, node, flags, row) {
    return node.children.reduce(
      (result, child) => this.checkNode(data, child, flags, row) && result,
      super.checkData(data, flags, node.data, node.components),
    );
  }
}

TreeComponent.prototype.hasChanged = Component.prototype.hasChanged;
TreeComponent.prototype.updateValue = Component.prototype.updateValue;
<commit_msg>Fixed Tree component.<commit_after>import _ from 'lodash';
import Component from '../_classes/component/Component';
import Components from '../Components';
import NestedComponent from '../_classes/nested/NestedComponent';
import Node from './Node';
import NativePromise from 'native-promise-only';

export default class TreeComponent extends NestedComponent {
  static schema(...extend) {
    return NestedComponent.schema({
      label: 'Tree',
      key: 'tree',
      type: 'tree',
      clearOnHide: true,
      input: true,
      tree: true,
      components: [],
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Tree',
      icon: 'indent',
      group: 'data',
      weight: 40,
      schema: TreeComponent.schema(),
    };
  }

  constructor(...args) {
    super(...args);
    this.type = 'tree';
  }

  get emptyValue() {
    return {};
  }

  get viewComponents() {
    if (!this.viewComponentsInstantiated) {
      this.viewComponentsInstantiated = true;
      this._viewComponents = this.createComponents({});
    }

    return this._viewComponents;
  }

  init() {
    if (this.builderMode) {
      return super.init();
    }

    this.components = [];
    this.componentOptions = {
      ...this.options,
      parent: this,
      root: this.root || this,
    };
    this.setRoot();
    this.viewComponentsInstantiated = false;
    this._viewComponents = [];
  }

  destroy() {
    super.destroy();

    if (!this.builderMode) {
      this.removeComponents(this._viewComponents);
    }
  }

  createComponents(data, node) {
    const components = this.componentComponents.map(
      (component) => Components.create(component, this.componentOptions, data),
    );

    if (node) {
      this.checkNode(this.data, node);
    }

    return components;
  }

  removeComponents(components) {
    return components.map((component) => component.destroy());
  }

  render() {
    if (this.builderMode) {
      return super.render();
    }

    return super.render(this.renderTree(this.treeRoot));
  }

  renderTree(node = {}, odd = true) {
    const childNodes = (node.hasChildren && !node.collapsed)
      ? this.renderChildNodes(node.children, !odd)
      : [];
    const content = node.changing
      ? this.renderEdit(node)
      : this.renderView(node);

    return this.renderTemplate('tree', {
      odd,
      childNodes,
      content,
      node,
    });
  }

  renderChildNodes(nodes = [], odd) {
    return nodes.map((node) => this.renderTree(node, odd));
  }

  renderEdit(node = {}) {
    return this.renderTemplate('treeEdit', {
      children: this.renderComponents(node.components),
      node,
    });
  }

  renderView(node = {}) {
    return this.renderTemplate('treeView', {
      values: this.viewComponents.map((component) => {
        component.data = node.data;
        component.checkComponentConditions(node.data);
        return component.getView(component.dataValue);
      }),
      nodeData: node.data,
      node,
    });
  }

  attach(element) {
    if (this.builderMode) {
      return super.attach(element);
    }

    this.loadRefs(element, {
      root: 'single',
    });

    return NativePromise.all([
      super.attach(element),
      this.attachNode(this.refs.root, this.treeRoot),
    ]);
  }

  attachNode(element, node) {
    if (!element) {
      return NativePromise.resolve();
    }

    let componentsPromise = NativePromise.resolve();
    let childrenPromise = NativePromise.resolve();

    node.refs = _.reduce(
      element.children,
      (refs, child) => (
        child.hasAttribute('ref')
          ? {
            ...refs,
            [child.getAttribute('ref')]: child,
          }
          : refs
      ),
      {},
    );

    if (node.refs.content) {
      this.attachActions(node);
      componentsPromise = this.attachComponents(node);
    }

    if (node.refs.childNodes) {
      childrenPromise = this.attachChildren(node);
    }

    return NativePromise.all([
      componentsPromise,
      childrenPromise,
    ]);
  }

  attachActions(node) {
    this.loadRefs.call(node, node.refs.content, {
      addChild: 'single',
      cancelNode: 'single',
      editNode: 'single',
      removeNode: 'single',
      revertNode: 'single',
      saveNode: 'single',
      toggleNode: 'single',
    });

    if (node.refs.addChild) {
      this.addEventListener(node.refs.addChild, 'click', () => {
        this.addChild(node);
      });
    }

    if (node.refs.cancelNode) {
      this.addEventListener(node.refs.cancelNode, 'click', () => {
        this.cancelNode(node);
      });
    }

    if (node.refs.editNode) {
      this.addEventListener(node.refs.editNode, 'click', () => {
        this.editNode(node);
      });
    }

    if (node.refs.removeNode) {
      this.addEventListener(node.refs.removeNode, 'click', () => {
        this.removeNode(node);
      });
    }

    if (node.refs.revertNode) {
      this.addEventListener(node.refs.revertNode, 'click', () => {
        this.revertNode(node);
      });
    }

    if (node.refs.saveNode) {
      this.addEventListener(node.refs.saveNode, 'click', () => {
        this.saveNode(node);
      });
    }

    if (node.refs.toggleNode) {
      this.addEventListener(node.refs.toggleNode, 'click', () => {
        this.toggleNode(node);
      });
    }
  }

  attachComponents(node, ...args) {
    if (this.builderMode) {
      return super.attachComponents.call(this, node, ...args);
    }

    this.loadRefs.call(node, node.refs.content, {
      nodeEdit: 'single',
    });

    return node.refs.nodeEdit
      ? super.attachComponents(node.refs.nodeEdit, node.components)
      : NativePromise.resolve();
  }

  attachChildren(node) {
    const childElements = node.refs.childNodes.children;

    return NativePromise.all(
      _.map(
        childElements,
        (childElement, index) => this.attachNode(childElement, node.children[index]),
      ),
    );
  }

  setValue(value) {
    const changed = this.updateValue(value);
    this.setRoot();
    return changed;
  }

  addChild(parent) {
    if (this.options.readOnly || parent.new) {
      return;
    }

    this.hook('tree.addChild', {
      parent,
      component: this,
    }, () => {
      const child = parent.addChild();
      this.redraw();

      return child;
    });
  }

  cancelNode(node) {
    if (this.options.readOnly) {
      return;
    }

    this.hook('tree.cancelNode', {
      node,
      component: this,
    }, () => {
      if (node.isRoot) {
        this.removeRoot();
      }
      else {
        node.cancel();
        this.redraw();
      }

      return node;
    });
  }

  editNode(node) {
    if (this.options.readOnly || node.new) {
      return;
    }

    this.hook('tree.editNode', {
      node,
      component: this,
    }, () => {
      node.edit();
      this.redraw();

      return node;
    });
  }

  removeNode(node) {
    if (this.options.readOnly || node.new) {
      return;
    }

    this.hook('tree.removeNode', {
      node,
      component: this,
    }, () => {
      if (node.isRoot) {
        this.removeRoot();
      }
      else {
        node.remove();
        this.updateTree();
      }

      return node;
    });
  }

  revertNode(node) {
    if (this.options.readOnly || !node.revertAvailable) {
      return;
    }

    this.hook('tree.revertNode', {
      node,
      component: this,
    }, () => {
      node.revert();
      this.updateTree();

      return node;
    });
  }

  saveNode(node) {
    if (this.options.readOnly) {
      return;
    }

    this.hook('tree.saveNode', {
      node,
      component: this,
    }, () => {
      node.save();
      this.updateTree();

      return node;
    });
  }

  toggleNode(node) {
    this.hook('tree.toggleNode', {
      node,
      component: this,
    }, () => {
      node.collapsed = !node.collapsed;
      this.redraw();

      return node;
    });
  }

  removeRoot() {
    if (this.options.readOnly) {
      return;
    }

    this.dataValue = this.defaultValue;
    this.setRoot();
    this.redraw();
  }

  setRoot() {
    const value = this.dataValue;
    this.treeRoot = new Node(null, value, {
      isNew: !value.data,
      createComponents: this.createComponents.bind(this),
      checkNode: this.checkNode.bind(this, this.data),
      removeComponents: this.removeComponents,
    });
    this.hook('tree.setRoot', {
      root: this.treeRoot,
      component: this,
    });
  }

  getValue() {
    return this.dataValue;
  }

  updateTree() {
    this.updateValue(this.treeRoot.value);
    this.redraw();
  }

  checkData(data, flags, row) {
    return this.checkNode(data, this.treeRoot, flags, row);
  }

  checkNode(data, node, flags, row) {
    return node.children.reduce(
      (result, child) => this.checkNode(data, child, flags, row) && result,
      super.checkData(data, flags, node.data, node.components),
    );
  }
}

TreeComponent.prototype.hasChanged = Component.prototype.hasChanged;
TreeComponent.prototype.updateValue = Component.prototype.updateValue;
<|endoftext|>


<commit_before>(function ($)
{
	"use strict";

	function KeyboardService($rootScope)
	{
		$rootScope.__changeKeyboardStatus = {
			'shift': false,
			'ctrl': false,
			'alt': false,
			'meta': false
		};

		function keyDown(event)
		{
			if (event.shiftKey)
			{
				$rootScope.__changeKeyboardStatus.shift = true;
			}
			if (event.ctrlKey)
			{
				$rootScope.__changeKeyboardStatus.ctrl = true;
			}
			if (event.altKey)
			{
				$rootScope.__changeKeyboardStatus.alt = true;
			}
			if (event.metaKey)
			{
				$rootScope.__changeKeyboardStatus.meta = true;
			}
			$rootScope.$digest();
		}

		function keyUp(event)
		{
			if (!event.shiftKey)
			{
				$rootScope.__changeKeyboardStatus.shift = false;
			}
			if (!event.ctrlKey)
			{
				$rootScope.__changeKeyboardStatus.ctrl = false;
			}
			if (!event.altKey)
			{
				$rootScope.__changeKeyboardStatus.alt = false;
			}
			if (!event.metaKey)
			{
				$rootScope.__changeKeyboardStatus.meta = false;
			}
			$rootScope.$digest();
		}

		this.watch = function (scope, key, callback)
		{
			var expr = '__changeKeyboardStatus.' +
				key.replace(/\+/g, ' && __changeKeyboardStatus.').replace(/\-/g, ' && !__changeKeyboardStatus.');
			var deregistrationFunc = $rootScope.$watch(expr, function (value, oldValue)
			{
				if (value === true || (value === false))
				{
					callback(value, oldValue);
				}
			}, true);
			scope.$on('$destroy', function ()
			{
				deregistrationFunc();
			});
		};

		$('body').on('keydown', keyDown).on('keyup', keyUp);
	}

	/**
	 * <rbs-kb-switch>
	 *
	 *
	 *
	 *
	 * </rbs-kb-switch>
	 */
	function rbsKbSwitch(Keyboard)
	{
		return {
			restrict: 'EAC',
			link: function (scope, elm)
			{
				var when, whenCounter, def;

				when = elm.find('[rbs-kb-when]');
				whenCounter = 0;
				def = elm.find('[rbs-kb-default]');

				when.each(function ()
				{
					var $el = $(this);
					Keyboard.watch(scope, $el.attr('rbs-kb-when'), function (value, oldValue)
					{
						if (value)
						{
							def.hide();
							$el.show();
							whenCounter++;
						}
						else
						{
							$el.hide();
							if (oldValue === true)
							{
								whenCounter--;
							}
							if (whenCounter === 0)
							{
								def.show();
							}
						}
					});
				});
			}
		};
	}

	var app = angular.module('RbsChange');
	app.service('RbsChange.Keyboard', ['$rootScope', KeyboardService]);
	app.directive('rbsKbSwitch', ['RbsChange.Keyboard', rbsKbSwitch]);
})(window.jQuery);<commit_msg>Added shortcut `rbs-kb-alt=""`. Use it instead of `rbs-kb-when="alt"`, so that we are sure it is always the alt key that is used as the alternate action (shift may be used if there are more than 2 options).<commit_after>(function ($)
{
	"use strict";

	function KeyboardService($rootScope)
	{
		$rootScope.__changeKeyboardStatus = {
			'shift': false,
			'ctrl': false,
			'alt': false,
			'meta': false
		};

		function keyDown(event)
		{
			if (event.shiftKey)
			{
				$rootScope.__changeKeyboardStatus.shift = true;
			}
			if (event.ctrlKey)
			{
				$rootScope.__changeKeyboardStatus.ctrl = true;
			}
			if (event.altKey)
			{
				$rootScope.__changeKeyboardStatus.alt = true;
			}
			if (event.metaKey)
			{
				$rootScope.__changeKeyboardStatus.meta = true;
			}
			$rootScope.$digest();
		}

		function keyUp(event)
		{
			if (!event.shiftKey)
			{
				$rootScope.__changeKeyboardStatus.shift = false;
			}
			if (!event.ctrlKey)
			{
				$rootScope.__changeKeyboardStatus.ctrl = false;
			}
			if (!event.altKey)
			{
				$rootScope.__changeKeyboardStatus.alt = false;
			}
			if (!event.metaKey)
			{
				$rootScope.__changeKeyboardStatus.meta = false;
			}
			$rootScope.$digest();
		}

		this.watch = function (scope, key, callback)
		{
			var expr = '__changeKeyboardStatus.' +
				key.replace(/\+/g, ' && __changeKeyboardStatus.').replace(/\-/g, ' && !__changeKeyboardStatus.');
			var deregistrationFunc = $rootScope.$watch(expr, function (value, oldValue)
			{
				if (value === true || (value === false))
				{
					callback(value, oldValue);
				}
			}, true);
			scope.$on('$destroy', function ()
			{
				deregistrationFunc();
			});
		};

		$('body').on('keydown', keyDown).on('keyup', keyUp);
	}

	/**
	 * <rbs-kb-switch>
	 *
	 *
	 *
	 *
	 * </rbs-kb-switch>
	 */
	function rbsKbSwitch(Keyboard)
	{
		return {
			restrict : 'EAC',
			link : function (scope, elm)
			{
				var when, whenCounter, def;

				// shortcut rbs-kb-alt="" instead of rbs-kb-when="alt"
				elm.find('[rbs-kb-alt]').each(function () {
					$(this).removeAttr('rbs-kb-alt').attr('rbs-kb-when', 'alt');
				});

				when = elm.find('[rbs-kb-when]');
				whenCounter = 0;
				def = elm.find('[rbs-kb-default]');

				when.each(function ()
				{
					var $el = $(this);
					Keyboard.watch(scope, $el.attr('rbs-kb-when'), function (value, oldValue)
					{
						if (value)
						{
							def.hide();
							$el.show();
							whenCounter++;
						}
						else
						{
							$el.hide();
							if (oldValue === true)
							{
								whenCounter--;
							}
							if (whenCounter === 0)
							{
								def.show();
							}
						}
					});
				});
			}
		};
	}

	var app = angular.module('RbsChange');
	app.service('RbsChange.Keyboard', ['$rootScope', KeyboardService]);
	app.directive('rbsKbSwitch', ['RbsChange.Keyboard', rbsKbSwitch]);
})(window.jQuery);<|endoftext|>


<commit_before>;(function() {
    "use strict"

    function in_viewport($el) {
        return (($el.offset().top + $el.height() <= $(window).scrollTop() + $(window).height()) && ($el.offset().top >= $(window).scrollTop()))
    }

    ;(function() {
        // Shakes icon for retweeting article when the icon is in the viewport.
        var has_shaked = false
        $(document).scroll(function() {
            var $icon_retweet = $(".icon-retweet")
            if (! has_shaked && in_viewport($icon_retweet)) {
                has_shaked = true
                setTimeout(function() {
                    $icon_retweet.effect("shake", {times: 4, distance: 6}, 400)
                }, 2000)
            }
        })
    }())
}())
<commit_msg>Bug #77: JavaScript errors in console<commit_after>;(function() {
    "use strict"

    function in_viewport($el) {
        return (($el.offset().top + $el.height() <= $(window).scrollTop() + $(window).height()) && ($el.offset().top >= $(window).scrollTop()))
    }

    ;(function() {
        // Shakes icon for retweeting article when the icon is in the viewport.
        var has_shaked = false
        $(document).scroll(function() {
            var $icon_retweet = $(".icon-retweet")
            if (! $icon_retweet.length) {
                return
            }
            if (! has_shaked && in_viewport($icon_retweet)) {
                has_shaked = true
                setTimeout(function() {
                    $icon_retweet.effect("shake", {times: 4, distance: 6}, 400)
                }, 2000)
            }
        })
    }())
}())
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-highlight-portals-my-level@vita10gy
// @name           IITC plugin: highlight portals by my level
// @category       Highlighter
// @version        0.1.0.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Use the portal fill color to denote if the portal is either at and above, or at and below your level.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.portalHighlighterPortalsMyLevel = function() {};

window.plugin.portalHighlighterPortalsMyLevel.belowLevel = function(data) {
  window.plugin.portalHighlighterPortalsMyLevel.colorLevel(true,data);
}

window.plugin.portalHighlighterPortalsMyLevel.aboveLevel = function(data) {
  window.plugin.portalHighlighterPortalsMyLevel.colorLevel(false,data);
}

window.plugin.portalHighlighterPortalsMyLevel.colorLevel = function(below,data) {
  var portal_level = data.portal.options.level;
  var player_level = PLAYER.level;
  var opacity = .6;
  if((below && portal_level <= player_level) ||
     (!below && portal_level >= player_level)) {
    data.portal.setStyle({fillColor: 'red', fillOpacity: opacity});
  }
}

var setup =  function() {
  window.addPortalHighlighter('Below My Level', window.plugin.portalHighlighterPortalsMyLevel.belowLevel);
  window.addPortalHighlighter('Above My Level', window.plugin.portalHighlighterPortalsMyLevel.aboveLevel);
}

// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<commit_msg>limit by my level highlighter to no more than L8, as portals cannot be higher than this, but players now can<commit_after>// ==UserScript==
// @id             iitc-plugin-highlight-portals-my-level@vita10gy
// @name           IITC plugin: highlight portals by my level
// @category       Highlighter
// @version        0.1.2.@@DATETIMEVERSION@@
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL      @@UPDATEURL@@
// @downloadURL    @@DOWNLOADURL@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Use the portal fill color to denote if the portal is either at and above, or at and below your level.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @grant          none
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.portalHighlighterPortalsMyLevel = function() {};

window.plugin.portalHighlighterPortalsMyLevel.belowLevel = function(data) {
  window.plugin.portalHighlighterPortalsMyLevel.colorLevel(true,data);
}

window.plugin.portalHighlighterPortalsMyLevel.aboveLevel = function(data) {
  window.plugin.portalHighlighterPortalsMyLevel.colorLevel(false,data);
}

window.plugin.portalHighlighterPortalsMyLevel.colorLevel = function(below,data) {
  var portal_level = data.portal.options.level;

  // as portal levels can never be higher than L8, clamp the player level to this for highlight purposes
  var player_level = Math.min(PLAYER.level,8);

  var opacity = .6;
  if((below && portal_level <= player_level) ||
     (!below && portal_level >= player_level)) {
    data.portal.setStyle({fillColor: 'red', fillOpacity: opacity});
  }
}

var setup =  function() {
  window.addPortalHighlighter('Below My Level', window.plugin.portalHighlighterPortalsMyLevel.belowLevel);
  window.addPortalHighlighter('Above My Level', window.plugin.portalHighlighterPortalsMyLevel.aboveLevel);
}

// PLUGIN END //////////////////////////////////////////////////////////

@@PLUGINEND@@
<|endoftext|>


<commit_before>function _resize() {
    // I couldn't figure out how to do this in CSS: resize the table
    // so that it takes as much space as it can without expanding the
    // page horizontally.
    var space = parseInt($("#lava-breadcrumbs").outerWidth() - $("#outer-table").outerWidth());
    space -= $("#lava-content").outerWidth() - $("#lava-content").width();
    var table = $("#results-table"), scroller=$("#scroller");
    var atRight = scroller.width() + scroller.scrollLeft() >= table.attr('scrollWidth');
    scroller.width(scroller.width() + space);
    if (atRight) scroller.scrollLeft(table.attr('scrollWidth'));
}
$(window).ready(
    function () {
        // Hook up the event and run resize ASAP (looks jumpy in FF if you
        // don't run it here).
        $(window).resize(_resize);
        $("#scroller").scrollLeft(100000);
        _resize();

        function _submit() {
            $(this).submit();
        }
        var add_bug_dialog = $('#add-bug-dialog').dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'OK': _submit },
                modal: true,
                title: "Link bug to XXX"
            });
        var go_to_bug_dialog = $("#go-to-bug-dialog").dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'Remove link': _submit},
                modal: true,
                title: "Link bug to XXX"
            });

        function get_testrun_and_buildnumber (element) {
            var cell = element.closest('td');
            var row = cell.closest('tr');
            var testrun = $($("#test-run-names > tbody > tr")[row.index()]).text();
            var header_cells = element.closest('table').find('thead > tr > th');
            var buildnumber = $(header_cells[cell.index()]).text();
            return {testrun: $.trim(testrun), buildnumber: $.trim(buildnumber)};
        }

        function find_previous_bugs (element) {
            var td = $(element).closest('td');
            var bugs = [];
            var start = td;
            while ((td = td.prev()) && td.size()) {
                td.find(".bug-link").each(
                    function (index, link) {
                        var bug_id = $(link).data('bug-id');
                        if (bugs.indexOf(bug_id) < 0) bugs.push(bug_id);
                    });
            }
            var already_linked = [];
            start.find(".bug-link").each(
                function (index, link) {
                    var bug_id = $(link).data('bug-id');
                    if (bugs.indexOf(bug_id) >= 0) {
                        bugs.splice(bugs.indexOf(bug_id), 1);
                        already_linked.push(bug_id);
                    }
                });
            return {bugs:bugs, already_linked:already_linked};
        }

        $('a.add-bug-link').click(
            function (e) {
                e.preventDefault();

                var previous = find_previous_bugs($(this));
                var prev_div = add_bug_dialog.find('div.prev');
                var names = get_testrun_and_buildnumber($(this));

                if (previous.bugs.length) {
                    var html = '';
                    prev_div.show();
                    html = '
Use a bug previously linked to ' + names.testrun + ':

';
                    for (var i = 0; i < previous.already_linked.length; i++) {
                        html += '
' + previous.already_linked[i] + ' (already linked)
';
                    }
                    for (var i = 0; i < previous.bugs.length; i++) {
                        html += '
' +
                            previous.bugs[i] + '
';
                    }
                    html += '
';
                    html += "
Or enter another bug number:
";
                    prev_div.html(html);
                    prev_div.find('a').click(
                        function (e) {
                            e.preventDefault();
                            add_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                            add_bug_dialog.submit();
                        });
                } else {
                    prev_div.hide();
                }

                var title = "Link a bug to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                add_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                add_bug_dialog.dialog('option', 'title', title);
                add_bug_dialog.dialog('open');
            });

        $("a.bug-link").click(
            function (e) {
                e.preventDefault();
                var names = get_testrun_and_buildnumber($(this));
                var title = "Bug linked to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                go_to_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                go_to_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                go_to_bug_dialog.find('a').attr('href', $(this).attr('href'));
                go_to_bug_dialog.find('a').text('View bug ' + $(this).data('bug-id'));
                go_to_bug_dialog.dialog('option', 'title', title);
                go_to_bug_dialog.dialog('open');
            });
    });
// Because what resize does depends on the final sizes of elements,
// run it again after everything is loaded (things end up wrong in
// chromium if you don't do this).
$(window).load(_resize);
<commit_msg>ensure table row heights match up in image status view<commit_after>function _resize() {
    // I couldn't figure out how to do this in CSS: resize the table
    // so that it takes as much space as it can without expanding the
    // page horizontally.
    var space = parseInt($("#lava-breadcrumbs").outerWidth() - $("#outer-table").outerWidth());
    space -= $("#lava-content").outerWidth() - $("#lava-content").width();
    var table = $("#results-table"), scroller=$("#scroller");
    var atRight = scroller.width() + scroller.scrollLeft() >= table.attr('scrollWidth');
    scroller.width(scroller.width() + space);
    if (atRight) scroller.scrollLeft(table.attr('scrollWidth'));
}
function _fixRowHeights () {
    var index = 0;
    var nameRows = $("#test-run-names > tbody > tr");
    var resultRows = $("#results-table > tbody > tr");
    for (; index < nameRows.length; index++) {
        var nameRow = $(nameRows[index]);
        var resultRow = $(resultRows[index]);
        var nameRowHeight = parseInt(nameRow.css('height'));
        var resultRowHeight = parseInt(resultRow.css('height'));
        nameRow.css('height', Math.max(nameRowHeight, resultRowHeight));
        resultRow.css('height', Math.max(nameRowHeight, resultRowHeight));
    }
}
$(window).ready(
    function () {
        // Hook up the event and run resize ASAP (looks jumpy in FF if you
        // don't run it here).
        $(window).resize(_resize);
        $("#scroller").scrollLeft(100000);
        _resize();
        _fixRowHeights();

        function _submit() {
            $(this).submit();
        }
        var add_bug_dialog = $('#add-bug-dialog').dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'OK': _submit },
                modal: true,
                title: "Link bug to XXX"
            });
        var go_to_bug_dialog = $("#go-to-bug-dialog").dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'Remove link': _submit},
                modal: true,
                title: "Link bug to XXX"
            });

        function get_testrun_and_buildnumber (element) {
            var cell = element.closest('td');
            var row = cell.closest('tr');
            var testrun = $($("#test-run-names > tbody > tr")[row.index()]).text();
            var header_cells = element.closest('table').find('thead > tr > th');
            var buildnumber = $(header_cells[cell.index()]).text();
            return {testrun: $.trim(testrun), buildnumber: $.trim(buildnumber)};
        }

        function find_previous_bugs (element) {
            var td = $(element).closest('td');
            var bugs = [];
            var start = td;
            while ((td = td.prev()) && td.size()) {
                td.find(".bug-link").each(
                    function (index, link) {
                        var bug_id = $(link).data('bug-id');
                        if (bugs.indexOf(bug_id) < 0) bugs.push(bug_id);
                    });
            }
            var already_linked = [];
            start.find(".bug-link").each(
                function (index, link) {
                    var bug_id = $(link).data('bug-id');
                    if (bugs.indexOf(bug_id) >= 0) {
                        bugs.splice(bugs.indexOf(bug_id), 1);
                        already_linked.push(bug_id);
                    }
                });
            return {bugs:bugs, already_linked:already_linked};
        }

        $('a.add-bug-link').click(
            function (e) {
                e.preventDefault();

                var previous = find_previous_bugs($(this));
                var prev_div = add_bug_dialog.find('div.prev');
                var names = get_testrun_and_buildnumber($(this));

                if (previous.bugs.length) {
                    var html = '';
                    prev_div.show();
                    html = '
Use a bug previously linked to ' + names.testrun + ':

';
                    for (var i = 0; i < previous.already_linked.length; i++) {
                        html += '
' + previous.already_linked[i] + ' (already linked)
';
                    }
                    for (var i = 0; i < previous.bugs.length; i++) {
                        html += '
' +
                            previous.bugs[i] + '
';
                    }
                    html += '
';
                    html += "
Or enter another bug number:
";
                    prev_div.html(html);
                    prev_div.find('a').click(
                        function (e) {
                            e.preventDefault();
                            add_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                            add_bug_dialog.submit();
                        });
                } else {
                    prev_div.hide();
                }

                var title = "Link a bug to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                add_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                add_bug_dialog.dialog('option', 'title', title);
                add_bug_dialog.dialog('open');
            });

        $("a.bug-link").click(
            function (e) {
                e.preventDefault();
                var names = get_testrun_and_buildnumber($(this));
                var title = "Bug linked to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                go_to_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                go_to_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                go_to_bug_dialog.find('a').attr('href', $(this).attr('href'));
                go_to_bug_dialog.find('a').text('View bug ' + $(this).data('bug-id'));
                go_to_bug_dialog.dialog('option', 'title', title);
                go_to_bug_dialog.dialog('open');
            });
    });
// Because what resize does depends on the final sizes of elements,
// run it again after everything is loaded (things end up wrong in
// chromium if you don't do this).
$(window).load(_resize);
$(window).load(_fixRowHeights);
<|endoftext|>


<commit_before>function makeMapScales(scaleData) {

  var fontSize = window.devicePixelRatio == 2 ? 12 : 10;

  if(scaleData == null) {
    document.getElementById("dataStats").innerHTML = '';
    document.getElementById("mainScaleBox").innerHTML = '';
    document.getElementById("auxScaleBox").innerHTML = '';
    return;
  }

  if("data_stats" in scaleData)
    document.getElementById("dataStats").innerHTML = "Stats: " + scaleData.data_stats;
  else
    document.getElementById("dataStats").innerHTML = '';

  var mainScaleProps = {}
  // properties that define the scale
  mainScaleProps.sp_tick_font_size = fontSize;
  mainScaleProps.sp_xoff           = 5;
  mainScaleProps.sp_width          = 40;
  mainScaleProps.sp_height         = 15;
  mainScaleProps.sp_tick_len       = 5;
  mainScaleProps.sp_xHeight        = Math.round(0.7 * mainScaleProps.sp_tick_font_size);
  mainScaleProps.sp_yoff           = mainScaleProps.sp_tick_font_size + 2;
  mainScaleProps.sp_tick_yoff      = mainScaleProps.sp_yoff + mainScaleProps.sp_height;
  mainScaleProps.sp_tick_text_yoff = mainScaleProps.sp_tick_yoff + mainScaleProps.sp_tick_len + mainScaleProps.sp_xHeight;

  // properties that provide the scale data
  mainScaleProps.sp_divId = "#mainScale";
  mainScaleProps.sp_svgId = "#svgMainScale";
  if ("main" in scaleData) {
    // set up the mainScaleBox
    var msp = scaleData["main"];
    var divTitle = "divTitle" in msp ? msp.divTitle : "Main Scale";
    document.getElementById("mainScaleBox").innerHTML = '
' + divTitle + ':

';
    mainScaleProps.sp_values = msp.values;
    if(msp.scale_type == "factor")
       mainScaleProps.sp_values.push(msp.def_value[0]);
    var main_sp_breaks = msp.breaks;
    mainScaleProps.sp_breaks_idx_off = 1;
    if (("min_value" in msp) || ("max_value" in msp)) {
      main_sp_breaks = [];
      if ("min_value" in msp) {
        main_sp_breaks.push(Math.floor(msp.min_value[0]));
        mainScaleProps.sp_breaks_idx_off = 0;
      }
      for(var i = 0; i < msp.breaks.length; i++)
        main_sp_breaks.push(msp.breaks[i]);
      if ("max_value" in msp) {
        var main_max_value = Math.ceil(msp.max_value[0]);
        var main_breaks_max_value = msp.breaks[msp.breaks.length - 1];
        main_sp_breaks.push(main_max_value > main_breaks_max_value ? main_max_value : main_breaks_max_value);
      }
    }
    mainScaleProps.sp_breaks = main_sp_breaks;
    mainScaleProps.sp_title = ("title" in msp) ? msp.title : ["Main Scale"];
    mainScaleProps.sp_fill_boxes_func = function(d, i) {
      return "rgb(" + Math.round(d[0]*255) + "," + Math.round(d[1]*255) + "," + Math.round(d[2]*255) + ")";	// DIFF!
    };
    if("stats" in msp) {
      var main_box_text = [];
      for(var i = 0; i < msp.stats.length; i++) {
        main_box_text.push(msp.stats[i][1] + "%");								// DIFF!
      }
      mainScaleProps.sp_box_text = main_box_text;
      if("box_text_color" in msp){										// DIFF!
        mainScaleProps.sp_box_text_color = msp.box_text_color[0];						// DIFF!
      } else {													// DIFF!
        mainScaleProps.sp_box_text_color = "rgb(255,255,255)";							// DIFF!
      }														// DIFF!
    } else if("keys" in msp) {
      var main_box_text = [];
      for(var i = 0; i < msp.keys.length; i++) {
        main_box_text.push(msp.keys[i]);									// DIFF!
      }
      main_box_text.push(msp.def_key_text);
      mainScaleProps.sp_box_text = main_box_text;
    } else {
      mainScaleProps.sp_box_text = null;									// DIFF!
    }
    makeScale(mainScaleProps);
  } else {
    // Clear the mainScaleBox
    document.getElementById("mainScaleBox").innerHTML = '';
  }

  var auxScaleProps = {};
  // properties that define the scale
  auxScaleProps.sp_tick_font_size = fontSize;
  auxScaleProps.sp_xoff           = 9;	// will work up to 999
  auxScaleProps.sp_width          = 75;
  auxScaleProps.sp_height         = 15;
  auxScaleProps.sp_tick_len       = 5;
  auxScaleProps.sp_xHeight        = Math.round(0.7 * auxScaleProps.sp_tick_font_size);
  auxScaleProps.sp_yoff           = auxScaleProps.sp_tick_font_size + 2;
  auxScaleProps.sp_tick_yoff      = auxScaleProps.sp_yoff + auxScaleProps.sp_height;
  auxScaleProps.sp_tick_text_yoff = auxScaleProps.sp_tick_yoff + auxScaleProps.sp_tick_len + auxScaleProps.sp_xHeight;

  // properties that provide the scale data
  auxScaleProps.sp_divId = "#auxScale";
  auxScaleProps.sp_svgId = "#svgAuxScale";
  if ("aux" in scaleData) {
    // set up the auxScaleBox
    var asp = scaleData["aux"];
    var divTitle = "divTitle" in asp ? asp.divTitle : "Aux Scale";
    document.getElementById("auxScaleBox").innerHTML = '
' + divTitle + ':

';
    auxScaleProps.sp_values = asp.values;
    var aux_sp_breaks = asp.breaks;
    auxScaleProps.sp_breaks_idx_off = 1;
    if (("min_value" in asp) || ("max_value" in asp)) {
      aux_sp_breaks = [];
      if ("min_value" in asp) {
        aux_sp_breaks.push(Math.floor(asp.min_value[0]));
        auxScaleProps.sp_breaks_idx_off = 0;
      }
      for(var i = 0; i < asp.breaks.length; i++)
        aux_sp_breaks.push(asp.breaks[i]);
      if ("max_value" in asp) {
        var aux_max_value = Math.ceil(asp.max_value[0]);
        var aux_breaks_max_value = asp.breaks[asp.breaks.length - 1];
        aux_sp_breaks.push(aux_max_value > aux_breaks_max_value ? aux_max_value : aux_breaks_max_value);
      }
    }
    auxScaleProps.sp_breaks = aux_sp_breaks;
    auxScaleProps.sp_title = ("title" in asp) ? asp.title : ["Aux. Scale"];
    auxScaleProps.sp_fill_boxes_func = function(d, i) {
      return "white";											// DIFF!
    }
    if("stats" in asp) {
      auxScaleProps.sp_box_text = scaleData.size_values;
      var aux_box_text = [];
      for(var i = 0; i < asp.stats.length; i++){
        aux_box_text.push(asp.values[i] + ", " + asp.stats[i][1] + "%");
      }
      auxScaleProps.sp_box_text = aux_box_text;
    } else if("keys" in asp) {
    } else {
      auxScaleProps.sp_box_text = asp.values;
    }
    auxScaleProps.sp_box_text_color = "black";
    makeScale(auxScaleProps);
  } else {
    // Clear the auxScaleBox
    document.getElementById("auxScaleBox").innerHTML = '';
  }
}
<commit_msg>make_map_scales.js	-- default scale title is now ''<commit_after>function makeMapScales(scaleData) {

  var fontSize = window.devicePixelRatio == 2 ? 12 : 10;

  if(scaleData == null) {
    document.getElementById("dataStats").innerHTML = '';
    document.getElementById("mainScaleBox").innerHTML = '';
    document.getElementById("auxScaleBox").innerHTML = '';
    return;
  }

  if("data_stats" in scaleData)
    document.getElementById("dataStats").innerHTML = "Stats: " + scaleData.data_stats;
  else
    document.getElementById("dataStats").innerHTML = '';

  var mainScaleProps = {}
  // properties that define the scale
  mainScaleProps.sp_tick_font_size = fontSize;
  mainScaleProps.sp_xoff           = 5;
  mainScaleProps.sp_width          = 40;
  mainScaleProps.sp_height         = 15;
  mainScaleProps.sp_tick_len       = 5;
  mainScaleProps.sp_xHeight        = Math.round(0.7 * mainScaleProps.sp_tick_font_size);
  mainScaleProps.sp_yoff           = mainScaleProps.sp_tick_font_size + 2;
  mainScaleProps.sp_tick_yoff      = mainScaleProps.sp_yoff + mainScaleProps.sp_height;
  mainScaleProps.sp_tick_text_yoff = mainScaleProps.sp_tick_yoff + mainScaleProps.sp_tick_len + mainScaleProps.sp_xHeight;

  // properties that provide the scale data
  mainScaleProps.sp_divId = "#mainScale";
  mainScaleProps.sp_svgId = "#svgMainScale";
  if ("main" in scaleData) {
    // set up the mainScaleBox
    var msp = scaleData["main"];
    var divTitle = "divTitle" in msp ? msp.divTitle : "Main Scale";
    document.getElementById("mainScaleBox").innerHTML = '
' + divTitle + ':

';
    mainScaleProps.sp_values = msp.values;
    if(msp.scale_type == "factor")
       mainScaleProps.sp_values.push(msp.def_value[0]);
    var main_sp_breaks = msp.breaks;
    mainScaleProps.sp_breaks_idx_off = 1;
    if (("min_value" in msp) || ("max_value" in msp)) {
      main_sp_breaks = [];
      if ("min_value" in msp) {
        main_sp_breaks.push(Math.floor(msp.min_value[0]));
        mainScaleProps.sp_breaks_idx_off = 0;
      }
      for(var i = 0; i < msp.breaks.length; i++)
        main_sp_breaks.push(msp.breaks[i]);
      if ("max_value" in msp) {
        var main_max_value = Math.ceil(msp.max_value[0]);
        var main_breaks_max_value = msp.breaks[msp.breaks.length - 1];
        main_sp_breaks.push(main_max_value > main_breaks_max_value ? main_max_value : main_breaks_max_value);
      }
    }
    mainScaleProps.sp_breaks = main_sp_breaks;
    mainScaleProps.sp_title = ("title" in msp) ? msp.title : [""];
    mainScaleProps.sp_fill_boxes_func = function(d, i) {
      return "rgb(" + Math.round(d[0]*255) + "," + Math.round(d[1]*255) + "," + Math.round(d[2]*255) + ")";	// DIFF!
    };
    if("stats" in msp) {
      var main_box_text = [];
      for(var i = 0; i < msp.stats.length; i++) {
        main_box_text.push(msp.stats[i][1] + "%");								// DIFF!
      }
      mainScaleProps.sp_box_text = main_box_text;
      if("box_text_color" in msp){										// DIFF!
        mainScaleProps.sp_box_text_color = msp.box_text_color[0];						// DIFF!
      } else {													// DIFF!
        mainScaleProps.sp_box_text_color = "rgb(255,255,255)";							// DIFF!
      }														// DIFF!
    } else if("keys" in msp) {
      var main_box_text = [];
      for(var i = 0; i < msp.keys.length; i++) {
        main_box_text.push(msp.keys[i]);									// DIFF!
      }
      main_box_text.push(msp.def_key_text);
      mainScaleProps.sp_box_text = main_box_text;
    } else {
      mainScaleProps.sp_box_text = null;									// DIFF!
    }
    makeScale(mainScaleProps);
  } else {
    // Clear the mainScaleBox
    document.getElementById("mainScaleBox").innerHTML = '';
  }

  var auxScaleProps = {};
  // properties that define the scale
  auxScaleProps.sp_tick_font_size = fontSize;
  auxScaleProps.sp_xoff           = 9;	// will work up to 999
  auxScaleProps.sp_width          = 75;
  auxScaleProps.sp_height         = 15;
  auxScaleProps.sp_tick_len       = 5;
  auxScaleProps.sp_xHeight        = Math.round(0.7 * auxScaleProps.sp_tick_font_size);
  auxScaleProps.sp_yoff           = auxScaleProps.sp_tick_font_size + 2;
  auxScaleProps.sp_tick_yoff      = auxScaleProps.sp_yoff + auxScaleProps.sp_height;
  auxScaleProps.sp_tick_text_yoff = auxScaleProps.sp_tick_yoff + auxScaleProps.sp_tick_len + auxScaleProps.sp_xHeight;

  // properties that provide the scale data
  auxScaleProps.sp_divId = "#auxScale";
  auxScaleProps.sp_svgId = "#svgAuxScale";
  if ("aux" in scaleData) {
    // set up the auxScaleBox
    var asp = scaleData["aux"];
    var divTitle = "divTitle" in asp ? asp.divTitle : "Aux Scale";
    document.getElementById("auxScaleBox").innerHTML = '
' + divTitle + ':

';
    auxScaleProps.sp_values = asp.values;
    var aux_sp_breaks = asp.breaks;
    auxScaleProps.sp_breaks_idx_off = 1;
    if (("min_value" in asp) || ("max_value" in asp)) {
      aux_sp_breaks = [];
      if ("min_value" in asp) {
        aux_sp_breaks.push(Math.floor(asp.min_value[0]));
        auxScaleProps.sp_breaks_idx_off = 0;
      }
      for(var i = 0; i < asp.breaks.length; i++)
        aux_sp_breaks.push(asp.breaks[i]);
      if ("max_value" in asp) {
        var aux_max_value = Math.ceil(asp.max_value[0]);
        var aux_breaks_max_value = asp.breaks[asp.breaks.length - 1];
        aux_sp_breaks.push(aux_max_value > aux_breaks_max_value ? aux_max_value : aux_breaks_max_value);
      }
    }
    auxScaleProps.sp_breaks = aux_sp_breaks;
    auxScaleProps.sp_title = ("title" in asp) ? asp.title : [""];
    auxScaleProps.sp_fill_boxes_func = function(d, i) {
      return "white";											// DIFF!
    }
    if("stats" in asp) {
      auxScaleProps.sp_box_text = scaleData.size_values;
      var aux_box_text = [];
      for(var i = 0; i < asp.stats.length; i++){
        aux_box_text.push(asp.values[i] + ", " + asp.stats[i][1] + "%");
      }
      auxScaleProps.sp_box_text = aux_box_text;
    } else if("keys" in asp) {
    } else {
      auxScaleProps.sp_box_text = asp.values;
    }
    auxScaleProps.sp_box_text_color = "black";
    makeScale(auxScaleProps);
  } else {
    // Clear the auxScaleBox
    document.getElementById("auxScaleBox").innerHTML = '';
  }
}
<|endoftext|>


<commit_before>var socket = io();

$("#run_code_button").prop('disabled', true);
$("#step_debugger").prop('disabled', true);
$("#next_debugger").prop('disabled', true);
$("#continue_debugger").prop('disabled', true);
$("#pls").prop('disabled', true);

function sendCommand(comand) {
    socket.emit("gdb_command", comand);
}

$("#send_command").click(function(){
    var cmd = $("#gdb_command").val();
    sendCommand(cmd);
});

socket.on("compile_error",function(data){
	waitingDialog.hide();

	$("#errors").text(data);
	$("#compilation_error_modal").modal();

	if(data == "Successfully compiled!"){
		console.log("Sucessfully compiled!");
		$("#run_code_button").prop('disabled', false);
		$("#step_debugger").prop('disabled', false);
		$("#next_debugger").prop('disabled', false);
		$("#continue_debugger").prop('disabled', false);
		$("#stop_button").prop('disabled', false);
		$("#pls").prop('disabled', false);
	}

	else console.log("Compilation error!");
});

socket.on("compile_success",function(data){
	$("#errors").text(data);
	$("#compilation_error_modal").modal();

	$("#run_code_button").prop('disabled', false);
	$("#step_debugger").prop('disabled', false);
	$("#next_debugger").prop('disabled', false);
	$("#continue_debugger").prop('disabled', false);
	$("#pls").prop('disabled', false);
});

socket.on('debug', function(data){
	console.log(data);
	if(data.line){
		moveHighlight(data.line-1);
	}
});

socket.on('gdb_stdout', function(data){
	console.log(data);
});

socket.on('gdb_stderr', function(data){
	console.log(data);
});

socket.on("step", function(data){
    console.log("step data: " + JSON.stringify(data));
    updateWatchesData(data.watches);
    simpleVar.updateVarData(data.watches);
    pointerVar.updateVarData(data.watches);
    memoryHandler.gatherVarData();
    moveHighlight(data.line-1);
});

socket.on("next", function(data){
	console.log(JSON.stringify(data));
	console.log("next data: " + JSON.stringify(data));
    updateWatchesData(data.watches);
    simpleVar.updateVarData(data.watches);
    pointerVar.updateVarData(data.watches);
    memoryHandler.gatherVarData();
    moveHighlight(data.line-1);
});
socket.on("continue", function(data){
	console.log("continue data: " + JSON.stringify(data));
    updateWatchesData(data.watches);
    simpleVar.updateVarData(data.watches);
    pointerVar.updateVarData(data.watches);
    memoryHandler.gatherVarData();
    moveHighlight(data.line-1);
});

function recievedData(data) {
    console.log(data);
    updateWatchesData(data);
    simpleVar.updateVarData(data);
    pointerVar.updateVarData(data);
    memoryHandler.gatherVarData();
}

socket.on("print_expressions", function(data){
    recievedData(data);
});

// socket.on('add_watch',function(data){
// 	updateWatchesData(data);
// });
socket.on('add_watch', function(data){
    console.log(JSON.stringify(data));
    var x = {};
    x[data.result.expr] = data.result.value;
    updateWatchesData(x);
    simpleVar.updateVarData(x);
    pointerVar.updateVarData(x);
    memoryHandler.gatherVarData();
});

socket.on('run', function(data){
	alert('RUN'+data);
	if(data.line)
		moveHighlight(data.line-1);
});

socket.on('code_saved', function(data) {
    if (data.status == false) {
        alert("saving failed");
    }
    else {
        alert("Code successfully saved as http://localhost:3000/code/" + data.id);
    }
});

socket.on('editor_source', function(data){
	if(data.indexOf('no source code') != -1){
		if(Cookies.get('code'))
			editor.setValue(Cookies.get('code'), 1);
	} else {
		console.log("editor: " + data);
		editor.setValue(data, 1);
	}
});

socket.on('add_breakpoints_result', function(data){
    console.log(data);
});
<commit_msg>Fixed debugger behaviour when no watches added<commit_after>var socket = io();

$("#run_code_button").prop('disabled', true);
$("#step_debugger").prop('disabled', true);
$("#next_debugger").prop('disabled', true);
$("#continue_debugger").prop('disabled', true);
$("#pls").prop('disabled', true);

function sendCommand(comand) {
    socket.emit("gdb_command", comand);
}

$("#send_command").click(function(){
    var cmd = $("#gdb_command").val();
    sendCommand(cmd);
});

socket.on("compile_error",function(data){
	waitingDialog.hide();

	$("#errors").text(data);
	$("#compilation_error_modal").modal();

	if(data == "Successfully compiled!"){
		console.log("Sucessfully compiled!");
		$("#run_code_button").prop('disabled', false);
		$("#step_debugger").prop('disabled', false);
		$("#next_debugger").prop('disabled', false);
		$("#continue_debugger").prop('disabled', false);
		$("#stop_button").prop('disabled', false);
		$("#pls").prop('disabled', false);
	}

	else console.log("Compilation error!");
});

socket.on("compile_success",function(data){
	$("#errors").text(data);
	$("#compilation_error_modal").modal();

	$("#run_code_button").prop('disabled', false);
	$("#step_debugger").prop('disabled', false);
	$("#next_debugger").prop('disabled', false);
	$("#continue_debugger").prop('disabled', false);
	$("#pls").prop('disabled', false);
});

socket.on('debug', function(data){
	console.log(data);
	if(data.line){
		moveHighlight(data.line-1);
	}
});

socket.on('gdb_stdout', function(data){
	console.log(data);
});

socket.on('gdb_stderr', function(data){
	console.log(data);
});

socket.on("step", function(data){
    console.log("step data: " + JSON.stringify(data));
	if(data.watches){
		updateWatchesData(data.watches);
		simpleVar.updateVarData(data.watches);
		pointerVar.updateVarData(data.watches);
		memoryHandler.gatherVarData();
	}
    moveHighlight(data.line-1);
});

socket.on("next", function(data){
	console.log(JSON.stringify(data));
	console.log("next data: " + JSON.stringify(data));
	if(data.watches){
		updateWatchesData(data.watches);
		simpleVar.updateVarData(data.watches);
		pointerVar.updateVarData(data.watches);
		memoryHandler.gatherVarData();
	}
    moveHighlight(data.line-1);
});
socket.on("continue", function(data){
	console.log("continue data: " + JSON.stringify(data));
	if(data.watches){
		updateWatchesData(data.watches);
		simpleVar.updateVarData(data.watches);
		pointerVar.updateVarData(data.watches);
		memoryHandler.gatherVarData();
	}
    moveHighlight(data.line-1);
});

function recievedData(data) {
    console.log(data);
    updateWatchesData(data);
    simpleVar.updateVarData(data);
    pointerVar.updateVarData(data);
    memoryHandler.gatherVarData();
}

socket.on("print_expressions", function(data){
    recievedData(data);
});

// socket.on('add_watch',function(data){
// 	updateWatchesData(data);
// });
socket.on('add_watch', function(data){
    console.log(JSON.stringify(data));
    var x = {};
    x[data.result.expr] = data.result.value;
    updateWatchesData(x);
    simpleVar.updateVarData(x);
    pointerVar.updateVarData(x);
    memoryHandler.gatherVarData();
});

socket.on('run', function(data){
	alert('RUN'+data);
	if(data.line)
		moveHighlight(data.line-1);
});

socket.on('code_saved', function(data) {
    if (data.status == false) {
        alert("saving failed");
    }
    else {
        alert("Code successfully saved as http://localhost:3000/code/" + data.id);
    }
});

socket.on('editor_source', function(data){
	if(data.indexOf('no source code') != -1){
		if(Cookies.get('code'))
			editor.setValue(Cookies.get('code'), 1);
	} else {
		console.log("editor: " + data);
		editor.setValue(data, 1);
	}
});

socket.on('add_breakpoints_result', function(data){
    console.log(data);
});
<|endoftext|>