<commit_before>let render2D = {
    Via: {
        featureParams: {
            position: "position",
            radius1: "radius1",
            radius2: "radius2"
        },
        targetParams: {
            radius1: "radius1",
            radius2: "radius2"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GradientCircle",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Port: {
        featureParams: {
            position: "position",
            portRadius: "portRadius"
        },
        targetParams: {
            portRadius: "portRadius"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "PortCircle",
        targetPrimitiveType: "PortTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Node: {
        featureParams: {
            position: "position",
            radius1: "radius1",
            radius2: "radius2"
        },
        targetParams: {
            radius1: "radius1",
            radius2: "radius2"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GradientCircle",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    CircleValve: {
        featureParams: {
            position: "position",
            radius1: "radius1",
            radius2: "radius2"
        },
        targetParams: {
            radius1: "radius1",
            radius2: "radius2"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GradientCircle",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Valve3D: {
        featureParams: {
            position: "position",
            orientation: "orientation",
            radius1: "valveRadius",
            radius2: "valveRadius",
            valveRadius: "valveRadius",
            gap: "gap"
        },
        targetParams: {
            radius1: "valveRadius",
            radius2: "valveRadius"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GroverValve",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Channel: {
        featureParams: {
            start: "start",
            end: "end",
            width: "channelWidth"
        },
        targetParams: {
            diameter: "channelWidth"
        },
        featurePrimitiveType: "EdgedRectLine",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Chamber: {
        featureParams: {
            start: "start",
            end: "end",
            borderWidth: "borderWidth"
        },
        targetParams: {
            diameter: "borderWidth"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "RoundedRect",
        targetPrimitiveSet: "Basic2D",
        targetPrimitiveType: "CircleTarget"
    },
    DiamondReactionChamber: {
        featureParams: {
            position: "position",
            orientation: "orientation",
            channelWidth: "channelWidth",
            length: "length",
            width: "width"
        },
        targetParams: {
            channelWidth: "channelWidth",
            length: "length",
            width: "width",
            orientation: "orientation"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "Diamond",
        targetPrimitiveType: "DiamondTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Mixer: {
        featureParams: {
            position: "position",
            channelWidth: "channelWidth",
            bendSpacing: "bendSpacing",
            numberOfBends: "numberOfBends",
            orientation: "orientation",
            bendLength: "bendLength"
        },
        targetParams: {
            channelWidth: "channelWidth",
            bendSpacing: "bendSpacing",
            numberOfBends: "numberOfBends",
            orientation: "orientation",
            bendLength: "bendLength"
        },
        featurePrimitiveType: "Mixer",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "MixerTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Tree: {
        featureParams: {
            position: "position",
            flowChannelWidth: "flowChannelWidth",
            orientation: "orientation",
            spacing: "spacing",
            width: "width",
            length: "length",
            leafs: "leafs",
            radius1: "width",
            radius2: "length"
        },
        targetParams: {
            flowChannelWidth: "flowChannelWidth",
            orientation: "orientation",
            spacing: "spacing",
            width: "width",
            length: "length",
            leafs: "leafs",
            radius1: "width",
            radius2: "length"
        },
        featurePrimitiveType: "Tree",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "TreeTarget",
        targetPrimitiveSet: "Basic2D"
    },
    CellTrapL: {
        featureParams: {
            position: "position",
            chamberLength: "chamberLength",
            feedingChannelWidth: "feedingChannelWidth",
            orientation: "orientation",
            chamberWidth: "chamberWidth",
            numberOfChambers: "numberOfChambers",
            chamberSpacing: "chamberSpacing",
            radius1: "chamberWidth",
            radius2: "chamberSpacing"
        },
        targetParams: {
            chamberLength: "chamberLength",
            feedingChannelWidth: "feedingChannelWidth",
            orientation: "orientation",
            chamberWidth: "chamberWidth",
            numberOfChambers: "numberOfChambers",
            chamberSpacing: "chamberSpacing",
            radius1: "chamberSpacing",
            radius2: "chamberSpacing"
        },
        featurePrimitiveType: "CellTrapL",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "CellTrapLTarget",
        targetPrimitiveSet: "Basic2D"
    },
    DropletGen: {
        featureParams: {
            position: "position",
            orificeSize: "orificeSize"
        },
        targetParams: {
            orificeSize: "orificeSize"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "DropletGen",
        targetPrimitiveType: "DropletGenTarget",
        targetPrimitiveSet: "Basic2D"
    },
};

module.exports = render2D;<commit_msg>Cleaned up channel rendering to be friendlier to large intersections (like with gradient generator)<commit_after>let render2D = {
    Via: {
        featureParams: {
            position: "position",
            radius1: "radius1",
            radius2: "radius2"
        },
        targetParams: {
            radius1: "radius1",
            radius2: "radius2"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GradientCircle",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Port: {
        featureParams: {
            position: "position",
            portRadius: "portRadius"
        },
        targetParams: {
            portRadius: "portRadius"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "PortCircle",
        targetPrimitiveType: "PortTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Node: {
        featureParams: {
            position: "position",
            radius1: "radius1",
            radius2: "radius2"
        },
        targetParams: {
            radius1: "radius1",
            radius2: "radius2"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GradientCircle",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    CircleValve: {
        featureParams: {
            position: "position",
            radius1: "radius1",
            radius2: "radius2"
        },
        targetParams: {
            radius1: "radius1",
            radius2: "radius2"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GradientCircle",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Valve3D: {
        featureParams: {
            position: "position",
            orientation: "orientation",
            radius1: "valveRadius",
            radius2: "valveRadius",
            valveRadius: "valveRadius",
            gap: "gap"
        },
        targetParams: {
            radius1: "valveRadius",
            radius2: "valveRadius"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "GroverValve",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Channel: {
        featureParams: {
            start: "start",
            end: "end",
            width: "channelWidth"
        },
        targetParams: {
            diameter: "channelWidth"
        },
        featurePrimitiveType: "RoundedRectLine",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "CircleTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Chamber: {
        featureParams: {
            start: "start",
            end: "end",
            borderWidth: "borderWidth"
        },
        targetParams: {
            diameter: "borderWidth"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "RoundedRect",
        targetPrimitiveSet: "Basic2D",
        targetPrimitiveType: "CircleTarget"
    },
    DiamondReactionChamber: {
        featureParams: {
            position: "position",
            orientation: "orientation",
            channelWidth: "channelWidth",
            length: "length",
            width: "width"
        },
        targetParams: {
            channelWidth: "channelWidth",
            length: "length",
            width: "width",
            orientation: "orientation"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "Diamond",
        targetPrimitiveType: "DiamondTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Mixer: {
        featureParams: {
            position: "position",
            channelWidth: "channelWidth",
            bendSpacing: "bendSpacing",
            numberOfBends: "numberOfBends",
            orientation: "orientation",
            bendLength: "bendLength"
        },
        targetParams: {
            channelWidth: "channelWidth",
            bendSpacing: "bendSpacing",
            numberOfBends: "numberOfBends",
            orientation: "orientation",
            bendLength: "bendLength"
        },
        featurePrimitiveType: "Mixer",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "MixerTarget",
        targetPrimitiveSet: "Basic2D"
    },
    Tree: {
        featureParams: {
            position: "position",
            flowChannelWidth: "flowChannelWidth",
            orientation: "orientation",
            spacing: "spacing",
            width: "width",
            length: "length",
            leafs: "leafs",
            radius1: "width",
            radius2: "length"
        },
        targetParams: {
            flowChannelWidth: "flowChannelWidth",
            orientation: "orientation",
            spacing: "spacing",
            width: "width",
            length: "length",
            leafs: "leafs",
            radius1: "width",
            radius2: "length"
        },
        featurePrimitiveType: "Tree",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "TreeTarget",
        targetPrimitiveSet: "Basic2D"
    },
    CellTrapL: {
        featureParams: {
            position: "position",
            chamberLength: "chamberLength",
            feedingChannelWidth: "feedingChannelWidth",
            orientation: "orientation",
            chamberWidth: "chamberWidth",
            numberOfChambers: "numberOfChambers",
            chamberSpacing: "chamberSpacing",
            radius1: "chamberWidth",
            radius2: "chamberSpacing"
        },
        targetParams: {
            chamberLength: "chamberLength",
            feedingChannelWidth: "feedingChannelWidth",
            orientation: "orientation",
            chamberWidth: "chamberWidth",
            numberOfChambers: "numberOfChambers",
            chamberSpacing: "chamberSpacing",
            radius1: "chamberSpacing",
            radius2: "chamberSpacing"
        },
        featurePrimitiveType: "CellTrapL",
        featurePrimitiveSet: "Basic2D",
        targetPrimitiveType: "CellTrapLTarget",
        targetPrimitiveSet: "Basic2D"
    },
    DropletGen: {
        featureParams: {
            position: "position",
            orificeSize: "orificeSize"
        },
        targetParams: {
            orificeSize: "orificeSize"
        },
        featurePrimitiveSet: "Basic2D",
        featurePrimitiveType: "DropletGen",
        targetPrimitiveType: "DropletGenTarget",
        targetPrimitiveSet: "Basic2D"
    },
};

module.exports = render2D;<|endoftext|>


<commit_before>/* global $ */

import {copied, slugify, positionCheck, returnCode} from './includes/utils.js';

// Load clipboard.js
// add functionality to all .copy
import Clipboard from 'clipboard';
new Clipboard('.copy');

function readmore(headlineSlug, link, headline) {
  var codeBlock = 'Read More'+ headline +'';

  return codeBlock;
}

$('#readmorecode_form').submit(function(e) {
  var headline = $('#readmore_headline').val(),
      link = $('#readmore_link').val(),
      headlineSlug = slugify(headline),
      codeBlock = readmore(headlineSlug, link, headline);

  returnCode(codeBlock, 'readmorecode');
  copied(this.id);
  e.preventDefault();
});

function twitterinline(sentence, sentenceEncode, hashtag) {
  var codeBlock;

  if(hashtag) {
    codeBlock = '' + sentence + '';
  } else {
    codeBlock = '' + sentence + '';
  }

  return codeBlock;
}

$('#twitterinlinecode_form').submit(function(e) {
  var shareSentence = $('#twitterinline_sentence').val(),
      shareSentenceEncoded = encodeURI(shareSentence),
      shareHashtag = $('#twitterinline_hashtag').val().replace(/\s+/g, ''),
      codeBlock = twitterinline(shareSentence, shareSentenceEncoded, shareHashtag),
      shareSentenceLength = shareSentence.length,
      shareHashtagLength = shareHashtag.length,
      shareLength = shareSentenceLength + shareHashtagLength,
      shareSentenceLengthHTML = $('#twitterinline_sentence_length');

  if(shareLength >= 110) {
    $('#twitterinline_warning').removeClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  } else {
    $('#twitterinline_warning').addClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  }

  returnCode(codeBlock, 'twitterinlinecode');
  copied(this.id);
  e.preventDefault();
});

function pullquote(type, text, speaker, color, positionVal) {
  var codeBlock;

  if (type === 'quote') {
    codeBlock = '“' + text + '”— ' + speaker + '';
  } else {
    codeBlock = '' + text + '';
  }

  return codeBlock;
}

$('#pulltextcode_form').change(function(e) {
  var type = $('input[name=type]:checked').val();
  if (type === 'quote') {
    $('.quote-label').show();
    $('.speaker-label').show();
    $('.speaker-input').show();
    $('.text-label').hide();
  } else {
    $('.quote-label').hide();
    $('.speaker-label').hide();
    $('.speaker-input').hide();
    $('.text-label').show();
  }
});

$('#pulltextcode_form').submit(function(e) {
  var type = $('input[name=type]:checked').val(),
      colorVal = $('input[name=color]:checked').val(),
      color,
      positionVal = $('input[name=position]:checked').val(),
      text = $('#pullquote_quote').val(),
      speaker = $('#pullquote_speaker').val();

  if (colorVal === 'bsp') {
    color = '#925352';
  } else {
    color = 'rgb(255, 194, 0)';
  }

  var codeBlock = pullquote(type, text, speaker, color, positionVal);
  returnCode (codeBlock, 'pulltextcode');
  copied(this.id);

  e.preventDefault();
});

function photoEmbed(url, credit, caption, position) {
  var codeBlock = '

Enlarge Photo by: ' + credit + '

' + caption + '

';

  return codeBlock;
}

$('#photoembedcode_form').submit(function(e) {
  var positionVal = $('input[name=photoPosition]:checked').val(),
      url = $('#photoEmbed_URL').val(),
      credit = $('#photoEmbed_credit').val(),
      caption = $('#photoEmbed_caption').val(),
      position = positionCheck(positionVal, 'photo'),
      codeBlock = photoEmbed(url, credit, caption, position);

  returnCode(codeBlock, 'photoembedcode');
  copied(this.id);
  e.preventDefault();
});

function videoEmbed(video, host, width, height) {
  var codeBlock = '

';

  return codeBlock;
}

$('#videoembedcode_form').submit(function(e) {
  var videoID = $('#videoID').val(),
      videoHost = $('input[name=videoHost]:checked').val(),
      width = $('#videoWidth').val(),
      height = $('#videoHeight').val(),
      video;

  if(videoHost === 'youtube') {
    video = 'https://www.youtube.com/embed/' + videoID;
  } else {
    video = 'https://player.vimeo.com/video/' + videoID;
  }

  var codeBlock = videoEmbed(video, videoHost, width, height);
  returnCode (codeBlock, 'videoembedcode');

  copied(this.id);

  e.preventDefault();
});

function seriesHeader(series) {
  var codeBlock;

  if (series === 'bsp') {
    codeBlock = '

The Texas Tribune is taking a yearlong look at the issues of border security and immigration, reporting on the reality and rhetoric around these topics. Sign up to get story alerts.

';
  } else if (series === 'rough-patch') {
    codeBlock = '

How plunging oil prices are reversing fortunes across Texas. Read all the stories in this series.

';
  } else if (series === 'mental-health-matters') {
    codeBlock = '
Throughout Mental Health Month in May, The Texas Tribune is partnering with Mental Health Channel and KLRU to focus on some of Texas’ biggest challenges in providing mental health care. See all the stories in this series.

';
  }

  return codeBlock;
}

function initializePreviews() {
  var readmorecode = readmore('test', 'https://', 'This is a test headline'),
      twitterinlinecode = twitterinline('This is preview sentence', '', '');

  $('#readmorecode_preview').html(readmorecode);
  $('#twitterinlinecode_preview').html(twitterinlinecode);
}

$('#seriesheadercode_form').submit(function(e) {
  var series = $('input[name=series]:checked').val();

  var codeBlock = seriesHeader(series);
  returnCode (codeBlock, 'seriesheadercode');

  copied(this.id);

  e.preventDefault();
});
initializePreviews();
<commit_msg>Update readmore code to make fb instant happy too<commit_after>/* global $ */

import {copied, slugify, positionCheck, returnCode} from './includes/utils.js';

// Load clipboard.js
// add functionality to all .copy
import Clipboard from 'clipboard';
new Clipboard('.copy');

function readmore(headlineSlug, link, headline) {
  var codeBlock = '

Read More '+ headline +'

';

  return codeBlock;
}

$('#readmorecode_form').submit(function(e) {
  var headline = $('#readmore_headline').val(),
      link = $('#readmore_link').val(),
      headlineSlug = slugify(headline),
      codeBlock = readmore(headlineSlug, link, headline);

  returnCode(codeBlock, 'readmorecode');
  copied(this.id);
  e.preventDefault();
});

function twitterinline(sentence, sentenceEncode, hashtag) {
  var codeBlock;

  if(hashtag) {
    codeBlock = '' + sentence + '';
  } else {
    codeBlock = '' + sentence + '';
  }

  return codeBlock;
}

$('#twitterinlinecode_form').submit(function(e) {
  var shareSentence = $('#twitterinline_sentence').val(),
      shareSentenceEncoded = encodeURI(shareSentence),
      shareHashtag = $('#twitterinline_hashtag').val().replace(/\s+/g, ''),
      codeBlock = twitterinline(shareSentence, shareSentenceEncoded, shareHashtag),
      shareSentenceLength = shareSentence.length,
      shareHashtagLength = shareHashtag.length,
      shareLength = shareSentenceLength + shareHashtagLength,
      shareSentenceLengthHTML = $('#twitterinline_sentence_length');

  if(shareLength >= 110) {
    $('#twitterinline_warning').removeClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  } else {
    $('#twitterinline_warning').addClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  }

  returnCode(codeBlock, 'twitterinlinecode');
  copied(this.id);
  e.preventDefault();
});

function pullquote(type, text, speaker, color, positionVal) {
  var codeBlock;

  if (type === 'quote') {
    codeBlock = '“' + text + '”— ' + speaker + '';
  } else {
    codeBlock = '' + text + '';
  }

  return codeBlock;
}

$('#pulltextcode_form').change(function(e) {
  var type = $('input[name=type]:checked').val();
  if (type === 'quote') {
    $('.quote-label').show();
    $('.speaker-label').show();
    $('.speaker-input').show();
    $('.text-label').hide();
  } else {
    $('.quote-label').hide();
    $('.speaker-label').hide();
    $('.speaker-input').hide();
    $('.text-label').show();
  }
});

$('#pulltextcode_form').submit(function(e) {
  var type = $('input[name=type]:checked').val(),
      colorVal = $('input[name=color]:checked').val(),
      color,
      positionVal = $('input[name=position]:checked').val(),
      text = $('#pullquote_quote').val(),
      speaker = $('#pullquote_speaker').val();

  if (colorVal === 'bsp') {
    color = '#925352';
  } else {
    color = 'rgb(255, 194, 0)';
  }

  var codeBlock = pullquote(type, text, speaker, color, positionVal);
  returnCode (codeBlock, 'pulltextcode');
  copied(this.id);

  e.preventDefault();
});

function photoEmbed(url, credit, caption, position) {
  var codeBlock = '

Enlarge Photo by: ' + credit + '

' + caption + '

';

  return codeBlock;
}

$('#photoembedcode_form').submit(function(e) {
  var positionVal = $('input[name=photoPosition]:checked').val(),
      url = $('#photoEmbed_URL').val(),
      credit = $('#photoEmbed_credit').val(),
      caption = $('#photoEmbed_caption').val(),
      position = positionCheck(positionVal, 'photo'),
      codeBlock = photoEmbed(url, credit, caption, position);

  returnCode(codeBlock, 'photoembedcode');
  copied(this.id);
  e.preventDefault();
});

function videoEmbed(video, host, width, height) {
  var codeBlock = '

';

  return codeBlock;
}

$('#videoembedcode_form').submit(function(e) {
  var videoID = $('#videoID').val(),
      videoHost = $('input[name=videoHost]:checked').val(),
      width = $('#videoWidth').val(),
      height = $('#videoHeight').val(),
      video;

  if(videoHost === 'youtube') {
    video = 'https://www.youtube.com/embed/' + videoID;
  } else {
    video = 'https://player.vimeo.com/video/' + videoID;
  }

  var codeBlock = videoEmbed(video, videoHost, width, height);
  returnCode (codeBlock, 'videoembedcode');

  copied(this.id);

  e.preventDefault();
});

function seriesHeader(series) {
  var codeBlock;

  if (series === 'bsp') {
    codeBlock = '

The Texas Tribune is taking a yearlong look at the issues of border security and immigration, reporting on the reality and rhetoric around these topics. Sign up to get story alerts.

';
  } else if (series === 'rough-patch') {
    codeBlock = '

How plunging oil prices are reversing fortunes across Texas. Read all the stories in this series.

';
  } else if (series === 'mental-health-matters') {
    codeBlock = '
Throughout Mental Health Month in May, The Texas Tribune is partnering with Mental Health Channel and KLRU to focus on some of Texas’ biggest challenges in providing mental health care. See all the stories in this series.

';
  }

  return codeBlock;
}

function initializePreviews() {
  var readmorecode = readmore('test', 'https://', 'This is a test headline'),
      twitterinlinecode = twitterinline('This is preview sentence', '', '');

  $('#readmorecode_preview').html(readmorecode);
  $('#twitterinlinecode_preview').html(twitterinlinecode);
}

$('#seriesheadercode_form').submit(function(e) {
  var series = $('input[name=series]:checked').val();

  var codeBlock = seriesHeader(series);
  returnCode (codeBlock, 'seriesheadercode');

  copied(this.id);

  e.preventDefault();
});
initializePreviews();
<|endoftext|>


<commit_before>import $ from "jquery";

import L from "leaflet";
import "leaflet-rotatedmarker";
import "leaflet/dist/leaflet.css";

import { LeafletPolylineWidget } from "./leaflet/LeafletWidget";

import { addAmbulanceRoute, createMarker } from "./map_tools";

function addCallToMap(call, map) {

    console.log('Adding call to map');
    // console.log(call);

    // waypoint markers
    const icon = icon || L.icon({
        iconUrl: '/static/icons/maki/marker-15.svg',
        iconSize: [15, 30],
    });

    // loop through ambulancecall records
    call['ambulancecall_set'].forEach(function (ambulancecall) {

        console.log('Adding ambulancecall');
        // console.log(ambulancecall);

        // loop through waypoints
        ambulancecall['waypoint_set'].forEach(function (waypoint) {

            console.log('Adding waypoint');
            // console.log(waypoint);

            // waypoint label
            let label = location_type[waypoint['location']['type']];
            if (waypoint['location']['name'])
                label += ": " + waypoint['location']['name'];

            // add waypoint markers
            createMarker(waypoint['location'], icon)
                .addTo(map.map)
                .bindPopup("" + label + "")
                .on('mouseover',
                    function () {
                        // open popup bubble
                        this.openPopup().on('mouseout',
                            function () {
                                this.closePopup();
                            });
                    });
        });

        // add ambulance updates
        retrieveAmbulanceUpdates(ambulancecall['ambulance_id'], call['id'], map);

    });

}

function retrieveCall(call_id, map) {

    console.log("Retrieving call '" + call_id + "'from API");

    // Build url
    const url = APIBaseUrl + 'call/' + call_id + '/?exclude=';

    $.ajax({
        type: 'GET',
        datatype: "json",
        url: url,

        fail: function (msg) {

            alert('Could not retrieve call from API:' + msg);

        },

        success: function (data) {

            console.log("Got call '" + call_id + "'from API");
            addCallToMap(data, map);

        }

    })
        .done(function () {
            if (console && console.log) {
                console.log("Done retrieving call '" + call_id + "' from API");
            }
        });

}

function retrieveAmbulanceUpdates(ambulance_id, call_id, map) {

    console.log("Retrieving ambulance '" + ambulance_id + "' from API");

    // Build url
    const url = APIBaseUrl + 'ambulance/' + ambulance_id + '/updates/?call_id=' + call_id;

    $.ajax({
        type: 'GET',
        datatype: "json",
        url: url,

        fail: function (msg) {

            alert('Could not retrieve ambulance updates from API:' + msg);

        },

        success: function (data) {

            console.log("Got '" + data.length + "' ambulance '" + ambulance_id + "' updates from API");
            addAmbulanceRoute(map, data, true);

        }

    })
        .done(function () {
            if (console && console.log) {
                console.log("Done retrieving ambulance '" + ambulance_id + "' updates from API");
            }
        });

}

$(function () {

    // Set up map widget
    const options = {
        map_id: "map",
        zoom: 12,
        access_token: access_token
    };
    const map = new LeafletPolylineWidget(options);

    // Retrieve call
    retrieveCall(call_id, map);

});

<commit_msg>Bundling point widget.<commit_after>import $ from "jquery";

import L from "leaflet";
import "leaflet-rotatedmarker";
import "leaflet/dist/leaflet.css";

import { LeafletPolylineWidget } from "./leaflet/LeafletWidget";

import { addAmbulanceRoute, createMarker } from "./map_tools";

function addCallToMap(call, map, icon) {

    console.log('Adding call to map');
    // console.log(call);

    // waypoint markers
    icon = icon || L.icon({
        iconUrl: '/static/icons/maki/marker-15.svg',
        iconSize: [15, 30],
    });

    // loop through ambulancecall records
    call['ambulancecall_set'].forEach(function (ambulancecall) {

        console.log('Adding ambulancecall');
        // console.log(ambulancecall);

        // loop through waypoints
        ambulancecall['waypoint_set'].forEach(function (waypoint) {

            console.log('Adding waypoint');
            // console.log(waypoint);

            // waypoint label
            let label = location_type[waypoint['location']['type']];
            if (waypoint['location']['name'])
                label += ": " + waypoint['location']['name'];

            // add waypoint markers
            createMarker(waypoint['location'], icon)
                .addTo(map.map)
                .bindPopup("" + label + "")
                .on('mouseover',
                    function () {
                        // open popup bubble
                        this.openPopup().on('mouseout',
                            function () {
                                this.closePopup();
                            });
                    });
        });

        // add ambulance updates
        retrieveAmbulanceUpdates(ambulancecall['ambulance_id'], call['id'], map);

    });

}

function retrieveCall(call_id, map) {

    console.log("Retrieving call '" + call_id + "'from API");

    // Build url
    const url = APIBaseUrl + 'call/' + call_id + '/?exclude=';

    $.ajax({
        type: 'GET',
        datatype: "json",
        url: url,

        fail: function (msg) {

            alert('Could not retrieve call from API:' + msg);

        },

        success: function (data) {

            console.log("Got call '" + call_id + "'from API");
            addCallToMap(data, map);

        }

    })
        .done(function () {
            if (console && console.log) {
                console.log("Done retrieving call '" + call_id + "' from API");
            }
        });

}

function retrieveAmbulanceUpdates(ambulance_id, call_id, map) {

    console.log("Retrieving ambulance '" + ambulance_id + "' from API");

    // Build url
    const url = APIBaseUrl + 'ambulance/' + ambulance_id + '/updates/?call_id=' + call_id;

    $.ajax({
        type: 'GET',
        datatype: "json",
        url: url,

        fail: function (msg) {

            alert('Could not retrieve ambulance updates from API:' + msg);

        },

        success: function (data) {

            console.log("Got '" + data.length + "' ambulance '" + ambulance_id + "' updates from API");
            addAmbulanceRoute(map, data, true);

        }

    })
        .done(function () {
            if (console && console.log) {
                console.log("Done retrieving ambulance '" + ambulance_id + "' updates from API");
            }
        });

}

$(function () {

    // Set up map widget
    const options = {
        map_id: "map",
        zoom: 12,
        access_token: access_token
    };
    const map = new LeafletPolylineWidget(options);

    // Retrieve call
    retrieveCall(call_id, map);

});

<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Randomolunk Egyet",

  bet_request: function(game_state, bet) {
    bet(10);
  },

  showdown: function(game_state) {

  }
};
<commit_msg>except<commit_after>
module.exports = {

  VERSION: "Randomolunk Egyet",

  bet_request: function(game_state, bet) {
    try {
      bet(100);
    } catch (e) {
      console.log(e);
      bet(0);
    }
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>/*
 * Interactions in the Game are governed by Cards and their managers: Prompt, Response, and Feedback objects.
 *
 */

/* FAILSAFE */
Game = Game || function () {};

/*
 * Cards
 * Cards represent interactions with the player. They are represented by some DOM element(s).
 * The generic Card prototype specifies a generic 'deal' function,
 * but that can be overridden by 'deal' function passed in a card spec.
 * Alternately, other Card prototypes can be defined on the Game object,
 * specifying animations, interactivity, even peer-to-peer communications through "cards."
 */
Game.Card = function(spec) {
	if (spec === null) {
		return; // this is when we are creating a Card to be a prototype for another type of object.
	} else if (spec instanceof String) {
		spec = spec.toString();
	}

	// some card-related constants.
	Game.Card.SEND_TO_BACK = -1;

	// save the spec, in case we need to manipulate the card contents later on.
	this.spec = spec;

	// make space to save any dealer I'm associated with.
	this.dealer = {};

	// we want to always have a single HTML element to represent each Card.
	if ( ((spec instanceof HTMLElement) || (spec instanceof jQuery))
		&& ($(spec).attr("data-keep-in-dom") === "true")) {
		this.element = $(spec);
	} else {
		// remove 'type' from spec
		var card_type = spec.type || "";
		delete spec.type

		in_production_try(this, function () {
			var card_scaffold = $(document.createElement("div"));
			var rendered_element = card_scaffold.render(spec.content || spec);
			this.load_promise = rendered_element.data().promise;

			// we want to always have a single HTML element to represent each Card.
			// so if the spec has generated siblings, we wrap them in a div.
			var nodes_in_card = card_scaffold.get(0).childNodes;
			switch (nodes_in_card.length) {
				case 0:
					throw new Error("Failed to create Card.");
					break;

				case 1:
					// if it is a text node, use card_scaffold as the Card element.
					// otherwise, use the child node.
					var node = nodes_in_card[0];
					this.element = (node.nodeType == 3) ? card_scaffold : $(node);
					break;

				default:
					this.element = card_scaffold;
					break;
			}
		});
	}

	// add the generic card class.
	// keep track of this Card via the jQuery data for the element.
	// this will work, even if we use another jQuery selector to select this one element.
	this.element.addClass("card").data("card", this);
	if (card_type) {
		this.element.addClass(card_type);
	}

	// add any other specified css_classes.
	if (spec.css_class || false) {
		this.element.addClass(spec.css_class);
	}

	// respond to user and game actions and track what will get reported to the db.
	this.history = [];

	// will have to list out all types of Card events.
	var _this = this;
	this.element.on("Card.userInput", function (evt, data) {
		if (_this.element.is(this)) {
			var answer;
			try {
				data = data.answer;
			} catch (e) {
				data = JSON.stringify(data);
			}
			_this.history.push({ event: evt.namespace, data: data, timestamp: evt.timeStamp });
		}
	});
}

// default values for cards.
Game.Card.DEFAULTS = {
	timeout: null
};

Game.Card.prototype.style = function (css_classes) {
	// remove card class and then add back those specified.
	// this is done so we can keep cards out the 'clearCards' function.
	// TODO: *** Look into a better way to do this. cards should remain '.card's ***
	this.element.removeClass("card").addClass(css_classes);
	return this; // for daisy-chaining.
}

Game.Card.prototype.find = function (selector) {
	// just pass to element.
	return this.element.find(selector);
}

// default way to activate/deactivate card is to set disabled attr on any input(s) and/or link(s) in the card.
// we also set disabled on the card, in case it IS the interactive element, or if we want to do css on the card.
Game.Card.prototype.setActive = function (flag) {
	$(this.element).find("input, a").addBack().prop( "disabled", !flag );
}

Game.Card.prototype.dealTo = function (container) {
	// find or create a place in the game in which to put the cards.
	var container_spec = container || this.spec.container || this.dealer.container;
	this.container = $(container_spec);
	if (this.container.length == 0) {
		this.container = $("#game");
	}
	$(this.container).append(this.element);
}

Game.Card.prototype.unbindEvents = function (in_event_names) {
	// remove passed-in (or any) events bound to the card element, or any nested input or link elements.
	var interactive_elements = this.element.find("input, a").addBack();
	$(interactive_elements).each(function () {
		var event_names = in_event_names || ( Object.keys($._data(this, "events") || {}).join(" ") );
		$(this).off(event_names);
	});
}

Game.Card.prototype.remove = function () {
	this.unbindEvents();
	this.element.remove();
}

// what I tell the Reporter about myself.
Game.Card.prototype.getHistory = function () {
	return this.history;
}

// return a descriptor string from the spec or create a jQuery descriptor for my element.
Game.Card.prototype.getDescriptor = function () {
	if (typeof this.spec === "string") {
		return this.spec;
	} else {
		return Util.createDescriptor(this.element.get(0));
	}
}

// a create method for basic Card types (as opposed to those controlled by Dealers).
Game.Card.create = function (spec) {
	var card_class = spec["type"] || "Card";
	var card;
	if (card_class === "Card"){
		card = new Game.Card(spec);
	} else {
		card = new Game.Card[card_class](spec);
	}
	return card;
}

/*
 * Game.Card.Modal
 * Cards which 'stop the action' & require a user response.
 */
Game.Card.Modal = Util.extendClass(Game.Card, function (spec) {
  Game.Card.call(this, spec);
	// add the bit where we wait for the user.
	this.user_input_dfd = $.Deferred();
	this.user_input_promise = this.user_input_dfd.promise();
},
{
  dealTo: function (container) {
  	Game.Card.prototype.dealTo.call(this, container);
  	this.addOKButton();
  	return true;
  },

  addOKButton: function () {
  	// once the user clicks to continue, we can move onto the game.
  	// for now, we"re going to stick to the notion that all intros require a click to continue.
  	if (this.element.find("button.continue").length > 0) {
  		return;
  	}
  	var _this = this;
  	var ok_button = $(document.createElement("button"))
  										.attr("href", "#")
  										.addClass("continue")
  										.html("Continue").click(function () {
  		_this.user_input_dfd.resolve();
  		_this.remove();
  	});
  	ok_button.appendTo(this.element);
  }
});<commit_msg>save & remove css_class when passed in as pt of spec.<commit_after>/*
 * Interactions in the Game are governed by Cards and their managers: Prompt, Response, and Feedback objects.
 *
 */

/* FAILSAFE */
Game = Game || function () {};

/*
 * Cards
 * Cards represent interactions with the player. They are represented by some DOM element(s).
 * The generic Card prototype specifies a generic 'deal' function,
 * but that can be overridden by 'deal' function passed in a card spec.
 * Alternately, other Card prototypes can be defined on the Game object,
 * specifying animations, interactivity, even peer-to-peer communications through "cards."
 */
Game.Card = function(spec) {
	if (spec === null) {
		return; // this is when we are creating a Card to be a prototype for another type of object.
	} else if (spec instanceof String) {
		spec = spec.toString();
	}

	// some card-related constants.
	Game.Card.SEND_TO_BACK = -1;

  // save any custom style passed in.
  var css_class;
  if (spec.hasOwnProperty("css_class")) {
    css_class = spec.css_class;
    delete spec.css_class
  }

	// save the spec, in case we need to manipulate the card contents later on.
	this.spec = spec;

	// make space to save any dealer I'm associated with.
	this.dealer = {};

	// we want to always have a single HTML element to represent each Card.
	if ( ((spec instanceof HTMLElement) || (spec instanceof jQuery))
		&& ($(spec).attr("data-keep-in-dom") === "true")) {
		this.element = $(spec);
	} else {
		// remove 'type' from spec
		var card_type = spec.type || "";
		delete spec.type

		in_production_try(this, function () {
			var card_scaffold = $(document.createElement("div"));
			var rendered_element = card_scaffold.render(spec.content || spec);
			this.load_promise = rendered_element.data().promise;

			// we want to always have a single HTML element to represent each Card.
			// so if the spec has generated siblings, we wrap them in a div.
			var nodes_in_card = card_scaffold.get(0).childNodes;
			switch (nodes_in_card.length) {
				case 0:
					throw new Error("Failed to create Card.");
					break;

				case 1:
					// if it is a text node, use card_scaffold as the Card element.
					// otherwise, use the child node.
					var node = nodes_in_card[0];
					this.element = (node.nodeType == 3) ? card_scaffold : $(node);
					break;

				default:
					this.element = card_scaffold;
					break;
			}
		});
	}

	// add the generic card class.
	// keep track of this Card via the jQuery data for the element.
	// this will work, even if we use another jQuery selector to select this one element.
	this.element.addClass("card").data("card", this);
	if (card_type) {
		this.element.addClass(card_type);
	}

	// add any other saved css_classes.
	if (css_class || false) {
		this.element.addClass(css_class);
	}

	// respond to user and game actions and track what will get reported to the db.
	this.history = [];

	// will have to list out all types of Card events.
	var _this = this;
	this.element.on("Card.userInput", function (evt, data) {
		if (_this.element.is(this)) {
			var answer;
			try {
				data = data.answer;
			} catch (e) {
				data = JSON.stringify(data);
			}
			_this.history.push({ event: evt.namespace, data: data, timestamp: evt.timeStamp });
		}
	});
}

// default values for cards.
Game.Card.DEFAULTS = {
	timeout: null
};

Game.Card.prototype.style = function (css_classes) {
	// remove card class and then add back those specified.
	// this is done so we can keep cards out the 'clearCards' function.
	// TODO: *** Look into a better way to do this. cards should remain '.card's ***
	this.element.removeClass("card").addClass(css_classes);
	return this; // for daisy-chaining.
}

Game.Card.prototype.find = function (selector) {
	// just pass to element.
	return this.element.find(selector);
}

// default way to activate/deactivate card is to set disabled attr on any input(s) and/or link(s) in the card.
// we also set disabled on the card, in case it IS the interactive element, or if we want to do css on the card.
Game.Card.prototype.setActive = function (flag) {
	$(this.element).find("input, a").addBack().prop( "disabled", !flag );
}

Game.Card.prototype.dealTo = function (container) {
	// find or create a place in the game in which to put the cards.
	var container_spec = container || this.spec.container || this.dealer.container;
	this.container = $(container_spec);
	if (this.container.length == 0) {
		this.container = $("#game");
	}
	$(this.container).append(this.element);
}

Game.Card.prototype.unbindEvents = function (in_event_names) {
	// remove passed-in (or any) events bound to the card element, or any nested input or link elements.
	var interactive_elements = this.element.find("input, a").addBack();
	$(interactive_elements).each(function () {
		var event_names = in_event_names || ( Object.keys($._data(this, "events") || {}).join(" ") );
		$(this).off(event_names);
	});
}

Game.Card.prototype.remove = function () {
	this.unbindEvents();
	this.element.remove();
}

// what I tell the Reporter about myself.
Game.Card.prototype.getHistory = function () {
	return this.history;
}

// return a descriptor string from the spec or create a jQuery descriptor for my element.
Game.Card.prototype.getDescriptor = function () {
	if (typeof this.spec === "string") {
		return this.spec;
	} else {
		return Util.createDescriptor(this.element.get(0));
	}
}

// a create method for basic Card types (as opposed to those controlled by Dealers).
Game.Card.create = function (spec) {
	var card_class = spec["type"] || "Card";
	var card;
	if (card_class === "Card"){
		card = new Game.Card(spec);
	} else {
		card = new Game.Card[card_class](spec);
	}
	return card;
}

/*
 * Game.Card.Modal
 * Cards which 'stop the action' & require a user response.
 */
Game.Card.Modal = Util.extendClass(Game.Card, function (spec) {
  Game.Card.call(this, spec);
	// add the bit where we wait for the user.
	this.user_input_dfd = $.Deferred();
	this.user_input_promise = this.user_input_dfd.promise();
},
{
  dealTo: function (container) {
  	Game.Card.prototype.dealTo.call(this, container);
  	this.addOKButton();
  	return true;
  },

  addOKButton: function () {
  	// once the user clicks to continue, we can move onto the game.
  	// for now, we"re going to stick to the notion that all intros require a click to continue.
  	if (this.element.find("button.continue").length > 0) {
  		return;
  	}
  	var _this = this;
  	var ok_button = $(document.createElement("button"))
  										.attr("href", "#")
  										.addClass("continue")
  										.html("Continue").click(function () {
  		_this.user_input_dfd.resolve();
  		_this.remove();
  	});
  	ok_button.appendTo(this.element);
  }
});<|endoftext|>


<commit_before>import React from 'react'
import Icon from '../components/Icon'
import { position } from '../util/scrolling'
import { closeModal } from '../actions'
// circular import; code smell; refactor?
import BrowseTopicsModal from '../containers/BrowseTopicsModal'
import ShareTopicModal from '../containers/ShareTopicModal'
import ExpandedPostModal from '../containers/ExpandedPostModal'
import DirectMessageModal from '../containers/DirectMessageModal'
import ChecklistModal from '../containers/ChecklistModal'
import TagEditorModal from '../containers/TagEditorModal'
import AddLogoModal from '../containers/AddLogoModal'
import InviteModal from '../containers/InviteModal'
import PostEditorModal from '../containers/PostEditorModal'
import { NotificationsModal } from '../containers/Notifications'
import cx from 'classnames'
import { get } from 'lodash/fp'
const { array, bool, func, node, object, string, oneOfType } = React.PropTypes

export const modalWrapperCSSId = 'top-level-modal-wrapper'
const mainColumnWidth = 688 // defined in CSS

// this has to cover the cases:
//  - desktop, left nav open
//  - desktop, left nav closed
//  - mobile
//
const modalStyle = isMobile => {
  if (typeof window === 'undefined') return {}
  const main = document.getElementById('main')
  const marginLeft = Math.max((main.offsetWidth - mainColumnWidth) / 2, 0) + main.offsetLeft
  return {marginLeft}
}

export class BareModalWrapper extends React.Component {
  static propTypes = {children: object, onClick: func, top: bool}

  render () {
    const { children, top } = this.props
    const onClick = event => {
      if (event.target !== this.refs.backdrop) return
      return this.props.onClick(event)
    }

    return

      {top
        ?

            {children}

        :

            {children}

}

  }
}

export class ModalWrapper extends React.Component {
  static propTypes = {type: string, params: object, top: bool, bottom: bool}
  static defaultProps = {top: true}
  static contextTypes = {dispatch: func}

  lockScrolling = () => {
    window.scrollTo(0, this.lockedScrollTop)
  }

  componentDidMount () {
    if (this.props.bottom) {
      this.lockedScrollTop = document.body.scrollTop
      window.addEventListener('scroll', this.lockScrolling)
    }
  }

  componentWillUnmount () {
    if (this.props.bottom) window.removeEventListener('scroll', this.lockScrolling)
  }

  render () {
    const { type, params, top } = this.props
    const { dispatch } = this.context
    if (!type) return null

    let modal, clickToClose
    const close = () => dispatch(closeModal())
    switch (type) {
      case 'tags':
        modal = <BrowseTopicsModal onCancel={close}/>
        clickToClose = true
        break
      case 'share-tag':
        modal = <ShareTopicModal tagName={params.tagName} slug={params.slug}
          onCancel={close}/>
        clickToClose = true
        break
      case 'expanded-post':
        modal = <ExpandedPostModal id={params.id} commentId={params.commentId}/>
        clickToClose = true
        break
      case 'direct-message':
        modal = <DirectMessageModal userId={params.userId} userName={params.userName} onCancel={close}/>
        clickToClose = true
        break
      case 'notifications':
        modal = <NotificationsModal onCancel={close}/>
        clickToClose = true
        break
      case 'checklist':
        modal = <ChecklistModal onCancel={close}/>
        clickToClose = true
        break
      case 'tag-editor':
        modal = <TagEditorModal onCancel={close}
          saveParent={params.saveParent}
          useCreatedTag={params.useCreatedTag}
          creating={params.creating}/>
        clickToClose = true
        break
      case 'add-logo':
        modal = <AddLogoModal onCancel={close}/>
        clickToClose = true
        break
      case 'invite':
        modal = <InviteModal onCancel={close}/>
        clickToClose = true
        break
      case 'post-editor':
        modal = <PostEditorModal post={get('post', params)} onCancel={close}/>
        clickToClose = true
        break
    }

    return <BareModalWrapper top={top} onClick={() => clickToClose && close()}>
      {modal}
    </BareModalWrapper>
  }
}

export const ModalContainer = (props, { isMobile }) => {
  const { id, className, children, standalone } = props
  return

    {children}

}
ModalContainer.propTypes = {
  id: string,
  children: oneOfType([array, object]),
  className: string,
  standalone: bool
}
ModalContainer.contextTypes = {isMobile: bool}

export const Modal = (props, { isMobile }) => {
  const { children, title, subtitle, onCancel, standalone } = props
  return <ModalContainer {...props}>
    {(title || subtitle) &&

        {title}
        {!standalone &&
          <Icon name='Fail'/>
        }

      {subtitle &&

        {subtitle}

}

}
    {children}
  </ModalContainer>
}
Modal.propTypes = {
  id: string,
  children: oneOfType([array, object]),
  className: string,
  onCancel: func,
  subtitle: oneOfType([string, node]),
  standalone: bool,
  title: oneOfType([string, object])
}
Modal.contextTypes = {isMobile: bool}

export default Modal
<commit_msg>remove unused import<commit_after>import React from 'react'
import Icon from '../components/Icon'
import { closeModal } from '../actions'
// circular import; code smell; refactor?
import BrowseTopicsModal from '../containers/BrowseTopicsModal'
import ShareTopicModal from '../containers/ShareTopicModal'
import ExpandedPostModal from '../containers/ExpandedPostModal'
import DirectMessageModal from '../containers/DirectMessageModal'
import ChecklistModal from '../containers/ChecklistModal'
import TagEditorModal from '../containers/TagEditorModal'
import AddLogoModal from '../containers/AddLogoModal'
import InviteModal from '../containers/InviteModal'
import PostEditorModal from '../containers/PostEditorModal'
import { NotificationsModal } from '../containers/Notifications'
import cx from 'classnames'
import { get } from 'lodash/fp'
const { array, bool, func, node, object, string, oneOfType } = React.PropTypes

export const modalWrapperCSSId = 'top-level-modal-wrapper'
const mainColumnWidth = 688 // defined in CSS

// this has to cover the cases:
//  - desktop, left nav open
//  - desktop, left nav closed
//  - mobile
//
const modalStyle = isMobile => {
  if (typeof window === 'undefined') return {}
  const main = document.getElementById('main')
  const marginLeft = Math.max((main.offsetWidth - mainColumnWidth) / 2, 0) + main.offsetLeft
  return {marginLeft}
}

export class BareModalWrapper extends React.Component {
  static propTypes = {children: object, onClick: func, top: bool}

  render () {
    const { children, top } = this.props
    const onClick = event => {
      if (event.target !== this.refs.backdrop) return
      return this.props.onClick(event)
    }

    return

      {top
        ?

            {children}

        :

            {children}

}

  }
}

export class ModalWrapper extends React.Component {
  static propTypes = {type: string, params: object, top: bool, bottom: bool}
  static defaultProps = {top: true}
  static contextTypes = {dispatch: func}

  lockScrolling = () => {
    window.scrollTo(0, this.lockedScrollTop)
  }

  componentDidMount () {
    if (this.props.bottom) {
      this.lockedScrollTop = document.body.scrollTop
      window.addEventListener('scroll', this.lockScrolling)
    }
  }

  componentWillUnmount () {
    if (this.props.bottom) window.removeEventListener('scroll', this.lockScrolling)
  }

  render () {
    const { type, params, top } = this.props
    const { dispatch } = this.context
    if (!type) return null

    let modal, clickToClose
    const close = () => dispatch(closeModal())
    switch (type) {
      case 'tags':
        modal = <BrowseTopicsModal onCancel={close}/>
        clickToClose = true
        break
      case 'share-tag':
        modal = <ShareTopicModal tagName={params.tagName} slug={params.slug}
          onCancel={close}/>
        clickToClose = true
        break
      case 'expanded-post':
        modal = <ExpandedPostModal id={params.id} commentId={params.commentId}/>
        clickToClose = true
        break
      case 'direct-message':
        modal = <DirectMessageModal userId={params.userId} userName={params.userName} onCancel={close}/>
        clickToClose = true
        break
      case 'notifications':
        modal = <NotificationsModal onCancel={close}/>
        clickToClose = true
        break
      case 'checklist':
        modal = <ChecklistModal onCancel={close}/>
        clickToClose = true
        break
      case 'tag-editor':
        modal = <TagEditorModal onCancel={close}
          saveParent={params.saveParent}
          useCreatedTag={params.useCreatedTag}
          creating={params.creating}/>
        clickToClose = true
        break
      case 'add-logo':
        modal = <AddLogoModal onCancel={close}/>
        clickToClose = true
        break
      case 'invite':
        modal = <InviteModal onCancel={close}/>
        clickToClose = true
        break
      case 'post-editor':
        modal = <PostEditorModal post={get('post', params)} onCancel={close}/>
        clickToClose = true
        break
    }

    return <BareModalWrapper top={top} onClick={() => clickToClose && close()}>
      {modal}
    </BareModalWrapper>
  }
}

export const ModalContainer = (props, { isMobile }) => {
  const { id, className, children, standalone } = props
  return

    {children}

}
ModalContainer.propTypes = {
  id: string,
  children: oneOfType([array, object]),
  className: string,
  standalone: bool
}
ModalContainer.contextTypes = {isMobile: bool}

export const Modal = (props, { isMobile }) => {
  const { children, title, subtitle, onCancel, standalone } = props
  return <ModalContainer {...props}>
    {(title || subtitle) &&

        {title}
        {!standalone &&
          <Icon name='Fail'/>
        }

      {subtitle &&

        {subtitle}

}

}
    {children}
  </ModalContainer>
}
Modal.propTypes = {
  id: string,
  children: oneOfType([array, object]),
  className: string,
  onCancel: func,
  subtitle: oneOfType([string, node]),
  standalone: bool,
  title: oneOfType([string, object])
}
Modal.contextTypes = {isMobile: bool}

export default Modal
<|endoftext|>


<commit_before>define(['util'], function (util) {
  // Defaults
  var lifeDefaults = {
    cellSize : 10,
    cellFill : '#87AFC7',
    cellBorder : '25383C',
    cellBorderSize : 1,
    controlSelector : 'Life-'
  };

  function Life(options) {
    /* Encapsulate a single Life game */

    options = options || {};
    this.options = util.extend(lifeDefaults, options);

    // Set controls and event listeners
    this._initControls();

    // Save the size of the grid
    this.gridSize = {
      x : Math.floor(this.canvasControl.width / this.options.cellSize),
      y : Math.floor(this.canvasControl.height / this.options.cellSize)
    };

    // Build game grid
    this.gameGrid = this._makeGrid();

  }

  Life.prototype._initControls = function() {
    /* Initialize handlers and etc. */
    var self = this;
    var controls = [
      { id : 'start', handler : this.start, event : 'click' },
      { id : 'stop', handler : this.stop, event : 'click' },
      { id : 'clear', handler : this.clear, event : 'click' },
      { id : 'speed', handler : this.updateFps, event : 'change' },
      { id : 'canvas', handler : this.click, event : 'mousedown' }
    ];

    // Create an event handler. Take function and what `this` should be
    function makeHandler(f, t) {
      return function(e) { f.apply(t, arguments); e.preventDefault(); };
    }

    util.each(controls, function(control) {
      var id = self.options.controlSelector + control.id;
      var el = document.getElementById(id);
      // Set control elements
      self[control.id + 'Control'] = el;
      // Set event listener
      el.addEventListener(control.event, makeHandler(control.handler, self));
    });

    this.ctx = this.canvasControl.getContext('2d');

  };

  Life.prototype.pixelsToCoords = function(x, y) {
    return {
      x : Math.floor(x / this.options.cellSize),
      y : Math.floor(y / this.options.cellSize)
    };
  };

  Life.prototype.coordsToPixels = function(x, y) {
    /* Get actual canvas coords for a life grid point */
    return {
      x : this.options.cellSize * x,
      y : this.options.cellSize * y
    };
  }

  Life.prototype.click = function(e) {
    var x = e.x - this.canvasControl.offsetLeft;
    var y = e.y - this.canvasControl.offsetTop;

    // Account for the border
    var re = /px$/;
    var canvasStyle = getComputedStyle(this.canvasControl);
    x -= canvasStyle.getPropertyValue('border-left-width').replace(re, '');
    y -= canvasStyle.getPropertyValue('border-top-width').replace(re, '');

    // Invalid click
    if(x < 0 || y < 0) return;

    var coords = this.pixelsToCoords(x, y);
    var cell = this.gameGrid[coords.x][coords.y];

    // Flip the alive state
    cell.alive = !cell.alive;

    // Draw or clear as appropriate
    cell.alive ? this.drawCell(coords.x, coords.y) : this.clearCell(coords.x, coords.y);

  };

  Life.prototype._makeGrid = function() {
    /* Generate a new grid of size (x, y) */

    var gameGrid = [];
    for(var i = 0; i < this.gridSize.x; ++i) {
      gameGrid[i] = [];
      for(var j = 0; j < this.gridSize.y; ++j) {
        gameGrid[i][j] = { neighbours : 0, alive : false };
      }
    }
    return gameGrid;
  };

  Life.prototype.clear = function() {
    /* Clear the board */
    for(var i = 0; i < this.gameGrid.length; ++i) {
      for(var j = 0; j < this.gameGrid[i].length; ++j) {
        this.gameGrid[i][j].alive = false;
        this.gameGrid[i][j].neighbours = 0;
      }
    }
    this.ctx.clearRect(0, 0, this.canvasControl.width, this.canvasControl.height);
  };

  Life.prototype.stop = function() {
    /* Stop the game. */
    if(this.started) {
      this._stopTimer();
      this.started = false;
    }
  };

  Life.prototype.start = function() {
    /* Start the game. */

    // If not started, update the FPS, which starts the game
    if(!this.started) {
      this._startTimer();
      this.started = true;
    }
  };

  Life.prototype._stopTimer = function() {
    window.clearInterval(this.interval);
    delete this.interval;
  };

  Life.prototype._startTimer = function() {
    var fps = this.speedControl.value;
    // Milliseconds in between ticks
    var ms = Math.floor(1000 / fps);
    this.interval = window.setInterval(this._tick.bind(this), ms);
  };

  Life.prototype.updateFps = function() {
    if(!this.started) return;
    this._stopTimer();
    this._startTimer();
  };

  Life.prototype._tick = function() {
    console.log('tick');
    // Count the neighbours of each
    for(var x = 0; x < this.gridSize.x; ++x) {
      for(var y = 0; y < this.gridSize.y; ++y) {
        this._countNeighbours(x, y);
      }
    }

    // Check each to see if alive and reset the neighbours count
    for(var x = 0; x < this.gridSize.x; ++x) {
      for(var y = 0; y < this.gridSize.y; ++y) {
        cell = this.gameGrid[x][y];

        if(cell.alive) {
          // Live if neighbours are 2 or 3, die otherwise
          cell.alive = !(cell.neighbours === 2 || cell.neighbours === 3);
        } else {
          // Become alive if exactly 3 neighbours
          cell.alive = cell.neighbours === 3;
        }

        cell.neighbours = 0;

        // Draw or clear the cell
        cell.alive ? this.drawCell(x, y) : this.clearCell(x, y);
      }
    }
  }

  Life.prototype.drawCell = function(x, y) {
    /* Draw the cell at position (x, y) */
    var coords = this.coordsToPixels(x, y);
    var cellSize = this.options.cellSize;

    util.drawSquare(this.ctx, coords, cellSize, this.options.cellBorder);

    // Border size
    var bs = this.options.cellBorderSize;
    // Move up+left by border size
    coords.x += bs;
    coords.y += bs;

    // Reduce size by twice border size so border appears on all sides
    cellSize -= 2 * bs;
    util.drawSquare(this.ctx, coords, cellSize, this.options.cellFill);
  };

  Life.prototype.clearCell = function(x, y) {
    /* Undraw cell at position (x, y) */
    var coords = this.coordsToPixels(x, y);
    var cellSize = this.options.cellSize;
    this.ctx.clearRect(coords.x, coords.y, cellSize, cellSize);
  };

  Life.prototype._getNeighbours = function(x, y) {
    /* Return array of neighbouring cells to cell at (x, y) */

  };

  Life.prototype._countNeighbours = function(x, y) {
    /*
     * Add 1 to the number of neighbours of each neighbour
     * of gameGrid[x][y].
     */
    var width = this.gridSize.x;
    var height = this.gridSize.y;

    // Add to neighbours only if alive
    if(!this.gameGrid[x][y].alive) return;

    // Don't go out of bounds
    for(var i = (x && -1); i <= ((width-x-1) && 1); ++i) {
      for(var j = (y && -1); j <= ((height-y-1) && 1); ++j) {
        // Don't do the current block (both 0)
        if(i || j) {
          this.gameGrid[x+i][y+j].neighbours += 1;
        }
      }
    }
  };

  return Life;

});
<commit_msg>Fixing life logic<commit_after>define(['util'], function (util) {
  // Defaults
  var lifeDefaults = {
    cellSize : 10,
    cellFill : '#87AFC7',
    cellBorder : '25383C',
    cellBorderSize : 1,
    controlSelector : 'Life-'
  };

  function Life(options) {
    /* Encapsulate a single Life game */

    options = options || {};
    this.options = util.extend(lifeDefaults, options);

    // Set controls and event listeners
    this._initControls();

    // Save the size of the grid
    this.gridSize = {
      x : Math.floor(this.canvasControl.width / this.options.cellSize),
      y : Math.floor(this.canvasControl.height / this.options.cellSize)
    };

    // Build game grid
    this.gameGrid = this._makeGrid();

  }

  Life.prototype._initControls = function() {
    /* Initialize handlers and etc. */
    var self = this;
    var controls = [
      { id : 'start', handler : this.start, event : 'click' },
      { id : 'stop', handler : this.stop, event : 'click' },
      { id : 'clear', handler : this.clear, event : 'click' },
      { id : 'speed', handler : this.updateFps, event : 'change' },
      { id : 'canvas', handler : this.click, event : 'mousedown' }
    ];

    // Create an event handler. Take function and what `this` should be
    function makeHandler(f, t) {
      return function(e) { f.apply(t, arguments); e.preventDefault(); };
    }

    util.each(controls, function(control) {
      var id = self.options.controlSelector + control.id;
      var el = document.getElementById(id);
      // Set control elements
      self[control.id + 'Control'] = el;
      // Set event listener
      el.addEventListener(control.event, makeHandler(control.handler, self));
    });

    this.ctx = this.canvasControl.getContext('2d');

  };

  Life.prototype.pixelsToCoords = function(x, y) {
    return {
      x : Math.floor(x / this.options.cellSize),
      y : Math.floor(y / this.options.cellSize)
    };
  };

  Life.prototype.coordsToPixels = function(x, y) {
    /* Get actual canvas coords for a life grid point */
    return {
      x : this.options.cellSize * x,
      y : this.options.cellSize * y
    };
  }

  Life.prototype.click = function(e) {
    var x = e.x - this.canvasControl.offsetLeft;
    var y = e.y - this.canvasControl.offsetTop;

    // Account for the border
    var re = /px$/;
    var canvasStyle = getComputedStyle(this.canvasControl);
    x -= canvasStyle.getPropertyValue('border-left-width').replace(re, '');
    y -= canvasStyle.getPropertyValue('border-top-width').replace(re, '');

    // Invalid click
    if(x < 0 || y < 0) return;

    var coords = this.pixelsToCoords(x, y);
    var cell = this.gameGrid[coords.x][coords.y];

    // Flip the alive state
    cell.alive = !cell.alive;

    // Draw or clear as appropriate
    cell.alive ? this.drawCell(coords.x, coords.y) : this.clearCell(coords.x, coords.y);

  };

  Life.prototype._makeGrid = function() {
    /* Generate a new grid of size (x, y) */

    var gameGrid = [];
    for(var i = 0; i < this.gridSize.x; ++i) {
      gameGrid[i] = [];
      for(var j = 0; j < this.gridSize.y; ++j) {
        gameGrid[i][j] = { neighbours : 0, alive : false };
      }
    }
    return gameGrid;
  };

  Life.prototype.clear = function() {
    /* Clear the board */
    for(var i = 0; i < this.gameGrid.length; ++i) {
      for(var j = 0; j < this.gameGrid[i].length; ++j) {
        this.gameGrid[i][j].alive = false;
        this.gameGrid[i][j].neighbours = 0;
      }
    }
    this.ctx.clearRect(0, 0, this.canvasControl.width, this.canvasControl.height);
  };

  Life.prototype.stop = function() {
    /* Stop the game. */
    if(this.started) {
      this._stopTimer();
      this.started = false;
    }
  };

  Life.prototype.start = function() {
    /* Start the game. */

    // If not started, update the FPS, which starts the game
    if(!this.started) {
      this._startTimer();
      this.started = true;
    }
  };

  Life.prototype._stopTimer = function() {
    window.clearInterval(this.interval);
    delete this.interval;
  };

  Life.prototype._startTimer = function() {
    var fps = this.speedControl.value;
    // Milliseconds in between ticks
    var ms = Math.floor(1000 / fps);
    this.interval = window.setInterval(this._tick.bind(this), ms);
  };

  Life.prototype.updateFps = function() {
    if(!this.started) return;
    this._stopTimer();
    this._startTimer();
  };

  Life.prototype._tick = function() {
    console.log('tick');
    // Count the neighbours of each
    for(var x = 0; x < this.gridSize.x; ++x) {
      for(var y = 0; y < this.gridSize.y; ++y) {
        this._countNeighbours(x, y);
      }
    }

    // Check each to see if alive and reset the neighbours count
    for(var x = 0; x < this.gridSize.x; ++x) {
      for(var y = 0; y < this.gridSize.y; ++y) {
        cell = this.gameGrid[x][y];

        if(cell.alive) {
          // Live if neighbours are 2 or 3, die otherwise
          cell.alive = (cell.neighbours === 2 || cell.neighbours === 3);
        } else {
          // Become alive if exactly 3 neighbours
          cell.alive = (cell.neighbours === 3);
        }

        cell.neighbours = 0;

        // Draw or clear the cell
        cell.alive ? this.drawCell(x, y) : this.clearCell(x, y);
      }
    }
  }

  Life.prototype.drawCell = function(x, y) {
    /* Draw the cell at position (x, y) */
    var coords = this.coordsToPixels(x, y);
    var cellSize = this.options.cellSize;

    util.drawSquare(this.ctx, coords, cellSize, this.options.cellBorder);

    // Border size
    var bs = this.options.cellBorderSize;
    // Move up+left by border size
    coords.x += bs;
    coords.y += bs;

    // Reduce size by twice border size so border appears on all sides
    cellSize -= 2 * bs;
    util.drawSquare(this.ctx, coords, cellSize, this.options.cellFill);
  };

  Life.prototype.clearCell = function(x, y) {
    /* Undraw cell at position (x, y) */
    var coords = this.coordsToPixels(x, y);
    var cellSize = this.options.cellSize;
    this.ctx.clearRect(coords.x, coords.y, cellSize, cellSize);
  };

  Life.prototype._getNeighbours = function(x, y) {
    /* Return array of neighbouring cells to cell at (x, y) */

    var width = this.gridSize.x;
    var height = this.gridSize.y;

    var neighbours = [];

    // i, j are offsets from x, y.  Make sure to not go out of bounds
    for(var i = (x && -1); i <= ((width-x-1) && 1); ++i) {
      for(var j = (y && -1); j <= ((height-y-1) && 1); ++j) {
        // A cell is not its own neighbour
        if(i || j) neighbours.push(this.gameGrid[x + i][y + j]);
      }
    }

    return neighbours;
  };

  Life.prototype._countNeighbours = function(x, y) {
    /*
     * Add 1 to the number of neighbours of each neighbour
     * of cell (x, y) if cell (x, y) is alive.
     */

    // Add to neighbours only if alive
    if(!this.gameGrid[x][y].alive) return;

    // Don't go out of bounds
    var neighbours = this._getNeighbours(x, y);
    for(var i = 0; i < neighbours.length; ++i) {
      neighbours.neighbours += 1;
    }
  };

  return Life;

});
<|endoftext|>


<commit_before>const React = require('react');
const Radium = require('radium');

const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

class Modal extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      showTooltip: false
    };
  }

  _handleTooltipToggle (show) {
    this.setState({
      showTooltip: show
    });
  }

  _renderTitleBar () {
    if (this.props.showTitleBar) {
      return (

          {this.props.title}

      );
    }
  }

  _renderFooter () {
    if (this.props.showFooter) {
      return (

          {this._renderTooltipIconAndLabel()}
          {this._renderFooterContent()}

            {this.props.buttons.map((button, i) => {
              return (

                  {button.label}

              );
            })}

      );
    }
  }

  _renderFooterContent () {
    if (this.props.footerContent) {
      return (

          {this.props.footerContent}

      );
    }
  }

  _renderTooltip () {
    if (this.state.showTooltip) {
      return (

            {this.props.tooltipTitle}

            {this.props.tooltip}

      );
    }
  }

  _renderTooltipIconAndLabel () {
    if (this.props.tooltip) {
      return (

          <Icon
            className='mx-modal-tooltip-label-icon'
            onMouseOut={this._handleTooltipToggle.bind(this, false)}
            onMouseOver={this._handleTooltipToggle.bind(this, true)}
            size={18}
            style={{ color: this.props.color }}
            type='info'
          />

            {this.props.tooltipLabel}

      );
    }
  }

  render () {
    if (this.props.isOpen)
      return (

            <Icon
              className='mx-modal-close'
              onClick={this.props.onRequestClose}
              size={24}
              style={styles.close}
              type='close-solid'
            />
            {this._renderTitleBar()}

              {this.props.children}
              {this._renderTooltip()}

            {this._renderFooter()}

      );
    else
      return (
        null
      );
  }
}

const styles = {
  scrim: {
    zIndex: 1000,
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    textAlign: 'center'
  },
  relative: {
    position: 'absolute'
  },
  overlay: {
    backgroundColor: StyleConstants.Colors.SCRIM
  },
  close: {
    position: 'absolute',
    top: 0,
    right: 0,
    margin: '-12px -12px 0 0',
    cursor: 'pointer',
    color: StyleConstants.Colors.CHARCOAL
  },
  container: {
    fontFamily: StyleConstants.FontFamily,
    boxSizing: 'border-box',
    position: 'relative',
    zIndex: 1001,
    backgroundColor: StyleConstants.Colors.WHITE,
    boxShadow: '0 0 30px 5px rgba(0,0,0,0.1)',
    borderRadius: 2,
    top: 20,
    maxWidth: 'calc(100% - 40px)',
    display: 'inline-block',
    textAlign: 'left'
  },
  titleBar: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderTopLeftRadius: 2,
    borderTopRightRadius: 2,
    padding: '15px 20px',
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    textTransform: 'uppercase'
  },
  content: {
    position: 'relative',
    maxHeight: 'calc(100% - 140px)',
    overflow: 'auto'
  },
  footer: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderBottomLeftRadius: 2,
    borderBottomRightRadius: 2,
    padding: '10px 20px',
    display: 'flex',
    justifyContent: 'space-between'
  },
  footerContent: {
    padding: '5px 0',
    textAlign: 'left'
  },
  tooltipLabel: {
    padding: '5px 0'
  },
  tooltipLabelText: {
    fontSize: StyleConstants.FontSizes.SMALL
  },
  tooltip: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderColor: StyleConstants.Colors.FOG,
    borderStyle: 'solid',
    borderWidth: 1,
    boxSizing: 'border-box',
    bottom: 10,
    left: 10,
    position: 'absolute',
    width: 250,
    maxWidth: '100%',
    padding: 10
  },
  tooltipTitle: {
    fontSize: StyleConstants.FontSizes.MEDIUM,
    marginBottom: 5
  },
  tooltipContent: {
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    lineHeight: '1.5em',
    textAlign: 'left'
  },
  buttons: {
    textAlign: 'right'
  },
  button: {
    display: 'inline-block',
    borderRadius: 2,
    cursor: 'pointer',
    fontSize: StyleConstants.FontSizes.MEDIUM,
    fontWeight: 600,
    padding: '7px 14px',
    marginLeft: 5
  },
  primaryButton: {
    backgroundColor: StyleConstants.Colors.PRIMARY,
    color: StyleConstants.Colors.WHITE
  },
  secondaryButton: {
    backgroundColor: StyleConstants.Colors.FOG,
    color: StyleConstants.Colors.CHARCOAL
  },
  small: {
    width: 400,
    textAlign: 'center'
  }
};

Modal.propTypes = {
  buttons: React.PropTypes.arrayOf(React.PropTypes.shape({
    className: React.PropTypes.string,
    label: React.PropTypes.string,
    onClick: React.PropTypes.func,
    style: React.PropTypes.oneOfType([
      React.PropTypes.array,
      React.PropTypes.object
    ]),
    type: React.PropTypes.oneOf(['primary', 'secondary'])
  })),
  color: React.PropTypes.string,
  contentStyle: React.PropTypes.object,
  footerContent: React.PropTypes.node,
  isOpen: React.PropTypes.bool,
  isRelative: React.PropTypes.bool,
  onRequestClose: React.PropTypes.func,
  showFooter: React.PropTypes.bool,
  showTitleBar: React.PropTypes.bool,
  title: React.PropTypes.string,
  tooltip: React.PropTypes.string,
  tooltipLabel: React.PropTypes.string,
  tooltipTitle: React.PropTypes.string
};

Modal.defaultProps = {
  buttons: [],
  color: StyleConstants.Colors.PRIMARY,
  isOpen: false,
  isRelative: false,
  showFooter: false,
  showTitleBar: false,
  title: '',
  tooltip: null,
  tooltipLabel: '',
  tooltipTitle: null
};

module.exports = Radium(Modal);
<commit_msg>always render footer content div<commit_after>const React = require('react');
const Radium = require('radium');

const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

class Modal extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      showTooltip: false
    };
  }

  _handleTooltipToggle (show) {
    this.setState({
      showTooltip: show
    });
  }

  _renderTitleBar () {
    if (this.props.showTitleBar) {
      return (

          {this.props.title}

      );
    }
  }

  _renderFooter () {
    if (this.props.showFooter) {
      return (

          {this._renderTooltipIconAndLabel()}
          {this._renderFooterContent()}

            {this.props.buttons.map((button, i) => {
              return (

                  {button.label}

              );
            })}

      );
    }
  }

  _renderFooterContent () {
    return (

        {this.props.footerContent ? this.props.footerContent : null}

    );
  }

  _renderTooltip () {
    if (this.state.showTooltip) {
      return (

            {this.props.tooltipTitle}

            {this.props.tooltip}

      );
    }
  }

  _renderTooltipIconAndLabel () {
    if (this.props.tooltip) {
      return (

          <Icon
            className='mx-modal-tooltip-label-icon'
            onMouseOut={this._handleTooltipToggle.bind(this, false)}
            onMouseOver={this._handleTooltipToggle.bind(this, true)}
            size={18}
            style={{ color: this.props.color }}
            type='info'
          />

            {this.props.tooltipLabel}

      );
    }
  }

  render () {
    if (this.props.isOpen)
      return (

            <Icon
              className='mx-modal-close'
              onClick={this.props.onRequestClose}
              size={24}
              style={styles.close}
              type='close-solid'
            />
            {this._renderTitleBar()}

              {this.props.children}
              {this._renderTooltip()}

            {this._renderFooter()}

      );
    else
      return (
        null
      );
  }
}

const styles = {
  scrim: {
    zIndex: 1000,
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    textAlign: 'center'
  },
  relative: {
    position: 'absolute'
  },
  overlay: {
    backgroundColor: StyleConstants.Colors.SCRIM
  },
  close: {
    position: 'absolute',
    top: 0,
    right: 0,
    margin: '-12px -12px 0 0',
    cursor: 'pointer',
    color: StyleConstants.Colors.CHARCOAL
  },
  container: {
    fontFamily: StyleConstants.FontFamily,
    boxSizing: 'border-box',
    position: 'relative',
    zIndex: 1001,
    backgroundColor: StyleConstants.Colors.WHITE,
    boxShadow: '0 0 30px 5px rgba(0,0,0,0.1)',
    borderRadius: 2,
    top: 20,
    maxWidth: 'calc(100% - 40px)',
    display: 'inline-block',
    textAlign: 'left'
  },
  titleBar: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderTopLeftRadius: 2,
    borderTopRightRadius: 2,
    padding: '15px 20px',
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    textTransform: 'uppercase'
  },
  content: {
    position: 'relative',
    maxHeight: 'calc(100% - 140px)',
    overflow: 'auto'
  },
  footer: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderBottomLeftRadius: 2,
    borderBottomRightRadius: 2,
    padding: '10px 20px',
    display: 'flex',
    justifyContent: 'space-between'
  },
  footerContent: {
    padding: '5px 0',
    textAlign: 'left'
  },
  tooltipLabel: {
    padding: '5px 0'
  },
  tooltipLabelText: {
    fontSize: StyleConstants.FontSizes.SMALL
  },
  tooltip: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderColor: StyleConstants.Colors.FOG,
    borderStyle: 'solid',
    borderWidth: 1,
    boxSizing: 'border-box',
    bottom: 10,
    left: 10,
    position: 'absolute',
    width: 250,
    maxWidth: '100%',
    padding: 10
  },
  tooltipTitle: {
    fontSize: StyleConstants.FontSizes.MEDIUM,
    marginBottom: 5
  },
  tooltipContent: {
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    lineHeight: '1.5em',
    textAlign: 'left'
  },
  buttons: {
    alignSelf: 'flex-end',
    textAlign: 'right'
  },
  button: {
    display: 'inline-block',
    borderRadius: 2,
    cursor: 'pointer',
    fontSize: StyleConstants.FontSizes.MEDIUM,
    fontWeight: 600,
    padding: '7px 14px',
    marginLeft: 5
  },
  primaryButton: {
    backgroundColor: StyleConstants.Colors.PRIMARY,
    color: StyleConstants.Colors.WHITE
  },
  secondaryButton: {
    backgroundColor: StyleConstants.Colors.FOG,
    color: StyleConstants.Colors.CHARCOAL
  },
  small: {
    width: 400,
    textAlign: 'center'
  }
};

Modal.propTypes = {
  buttons: React.PropTypes.arrayOf(React.PropTypes.shape({
    className: React.PropTypes.string,
    label: React.PropTypes.string,
    onClick: React.PropTypes.func,
    style: React.PropTypes.oneOfType([
      React.PropTypes.array,
      React.PropTypes.object
    ]),
    type: React.PropTypes.oneOf(['primary', 'secondary'])
  })),
  color: React.PropTypes.string,
  contentStyle: React.PropTypes.object,
  footerContent: React.PropTypes.node,
  isOpen: React.PropTypes.bool,
  isRelative: React.PropTypes.bool,
  onRequestClose: React.PropTypes.func,
  showFooter: React.PropTypes.bool,
  showTitleBar: React.PropTypes.bool,
  title: React.PropTypes.string,
  tooltip: React.PropTypes.string,
  tooltipLabel: React.PropTypes.string,
  tooltipTitle: React.PropTypes.string
};

Modal.defaultProps = {
  buttons: [],
  color: StyleConstants.Colors.PRIMARY,
  isOpen: false,
  isRelative: false,
  showFooter: false,
  showTitleBar: false,
  title: '',
  tooltip: null,
  tooltipLabel: '',
  tooltipTitle: null
};

module.exports = Radium(Modal);
<|endoftext|>


<commit_before>// Responsive logo
$(document).ready(function() {
     $width = $('#content').width();
     $('#header-logo img').css({
     	  'max-width' : $width , 'height' : 'auto'
          });
     });

<commit_msg>Ident lines of kamapp.js file<commit_after>// Responsive logo
$(document).ready(function() {
     $width = $('#header-logo').width();
     $('#header-logo img').css({
		'max-width' : $width , 'height' : 'auto'
     });
});

<|endoftext|>


<commit_before>/* global $ */

import {copied, slugify, positionCheck, returnCode} from './includes/utils.js';

// Load clipboard.js
// add functionality to all .copy
import Clipboard from 'clipboard';
new Clipboard('.copy');

function readmore(headlineSlug, link, headline) {
  var codeBlock = '

Read More '+ headline +'

';

  return codeBlock;
}

$('#readmorecode_form').submit(function(e) {
  var headline = $('#readmore_headline').val(),
      link = $('#readmore_link').val(),
      headlineSlug = slugify(headline),
      codeBlock = readmore(headlineSlug, link, headline);

  returnCode(codeBlock, 'readmorecode');
  copied(this.id);
  e.preventDefault();
});

function festival(speaker, positionFloat, lastName) {
  var codeBlock = '
' + speaker + ' is speaking at the 2016 Texas Tribune Festival. Find out more at texastribune.org/festival
';

  return codeBlock;
}

$('#festivalcode_form').submit(function(e) {
  var speaker = $('select[name=festival-speaker] option:selected').val(),
      positionVal = $('input[name=festival_position]:checked').val(),
      festivalPosition,
      lastName = $('select[name=festival-speaker] option:selected').data('last');

  if (positionVal === 'right') {
    festivalPosition = ' float_right" style="';
  } else if (positionVal === 'left') {
    festivalPosition = ' float_left" style="';
  } else {
    festivalPosition = '" style="width: 100%;';
  }

  var codeBlock = festival(speaker, festivalPosition, lastName);
  returnCode(codeBlock, 'festivalcode');
  copied(this.id);
  e.preventDefault();
});

function twitterinline(sentence, sentenceEncode, hashtag) {
  var codeBlock;

  if(hashtag) {
    codeBlock = '' + sentence + '';
  } else {
    codeBlock = '' + sentence + '';
  }

  return codeBlock;
}

$('#twitterinlinecode_form').submit(function(e) {
  var shareSentence = $('#twitterinline_sentence').val(),
      shareSentenceEncoded = encodeURI(shareSentence),
      shareHashtag = $('#twitterinline_hashtag').val().replace(/\s+/g, ''),
      codeBlock = twitterinline(shareSentence, shareSentenceEncoded, shareHashtag),
      shareSentenceLength = shareSentence.length,
      shareHashtagLength = shareHashtag.length,
      shareLength = shareSentenceLength + shareHashtagLength,
      shareSentenceLengthHTML = $('#twitterinline_sentence_length');

  if(shareLength >= 110) {
    $('#twitterinline_warning').removeClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  } else {
    $('#twitterinline_warning').addClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  }

  returnCode(codeBlock, 'twitterinlinecode');
  copied(this.id);
  e.preventDefault();
});

function pullquote(type, text, speaker, color, positionFloat) {
  var codeBlock;

  if (type === 'quote') {
    codeBlock = '“' + text + '”— ' + speaker + '';
  } else {
    codeBlock = '
' + text + '
';
  }

  return codeBlock;
}

$('#pulltextcode_form').change(function(e) {
  var type = $('input[name=type]:checked').val();
  if (type === 'quote') {
    $('.quote-label').show();
    $('.speaker-label').show();
    $('.speaker-input').show();
    $('.text-label').hide();
  } else {
    $('.quote-label').hide();
    $('.speaker-label').hide();
    $('.speaker-input').hide();
    $('.text-label').show();
  }
});

$('#pulltextcode_form').submit(function(e) {
  var type = $('input[name=type]:checked').val(),
      colorVal = $('input[name=color]:checked').val(),
      color,
      positionVal = $('input[name=position]:checked').val(),
      text = $('#pullquote_quote').val(),
      speaker = $('#pullquote_speaker').val(),
      positionFloat;

  if (colorVal === 'bsp') {
    color = '#925352';
  } else {
    color = 'rgb(255, 194, 0)';
  }

  if (positionVal === 'right') {
    positionFloat = ' float_right" style="';
  } else if (positionVal === 'left') {
    positionFloat = ' float_left" style="';
  } else {
    positionFloat = '" style="width: 100%;';
  }

  var codeBlock = pullquote(type, text, speaker, color, positionFloat);
  returnCode (codeBlock, 'pulltextcode');
  copied(this.id);

  e.preventDefault();
});

function photoEmbed(url, credit, caption, positionFloat) {
  var codeBlock = '

' + caption + '' + credit + ''+ '

';

  return codeBlock;
}

$('#photoembedcode_form').submit(function(e) {
  var positionVal = $('input[name=photoPosition]:checked').val();
  var positionFloat;
  if (positionVal === 'right') {
    positionFloat = ' float_right"';
  } else if (positionVal === 'left') {
    positionFloat = ' float_left"';
  } else {
    positionFloat = '" style="width: 100%;"';
  }

  var url = $('#photoEmbed_URL').val(),
      credit = $('#photoEmbed_credit').val(),
      caption = $('#photoEmbed_caption').val(),
      codeBlock = photoEmbed(url, credit, caption, positionFloat);

  returnCode(codeBlock, 'photoembedcode');
  copied(this.id);
  e.preventDefault();
});

function videoEmbed(video, width, height) {
  var codeBlock = '

';

  return codeBlock;
}

$('#videoembedcode_form').submit(function(e) {
  var videoID = $('#videoID').val(),
      width = $('#videoWidth').val(),
      height = $('#videoHeight').val(),
      video = 'https://www.youtube.com/embed/' + videoID;

  var codeBlock = videoEmbed(video, width, height);
  returnCode (codeBlock, 'videoembedcode');

  copied(this.id);

  e.preventDefault();
});

function seriesHeader(series) {
  var codeBlock;

  if (series === 'bsp') {
    codeBlock = '

The Texas Tribune is taking a yearlong look at the issues of border security and immigration, reporting on the reality and rhetoric around these topics. Sign up to get story alerts.

';
  } else if (series === 'rough-patch') {
    codeBlock = '

How plunging oil prices are reversing fortunes across Texas. Read all the stories in this series.

';
  } else if (series === 'mental-health-matters') {
    codeBlock = '

Throughout Mental Health Month in May, The Texas Tribune is partnering with Mental Health Channel and KLRU to focus on some of Texas’ biggest challenges in providing mental health care. See all the stories in this series.

';
  }

  return codeBlock;
}

function initializePreviews() {
  var readmorecode = readmore('test', 'https://', 'This is a test headline'),
      twitterinlinecode = twitterinline('This is preview sentence', '', ''),
      festivalcode = festival('Steve Adler, Mayor of Austin', '" style="width: 100%;', 'preview');

  $('#readmorecode_preview').html(readmorecode);
  $('#twitterinlinecode_preview').html(twitterinlinecode);
  $('#festivalcode_preview').html(festivalcode);
}

$('#seriesheadercode_form').submit(function(e) {
  var series = $('input[name=series]:checked').val();

  var codeBlock = seriesHeader(series);
  returnCode (codeBlock, 'seriesheadercode');

  copied(this.id);

  e.preventDefault();
});

initializePreviews();
<commit_msg>update bsp series text<commit_after>/* global $ */

import {copied, slugify, positionCheck, returnCode} from './includes/utils.js';

// Load clipboard.js
// add functionality to all .copy
import Clipboard from 'clipboard';
new Clipboard('.copy');

function readmore(headlineSlug, link, headline) {
  var codeBlock = '

Read More '+ headline +'

';

  return codeBlock;
}

$('#readmorecode_form').submit(function(e) {
  var headline = $('#readmore_headline').val(),
      link = $('#readmore_link').val(),
      headlineSlug = slugify(headline),
      codeBlock = readmore(headlineSlug, link, headline);

  returnCode(codeBlock, 'readmorecode');
  copied(this.id);
  e.preventDefault();
});

function festival(speaker, positionFloat, lastName) {
  var codeBlock = '
' + speaker + ' is speaking at the 2016 Texas Tribune Festival. Find out more at texastribune.org/festival
';

  return codeBlock;
}

$('#festivalcode_form').submit(function(e) {
  var speaker = $('select[name=festival-speaker] option:selected').val(),
      positionVal = $('input[name=festival_position]:checked').val(),
      festivalPosition,
      lastName = $('select[name=festival-speaker] option:selected').data('last');

  if (positionVal === 'right') {
    festivalPosition = ' float_right" style="';
  } else if (positionVal === 'left') {
    festivalPosition = ' float_left" style="';
  } else {
    festivalPosition = '" style="width: 100%;';
  }

  var codeBlock = festival(speaker, festivalPosition, lastName);
  returnCode(codeBlock, 'festivalcode');
  copied(this.id);
  e.preventDefault();
});

function twitterinline(sentence, sentenceEncode, hashtag) {
  var codeBlock;

  if(hashtag) {
    codeBlock = '' + sentence + '';
  } else {
    codeBlock = '' + sentence + '';
  }

  return codeBlock;
}

$('#twitterinlinecode_form').submit(function(e) {
  var shareSentence = $('#twitterinline_sentence').val(),
      shareSentenceEncoded = encodeURI(shareSentence),
      shareHashtag = $('#twitterinline_hashtag').val().replace(/\s+/g, ''),
      codeBlock = twitterinline(shareSentence, shareSentenceEncoded, shareHashtag),
      shareSentenceLength = shareSentence.length,
      shareHashtagLength = shareHashtag.length,
      shareLength = shareSentenceLength + shareHashtagLength,
      shareSentenceLengthHTML = $('#twitterinline_sentence_length');

  if(shareLength >= 110) {
    $('#twitterinline_warning').removeClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  } else {
    $('#twitterinline_warning').addClass('hidden');
    shareSentenceLengthHTML.html(shareLength);
  }

  returnCode(codeBlock, 'twitterinlinecode');
  copied(this.id);
  e.preventDefault();
});

function pullquote(type, text, speaker, color, positionFloat) {
  var codeBlock;

  if (type === 'quote') {
    codeBlock = '“' + text + '”— ' + speaker + '';
  } else {
    codeBlock = '
' + text + '
';
  }

  return codeBlock;
}

$('#pulltextcode_form').change(function(e) {
  var type = $('input[name=type]:checked').val();
  if (type === 'quote') {
    $('.quote-label').show();
    $('.speaker-label').show();
    $('.speaker-input').show();
    $('.text-label').hide();
  } else {
    $('.quote-label').hide();
    $('.speaker-label').hide();
    $('.speaker-input').hide();
    $('.text-label').show();
  }
});

$('#pulltextcode_form').submit(function(e) {
  var type = $('input[name=type]:checked').val(),
      colorVal = $('input[name=color]:checked').val(),
      color,
      positionVal = $('input[name=position]:checked').val(),
      text = $('#pullquote_quote').val(),
      speaker = $('#pullquote_speaker').val(),
      positionFloat;

  if (colorVal === 'bsp') {
    color = '#925352';
  } else {
    color = 'rgb(255, 194, 0)';
  }

  if (positionVal === 'right') {
    positionFloat = ' float_right" style="';
  } else if (positionVal === 'left') {
    positionFloat = ' float_left" style="';
  } else {
    positionFloat = '" style="width: 100%;';
  }

  var codeBlock = pullquote(type, text, speaker, color, positionFloat);
  returnCode (codeBlock, 'pulltextcode');
  copied(this.id);

  e.preventDefault();
});

function photoEmbed(url, credit, caption, positionFloat) {
  var codeBlock = '

' + caption + '' + credit + ''+ '

';

  return codeBlock;
}

$('#photoembedcode_form').submit(function(e) {
  var positionVal = $('input[name=photoPosition]:checked').val();
  var positionFloat;
  if (positionVal === 'right') {
    positionFloat = ' float_right"';
  } else if (positionVal === 'left') {
    positionFloat = ' float_left"';
  } else {
    positionFloat = '" style="width: 100%;"';
  }

  var url = $('#photoEmbed_URL').val(),
      credit = $('#photoEmbed_credit').val(),
      caption = $('#photoEmbed_caption').val(),
      codeBlock = photoEmbed(url, credit, caption, positionFloat);

  returnCode(codeBlock, 'photoembedcode');
  copied(this.id);
  e.preventDefault();
});

function videoEmbed(video, width, height) {
  var codeBlock = '

';

  return codeBlock;
}

$('#videoembedcode_form').submit(function(e) {
  var videoID = $('#videoID').val(),
      width = $('#videoWidth').val(),
      height = $('#videoHeight').val(),
      video = 'https://www.youtube.com/embed/' + videoID;

  var codeBlock = videoEmbed(video, width, height);
  returnCode (codeBlock, 'videoembedcode');

  copied(this.id);

  e.preventDefault();
});

function seriesHeader(series) {
  var codeBlock;

  if (series === 'bsp') {
    codeBlock = '

The Texas Tribune is taking a yearlong look at the issues of border security and immigration. This part of the project focuses on U.S. law enforcement corruption, which has undermined efforts to secure the border. Sign up to get story alerts.

';
  } else if (series === 'rough-patch') {
    codeBlock = '

How plunging oil prices are reversing fortunes across Texas. Read all the stories in this series.

';
  } else if (series === 'mental-health-matters') {
    codeBlock = '

Throughout Mental Health Month in May, The Texas Tribune is partnering with Mental Health Channel and KLRU to focus on some of Texas’ biggest challenges in providing mental health care. See all the stories in this series.

';
  }

  return codeBlock;
}

function initializePreviews() {
  var readmorecode = readmore('test', 'https://', 'This is a test headline'),
      twitterinlinecode = twitterinline('This is preview sentence', '', ''),
      festivalcode = festival('Steve Adler, Mayor of Austin', '" style="width: 100%;', 'preview');

  $('#readmorecode_preview').html(readmorecode);
  $('#twitterinlinecode_preview').html(twitterinlinecode);
  $('#festivalcode_preview').html(festivalcode);
}

$('#seriesheadercode_form').submit(function(e) {
  var series = $('input[name=series]:checked').val();

  var codeBlock = seriesHeader(series);
  returnCode (codeBlock, 'seriesheadercode');

  copied(this.id);

  e.preventDefault();
});

initializePreviews();
<|endoftext|>


<commit_before>define([
  'underscore',
  'kbn'
],
function (_, kbn) {
  'use strict';

  var ts = {};

  ts.ZeroFilled = function (opts) {
    this.datapoints = opts.datapoints;
    this.info = opts.info;
    this.label = opts.info.alias;
  };

  ts.ZeroFilled.prototype.getFlotPairs = function (fillStyle, yFormats) {
    var result = [];

    this.color = this.info.color;
    this.yaxis = this.info.yaxis;

    this.info.total = 0;
    this.info.max = null;
    this.info.min = 212312321312;

    _.each(this.datapoints, function(valueArray) {
      var currentTime = valueArray[1];
      var currentValue = valueArray[0];
      if (currentValue === null) {
        if (fillStyle === 'connected') {
          return;
        }
        if (fillStyle === 'null as zero') {
          currentValue = 0;
        }
      }

      if (_.isNumber(currentValue)) {
        this.info.total += currentValue;
      }

      if (currentValue > this.info.max) {
        this.info.max = currentValue;
      }

      if (currentValue < this.info.min) {
        this.info.min = currentValue;
      }

      result.push([currentTime * 1000, currentValue]);
    }, this);

    if (result.length) {
      this.info.avg = (this.info.total / result.length);
      this.info.current = result[result.length-1][1];

      var formater = getFormater(yFormats[this.yaxis - 1]);
      this.info.avg = formater(this.info.avg);
      this.info.current = formater(this.info.current);
      this.info.min = formater(this.info.min);
      this.info.max = formater(this.info.max);
      this.info.total = formater(this.info.total);
    }

    return result;
  };

  function getFormater(yformat) {
    switch(yformat) {
    case 'bytes':
      return kbn.byteFormat;
    case 'short':
      return kbn.shortFormat;
    case 'ms':
      return kbn.msFormat;
    default:
      return function(val) {
        if (val % 1 === 0) {
          return val;
        }
        else {
          return val.toFixed(2);
        }
      };
    }
  }

  return ts;
});<commit_msg>Fixes null checks for legend value formaters (fix for #97)<commit_after>define([
  'underscore',
  'kbn'
],
function (_, kbn) {
  'use strict';

  var ts = {};

  ts.ZeroFilled = function (opts) {
    this.datapoints = opts.datapoints;
    this.info = opts.info;
    this.label = opts.info.alias;
  };

  ts.ZeroFilled.prototype.getFlotPairs = function (fillStyle, yFormats) {
    var result = [];

    this.color = this.info.color;
    this.yaxis = this.info.yaxis;

    this.info.total = 0;
    this.info.max = null;
    this.info.min = 212312321312;

    _.each(this.datapoints, function(valueArray) {
      var currentTime = valueArray[1];
      var currentValue = valueArray[0];
      if (currentValue === null) {
        if (fillStyle === 'connected') {
          return;
        }
        if (fillStyle === 'null as zero') {
          currentValue = 0;
        }
      }

      if (_.isNumber(currentValue)) {
        this.info.total += currentValue;
      }

      if (currentValue > this.info.max) {
        this.info.max = currentValue;
      }

      if (currentValue < this.info.min) {
        this.info.min = currentValue;
      }

      result.push([currentTime * 1000, currentValue]);
    }, this);

    if (result.length) {
      this.info.avg = (this.info.total / result.length);
      this.info.current = result[result.length-1][1];

      var formater = getFormater(yFormats[this.yaxis - 1]);
      this.info.avg = this.info.avg ? formater(this.info.avg) : null;
      this.info.current = this.info.current ? formater(this.info.current) : null;
      this.info.min = this.info.min ? formater(this.info.min) : null;
      this.info.max = this.info.max ? formater(this.info.max) : null;
      this.info.total = this.info.total ? formater(this.info.total) : null;
    }

    return result;
  };

  function getFormater(yformat) {
    switch(yformat) {
    case 'bytes':
      return kbn.byteFormat;
    case 'short':
      return kbn.shortFormat;
    case 'ms':
      return kbn.msFormat;
    default:
      return function(val) {
        if (val % 1 === 0) {
          return val;
        }
        else {
          return val.toFixed(2);
        }
      };
    }
  }

  return ts;
});<|endoftext|>