<commit_before>// diff
// getAccessType(settings)
// Group editing
//      saveInformationForm
//      saveSettingsForm
//      deleteGroup

describe("Test group details sidebar functions", function() {

    it("Test diff function for comparing objects", function(done) {

        $.getScript('/src/main/webapp/scripts/group-details-script.js', function() {
            var original = {
                "a": "1",
                "b": "2",
                "c": "3",
            };
            var diffValues = {
                "a": "1",
                "b": "4",
                "c": "3",
            };
            var fewerKeys = {
                "a": "1",
                "b": "2",
            };
            var empty = {};

            expect(diff(diffValues, original)).toEqual({"b": "4"});
            expect(diff(original, diffValues)).toEqual({"b": "2"});
            expect(diff(fewerKeys, original)).toEqual({"c": undefined});
            expect(diff(original, fewerKeys)).toEqual({});
            expect(diff(diffValues, fewerKeys)).toEqual({"b": "4"});
            expect(diff(fewerKeys, diffValues)).toEqual({"b": "2", "c": undefined});
            expect(diff(original, empty)).toEqual({});
            expect(diff(empty, original)).toEqual({"a": undefined, "b": undefined, "c": undefined});

            done();
        });
    });

    it("Test get access type based on settings parameter", function(done) {

        $.when(
            $.getScript( '/src/main/webapp/scripts/group-details-script.js' ),
            $.getScript( '/src/main/webapp/scripts/group-constants.js' ),
            $.Deferred(function( deferred ){
                $( deferred.resolve );
            })
        ).done(function(){
            var publicSettings = {
                "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
                "whoCanAddReferences": "NONE",
                "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
                "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
                "whoCanAssignTopics": "NONE",
                "whoCanAssistContent": "NONE",
                "whoCanBanUsers": "OWNERS_AND_MANAGERS",
                "whoCanContactOwner": "ANYONE_CAN_CONTACT",
                "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
                "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
                "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
                "whoCanEnterFreeFormTags": "NONE",
                "whoCanHideAbuse": "NONE",
                "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
                "whoCanJoin": "ALL_IN_DOMAIN_CAN_JOIN",
                "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
                "whoCanLockTopics": "OWNERS_AND_MANAGERS",
                "whoCanMakeTopicsSticky": "NONE",
                "whoCanMarkDuplicate": "NONE",
                "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
                "whoCanMarkNoResponseNeeded": "NONE",
                "whoCanModerateContent": "OWNERS_AND_MANAGERS",
                "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyTagsAndCategories": "NONE",
                "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
                "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
                "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
                "whoCanPostMessage": "ALL_IN_DOMAIN_CAN_POST",
                "whoCanTakeTopics": "NONE",
                "whoCanUnassignTopic": "NONE",
                "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanViewGroup": "ALL_IN_DOMAIN_CAN_VIEW",
                "whoCanViewMembership": "ALL_IN_DOMAIN_CAN_VIEW"
            };
            var teamSettings = {
                "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
                "whoCanAddReferences": "NONE",
                "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
                "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
                "whoCanAssignTopics": "NONE",
                "whoCanAssistContent": "NONE",
                "whoCanBanUsers": "OWNERS_AND_MANAGERS",
                "whoCanContactOwner": "ANYONE_CAN_CONTACT",
                "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
                "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
                "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
                "whoCanEnterFreeFormTags": "NONE",
                "whoCanHideAbuse": "NONE",
                "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
                "whoCanJoin": "CAN_REQUEST_TO_JOIN",
                "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
                "whoCanLockTopics": "OWNERS_AND_MANAGERS",
                "whoCanMakeTopicsSticky": "NONE",
                "whoCanMarkDuplicate": "NONE",
                "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
                "whoCanMarkNoResponseNeeded": "NONE",
                "whoCanModerateContent": "OWNERS_AND_MANAGERS",
                "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyTagsAndCategories": "NONE",
                "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
                "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
                "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
                "whoCanPostMessage": "ALL_IN_DOMAIN_CAN_POST",
                "whoCanTakeTopics": "NONE",
                "whoCanUnassignTopic": "NONE",
                "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanViewGroup": "ALL_IN_DOMAIN_CAN_VIEW",
                "whoCanViewMembership": "ALL_IN_DOMAIN_CAN_VIEW",
            };
            var announcementSettings = {
                "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
                "whoCanAddReferences": "NONE",
                "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
                "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
                "whoCanAssignTopics": "NONE",
                "whoCanAssistContent": "NONE",
                "whoCanBanUsers": "OWNERS_AND_MANAGERS",
                "whoCanContactOwner": "ANYONE_CAN_CONTACT",
                "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
                "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
                "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
                "whoCanEnterFreeFormTags": "NONE",
                "whoCanHideAbuse": "NONE",
                "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
                "whoCanJoin": "ALL_IN_DOMAIN_CAN_JOIN",
                "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
                "whoCanLockTopics": "OWNERS_AND_MANAGERS",
                "whoCanMakeTopicsSticky": "NONE",
                "whoCanMarkDuplicate": "NONE",
                "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
                "whoCanMarkNoResponseNeeded": "NONE",
                "whoCanModerateContent": "OWNERS_AND_MANAGERS",
                "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyTagsAndCategories": "NONE",
                "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
                "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
                "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
                "whoCanPostMessage": "ALL_MANAGERS_CAN_POST",
                "whoCanTakeTopics": "NONE",
                "whoCanUnassignTopic": "NONE",
                "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanViewGroup": "ALL_IN_DOMAIN_CAN_VIEW",
                "whoCanViewMembership": "ALL_MANAGERS_CAN_VIEW"
            };
            var restrictedSettings = {
                "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
                "whoCanAddReferences": "NONE",
                "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
                "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
                "whoCanAssignTopics": "NONE",
                "whoCanAssistContent": "NONE",
                "whoCanBanUsers": "OWNERS_AND_MANAGERS",
                "whoCanContactOwner": "ANYONE_CAN_CONTACT",
                "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
                "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
                "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
                "whoCanEnterFreeFormTags": "NONE",
                "whoCanHideAbuse": "NONE",
                "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
                "whoCanJoin": "CAN_REQUEST_TO_JOIN",
                "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
                "whoCanLockTopics": "OWNERS_AND_MANAGERS",
                "whoCanMakeTopicsSticky": "NONE",
                "whoCanMarkDuplicate": "NONE",
                "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
                "whoCanMarkNoResponseNeeded": "NONE",
                "whoCanModerateContent": "OWNERS_AND_MANAGERS",
                "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyTagsAndCategories": "NONE",
                "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
                "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
                "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
                "whoCanPostMessage": "ALL_MEMBERS_CAN_POST",
                "whoCanTakeTopics": "NONE",
                "whoCanUnassignTopic": "NONE",
                "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanViewGroup": "ALL_MEMBERS_CAN_VIEW",
                "whoCanViewMembership": "ALL_MEMBERS_CAN_VIEW",
            };
            var customSettings1 = {
                "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
                "whoCanAddReferences": "NONE",
                "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
                "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
                "whoCanAssignTopics": "NONE",
                "whoCanAssistContent": "NONE",
                "whoCanBanUsers": "OWNERS_AND_MANAGERS",
                "whoCanContactOwner": "ANYONE_CAN_CONTACT",
                "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
                "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
                "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
                "whoCanEnterFreeFormTags": "NONE",
                "whoCanHideAbuse": "NONE",
                "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
                "whoCanJoin": "CAN_REQUEST_TO_JOIN",
                "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
                "whoCanLockTopics": "OWNERS_AND_MANAGERS",
                "whoCanMakeTopicsSticky": "NONE",
                "whoCanMarkDuplicate": "NONE",
                "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
                "whoCanMarkNoResponseNeeded": "NONE",
                "whoCanModerateContent": "OWNERS_AND_MANAGERS",
                "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyMembers": "NONE",
                "whoCanModifyTagsAndCategories": "NONE",
                "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
                "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
                "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
                "whoCanPostMessage": "NONE_CAN_POST",
                "whoCanTakeTopics": "NONE",
                "whoCanUnassignTopic": "NONE",
                "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanViewGroup": "ALL_MANAGERS_CAN_VIEW",
                "whoCanViewMembership": "ALL_MEMBERS_CAN_VIEW",
            };
            var customSettings2 = {
                "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
                "whoCanAddReferences": "NONE",
                "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
                "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
                "whoCanAssignTopics": "NONE",
                "whoCanAssistContent": "NONE",
                "whoCanBanUsers": "OWNERS_AND_MANAGERS",
                "whoCanContactOwner": "ANYONE_CAN_CONTACT",
                "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
                "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
                "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
                "whoCanEnterFreeFormTags": "NONE",
                "whoCanHideAbuse": "NONE",
                "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
                "whoCanJoin": "CAN_REQUEST_TO_JOIN",
                "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
                "whoCanLockTopics": "OWNERS_AND_MANAGERS",
                "whoCanMakeTopicsSticky": "NONE",
                "whoCanMarkDuplicate": "NONE",
                "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
                "whoCanMarkNoResponseNeeded": "NONE",
                "whoCanModerateContent": "OWNERS_AND_MANAGERS",
                "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
                "whoCanModifyMembers": "NONE",
                "whoCanModifyTagsAndCategories": "NONE",
                "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
                "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
                "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
                "whoCanPostMessage": "OWNERS_AND_MANAGERS",
                "whoCanTakeTopics": "NONE",
                "whoCanUnassignTopic": "NONE",
                "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
                "whoCanViewGroup": "ALL_MEMBERS_CAN_VIEW",
                "whoCanViewMembership": "ALL_MEMBERS_CAN_VIEW",
            }

            expect(getAccessType(publicSettings)).toEqual("Public");
            expect(getAccessType(teamSettings)).toEqual("Team");
            expect(getAccessType(announcementSettings)).toEqual("Announcement Only");
            expect(getAccessType(restrictedSettings)).toEqual("Restricted");
            expect(getAccessType(customSettings1)).toEqual("Custom");
            expect(getAccessType(customSettings2)).toEqual("Custom");

            done();
        });
    });
});
<commit_msg>Move settings constants<commit_after>var customSettings1 = {
    "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
    "whoCanAddReferences": "NONE",
    "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
    "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
    "whoCanAssignTopics": "NONE",
    "whoCanAssistContent": "NONE",
    "whoCanBanUsers": "OWNERS_AND_MANAGERS",
    "whoCanContactOwner": "ANYONE_CAN_CONTACT",
    "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
    "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
    "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
    "whoCanEnterFreeFormTags": "NONE",
    "whoCanHideAbuse": "NONE",
    "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
    "whoCanJoin": "CAN_REQUEST_TO_JOIN",
    "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
    "whoCanLockTopics": "OWNERS_AND_MANAGERS",
    "whoCanMakeTopicsSticky": "NONE",
    "whoCanMarkDuplicate": "NONE",
    "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
    "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
    "whoCanMarkNoResponseNeeded": "NONE",
    "whoCanModerateContent": "OWNERS_AND_MANAGERS",
    "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
    "whoCanModifyMembers": "NONE",
    "whoCanModifyTagsAndCategories": "NONE",
    "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
    "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
    "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
    "whoCanPostMessage": "NONE_CAN_POST",
    "whoCanTakeTopics": "NONE",
    "whoCanUnassignTopic": "NONE",
    "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
    "whoCanViewGroup": "ALL_MANAGERS_CAN_VIEW",
    "whoCanViewMembership": "ALL_MEMBERS_CAN_VIEW",
};
var customSettings2 = {
    "whoCanAdd": "ALL_MANAGERS_CAN_ADD",
    "whoCanAddReferences": "NONE",
    "whoCanApproveMembers": "ALL_MANAGERS_CAN_APPROVE",
    "whoCanApproveMessages": "OWNERS_AND_MANAGERS",
    "whoCanAssignTopics": "NONE",
    "whoCanAssistContent": "NONE",
    "whoCanBanUsers": "OWNERS_AND_MANAGERS",
    "whoCanContactOwner": "ANYONE_CAN_CONTACT",
    "whoCanDeleteAnyPost": "OWNERS_AND_MANAGERS",
    "whoCanDeleteTopics": "OWNERS_AND_MANAGERS",
    "whoCanDiscoverGroup": "ALL_IN_DOMAIN_CAN_DISCOVER",
    "whoCanEnterFreeFormTags": "NONE",
    "whoCanHideAbuse": "NONE",
    "whoCanInvite": "ALL_MANAGERS_CAN_INVITE",
    "whoCanJoin": "CAN_REQUEST_TO_JOIN",
    "whoCanLeaveGroup": "ALL_MEMBERS_CAN_LEAVE",
    "whoCanLockTopics": "OWNERS_AND_MANAGERS",
    "whoCanMakeTopicsSticky": "NONE",
    "whoCanMarkDuplicate": "NONE",
    "whoCanMarkFavoriteReplyOnAnyTopic": "NONE",
    "whoCanMarkFavoriteReplyOnOwnTopic": "NONE",
    "whoCanMarkNoResponseNeeded": "NONE",
    "whoCanModerateContent": "OWNERS_AND_MANAGERS",
    "whoCanModerateMembers": "OWNERS_AND_MANAGERS",
    "whoCanModifyMembers": "NONE",
    "whoCanModifyTagsAndCategories": "NONE",
    "whoCanMoveTopicsIn": "OWNERS_AND_MANAGERS",
    "whoCanMoveTopicsOut": "OWNERS_AND_MANAGERS",
    "whoCanPostAnnouncements": "OWNERS_AND_MANAGERS",
    "whoCanPostMessage": "OWNERS_AND_MANAGERS",
    "whoCanTakeTopics": "NONE",
    "whoCanUnassignTopic": "NONE",
    "whoCanUnmarkFavoriteReplyOnAnyTopic": "NONE",
    "whoCanViewGroup": "ALL_MEMBERS_CAN_VIEW",
    "whoCanViewMembership": "ALL_MEMBERS_CAN_VIEW",
}

describe("Test group details sidebar functions", function() {

    it("Test diff function for comparing objects", function(done) {

        $.getScript('/src/main/webapp/scripts/group-details-script.js', function() {
            var original = {
                "a": "1",
                "b": "2",
                "c": "3",
            };
            var diffValues = {
                "a": "1",
                "b": "4",
                "c": "3",
            };
            var fewerKeys = {
                "a": "1",
                "b": "2",
            };
            var empty = {};

            expect(diff(diffValues, original)).toEqual({"b": "4"});
            expect(diff(original, diffValues)).toEqual({"b": "2"});
            expect(diff(fewerKeys, original)).toEqual({"c": undefined});
            expect(diff(original, fewerKeys)).toEqual({});
            expect(diff(diffValues, fewerKeys)).toEqual({"b": "4"});
            expect(diff(fewerKeys, diffValues)).toEqual({"b": "2", "c": undefined});
            expect(diff(original, empty)).toEqual({});
            expect(diff(empty, original)).toEqual({"a": undefined, "b": undefined, "c": undefined});

            done();
        });
    });

    it("Test get access type based on settings parameter", function(done) {

        $.when(
            $.getScript( '/src/main/webapp/scripts/group-details-script.js' ),
            $.getScript( '/src/main/webapp/scripts/group-constants.js' ),
            $.Deferred(function( deferred ){
                $( deferred.resolve );
            })
        ).done(function(){
            expect(getAccessType(publicSettings)).toEqual("Public");
            expect(getAccessType(teamSettings)).toEqual("Team");
            expect(getAccessType(announcementOnlySettings)).toEqual("Announcement Only");
            expect(getAccessType(restrictedSettings)).toEqual("Restricted");
            expect(getAccessType(customSettings1)).toEqual("Custom");
            expect(getAccessType(customSettings2)).toEqual("Custom");

            done();
        });
    });
});
<|endoftext|>


<commit_before>moduleAid.VERSION = '1.1.3';

// move the status bar onto our container
this.prepareStatusBar = function(aWindow) {
	if(aWindow.closed || aWindow.willClose) { return; }

	var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName+'__statusBar'] || aWindow[objName]._statusBar.node;
	delete aWindow[objName+'__statusBar'];
	if(!sBar) {
		sBar = aWindow.document.getElementById('navigator-toolbox').palette.getElementsByAttribute('id', 'status-bar')[0];
	}

	if(!aWindow[objName]._statusBar) {
		aWindow[objName]._statusBar = {
			node: sBar,
			originalParent: null,
			originalRemovable: null
		};
	}

	moveStatusBar(aWindow);
};

// move the status bar onto our container
this.moveStatusBar = function(aWindow) {
	if(aWindow.closed || aWindow.willClose) { return; }

	if(!CustomizableUI.getPlacementOfWidget(objName+'-status-bar-container')) {
		moveStatusBarBack(aWindow);
		return;
	}

	var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
	var sStack = aWindow.document.getElementById(objName+'-status-bar-stack');
	if(!sBar || sBar.parentNode == sStack) { return; }

	aWindow[objName]._statusBar.originalParent = sBar.parentNode;
	aWindow[objName]._statusBar.originalRemovable = sBar.getAttribute('removable');

	setAttribute(sBar, 'removable', 'true');
	if(CustomizableUI.getWidget('status-bar').areaType) {
		// in case we haven't yet enabled the add-on in other windows, we have to keep a reference to the status bar node,
		// otherwise we'll lose it when we continue. This will be deleted once the add-on is enabled there.
		windowMediator.callOnAll(function(bWindow) {
			if(!bWindow[objName]) {
				bWindow[objName+'__statusBar'] = bWindow.document.getElementById('status-bar');
			}
		}, 'navigator:browser');

		CustomizableUI.removeWidgetFromArea('status-bar');

		// because when we do the above command, the node is physically removed from all windows, we have to put it back
		windowMediator.callOnAll(function(cWindow) {
			if(!cWindow[objName]) { return; }
			moveStatusBarNode(cWindow);
		}, 'navigator:browser');
	} else {
		// this should happen when enabling the add-on on a second window, that was already opened when we called removeWidgetFromArea above
		moveStatusBarNode(aWindow);
	}
};

this.moveAllStatusBars = function() {
	windowMediator.callOnAll(function(cWindow) {
		if(!cWindow[objName]) { return; }
		moveStatusBar(cWindow);
	}, 'navigator:browser');
};

this.moveStatusBarNode = function(aWindow) {
	var sStack = aWindow.document.getElementById(objName+'-status-bar-stack');
	if(!aWindow[objName] || !aWindow[objName]._statusBar || aWindow[objName]._statusBar.node.parentNode == sStack) { return; }

	sStack.insertBefore(aWindow[objName]._statusBar.node, sStack.firstChild);
};

this.moveStatusBarBack = function(aWindow) {
	if(aWindow[objName] && aWindow[objName]._statusBar.originalParent) {
		var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
		if(aWindow[objName]._statusBar.originalParent != sBar.parentNode) { aWindow[objName]._statusBar.originalParent.appendChild(sBar); }
		if(aWindow[objName]._statusBar.originalRemovable) { setAttribute(sBar, 'removable', aWindow[objName]._statusBar.originalRemovable); }
		aWindow[objName]._statusBar.originalParent = null;
		aWindow[objName]._statusBar.originalRemovable = null;
	}
};

// see https://bugzilla.mozilla.org/show_bug.cgi?id=989338
this.preventLosingCustomizeData = function() {
	windowMediator.callOnAll(function(aWindow) {
		moveStatusBarBack(aWindow);
	}, 'navigator:browser');
	try { CustomizableUI.addWidgetToArea('status-bar', 'addon-bar'); } catch(ex) {}
};

// don't forget that add-ons that use the status-bar seem to assume it is always in the DOM tree!
this.trackStatusBar = {
	handler: function(aWidgetId, aArea) {
		if(aWidgetId == objName+'-status-bar-container') {
			if(aArea && aArea == CustomizableUI.AREA_PANEL) {
				CustomizableUI.removeWidgetFromArea(aWidgetId);
				return;
			}
			moveAllStatusBars();
		}
	},

	waitForIt: function(aWindow, aArea) {
		if(!aWindow.document.getElementById(aArea)) {
			aSync(function() {
				if(typeof(trackStatusBar) == 'undefined') { return; }
				try { trackStatusBar.waitForIt(aWindow, aArea); } catch(ex) { Cu.reportError(ex); }
			});
			return;
		}
		moveStatusBar(aWindow);
	},

	onWidgetAdded: function(aWidgetId, aArea) { this.handler(aWidgetId, aArea); },
	onWidgetRemoved: function(aWidgetId) { this.handler(aWidgetId); },

	onAreaNodeRegistered: function(aArea, aContainer) {
		this.waitForIt(aContainer.ownerDocument.defaultView, aArea);
	},

	onAreaNodeUnregistered: function(aArea, aContainer, aReason) {
		if(aReason == CustomizableUI.REASON_AREA_UNREGISTERED) {
			moveStatusBar(aContainer.ownerDocument.defaultView);
		}
	}
};

moduleAid.LOADMODULE = function() {
	alwaysRunOnShutdown.push(preventLosingCustomizeData);

	CustomizableUI.addListener(trackStatusBar);

	overlayAid.overlayURI('chrome://browser/content/browser.xul', 'statusBar', null,
		function(aWindow) {
			prepareObject(aWindow);
			prepareStatusBar(aWindow);
		},
		function(aWindow) {
			moveStatusBarBack(aWindow);
			removeObject(aWindow);
		}
	);

	overlayAid.overlayURI('chrome://'+objPathString+'/content/statusBar.xul', objName, null,
		function(aWindow) {
			aWindow[objName].moduleAid.load(objName, true);
		},
		function(aWindow) {
			aWindow[objName].moduleAid.unload(objName);
		}
	);
};

moduleAid.UNLOADMODULE = function() {
	overlayAid.removeOverlayURI('chrome://'+objPathString+'/content/statusBar.xul', objName);
	overlayAid.removeOverlayURI('chrome://browser/content/browser.xul', 'statusBar');

	CustomizableUI.removeListener(trackStatusBar);

	preventLosingCustomizeData();
};
<commit_msg>get rid of statusbar message in console<commit_after>moduleAid.VERSION = '1.1.4';

// move the status bar onto our container
this.prepareStatusBar = function(aWindow) {
	if(aWindow.closed || aWindow.willClose) { return; }

	var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName+'__statusBar'] || aWindow[objName]._statusBar.node;
	delete aWindow[objName+'__statusBar'];
	if(!sBar) {
		sBar = aWindow.document.getElementById('navigator-toolbox').palette.getElementsByAttribute('id', 'status-bar')[0];
	}

	if(!aWindow[objName]._statusBar) {
		aWindow[objName]._statusBar = {
			node: sBar,
			originalParent: null,
			originalRemovable: null
		};
	}

	moveStatusBar(aWindow);
};

// move the status bar onto our container
this.moveStatusBar = function(aWindow) {
	if(aWindow.closed || aWindow.willClose) { return; }

	if(!CustomizableUI.getPlacementOfWidget(objName+'-status-bar-container')) {
		moveStatusBarBack(aWindow);
		return;
	}

	var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
	var sStack = aWindow.document.getElementById(objName+'-status-bar-stack');
	if(!sBar || sBar.parentNode == sStack) { return; }

	aWindow[objName]._statusBar.originalParent = sBar.parentNode;
	aWindow[objName]._statusBar.originalRemovable = sBar.getAttribute('removable');

	setAttribute(sBar, 'removable', 'true');
	if(CustomizableUI.getWidget('status-bar').areaType) {
		// in case we haven't yet enabled the add-on in other windows, we have to keep a reference to the status bar node,
		// otherwise we'll lose it when we continue. This will be deleted once the add-on is enabled there.
		windowMediator.callOnAll(function(bWindow) {
			if(!bWindow[objName]) {
				bWindow[objName+'__statusBar'] = bWindow.document.getElementById('status-bar');
			}
		}, 'navigator:browser');

		CustomizableUI.removeWidgetFromArea('status-bar');

		// because when we do the above command, the node is physically removed from all windows, we have to put it back
		windowMediator.callOnAll(function(cWindow) {
			if(!cWindow[objName]) { return; }
			moveStatusBarNode(cWindow);
		}, 'navigator:browser');
	} else {
		// this should happen when enabling the add-on on a second window, that was already opened when we called removeWidgetFromArea above
		moveStatusBarNode(aWindow);
	}
};

this.moveAllStatusBars = function() {
	windowMediator.callOnAll(function(cWindow) {
		if(!cWindow[objName]) { return; }
		moveStatusBar(cWindow);
	}, 'navigator:browser');
};

this.moveStatusBarNode = function(aWindow) {
	var sStack = aWindow.document.getElementById(objName+'-status-bar-stack');

	// I have no idea how this is possible, but it happens when disabling and re-enabling the add-on...
	if(!sStack) { return; }

	if(!aWindow[objName] || !aWindow[objName]._statusBar || aWindow[objName]._statusBar.node.parentNode == sStack) { return; }

	sStack.insertBefore(aWindow[objName]._statusBar.node, sStack.firstChild);
};

this.moveStatusBarBack = function(aWindow) {
	if(aWindow[objName] && aWindow[objName]._statusBar.originalParent) {
		var sBar = aWindow.document.getElementById('status-bar') || aWindow[objName]._statusBar.node;
		if(aWindow[objName]._statusBar.originalParent != sBar.parentNode) { aWindow[objName]._statusBar.originalParent.appendChild(sBar); }
		if(aWindow[objName]._statusBar.originalRemovable) { setAttribute(sBar, 'removable', aWindow[objName]._statusBar.originalRemovable); }
		aWindow[objName]._statusBar.originalParent = null;
		aWindow[objName]._statusBar.originalRemovable = null;
	}
};

// see https://bugzilla.mozilla.org/show_bug.cgi?id=989338
this.preventLosingCustomizeData = function() {
	windowMediator.callOnAll(function(aWindow) {
		moveStatusBarBack(aWindow);
	}, 'navigator:browser');
	try { CustomizableUI.addWidgetToArea('status-bar', 'addon-bar'); } catch(ex) {}
};

// don't forget that add-ons that use the status-bar seem to assume it is always in the DOM tree!
this.trackStatusBar = {
	handler: function(aWidgetId, aArea) {
		if(aWidgetId == objName+'-status-bar-container') {
			if(aArea && aArea == CustomizableUI.AREA_PANEL) {
				CustomizableUI.removeWidgetFromArea(aWidgetId);
				return;
			}
			moveAllStatusBars();
		}
	},

	waitForIt: function(aWindow, aArea) {
		if(!aWindow.document.getElementById(aArea)) {
			aSync(function() {
				if(typeof(trackStatusBar) == 'undefined') { return; }
				try { trackStatusBar.waitForIt(aWindow, aArea); } catch(ex) { Cu.reportError(ex); }
			});
			return;
		}
		moveStatusBar(aWindow);
	},

	onWidgetAdded: function(aWidgetId, aArea) { this.handler(aWidgetId, aArea); },
	onWidgetRemoved: function(aWidgetId) { this.handler(aWidgetId); },

	onAreaNodeRegistered: function(aArea, aContainer) {
		this.waitForIt(aContainer.ownerDocument.defaultView, aArea);
	},

	onAreaNodeUnregistered: function(aArea, aContainer, aReason) {
		if(aReason == CustomizableUI.REASON_AREA_UNREGISTERED) {
			moveStatusBar(aContainer.ownerDocument.defaultView);
		}
	}
};

moduleAid.LOADMODULE = function() {
	alwaysRunOnShutdown.push(preventLosingCustomizeData);

	CustomizableUI.addListener(trackStatusBar);

	overlayAid.overlayURI('chrome://browser/content/browser.xul', 'statusBar', null,
		function(aWindow) {
			prepareObject(aWindow);
			prepareStatusBar(aWindow);
		},
		function(aWindow) {
			moveStatusBarBack(aWindow);
			removeObject(aWindow);
		}
	);

	overlayAid.overlayURI('chrome://'+objPathString+'/content/statusBar.xul', objName, null,
		function(aWindow) {
			aWindow[objName].moduleAid.load(objName, true);
		},
		function(aWindow) {
			aWindow[objName].moduleAid.unload(objName);
		}
	);
};

moduleAid.UNLOADMODULE = function() {
	overlayAid.removeOverlayURI('chrome://'+objPathString+'/content/statusBar.xul', objName);
	overlayAid.removeOverlayURI('chrome://browser/content/browser.xul', 'statusBar');

	CustomizableUI.removeListener(trackStatusBar);

	preventLosingCustomizeData();
};
<|endoftext|>


<commit_before>import React from 'react'
import {shallow} from 'enzyme'
import {Layout} from 'tocco-ui'
import {Field} from 'redux-form'

import FormBuilder from './FormBuilder'

const testData = {
  entity: {
    key: '1',
    paths: {
      firstname: {
        type: 'field',
        value: {
          value: 'First Name',
          type: 'string',
          readable: true,
          writable: true
        }
      },
      lastname: {
        type: 'field',
        value: {
          value: 'Last Name',
          type: 'string',
          readable: true,
          writable: true
        }
      }
    }
  },
  model: {
    paths: {
      fistname: {
        fieldName: 'firstname',
        type: 'string'
      },
      lastname: {
        fieldName: 'lastname',
        type: 'string'
      }
    }
  },
  formName: 'detail',
  formValues: {
    firstname: 'Fist Name',
    lastname: 'Last Name'
  },
  formDefinition: {
    id: 'UserSearch_detail',
    readonly: false,
    children: [
      {
        id: 'box1',
        componentType: 'layout',
        layoutType: 'vertical-box',
        readonly: true,
        children: [
          {
            id: 'box1',
            componentType: 'layout',
            layoutType: 'horizontal-box',
            displayType: 'READONLY',
            children: [
              {
                id: 'user_information',
                componentType: 'layout',
                layoutType: 'vertical-box',
                readonly: true,
                children: [
                  {
                    id: 'firstname',
                    componentType: 'field-set',
                    label: 'Vorname',
                    scopes: ['create'],
                    hidden: false,
                    readonly: true,
                    children: [
                      {
                        id: 'firstname-field', // does not match path by intention (-> should use path to get data)
                        componentType: 'field',
                        path: 'firstname',
                        dataType: 'string',
                        label: null
                      }
                    ]
                  },
                  {
                    id: 'lastname',
                    componentType: 'field-set',
                    label: 'Nachname',
                    hidden: false,
                    readonly: true,
                    children: [
                      {
                        id: 'lastname',
                        componentType: 'field',
                        path: 'lastname',
                        dataType: 'string',
                        label: null
                      }
                    ]
                  }
                ]
              },
              {
                id: 'readonly-box',
                componentType: 'layout',
                layoutType: 'vertical-box',
                readonly: true,
                children: [
                  {
                    id: 'not-readonly-field-set',
                    componentType: 'field-set',
                    label: 'Not Readonly',
                    hidden: false,
                    readonly: false,
                    children: [
                      {
                        id: 'not-readonly-field',
                        componentType: 'field',
                        path: 'not-readonly-field',
                        dataType: 'string',
                        label: null
                      }
                    ]
                  }
                ]
              }
            ],
            label: null
          }
        ]
      }]
  }
}

describe('app-extensions', () => {
  describe('form', () => {
    describe('formBuilder', () => {
      test('should render layout boxes and Fields', () => {
        const {entity, model, formName, formDefinition, formValues} = testData
        const props = {entity, model, formName, formDefinition, formValues, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Layout.Box)).to.have.length(3)
        expect(wrapper.find(Field)).to.have.length(3)
      })

      test('should not render field if beforeRenderField returns false', () => {
        const {entity, model, formName, formDefinition, formValues} = testData

        const beforeRenderField = name => name !== 'lastname'

        const props = {entity, model, formName, formDefinition, formValues, beforeRenderField, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Layout.Box)).to.have.length(3)
        expect(wrapper.find(Field)).to.have.length(2)
      })

      test('should not render none readable fields', () => {
        const {entity, model, formName, formDefinition, formValues} = testData

        entity.paths.lastname = {
          type: 'field',
          value: {
            value: 'Last Name',
            type: 'string',
            readable: false,
            writable: true
          }
        }

        const props = {entity, model, formName, formDefinition, formValues, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)

        expect(wrapper.find(Field)).to.have.length(2)
      })

      test(
        'should not require an entity (should not check readable flag in this case)',
        () => {
          const {model, formName, formDefinition, formValues} = testData
          const entity = null
          const props = {entity, model, formName, formDefinition, formValues, formFieldMapping: {}}
          const wrapper = shallow(<FormBuilder {...props}/>)
          expect(wrapper.find(Field)).to.have.length(3)
        }
      )

      test('should not render empty values in readonly form', () => {
        const {entity, model, formName, formDefinition} = testData
        const formDefinitionReadOnly = {...formDefinition, readonly: true}
        const formValues = {lastname: undefined}
        const props = {entity, model, formName, formValues, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props} formDefinition={formDefinitionReadOnly}/>)
        expect(wrapper.find(Field)).to.have.length(0)
      })

      test('should render fields with matching scope', () => {
        const {model, formName, formDefinition, formValues} = testData
        const entity = null
        const props = {entity, model, formName, formDefinition, formValues, mode: 'create', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Field)).to.have.length(3)
      })

      test('should NOT render fields with unmatching scope', () => {
        const {model, formName, formDefinition, formValues} = testData
        const entity = null
        const props = {entity, model, formName, formDefinition, formValues, mode: 'update', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Field)).to.have.length(1)
      })

      test('should render children of readonly layouts to readonly', () => {
        const {model, formName, formDefinition, formValues} = testData
        const entity = null
        const props = {entity, model, formName, formDefinition, formValues, mode: 'update', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        const field = wrapper.findWhere(e => e.props().id === 'input-detail-not-readonly-field')
        expect(field.props().readOnlyForm).to.be.true
      })

      test('should read multi paths entity fields', () => {
        const entity = {
          paths: {
            relOrder: {
              type: 'entity',
              writable: false,
              value: {
                _links: null,
                key: '12556',
                model: 'Order',
                version: 4,
                paths: {
                  relOrder_debitor_status: {
                    type: 'entity',
                    writable: false,
                    value: {
                      _links: null,
                      key: '2',
                      model: 'Order_debitor_status',
                      version: 2,
                      paths: {}
                    }
                  }
                }
              }
            }
          }
        }

        const formDefinition = {
          id: 'UserSearch_detail',
          readonly: false,
          children: [
            {
              id: 'user_information',
              componentType: 'layout',
              layoutType: 'vertical-box',
              readonly: true,
              children: [
                {
                  id: 'Order_debitor_status',
                  componentType: 'field-set',
                  label: 'Status',
                  hidden: false,
                  readonly: true,
                  children: [
                    {
                      id: 'Order_debitor_status', // does not match path by intention (-> should use path to get data)
                      componentType: 'field',
                      path: 'relOrder.relOrder_debitor_status',
                      dataType: 'string',
                      label: null
                    }
                  ]
                }
              ]
            }
          ]
        }

        const {model, formName, formValues} = testData
        const props = {entity, model, formName, formDefinition, formValues, mode: 'update', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)

        expect(wrapper.find(Field).first().props().entityField).to.equal(
          entity.paths.relOrder.value.paths.relOrder_debitor_status
        )
      })
    })
  })
})
<commit_msg>fix(app-extensions): correct FormBuilder test<commit_after>import React from 'react'
import {shallow} from 'enzyme'
import {Layout} from 'tocco-ui'
import {Field} from 'redux-form'

import FormBuilder from './FormBuilder'

const testData = {
  entity: {
    key: '1',
    paths: {
      firstname: {
        type: 'field',
        value: {
          value: 'First Name',
          type: 'string',
          readable: true,
          writable: true
        }
      },
      lastname: {
        type: 'field',
        value: {
          value: 'Last Name',
          type: 'string',
          readable: true,
          writable: true
        }
      }
    }
  },
  model: {
    paths: {
      fistname: {
        fieldName: 'firstname',
        type: 'string'
      },
      lastname: {
        fieldName: 'lastname',
        type: 'string'
      }
    }
  },
  formName: 'detail',
  formValues: {
    firstname: 'Fist Name',
    lastname: 'Last Name'
  },
  formDefinition: {
    id: 'UserSearch_detail',
    readonly: false,
    children: [
      {
        id: 'box1',
        componentType: 'layout',
        layoutType: 'vertical-box',
        readonly: true,
        children: [
          {
            id: 'box1',
            componentType: 'layout',
            layoutType: 'horizontal-box',
            displayType: 'READONLY',
            children: [
              {
                id: 'user_information',
                componentType: 'layout',
                layoutType: 'vertical-box',
                readonly: true,
                children: [
                  {
                    id: 'firstname',
                    componentType: 'field-set',
                    label: 'Vorname',
                    scopes: ['create'],
                    hidden: false,
                    readonly: true,
                    children: [
                      {
                        id: 'firstname-field', // does not match path by intention (-> should use path to get data)
                        componentType: 'field',
                        path: 'firstname',
                        dataType: 'string',
                        label: null
                      }
                    ]
                  },
                  {
                    id: 'lastname',
                    componentType: 'field-set',
                    label: 'Nachname',
                    hidden: false,
                    readonly: true,
                    children: [
                      {
                        id: 'lastname',
                        componentType: 'field',
                        path: 'lastname',
                        dataType: 'string',
                        label: null
                      }
                    ]
                  }
                ]
              },
              {
                id: 'readonly-box',
                componentType: 'layout',
                layoutType: 'vertical-box',
                readonly: true,
                children: [
                  {
                    id: 'not-readonly-field-set',
                    componentType: 'field-set',
                    label: 'Not Readonly',
                    hidden: false,
                    readonly: false,
                    children: [
                      {
                        id: 'not-readonly-field',
                        componentType: 'field',
                        path: 'not-readonly-field',
                        dataType: 'string',
                        label: null
                      }
                    ]
                  }
                ]
              }
            ],
            label: null
          }
        ]
      }]
  }
}

describe('app-extensions', () => {
  describe('form', () => {
    describe('formBuilder', () => {
      test('should render layout boxes and Fields', () => {
        const {entity, model, formName, formDefinition, formValues} = testData
        const props = {entity, model, formName, formDefinition, formValues, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Layout.Box)).to.have.length(3)
        expect(wrapper.find(Field)).to.have.length(3)
      })

      test('should not render field if beforeRenderField returns false', () => {
        const {entity, model, formName, formDefinition, formValues} = testData

        const beforeRenderField = name => name !== 'lastname'

        const props = {entity, model, formName, formDefinition, formValues, beforeRenderField, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Layout.Box)).to.have.length(3)
        expect(wrapper.find(Field)).to.have.length(2)
      })

      test('should not render none readable fields', () => {
        const {entity, model, formName, formDefinition, formValues} = testData

        entity.paths.lastname = {
          type: 'field',
          value: {
            value: 'Last Name',
            type: 'string',
            readable: false,
            writable: true
          }
        }

        const props = {entity, model, formName, formDefinition, formValues, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)

        expect(wrapper.find(Field)).to.have.length(2)
      })

      test(
        'should not require an entity (should not check readable flag in this case)',
        () => {
          const {model, formName, formDefinition, formValues} = testData
          const entity = null
          const props = {entity, model, formName, formDefinition, formValues, formFieldMapping: {}}
          const wrapper = shallow(<FormBuilder {...props}/>)
          expect(wrapper.find(Field)).to.have.length(3)
        }
      )

      test('should not render empty values in readonly form', () => {
        const {entity, model, formName, formDefinition} = testData
        const formDefinitionReadOnly = {...formDefinition, readonly: true}
        const formValues = {lastname: undefined}
        const props = {entity, model, formName, formValues, formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props} formDefinition={formDefinitionReadOnly}/>)
        expect(wrapper.find(Field)).to.have.length(0)
      })

      test('should render fields with matching scope', () => {
        const {model, formName, formDefinition, formValues} = testData
        const entity = null
        const props = {entity, model, formName, formDefinition, formValues, mode: 'create', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Field)).to.have.length(3)
      })

      test('should NOT render fields with unmatching scope', () => {
        const {model, formName, formDefinition, formValues} = testData
        const entity = null
        const props = {entity, model, formName, formDefinition, formValues, mode: 'update', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        expect(wrapper.find(Field)).to.have.length(2)
      })

      test('should render children of readonly layouts to readonly', () => {
        const {model, formName, formDefinition, formValues} = testData
        const entity = null
        const props = {entity, model, formName, formDefinition, formValues, mode: 'update', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)
        const field = wrapper.findWhere(e => e.props().id === 'input-detail-not-readonly-field')
        expect(field).to.have.length(1)
        expect(field.props().readOnlyForm).to.be.true
      })

      test('should read multi paths entity fields', () => {
        const entity = {
          paths: {
            relOrder: {
              type: 'entity',
              writable: false,
              value: {
                _links: null,
                key: '12556',
                model: 'Order',
                version: 4,
                paths: {
                  relOrder_debitor_status: {
                    type: 'entity',
                    writable: false,
                    value: {
                      _links: null,
                      key: '2',
                      model: 'Order_debitor_status',
                      version: 2,
                      paths: {}
                    }
                  }
                }
              }
            }
          }
        }

        const formDefinition = {
          id: 'UserSearch_detail',
          readonly: false,
          children: [
            {
              id: 'user_information',
              componentType: 'layout',
              layoutType: 'vertical-box',
              readonly: true,
              children: [
                {
                  id: 'Order_debitor_status',
                  componentType: 'field-set',
                  label: 'Status',
                  hidden: false,
                  readonly: true,
                  children: [
                    {
                      id: 'Order_debitor_status', // does not match path by intention (-> should use path to get data)
                      componentType: 'field',
                      path: 'relOrder.relOrder_debitor_status',
                      dataType: 'string',
                      label: null
                    }
                  ]
                }
              ]
            }
          ]
        }

        const {model, formName, formValues} = testData
        const props = {entity, model, formName, formDefinition, formValues, mode: 'update', formFieldMapping: {}}
        const wrapper = shallow(<FormBuilder {...props}/>)

        expect(wrapper.find(Field).first().props().entityField).to.equal(
          entity.paths.relOrder.value.paths.relOrder_debitor_status
        )
      })
    })
  })
})
<|endoftext|>


<commit_before>app.directive('trainingDataFileReader', function() {
  return {
	restrict: 'A',
	scope: {},
    link: function(scope, element, attrs) {
      element.on('change', function(changeEvent) {
        var files = changeEvent.target.files;
        if (files.length) {
          var r = new FileReader();
          r.onload = function(e) {
              var contents = e.target.result;
              scope.$apply(function () {
				function digestCSV(rawContent)
				{
					var retArr = [];
					var arrayOfLines = rawContent.match(/[^\r\n]+/g);

					for(var i=0; i<arrayOfLines; i++)
						retArr[i] = arrayOfLines[i].split(',');

					return retArr;
				}
				if(attrs.fileType === 'learning')
					scope.trainingProps.learningSet = digestCSV(contents);
				if(attrs.fileType === 'training')
					scope.trainingProps.trainingSet = digestCSV(contents);
              });
          };

          r.readAsText(files[0]);
        }
      });
    }
  };
});
<commit_msg>Bugfix<commit_after>app.directive('trainingDataFileReader', function() {
  return {
	restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('change', function(changeEvent) {
        var files = changeEvent.target.files;
        if (files.length) {
          var r = new FileReader();
          r.onload = function(e) {
              var contents = e.target.result;
              scope.$apply(function () {
				function digestCSV(rawContent)
				{
					var retArr = [];
					var arrayOfLines = rawContent.match(/[^\r\n]+/g);

					for(var i=0; i<arrayOfLines; i++)
						retArr[i] = arrayOfLines[i].split(',');

					return retArr;
				}
				if(attrs.fileType === 'learning')
					scope.trainingProps.learningSet = digestCSV(contents);
				if(attrs.fileType === 'training')
					scope.trainingProps.trainingSet = digestCSV(contents);
              });
          };

          r.readAsText(files[0]);
        }
      });
    }
  };
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Navigation from '../navigation/Navigation';
import './Feed.css';

import * as api from '../../helpers/api';

class Feed extends Component {

  constructor(props) {
    super(props);
    this.state = {
      topStoryIds: []
    };
  }

  loadTopStoriesIds() {
    api.getTopStories()
      .then((response) => {
        if(response.data) {
         this.setState({ topStoryIds: response.data });
        }
    });
  }

  componentDidMount() {
    this.loadTopStoriesIds();
  }

  render() {

    const topStoryIds = this.state.topStoryIds;

    return (

          <Navigation />

                { topStoryIds }

    );
  }
}

Feed.propTypes = {
  topStoryIds: React.PropTypes.array
};

export default Feed;
<commit_msg>Fixed issue with unique "key" prop<commit_after>import React, { Component } from 'react';
import Navigation from '../navigation/Navigation';
import './Feed.css';

import * as api from '../../helpers/api';

class Feed extends Component {

  constructor(props) {
    super(props);
    this.state = {
      topStoryIds: []
    };
  }

  loadTopStoriesIds() {
    api.getTopStories()
      .then((response) => {
        if(response.data) {
         this.setState({ topStoryIds: response.data });
        }
    });
  }

  componentDidMount() {
    this.loadTopStoriesIds();
  }

  render() {

    const topStoryIds = this.state.topStoryIds;

    const topStoryList = topStoryIds.map((storyId) => {
      return (

{ storyId }

      );
    });

    return (

          <Navigation />

                    { topStoryList }

    );
  }
}

Feed.propTypes = {
  topStoryIds: React.PropTypes.array
};

export default Feed;
<|endoftext|>


<commit_before>var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor;

function WebService(currentUser) {
	this._currentUser = currentUser;
	this._dependencies = {};
	this.runRef = undefined;
}

WebService.prototype.runWrapper = function () {
	var self = this;

	return function (name, allowedTypeAccount, params) {
		allowedTypeAccount = allowedTypeAccount || [];
		params = params || {};

		return function (req, res) {
			params.req = req;
			params.res = res;
			self.runRef(name, allowedTypeAccount, params);
		};
	};
};

WebService.prototype.run = function (name, allowedTypeAccount, params) {
	allowedTypeAccount = allowedTypeAccount || [];
	params = params || {};

	var self = this;
	var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser);
	var webServices = require('../ServiceDirectories/Web/Public');

	if (permissionsInit.check()) {
		webServices[name].call(undefined, self._dependencies, params);
	} else {
		webServices['accessDenied'].call(undefined, self._dependencies, params);
	}
};

WebService.prototype.addDependency = function (name, value) {
	this._dependencies[name] = value;
};

module.exports.WebService = WebService;<commit_msg>Add option if name not exists.<commit_after>var PermissionConstructor = require('./PermissionConstructor').PermissionConstructor;

function WebService(currentUser) {
	this._currentUser = currentUser;
	this._dependencies = {};
	this.runRef = undefined;
}

WebService.prototype.runWrapper = function () {
	var self = this;

	return function (name, allowedTypeAccount, params) {
		name = name || 'accessDenied';
		allowedTypeAccount = allowedTypeAccount || [];
		params = params || {};

		return function (req, res) {
			params.req = req;
			params.res = res;
			self.runRef(name, allowedTypeAccount, params);
		};
	};
};

WebService.prototype.run = function (name, allowedTypeAccount, params) {
	allowedTypeAccount = allowedTypeAccount || [];
	params = params || {};

	var self = this;
	var permissionsInit = new PermissionConstructor(allowedTypeAccount, this._currentUser);
	var webServices = require('../ServiceDirectories/Web/Public');

	if (permissionsInit.check()) {
		webServices[name].call(undefined, self._dependencies, params);
	} else {
		webServices['accessDenied'].call(undefined, self._dependencies, params);
	}
};

WebService.prototype.addDependency = function (name, value) {
	this._dependencies[name] = value;
};

module.exports.WebService = WebService;<|endoftext|>


<commit_before>/*
 * Slugify for Voyager v0.9.0
 *
 * Generates a slug for a given input element.
 * This script was created for Voyager, but works with any HTML structure.
 *
 * Default behavior is to auto generate a new slug, only if the input is empty.
 * If input isn't empty, the auto generation is disabled.
 * To force the auto generator, set the option "forceUpdate: true".
 *
 * Copyright 2017 Bruno Torrinha
 * License MIT
 *
 * Some credits:
 * Char map from: https://github.com/diegok/slugit-jquery
 */
;( function( $, window, document, undefined ) {

    "use strict";

        var pluginName = "slugify",
            defaults = {
                separator:   '-',
                input:       false, // The origin from where we generate the slug.
                forceUpdate: false, // Force update if input is not empty.
                map:         false  // Provide an extra character map translator.
            };

        function Plugin ( element, options ) {
            this.element   = $(element);  // The input where slug is placed.
            this.settings  = $.extend( {}, defaults, options );
            this._defaults = defaults;
            this.chars     = this._load_char_maps();
            if (!this.settings.map) {      // Load extra character map translator
                $.extend(this.chars, this.settings.map);
            }
            this.init();
        }

        // Avoid Plugin.prototype conflicts
        $.extend( Plugin.prototype, {
            init: function() {
                this.input = this.settings.input
                             || $(this.element).closest('form').find('input[name="' + this.element.attr("data-slug-origin") + '"]');

                this.forceUpdate = (this.element.data('slug-forceupdate')) ? true : false;
                this.input.on('keyup change', $.proxy(this.onChange, this));

                this.refresh();
            },

            refresh: function() {
                this.element.update = this.element.val() === '';
            },

            /**
             * When input changes
             */
            onChange: function(ev) {
                var code = ev.keyCode ? ev.keyCode : ev.which;

                if (code > 34 && code < 41) {
                    return;
                }

                var strOrigin = $(ev.target).val(),
                    strTarget = this.element.val();

                if (
                    this.element.update
                    || strTarget === ''
                    || (strTarget != '' && this.forceUpdate)
                ){
                    this.element.val(this.slug(strOrigin));
                    this.element.update = true;
                }
                return;
            },

            /**
             * Generate a slug
             */
            slug: function(str) {
                str = str
                    .toString()
                    .toLowerCase();

                var _slug = '',
                    _sep = this.settings.separator;

                // Replace Char Map
                //
                for (var i=0, l=str.length ; i<l ; i++) {
                    _slug += (this.chars[str.charAt(i)])
                             ? this.chars[str.charAt(i)]
                             : str.charAt(i);
                }

                str = _slug
                    .replace(/^\s+|\s+$/g, '')      // Trim
                    .replace(/[^-\u0600-۾\w\d\$\*\(\)\'\!\_]/g, _sep)   // Remove invalid chars
                    .replace(/\s+/g, _sep)          // Replace spaces with separator
                    .replace(/\-\-+/g, _sep);       // Replace multiple separators with single

                return str;
            },

            _load_char_maps: function() {
                return $.extend(
                            this._map_latin(),
                            this._map_greek(),
                            this._map_turkish(),
                            this._map_russian(),
                            this._map_ukranian(),
                            this._map_czech(),
                            this._map_polish(),
                            this._map_vietnam(),
                            this._map_latvian(),
                            this._map_currency(),
                            this._map_symbols()
                        );
            },
            _map_latin: function() {
                return {
                    'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç':
                    'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I',
                    'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö':
                    'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ű': 'U',
                    'Ý': 'Y', 'Þ': 'TH', 'ß': 'ss', 'à':'a', 'á':'a', 'â': 'a', 'ã': 'a', 'ä':
                    'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e',
                    'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó':
                    'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u',
                    'û': 'u', 'ü': 'u', 'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y'
                };
            },
            _map_greek: function() {
                return {
                    'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'8',
                    'ι':'i', 'κ':'k', 'λ':'l', 'μ':'m', 'ν':'n', 'ξ':'3', 'ο':'o', 'π':'p',
                    'ρ':'r', 'σ':'s', 'τ':'t', 'υ':'y', 'φ':'f', 'χ':'x', 'ψ':'ps', 'ω':'w',
                    'ά':'a', 'έ':'e', 'ί':'i', 'ό':'o', 'ύ':'y', 'ή':'h', 'ώ':'w', 'ς':'s',
                    'ϊ':'i', 'ΰ':'y', 'ϋ':'y', 'ΐ':'i',
                    'Α':'A', 'Β':'B', 'Γ':'G', 'Δ':'D', 'Ε':'E', 'Ζ':'Z', 'Η':'H', 'Θ':'8',
                    'Ι':'I', 'Κ':'K', 'Λ':'L', 'Μ':'M', 'Ν':'N', 'Ξ':'3', 'Ο':'O', 'Π':'P',
                    'Ρ':'R', 'Σ':'S', 'Τ':'T', 'Υ':'Y', 'Φ':'F', 'Χ':'X', 'Ψ':'PS', 'Ω':'W',
                    'Ά':'A', 'Έ':'E', 'Ί':'I', 'Ό':'O', 'Ύ':'Y', 'Ή':'H', 'Ώ':'W', 'Ϊ':'I',
                    'Ϋ':'Y'
                };
            },
            _map_turkish: function() {
                return {
                    'ş':'s', 'Ş':'S', 'ı':'i', 'İ':'I', 'ç':'c', 'Ç':'C', 'ü':'u', 'Ü':'U',
                    'ö':'o', 'Ö':'O', 'ğ':'g', 'Ğ':'G'
                };
            },
            _map_russian: function() {
                return {
                    'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'yo', 'ж':'zh',
                    'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o',
                    'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c',
                    'ч':'ch', 'ш':'sh', 'щ':'sh', 'ъ':'', 'ы':'y', 'ь':'', 'э':'e', 'ю':'yu',
                    'я':'ya',
                    'А':'A', 'Б':'B', 'В':'V', 'Г':'G', 'Д':'D', 'Е':'E', 'Ё':'Yo', 'Ж':'Zh',
                    'З':'Z', 'И':'I', 'Й':'J', 'К':'K', 'Л':'L', 'М':'M', 'Н':'N', 'О':'O',
                    'П':'P', 'Р':'R', 'С':'S', 'Т':'T', 'У':'U', 'Ф':'F', 'Х':'H', 'Ц':'C',
                    'Ч':'Ch', 'Ш':'Sh', 'Щ':'Sh', 'Ъ':'', 'Ы':'Y', 'Ь':'', 'Э':'E', 'Ю':'Yu',
                    'Я':'Ya'
                };
            },
            _map_ukranian: function() {
                return {
                    'Є':'Ye', 'І':'I', 'Ї':'Yi', 'Ґ':'G', 'є':'ye', 'і':'i', 'ї':'yi', 'ґ':'g'
                };
            },
            _map_czech: function() {
                return {
                    'č':'c', 'ď':'d', 'ě':'e', 'ň': 'n', 'ř':'r', 'š':'s', 'ť':'t', 'ů':'u',
                    'ž':'z', 'Č':'C', 'Ď':'D', 'Ě':'E', 'Ň': 'N', 'Ř':'R', 'Š':'S', 'Ť':'T',
                    'Ů':'U', 'Ž':'Z'
                };
            },
            _map_polish: function() {
                return {
                    'ą':'a', 'ć':'c', 'ę':'e', 'ł':'l', 'ń':'n', 'ó':'o', 'ś':'s', 'ź':'z',
                    'ż':'z', 'Ą':'A', 'Ć':'C', 'Ę':'e', 'Ł':'L', 'Ń':'N', 'Ó':'o', 'Ś':'S',
                    'Ź':'Z', 'Ż':'Z'
                };
            },
            _map_vietnam: function() {
                return {
                    'ạ': 'a','ả': 'a','ầ': 'a','ấ': 'a','ậ': 'a','ẩ': 'a','ẫ': 'a','ằ': 'a',
                    'ắ': 'a','ặ': 'a','ẳ': 'a','ẵ': 'a','ẹ': 'e','ẻ': 'e','ẽ': 'e','ề': 'e',
                    'ế': 'e','ệ': 'e','ể': 'e','ễ': 'e','ị': 'i','ỉ': 'i','ọ': 'o','ỏ': 'o',
                    'ồ': 'o','ố': 'o','ộ': 'o','ổ': 'o','ỗ': 'o','ờ': 'o','ớ': 'o','ợ': 'o',
                    'ở': 'o','ỡ': 'o','ụ': 'u','ủ': 'u','ừ': 'u','ứ': 'u','ự': 'u','ử': 'u',
                    'ữ': 'u','ỳ': 'y','ỵ': 'y','ỷ': 'y','ỹ': 'y','Ạ': 'A','Ả': 'A','Ầ': 'A',
                    'Ấ': 'A','Ậ': 'A','Ẩ': 'A','Ẫ': 'A','Ằ': 'A','Ắ': 'A','Ặ': 'A','Ẳ': 'A',
                    'Ẵ': 'A','Ẹ': 'E','Ẻ': 'E','Ẽ': 'E','Ề': 'E','Ế': 'E','Ệ': 'E','Ể': 'E',
                    'Ễ': 'E','Ị': 'I','Ỉ': 'I','Ọ': 'O','Ỏ': 'O','Ồ': 'O','Ố': 'O','Ộ': 'O',
                    'Ổ': 'O','Ỗ': 'O','Ờ': 'O','Ớ': 'O','Ợ': 'O','Ở': 'O','Ỡ': 'O','Ụ': 'U',
                    'Ủ': 'U','Ừ': 'U','Ứ': 'U','Ự': 'U','Ử': 'U','Ữ': 'U','Ỳ': 'Y','Ỵ': 'Y',
                    'đ': 'd','Đ': 'D','Ỷ': 'Y','Ỹ': 'Y'
                };
            },
            _map_latvian: function() {
                return {
                    'ā':'a', 'č':'c', 'ē':'e', 'ģ':'g', 'ī':'i', 'ķ':'k', 'ļ':'l', 'ņ':'n',
                    'š':'s', 'ū':'u', 'ž':'z', 'Ā':'A', 'Č':'C', 'Ē':'E', 'Ģ':'G', 'Ī':'i',
                    'Ķ':'k', 'Ļ':'L', 'Ņ':'N', 'Š':'S', 'Ū':'u', 'Ž':'Z'
                };
            },
            _map_currency: function() {
                return {
                    '€': 'euro', '$': 'dollar', '₢': 'cruzeiro', '₣': 'french franc', '£': 'pound',
                    '₤': 'lira', '₥': 'mill', '₦': 'naira', '₧': 'peseta', '₨': 'rupee',
                    '₩': 'won', '₪': 'new shequel', '₫': 'dong', '₭': 'kip', '₮': 'tugrik',
                    '₯': 'drachma', '₰': 'penny', '₱': 'peso', '₲': 'guarani', '₳': 'austral',
                    '₴': 'hryvnia', '₵': 'cedi', '¢': 'cent', '¥': 'yen', '元': 'yuan',
                    '円': 'yen', '﷼': 'rial', '₠': 'ecu', '¤': 'currency', '฿': 'baht'
                };
            },
            _map_symbols: function() {
                return {
                    '©':'(c)', 'œ': 'oe', 'Œ': 'OE', '∑': 'sum', '®': '(r)', '†': '+',
                    '“': '"', '”': '"', '‘': "'", '’': "'", '∂': 'd', 'ƒ': 'f', '™': 'tm',
                    '℠': 'sm', '…': '...', '˚': 'o', 'º': 'o', 'ª': 'a', '•': '*',
                    '∆': 'delta', '∞': 'infinity', '♥': 'love', '&': 'and'
                };
            }
        });

        $.fn[ pluginName ] = function( options ) {
            return this.each( function() {
                if ( !$.data( this, pluginName ) ) {
                    $.data( this, pluginName, new Plugin(this, options) );
                }
            } );
        };

} )( jQuery, window, document );
<commit_msg>support arabic (#2659)<commit_after>/*
 * Slugify for Voyager v0.9.0
 *
 * Generates a slug for a given input element.
 * This script was created for Voyager, but works with any HTML structure.
 *
 * Default behavior is to auto generate a new slug, only if the input is empty.
 * If input isn't empty, the auto generation is disabled.
 * To force the auto generator, set the option "forceUpdate: true".
 *
 * Copyright 2017 Bruno Torrinha
 * License MIT
 *
 * Some credits:
 * Char map from: https://github.com/diegok/slugit-jquery
 */
;( function( $, window, document, undefined ) {

    "use strict";

        var pluginName = "slugify",
            defaults = {
                separator:   '-',
                input:       false, // The origin from where we generate the slug.
                forceUpdate: false, // Force update if input is not empty.
                map:         false  // Provide an extra character map translator.
            };

        function Plugin ( element, options ) {
            this.element   = $(element);  // The input where slug is placed.
            this.settings  = $.extend( {}, defaults, options );
            this._defaults = defaults;
            this.chars     = this._load_char_maps();
            if (!this.settings.map) {      // Load extra character map translator
                $.extend(this.chars, this.settings.map);
            }
            this.init();
        }

        // Avoid Plugin.prototype conflicts
        $.extend( Plugin.prototype, {
            init: function() {
                this.input = this.settings.input
                             || $(this.element).closest('form').find('input[name="' + this.element.attr("data-slug-origin") + '"]');

                this.forceUpdate = (this.element.data('slug-forceupdate')) ? true : false;
                this.input.on('keyup change', $.proxy(this.onChange, this));

                this.refresh();
            },

            refresh: function() {
                this.element.update = this.element.val() === '';
            },

            /**
             * When input changes
             */
            onChange: function(ev) {
                var code = ev.keyCode ? ev.keyCode : ev.which;

                if (code > 34 && code < 41) {
                    return;
                }

                var strOrigin = $(ev.target).val(),
                    strTarget = this.element.val();

                if (
                    this.element.update
                    || strTarget === ''
                    || (strTarget != '' && this.forceUpdate)
                ){
                    this.element.val(this.slug(strOrigin));
                    this.element.update = true;
                }
                return;
            },

            /**
             * Generate a slug
             */
            slug: function(str) {
                str = str
                    .toString()
                    .toLowerCase();

                var _slug = '',
                    _sep = this.settings.separator;

                // Replace Char Map
                //
                for (var i=0, l=str.length ; i<l ; i++) {
                    _slug += (this.chars[str.charAt(i)])
                             ? this.chars[str.charAt(i)]
                             : str.charAt(i);
                }

                str = _slug
                    .replace(/^\s+|\s+$/g, '')      // Trim
                    .replace(/[^-\u0600-۾\w\d\$\*\(\)\'\!\_]/g, _sep)   // Remove invalid chars
                    .replace(/\s+/g, _sep)          // Replace spaces with separator
                    .replace(/\-\-+/g, _sep);       // Replace multiple separators with single

                return str;
            },

            _load_char_maps: function() {
                return $.extend(
                            this._map_latin(),
                            this._map_arabic(),
                            this._map_greek(),
                            this._map_turkish(),
                            this._map_russian(),
                            this._map_ukranian(),
                            this._map_czech(),
                            this._map_polish(),
                            this._map_vietnam(),
                            this._map_latvian(),
                            this._map_currency(),
                            this._map_symbols()
                        );
            },
            _map_latin: function() {
                return {
                    'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç':
                    'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I',
                    'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö':
                    'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ű': 'U',
                    'Ý': 'Y', 'Þ': 'TH', 'ß': 'ss', 'à':'a', 'á':'a', 'â': 'a', 'ã': 'a', 'ä':
                    'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e',
                    'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó':
                    'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u',
                    'û': 'u', 'ü': 'u', 'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y'
                };
            },
                        _map_arabic:  function() {
              return {
                'ا': 'a',
                'أ': 'a',
                'إ': 'i',
                'آ': 'aa',
                'ؤ': 'u',
                'ئ': 'e',
                'ء': 'a',
                'ب': 'b',
                'ت': 't',
                'ث': 'th',
                'ج': 'j',
                'ح': 'h',
                'خ': 'kh',
                'د': 'd',
                'ذ': 'th',
                'ر': 'r',
                'ز': 'z',
                'س': 's',
                'ش': 'sh',
                'ص': 's',
                'ض': 'dh',
                'ط': 't',
                'ظ': 'z',
                'ع': 'a',
                'غ': 'gh',
                'ف': 'f',
                'ق': 'q',
                'ك': 'k',
                'ل': 'l',
                'م': 'm',
                'ن': 'n',
                'ه': 'h',
                'و': 'w',
                'ي': 'y',
                'ى': 'a',
                'ة': 'h',
                'ﻻ': 'la',
                'ﻷ': 'laa',
                'ﻹ': 'lai',
                'ﻵ': 'laa',
              };
            },
            _map_greek: function() {
                return {
                    'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'8',
                    'ι':'i', 'κ':'k', 'λ':'l', 'μ':'m', 'ν':'n', 'ξ':'3', 'ο':'o', 'π':'p',
                    'ρ':'r', 'σ':'s', 'τ':'t', 'υ':'y', 'φ':'f', 'χ':'x', 'ψ':'ps', 'ω':'w',
                    'ά':'a', 'έ':'e', 'ί':'i', 'ό':'o', 'ύ':'y', 'ή':'h', 'ώ':'w', 'ς':'s',
                    'ϊ':'i', 'ΰ':'y', 'ϋ':'y', 'ΐ':'i',
                    'Α':'A', 'Β':'B', 'Γ':'G', 'Δ':'D', 'Ε':'E', 'Ζ':'Z', 'Η':'H', 'Θ':'8',
                    'Ι':'I', 'Κ':'K', 'Λ':'L', 'Μ':'M', 'Ν':'N', 'Ξ':'3', 'Ο':'O', 'Π':'P',
                    'Ρ':'R', 'Σ':'S', 'Τ':'T', 'Υ':'Y', 'Φ':'F', 'Χ':'X', 'Ψ':'PS', 'Ω':'W',
                    'Ά':'A', 'Έ':'E', 'Ί':'I', 'Ό':'O', 'Ύ':'Y', 'Ή':'H', 'Ώ':'W', 'Ϊ':'I',
                    'Ϋ':'Y'
                };
            },
            _map_turkish: function() {
                return {
                    'ş':'s', 'Ş':'S', 'ı':'i', 'İ':'I', 'ç':'c', 'Ç':'C', 'ü':'u', 'Ü':'U',
                    'ö':'o', 'Ö':'O', 'ğ':'g', 'Ğ':'G'
                };
            },
            _map_russian: function() {
                return {
                    'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'yo', 'ж':'zh',
                    'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o',
                    'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c',
                    'ч':'ch', 'ш':'sh', 'щ':'sh', 'ъ':'', 'ы':'y', 'ь':'', 'э':'e', 'ю':'yu',
                    'я':'ya',
                    'А':'A', 'Б':'B', 'В':'V', 'Г':'G', 'Д':'D', 'Е':'E', 'Ё':'Yo', 'Ж':'Zh',
                    'З':'Z', 'И':'I', 'Й':'J', 'К':'K', 'Л':'L', 'М':'M', 'Н':'N', 'О':'O',
                    'П':'P', 'Р':'R', 'С':'S', 'Т':'T', 'У':'U', 'Ф':'F', 'Х':'H', 'Ц':'C',
                    'Ч':'Ch', 'Ш':'Sh', 'Щ':'Sh', 'Ъ':'', 'Ы':'Y', 'Ь':'', 'Э':'E', 'Ю':'Yu',
                    'Я':'Ya'
                };
            },
            _map_ukranian: function() {
                return {
                    'Є':'Ye', 'І':'I', 'Ї':'Yi', 'Ґ':'G', 'є':'ye', 'і':'i', 'ї':'yi', 'ґ':'g'
                };
            },
            _map_czech: function() {
                return {
                    'č':'c', 'ď':'d', 'ě':'e', 'ň': 'n', 'ř':'r', 'š':'s', 'ť':'t', 'ů':'u',
                    'ž':'z', 'Č':'C', 'Ď':'D', 'Ě':'E', 'Ň': 'N', 'Ř':'R', 'Š':'S', 'Ť':'T',
                    'Ů':'U', 'Ž':'Z'
                };
            },
            _map_polish: function() {
                return {
                    'ą':'a', 'ć':'c', 'ę':'e', 'ł':'l', 'ń':'n', 'ó':'o', 'ś':'s', 'ź':'z',
                    'ż':'z', 'Ą':'A', 'Ć':'C', 'Ę':'e', 'Ł':'L', 'Ń':'N', 'Ó':'o', 'Ś':'S',
                    'Ź':'Z', 'Ż':'Z'
                };
            },
            _map_vietnam: function() {
                return {
                    'ạ': 'a','ả': 'a','ầ': 'a','ấ': 'a','ậ': 'a','ẩ': 'a','ẫ': 'a','ằ': 'a',
                    'ắ': 'a','ặ': 'a','ẳ': 'a','ẵ': 'a','ẹ': 'e','ẻ': 'e','ẽ': 'e','ề': 'e',
                    'ế': 'e','ệ': 'e','ể': 'e','ễ': 'e','ị': 'i','ỉ': 'i','ọ': 'o','ỏ': 'o',
                    'ồ': 'o','ố': 'o','ộ': 'o','ổ': 'o','ỗ': 'o','ờ': 'o','ớ': 'o','ợ': 'o',
                    'ở': 'o','ỡ': 'o','ụ': 'u','ủ': 'u','ừ': 'u','ứ': 'u','ự': 'u','ử': 'u',
                    'ữ': 'u','ỳ': 'y','ỵ': 'y','ỷ': 'y','ỹ': 'y','Ạ': 'A','Ả': 'A','Ầ': 'A',
                    'Ấ': 'A','Ậ': 'A','Ẩ': 'A','Ẫ': 'A','Ằ': 'A','Ắ': 'A','Ặ': 'A','Ẳ': 'A',
                    'Ẵ': 'A','Ẹ': 'E','Ẻ': 'E','Ẽ': 'E','Ề': 'E','Ế': 'E','Ệ': 'E','Ể': 'E',
                    'Ễ': 'E','Ị': 'I','Ỉ': 'I','Ọ': 'O','Ỏ': 'O','Ồ': 'O','Ố': 'O','Ộ': 'O',
                    'Ổ': 'O','Ỗ': 'O','Ờ': 'O','Ớ': 'O','Ợ': 'O','Ở': 'O','Ỡ': 'O','Ụ': 'U',
                    'Ủ': 'U','Ừ': 'U','Ứ': 'U','Ự': 'U','Ử': 'U','Ữ': 'U','Ỳ': 'Y','Ỵ': 'Y',
                    'đ': 'd','Đ': 'D','Ỷ': 'Y','Ỹ': 'Y'
                };
            },
            _map_latvian: function() {
                return {
                    'ā':'a', 'č':'c', 'ē':'e', 'ģ':'g', 'ī':'i', 'ķ':'k', 'ļ':'l', 'ņ':'n',
                    'š':'s', 'ū':'u', 'ž':'z', 'Ā':'A', 'Č':'C', 'Ē':'E', 'Ģ':'G', 'Ī':'i',
                    'Ķ':'k', 'Ļ':'L', 'Ņ':'N', 'Š':'S', 'Ū':'u', 'Ž':'Z'
                };
            },
            _map_currency: function() {
                return {
                    '€': 'euro', '$': 'dollar', '₢': 'cruzeiro', '₣': 'french franc', '£': 'pound',
                    '₤': 'lira', '₥': 'mill', '₦': 'naira', '₧': 'peseta', '₨': 'rupee',
                    '₩': 'won', '₪': 'new shequel', '₫': 'dong', '₭': 'kip', '₮': 'tugrik',
                    '₯': 'drachma', '₰': 'penny', '₱': 'peso', '₲': 'guarani', '₳': 'austral',
                    '₴': 'hryvnia', '₵': 'cedi', '¢': 'cent', '¥': 'yen', '元': 'yuan',
                    '円': 'yen', '﷼': 'rial', '₠': 'ecu', '¤': 'currency', '฿': 'baht'
                };
            },
            _map_symbols: function() {
                return {
                    '©':'(c)', 'œ': 'oe', 'Œ': 'OE', '∑': 'sum', '®': '(r)', '†': '+',
                    '“': '"', '”': '"', '‘': "'", '’': "'", '∂': 'd', 'ƒ': 'f', '™': 'tm',
                    '℠': 'sm', '…': '...', '˚': 'o', 'º': 'o', 'ª': 'a', '•': '*',
                    '∆': 'delta', '∞': 'infinity', '♥': 'love', '&': 'and'
                };
            }
        });

        $.fn[ pluginName ] = function( options ) {
            return this.each( function() {
                if ( !$.data( this, pluginName ) ) {
                    $.data( this, pluginName, new Plugin(this, options) );
                }
            } );
        };

} )( jQuery, window, document );
<|endoftext|>


<commit_before>shortcuts.register('Documents list', ['r', 'R'], ['R'], 'Refresh list', function() { $('#refresh-documents').click() });
shortcuts.register('Documents list', ['c', 'C'], ['C'], 'Clear filter', function() { $('#reset-filter').click() });
shortcuts.register('Documents list', ['n', 'N'], ['N'], 'Previous page', function() { $('.pagination-previous').click() });
shortcuts.register('Documents list', ['m', 'M'], ['M'], 'Next page', function() { $('.pagination-next').click() });

Template.Documents.onCreated(function () {
  this.autorun(() => {
    //log('> autorun 2');
    if (!CurrentSession.collection) return false;

    let filter = CurrentSession.documentsFilter || '{}';
    Session.set('showLoader', true);

    CurrentSession.documentsReady = false;
    Meteor.call('getDocuments', CurrentSession.database._id, CurrentSession.collection.name, filter, CurrentSession.documentsPagination, CurrentSession.documentsRandomSeed, function(error, result) {
      if (result == false) {
        alert('Filter incorrect...');
        return false;
      }
      CurrentSession.documents = result.docs;
      CurrentSession.documentsCount = result.count;
      CurrentSession.documentsReady = true;
      Session.set('showLoader', false);

    });
  });
});

Template.Documents.helpers({
  documentsReady() {
    return CurrentSession.documentsReady;
  },
  filterData() {
    return {
      collection: CurrentSession.collection,
      filter: CurrentSession.documentsFilter
    }
  },

  viewParameters() {
    if (!ConnectionStructureSubscription.ready()) return false;
    let documents = CurrentSession.documents || false;
    if (!documents) return false;

    let index = (CurrentSession.documentsPagination * CurrentSession.documentsPaginationLimit) + 1;
    _.each(documents, function(doc) {
      doc.drMongoIndex = index++ + '.';
    });
    return {documents: documents};
  },

  collection() {
    return CurrentSession.collection;
  },

  savedFilters() {
    if (!CurrentSession.collection) return false;
    return FilterHistory.find({name: {$ne: null}, collection_id: CurrentSession.collection._id});
  }
});

Template.Documents.events({
  'click #refresh-documents'(event, templateInstance) {
    refreshDocuments();
  },

  'click #reset-filter'(event, templateInstance) {
    FlowRouter.go(getFilterRoute());
  },

  'click #save-filter'(event, templateInstance) {
    event.preventDefault();
    event.stopImmediatePropagation();

    let filterId = FlowRouter.getParam('filter');
    if (filterId) {
      let name = prompt('Give filter a name to save it:');
      FilterHistory.update(filterId, {$set: {name: name}});
    } else {
      sAlert.info('No filter set.')
    }
  },

  'click #saved-filters li a:not(#save-filter)'(event, templateInstance) {
    event.preventDefault();
    FlowRouter.go(getFilterRoute(this._id));
  },

  'click #insert-document'(event, templateInstance) {
    event.preventDefault();
    event.stopImmediatePropagation();
    Session.set('DocumentInsertModal', {
      connectionId: CurrentSession.connection._id,
      databaseId: CurrentSession.database._id,
      collectionId: CurrentSession.collection._id
    });
    $('#DocumentInsertModal').modal('show');
  },

  'click #collection-dashboard'(event, templateInstance) {
    event.preventDefault();
    event.stopImmediatePropagation();
    Session.set('CollectionDashboardModal', {
      connectionId: CurrentSession.connection._id,
      databaseId: CurrentSession.database._id,
      collectionId: CurrentSession.collection._id
    });
    $('#CollectionDashboardModal').modal('show');
  }

});
<commit_msg>Connection failed error message<commit_after>shortcuts.register('Documents list', ['r', 'R'], ['R'], 'Refresh list', function() { $('#refresh-documents').click() });
shortcuts.register('Documents list', ['c', 'C'], ['C'], 'Clear filter', function() { $('#reset-filter').click() });
shortcuts.register('Documents list', ['n', 'N'], ['N'], 'Previous page', function() { $('.pagination-previous').click() });
shortcuts.register('Documents list', ['m', 'M'], ['M'], 'Next page', function() { $('.pagination-next').click() });

Template.Documents.onCreated(function () {
  this.autorun(() => {
    //log('> autorun 2');
    if (!CurrentSession.collection) return false;

    let filter = CurrentSession.documentsFilter || '{}';
    Session.set('showLoader', true);

    CurrentSession.documentsReady = false;
    Meteor.call('getDocuments', CurrentSession.database._id, CurrentSession.collection.name, filter, CurrentSession.documentsPagination, CurrentSession.documentsRandomSeed, function(error, result) {

      if (error || result == false || typeof result == 'undefined') {
        alert('Connection failed or filter incorrect...');
        return false;
      }
      CurrentSession.documents = result.docs;
      CurrentSession.documentsCount = result.count;
      CurrentSession.documentsReady = true;
      Session.set('showLoader', false);

    });
  });
});

Template.Documents.helpers({
  documentsReady() {
    return CurrentSession.documentsReady;
  },
  filterData() {
    return {
      collection: CurrentSession.collection,
      filter: CurrentSession.documentsFilter
    }
  },

  viewParameters() {
    if (!ConnectionStructureSubscription.ready()) return false;
    let documents = CurrentSession.documents || false;
    if (!documents) return false;

    let index = (CurrentSession.documentsPagination * CurrentSession.documentsPaginationLimit) + 1;
    _.each(documents, function(doc) {
      doc.drMongoIndex = index++ + '.';
    });
    return {documents: documents};
  },

  collection() {
    return CurrentSession.collection;
  },

  savedFilters() {
    if (!CurrentSession.collection) return false;
    return FilterHistory.find({name: {$ne: null}, collection_id: CurrentSession.collection._id});
  }
});

Template.Documents.events({
  'click #refresh-documents'(event, templateInstance) {
    refreshDocuments();
  },

  'click #reset-filter'(event, templateInstance) {
    FlowRouter.go(getFilterRoute());
  },

  'click #save-filter'(event, templateInstance) {
    event.preventDefault();
    event.stopImmediatePropagation();

    let filterId = FlowRouter.getParam('filter');
    if (filterId) {
      let name = prompt('Give filter a name to save it:');
      FilterHistory.update(filterId, {$set: {name: name}});
    } else {
      sAlert.info('No filter set.')
    }
  },

  'click #saved-filters li a:not(#save-filter)'(event, templateInstance) {
    event.preventDefault();
    FlowRouter.go(getFilterRoute(this._id));
  },

  'click #insert-document'(event, templateInstance) {
    event.preventDefault();
    event.stopImmediatePropagation();
    Session.set('DocumentInsertModal', {
      connectionId: CurrentSession.connection._id,
      databaseId: CurrentSession.database._id,
      collectionId: CurrentSession.collection._id
    });
    $('#DocumentInsertModal').modal('show');
  },

  'click #collection-dashboard'(event, templateInstance) {
    event.preventDefault();
    event.stopImmediatePropagation();
    Session.set('CollectionDashboardModal', {
      connectionId: CurrentSession.connection._id,
      databaseId: CurrentSession.database._id,
      collectionId: CurrentSession.collection._id
    });
    $('#CollectionDashboardModal').modal('show');
  }

});
<|endoftext|>


<commit_before>import React from 'react'
import { useConfig } from 'base-shell/lib/providers/Config'
import * as BS from "react-bootstrap";
import RMWLogo from "../../assets/rmw.svg";
import { useMenu } from 'bootstrap-shell/lib/providers/Menu'
import { GiHamburgerMenu } from "react-icons/gi"

const Menu = ({ brand }) => {
  const { appConfig } = useConfig();
  const { routes } = appConfig || {};
  const { menu } = appConfig || {};
  const { globalBrand, MenuRight } = menu || {};
  const menuContext = useMenu();

  // Replace with Provider
  const [toggleMenu, setToggleMenu] = React.useState(false);

  const _brand = brand ? brand : globalBrand;

  return
    <BS.Navbar bg="dark">
      <BS.Container fluid className="justify-content-space-between">
        <BS.Col>
          <BS.Navbar>
            <BS.Navbar.Brand href="#home" className="text-white">
              {_brand ? _brand : }
            </BS.Navbar.Brand>
            <BS.Navbar.Toggle aria-controls="basic-navbar-nav" />
            <BS.Navbar.Collapse>
              <BS.Nav className="d-none d-md-flex d-lg-flex">
                {routes.filter(({ generateHeaderLink }) => generateHeaderLink).map(({ path, displayName }) => {
                  return <BS.Nav.Link key={displayName} href={path} className="text-light">{displayName}</BS.Nav.Link>
                })}
              </BS.Nav>
            </BS.Navbar.Collapse>
          </BS.Navbar>
        </BS.Col>
        <BS.Col>
          <BS.Navbar className="d-none d-md-flex d-lg-flex justify-content-end">
            {MenuRight && <MenuRight />}
          </BS.Navbar>
          {/*Mobile Menu*/}
          <BS.Navbar className="d-sm-flex d-md-none d-lg-none justify-content-end">
            <GiHamburgerMenu className="text-white d-sm-block d-md-none d-lg-none" onClick={() => setToggleMenu(!toggleMenu)} />
          </BS.Navbar>
        </BS.Col>
      </BS.Container>
    </BS.Navbar>
    {/*Mobile Menu*/}
    <BS.Col className="top-0 float-right bg-dark p-2 overflow-hidden" style={{ maxHeight: toggleMenu ? 1000 : 0, transition: "max-height 2s ease-in-out" }}>
      {routes.filter(({ generateHeaderLink }) => generateHeaderLink).map(({ path, displayName }) => {
        return <BS.Nav.Link key={displayName} href={path} className="text-light">{displayName}</BS.Nav.Link>
      })}
      {MenuRight && <MenuRight />}
    </BS.Col>

}

export default Menu
<commit_msg>change transition style<commit_after>import React from 'react'
import { useConfig } from 'base-shell/lib/providers/Config'
import * as BS from "react-bootstrap";
import RMWLogo from "../../assets/rmw.svg";
import { useMenu } from 'bootstrap-shell/lib/providers/Menu'
import { GiHamburgerMenu } from "react-icons/gi"

const Menu = ({ brand }) => {
  const { appConfig } = useConfig();
  const { routes } = appConfig || {};
  const { menu } = appConfig || {};
  const { globalBrand, MenuRight } = menu || {};
  const menuContext = useMenu();

  // Replace with Provider
  const [toggleMenu, setToggleMenu] = React.useState(false);

  const _brand = brand ? brand : globalBrand;

  return
    <BS.Navbar bg="dark">
      <BS.Container fluid className="justify-content-space-between">
        <BS.Col>
          <BS.Navbar>
            <BS.Navbar.Brand href="#home" className="text-white">
              {_brand ? _brand : }
            </BS.Navbar.Brand>
            <BS.Navbar.Toggle aria-controls="basic-navbar-nav" />
            <BS.Navbar.Collapse>
              <BS.Nav className="d-none d-md-flex d-lg-flex">
                {routes.filter(({ generateHeaderLink }) => generateHeaderLink).map(({ path, displayName }) => {
                  return <BS.Nav.Link key={displayName} href={path} className="text-light">{displayName}</BS.Nav.Link>
                })}
              </BS.Nav>
            </BS.Navbar.Collapse>
          </BS.Navbar>
        </BS.Col>
        <BS.Col>
          <BS.Navbar className="d-none d-md-flex d-lg-flex justify-content-end">
            {MenuRight && <MenuRight />}
          </BS.Navbar>
          {/*Mobile Menu*/}
          <BS.Navbar className="d-sm-flex d-md-none d-lg-none justify-content-end">
            <GiHamburgerMenu className="text-white d-sm-block d-md-none d-lg-none" onClick={() => setToggleMenu(!toggleMenu)} />
          </BS.Navbar>
        </BS.Col>
      </BS.Container>
    </BS.Navbar>
    {/*Mobile Menu*/}
    <BS.Col className="top-0 float-right bg-dark p-2 overflow-hidden" style={{ maxHeight: toggleMenu ? 1000 : 0, transition: "max-height 2s linear" }}>
      {routes.filter(({ generateHeaderLink }) => generateHeaderLink).map(({ path, displayName }) => {
        return <BS.Nav.Link key={displayName} href={path} className="text-light">{displayName}</BS.Nav.Link>
      })}
      {MenuRight && <MenuRight />}
    </BS.Col>

}

export default Menu
<|endoftext|>


<commit_before>/**
 * @ngdoc module
 * @name material.components.form
 * @description
 * Form
 */
angular.module('material.components.form', [])
  .directive('materialInputGroup', [
    materialInputGroupDirective
  ])
  .directive('input', [
    groupInputDirective
  ]);

/**
 * @ngdoc directive
 * @name materialInputGroup
 * @module material.components.form
 * @restrict E
 * @description
 * Put the `<material-input-group>` directive as the parent of an `<input>` element to
 * add proper styling for the input.
 *
 * @usage
 * <hljs lang="html">
 * <material-input-group>
 *   <input type="text" ng-model="myText">
 * </material-input-group
 * </hljs>
 */
function materialInputGroupDirective() {
  return {
    restrict: 'CE',
    controller: ['$element', function($element) {
      this.setFocused = function(isFocused) {
        $element.toggleClass('material-input-focused', !!isFocused);
      };
      this.setHasValue = function(hasValue) {
        $element.toggleClass('material-input-has-value', !!hasValue);
      };
    }]
  };
}

function groupInputDirective() {
  return {
    restrict: 'E',
    require: ['^?materialInputGroup', '?ngModel'],
    link: function(scope, element, attr, ctrls) {
      var inputGroupCtrl = ctrls[0];
      var ngModelCtrl = ctrls[1];
      if (!inputGroupCtrl) {
        return;
      }

      // When the input value changes, check if it "has" a value, and
      // set the appropriate class on the input group
      if (ngModelCtrl) {
        //Add a $formatter so we don't use up the render function
        ngModelCtrl.$formatters.push(function(value) {
          inputGroupCtrl.setHasValue(!!value);
          return value;
        });
      }
      element.on('input', function() {
        inputGroupCtrl.setHasValue(!!element.val());
      });

      // When the input focuses, add the focused class to the group
      element.on('focus', function(e) {
        inputGroupCtrl.setFocused(true);
      });
      // When the input blurs, remove the focused class from the group
      element.on('blur', function(e) {
        inputGroupCtrl.setFocused(false);
      });

      scope.$on('$destroy', function() {
        inputGroupCtrl.setFocused(false);
        inputGroupCtrl.setHasValue(false);
      });
    }
  };
}
<commit_msg>refactor(form) - exclude directive from docs<commit_after>/**
 * @ngdoc module
 * @name material.components.form
 * @description
 * Form
 */
angular.module('material.components.form', [])
  .directive('materialInputGroup', [
    materialInputGroupDirective
  ])
  .directive('input', [
    groupInputDirective
  ]);

/**
 * @private
 * @ngdoc directive
 * @name materialInputGroup
 * @module material.components.form
 * @restrict E
 * @description
 * Put the `<material-input-group>` directive as the parent of an `<input>` element to
 * add proper styling for the input.
 *
 * @usage
 * <hljs lang="html">
 * <material-input-group>
 *   <input type="text" ng-model="myText">
 * </material-input-group
 * </hljs>
 */
function materialInputGroupDirective() {
  return {
    restrict: 'CE',
    controller: ['$element', function($element) {
      this.setFocused = function(isFocused) {
        $element.toggleClass('material-input-focused', !!isFocused);
      };
      this.setHasValue = function(hasValue) {
        $element.toggleClass('material-input-has-value', !!hasValue);
      };
    }]
  };
}

function groupInputDirective() {
  return {
    restrict: 'E',
    require: ['^?materialInputGroup', '?ngModel'],
    link: function(scope, element, attr, ctrls) {
      var inputGroupCtrl = ctrls[0];
      var ngModelCtrl = ctrls[1];
      if (!inputGroupCtrl) {
        return;
      }

      // When the input value changes, check if it "has" a value, and
      // set the appropriate class on the input group
      if (ngModelCtrl) {
        //Add a $formatter so we don't use up the render function
        ngModelCtrl.$formatters.push(function(value) {
          inputGroupCtrl.setHasValue(!!value);
          return value;
        });
      }
      element.on('input', function() {
        inputGroupCtrl.setHasValue(!!element.val());
      });

      // When the input focuses, add the focused class to the group
      element.on('focus', function(e) {
        inputGroupCtrl.setFocused(true);
      });
      // When the input blurs, remove the focused class from the group
      element.on('blur', function(e) {
        inputGroupCtrl.setFocused(false);
      });

      scope.$on('$destroy', function() {
        inputGroupCtrl.setFocused(false);
        inputGroupCtrl.setHasValue(false);
      });
    }
  };
}
<|endoftext|>