<commit_before>$(document).ready(function() {
	if (typeof FileActions !== 'undefined') {
		FileActions.register('all', 'Share', function(filename) {
			var icon;
			var file = $('#dir').val()+'/'+filename;
			$.ajax({
				type: 'GET',
				url: OC.linkTo('files_sharing', 'ajax/getitem.php'),
				dataType: 'json',
				data: 'source='+file,
				async: false,
				success: function(users) {
					if (users.length > 0) {
						icon = OC.imagePath('core', 'actions/shared');
					} else {
						icon = OC.imagePath('core', 'actions/share');
					}
				}
			});
			return icon;
		}, function(filename) {
			if (($('#dropdown').length > 0)) {
				$('#dropdown').hide('blind', function() {
					var dropdownFile = $('#dropdown').data('file')
					var file = $('#dir').val()+'/'+filename;
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
					if (dropdownFile != file) {
						createDropdown(filename, file);
					}
				});
			} else {
				createDropdown(filename, $('#dir').val()+'/'+filename);
			}
		});
	};

	$('.share').click(function(event) {
		event.preventDefault();
		var filenames = getSelectedFiles('name');
		var length = filenames.length;
		var files = '';
		for (var i = 0; i < length; i++) {
			files += $('#dir').val()+'/'+filenames[i]+';';
		}
		createDropdown(false, files);
	});

	$(this).click(function(event) {
		if (!($(event.target).hasClass('drop')) && $(event.target).parents().index($('#dropdown')) == -1) {
			if ($('#dropdown').is(':visible')) {
				$('#dropdown').hide('blind', function() {
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
				});
			}
		}
	});

	$('#share_with').live('change', function() {
		var source = $('#dropdown').data('file');
		var uid_shared_with = $(this).val();
		var permissions = 0;
		var data = 'sources='+encodeURIComponent(source)+'&uid_shared_with='+encodeURIComponent(uid_shared_with)+'&permissions='+encodeURIComponent(permissions);
		$.ajax({
			type: 'POST',
			url: OC.linkTo('files_sharing','ajax/share.php'),
			cache: false,
			data: data,
			success: function(result) {
				if (result !== 'false') {
					addUser(uid_shared_with, permissions, false);
				}
			}
		});
	});

	$('#shared_list > li').live('mouseenter', function(event) {
		$(':hidden', this).show();
	});

	$('#shared_list > li').live('mouseleave', function(event) {
		$('a', this).hide();
		if (!$('input:[type=checkbox]', this).is(':checked')) {
			$('input:[type=checkbox]', this).hide();
			$('label', this).hide();
		}
	});

	$('.permissions').live('change', function() {
		var permissions = (this.checked) ? 1 : 0;
		var source = $('#dropdown').data('file');
		var uid_shared_with = $(this).parent().data('uid_shared_with');
		var data = 'source='+encodeURIComponent(source)+'&uid_shared_with='+encodeURIComponent(uid_shared_with)+'&permissions='+encodeURIComponent(permissions);
		$.ajax({
			type: 'GET',
			url: OC.linkTo('files_sharing','ajax/setpermissions.php'),
			cache: false,
			data: data
		});
	});

	$('.unshare').live('click', function(event) {
		event.preventDefault();
		var user = $(this).parent();
		var source = $('#dropdown').data('file');
		var uid_shared_with = user.data('uid_shared_with');
		var data = 'source='+encodeURIComponent(source)+'&uid_shared_with='+encodeURIComponent(uid_shared_with);
		$.ajax({
			type: 'GET',
			url: OC.linkTo('files_sharing','ajax/unshare.php'),
			cache: false,
			data: data,
			success: function() {
				var option = "<option value='"+uid_shared_with+"'>"+uid_shared_with+"</option>";
				$(user).remove();
				$(option).appendTo('#share_with');
				$('#share_with').trigger('liszt:updated');
			}
		});
	});

	$('#makelink').live('change', function() {
		if (this.checked) {
			var data = 'path='+$('#dropdown').data('file')+'&expire=0';
			$.ajax({
				type: 'GET',
				url: OC.linkTo('files_publiclink','ajax/makelink.php'),
				cache: false,
				data: data,
				success: function(token) {
					if (token) {
						showPublicLink(token);
					}
				}
			});
		} else {
			var data = 'token='+$('#link').data('token');
			$.ajax({
				type: 'GET',
				url: OC.linkTo('files_publiclink','ajax/deletelink.php'),
				cache: false,
				data: data,
				success: function(){
					$('#link').hide('blind');
				}
			});
		}
	});

	$('#link').live('click', function() {
		$(this).focus();
		$(this).select();
	});
});

function createDropdown(filename, files) {
	var html = "
";
	html += "
";
	html += "<select data-placeholder='User or Group' style='width:220px;' id='share_with' class='chzen-select'>";
	html += "<option value=''></option>";
	html += "</select>";
	html += "

";
	html += "
";
	html += "
";
	html += "<input type='checkbox' name='makelink' id='makelink' value='1' />make public";
	html += "<input type='checkbox' name='public_link_write' id='public_link_write' value='1' />allow upload";
	html += "
";
	html += "<input id='link' style='display:none; width:90%;' />";
	html += "
";
	if (filename) {
		$('tr[data-file="'+filename+'"]').addClass('mouseOver');
		$(html).appendTo($('tr[data-file="'+filename+'"] td.filename'));
	} else {
		$(html).appendTo($('thead .share'));
	}
	$.getJSON(OC.linkTo('files_sharing', 'ajax/userautocomplete.php'), function(users) {
		if (users) {
			$.each(users, function(index, row) {
				$(row).appendTo('#share_with');
			});
			$('#share_with').trigger('liszt:updated');
		}
	});
	$.getJSON(OC.linkTo('files_sharing', 'ajax/getitem.php'), { source: files }, function(users) {
		if (users) {
			$.each(users, function(index, row) {
				if (isNaN(index)) {
					addUser(row.uid_shared_with, row.permissions, index.substr(0, index.lastIndexOf('-')));
				} else {
					addUser(row.uid_shared_with, row.permissions, false);
				}
			});
		}
	});
	$.getJSON(OC.linkTo('files_publiclink', 'ajax/getlink.php'), { path: files }, function(token) {
		if (token) {
			showPublicLink(token);
		}
	});
	$('#dropdown').show('blind');
	$('#share_with').chosen();
}

function addUser(uid_shared_with, permissions, parentFolder) {
	if (parentFolder) {
		var user = "
Parent folder "+parentFolder+" shared with "+uid_shared_with+"
";
	} else {
		var checked = ((permissions > 0) ? "checked='checked'" : "style='display:none;'");
		var style = ((permissions == 0) ? "style='display:none;'" : "");
		var user = "
"+uid_shared_with;
		user += "<input type='checkbox' name='permissions' id='"+uid_shared_with+"' class='permissions' "+checked+"/>can edit";
		user += "
";
	}
	$('#share_with option[value="'+uid_shared_with+'"]').remove();
	$('#share_with').trigger('liszt:updated');
	$(user).appendTo('#shared_list');
}

function showPublicLink(token) {
	$('#makelink').attr('checked', true);
	$('#link').data('token', token);
	$('#link').val(parent.location.protocol+"//"+location.host+OC.linkTo('files_publiclink','get.php')+'?token='+token);
	$('#link').show('blind');
}
<commit_msg>Public link folder uploading not implemented, comment out checkbox for it in dropdown<commit_after>$(document).ready(function() {
	if (typeof FileActions !== 'undefined') {
		FileActions.register('all', 'Share', function(filename) {
			var icon;
			var file = $('#dir').val()+'/'+filename;
			$.ajax({
				type: 'GET',
				url: OC.linkTo('files_sharing', 'ajax/getitem.php'),
				dataType: 'json',
				data: 'source='+file,
				async: false,
				success: function(users) {
					if (users.length > 0) {
						icon = OC.imagePath('core', 'actions/shared');
					} else {
						icon = OC.imagePath('core', 'actions/share');
					}
				}
			});
			return icon;
		}, function(filename) {
			if (($('#dropdown').length > 0)) {
				$('#dropdown').hide('blind', function() {
					var dropdownFile = $('#dropdown').data('file')
					var file = $('#dir').val()+'/'+filename;
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
					if (dropdownFile != file) {
						createDropdown(filename, file);
					}
				});
			} else {
				createDropdown(filename, $('#dir').val()+'/'+filename);
			}
		});
	};

	$('.share').click(function(event) {
		event.preventDefault();
		var filenames = getSelectedFiles('name');
		var length = filenames.length;
		var files = '';
		for (var i = 0; i < length; i++) {
			files += $('#dir').val()+'/'+filenames[i]+';';
		}
		createDropdown(false, files);
	});

	$(this).click(function(event) {
		if (!($(event.target).hasClass('drop')) && $(event.target).parents().index($('#dropdown')) == -1) {
			if ($('#dropdown').is(':visible')) {
				$('#dropdown').hide('blind', function() {
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
				});
			}
		}
	});

	$('#share_with').live('change', function() {
		var source = $('#dropdown').data('file');
		var uid_shared_with = $(this).val();
		var permissions = 0;
		var data = 'sources='+encodeURIComponent(source)+'&uid_shared_with='+encodeURIComponent(uid_shared_with)+'&permissions='+encodeURIComponent(permissions);
		$.ajax({
			type: 'POST',
			url: OC.linkTo('files_sharing','ajax/share.php'),
			cache: false,
			data: data,
			success: function(result) {
				if (result !== 'false') {
					addUser(uid_shared_with, permissions, false);
				}
			}
		});
	});

	$('#shared_list > li').live('mouseenter', function(event) {
		$(':hidden', this).show();
	});

	$('#shared_list > li').live('mouseleave', function(event) {
		$('a', this).hide();
		if (!$('input:[type=checkbox]', this).is(':checked')) {
			$('input:[type=checkbox]', this).hide();
			$('label', this).hide();
		}
	});

	$('.permissions').live('change', function() {
		var permissions = (this.checked) ? 1 : 0;
		var source = $('#dropdown').data('file');
		var uid_shared_with = $(this).parent().data('uid_shared_with');
		var data = 'source='+encodeURIComponent(source)+'&uid_shared_with='+encodeURIComponent(uid_shared_with)+'&permissions='+encodeURIComponent(permissions);
		$.ajax({
			type: 'GET',
			url: OC.linkTo('files_sharing','ajax/setpermissions.php'),
			cache: false,
			data: data
		});
	});

	$('.unshare').live('click', function(event) {
		event.preventDefault();
		var user = $(this).parent();
		var source = $('#dropdown').data('file');
		var uid_shared_with = user.data('uid_shared_with');
		var data = 'source='+encodeURIComponent(source)+'&uid_shared_with='+encodeURIComponent(uid_shared_with);
		$.ajax({
			type: 'GET',
			url: OC.linkTo('files_sharing','ajax/unshare.php'),
			cache: false,
			data: data,
			success: function() {
				var option = "<option value='"+uid_shared_with+"'>"+uid_shared_with+"</option>";
				$(user).remove();
				$(option).appendTo('#share_with');
				$('#share_with').trigger('liszt:updated');
			}
		});
	});

	$('#makelink').live('change', function() {
		if (this.checked) {
			var data = 'path='+$('#dropdown').data('file')+'&expire=0';
			$.ajax({
				type: 'GET',
				url: OC.linkTo('files_publiclink','ajax/makelink.php'),
				cache: false,
				data: data,
				success: function(token) {
					if (token) {
						showPublicLink(token);
					}
				}
			});
		} else {
			var data = 'token='+$('#link').data('token');
			$.ajax({
				type: 'GET',
				url: OC.linkTo('files_publiclink','ajax/deletelink.php'),
				cache: false,
				data: data,
				success: function(){
					$('#link').hide('blind');
				}
			});
		}
	});

	$('#link').live('click', function() {
		$(this).focus();
		$(this).select();
	});
});

function createDropdown(filename, files) {
	var html = "
";
	html += "
";
	html += "<select data-placeholder='User or Group' style='width:220px;' id='share_with' class='chzen-select'>";
	html += "<option value=''></option>";
	html += "</select>";
	html += "

";
	html += "
";
	html += "
";
	html += "<input type='checkbox' name='makelink' id='makelink' value='1' />make public";
	//html += "<input type='checkbox' name='public_link_write' id='public_link_write' value='1' />allow upload";
	html += "
";
	html += "<input id='link' style='display:none; width:90%;' />";
	html += "
";
	if (filename) {
		$('tr[data-file="'+filename+'"]').addClass('mouseOver');
		$(html).appendTo($('tr[data-file="'+filename+'"] td.filename'));
	} else {
		$(html).appendTo($('thead .share'));
	}
	$.getJSON(OC.linkTo('files_sharing', 'ajax/userautocomplete.php'), function(users) {
		if (users) {
			$.each(users, function(index, row) {
				$(row).appendTo('#share_with');
			});
			$('#share_with').trigger('liszt:updated');
		}
	});
	$.getJSON(OC.linkTo('files_sharing', 'ajax/getitem.php'), { source: files }, function(users) {
		if (users) {
			$.each(users, function(index, row) {
				if (isNaN(index)) {
					addUser(row.uid_shared_with, row.permissions, index.substr(0, index.lastIndexOf('-')));
				} else {
					addUser(row.uid_shared_with, row.permissions, false);
				}
			});
		}
	});
	$.getJSON(OC.linkTo('files_publiclink', 'ajax/getlink.php'), { path: files }, function(token) {
		if (token) {
			showPublicLink(token);
		}
	});
	$('#dropdown').show('blind');
	$('#share_with').chosen();
}

function addUser(uid_shared_with, permissions, parentFolder) {
	if (parentFolder) {
		var user = "
Parent folder "+parentFolder+" shared with "+uid_shared_with+"
";
	} else {
		var checked = ((permissions > 0) ? "checked='checked'" : "style='display:none;'");
		var style = ((permissions == 0) ? "style='display:none;'" : "");
		var user = "
"+uid_shared_with;
		user += "<input type='checkbox' name='permissions' id='"+uid_shared_with+"' class='permissions' "+checked+"/>can edit";
		user += "
";
	}
	$('#share_with option[value="'+uid_shared_with+'"]').remove();
	$('#share_with').trigger('liszt:updated');
	$(user).appendTo('#shared_list');
}

function showPublicLink(token) {
	$('#makelink').attr('checked', true);
	$('#link').data('token', token);
	$('#link').val(parent.location.protocol+"//"+location.host+OC.linkTo('files_publiclink','get.php')+'?token='+token);
	$('#link').show('blind');
}
<|endoftext|>


<commit_before>(function($) {
  $.fn.labelizeField = function(options) {

    var settings = $.extend({
      'labelClass'  : 'fade',
      'labelEffect' : true
    }, options);

    var allLabelizeFields = $('input.labelize-field')
    allLabelizeFields.each(function(){
      if ($(this).val() != "")
        {
          $(this).prev('label').hide();
        }
    });

    this.click(function(){
      $(this).next('input').focus();

      if (settings['labelEffect']) {
        $(this).addClass(settings['labelClass']);
        $(this).next('input').keypress(function(){
          $(this).prev('label').hide();
        });

        $(this).next('input').blur(function(){
          $(this).prev('label').removeClass(settings['labelClass']);
          if ($(this).val() == "") {
              $(this).prev('label').show();
            }
        });
      }
      else {
        $(this).hide();
        $(this).next('input').blur(function(){
          if ($(this).val() == "") {
              $(this).prev('label').show();
            }
        })
      }
    });
    return this;
  };

})(jQuery);
<commit_msg>Validated code using jshint :)<commit_after>(function($) {
  "use strict";
  $.fn.labelizeField = function(options) {
    var settings = $.extend({
      'labelClass'  : 'fade',
      'labelEffect' : true
    }, options);

    var allLabelizeFields = $('input.labelize-field');
    allLabelizeFields.each(function(){
      if ($(this).val() !== "")
        {
          $(this).prev('label').hide();
        }
    });

    this.click(function(){
      $(this).next('input').focus();

      if (settings.labelEffect) {
        $(this).addClass(settings.labelClass);
        $(this).next('input').keypress(function(){
          $(this).prev('label').hide();
        });

        $(this).next('input').blur(function(){
          $(this).prev('label').removeClass(settings.labelClass);
          if ($(this).val() === "") {
            $(this).prev('label').show();
          }
        });
      }
      else {
        $(this).hide();
        $(this).next('input').blur(function(){
          if ($(this).val() === "") {
            $(this).prev('label').show();
          }
        });
      }
    });
    return this;
  };

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

import EventBus from '../components/EventBus';
import {AdType} from '../modules/adType';

let instance = null;

/**
 * ImplementationTest
 */
class ImplementationTest {
    /**
     * Constructor of ImplementationTest.
     * @param {String} testing
     * @return {*}
     */
    constructor(testing) {
        // Make this a singleton.
        if (instance) {
            return instance;
        } else {
            instance = this;
        }

        this.testing = testing;
        this.eventBus = new EventBus();
    }

    /**
     * Start testing.
     */
    start() {
        const css = `
            #gdsdk__implementation {
                display: flex;
                box-sizing: border-box;
                position: fixed;
                z-index: 667;
                bottom: 0;
                left: 0;
                width: 100%;
                padding: 3px;
                background: linear-gradient(90deg,#3d1b5d,#5c3997);
                box-shadow: 0 0 8px rgba(0, 0, 0, 0.8);
                color: #fff;
                font-family: Helvetica, Arial, sans-serif;
                font-size: 8px;
            }
            #gdsdk__implementation button {
                flex: 1;
                background: #44a5ab;
                padding: 3px 10px;
                margin: 2px;
                border: 0;
                border-radius: 3px;
                color: #fff;
                outline: 0;
                cursor: pointer;
                font-size: 8px;
                box-shadow: 0 0 0 transparent;
                text-shadow: 0 0 0 transparent;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }
            #gdsdk__implementation button:hover {
                background: #4fb3b9;
            }
            #gdsdk__implementation button:active {
                background: #62bbc0;
            }
        `;

        const html = `

                <button id="gdsdk__hbgdDebug">Activate hbgd debug</button>
                <button id="gdsdk__hbgdConfig">Log idhbgd config</button>

                <button id="gdsdk__showBanner">Interstitial</button>
                <button id="gdsdk__showRewarded">Rewarded</button>
                <button id="gdsdk__preloadRewarded">Preload rewarded</button>
                <button id="gdsdk__cancel">Cancel</button>
                <button id="gdsdk__demo">Demo VAST tag</button>
                <button id="gdsdk__midrollTimer">Disable delay</button>
                <button id="gdsdk__closeDebug">Close</button>

        `;

        // Add css
        const head = document.head || document.getElementsByTagName('head')[0];
        const style = document.createElement('style');
        style.type = 'text/css';
        if (style.styleSheet) {
            style.styleSheet.cssText = css;
        } else {
            style.appendChild(document.createTextNode(css));
        }
        head.appendChild(style);

        // Add html
        const body = document.body || document.getElementsByTagName('body')[0];
        const container = document.createElement('div');
        container.style.position = 'fixed';
        container.style.zIndex = '668';
        container.style.bottom = '0';
        container.innerHTML = html;
        body.appendChild(container);

        // Add listeners
        // const pauseGame = document.getElementById('gdsdk__pauseGame');
        // const resumeGame = document.getElementById('gdsdk__resumeGame');
        const showBanner = document.getElementById('gdsdk__showBanner');
        const showRewarded = document.getElementById('gdsdk__showRewarded');
        const preloadRewarded = document.getElementById('gdsdk__preloadRewarded');
        const cancelAd = document.getElementById('gdsdk__cancel');
        const demoAd = document.getElementById('gdsdk__demo');
        const midrollTimer = document.getElementById('gdsdk__midrollTimer');
        const hbgdDebug = document.getElementById('gdsdk__hbgdDebug');
        const hbgdConfig = document.getElementById('gdsdk__hbgdConfig');
        const closeDebug = document.getElementById('gdsdk__closeDebug');

        if (localStorage.getItem('gd_tag')) {
            demoAd.innerHTML = 'Revert Vast tag';
            demoAd.style.background = '#ff8c1c';
        } else {
            demoAd.innerHTML = 'Demo VAST tag';
            demoAd.style.background = '#44a5ab';
        }

        if (localStorage.getItem('gd_midroll')) {
            midrollTimer.innerHTML = 'Revert delay';
            midrollTimer.style.background = '#ff8c1c';
        } else {
            midrollTimer.innerHTML = 'Disable delay';
            midrollTimer.style.background = '#44a5ab';
        }

        // pauseGame.addEventListener('click', () => {
        //     window.gdsdk.onPauseGame('Pause game requested from debugger',
        //         'warning');
        // });
        // resumeGame.addEventListener('click', () => {
        //     window.gdsdk.onResumeGame('Resume game requested from debugger',
        //         'warning');
        // });
        showBanner.addEventListener('click', () => {
            window.gdsdk
                .showAd(AdType.Interstitial)
                .then(() => console.info('showAd(AdType.Interstitial) resolved.'))
                .catch((error) => console.info(error));
        });
        showRewarded.addEventListener('click', () => {
            window.gdsdk
                .showAd(AdType.Rewarded)
                .then(() => console.info('showAd(AdType.Rewarded) resolved.'))
                .catch((error) => console.info(error));
        });
        preloadRewarded.addEventListener('click', () => {
            window.gdsdk
                .preloadAd(AdType.Rewarded)
                .then((response) => console.info(response))
                .catch((error) => console.info(error.message));
        });
        cancelAd.addEventListener('click', () => {
            window.gdsdk.cancelAd();
        });
        demoAd.addEventListener('click', () => {
            try {
                if (localStorage.getItem('gd_tag')) {
                    localStorage.removeItem('gd_tag');
                } else {
                    const tag = `https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dskippablelinear&correlator=`;
                    localStorage.setItem('gd_tag', tag);
                }
                location.reload();
            } catch (error) {
                console.log(error);
            }
        });
        midrollTimer.addEventListener('click', () => {
            try {
                if (localStorage.getItem('gd_midroll')) {
                    localStorage.removeItem('gd_midroll');
                } else {
                    localStorage.setItem('gd_midroll', '0');
                }
                location.reload();
            } catch (error) {
                console.log(error);
            }
        });
        closeDebug.addEventListener('click', () => {
            try {
                if (localStorage.getItem('gd_debug')) {
                    localStorage.removeItem('gd_debug');
                } else {
                    localStorage.setItem('gd_debug', '0');
                }
                location.reload();
            } catch (error) {
                console.log(error);
            }
        });
        hbgdDebug.addEventListener('click', () => {
            try {
                window.idhbgd.debug(true);
            } catch (error) {
                console.log(error);
            }
        });
        hbgdConfig.addEventListener('click', () => {
            try {
                const config = window.idhbgd.getConfig();
                console.info(config);
            } catch (error) {
                console.log(error);
            }
        });
    }
}

export default ImplementationTest;
<commit_msg>implementation handle requests.<commit_after>'use strict';

import EventBus from '../components/EventBus';
import {AdType} from '../modules/adType';

let instance = null;

/**
 * ImplementationTest
 */
class ImplementationTest {
    /**
     * Constructor of ImplementationTest.
     * @param {String} testing
     * @return {*}
     */
    constructor(testing) {
        // Make this a singleton.
        if (instance) {
            return instance;
        } else {
            instance = this;
        }

        this.testing = testing;
        this.eventBus = new EventBus();
    }

    /**
     * Start testing.
     */
    start() {
        const css = `
            #gdsdk__implementation {
                display: flex;
                box-sizing: border-box;
                position: fixed;
                z-index: 667;
                bottom: 0;
                left: 0;
                width: 100%;
                padding: 3px;
                background: linear-gradient(90deg,#3d1b5d,#5c3997);
                box-shadow: 0 0 8px rgba(0, 0, 0, 0.8);
                color: #fff;
                font-family: Helvetica, Arial, sans-serif;
                font-size: 8px;
            }
            #gdsdk__implementation button {
                flex: 1;
                background: #44a5ab;
                padding: 3px 10px;
                margin: 2px;
                border: 0;
                border-radius: 3px;
                color: #fff;
                outline: 0;
                cursor: pointer;
                font-size: 8px;
                box-shadow: 0 0 0 transparent;
                text-shadow: 0 0 0 transparent;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }
            #gdsdk__implementation button:hover {
                background: #4fb3b9;
            }
            #gdsdk__implementation button:active {
                background: #62bbc0;
            }
        `;

        const html = `

                <button id="gdsdk__hbgdDebug">Activate hbgd debug</button>
                <button id="gdsdk__hbgdConfig">Log idhbgd config</button>

                <button id="gdsdk__showBanner">Interstitial</button>
                <button id="gdsdk__showRewarded">Rewarded</button>
                <button id="gdsdk__preloadRewarded">Preload rewarded</button>
                <button id="gdsdk__cancel">Cancel</button>
                <button id="gdsdk__demo">Demo VAST tag</button>
                <button id="gdsdk__midrollTimer">Disable delay</button>
                <button id="gdsdk__closeDebug">Close</button>

        `;

        // Add css
        const head = document.head || document.getElementsByTagName('head')[0];
        const style = document.createElement('style');
        style.type = 'text/css';
        if (style.styleSheet) {
            style.styleSheet.cssText = css;
        } else {
            style.appendChild(document.createTextNode(css));
        }
        head.appendChild(style);

        // Add html
        const body = document.body || document.getElementsByTagName('body')[0];
        const container = document.createElement('div');
        container.style.position = 'fixed';
        container.style.zIndex = '668';
        container.style.bottom = '0';
        container.innerHTML = html;
        body.appendChild(container);

        // Add listeners
        // const pauseGame = document.getElementById('gdsdk__pauseGame');
        // const resumeGame = document.getElementById('gdsdk__resumeGame');
        const showBanner = document.getElementById('gdsdk__showBanner');
        const showRewarded = document.getElementById('gdsdk__showRewarded');
        const preloadRewarded = document.getElementById('gdsdk__preloadRewarded');
        const cancelAd = document.getElementById('gdsdk__cancel');
        const demoAd = document.getElementById('gdsdk__demo');
        const midrollTimer = document.getElementById('gdsdk__midrollTimer');
        const hbgdDebug = document.getElementById('gdsdk__hbgdDebug');
        const hbgdConfig = document.getElementById('gdsdk__hbgdConfig');
        const closeDebug = document.getElementById('gdsdk__closeDebug');

        if (localStorage.getItem('gd_tag')) {
            demoAd.innerHTML = 'Revert Vast tag';
            demoAd.style.background = '#ff8c1c';
        } else {
            demoAd.innerHTML = 'Demo VAST tag';
            demoAd.style.background = '#44a5ab';
        }

        if (localStorage.getItem('gd_midroll')) {
            midrollTimer.innerHTML = 'Revert delay';
            midrollTimer.style.background = '#ff8c1c';
        } else {
            midrollTimer.innerHTML = 'Disable delay';
            midrollTimer.style.background = '#44a5ab';
        }

        // pauseGame.addEventListener('click', () => {
        //     window.gdsdk.onPauseGame('Pause game requested from debugger',
        //         'warning');
        // });
        // resumeGame.addEventListener('click', () => {
        //     window.gdsdk.onResumeGame('Resume game requested from debugger',
        //         'warning');
        // });
        showBanner.addEventListener('click', () => {
            window.gdsdk
                .showAd(AdType.Interstitial)
                .then(() => console.info('showAd(AdType.Interstitial) resolved.'))
                .catch(error => console.info(error));
        });
        showRewarded.addEventListener('click', () => {
            window.gdsdk
                .showAd(AdType.Rewarded)
                .then(() => console.info('showAd(AdType.Rewarded) resolved.'))
                .catch(error => console.info(error));
        });
        preloadRewarded.addEventListener('click', () => {
            window.gdsdk
                .preloadAd(AdType.Rewarded)
                .then(response => console.info(response))
                .catch(error => console.info(error.message));
        });
        cancelAd.addEventListener('click', () => {
            window.gdsdk.cancelAd();
        });
        demoAd.addEventListener('click', () => {
            try {
                if (localStorage.getItem('gd_tag')) {
                    localStorage.removeItem('gd_tag');
                } else {
                    const tag = `https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dskippablelinear&correlator=`;
                    localStorage.setItem('gd_tag', tag);
                }
                location.reload();
            } catch (error) {
                console.log(error);
            }
        });
        midrollTimer.addEventListener('click', () => {
            try {
                if (localStorage.getItem('gd_midroll')) {
                    localStorage.removeItem('gd_midroll');
                } else {
                    localStorage.setItem('gd_midroll', '0');
                }
                location.reload();
            } catch (error) {
                console.log(error);
            }
        });
        closeDebug.addEventListener('click', () => {
            try {
                if (localStorage.getItem('gd_debug')) {
                    localStorage.removeItem('gd_debug');
                } else {
                    localStorage.setItem('gd_debug', '0');
                }
                location.reload();
            } catch (error) {
                console.log(error);
            }
        });
        hbgdDebug.addEventListener('click', () => {
            try {
                window.idhbgd.debug(true);
            } catch (error) {
                console.log(error);
            }
        });
        hbgdConfig.addEventListener('click', () => {
            try {
                const config = window.idhbgd.getConfig();
                console.info(config);
            } catch (error) {
                console.log(error);
            }
        });
    }
}

export default ImplementationTest;
<|endoftext|>


<commit_before>const buster = require('buster')
// const InvalidInputError = require('arrow/lib/invalid-input-error')

const feedback = require('../lib/feedback')
const postApiFeedback = require('../lib/post-api-feedback')
const sinon = require('sinon')
const Request = require('../lib/models/request')

buster.testCase('postApiFeedback', {
  setUp: function (done) {
    this.create = this.stub(Request, 'create')
    this.addFeedback = this.stub(feedback, 'addFeedback')
    this.addFeedback.yields({uid: '123', cid: '123'})
    this.timeout = 2500
    this.req = { body: {} }
    this.res = { send: this.stub(), json: this.stub() }
    done()
  },
  'No input': {
    'should return failure code on empty request': function () {
      buster.assert.exception(function () {
        postApiFeedback(this.req, this.res)
      }, 'InvalidInputError')
    }
  },
  'Wrong input': {
    'should return failure code on wrong request': function () {
      this.req.body = { uid: '123', cid: 123 }
      buster.assert.exception(function () {
        postApiFeedback(this.req, this.res)
      }, 'InvalidInputError')
    }
  },
  'Uid not in database': {
    'should return failure code on empty request': function () {
      this.req.body = { uid: 'Wrong UID', cid: '123' }
      buster.assert.exception(function () {
        postApiFeedback(this.req, this.res)
      }, 'InvalidInputError')
    }
  },
  'Valid input': {
    'should return success and the searched request with the given uid and cid': function (done) {
      this.req.body = { uid: '123', cid: '123' }
      postApiFeedback(this.req, this.res, () => {
        buster.assert.calledWith(this.res.json, sinon.match.has('success', true))
        buster.assert.calledWith(this.res.json, sinon.match.has('uid', '123'))
        buster.assert.calledWith(this.res.json, sinon.match.has('cid', '123'))
        done()
      })
    }
  }
})
<commit_msg>changed post-api-feedback-test, still got time outs<commit_after>const buster = require('buster')
// const InvalidInputError = require('arrow/lib/invalid-input-error')

// const feedback = require('../lib/feedback')
const postApiFeedback = require('../lib/post-api-feedback')
// const sinon = require('sinon')
const Request = require('../lib/models/request')

buster.testCase('postApiFeedback', {
  setUp: function (done) {
    this.create = this.stub(Request, 'create')
    this.addFeedback = this.stub(Request, 'findByIdAndUpdate')
    this.timeout = 100000
    this.req = { body: {} }
    this.res = { send: this.stub(), json: this.stub() }
    done()
  },
  'No input': {
    'should return failure code on empty request': function () {
      buster.assert.exception(function () {
        postApiFeedback(this.req, this.res)
      }, 'InvalidInputError')
    }
  },
  'Wrong input': {
    'should return failure code on wrong request': function () {
      this.req.body = { uid: '123', cid: 123 }
      buster.assert.exception(function () {
        postApiFeedback(this.req, this.res)
      }, 'InvalidInputError')
    }
  },
  'Uid not in database': {
    'should return failure code on wrong request': function () {
      this.req.body = { uid: '123', cid: '123' }
      this.addFeedback.yields('err')
      buster.assert.exception(function () {
        postApiFeedback(this.req, this.res)
      }, 'InvalidInputError')
    }
  }
  // 'Valid input': {
  //   'should return success and the searched request with the given uid and cid': function (done) {
  //     this.req.body = { uid: '123', cid: '123' }
  //     this.addFeedback.yields(null, 'doc')
  //     postApiFeedback(this.req, this.res, () => {
  //       buster.assert.calledWith(this.res.json, sinon.match.has('success', true))
  //       done()
  //     })
  //   }
})
<|endoftext|>


<commit_before>import React from 'react';
import styled from '@emotion/styled';
import { faClock, faEdit } from '@fortawesome/free-regular-svg-icons';
import {
  faDirections,
  faList,
  faTimes,
  faCheck,
  faPoundSign,
  faBaby,
  faWheelchair,
  faVenusMars,
  faGenderless,
  faKey,
  faCog,
  faQuestion,
} from '@fortawesome/free-solid-svg-icons';
import { DateTime } from 'luxon';
import { Link } from 'react-router-dom';

import Box from './Box';
import Button from './Button';
import Text from './Text';
import Spacer from './Spacer';
import Icon from './Icon';
import {
  getOpeningTimes,
  getIsOpen,
  WEEKDAYS,
  rangeTypes,
} from '../openingHours';
import { useMutation, gql } from '@apollo/client';

const Grid = styled(Box)`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  margin: -${({ theme }) => theme.space[3]}px;
`;

const UnstyledList = styled.ul`
  list-style: none;
`;

function getTimeRangeLabel(range) {
  if (range === rangeTypes.CLOSED) {
    return 'Closed';
  }

  if (range.length === 2) {
    return range.join(' - ');
  }

  return 'Unknown';
}

function getIsOpenLabel(openingTimes = [], dateTime = DateTime.local()) {
  const isOpen = getIsOpen(openingTimes, dateTime);

  if (isOpen === null) {
    return 'Unknown';
  }

  return isOpen ? 'Open now' : 'Closed';
}

const SUBMIT_VERIFICATION_REPORT_MUTATION = gql`
  mutation submitVerificationReportMutation($id: ID) {
    submitVerificationReport(id: $id) {
      loo {
        id
        verifiedAt
      }
    }
  }
`;

const ToiletDetailsPanel = ({ data, isLoading }) => {
  const [isExpanded, setIsExpanded] = React.useState(false);

  const [
    submitVerificationReport,
    { loading: submitVerificationLoading },
  ] = useMutation(SUBMIT_VERIFICATION_REPORT_MUTATION);

  // collapse panel if isLoading or data changes (e.g. a user has selected a new marker)
  // React.useEffect(() => {
  //   setIsExpanded(false);
  // }, [isLoading, data]);

  // programmatically set focus on close button when panel expands
  const closeButtonRef = React.useRef();
  React.useEffect(() => {
    if (isExpanded && closeButtonRef.current) {
      closeButtonRef.current.focus();
    }
  }, [isExpanded]);

  if (isLoading) {
    return (
      <Box
        width="100%"
        color="primary"
        bg="white"
        minHeight={100}
        borderTopLeftRadius={4}
        borderTopRightRadius={4}
        padding={4}
        display="flex"
        alignItems="center"
      >
        Loading toilet...
      </Box>
    );
  }

  const titleFragment = (
    <Text fontWeight="bold" fontSize={4}>

{data.name || 'Unnamed Toilet'}

    </Text>
  );

  const getDirectionsFragment = (
    <Button
      icon={<Icon icon={faDirections} />}
      as="a"
      href={`https://maps.apple.com/?dirflg=w&daddr=${[
        data.location.lat,
        data.location.lng,
      ]}`}
      target="_blank"
      rel="noopener noreferrer"
    >
      Get directions
    </Button>
  );

  const crossIconFragment = <Icon icon={faTimes} color="tertiary" />;
  const questionIconFragment = <Icon icon={faQuestion} color="tertiary" />;
  const checkIconFragment = <Icon icon={faCheck} />;

  const getFeatureValueIcon = (value, checkFunction) => {
    if (value === null) {
      return questionIconFragment;
    }

    if (checkFunction) {
      return checkFunction() ? checkIconFragment : crossIconFragment;
    }

    return value ? checkIconFragment : crossIconFragment;
  };

  const features = [
    {
      icon: <Icon icon={faPoundSign} />,
      label: 'Free',
      valueIcon: getFeatureValueIcon(data.fee, () => !data.fee),
    },
    {
      icon: <Icon icon={faBaby} />,
      label: 'Baby Changing',
      valueIcon: getFeatureValueIcon(data.babyChange),
    },
    {
      icon: <Icon icon={faWheelchair} />,
      label: 'Accessible',
      valueIcon: getFeatureValueIcon(data.accessible),
    },
    ...(data.accessible
      ? [
          {
            icon: <Icon icon={faKey} />,
            label: 'RADAR Key',
            valueIcon: getFeatureValueIcon(data.radar),
          },
        ]
      : []),
    {
      icon: <Icon icon={faVenusMars} />,
      label: 'Unisex',
      valueIcon: getFeatureValueIcon(data.allGender),
    },
    {
      icon: <Icon icon={faGenderless} />,
      label: 'Gender Neutral',
      valueIcon: getFeatureValueIcon(data.allGender),
    },
    {
      icon: <Icon icon={faCog} />,
      label: 'Automatic',
      valueIcon: getFeatureValueIcon(data.automatic),
    },
  ];

  const openingTimes = getOpeningTimes(data.opening);
  const todayWeekdayIndex = DateTime.local().weekday - 1;

  const editUrl = `/loos/${data.id}/edit`;

  const updatedAt = DateTime.fromISO(data.updatedAt);
  let verifiedOrUpdatedDate = updatedAt;
  if (data.verifiedAt) {
    const verifiedAt = DateTime.fromISO(data.verifiedAt);
    if (updatedAt < verifiedAt) {
      verifiedOrUpdatedDate = verifiedAt;
    }
  }

  if (isExpanded) {
    return (
      <Box
        width="100%"
        color="primary"
        bg="white"
        maxHeight={400}
        overflow="auto"
        borderTopLeftRadius={4}
        borderTopRightRadius={4}
        padding={4}
        paddingRight={5}
        as="section"
        aria-labelledby="toilet-details-heading"
      >
        <Grid>
          <Box position="absolute" top={30} right={30}>
            <button
              type="button"
              aria-label="Close toilet details"
              onClick={() => setIsExpanded(false)}
              aria-expanded="true"
              ref={closeButtonRef}
            >
              <Box
                height={26}
                width={26}
                display="flex"
                alignItems="center"
                justifyContent="center"
                borderRadius={13}
                borderColor="primary"
                borderWidth={1}
                borderStyle="solid"
              >
                <Icon icon={faTimes} />
              </Box>
            </button>
          </Box>

          <Box width={['100%', '50%', '25%']} padding={3}>
            {titleFragment}
            <Spacer mb={2} />
            {getDirectionsFragment}
            <Spacer mb={4} />
            <Text fontWeight="bold">

Is this information correct?

            </Text>
            <Spacer mb={2} />
            <Box display="flex" alignItems="center">
              <Button
                onClick={() =>
                  submitVerificationReport({ variables: { id: data.id } })
                }
                disabled={submitVerificationLoading}
              >
                Yes
              </Button>
              <Spacer mr={4} />
              <Box display="flex" alignItems="center">
                No?
                <Spacer mr={2} />
                <Button
                  variant="secondary"
                  icon={<Icon icon={faEdit} />}
                  as={Link}
                  to={editUrl}
                >
                  Edit
                </Button>
              </Box>
            </Box>
            <Spacer mb={2} />
            Last verified:{' '}
            {verifiedOrUpdatedDate.toLocaleString(DateTime.DATETIME_SHORT)}
          </Box>

          <Box width={['100%', '50%', '25%']} padding={3} order={[0, 1]}>
            <Box display="flex" alignItems="center">
              <Icon icon={faClock} />
              <Spacer mr={2} />
              <Text fontWeight="bold">

Opening Hours

              </Text>
            </Box>
            <Spacer mb={2} />
            <UnstyledList>
              {openingTimes.map((timeRange, i) => (
                <Box
                  as="li"
                  display="flex"
                  justifyContent="space-between"
                  key={i}
                  padding={1}
                  bg={i === todayWeekdayIndex ? 'ice' : 'white'}
                >
                  {WEEKDAYS[i]}
                  {getTimeRangeLabel(timeRange)}
                </Box>
              ))}
            </UnstyledList>
            <Spacer mb={2} />
            <Text fontSize={1} color="grey">
              Hours may vary with national holidays or seasonal changes. If you
              know these hours to be out of date please{' '}
              <Button as={Link} to={editUrl} variant="link">
                edit this toilet
              </Button>
              .
            </Text>
          </Box>

          <Box width={['100%', '50%', '25%']} padding={3}>
            <Text fontWeight="bold">

Features

            </Text>
            <Spacer mb={2} />
            <UnstyledList>
              {features.map((feature) => (
                <Box
                  as="li"
                  key={feature.label}
                  display="flex"
                  alignItems="center"
                  justifyContent="space-between"
                  mb={1}
                >
                  <Box display="flex" alignItems="center">
                    <Box width="20px" display="flex" justifyContent="center">
                      {feature.icon}
                    </Box>
                    <Spacer mr={2} />
                    {feature.label}
                  </Box>
                  {feature.valueIcon}
                </Box>
              ))}
            </UnstyledList>
          </Box>

          <Box width={['100%', '50%', '25%']} padding={3}>
            {Boolean(data.fee) && (
              <>
                <Text fontWeight="bold">

Fee

                </Text>
                <Spacer mb={2} />
                {data.fee}
                <Spacer mb={3} />
              </>
            )}
            {Boolean(data.notes) && (
              <>
                <Text fontWeight="bold">

Notes

                </Text>
                <Spacer mb={2} />

                  {data.notes.split('\n').map((string, i) => (

{string}

                  ))}

              </>
            )}
          </Box>
        </Grid>
      </Box>
    );
  }

  return (
    <Box
      width="100%"
      color="primary"
      bg="white"
      minHeight={100}
      borderTopLeftRadius={4}
      borderTopRightRadius={4}
      padding={4}
      as="section"
      aria-labelledby="toilet-details-heading"
    >
      <Grid>
        <Box width={['100%', '50%', '25%']} padding={3}>
          {titleFragment}
        </Box>

        <Box width={['100%', '50%', '25%']} padding={3}>
          <Box display="flex" alignItems="center">
            <Icon icon={faClock} />
            <Spacer mr={2} />
            <Text fontWeight="bold">

Opening Hours

            </Text>
          </Box>
          <Spacer mb={2} />
          {getIsOpenLabel(openingTimes)}
        </Box>

        <Box
          width={['100%', '50%']}
          padding={3}
          display="flex"
          justifyContent={['flex-start', 'flex-start', 'flex-end']}
          alignItems="center"
        >
          {getDirectionsFragment}
          <Spacer mr={2} />
          <Button
            variant="secondary"
            icon={<Icon icon={faList} />}
            onClick={() => setIsExpanded(true)}
            aria-expanded="false"
          >
            More details
          </Button>
        </Box>
      </Grid>
    </Box>
  );
};

export default ToiletDetailsPanel;
<commit_msg>feat: add collapse arrow and back to top<commit_after>import React from 'react';
import styled from '@emotion/styled';
import { faClock, faEdit } from '@fortawesome/free-regular-svg-icons';
import {
  faDirections,
  faList,
  faTimes,
  faCheck,
  faPoundSign,
  faBaby,
  faWheelchair,
  faVenusMars,
  faGenderless,
  faKey,
  faCog,
  faQuestion,
  faChevronDown,
} from '@fortawesome/free-solid-svg-icons';
import { DateTime } from 'luxon';
import { Link } from 'react-router-dom';
import { useMutation, gql } from '@apollo/client';

import Box from './Box';
import Button from './Button';
import Text from './Text';
import Spacer from './Spacer';
import Icon from './Icon';
import { Media } from './Media';
import {
  getOpeningTimes,
  getIsOpen,
  WEEKDAYS,
  rangeTypes,
} from '../openingHours';

const Grid = styled(Box)`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  margin: -${({ theme }) => theme.space[3]}px;
`;

const UnstyledList = styled.ul`
  list-style: none;
`;

function getTimeRangeLabel(range) {
  if (range === rangeTypes.CLOSED) {
    return 'Closed';
  }

  if (range.length === 2) {
    return range.join(' - ');
  }

  return 'Unknown';
}

function getIsOpenLabel(openingTimes = [], dateTime = DateTime.local()) {
  const isOpen = getIsOpen(openingTimes, dateTime);

  if (isOpen === null) {
    return 'Unknown';
  }

  return isOpen ? 'Open now' : 'Closed';
}

const SUBMIT_VERIFICATION_REPORT_MUTATION = gql`
  mutation submitVerificationReportMutation($id: ID) {
    submitVerificationReport(id: $id) {
      loo {
        id
        verifiedAt
      }
    }
  }
`;

const ToiletDetailsPanel = ({ data, isLoading }) => {
  const [isExpanded, setIsExpanded] = React.useState(false);

  const [
    submitVerificationReport,
    { loading: submitVerificationLoading },
  ] = useMutation(SUBMIT_VERIFICATION_REPORT_MUTATION);

  // collapse panel if isLoading or data changes (e.g. a user has selected a new marker)
  // React.useEffect(() => {
  //   setIsExpanded(false);
  // }, [isLoading, data]);

  // programmatically set focus on close button when panel expands
  const closeButtonRef = React.useRef(null);
  React.useEffect(() => {
    if (isExpanded && closeButtonRef.current) {
      closeButtonRef.current.focus();
    }
  }, [isExpanded]);

  const overflowRef = React.useRef(null);
  const handleBackToTopClick = () => {
    if (!overflowRef.current) {
      return;
    }
    overflowRef.current.scrollTop = 0;
  };

  if (isLoading) {
    return (
      <Box
        width="100%"
        color="primary"
        bg="white"
        minHeight={100}
        borderTopLeftRadius={4}
        borderTopRightRadius={4}
        padding={4}
        display="flex"
        alignItems="center"
      >
        Loading toilet...
      </Box>
    );
  }

  const titleFragment = (
    <Text fontWeight="bold" fontSize={4}>

{data.name || 'Unnamed Toilet'}

    </Text>
  );

  const getDirectionsFragment = (
    <Button
      icon={<Icon icon={faDirections} />}
      as="a"
      href={`https://maps.apple.com/?dirflg=w&daddr=${[
        data.location.lat,
        data.location.lng,
      ]}`}
      target="_blank"
      rel="noopener noreferrer"
    >
      Get directions
    </Button>
  );

  const crossIconFragment = <Icon icon={faTimes} color="tertiary" />;
  const questionIconFragment = <Icon icon={faQuestion} color="tertiary" />;
  const checkIconFragment = <Icon icon={faCheck} />;

  const getFeatureValueIcon = (value, checkFunction) => {
    if (value === null) {
      return questionIconFragment;
    }

    if (checkFunction) {
      return checkFunction() ? checkIconFragment : crossIconFragment;
    }

    return value ? checkIconFragment : crossIconFragment;
  };

  const features = [
    {
      icon: <Icon icon={faPoundSign} />,
      label: 'Free',
      valueIcon: getFeatureValueIcon(data.fee, () => !data.fee),
    },
    {
      icon: <Icon icon={faBaby} />,
      label: 'Baby Changing',
      valueIcon: getFeatureValueIcon(data.babyChange),
    },
    {
      icon: <Icon icon={faWheelchair} />,
      label: 'Accessible',
      valueIcon: getFeatureValueIcon(data.accessible),
    },
    ...(data.accessible
      ? [
          {
            icon: <Icon icon={faKey} />,
            label: 'RADAR Key',
            valueIcon: getFeatureValueIcon(data.radar),
          },
        ]
      : []),
    {
      icon: <Icon icon={faVenusMars} />,
      label: 'Unisex',
      valueIcon: getFeatureValueIcon(data.allGender),
    },
    {
      icon: <Icon icon={faGenderless} />,
      label: 'Gender Neutral',
      valueIcon: getFeatureValueIcon(data.allGender),
    },
    {
      icon: <Icon icon={faCog} />,
      label: 'Automatic',
      valueIcon: getFeatureValueIcon(data.automatic),
    },
  ];

  const openingTimes = getOpeningTimes(data.opening);
  const todayWeekdayIndex = DateTime.local().weekday - 1;

  const editUrl = `/loos/${data.id}/edit`;

  const updatedAt = DateTime.fromISO(data.updatedAt);
  let verifiedOrUpdatedDate = updatedAt;
  if (data.verifiedAt) {
    const verifiedAt = DateTime.fromISO(data.verifiedAt);
    if (updatedAt < verifiedAt) {
      verifiedOrUpdatedDate = verifiedAt;
    }
  }

  if (isExpanded) {
    return (
      <Box
        width="100%"
        color="primary"
        bg="white"
        borderTopLeftRadius={4}
        borderTopRightRadius={4}
        as="section"
        aria-labelledby="toilet-details-heading"
      >
        <Media greaterThanOrEqual="md">
          <Box position="absolute" top={30} right={30}>
            <button
              type="button"
              aria-label="Close toilet details"
              onClick={() => setIsExpanded(false)}
              aria-expanded="true"
              ref={closeButtonRef}
            >
              <Box
                height={26}
                width={26}
                display="flex"
                alignItems="center"
                justifyContent="center"
                borderRadius={13}
                borderColor="primary"
                borderWidth={1}
                borderStyle="solid"
              >
                <Icon icon={faTimes} />
              </Box>
            </button>
          </Box>
        </Media>

        <Media lessThan="md">
          <Box display="flex" justifyContent="center" paddingTop={2}>
            <Box
              as="button"
              type="button"
              aria-label="Close toilet details"
              onClick={() => setIsExpanded(false)}
              aria-expanded="true"
              padding={2}
              ref={closeButtonRef}
            >
              <Icon icon={faChevronDown} />
            </Box>
          </Box>
        </Media>

        <Box
          ref={overflowRef}
          maxHeight={400}
          overflow="auto"
          padding={4}
          paddingTop={[0, 4]}
          paddingRight={[4, 5]}
        >
          <Grid>
            <Box width={['100%', '50%', '25%']} padding={3}>
              {titleFragment}
              <Spacer mb={2} />
              {getDirectionsFragment}
              <Spacer mb={4} />
              <Text fontWeight="bold">

Is this information correct?

              </Text>
              <Spacer mb={2} />
              <Box display="flex" alignItems="center">
                <Button
                  onClick={() =>
                    submitVerificationReport({ variables: { id: data.id } })
                  }
                  disabled={submitVerificationLoading}
                >
                  Yes
                </Button>
                <Spacer mr={4} />
                <Box display="flex" alignItems="center">
                  No?
                  <Spacer mr={2} />
                  <Button
                    variant="secondary"
                    icon={<Icon icon={faEdit} />}
                    as={Link}
                    to={editUrl}
                  >
                    Edit
                  </Button>
                </Box>
              </Box>
              <Spacer mb={2} />
              Last verified:{' '}
              {verifiedOrUpdatedDate.toLocaleString(DateTime.DATETIME_SHORT)}
            </Box>

            <Box width={['100%', '50%', '25%']} padding={3} order={[0, 1]}>
              <Box display="flex" alignItems="center">
                <Icon icon={faClock} />
                <Spacer mr={2} />
                <Text fontWeight="bold">

Opening Hours

                </Text>
              </Box>
              <Spacer mb={2} />
              <UnstyledList>
                {openingTimes.map((timeRange, i) => (
                  <Box
                    as="li"
                    display="flex"
                    justifyContent="space-between"
                    key={i}
                    padding={1}
                    bg={i === todayWeekdayIndex ? 'ice' : 'white'}
                  >
                    {WEEKDAYS[i]}
                    {getTimeRangeLabel(timeRange)}
                  </Box>
                ))}
              </UnstyledList>
              <Spacer mb={2} />
              <Text fontSize={1} color="grey">
                Hours may vary with national holidays or seasonal changes. If
                you know these hours to be out of date please{' '}
                <Button as={Link} to={editUrl} variant="link">
                  edit this toilet
                </Button>
                .
              </Text>
            </Box>

            <Box width={['100%', '50%', '25%']} padding={3}>
              <Text fontWeight="bold">

Features

              </Text>
              <Spacer mb={2} />
              <UnstyledList>
                {features.map((feature) => (
                  <Box
                    as="li"
                    key={feature.label}
                    display="flex"
                    alignItems="center"
                    justifyContent="space-between"
                    mb={1}
                  >
                    <Box display="flex" alignItems="center">
                      <Box width="20px" display="flex" justifyContent="center">
                        {feature.icon}
                      </Box>
                      <Spacer mr={2} />
                      {feature.label}
                    </Box>
                    {feature.valueIcon}
                  </Box>
                ))}
              </UnstyledList>
            </Box>

            <Box width={['100%', '50%', '25%']} padding={3}>
              {Boolean(data.fee) && (
                <>
                  <Text fontWeight="bold">

Fee

                  </Text>
                  <Spacer mb={2} />
                  {data.fee}
                  <Spacer mb={3} />
                </>
              )}
              {Boolean(data.notes) && (
                <>
                  <Text fontWeight="bold">

Notes

                  </Text>
                  <Spacer mb={2} />

                    {data.notes.split('\n').map((string, i) => (

{string}

                    ))}

                </>
              )}
            </Box>

            <Box
              as={Media}
              lessThan="md"
              display="flex"
              justifyContent="center"
              width="100%"
              padding={2}
              marginBottom={2}
            >
              <Button variant="link" onClick={handleBackToTopClick}>
                Back to top
              </Button>
            </Box>
          </Grid>
        </Box>
      </Box>
    );
  }

  return (
    <Box
      width="100%"
      color="primary"
      bg="white"
      minHeight={100}
      borderTopLeftRadius={4}
      borderTopRightRadius={4}
      padding={4}
      as="section"
      aria-labelledby="toilet-details-heading"
    >
      <Grid>
        <Box width={['100%', '50%', '25%']} padding={3}>
          {titleFragment}
        </Box>

        <Box width={['100%', '50%', '25%']} padding={3}>
          <Box display="flex" alignItems="center">
            <Icon icon={faClock} />
            <Spacer mr={2} />
            <Text fontWeight="bold">

Opening Hours

            </Text>
          </Box>
          <Spacer mb={2} />
          {getIsOpenLabel(openingTimes)}
        </Box>

        <Box
          width={['100%', '50%']}
          padding={3}
          display="flex"
          justifyContent={['flex-start', 'flex-start', 'flex-end']}
          alignItems="center"
        >
          {getDirectionsFragment}
          <Spacer mr={2} />
          <Button
            variant="secondary"
            icon={<Icon icon={faList} />}
            onClick={() => setIsExpanded(true)}
            aria-expanded="false"
          >
            More details
          </Button>
        </Box>
      </Grid>
    </Box>
  );
};

export default ToiletDetailsPanel;
<|endoftext|>


<commit_before>import React from 'react'

import numberShow from 'lib/numberShower/numberShower'

const PrecisionNumber = ({value, precision, number=numberShow(value, precision)}) => (

    {number.value}{number.symbol}
    {number.power && ({`\u00b710`}{number.power})}

)

const RangeDisplay = ({range: [low, high]}) => (

<PrecisionNumber value={low}/> to <PrecisionNumber value={high}/>

)

export const Output = ({metric: {name, simulation}}) => {
  if (!_.has(simulation, 'stats')) { return false }
  const {length, mean, adjustedConfidenceInterval} = simulation.stats
  return (

            {name}

            {length === 1 && <PrecisionNumber value={mean} precision={6}/> }
            {length > 1 && <RangeDisplay range={adjustedConfidenceInterval}/> }

  )
}
<commit_msg>Only show result number when there is error in results<commit_after>import React from 'react'

import numberShow from 'lib/numberShower/numberShower'

const PrecisionNumber = ({value, precision, number=numberShow(value, precision)}) => (

    {number.value}{number.symbol}
    {number.power && ({`\u00b710`}{number.power})}

)

const RangeDisplay = ({range: [low, high]}) => (

<PrecisionNumber value={low}/> to <PrecisionNumber value={high}/>

)

const ResultSection = ({length, mean, adjustedConfidenceInterval}) => (

    {length === 1 && <PrecisionNumber value={mean} precision={6}/> }
    {length > 1 && <RangeDisplay range={adjustedConfidenceInterval}/> }

)

export const Output = ({metric: {name, simulation}}) => {
  return (

            {name}

          {_.has(simulation, 'stats') &&
            <ResultSection {...simulation.stats}/>
          }

  )
}
<|endoftext|>


<commit_before>/* @flow */

import { SyncPromise } from 'sync-browser-mocks/src/promise';
import * as $logger from 'beaver-logger/client';
import * as xcomponent from 'xcomponent/src';

import { containerTemplate, componentTemplate } from './templates';

import { determineParameterFromToken, determineUrlFromToken } from './util';
import { setupPopupBridgeProxy, getPopupBridgeOpener, awaitPopupBridgeOpener } from './popupBridge';

import { isDevice, request, getQueryParam, redirect as redir, hasMetaViewPort, setLogLevel, getPageID } from '../../lib';
import { config, ENV, FPTI } from '../../config';
import { onLegacyPaymentAuthorize } from '../../compat';

function addHeader(name, value) : void {

    if (!window.$Api) {
        return;
    }

    if (window.$Api.addHeader) {
        return window.$Api.addHeader(name, value);
    }
}

export let Checkout = xcomponent.create({

    tag: 'paypal-checkout',
    name: 'ppcheckout',

    buildUrl(props) : string | SyncPromise<string> {
        let env = props.env || config.env;

        return props.payment().then(token => {
            if (!token) {
                throw new Error(`Expected payment id or token to be passed, got ${token}`);
            }

            return determineUrlFromToken(env, token);
        });
    },

    get domain() : Object {
        return config.paypalDomains;
    },

    get bridgeUrl() : Object {
        return config.postBridgeUrls;
    },

    get bridgeDomain() : Object {
        return config.paypalDomains;
    },

    contexts: {
        iframe: false,
        popup: true
    },

    get version() : string {
        return config.ppobjects ? __FILE_VERSION__ : __MINOR_VERSION__;
    },

    sandboxContainer: true,

    componentTemplate,
    containerTemplate,

    props: {

        uid: {
            type: 'string',
            value: getPageID(),
            def() : string {
                return getPageID();
            },
            queryParam: true
        },

        env: {
            type: 'string',
            required: false,
            queryParam: true,

            def() : string {
                return config.env;
            },

            validate(env) {
                if (!config.paypalUrls[env]) {
                    throw new Error(`Invalid env: ${env}`);
                }
            }
        },

        stage: {
            type: 'string',
            required: false,
            queryParam: true,

            def(props) : ?string {
                let env = props.env || config.env;

                if (env === ENV.STAGE || env === ENV.LOCAL) {
                    return config.stage;
                }
            }
        },

        locale: {
            type: 'string',
            required: false,
            queryParam: 'locale.x'
        },

        client: {
            type: 'object',
            required: false,
            def() : Object {
                return {};
            },
            sendToChild: false,

            validate(client, props) {
                let env = props.env || config.env;

                if (!client[env]) {
                    throw new Error(`Client ID not found for env: ${env}`);
                }

                if (client[env].match(/^(.)\1+$/)) {
                    throw new Error(`Invalid client ID: ${client[env]}`);
                }
            }
        },

        payment: {
            type: 'string',
            required: false,
            getter: true,
            memoize: true,
            timeout: __TEST__ ? 500 : 10 * 1000,
            queryParam(value = '') : string {
                return determineParameterFromToken(value);
            },
            childDef() : ?string {
                return getQueryParam('token');
            },
            validate(value, props) {
                if (!value && !props.url) {
                    throw new Error(`Expected props.payment to be passed`);
                }
            },
            alias: 'billingAgreement'
        },

        commit: {
            type: 'boolean',
            required: false
        },

        onAuthorize: {
            type: 'function',
            required: true,
            once: true,

            decorate(original) : ?Function {
                if (original) {
                    return function(data, actions = {}) : SyncPromise<void> {

                        let close = () => {
                            return SyncPromise.try(() => {
                                if (actions.close) {
                                    return actions.close();
                                }
                            }).then(() => {
                                return this.closeComponent();
                            });
                        };

                        let redirect = (win, url) => {
                            return SyncPromise.all([
                                redir(win || window.top, url || data.returnUrl),
                                close()
                            ]);
                        };

                        return SyncPromise.try(() => {

                            try {
                                let isButton = window.location.href.indexOf('/webapps/hermes/button') !== -1;
                                let isGuest  = this.window.location.href.indexOf('/webapps/xoonboarding') !== -1;

                                if (isButton && isGuest) {
                                    return request({
                                        win: this.window,
                                        method: 'get',
                                        url: '/webapps/hermes/api/auth'
                                    }).then(result => {
                                        if (result && result.data && result.data.access_token) {
                                            addHeader('x-paypal-internal-euat', result.data.access_token);
                                        }
                                    }).catch(err2 => {
                                        // pass
                                    });
                                }

                            } catch (err) {
                                // pass
                            }

                        }).then(() => {
                            return original.call(this, data, { ...actions, close, redirect });
                        }).finally(() => {
                            return this.close();
                        });
                    };
                }
            }
        },

        onAuth: {
            type: 'function',
            required: false,
            sameDomain: true
        },

        onCancel: {
            type: 'function',
            required: false,
            once: true,
            noop: true,

            decorate(original) : ?Function {
                if (original) {
                    return function(data, actions = {}) : SyncPromise<void> {

                        let close = () => {
                            return SyncPromise.try(() => {
                                if (actions.close) {
                                    return actions.close();
                                }
                            }).then(() => {
                                return this.closeComponent();
                            });
                        };

                        let redirect = (win, url) => {
                            return SyncPromise.all([
                                redir(win || window.top, url || data.cancelUrl),
                                close()
                            ]);
                        };

                        return SyncPromise.try(() => {
                            return original.call(this, data, { ...actions, close, redirect });
                        }).finally(() => {
                            this.close();
                        });
                    };
                }
            }
        },

        init: {
            type: 'function',
            required: false,
            once: true,

            decorate(original) : Function {
                return function(data) : void {

                    $logger.track({
                        [ FPTI.KEY.STATE ]: FPTI.STATE.CHECKOUT,
                        [ FPTI.KEY.TRANSITION ]: FPTI.TRANSITION.CHECKOUT_INIT,
                        [ FPTI.KEY.TOKEN ]: data.paymentToken,
                        [ FPTI.KEY.CONTEXT_ID ]: data.paymentToken
                    });

                    $logger.flush();

                    this.paymentToken = data.paymentToken;
                    this.cancelUrl    = data.cancelUrl;

                    if (original) {
                        return original.apply(this, arguments);
                    }
                };
            }
        },

        onClose: {
            type: 'function',
            required: false,
            once: true,
            promisify: true,

            def() : Function {
                return function(reason) : void {
                    let CLOSE_REASONS = xcomponent.CONSTANTS.CLOSE_REASONS;

                    if (this.props.onCancel && [ CLOSE_REASONS.CLOSE_DETECTED, CLOSE_REASONS.USER_CLOSED ].indexOf(reason) !== -1) {

                        if (this.paymentToken && this.cancelUrl) {

                            $logger.info(`close_trigger_cancel`);

                            return this.props.onCancel({
                                paymentToken: this.paymentToken,
                                cancelUrl:    this.cancelUrl
                            });

                        } else {

                            $logger.warn(`close_no_token_cancelurl`);
                        }
                    }
                };
            }
        },

        onError: {
            type: 'function',
            required: false,
            promisify: true,
            noop: true,
            once: true
        },

        fallback: {
            type: 'function',
            required: false,
            once: true,

            def() : Function {
                return function(url) : SyncPromise<void> {
                    $logger.warn('fallback', { url });
                    return onLegacyPaymentAuthorize(this.props.onAuthorize);
                };
            }
        },

        logLevel: {
            type: 'string',
            required: false,
            get value() : string {
                return config.logLevel;
            }
        },

        popupBridge: {
            type: 'object',
            required: false,
            get value() : Object {
                return {
                    open: getPopupBridgeOpener(),
                    awaitOpener: awaitPopupBridgeOpener
                };
            }
        },

        test: {
            type: 'object',
            required: false,
            def() : Object {
                return { action: 'checkout' };
            }
        }
    },

    autoResize: {
        width: false,
        height: false
    },

    get dimensions() : { width : string | number, height : string | number } {

        if (isDevice()) {
            return {
                width: '100%',
                height: '100%'
            };
        }

        return {
            width: '450px',
            height: '535px'
        };
    }
});

setupPopupBridgeProxy(Checkout);

let enableCheckoutIframeTimeout;

function allowCheckoutIframe() : boolean {

    if (isDevice()) {
        return false;
    }

    if (!hasMetaViewPort()) {
        return false;
    }

    return true;
}

export function enableCheckoutIframe({ force = false, timeout = 5 * 60 * 1000 } : { force? : boolean, timeout? : number } = {}) {

    if (!force && !allowCheckoutIframe()) {
        return;
    }

    Checkout.contexts.iframe = true;

    if (enableCheckoutIframeTimeout) {
        clearTimeout(enableCheckoutIframeTimeout);
    }

    enableCheckoutIframeTimeout = setTimeout(() => {
        Checkout.contexts.iframe = false;
    }, timeout);
}

if (Checkout.isChild()) {

    if (window.xprops.logLevel) {
        setLogLevel(window.xprops.logLevel);
    }

    awaitPopupBridgeOpener();
}
<commit_msg>Re-allow setting Checkout.contexts.lightbox manually<commit_after>/* @flow */

import { SyncPromise } from 'sync-browser-mocks/src/promise';
import * as $logger from 'beaver-logger/client';
import * as xcomponent from 'xcomponent/src';

import { containerTemplate, componentTemplate } from './templates';

import { determineParameterFromToken, determineUrlFromToken } from './util';
import { setupPopupBridgeProxy, getPopupBridgeOpener, awaitPopupBridgeOpener } from './popupBridge';

import { isDevice, request, getQueryParam, redirect as redir, hasMetaViewPort, setLogLevel, getPageID } from '../../lib';
import { config, ENV, FPTI } from '../../config';
import { onLegacyPaymentAuthorize } from '../../compat';

function addHeader(name, value) : void {

    if (!window.$Api) {
        return;
    }

    if (window.$Api.addHeader) {
        return window.$Api.addHeader(name, value);
    }
}

export let Checkout = xcomponent.create({

    tag: 'paypal-checkout',
    name: 'ppcheckout',

    buildUrl(props) : string | SyncPromise<string> {
        let env = props.env || config.env;

        return props.payment().then(token => {
            if (!token) {
                throw new Error(`Expected payment id or token to be passed, got ${token}`);
            }

            return determineUrlFromToken(env, token);
        });
    },

    get domain() : Object {
        return config.paypalDomains;
    },

    get bridgeUrl() : Object {
        return config.postBridgeUrls;
    },

    get bridgeDomain() : Object {
        return config.paypalDomains;
    },

    contexts: {
        iframe: false,
        popup: true
    },

    get version() : string {
        return config.ppobjects ? __FILE_VERSION__ : __MINOR_VERSION__;
    },

    sandboxContainer: true,

    componentTemplate,
    containerTemplate,

    props: {

        uid: {
            type: 'string',
            value: getPageID(),
            def() : string {
                return getPageID();
            },
            queryParam: true
        },

        env: {
            type: 'string',
            required: false,
            queryParam: true,

            def() : string {
                return config.env;
            },

            validate(env) {
                if (!config.paypalUrls[env]) {
                    throw new Error(`Invalid env: ${env}`);
                }
            }
        },

        stage: {
            type: 'string',
            required: false,
            queryParam: true,

            def(props) : ?string {
                let env = props.env || config.env;

                if (env === ENV.STAGE || env === ENV.LOCAL) {
                    return config.stage;
                }
            }
        },

        locale: {
            type: 'string',
            required: false,
            queryParam: 'locale.x'
        },

        client: {
            type: 'object',
            required: false,
            def() : Object {
                return {};
            },
            sendToChild: false,

            validate(client, props) {
                let env = props.env || config.env;

                if (!client[env]) {
                    throw new Error(`Client ID not found for env: ${env}`);
                }

                if (client[env].match(/^(.)\1+$/)) {
                    throw new Error(`Invalid client ID: ${client[env]}`);
                }
            }
        },

        payment: {
            type: 'string',
            required: false,
            getter: true,
            memoize: true,
            timeout: __TEST__ ? 500 : 10 * 1000,
            queryParam(value = '') : string {
                return determineParameterFromToken(value);
            },
            childDef() : ?string {
                return getQueryParam('token');
            },
            validate(value, props) {
                if (!value && !props.url) {
                    throw new Error(`Expected props.payment to be passed`);
                }
            },
            alias: 'billingAgreement'
        },

        commit: {
            type: 'boolean',
            required: false
        },

        onAuthorize: {
            type: 'function',
            required: true,
            once: true,

            decorate(original) : ?Function {
                if (original) {
                    return function(data, actions = {}) : SyncPromise<void> {

                        let close = () => {
                            return SyncPromise.try(() => {
                                if (actions.close) {
                                    return actions.close();
                                }
                            }).then(() => {
                                return this.closeComponent();
                            });
                        };

                        let redirect = (win, url) => {
                            return SyncPromise.all([
                                redir(win || window.top, url || data.returnUrl),
                                close()
                            ]);
                        };

                        return SyncPromise.try(() => {

                            try {
                                let isButton = window.location.href.indexOf('/webapps/hermes/button') !== -1;
                                let isGuest  = this.window.location.href.indexOf('/webapps/xoonboarding') !== -1;

                                if (isButton && isGuest) {
                                    return request({
                                        win: this.window,
                                        method: 'get',
                                        url: '/webapps/hermes/api/auth'
                                    }).then(result => {
                                        if (result && result.data && result.data.access_token) {
                                            addHeader('x-paypal-internal-euat', result.data.access_token);
                                        }
                                    }).catch(err2 => {
                                        // pass
                                    });
                                }

                            } catch (err) {
                                // pass
                            }

                        }).then(() => {
                            return original.call(this, data, { ...actions, close, redirect });
                        }).finally(() => {
                            return this.close();
                        });
                    };
                }
            }
        },

        onAuth: {
            type: 'function',
            required: false,
            sameDomain: true
        },

        onCancel: {
            type: 'function',
            required: false,
            once: true,
            noop: true,

            decorate(original) : ?Function {
                if (original) {
                    return function(data, actions = {}) : SyncPromise<void> {

                        let close = () => {
                            return SyncPromise.try(() => {
                                if (actions.close) {
                                    return actions.close();
                                }
                            }).then(() => {
                                return this.closeComponent();
                            });
                        };

                        let redirect = (win, url) => {
                            return SyncPromise.all([
                                redir(win || window.top, url || data.cancelUrl),
                                close()
                            ]);
                        };

                        return SyncPromise.try(() => {
                            return original.call(this, data, { ...actions, close, redirect });
                        }).finally(() => {
                            this.close();
                        });
                    };
                }
            }
        },

        init: {
            type: 'function',
            required: false,
            once: true,

            decorate(original) : Function {
                return function(data) : void {

                    $logger.track({
                        [ FPTI.KEY.STATE ]: FPTI.STATE.CHECKOUT,
                        [ FPTI.KEY.TRANSITION ]: FPTI.TRANSITION.CHECKOUT_INIT,
                        [ FPTI.KEY.TOKEN ]: data.paymentToken,
                        [ FPTI.KEY.CONTEXT_ID ]: data.paymentToken
                    });

                    $logger.flush();

                    this.paymentToken = data.paymentToken;
                    this.cancelUrl    = data.cancelUrl;

                    if (original) {
                        return original.apply(this, arguments);
                    }
                };
            }
        },

        onClose: {
            type: 'function',
            required: false,
            once: true,
            promisify: true,

            def() : Function {
                return function(reason) : void {
                    let CLOSE_REASONS = xcomponent.CONSTANTS.CLOSE_REASONS;

                    if (this.props.onCancel && [ CLOSE_REASONS.CLOSE_DETECTED, CLOSE_REASONS.USER_CLOSED ].indexOf(reason) !== -1) {

                        if (this.paymentToken && this.cancelUrl) {

                            $logger.info(`close_trigger_cancel`);

                            return this.props.onCancel({
                                paymentToken: this.paymentToken,
                                cancelUrl:    this.cancelUrl
                            });

                        } else {

                            $logger.warn(`close_no_token_cancelurl`);
                        }
                    }
                };
            }
        },

        onError: {
            type: 'function',
            required: false,
            promisify: true,
            noop: true,
            once: true
        },

        fallback: {
            type: 'function',
            required: false,
            once: true,

            def() : Function {
                return function(url) : SyncPromise<void> {
                    $logger.warn('fallback', { url });
                    return onLegacyPaymentAuthorize(this.props.onAuthorize);
                };
            }
        },

        logLevel: {
            type: 'string',
            required: false,
            get value() : string {
                return config.logLevel;
            }
        },

        popupBridge: {
            type: 'object',
            required: false,
            get value() : Object {
                return {
                    open: getPopupBridgeOpener(),
                    awaitOpener: awaitPopupBridgeOpener
                };
            }
        },

        test: {
            type: 'object',
            required: false,
            def() : Object {
                return { action: 'checkout' };
            }
        }
    },

    autoResize: {
        width: false,
        height: false
    },

    get dimensions() : { width : string | number, height : string | number } {

        if (isDevice()) {
            return {
                width: '100%',
                height: '100%'
            };
        }

        return {
            width: '450px',
            height: '535px'
        };
    }
});

setupPopupBridgeProxy(Checkout);

let enableCheckoutIframeTimeout;

function allowCheckoutIframe() : boolean {

    if (isDevice()) {
        return false;
    }

    if (!hasMetaViewPort()) {
        return false;
    }

    return true;
}

export function enableCheckoutIframe({ force = false, timeout = 5 * 60 * 1000 } : { force? : boolean, timeout? : number } = {}) {

    if (!force && !allowCheckoutIframe()) {
        return;
    }

    Checkout.contexts.iframe = true;

    if (enableCheckoutIframeTimeout) {
        clearTimeout(enableCheckoutIframeTimeout);
    }

    enableCheckoutIframeTimeout = setTimeout(() => {
        Checkout.contexts.iframe = false;
    }, timeout);
}

if (Checkout.isChild()) {

    if (window.xprops.logLevel) {
        setLogLevel(window.xprops.logLevel);
    }

    awaitPopupBridgeOpener();
}

// $FlowFixMe
Object.defineProperty(Checkout.contexts, 'lightbox', {
    set(value) {
        Checkout.contexts.iframe = value;
    }
});
<|endoftext|>


<commit_before>//
// This script provides some mechanics for testing ChromeFrame
//
function onSuccess(name, id) {
  onFinished(name, id, "OK");
}

function onFailure(name, id, status) {
  onFinished(name, id, status);
}

function byId(id) {
  return document.getElementById(id);
}

function getXHRObject(){
  var XMLHTTP_PROGIDS = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP',
                         'Msxml2.XMLHTTP.4.0'];
  var http = null;
  try {
    http = new XMLHttpRequest();
  } catch(e) {
  }

  if (http)
    return http;

  for (var i = 0; i < 3; ++i) {
    var progid = XMLHTTP_PROGIDS[i];
    try {
      http = new ActiveXObject(progid);
    } catch(e) {
  }

  if (http)
    break;
  }
  return http;
}

var reportURL = "/writefile/";

function shutdownServer() {
  var xhr = getXHRObject();
  if(!xhr)
    return;

  xhr.open("POST", "/kill", false);
  try {
    xhr.send(null);
  } catch(e) {
    appendStatus("XHR send failed. Error: " + e.description);
  }
}

// Optionally send the server a notification that onload was fired.
// To be called from within window.onload.
function sendOnLoadEvent() {
  writeToServer("OnLoadEvent", "loaded");
}

function writeToServer(name, result) {
  var xhr = getXHRObject();
  if(!xhr)
    return;

  // synchronously POST the results
  xhr.open("POST", reportURL + name, false);
  xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  try {
    xhr.send(result);
  } catch(e) {
    appendStatus("XHR send failed. Error: " + e.description);
  }
}

function postResult(name, result) {
  writeToServer(name, result);
  // NOTE:
  //  not watching for failure or return status issues. What should we do here?
  shutdownServer();
}

// Finish running a test by setting the status
// and the cookie.
function onFinished(name, id, result) {
  appendStatus(result);

  // set a cookie to report the results...
  var cookie = name + "." + id + ".status=" + result + "; path=/";
  document.cookie = cookie;

  // ...and POST the status back to the server
  postResult(name, result);
}

function appendStatus(message) {
  var statusPanel = byId("statusPanel");
  if (statusPanel) {
    statusPanel.innerHTML += '
' + message;
  }
}

function readCookie(name) {
  var cookie_name = name + "=";
  var ca = document.cookie.split(';');

  for(var i = 0 ; i < ca.length ; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1,c.length);
    }
    if (c.indexOf(cookie_name) == 0) {
      return c.substring(cookie_name.length, c.length);
    }
  }
  return null;
}

function createCookie(name,value,days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
  createCookie(name, "", -1);
}

function isRunningInMSIE() {
  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
      return true;

  return false;
}

function reloadUsingCFProtocol() {
  var redirect_location = "cf:";
  redirect_location += window.location;
  window.location = redirect_location;
}

function isRunningInChrome() {
  var is_chrome = /chrome/.test(navigator.userAgent.toLowerCase());
  return is_chrome;
}

function TestIfRunningInChrome() {
  var is_chrome = isRunningInChrome();
  if (!is_chrome) {
    onFailure("ChromeFrameWindowOpen", "Window Open failed :-(",
              "User agent = " + navigator.userAgent.toLowerCase());
  }
  return is_chrome;
}
<commit_msg>The function to check whether the page is running in Chrome was incorrectly flagging pages running in IE as running in Chrome. This was because the function was checking for the presence of the string chrome in the user agent. In ChromeFrame with host networking enabled the IE user agent contains the string chromeframe, which causes this function to fail.<commit_after>//
// This script provides some mechanics for testing ChromeFrame
//
function onSuccess(name, id) {
  onFinished(name, id, "OK");
}

function onFailure(name, id, status) {
  onFinished(name, id, status);
}

function byId(id) {
  return document.getElementById(id);
}

function getXHRObject(){
  var XMLHTTP_PROGIDS = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP',
                         'Msxml2.XMLHTTP.4.0'];
  var http = null;
  try {
    http = new XMLHttpRequest();
  } catch(e) {
  }

  if (http)
    return http;

  for (var i = 0; i < 3; ++i) {
    var progid = XMLHTTP_PROGIDS[i];
    try {
      http = new ActiveXObject(progid);
    } catch(e) {
  }

  if (http)
    break;
  }
  return http;
}

var reportURL = "/writefile/";

function shutdownServer() {
  var xhr = getXHRObject();
  if(!xhr)
    return;

  xhr.open("POST", "/kill", false);
  try {
    xhr.send(null);
  } catch(e) {
    appendStatus("XHR send failed. Error: " + e.description);
  }
}

// Optionally send the server a notification that onload was fired.
// To be called from within window.onload.
function sendOnLoadEvent() {
  writeToServer("OnLoadEvent", "loaded");
}

function writeToServer(name, result) {
  var xhr = getXHRObject();
  if(!xhr)
    return;

  // synchronously POST the results
  xhr.open("POST", reportURL + name, false);
  xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  try {
    xhr.send(result);
  } catch(e) {
    appendStatus("XHR send failed. Error: " + e.description);
  }
}

function postResult(name, result) {
  writeToServer(name, result);
  // NOTE:
  //  not watching for failure or return status issues. What should we do here?
  shutdownServer();
}

// Finish running a test by setting the status
// and the cookie.
function onFinished(name, id, result) {
  appendStatus(result);

  // set a cookie to report the results...
  var cookie = name + "." + id + ".status=" + result + "; path=/";
  document.cookie = cookie;

  // ...and POST the status back to the server
  postResult(name, result);
}

function appendStatus(message) {
  var statusPanel = byId("statusPanel");
  if (statusPanel) {
    statusPanel.innerHTML += '
' + message;
  }
}

function readCookie(name) {
  var cookie_name = name + "=";
  var ca = document.cookie.split(';');

  for(var i = 0 ; i < ca.length ; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1,c.length);
    }
    if (c.indexOf(cookie_name) == 0) {
      return c.substring(cookie_name.length, c.length);
    }
  }
  return null;
}

function createCookie(name,value,days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
  createCookie(name, "", -1);
}

function isRunningInMSIE() {
  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
      return true;

  return false;
}

function reloadUsingCFProtocol() {
  var redirect_location = "cf:";
  redirect_location += window.location;
  window.location = redirect_location;
}

function isRunningInChrome() {
  var is_chrome_frame = /chromeframe/.test(navigator.userAgent.toLowerCase());
  if (is_chrome_frame)
    return 0;
  var is_chrome = /chrome/.test(navigator.userAgent.toLowerCase());
  return is_chrome;
}

function TestIfRunningInChrome() {
  var is_chrome = isRunningInChrome();
  if (!is_chrome) {
    onFailure("ChromeFrameWindowOpen", "Window Open failed :-(",
              "User agent = " + navigator.userAgent.toLowerCase());
  }
  return is_chrome;
}
<|endoftext|>


<commit_before>import React from 'react';

const LinkedInIcon = ({ size = 18, fill = '#6E747A', ...props }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <title>linkedin icon</title>
    <g stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
      <g transform="translate(-1322.000000, -6039.000000)" fill={fill}>
        <g transform="translate(0.000000, 1964.000000)">
          <g transform="translate(888.000000, 3887.000000)">
            <g transform="translate(410.000000, 172.000000)">
              <path d="M37.632,29.635 L35.262,29.635 L35.262,25.922 C35.262,25.036 35.244,23.897 34.028,23.897 C32.793,23.897 32.604,24.861 32.604,25.857 L32.604,29.635 L30.234,29.635 L30.234,22 L32.51,22 L32.51,23.04 L32.54,23.04 C32.858,22.44 33.632,21.807 34.787,21.807 C37.187,21.807 37.632,23.387 37.632,25.444 L37.632,29.632 L37.632,29.635 Z M27.558,20.955 C26.796,20.955 26.182,20.338 26.182,19.578 C26.182,18.82 26.796,18.203 27.558,18.203 C28.318,18.203 28.934,18.82 28.934,19.578 C28.934,20.338 28.317,20.955 27.558,20.955 Z M28.746,29.635 L26.37,29.635 L26.37,22 L28.746,22 L28.746,29.635 Z M38.816,16 L25.18,16 C24.528,16 24,16.516 24,17.153 L24,30.847 C24,31.484 24.528,32 25.18,32 L38.815,32 C39.467,32 40,31.484 40,30.847 L40,17.153 C40,16.516 39.467,16 38.815,16 L38.816,16 Z" id="linkedin"></path>
            </g>
          </g>
        </g>
      </g>
    </g>
  </svg>
);

export default LinkedInIcon;
<commit_msg>fix(components/icons/LinkedInIcon): spread rest of props on svg<commit_after>import React from 'react';

const LinkedInIcon = ({ size = 18, fill = '#6E747A', ...props }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg" {...props}>
    <title>linkedin icon</title>
    <g stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
      <g transform="translate(-1322.000000, -6039.000000)" fill={fill}>
        <g transform="translate(0.000000, 1964.000000)">
          <g transform="translate(888.000000, 3887.000000)">
            <g transform="translate(410.000000, 172.000000)">
              <path d="M37.632,29.635 L35.262,29.635 L35.262,25.922 C35.262,25.036 35.244,23.897 34.028,23.897 C32.793,23.897 32.604,24.861 32.604,25.857 L32.604,29.635 L30.234,29.635 L30.234,22 L32.51,22 L32.51,23.04 L32.54,23.04 C32.858,22.44 33.632,21.807 34.787,21.807 C37.187,21.807 37.632,23.387 37.632,25.444 L37.632,29.632 L37.632,29.635 Z M27.558,20.955 C26.796,20.955 26.182,20.338 26.182,19.578 C26.182,18.82 26.796,18.203 27.558,18.203 C28.318,18.203 28.934,18.82 28.934,19.578 C28.934,20.338 28.317,20.955 27.558,20.955 Z M28.746,29.635 L26.37,29.635 L26.37,22 L28.746,22 L28.746,29.635 Z M38.816,16 L25.18,16 C24.528,16 24,16.516 24,17.153 L24,30.847 C24,31.484 24.528,32 25.18,32 L38.815,32 C39.467,32 40,31.484 40,30.847 L40,17.153 C40,16.516 39.467,16 38.815,16 L38.816,16 Z" id="linkedin"></path>
            </g>
          </g>
        </g>
      </g>
    </g>
  </svg>
);

export default LinkedInIcon;
<|endoftext|>


<commit_before>// topic.js

var base = require('./_base.js');

module.exports = function (warp) {
    return base.defineModel(warp, 'Topic', [
        base.column_id('board_id', { index: true }),
        base.column_id('user_id', { index: true }),
        base.column_bigint('replies'),
        base.column_varchar_100('name'),
        base.column_varchar_1000('tags'),
        base.column_bigint('upvotes'),
        base.column_bigint('downvotes'),
        base.column_bigint('score'),
        base.column_boolean('locked'),
        base.column_text('content', { type: 'text' })
    ], {
        table: 'topics'
    });
};
<commit_msg>add ref_id for topics<commit_after>// topic.js

var base = require('./_base.js');

module.exports = function (warp) {
    return base.defineModel(warp, 'Topic', [
        base.column_id('board_id', { index: true }),
        base.column_varchar_50('ref_type'),
        base.column_id('ref_id', { index: true }),
        base.column_id('user_id', { index: true }),
        base.column_bigint('replies'),
        base.column_varchar_100('name'),
        base.column_varchar_1000('tags'),
        base.column_bigint('upvotes'),
        base.column_bigint('downvotes'),
        base.column_bigint('score'),
        base.column_boolean('locked'),
        base.column_text('content', { type: 'text' })
    ], {
        table: 'topics'
    });
};
<|endoftext|>