<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

var dragComponent = null;
var dragitem = null;
var currentView = null;
var currentItem = null
var startPos = null;

function playlistNameValidate(parm,val) {
    if (parm == "") return true;
    for (var i=0; i<parm.length; i++) {
        if (val.indexOf(parm.charAt(i),0) != -1) return false;
    }
    return true;
}

function startDrag(mouse,view,item) {
    if (view == null || item == null)
        return;

    if (dragitem != null) {
        dragitem.destroy();
        dragitem = null;
    }

     dragComponent = view.delegate;

    currentView = view;
    currentItem = item;
    startPos = item.mapToItem(scene,mouse.x, mouse.y);

    if (dragComponent.status == Component.Loading) {
        component.statusChanged.connect(createItem);
    }else{
        createItem();
    }
}

// this function will return type SONG(2),ARTIST(3),ALBUM(4) or PLAYLIST(5) from MediaItem
// depending on the input type, which is one of the ModelType
// we can't access MediaItem from here, so hardcoded the enum value
function convertListType(type) {
    switch (type) {
    case MusicListModel.ListofSongs:
            return 2;

    case MusicListModel.ListofAlbums:
            return 4;

    case MusicListModel.ListofArtists:
            return 3;

    case MusicListModel.ListofPlaylists:
            return 5;

    case MusicListModel.ListofAlbumsForArtist:
            return 4;

    case MusicListModel.ListofSongsForAlbum:
            return 2;

    case MusicListModel.ListofSongsForArtist:
            return 2;

    case MusicListModel.ListofRecentlyPlayed:
            // special case
            return currentItem.mtype;

    case MusicListModel.MusicPlaylist:
            return 5;

    default:
            return -1;
    }
}

function createItem() {
    dragitem = dragComponent.createObject(scene);
    // set dragitem position:

    dragitem.x = startPos.x;
    dragitem.y = startPos.y;

    dragitem.mtitle = currentItem.mtitle;
    dragitem.mthumburi = currentItem.mthumburi;
    dragitem.mitemid = currentItem.mitemid;
    dragitem.mitemtype = currentItem.mitemtype;
    dragitem.opacity = 0.8;
    dragitem.mcount = currentItem.mcount;
    dragitem.martist = currentItem.martist;
}

// return true if the point is in item's area,
// the point should be in the item's coordinate system.
function itemContainsPoint(item, point) {
    if ( point.x >=0 && point.x < item.width
         && point.y >= 0 && point.y < item.height) {
        return true;
    }
    return false;
}

function moveDragItem(mouse,item) {

    if (dragitem == null)
        return;

    var pos = item.mapToItem(scene,mouse.x, mouse.y);
    dragitem.x = pos.x;
    dragitem.y = pos.y;

    if (sideContentStrip.activeContent.tabs) {
        for (var i = 0;  i < sideContentStrip.activeContent.tabs.length -1; i++) {
            var it = sideContentStrip.activeContent.tabs[i];
            var pt = item.mapToItem(it,mouse.x, mouse.y);
            if (itemContainsPoint(it,pt)) {
                sideContentStrip.activeContent.selectTabAtIndex(i);
                sideContentStrip.activeContent.open();
                return;
            }
        }

        // specific code for landingscreen side content
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y);
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                view.currentIndex = targetIndex;

               view.highlightItem.opacity = 0.4;
            }else {
               view.highlightItem.opacity = 0;
            }
        }
    }

}

function endDrag(mouse,item) {
    if (!dragitem) {
        return;
    }

    // check if dropped at now playing button,
    // if yes, add to now playing list
    var dropPos = item.mapToItem(npRect,mouse.x,mouse.y);
    if (dropPos.x > 0 && dropPos.x < npRect.width
        && dropPos.y > 0 && dropPos.y < npRect.height)
    {
        addToPlayqueue(item);
    }else {
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y) ;
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                appendItemToPlaylist(item,view.currentItem);
            }
            view.highlightItem.opacity = 0;
        }
    }

    if (dragitem != null) {
        dragitem.destroy(dragitem.animation == true? 500: 0);
        dragitem = null;
        currentView = null;
        currentItem = null;
        startPos = null;
        dragComponent == null
    }else {
        return;
    }
    updateNowNextPlaying();
}

function addToPlayqueue(item) {
    playqueueModel.addItems(item.mitemid);
    editorModel.setViewed(item.mitemid);
    updateNowNextPlaying();
}

function addMultipleToPlayqueue(list) {
    playqueueModel.addItems(list.getSelectedIDs());
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function removeFromPlayqueue(item) {
    if(playqueueView.currentIndex == playqueueModel.itemIndex(item.mitemid))
    {
        audio.stop();
    }
    playqueueModel.removeItems(item.mitemid);
    updateNowNextPlaying();
}

function removeMultipleFromPlayqueue(list) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        if(playqueueView.currentIndex == playqueueModel.itemIndex(ids[i]))
        {
            audio.stop();
            break;
        }
    }
    playqueueModel.removeItems(ids);
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function addToPlayqueueAndPlay(item)
{
    addToPlayqueue(item);
    playqueueView.currentIndex = playqueueModel.itemIndex(item.mitemid);
    console.log("Item Index is: " + playqueueModel.itemIndex(item.mitemid) + " " + item.mtitle);
    playNewSong();
    updateNowNextPlaying();
}

function addMultipleToPlayqueueAndPlay(list)
{
    var ids = list.getSelectedIDs();
    playqueueModel.addItems(ids);
    editorModel.setViewed(ids[0]);
    playqueueView.currentIndex = playqueueModel.itemIndex(ids[0]);
    playNewSong();
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function changeItemFavorite(item, val) {
    editorModel.setFavorite(item.mitemid,val);
}

function changeMultipleItemFavorite(list, val) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        editorModel.setFavorite(ids[i], val);
    }
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function play()
{
    if (audio.paused ) {
        audio.play();
    } else {
        return playNewSong();
    }
    return true;
}

function playNewSong() {
    audio.stop();

    // if there are no songs or the index is out of range, do nothing
    if((playqueueView.count <= 0)||
       (playqueueView.currentIndex >= playqueueView.count))
    {
        return false;
    }

    if (playqueueView.currentIndex == -1)
        playqueueView.currentIndex = 0;

    var item = playqueueView.currentItem;

    if (item == undefined){
        return false;
    }

    toolbar.trackName = item.mtitle;
    toolbar.artistName = item.martist;

    audio.source = item.muri;
    audio.playing = true;
    return true;
}

function playNextSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex < (playqueueView.count -1))
        {
            playqueueView.currentIndex++;
        }
        else
        {
            if (loop){
                playqueueView.currentIndex = 0;
            }else{
                stop();
                return;
            }
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function playPrevSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex == 0)
        {
            if (loop) {
                playqueueView.currentIndex = playqueueView.count - 1;
            }else {
                stop();
                return;
            }
        }
        else
        {
            playqueueView.currentIndex--;
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function updateNowNextPlaying()
{
    if (dbusControl.state == "stopped") {
        dbusControl.nextItem1 = -1;
        dbusControl.nextItem2 = -1;
    } else if (shuffle) {
        dbusControl.nextItem1 = playqueueModel.shuffleIndex(1);
        dbusControl.nextItem2 = playqueueModel.shuffleIndex(2);
    } else  if (playqueueView.currentIndex == 0) {
        if (playqueueView.count == 1) {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        } else if (playqueueView.count == 2) {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = -1;
        } else {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = 2;
        }
    } else {
        if (playqueueView.currentIndex+1 < playqueueView.count) {
            dbusControl.nextItem1 = playqueueView.currentIndex+1;

            if (dbusControl.nextItem1+1 < playqueueView.count) {
                dbusControl.nextItem2 = dbusControl.nextItem1+1;
            } else if (loop && playqueueView.count > 2) {
                dbusControl.nextItem2 = 0
            } else {
                dbusControl.nextItem2 = -1;
            }

        } else if (loop && playqueueView.count > 1) {
            dbusControl.nextItem1 = 0;
            if (playqueueView.count > 2) {
                dbusControl.nextItem2 = 1;
            } else {
                dbusControl.nextItem2 = -1
            }
        } else {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        }
    }
    dbusControl.updateNowNextTracks();

}

function pause()
{
    audio.pause()
}

function stop()
{
    audio.stop();
}

function formatLength(time)
{
    var val = parseInt(time);
    var dec = parseInt((time-val)*10);
    return (dec == 0)?val:(val + "." + dec)
}

function formatTime(time)
{
    var min = parseInt(time/60);
    var sec = parseInt(time%60);
    return min+ (sec<10 ? ":0":":") + sec
}

function openItemInDetailView(fromPage, item)
{
    switch(item.mitemtype) {
    case 2:
        // type is song
        // no detail view
        break;
    case 3:
        // type is artist
        labelArtist = item.mtitle;
        fromPage.addApplicationPage(artistDetailViewContent);
        break;
    case 4:
        // type is album
        thumbnailUri = item.mthumburi;
        labelAlbum = item.mtitle;
        albumLength = item.mlength;
        fromPage.addApplicationPage(albumDetailViewContent);
        break;
    case 5:
        // type is playlist
        thumbnailUri = item.mthumburi;
        labelPlaylist = item.mtitle;
        labelPlaylistURN = item.murn;
        fromPage.addApplicationPage(playlistDetailViewContent);
        break;
    default:
        break;
    }
}

function appendItemToPlaylist(item, playlistItem)
{
    miscModel.type = MusicListModel.MusicPlaylist;
    miscModel.clear();
    miscModel.playlist = playlistItem.mtitle;
    miscModel.addItems(item.mitemid);
    miscModel.savePlaylist(playlistItem.mtitle);
}
<commit_msg>changed setViewed to only get called when a song is played<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

var dragComponent = null;
var dragitem = null;
var currentView = null;
var currentItem = null
var startPos = null;

function playlistNameValidate(parm,val) {
    if (parm == "") return true;
    for (var i=0; i<parm.length; i++) {
        if (val.indexOf(parm.charAt(i),0) != -1) return false;
    }
    return true;
}

function startDrag(mouse,view,item) {
    if (view == null || item == null)
        return;

    if (dragitem != null) {
        dragitem.destroy();
        dragitem = null;
    }

     dragComponent = view.delegate;

    currentView = view;
    currentItem = item;
    startPos = item.mapToItem(scene,mouse.x, mouse.y);

    if (dragComponent.status == Component.Loading) {
        component.statusChanged.connect(createItem);
    }else{
        createItem();
    }
}

// this function will return type SONG(2),ARTIST(3),ALBUM(4) or PLAYLIST(5) from MediaItem
// depending on the input type, which is one of the ModelType
// we can't access MediaItem from here, so hardcoded the enum value
function convertListType(type) {
    switch (type) {
    case MusicListModel.ListofSongs:
            return 2;

    case MusicListModel.ListofAlbums:
            return 4;

    case MusicListModel.ListofArtists:
            return 3;

    case MusicListModel.ListofPlaylists:
            return 5;

    case MusicListModel.ListofAlbumsForArtist:
            return 4;

    case MusicListModel.ListofSongsForAlbum:
            return 2;

    case MusicListModel.ListofSongsForArtist:
            return 2;

    case MusicListModel.ListofRecentlyPlayed:
            // special case
            return currentItem.mtype;

    case MusicListModel.MusicPlaylist:
            return 5;

    default:
            return -1;
    }
}

function createItem() {
    dragitem = dragComponent.createObject(scene);
    // set dragitem position:

    dragitem.x = startPos.x;
    dragitem.y = startPos.y;

    dragitem.mtitle = currentItem.mtitle;
    dragitem.mthumburi = currentItem.mthumburi;
    dragitem.mitemid = currentItem.mitemid;
    dragitem.mitemtype = currentItem.mitemtype;
    dragitem.opacity = 0.8;
    dragitem.mcount = currentItem.mcount;
    dragitem.martist = currentItem.martist;
}

// return true if the point is in item's area,
// the point should be in the item's coordinate system.
function itemContainsPoint(item, point) {
    if ( point.x >=0 && point.x < item.width
         && point.y >= 0 && point.y < item.height) {
        return true;
    }
    return false;
}

function moveDragItem(mouse,item) {

    if (dragitem == null)
        return;

    var pos = item.mapToItem(scene,mouse.x, mouse.y);
    dragitem.x = pos.x;
    dragitem.y = pos.y;

    if (sideContentStrip.activeContent.tabs) {
        for (var i = 0;  i < sideContentStrip.activeContent.tabs.length -1; i++) {
            var it = sideContentStrip.activeContent.tabs[i];
            var pt = item.mapToItem(it,mouse.x, mouse.y);
            if (itemContainsPoint(it,pt)) {
                sideContentStrip.activeContent.selectTabAtIndex(i);
                sideContentStrip.activeContent.open();
                return;
            }
        }

        // specific code for landingscreen side content
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y);
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                view.currentIndex = targetIndex;

               view.highlightItem.opacity = 0.4;
            }else {
               view.highlightItem.opacity = 0;
            }
        }
    }

}

function endDrag(mouse,item) {
    if (!dragitem) {
        return;
    }

    // check if dropped at now playing button,
    // if yes, add to now playing list
    var dropPos = item.mapToItem(npRect,mouse.x,mouse.y);
    if (dropPos.x > 0 && dropPos.x < npRect.width
        && dropPos.y > 0 && dropPos.y < npRect.height)
    {
        addToPlayqueue(item);
    }else {
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y) ;
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                appendItemToPlaylist(item,view.currentItem);
            }
            view.highlightItem.opacity = 0;
        }
    }

    if (dragitem != null) {
        dragitem.destroy(dragitem.animation == true? 500: 0);
        dragitem = null;
        currentView = null;
        currentItem = null;
        startPos = null;
        dragComponent == null
    }else {
        return;
    }
    updateNowNextPlaying();
}

function addToPlayqueue(item) {
    playqueueModel.addItems(item.mitemid);
    updateNowNextPlaying();
}

function addMultipleToPlayqueue(list) {
    playqueueModel.addItems(list.getSelectedIDs());
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function removeFromPlayqueue(item) {
    if(playqueueView.currentIndex == playqueueModel.itemIndex(item.mitemid))
    {
        audio.stop();
    }
    playqueueModel.removeItems(item.mitemid);
    updateNowNextPlaying();
}

function removeMultipleFromPlayqueue(list) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        if(playqueueView.currentIndex == playqueueModel.itemIndex(ids[i]))
        {
            audio.stop();
            break;
        }
    }
    playqueueModel.removeItems(ids);
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function addToPlayqueueAndPlay(item)
{
    addToPlayqueue(item);
    playqueueView.currentIndex = playqueueModel.itemIndex(item.mitemid);
    console.log("Item Index is: " + playqueueModel.itemIndex(item.mitemid) + " " + item.mtitle);
    playNewSong();
    updateNowNextPlaying();
}

function addMultipleToPlayqueueAndPlay(list)
{
    var ids = list.getSelectedIDs();
    playqueueModel.addItems(ids);
    playqueueView.currentIndex = playqueueModel.itemIndex(ids[0]);
    playNewSong();
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function changeItemFavorite(item, val) {
    editorModel.setFavorite(item.mitemid,val);
}

function changeMultipleItemFavorite(list, val) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        editorModel.setFavorite(ids[i], val);
    }
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function play()
{
    if (audio.paused ) {
        audio.play();
    } else {
        return playNewSong();
    }
    return true;
}

function playNewSong() {
    audio.stop();

    // if there are no songs or the index is out of range, do nothing
    if((playqueueView.count <= 0)||
       (playqueueView.currentIndex >= playqueueView.count))
    {
        return false;
    }

    if (playqueueView.currentIndex == -1)
        playqueueView.currentIndex = 0;

    var item = playqueueView.currentItem;

    if (item == undefined){
        return false;
    }

    toolbar.trackName = item.mtitle;
    toolbar.artistName = item.martist;

    audio.source = item.muri;
    audio.playing = true;
    editorModel.setViewed(item.mitemid);
    return true;
}

function playNextSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex < (playqueueView.count -1))
        {
            playqueueView.currentIndex++;
        }
        else
        {
            if (loop){
                playqueueView.currentIndex = 0;
            }else{
                stop();
                return;
            }
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function playPrevSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex == 0)
        {
            if (loop) {
                playqueueView.currentIndex = playqueueView.count - 1;
            }else {
                stop();
                return;
            }
        }
        else
        {
            playqueueView.currentIndex--;
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function updateNowNextPlaying()
{
    if (dbusControl.state == "stopped") {
        dbusControl.nextItem1 = -1;
        dbusControl.nextItem2 = -1;
    } else if (shuffle) {
        dbusControl.nextItem1 = playqueueModel.shuffleIndex(1);
        dbusControl.nextItem2 = playqueueModel.shuffleIndex(2);
    } else  if (playqueueView.currentIndex == 0) {
        if (playqueueView.count == 1) {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        } else if (playqueueView.count == 2) {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = -1;
        } else {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = 2;
        }
    } else {
        if (playqueueView.currentIndex+1 < playqueueView.count) {
            dbusControl.nextItem1 = playqueueView.currentIndex+1;

            if (dbusControl.nextItem1+1 < playqueueView.count) {
                dbusControl.nextItem2 = dbusControl.nextItem1+1;
            } else if (loop && playqueueView.count > 2) {
                dbusControl.nextItem2 = 0
            } else {
                dbusControl.nextItem2 = -1;
            }

        } else if (loop && playqueueView.count > 1) {
            dbusControl.nextItem1 = 0;
            if (playqueueView.count > 2) {
                dbusControl.nextItem2 = 1;
            } else {
                dbusControl.nextItem2 = -1
            }
        } else {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        }
    }
    dbusControl.updateNowNextTracks();

}

function pause()
{
    audio.pause()
}

function stop()
{
    audio.stop();
}

function formatLength(time)
{
    var val = parseInt(time);
    var dec = parseInt((time-val)*10);
    return (dec == 0)?val:(val + "." + dec)
}

function formatTime(time)
{
    var min = parseInt(time/60);
    var sec = parseInt(time%60);
    return min+ (sec<10 ? ":0":":") + sec
}

function openItemInDetailView(fromPage, item)
{
    switch(item.mitemtype) {
    case 2:
        // type is song
        // no detail view
        break;
    case 3:
        // type is artist
        labelArtist = item.mtitle;
        fromPage.addApplicationPage(artistDetailViewContent);
        break;
    case 4:
        // type is album
        thumbnailUri = item.mthumburi;
        labelAlbum = item.mtitle;
        albumLength = item.mlength;
        fromPage.addApplicationPage(albumDetailViewContent);
        break;
    case 5:
        // type is playlist
        thumbnailUri = item.mthumburi;
        labelPlaylist = item.mtitle;
        labelPlaylistURN = item.murn;
        fromPage.addApplicationPage(playlistDetailViewContent);
        break;
    default:
        break;
    }
}

function appendItemToPlaylist(item, playlistItem)
{
    miscModel.type = MusicListModel.MusicPlaylist;
    miscModel.clear();
    miscModel.playlist = playlistItem.mtitle;
    miscModel.addItems(item.mitemid);
    miscModel.savePlaylist(playlistItem.mtitle);
}
<|endoftext|>


<commit_before>$(document).ready(function() {
	//--- check if presed enter ---
	$.fn.pressEnter = function(fn) {
		return this.each(function() {
			$(this).bind('enterPress', fn);
			$(this).keyup(function(e) {
				if(e.keyCode == 13) {
					$(this).trigger("enterPress");
				}
			})
		});
	};

	//---reload a image
	$.fn.reloadimg = function(fn) {
		return this.each(function(index) {
			var src = $(this).attr('src');
			$(this).attr('src', src);
			console.log("reload image:\nimg="+index+"\nsrc='"+src+"'");
		});
	};
});

//--- function basename (like PHP) ---
function basename(path) {
	var b = path;
	var lastChar = b.charAt(b.length - 1);
	if (lastChar === '/' || lastChar === '\\') {
		b = b.slice(0, -1);
	}
	b = b.replace(/^.*[\/\\]/g, '');
	return b;
}

//--- function empty (like PHP) ---
function empty(str) {
    return (!str || 0 === str.length);
}

//--- emailpattern ---
var emailpattern = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)(\\@)([a-zA-Z0-9\\-\\.]+)(\\.)([a-zA-Z]{2,4})$');

//--- Scroll to place ---
$(document).ready(function() {
	$("a[href^='#']").click(function(event) {
		event.preventDefault();
		var target = $(this).attr('href');
		$('html,body').animate({
			scrollTop: $(target).offset().top
		}, 1000);
		console.log("Scroll to "+target);
	});
});
function scrollto(place, valuetype) {
	if(typeof valuetype == "undefined") {
		var valuetype = object;
	}
	if(valuetype == "position") {
		$('html,body').animate({
			scrollTop: $(place).offset().top
		}, 1000);
		return false;
	}
	if(valuetype == "object") {
		$('html,body').animate({
			scrollTop: $(place).offset().top
		}, 1000);
		return false;
	}
}

//--- images first show after load --------------------------------------------
var images-show-after-laod = true;
$(document).ready(function() {
	if(images-show-after-laod) {
		$('img').each(function(){
			if(!$(this).hasClass("nojsload")) {
				$(this).hide();
				$(this).load(function() {
					$(this).fadeIn(400);
				});
			}
		})
	}
});<commit_msg>fixes<commit_after>$(document).ready(function() {
	//--- check if presed enter ---
	$.fn.pressEnter = function(fn) {
		return this.each(function() {
			$(this).bind('enterPress', fn);
			$(this).keyup(function(e) {
				if(e.keyCode == 13) {
					$(this).trigger("enterPress");
				}
			})
		});
	};

	//---reload a image
	$.fn.reloadimg = function(fn) {
		return this.each(function(index) {
			var src = $(this).attr('src');
			$(this).attr('src', src);
			console.log("reload image:\nimg="+index+"\nsrc='"+src+"'");
		});
	};
});

//--- function basename (like PHP) ---
function basename(path) {
	var b = path;
	var lastChar = b.charAt(b.length - 1);
	if (lastChar === '/' || lastChar === '\\') {
		b = b.slice(0, -1);
	}
	b = b.replace(/^.*[\/\\]/g, '');
	return b;
}

//--- function empty (like PHP) ---
function empty(str) {
    return (!str || 0 === str.length);
}

//--- emailpattern ---
var emailpattern = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)(\\@)([a-zA-Z0-9\\-\\.]+)(\\.)([a-zA-Z]{2,4})$');

//--- Scroll to place ---
$(document).ready(function() {
	$("a[href^='#']").click(function(event) {
		event.preventDefault();
		var target = $(this).attr('href');
		$('html,body').animate({
			scrollTop: $(target).offset().top
		}, 1000);
		console.log("Scroll to "+target);
	});
});
function scrollto(place, valuetype) {
	if(typeof valuetype == "undefined") {
		var valuetype = object;
	}
	if(valuetype == "position") {
		$('html,body').animate({
			scrollTop: $(place).offset().top
		}, 1000);
		return false;
	}
	if(valuetype == "object") {
		$('html,body').animate({
			scrollTop: $(place).offset().top
		}, 1000);
		return false;
	}
}

//--- images first show after load --------------------------------------------
var images_show_after_laod = true;
$(document).ready(function() {
	if(images_show_after_laod) {
		$('img').each(function(){
			if(!$(this).hasClass("nojsload")) {
				$(this).hide();
				$(this).load(function() {
					$(this).fadeIn(400);
				});
			}
		})
	}
});<|endoftext|>


<commit_before>//this is Logan's monstrosity
'use strict';
<<<<<<< HEAD
document.addEventListener('DOMContentLoaded', function () {
  var questionNum = 0;
  //array of place images
  var staticImageArray = ['../images/cf_building.jpg', '../images/cf_building.jpg', '../images/cf_building.jpg'];
  //array of questions/events
  var staticQuestionArray = ['You are on your home directory of the terminal and following along, what do you type in the command line?', 'How do you spend the weekend?'];
  //array of choices for the questions
  var staticChoiceArray = [['rm –rf', 'cd codefellows/201', 'tree', 'cmatrix'], ['Go to the spa', 'study all weekend', 'go out for dinner and drinks with friends', 'sleep your standard eight hours, run, study']];
  //array of responses to the choices
  var staticResponseArray = [['You deleted all files on your machine, you can no longer continue in the class. (-100, health, -100 grade)', 'You follow along with the class, learing much about how to properly operate your computer.', 'You tree from your home directory, the files keep flying past your screen, it amazes you how many "interesting" files are on your computer ;). (+5 grade, -10 social)', 'You cmatrix and stare at the screen mesmorized by the falling matrix, you pay little attention to the lecture. (-10 grade)'], ['You go to the spa to rejuvenate and relax, sleeping in and lounging all weekend. (+20 health, -10 grade, +10 social)', 'You study very hard all weekend, not getting a chance to relax or see any friends. (+10 grade, - 15 social)', 'You go out drinking all weekend having a terrible hangover, but somehow on Monday your code is finished? (-15 health, +5 grade, +20 social)', 'You get your standard eight hours of sleep, go for a run, study and finish your homework like a productive member of society. (+5 health, +5 grade, -5 social)']];

  var uniqueClassPerResponse = [['rm-rf', 'cdCorrectly', 'tree', 'cmatrix'], ['spa', 'studyWeekend', 'dinner', 'sleepEight']];
  // increments score
  var affectScore = [[[-100, -100, -100], [0, 0, +25], [0, 0, 0], [0, -25, 0]], [[+25, -25, 0], [-25, +25, -25], [-25, -25, +25], [+10, +10, +10]]];
  //array of randomly chosen questions
  var randomQuestionArray = [];
  //corresponding choices to the questions
  var randomChoiceArray = [];
  //corresponding responses to the choices
  var randomResponseArray = [];
  //collecting local storage from character page
  // var local = JASN.parse(localStorage);
  // console.log(local);
  //character constructor
  function Character(name, image) {
    this.name = name;
    this.image = image;
    this.health = 100;
    this.grade = 100;
    this.social = 100;
  }

  var character = new Character(localStorage.userName, localStorage.imgUrl);
  console.log(character);

  renderPage();

  function renderPage() {
    renderImage(staticImageArray[questionNum]);
    displayQuestionPrompt(questionNum);
    createDialogue(staticImageArray[questionNum], staticChoiceArray[questionNum], staticResponseArray[questionNum]);
  }

  //RENDERING PAGE
  function renderImage(image) {
    var pageEl = document.getElementById('place-image');
    var imageEl = document.createElement('img');
    imageEl.setAttribute('id', 'background-image');
    imageEl.setAttribute('src', image);
    pageEl.appendChild(imageEl);
  }

  function displayQuestionPrompt(questionNum) {
    var questionContainer = document.getElementById('prompt');
    var displayQuestionEl = document.createElement('p');
    displayQuestionEl.setAttribute('id', 'questionNum');
    displayQuestionEl.textContent = staticQuestionArray[questionNum];
    questionContainer.appendChild(displayQuestionEl);
  }

  function createDialogue(image, choices, responses) {
    var gameText = document.getElementById('game-text');

    for (var i = 0; i < choices.length; i++) {
      var choiceEl = document.createElement('li');
      choiceEl.setAttribute('class', 'question ' + uniqueClassPerResponse[questionNum][i]);
      choiceEl.setAttribute('id', i);
      choiceEl.textContent = choices[i];
      var choicesList = document.getElementById('choices-list');
      choicesList.appendChild(choiceEl);
    }
    handleChoiceClick();      //
  }

  function updateStats(responseIndex) {
    var responseIndex = parseInt(responseIndex);
    var character = JSON.parse(localStorage.character);
    console.log(character);
    for (var i = 0; i < affectScore.length; i++) {
      character.health = character.health + affectScore[responseIndex][i][0];
      console.log('this.health ' + character.health);
      character.grade = character.grade + affectScore[responseIndex][i][1];
      console.log('this.grade ' + character.grade);
      character.social = character.social + affectScore[responseIndex][i][2];
      console.log('this.social ' + character.social);
    }
  }
  //pair programmed with EVERYONE

  function handleChoiceClick() {    //renders the response
    var choicesCollection = document.getElementById('choices-list').children;
    var choicesArray = Array.prototype.slice.call(choicesCollection);

    choicesArray.forEach(function (choice) {
      choice.addEventListener('click', function () {
        renderResponse(this.id, questionNum);
        updateStats(this.id);
      });
    });
  }

  function removePrompt() {
    var promptParent = document.getElementById('prompt');
    var promptChild = document.getElementById('questionNum');
    promptParent.removeChild(promptChild);
  }

  function removeChoiceElements() {
    var choicesList = document.getElementById('choices-list').children;
    var choicesArray = Array.prototype.slice.call(choicesList);
    choicesArray.forEach(function (choice) {
      choice.remove();
    });
  }

  function renderResponse(id, questionNum) {
    removeChoiceElements();
    removePrompt();

    var gameText = document.getElementById('game-text');  //append response to textContent div
    var responsePar = document.createElement('p');
    responsePar.setAttribute('id', 'response-paragraph');

    var responseId = parseInt(id);
    // console.log(responseId);
    responsePar.textContent = staticResponseArray[questionNum][id];
    gameText.appendChild(responsePar);

    if (questionNum < staticQuestionArray.length - 1) {
      responsePar.addEventListener('click', function () {   //when click, clear DOM elements and render new
        clearElements();
        renderPage();
      });
    } else {
      renderTransition();
    }
  }

  function clearElements() {
    questionNum++;              //after rendering response, move to next question

    console.log('incrementing...now on question at index: ', questionNum);

    var response = document.getElementById('response-paragraph');
    console.log(response);
    var image = document.getElementById('background-image');
    console.log('removing image');
    image.remove();
    response.remove();
  }

  function renderTransition() {           //reveals a hidden link to transition to week2
    var jCharacter = JSON.stringify(character); //wraps up character in JSON to send through
    localStorage.character = jCharacter;
    console.log(jCharacter);
    location.href = '../game/dayTwo.html';
    // var hiddenLink = document.getElementById('link-to-week2');
    // hiddenLink.removeAttribute('class', 'hidden');
  }

});
=======
//array of boss images
var bossImageArray = ['../images/angrierAdam.jpg', '../images/angryAdam.jpg', '../images/normalAdam.jpg', '../images/happyAdam.jpg','../images/happierAdam.jpg'];
//array of boss questions
var bossQuestionArray = ['Adam uses busmall, what is your response?', 'Adam uses salmon cookies, what is your response?', 'Adam uses chocolate pizza, what is your response?', 'Adam uses about me, what is your response?'];
//corresponding choices to questions
var bossChoiceArray = [['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']];
//corresponding responses to choices
var bossResponseArray = [['hello', 'hello', 'hello', 'hello'], ['hello', 'hello', 'hello', 'hello'], ['hello', 'hello', 'hello', 'hello'], ['hello', 'hello', 'hello', 'hello']];
//corresponding effects per response
var bossEffectArray = [];
function Character(name){
  this.name = name;
  this.lowHealthImg = '../images/IMG_0008.jpg';
  this.health = 100;
  this.grade = 100;
  this.social = 100;
}
var player = new Character('LoganTemp');
function renderBossFight(){
  intro();
  renderImage('../images/cf_building.jpg');
  var win = bossAdam();
  if(win === true){
    location.href = '../credits/credits.html';
  }
}
renderBossFight();
function intro(){
  appendText('You arive at your final day of class and are confronted by Adam, he asks to speak to you privatly...');
  var clickEl = document.getElementById('game-text');
  clickEl.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    removeText();
  }), false;
}
function randomValue(max, min){
  return Math.round(Math.random() * (max - min) + min);
}
function bossQuestion(index){
  appendText(bossQuestionArray[index]);
  var questionEl = document.getElementById('game-text');
  questionEl.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    removeText();
    bossAnswer(index);
  }), false;
}
function bossAnswer(index){
  appendFour(index);
}
function bossResponse(index){
  console.log(index);
  removeFour();
  appendText(index);
  var responseEl = document.getElementById('game-text');
  responseEl.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    removeText();
  }), false;
}
function bossAdam(){
  var count = 0;
  do{
    var random = randomValue(bossQuestionArray.length - 1, 0);
    console.log(random);
    var questionEl = document.getElementById('game-text');
    questionEl.addEventListener('click', function(event) {
      event.stopPropagation();
      event.preventDefault();
      bossQuestion(random);
    }), false;
    count++;
  }while(player.grade < 90 && count < 4);
}
function playerImage(image){
  var pageEl = document.getElementById('user-box');
  var imageEl = document.createElement('img');
  imageEl.setAttribute('id', 'player-image');
  imageEl.setAttribute('src', image);
  pageEl.appendChild(imageEl);
}
function interactionImage(image){
  var pageEl = document.getElementById('interactive-box');
  var imageEl = document.createElement('img');
  imageEl.setAttribute('id', 'interactive-image');
  imageEl.setAttribute('src', image);
  pageEl.appendChild(imageEl);
}
function renderImage(image) {
  var pageEl = document.getElementById('place-image');
  var imageEl = document.createElement('img');
  imageEl.setAttribute('id', 'background-image');
  imageEl.setAttribute('src', image);
  pageEl.appendChild(imageEl);
}
function appendText(text){
  var sectionEl = document.getElementById('game-text');
  var textEl = document.createElement('p');
  textEl.setAttribute('id', 'text-content');
  textEl.textContent = text;
  sectionEl.appendChild(textEl);
}
function removeText(){
  var sectionEl = document.getElementById('game-text');
  var textEl = document.getElementById('text-content');
  sectionEl.removeChild(textEl);
}
function appendFour(index){
  var appendArray = bossChoiceArray[index];
  var ulEl = document.getElementById('questions-list');
  for(var i = 0; i < appendArray.length; i++){
    var liEl = document.createElement('li');
    liEl.setAttribute('id', 'listChoice' + i);
    liEl.textContent = appendArray[i];
    ulEl.appendChild(liEl);
  }
  var choiceOne = document.getElementById('listChoice0');
  choiceOne.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    bossResponse(bossResponseArray[index][0]);
  }), false;
  var choiceTwo = document.getElementById('listChoice1');
  choiceTwo.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    bossResponse(bossResponseArray[index][1]);
  }), false;
  var choiceThree = document.getElementById('listChoice2');
  choiceThree.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    bossResponse(bossResponseArray[index][2]);
  }), false;
  var choiceFour = document.getElementById('listChoice3');
  choiceFour.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    bossResponse(bossResponseArray[index][3]);
  }), false;
}
function removeFour(){
  var ulEl = document.getElementById('questions-list');
  for(var i = 0; i < 4; i++){
    var liEl = document.getElementById('listChoice' + i);
    ulEl.removeChild(liEl);
  }
}
>>>>>>> 4df359272ab74bdef8b59bd364ca58dde6134abc
<commit_msg>fixed merge conflict in boss.js<commit_after>//this is Logan's monstrosity
'use strict';
document.addEventListener('DOMContentLoaded', function () {
  var questionNum = 0;
  //array of place images
  var staticImageArray = ['../images/cf_building.jpg', '../images/cf_building.jpg', '../images/cf_building.jpg'];
  //array of questions/events
  var staticQuestionArray = ['You are on your home directory of the terminal and following along, what do you type in the command line?', 'How do you spend the weekend?'];
  //array of choices for the questions
  var staticChoiceArray = [['rm –rf', 'cd codefellows/201', 'tree', 'cmatrix'], ['Go to the spa', 'study all weekend', 'go out for dinner and drinks with friends', 'sleep your standard eight hours, run, study']];
  //array of responses to the choices
  var staticResponseArray = [['You deleted all files on your machine, you can no longer continue in the class. (-100, health, -100 grade)', 'You follow along with the class, learing much about how to properly operate your computer.', 'You tree from your home directory, the files keep flying past your screen, it amazes you how many "interesting" files are on your computer ;). (+5 grade, -10 social)', 'You cmatrix and stare at the screen mesmorized by the falling matrix, you pay little attention to the lecture. (-10 grade)'], ['You go to the spa to rejuvenate and relax, sleeping in and lounging all weekend. (+20 health, -10 grade, +10 social)', 'You study very hard all weekend, not getting a chance to relax or see any friends. (+10 grade, - 15 social)', 'You go out drinking all weekend having a terrible hangover, but somehow on Monday your code is finished? (-15 health, +5 grade, +20 social)', 'You get your standard eight hours of sleep, go for a run, study and finish your homework like a productive member of society. (+5 health, +5 grade, -5 social)']];

  var uniqueClassPerResponse = [['rm-rf', 'cdCorrectly', 'tree', 'cmatrix'], ['spa', 'studyWeekend', 'dinner', 'sleepEight']];
  // increments score
  var affectScore = [[[-100, -100, -100], [0, 0, +25], [0, 0, 0], [0, -25, 0]], [[+25, -25, 0], [-25, +25, -25], [-25, -25, +25], [+10, +10, +10]]];
  //array of randomly chosen questions
  var randomQuestionArray = [];
  //corresponding choices to the questions
  var randomChoiceArray = [];
  //corresponding responses to the choices
  var randomResponseArray = [];
  //collecting local storage from character page
  // var local = JASN.parse(localStorage);
  // console.log(local);
  //character constructor
  function Character(name, image) {
    this.name = name;
    this.image = image;
    this.health = 100;
    this.grade = 100;
    this.social = 100;
  }

  var character = new Character(localStorage.userName, localStorage.imgUrl);
  console.log(character);

  renderPage();

  function renderPage() {
    renderImage(staticImageArray[questionNum]);
    displayQuestionPrompt(questionNum);
    createDialogue(staticImageArray[questionNum], staticChoiceArray[questionNum], staticResponseArray[questionNum]);
  }

  //RENDERING PAGE
  function renderImage(image) {
    var pageEl = document.getElementById('place-image');
    var imageEl = document.createElement('img');
    imageEl.setAttribute('id', 'background-image');
    imageEl.setAttribute('src', image);
    pageEl.appendChild(imageEl);
  }

  function displayQuestionPrompt(questionNum) {
    var questionContainer = document.getElementById('prompt');
    var displayQuestionEl = document.createElement('p');
    displayQuestionEl.setAttribute('id', 'questionNum');
    displayQuestionEl.textContent = staticQuestionArray[questionNum];
    questionContainer.appendChild(displayQuestionEl);
  }

  function createDialogue(image, choices, responses) {
    var gameText = document.getElementById('game-text');

    for (var i = 0; i < choices.length; i++) {
      var choiceEl = document.createElement('li');
      choiceEl.setAttribute('class', 'question ' + uniqueClassPerResponse[questionNum][i]);
      choiceEl.setAttribute('id', i);
      choiceEl.textContent = choices[i];
      var choicesList = document.getElementById('choices-list');
      choicesList.appendChild(choiceEl);
    }
    handleChoiceClick();      //
  }

  function updateStats(responseIndex) {
    var responseIndex = parseInt(responseIndex);
    var character = JSON.parse(localStorage.character);
    console.log(character);
    for (var i = 0; i < affectScore.length; i++) {
      character.health = character.health + affectScore[responseIndex][i][0];
      console.log('this.health ' + character.health);
      character.grade = character.grade + affectScore[responseIndex][i][1];
      console.log('this.grade ' + character.grade);
      character.social = character.social + affectScore[responseIndex][i][2];
      console.log('this.social ' + character.social);
    }
  }
  //pair programmed with EVERYONE

  function handleChoiceClick() {    //renders the response
    var choicesCollection = document.getElementById('choices-list').children;
    var choicesArray = Array.prototype.slice.call(choicesCollection);

    choicesArray.forEach(function (choice) {
      choice.addEventListener('click', function () {
        renderResponse(this.id, questionNum);
        updateStats(this.id);
      });
    });
  }

  function removePrompt() {
    var promptParent = document.getElementById('prompt');
    var promptChild = document.getElementById('questionNum');
    promptParent.removeChild(promptChild);
  }

  function removeChoiceElements() {
    var choicesList = document.getElementById('choices-list').children;
    var choicesArray = Array.prototype.slice.call(choicesList);
    choicesArray.forEach(function (choice) {
      choice.remove();
    });
  }

  function renderResponse(id, questionNum) {
    removeChoiceElements();
    removePrompt();

    var gameText = document.getElementById('game-text');  //append response to textContent div
    var responsePar = document.createElement('p');
    responsePar.setAttribute('id', 'response-paragraph');

    var responseId = parseInt(id);
    // console.log(responseId);
    responsePar.textContent = staticResponseArray[questionNum][id];
    gameText.appendChild(responsePar);

    if (questionNum < staticQuestionArray.length - 1) {
      responsePar.addEventListener('click', function () {   //when click, clear DOM elements and render new
        clearElements();
        renderPage();
      });
    } else {
      renderTransition();
    }
  }

  function clearElements() {
    questionNum++;              //after rendering response, move to next question

    console.log('incrementing...now on question at index: ', questionNum);

    var response = document.getElementById('response-paragraph');
    console.log(response);
    var image = document.getElementById('background-image');
    console.log('removing image');
    image.remove();
    response.remove();
  }

  function renderTransition() {           //reveals a hidden link to transition to week2
    var jCharacter = JSON.stringify(character); //wraps up character in JSON to send through
    localStorage.character = jCharacter;
    console.log(jCharacter);
    location.href = '../game/dayTwo.html';
    // var hiddenLink = document.getElementById('link-to-week2');
    // hiddenLink.removeAttribute('class', 'hidden');
  }

});
// //array of boss images
// var bossImageArray = ['../images/angrierAdam.jpg', '../images/angryAdam.jpg', '../images/normalAdam.jpg', '../images/happyAdam.jpg','../images/happierAdam.jpg'];
// //array of boss questions
// var bossQuestionArray = ['Adam uses busmall, what is your response?', 'Adam uses salmon cookies, what is your response?', 'Adam uses chocolate pizza, what is your response?', 'Adam uses about me, what is your response?'];
// //corresponding choices to questions
// var bossChoiceArray = [['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']];
// //corresponding responses to choices
// var bossResponseArray = [['hello', 'hello', 'hello', 'hello'], ['hello', 'hello', 'hello', 'hello'], ['hello', 'hello', 'hello', 'hello'], ['hello', 'hello', 'hello', 'hello']];
// //corresponding effects per response
// var bossEffectArray = [];
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

import {StyledMenuEntryWrapper} from './StyledComponents'
import MenuItem from './MenuItem'
import {prepareMenuTree} from '../../utils/navigationUtils'

const MenuTree = ({
  items,
  searchFilter,
  typeMapping,
  requireSearch
}) => {
  if (requireSearch && !searchFilter) {
    return null
  }

  if (!items || items.length === 0) {
    return null
  }

  const actualItems = prepareMenuTree(items, searchFilter, typeMapping)

  const MenuItems = actualItems.map(item => (
    <MenuItem
      key={item.name}
      item={item}
      typeMapping={typeMapping}
      menuTreePath={item.name}
    />
  ))

  return (
    <StyledMenuEntryWrapper>
      {MenuItems}
    </StyledMenuEntryWrapper>
  )
}

MenuTree.propTypes = {
  items: PropTypes.array,
  searchFilter: PropTypes.string,
  typeMapping: PropTypes.objectOf(
    PropTypes.shape({
      component: PropTypes.elementType.isRequired,
      childrenWrapperComponent: PropTypes.elementType.isRequired,
      filterAttribute: PropTypes.arrayOf(PropTypes.string),
      props: PropTypes.object
    })
  ),
  requireSearch: PropTypes.bool
}

export default React.memo(MenuTree)
<commit_msg>fix(admin): fix duplicated search entries<commit_after>import React from 'react'
import PropTypes from 'prop-types'

import {StyledMenuEntryWrapper} from './StyledComponents'
import MenuItem from './MenuItem'
import {prepareMenuTree} from '../../utils/navigationUtils'

const MenuTree = ({
  items,
  searchFilter,
  typeMapping,
  requireSearch
}) => {
  if (requireSearch && !searchFilter) {
    return null
  }

  if (!items || items.length === 0) {
    return null
  }

  const actualItems = prepareMenuTree(items, searchFilter, typeMapping)

  const MenuItems = actualItems.map((item, index) => (
    <MenuItem
      key={index}
      item={item}
      typeMapping={typeMapping}
      menuTreePath={item.name}
    />
  ))

  return (
    <StyledMenuEntryWrapper>
      {MenuItems}
    </StyledMenuEntryWrapper>
  )
}

MenuTree.propTypes = {
  items: PropTypes.array,
  searchFilter: PropTypes.string,
  typeMapping: PropTypes.objectOf(
    PropTypes.shape({
      component: PropTypes.elementType.isRequired,
      childrenWrapperComponent: PropTypes.elementType.isRequired,
      filterAttribute: PropTypes.arrayOf(PropTypes.string),
      props: PropTypes.object
    })
  ),
  requireSearch: PropTypes.bool
}

export default React.memo(MenuTree)
<|endoftext|>


<commit_before>/**
 * pv统计service
 * Created by donaldcen on 2015/11/01
 * @constructor
 */

var pageConfig = require('../fileStorage/pageid.json');
var PvService = require('./PvService');
var dateFormat = require('../utils/dateFormat');
var LogService = require('../service/LogService');
var Omerge = require('../utils/objectMerge');
var FileStorage = require('./FileStorage');
var log4js = require('log4js'),
    logger = log4js.getLogger();

/**
 * 转换pageMap
 * @param {json} pageconfig 页面id配置
 * @returns {{}}
 */
var page2Map = function (pageconfig) {
    var map = {};
    for (var i in pageconfig) {
        var pageid = i.replace(/-/g, '_');
        if (!map[pageconfig[i]]) {
            map[pageconfig[i]] = [];
        }
        if (!(i in map[pageconfig[i]])) {
            map[pageconfig[i]].push(pageid);
        }
    }
    return map;
};

/**
 * 字符串转时间
 * @param str
 */
var string2Date = function (str, format) {
    var timeStr = {
        y: '',
        M: '',
        d: '',
        h: '',
        m: '',
        s: ''
    };
    var time;
    var len = format.length;
    for (var i = 0; i < len; i++) {
        if (typeof timeStr[format[i]] != 'undefined') {
            timeStr[format[i]] += str[i];
        }
    }
    time = new Date(timeStr.y + '/' + timeStr.M + '/' + timeStr.d + ' ' + timeStr.h + ':' + timeStr.m + ':' + timeStr.s);
    return time;
};

function StatisticsServicePV() {
    this.pageMap = page2Map(pageConfig);
    this.pvService = PvService.getServices()[0] || PvService.create();
    this.options = {
        filePath: __dirname + '/../fileStorage/count_{date}'
    };
    this.files = {};
    //this.pvService.getByDate('20151101', function(err, data){
    //    console.log(err, data);
    //});
}

StatisticsServicePV.prototype = {
    /**
     * 初始化fileStorage
     * @param {String} dateStr 日期（20151030）
     * @param {Function} callback 回调
     */
    openFile: function (dateStr, callback) {
        var opt = this.options;
        if (this.files[dateStr]) {
            callback(null, this.files[dateStr]);
        } else {
            this.files[dateStr] = new FileStorage(opt.filePath.replace(/\{date\}/g, dateStr), function (err, fileStorage) {
                callback(err, fileStorage);
            }, false);
        }
    },
    /**
     * 存入统计数据
     * @param {String} dateStr 日期时间戳(20151011)
     * @param {Object} data 存入内容
     * @param {Function} callback
     */
    save: function (dateStr, data, callback) {
        var me = this;
        me.openFile(dateStr, function (err, fileStorage) {
            if (err) {
                callback(err);
            } else {
                fileStorage.update(data, function (err, data) {
                    callback(err, data);
                });
            }

        });
    },

    /**
     * 取一天中每一份的错误量
     * @param {String} appid
     * @param {String} dateStr
     * @param {Function} callback
     */
    getErrLogByDate: function (appid, dateStr, callback) {
        var start = Number(string2Date(dateStr, 'yyyyMMdd'));
        var end = start + 1000 * 60 * 60 * 24;
        this.getErrLog(appid, start - 1000 * 60 * 10, end, callback);//多取前面10分钟和pv对齐
    },

    /**
     * 获取区间内每分钟错误
     * @param {String} appid 项目id
     * @param {Number} start 开始时间
     * @param {Number} end 结束时间
     * @param {Function} callback 回调
     */
    getErrLog: function (appid, start, end, callback) {
        var logService = new LogService();
        var params = {
            id: Number(appid),
            startDate: Number(start),
            endDate: Number(end)
        };
        logService.queryCount(params, function (err, items) {
            if (err) {
                logger.error('errLog：拉取错误失败,'+JSON.stringify(params) + err);
            }
            callback(err, items);
        });
    },

    /**
     * 获取数据统计并保存
     * @param dateStr
     * @param callback
     */
    countSave: function (dateStr, callback) {
        var me = this;
        me.getEP(dateStr, function(err, data){
            if(data){
                me.save(dateStr, data, function(err, data){
                    callback(err, data);
                });
            }
        });
    },

    /**
     * 获取对应天的错误和pv
     * @param {String} dateStr 日期戳
     * @param {Function} callback
     */
    getEP: function (dateStr, callback) {
        var me = this;
        var ep = {};
        var cblen = 0;
        var errs = [];
        var cb = function () {
            cblen--;
            if (cblen == 0) {
                console.log('数据采集完成'+dateStr);
                me.countCent(ep);
                (errs.length == 0) && (errs = null);
                callback(errs, ep);
            }
        };
        //拉取错误数据；
        var appids = [];
        for (var appid in this.pageMap) {
            appids.push(appid);
            cblen++;
        }

        var timer = setInterval(function () {
            var id = appids.pop();
            if (id) {
                me.getErrLogByDate(id, dateStr, function (err, data) {
                    if (data) {
                        console.log('拉取成功:'+ id);
                        (!ep[id]) && (ep[id] = {});
                        ep[id] = Omerge(ep[id], me.countError(data));
                    }
                    cb();
                });
            }else{
                clearInterval(timer);
                timer = null;
            }
        }, 500);

        //拉取pv数据
        cblen++;
        me.pvService.getByDate(dateStr, function(err, data){
            for(var appid in me.pageMap){
                var pvs = [];
                (me.pageMap[appid] || []).forEach(function(pageid){
                    if(data[pageid]){
                        pvs.push(data[pageid]);
                    }
                });
                ep[appid] = Omerge(ep[appid], me.countPv(dateStr, pvs));
            }
            console.log('pv计算完成');
            cb();
        });
    },

    /**
     * 计算错误率
     * @param eps
     * @returns {*}
     */
    countCent: function(eps){
        for(var id in eps){
            (function(ep){
                for(var t in ep){
                    if(ep[t].pv){
                        (!ep[t.count]) && (ep[t.count] = 0);
                        ep[t].cent = (ep[t].count / ep[t].pv).toFixed(5);
                    }
                }
            })(eps[id]);
        }
        return eps;
    },

    /**
     * 统计每10分钟的错误
     * @param elog
     * @returns {{}}
     */
    countError: function (elog) {
        var all = {};
        var detaT = 1000 * 60 * 10; //每10分钟的毫秒数
        (elog || []).forEach(function (item) {
            var t10 = (parseInt(item.time / detaT) + 1) * detaT; //由于pv是后收集加到下一个10分，时间轴后移
            if (!all[t10]) {
                all[t10] = {count: Number(item.count)};
            } else {
                all[t10].count += Number(item.count);
            }
        });
        return all;
    },

    /**
     * 统计pv
     * @param {String} dateStr
     * @param {Array} pvs
     * @returns {{}}
     */
    countPv: function (dateStr, pvs) {
        var all = {};
        (pvs || []).forEach(function (pv) {
            for (var date in pv) {
                var time = Number(string2Date(dateStr + date, 'yyyyMMddhhmm'));
                if (!all[time]) {
                    all[time] = {pv: Number(pv[date]) || 0};
                } else {
                    all[time].pv += Number(pv[date]);
                }
            }
        });
        return all;
    },

    query: function (appid, dateStr, callback) {

    }
};

module.exports = StatisticsServicePV;

<commit_msg>just do it<commit_after>/**
 * pv统计service
 * Created by donaldcen on 2015/11/01
 * @constructor
 */

var pageConfig = require('../fileStorage/pageid.json');
var PvService = require('./PvService');
var dateFormat = require('../utils/dateFormat');
var LogService = require('../service/LogService');
var Omerge = require('../utils/objectMerge');
var FileStorage = require('./FileStorage');
var log4js = require('log4js'),
    logger = log4js.getLogger();

/**
 * 转换pageMap
 * @param {json} pageconfig 页面id配置
 * @returns {{}}
 */
var page2Map = function (pageconfig) {
    var map = {};
    for (var i in pageconfig) {
        var pageid = i.replace(/-/g, '_');
        if (!map[pageconfig[i]]) {
            map[pageconfig[i]] = [];
        }
        if (!(i in map[pageconfig[i]])) {
            map[pageconfig[i]].push(pageid);
        }
    }
    return map;
};

/**
 * 字符串转时间
 * @param str
 */
var string2Date = function (str, format) {
    var timeStr = {
        y: '',
        M: '',
        d: '',
        h: '',
        m: '',
        s: ''
    };
    var time;
    var len = format.length;
    for (var i = 0; i < len; i++) {
        if (typeof timeStr[format[i]] != 'undefined') {
            timeStr[format[i]] += str[i];
        }
    }
    time = new Date(timeStr.y + '/' + timeStr.M + '/' + timeStr.d + ' ' + timeStr.h + ':' + timeStr.m + ':' + timeStr.s);
    return time;
};

function StatisticsServicePV() {
    this.pageMap = page2Map(pageConfig);
    this.pvService = PvService.getServices()[0] || PvService.create();
    this.options = {
        filePath: __dirname + '/../fileStorage/count_{date}'
    };
    this.files = {};
    //this.pvService.getByDate('20151101', function(err, data){
    //    console.log(err, data);
    //});
}

StatisticsServicePV.prototype = {
    /**
     * 初始化fileStorage
     * @param {String} dateStr 日期（20151030）
     * @param {Function} callback 回调
     */
    openFile: function (dateStr, callback) {
        var opt = this.options;
        if (this.files[dateStr]) {
            callback(null, this.files[dateStr]);
        } else {
            this.files[dateStr] = new FileStorage(opt.filePath.replace(/\{date\}/g, dateStr), function (err, fileStorage) {
                callback(err, fileStorage);
            }, false);
        }
    },
    /**
     * 存入统计数据
     * @param {String} dateStr 日期时间戳(20151011)
     * @param {Object} data 存入内容
     * @param {Function} callback
     */
    save: function (dateStr, data, callback) {
        var me = this;
        me.openFile(dateStr, function (err, fileStorage) {
            if (err) {
                callback(err);
            } else {
                fileStorage.update(data, function (err, data) {
                    callback(err, data);
                });
            }

        });
    },

    /**
     * 取一天中每一份的错误量
     * @param {String} appid
     * @param {String} dateStr
     * @param {Function} callback
     */
    getErrLogByDate: function (appid, dateStr, callback) {
        var start = Number(string2Date(dateStr, 'yyyyMMdd'));
        var end = start + 1000 * 60 * 60 * 24;
        this.getErrLog(appid, start - 1000 * 60 * 10, end, callback);//多取前面10分钟和pv对齐
    },

    /**
     * 获取区间内每分钟错误
     * @param {String} appid 项目id
     * @param {Number} start 开始时间
     * @param {Number} end 结束时间
     * @param {Function} callback 回调
     */
    getErrLog: function (appid, start, end, callback) {
        var logService = new LogService();
        var params = {
            id: Number(appid),
            startDate: Number(start),
            endDate: Number(end)
        };
        logService.queryCount(params, function (err, items) {
            if (err) {
                logger.error('errLog：拉取错误失败,'+JSON.stringify(params) + err);
            }
            callback(err, items);
        });
    },

    /**
     * 获取数据统计并保存
     * @param dateStr
     * @param callback
     */
    countSave: function (dateStr, callback) {
        var me = this;
        me.getEP(dateStr, function(err, data){
            if(data){
                me.save(dateStr, data, function(err, data){
                    callback(err, data);
                });
            }
        });
    },

    /**
     * 获取对应天的错误和pv
     * @param {String} dateStr 日期戳
     * @param {Function} callback
     */
    getEP: function (dateStr, callback) {
        var me = this;
        var ep = {};
        var cblen = 0;
        var errs = [];
        var cb = function () {
            cblen--;
            if (cblen == 0) {
                console.log('数据采集完成'+dateStr);
                me.countCent(ep);
                (errs.length == 0) && (errs = null);
                callback(errs, ep);
            }
        };
        //拉取错误数据；
        var appids = [];
        for (var appid in this.pageMap) {
            appids.push(appid);
            cblen++;
        }

        var timer = setInterval(function () {
            var id = appids.pop();
            if (id) {
                me.getErrLogByDate(id, dateStr, function (err, data) {
                    if (data) {
                        console.log('拉取成功:'+ id);
                        (!ep[id]) && (ep[id] = {});
                        ep[id] = Omerge(ep[id], me.countError(data));
                    }
                    cb();
                });
            }else{
                clearInterval(timer);
                timer = null;
            }
        }, 500);

        //拉取pv数据
        cblen++;
        me.pvService.getByDate(dateStr, function(err, data){
            for(var appid in me.pageMap){
                var pvs = [];
                (me.pageMap[appid] || []).forEach(function(pageid){
                    if(data[pageid]){
                        pvs.push(data[pageid]);
                    }
                });
                ep[appid] = Omerge(ep[appid], me.countPv(dateStr, pvs));
            }
            console.log('pv计算完成');
            cb();
        });
    },

    /**
     * 计算错误率
     * @param eps
     * @returns {*}
     */
    countCent: function(eps){
        for(var id in eps){
            (function(ep){
                for(var t in ep){
                    if(ep[t].pv > 0){
                        (typeof ep[t].count != 'number') && (ep[t].count = 0);
                        ep[t].cent = (ep[t].count / ep[t].pv).toFixed(5);
                    }
                }
            })(eps[id]);
        }
        return eps;
    },

    /**
     * 统计每10分钟的错误
     * @param elog
     * @returns {{}}
     */
    countError: function (elog) {
        var all = {};
        var detaT = 1000 * 60 * 10; //每10分钟的毫秒数
        (elog || []).forEach(function (item) {
            var t10 = (parseInt(item.time / detaT) + 1) * detaT; //由于pv是后收集加到下一个10分，时间轴后移
            if (!all[t10]) {
                all[t10] = {count: Number(item.count)};
            } else {
                all[t10].count += Number(item.count);
            }
        });
        return all;
    },

    /**
     * 统计pv
     * @param {String} dateStr
     * @param {Array} pvs
     * @returns {{}}
     */
    countPv: function (dateStr, pvs) {
        var all = {};
        (pvs || []).forEach(function (pv) {
            for (var date in pv) {
                var time = Number(string2Date(dateStr + date, 'yyyyMMddhhmm'));
                if (!all[time]) {
                    all[time] = {pv: Number(pv[date]) || 0};
                } else {
                    all[time].pv += Number(pv[date]);
                }
            }
        });
        return all;
    },

    query: function (appid, dateStr, callback) {

    }
};

module.exports = StatisticsServicePV;

<|endoftext|>


<commit_before>/* globals angular */
'use strict';

angular.module('betterfriendsLanding', ['ionic']);

// routes
angular.module('betterfriendsLanding').config(['$stateProvider', '$urlRouterProvider',
  function ($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('respond', {
        url: '/r/:eid/:inviteCode',
        templateUrl: '/landing/respond.client.view.html',
        controller: 'RespondController'
      })
      .state('accepted', {
        url: '/accepted/:eid/:inviteCode',
        templateUrl: '/landing/accepted.client.view.html',
        controller: 'AcceptedController'
      });
  }
]);

angular.module('betterfriendsLanding').controller('RespondController', ['$scope', '$stateParams', '$state', '$http',
  function ($scope, $stateParams, $state, $http) {
    $scope.accept = function() {
      var data = {newStatus:'accepted'};
      $http.post('/event/updateStatus/'+$stateParams.eid+'/'+$stateParams.inviteCode, data).then(function (res) {
        $state.go('accepted', {eid:$stateParams.eid, inviteCode:$stateParams.inviteCode});
      });
    };
    $http.get('/event/get/'+$stateParams.eid+'/'+$stateParams.inviteCode).then(function (res) {
      $scope.event = res.data.event;
      $scope.invitee = res.data.invitee;
    });
  }
]);

angular.module('betterfriendsLanding').controller('AcceptedController', ['$scope', '$stateParams', '$window', '$timeout', '$http',
  function ($scope, $stateParams, $window, $timeout, $http) {
    $scope.invite = function() {
      var clickedAt = new Date();
      $timeout(function () {
        if (new Date() - clickedAt < 2000) {
          $window.location.href = 'http://www.testflightapp.com/install/ba99bd94a202a6c4b4142ee99b83eac7-MTM3NDk0NTQ/'; //itms-apps://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6';
        }
      }, 500);
      var data = {
        eid:$stateParams.eid,
        inviteCode:$stateParams.inviteCode
      };
      var dataString = encodeURIComponent('j:'+JSON.stringify(data));
      $window.location.href = 'betterfriends://cookiedata?data='+dataString;
    };
    $http.get('/event/get/'+$stateParams.eid+'/'+$stateParams.inviteCode).then(function (res) {
      $scope.event = res.data.event;
      $scope.invitee = res.data.invitee;
    });
  }
]);
<commit_msg>fix links on install page<commit_after>/* globals angular */
'use strict';

angular.module('betterfriendsLanding', ['ionic']);

// routes
angular.module('betterfriendsLanding').config(['$stateProvider', '$urlRouterProvider',
  function ($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('respond', {
        url: '/r/:eid/:inviteCode',
        templateUrl: '/landing/respond.client.view.html',
        controller: 'RespondController'
      })
      .state('accepted', {
        url: '/accepted/:eid/:inviteCode',
        templateUrl: '/landing/accepted.client.view.html',
        controller: 'AcceptedController'
      });
  }
]);

angular.module('betterfriendsLanding').controller('RespondController', ['$scope', '$stateParams', '$state', '$http',
  function ($scope, $stateParams, $state, $http) {
    $scope.accept = function() {
      var data = {newStatus:'accepted'};
      $http.post('/event/updateStatus/'+$stateParams.eid+'/'+$stateParams.inviteCode, data).then(function (res) {
        $state.go('accepted', {eid:$stateParams.eid, inviteCode:$stateParams.inviteCode});
      });
    };
    $http.get('/event/get/'+$stateParams.eid+'/'+$stateParams.inviteCode).then(function (res) {
      $scope.event = res.data.event;
      $scope.invitee = res.data.invitee;
    });
  }
]);

angular.module('betterfriendsLanding').controller('AcceptedController', ['$scope', '$stateParams', '$window', '$timeout', '$http',
  function ($scope, $stateParams, $window, $timeout, $http) {
    $scope.invite = function() {
      var clickedAt = new Date();
      $timeout(function () {
        if (new Date() - clickedAt < 2000) {
          $window.location.href = 'http://www.testflightapp.com/install/b0917ddaaf8336dda336598c7613a26e-MTM3NDk5Nzk/';
          //itms-apps://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6';
        }
      }, 500);
      var data = {
        eid:$stateParams.eid,
        inviteCode:$stateParams.inviteCode
      };
      var dataString = encodeURIComponent('j:'+JSON.stringify(data));
      //TODO: off for now to force upgrade.
      //$window.location.href = 'betterfriends://cookiedata?data='+dataString;
    };
    $http.get('/event/get/'+$stateParams.eid+'/'+$stateParams.inviteCode).then(function (res) {
      $scope.event = res.data.event;
      $scope.invitee = res.data.invitee;
    });
  }
]);
<|endoftext|>


<commit_before>import get         from 'lodash.get';
import isEqual     from 'lodash.isequal';
import {Component} from 'react';
import {PropTypes} from 'react';

import BaseForm from '../forms/BaseForm';
import joinName from '../../helpers/joinName';

export default class BaseField extends Component {
    static propTypes = {
        id: PropTypes.string,

        name:     PropTypes.string,
        disabled: PropTypes.bool,

        label:       PropTypes.oneOfType([PropTypes.bool, PropTypes.string, PropTypes.node]),
        placeholder: PropTypes.oneOfType([PropTypes.bool, PropTypes.string])
    };

    static contextTypes      = BaseForm.childContextTypes;
    static childContextTypes = BaseForm.childContextTypes;

    constructor () {
        super(...arguments);

        this.randomId = this.context.uniforms.randomId();

        this.getFieldProps = this.getFieldProps.bind(this);

        this.getChildContextName     = this.getChildContextName.bind(this);
        this.getChildContextError    = this.getChildContextError.bind(this);
        this.getChildContextModel    = this.getChildContextModel.bind(this);
        this.getChildContextState    = this.getChildContextState.bind(this);
        this.getChildContextSchema   = this.getChildContextSchema.bind(this);
        this.getChildContextOnChange = this.getChildContextOnChange.bind(this);
    }

    shouldComponentUpdate (nextProps, nextState, {uniforms: nextContext}) {
        const prevProps   = this.props;
        const prevContext = this.context.uniforms;

        if (!isEqual(prevProps.value, nextProps.value)) {
            return true;
        }

        const prevName = joinName(prevContext.name, prevProps.name);
        const nextName = joinName(nextContext.name, nextProps.name);

        if (prevName !== nextName) {
            return true;
        }

        if (nextName.indexOf('.') !== -1) {
            const prevParentValue = get(prevContext.model, prevName.replace(/(.+)\..+$/, '$1'));
            const nextParentValue = get(nextContext.model, nextName.replace(/(.+)\..+$/, '$1'));

            if (Array.isArray(nextParentValue) && !isEqual(prevParentValue, nextParentValue)) {
                return true;
            }
        }

        const prevValue = get(prevContext.model, prevName);
        const nextValue = get(nextContext.model, nextName);

        if (!isEqual(prevValue, nextValue)) {
            return true;
        }

        return false;
    }

    getChildContext () {
        return {
            uniforms: {
                name:     this.getChildContextName(),
                error:    this.getChildContextError(),
                model:    this.getChildContextModel(),
                state:    this.getChildContextState(),
                schema:   this.getChildContextSchema(),
                onChange: this.getChildContextOnChange(),
                randomId: this.context.uniforms.randomId
            }
        };
    }

    getChildContextName () {
        return joinName(null, this.context.uniforms.name, this.props.name);
    }

    getChildContextError () {
        return this.context.uniforms.error;
    }

    getChildContextModel () {
        return this.context.uniforms.model;
    }

    getChildContextState () {
        const state = this.context.uniforms.state;
        const props = this.props;

        const propagate = name => props[name] === undefined || props[name] === null ? state[name] : !!props[name];

        return {
            ...state,

            label:       propagate('label'),
            disabled:    propagate('disabled'),
            placeholder: propagate('placeholder')
        };
    }

    getChildContextSchema () {
        return this.context.uniforms.schema;
    }

    getChildContextOnChange () {
        return this.context.uniforms.onChange;
    }

    // eslint-disable-next-line complexity
    getFieldProps (name, {explicitInitialValue = false, overrideValue = false, includeParent = false} = {}) {
        const context = this.context.uniforms;
        const props = {
            ...this.getChildContextState(),
            ...this.props
        };

        if (name === undefined) {
            name = joinName(context.name, props.name);
        }

        const field = context.schema.getField(name);
        const fieldType = context.schema.getType(name);
        const schemaProps = context.schema.getProps(name, props);

        const error  = context.schema.getError(name, context.error);
        const fields = context.schema.getSubfields(name);
        const parent = includeParent && name.indexOf('.') !== -1
            ? this.getFieldProps(name.replace(/(.+)\..+$/, '$1'), {includeParent: false})
            : null;

        const id = props.id || this.randomId;

        const errorMessage = context.schema.getErrorMessage(name, context.error);

        const label = props.label
            ? props.label === true
                ? schemaProps.label
                : props.label
            : props.label === null
                ? null
                : '';

        const placeholder = props.placeholder
            ? props.placeholder === true
                ? schemaProps.label
                : props.placeholder
            : '';

        const changed = !!get(context.state.changedMap, name);

        let value = get(context.model, name);
        if (value === undefined && !explicitInitialValue) {
            value = context.schema.getInitialValue(name, this.props);

            // This prevents (un)controlled input change warning.
            // More info: https://fb.me/react-controlled-components.
            if (value === undefined) {
                value = '';
            }
        } else if (explicitInitialValue) {
            props.initialValue = context.schema.getInitialValue(name, this.props);
        }

        const findValue = name => get(context.model, name);
        const findField = name => context.schema.getField(name);
        const findError = name => context.schema.getError(name, context.error);

        const onChange = (value, key = name) => context.onChange(key, value);

        return {
            changed,
            error,
            errorMessage,
            field,
            fields,
            fieldType,
            findError,
            findField,
            findValue,
            id,
            onChange,
            parent,
            value,

            ...props,
            ...schemaProps,
            ...overrideValue ? {value} : {},

            label,
            name,
            placeholder
        };
    }
}
<commit_msg>Improved performance of BaseField (#70).<commit_after>import get         from 'lodash.get';
import isEqual     from 'lodash.isequal';
import {Component} from 'react';
import {PropTypes} from 'react';

import BaseForm from '../forms/BaseForm';
import joinName from '../../helpers/joinName';

export default class BaseField extends Component {
    static propTypes = {
        id: PropTypes.string,

        name:     PropTypes.string,
        disabled: PropTypes.bool,

        label:       PropTypes.oneOfType([PropTypes.bool, PropTypes.string, PropTypes.node]),
        placeholder: PropTypes.oneOfType([PropTypes.bool, PropTypes.string])
    };

    static contextTypes      = BaseForm.childContextTypes;
    static childContextTypes = BaseForm.childContextTypes;

    constructor () {
        super(...arguments);

        this.randomId = this.context.uniforms.randomId();

        this.getFieldProps = this.getFieldProps.bind(this);

        this.getChildContextName     = this.getChildContextName.bind(this);
        this.getChildContextError    = this.getChildContextError.bind(this);
        this.getChildContextModel    = this.getChildContextModel.bind(this);
        this.getChildContextState    = this.getChildContextState.bind(this);
        this.getChildContextSchema   = this.getChildContextSchema.bind(this);
        this.getChildContextOnChange = this.getChildContextOnChange.bind(this);
    }

    shouldComponentUpdate (nextProps, nextState, {uniforms: nextContext}) {
        const prevProps   = this.props;
        const prevContext = this.context.uniforms;

        if (!isEqual(prevProps.value, nextProps.value)) {
            return true;
        }

        const prevName = joinName(prevContext.name, prevProps.name);
        const nextName = joinName(nextContext.name, nextProps.name);

        if (prevName !== nextName) {
            return true;
        }

        if (nextName.indexOf('.') !== -1) {
            const prevParentValue = get(prevContext.model, prevName.replace(/(.+)\..+$/, '$1'));
            const nextParentValue = get(nextContext.model, nextName.replace(/(.+)\..+$/, '$1'));

            if (Array.isArray(nextParentValue) && !isEqual(prevParentValue, nextParentValue)) {
                return true;
            }
        }

        const prevValue = get(prevContext.model, prevName);
        const nextValue = get(nextContext.model, nextName);

        if (!isEqual(prevValue, nextValue)) {
            return true;
        }

        if (prevContext.error !== nextContext.error) {
            const prevError = prevContext.error && prevContext.schema.getError(prevName, prevContext.error);
            const nextError = nextContext.error && nextContext.schema.getError(nextName, nextContext.error);

            if (!isEqual(prevError, nextError)) {
                return true;
            }
        }

        return false;
    }

    getChildContext () {
        return {
            uniforms: {
                name:     this.getChildContextName(),
                error:    this.getChildContextError(),
                model:    this.getChildContextModel(),
                state:    this.getChildContextState(),
                schema:   this.getChildContextSchema(),
                onChange: this.getChildContextOnChange(),
                randomId: this.context.uniforms.randomId
            }
        };
    }

    getChildContextName () {
        return joinName(null, this.context.uniforms.name, this.props.name);
    }

    getChildContextError () {
        return this.context.uniforms.error;
    }

    getChildContextModel () {
        return this.context.uniforms.model;
    }

    getChildContextState () {
        const state = this.context.uniforms.state;
        const props = this.props;

        const propagate = name => props[name] === undefined || props[name] === null ? state[name] : !!props[name];

        return {
            ...state,

            label:       propagate('label'),
            disabled:    propagate('disabled'),
            placeholder: propagate('placeholder')
        };
    }

    getChildContextSchema () {
        return this.context.uniforms.schema;
    }

    getChildContextOnChange () {
        return this.context.uniforms.onChange;
    }

    // eslint-disable-next-line complexity
    getFieldProps (name, {explicitInitialValue = false, overrideValue = false, includeParent = false} = {}) {
        const context = this.context.uniforms;
        const props = {
            ...this.getChildContextState(),
            ...this.props
        };

        if (name === undefined) {
            name = joinName(context.name, props.name);
        }

        const field = context.schema.getField(name);
        const fieldType = context.schema.getType(name);
        const schemaProps = context.schema.getProps(name, props);

        const error  = context.schema.getError(name, context.error);
        const fields = context.schema.getSubfields(name);
        const parent = includeParent && name.indexOf('.') !== -1
            ? this.getFieldProps(name.replace(/(.+)\..+$/, '$1'), {includeParent: false})
            : null;

        const id = props.id || this.randomId;

        const errorMessage = context.schema.getErrorMessage(name, context.error);

        const label = props.label
            ? props.label === true
                ? schemaProps.label
                : props.label
            : props.label === null
                ? null
                : '';

        const placeholder = props.placeholder
            ? props.placeholder === true
                ? schemaProps.label
                : props.placeholder
            : '';

        const changed = !!get(context.state.changedMap, name);

        let value = get(context.model, name);
        if (value === undefined && !explicitInitialValue) {
            value = context.schema.getInitialValue(name, this.props);

            // This prevents (un)controlled input change warning.
            // More info: https://fb.me/react-controlled-components.
            if (value === undefined) {
                value = '';
            }
        } else if (explicitInitialValue) {
            props.initialValue = context.schema.getInitialValue(name, this.props);
        }

        const findValue = name => get(context.model, name);
        const findField = name => context.schema.getField(name);
        const findError = name => context.schema.getError(name, context.error);

        const onChange = (value, key = name) => context.onChange(key, value);

        return {
            changed,
            error,
            errorMessage,
            field,
            fields,
            fieldType,
            findError,
            findField,
            findValue,
            id,
            onChange,
            parent,
            value,

            ...props,
            ...schemaProps,
            ...overrideValue ? {value} : {},

            label,
            name,
            placeholder
        };
    }
}
<|endoftext|>


<commit_before>'use strict';<commit_msg>began routing<commit_after>'use strict';

page('/', moonController.loadAll, moonController.index);
page('/about', aboutController.index);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { withTheme } from 'emotion-theming';

import { setValue, clearValues } from '@appbaseio/reactivecore/lib/actions';
import types from '@appbaseio/reactivecore/lib/utils/types';
import { getClassName } from '@appbaseio/reactivecore/lib/utils/helper';
import Button, { filters } from '../../styles/Button';
import Container from '../../styles/Container';
import Title from '../../styles/Title';
import { connect } from '../../utils';

class SelectedFilters extends Component {
	componentDidUpdate = () => {
		if (this.props.onChange) {
			this.props.onChange(this.props.selectedValues);
		}
	};

	remove = (component, value = null) => {
		const { onClear } = this.props;
		this.props.setValue(component, null);
		if (onClear) {
			onClear(component, value);
		}
	};

	clearValues = () => {
		const { onClear } = this.props;
		this.props.clearValues();
		if (onClear) {
			onClear(null);
		}
	};

	renderValue = (value, isArray) => {
		if (isArray && value.length) {
			const arrayToRender = value.map(item => this.renderValue(item));
			return arrayToRender.join(', ');
		} else if (value && typeof value === 'object') {
			// TODO: support for NestedList
			let label
				= (typeof value.label === 'string' ? value.label : value.value)
				|| value.key
				|| value.distance
				|| null;
			if (value.location) {
				label = `${value.location} - ${label}`;
			}
			return label;
		}
		return value;
	};

	renderFilters = () => {
		const { selectedValues } = this.props;
		return Object.keys(selectedValues)
			.filter(id => this.props.components.includes(id) && selectedValues[id].showFilter)
			.map((component, index) => {
				const { label, value, category } = selectedValues[component];
				const isArray = Array.isArray(value);

				if (label && ((isArray && value.length) || (!isArray && value))) {
					const valueToRender = category
						? this.renderValue(`${value} in ${category} category`, isArray)
						: this.renderValue(value, isArray);
					return (
						<Button
							className={getClassName(this.props.innerClass, 'button') || null}
							key={`${component}-${index + 1}`}
							onClick={() => this.remove(component, value)}
						>

								{selectedValues[component].label}: {valueToRender}

							✕
						</Button>
					);
				}
				return null;
			})
			.filter(Boolean);
	};

	render() {
		if (this.props.render) {
			return this.props.render(this.props);
		}

		const { theme } = this.props;
		const filtersToRender = this.renderFilters();
		const hasValues = !!filtersToRender.length;

		return (
			<Container
				style={this.props.style}
				className={`${filters(theme)}
				${this.props.className || ''}`}
			>
				{this.props.title && hasValues && (
					<Title className={getClassName(this.props.innerClass, 'title') || null}>
						{this.props.title}
					</Title>
				)}
				{filtersToRender}
				{this.props.showClearAll && hasValues ? (
					<Button
						className={getClassName(this.props.innerClass, 'button') || null}
						onClick={this.clearValues}
					>
						{this.props.clearAllLabel}
					</Button>
				) : null}
			</Container>
		);
	}
}

SelectedFilters.propTypes = {
	clearValues: types.func,
	setValue: types.func,
	components: types.components,
	selectedValues: types.selectedValues,
	className: types.string,
	clearAllLabel: types.title,
	innerClass: types.style,
	showClearAll: types.bool,
	style: types.style,
	theme: types.style,
	onClear: types.func,
	render: types.func,
	title: types.title,
	onChange: types.func,
};

SelectedFilters.defaultProps = {
	className: null,
	clearAllLabel: 'Clear All',
	showClearAll: true,
	style: {},
};

const mapStateToProps = state => ({
	components: state.components,
	selectedValues: state.selectedValues,
});

const mapDispatchtoProps = dispatch => ({
	clearValues: () => dispatch(clearValues()),
	setValue: (component, value) => dispatch(setValue(component, value)),
});

const ConnectedComponent = connect(
	mapStateToProps,
	mapDispatchtoProps,
)(withTheme(props => <SelectedFilters ref={props.myForwardedRef} {...props} />));

// eslint-disable-next-line
export default React.forwardRef((props, ref) => (
	<ConnectedComponent {...props} myForwardedRef={ref} />
));
<commit_msg>fix(web): make selectedfilters accessible (#1132)<commit_after>import React, { Component } from 'react';
import { withTheme } from 'emotion-theming';

import { setValue, clearValues } from '@appbaseio/reactivecore/lib/actions';
import types from '@appbaseio/reactivecore/lib/utils/types';
import { getClassName, handleA11yAction } from '@appbaseio/reactivecore/lib/utils/helper';
import Button, { filters } from '../../styles/Button';
import Container from '../../styles/Container';
import Title from '../../styles/Title';
import { connect } from '../../utils';

class SelectedFilters extends Component {
	componentDidUpdate = () => {
		if (this.props.onChange) {
			this.props.onChange(this.props.selectedValues);
		}
	};

	remove = (component, value = null) => {
		const { onClear } = this.props;
		this.props.setValue(component, null);
		if (onClear) {
			onClear(component, value);
		}
	};

	clearValues = () => {
		const { onClear } = this.props;
		this.props.clearValues();
		if (onClear) {
			onClear(null);
		}
	};

	renderValue = (value, isArray) => {
		if (isArray && value.length) {
			const arrayToRender = value.map(item => this.renderValue(item));
			return arrayToRender.join(', ');
		} else if (value && typeof value === 'object') {
			// TODO: support for NestedList
			let label
				= (typeof value.label === 'string' ? value.label : value.value)
				|| value.key
				|| value.distance
				|| null;
			if (value.location) {
				label = `${value.location} - ${label}`;
			}
			return label;
		}
		return value;
	};

	renderFilters = () => {
		const { selectedValues } = this.props;
		return Object.keys(selectedValues)
			.filter(id => this.props.components.includes(id) && selectedValues[id].showFilter)
			.map((component, index) => {
				const { label, value, category } = selectedValues[component];
				const isArray = Array.isArray(value);

				if (label && ((isArray && value.length) || (!isArray && value))) {
					const valueToRender = category
						? this.renderValue(`${value} in ${category} category`, isArray)
						: this.renderValue(value, isArray);
					return (
						<Button
							className={getClassName(this.props.innerClass, 'button') || null}
							key={`${component}-${index + 1}`}
							tabIndex="0"
							onKeyPress={event => handleA11yAction(event, () => this.remove(component, value))}
							onClick={() => this.remove(component, value)}
						>

								{selectedValues[component].label}: {valueToRender}

							✕
						</Button>
					);
				}
				return null;
			})
			.filter(Boolean);
	};

	render() {
		if (this.props.render) {
			return this.props.render(this.props);
		}

		const { theme } = this.props;
		const filtersToRender = this.renderFilters();
		const hasValues = !!filtersToRender.length;

		return (
			<Container
				style={this.props.style}
				className={`${filters(theme)}
				${this.props.className || ''}`}
			>
				{this.props.title && hasValues && (
					<Title className={getClassName(this.props.innerClass, 'title') || null}>
						{this.props.title}
					</Title>
				)}
				{filtersToRender}
				{this.props.showClearAll && hasValues ? (
					<Button
						className={getClassName(this.props.innerClass, 'button') || null}
						onClick={this.clearValues}
						tabIndex="0"
						onKeyPress={event => handleA11yAction(event, this.clearValues)}
					>
						{this.props.clearAllLabel}
					</Button>
				) : null}
			</Container>
		);
	}
}

SelectedFilters.propTypes = {
	clearValues: types.func,
	setValue: types.func,
	components: types.components,
	selectedValues: types.selectedValues,
	className: types.string,
	clearAllLabel: types.title,
	innerClass: types.style,
	showClearAll: types.bool,
	style: types.style,
	theme: types.style,
	onClear: types.func,
	render: types.func,
	title: types.title,
	onChange: types.func,
};

SelectedFilters.defaultProps = {
	className: null,
	clearAllLabel: 'Clear All',
	showClearAll: true,
	style: {},
};

const mapStateToProps = state => ({
	components: state.components,
	selectedValues: state.selectedValues,
});

const mapDispatchtoProps = dispatch => ({
	clearValues: () => dispatch(clearValues()),
	setValue: (component, value) => dispatch(setValue(component, value)),
});

const ConnectedComponent = connect(
	mapStateToProps,
	mapDispatchtoProps,
)(withTheme(props => <SelectedFilters ref={props.myForwardedRef} {...props} />));

// eslint-disable-next-line
export default React.forwardRef((props, ref) => (
	<ConnectedComponent {...props} myForwardedRef={ref} />
));
<|endoftext|>


<commit_before>'use strict';

$('#seedForm').submit(function(event) {
  event.preventDefault();
  var strainSearch = $('#strainSearch').val();
  console.log(strainSearch);
  // return strainSearch
  return strainSearch();
});
  let searchRequest = function(data) {
    console.log(data)
    var obj = data;
    var objToArr = Object.keys(obj).map(function(key) {return obj[key]});
    console.log(objToArr);
    var dataArr = objToArr[0];
    console.log(dataArr);
    let template = Handlebars.compile($('#strainResults').html())
    $('#strains').html(template({strain: dataArr}))
};
    let errorCallback = function(err) {
      console.error(err)
    }
    $.getJSON('https://www.cannabisreports.com/api/v1.0/strains/search/' + strainSearch)
    .then(searchRequest(strainSearch), errorCallback);
<commit_msg>search query rendered to DOM<commit_after>'use strict';

$('#seedForm').submit(function(event) {
  event.preventDefault();
  var strainSearch = $('#strainSearch').val();
  console.log(strainSearch);
  // return strainSearch
  $.getJSON('https://www.cannabisreports.com/api/v1.0/strains/search/' + strainSearch)
  .then(searchRequest, errorCallback);
});
  let searchRequest = function(data) {
    console.log(data)
    var obj = data;
    var objToArr = Object.keys(obj).map(function(key) {return obj[key]});
    console.log(objToArr);
    var dataArr = objToArr[0];
    console.log(dataArr);
    let template = Handlebars.compile($('#strainResults').html())
    $('#strains').html(template({strain: dataArr}))
};
    // let errorCallback = function(err) {
    //   console.error(err)
    // }
<|endoftext|>