<commit_before>import React, {PropTypes} from 'react'
import {Link, withRouter} from 'react-router'
import {connect} from 'react-redux'

import Authorized, {EDITOR_ROLE} from 'src/auth/Authorized'

import Dropdown from 'shared/components/Dropdown'
import QuestionMarkTooltip from 'shared/components/QuestionMarkTooltip'

const kapacitorDropdown = (
  kapacitors,
  source,
  router,
  setActiveKapacitor,
  handleDeleteKapacitor
) => {
  if (!kapacitors || kapacitors.length === 0) {
    return (
      <Authorized requiredRole={EDITOR_ROLE}>
        <Link
          to={`/sources/${source.id}/kapacitors/new`}
          className="btn btn-xs btn-default"
        >
           Add Config
        </Link>
      </Authorized>
    )
  }
  const kapacitorItems = kapacitors.map(k => {
    return {
      text: k.name,
      resource: `/sources/${source.id}/kapacitors/${k.id}`,
      kapacitor: k,
    }
  })

  const activeKapacitor = kapacitors.find(k => k.active)

  let selected = ''
  if (activeKapacitor) {
    selected = activeKapacitor.name
  } else {
    selected = kapacitorItems[0].text
  }

  return (
    <Authorized
      requiredRole={EDITOR_ROLE}
      propsOverride={{addNew: null, actions: null}}
    >
      <Dropdown
        className="dropdown-260"
        buttonColor="btn-primary"
        buttonSize="btn-xs"
        items={kapacitorItems}
        onChoose={setActiveKapacitor}
        addNew={{
          url: `/sources/${source.id}/kapacitors/new`,
          text: 'Add Kapacitor',
        }}
        actions={[
          {
            icon: 'pencil',
            text: 'edit',
            handler: item => {
              router.push(`${item.resource}/edit`)
            },
          },
          {
            icon: 'trash',
            text: 'delete',
            handler: item => {
              handleDeleteKapacitor(item.kapacitor)
            },
            confirmable: true,
          },
        ]}
        selected={selected}
      />
    </Authorized>
  )
}

const InfluxTable = ({
  source,
  router,
  sources,
  location,
  setActiveKapacitor,
  handleDeleteSource,
  handleDeleteKapacitor,
  isUsingAuth,
  me,
}) =>

            {isUsingAuth
              ? `InfluxDB Sources from ${me.currentOrganization.name}`
              : 'InfluxDB Sources'}

          <Authorized requiredRole={EDITOR_ROLE}>
            <Link
              to={`/sources/${source.id}/manage-sources/new`}
              className="btn btn-sm btn-primary"
            >
               Add Source
            </Link>
          </Authorized>

                Source Name & Host

                  Active Kapacitor{' '}
                  <QuestionMarkTooltip
                    tipID="kapacitor-node-helper"
                    tipContent={
                      '
Kapacitor Configurations are
scoped per InfluxDB Source.
Only one can be active at a time.
'
                    }
                  />

              {sources.map(s => {
                return (

                      {s.id === source.id
                        ?

                            Connected

                        : <Link
                            className="btn btn-default btn-xs source-table--connect"
                            to={`/sources/${s.id}/hosts`}
                          >
                            Connect
                          </Link>}

                        <Authorized
                          requiredRole={EDITOR_ROLE}
                          replaceWithIfNotAuthorized={

                              {s.name}

                          }
                        >
                          <Link
                            to={`${location.pathname}/${s.id}/edit`}
                            className={
                              s.id === source.id ? 'link-success' : null
                            }
                          >

                              {s.name}

                            {s.default ? ' (Default)' : null}
                          </Link>
                        </Authorized>

                        {s.url}

                      <Authorized requiredRole={EDITOR_ROLE}>

                          Delete Source

                      </Authorized>

                      {kapacitorDropdown(
                        s.kapacitors,
                        s,
                        router,
                        setActiveKapacitor,
                        handleDeleteKapacitor
                      )}

                )
              })}

const {array, bool, func, shape, string} = PropTypes

InfluxTable.propTypes = {
  handleDeleteSource: func.isRequired,
  location: shape({
    pathname: string.isRequired,
  }).isRequired,
  router: PropTypes.shape({
    push: PropTypes.func.isRequired,
  }).isRequired,
  source: shape({
    id: string.isRequired,
    links: shape({
      proxy: string.isRequired,
      self: string.isRequired,
    }),
  }),
  sources: array.isRequired,
  setActiveKapacitor: func.isRequired,
  handleDeleteKapacitor: func.isRequired,
  me: shape({
    currentOrganization: shape({
      id: string.isRequired,
      name: string.isRequired,
    }),
  }),
  isUsingAuth: bool,
}

const mapStateToProps = ({auth: {isUsingAuth, me}}) => ({isUsingAuth, me})

export default connect(mapStateToProps)(withRouter(InfluxTable))
<commit_msg>Add emphasis & fix preposition on Sources page _for_ <Organization><commit_after>import React, {PropTypes} from 'react'
import {Link, withRouter} from 'react-router'
import {connect} from 'react-redux'

import Authorized, {EDITOR_ROLE} from 'src/auth/Authorized'

import Dropdown from 'shared/components/Dropdown'
import QuestionMarkTooltip from 'shared/components/QuestionMarkTooltip'

const kapacitorDropdown = (
  kapacitors,
  source,
  router,
  setActiveKapacitor,
  handleDeleteKapacitor
) => {
  if (!kapacitors || kapacitors.length === 0) {
    return (
      <Authorized requiredRole={EDITOR_ROLE}>
        <Link
          to={`/sources/${source.id}/kapacitors/new`}
          className="btn btn-xs btn-default"
        >
           Add Config
        </Link>
      </Authorized>
    )
  }
  const kapacitorItems = kapacitors.map(k => {
    return {
      text: k.name,
      resource: `/sources/${source.id}/kapacitors/${k.id}`,
      kapacitor: k,
    }
  })

  const activeKapacitor = kapacitors.find(k => k.active)

  let selected = ''
  if (activeKapacitor) {
    selected = activeKapacitor.name
  } else {
    selected = kapacitorItems[0].text
  }

  return (
    <Authorized
      requiredRole={EDITOR_ROLE}
      propsOverride={{addNew: null, actions: null}}
    >
      <Dropdown
        className="dropdown-260"
        buttonColor="btn-primary"
        buttonSize="btn-xs"
        items={kapacitorItems}
        onChoose={setActiveKapacitor}
        addNew={{
          url: `/sources/${source.id}/kapacitors/new`,
          text: 'Add Kapacitor',
        }}
        actions={[
          {
            icon: 'pencil',
            text: 'edit',
            handler: item => {
              router.push(`${item.resource}/edit`)
            },
          },
          {
            icon: 'trash',
            text: 'delete',
            handler: item => {
              handleDeleteKapacitor(item.kapacitor)
            },
            confirmable: true,
          },
        ]}
        selected={selected}
      />
    </Authorized>
  )
}

const InfluxTable = ({
  source,
  router,
  sources,
  location,
  setActiveKapacitor,
  handleDeleteSource,
  handleDeleteKapacitor,
  isUsingAuth,
  me,
}) =>

            {isUsingAuth
              ?
                  InfluxDB Sources for {me.currentOrganization.name}

              : InfluxDB Sources}

          <Authorized requiredRole={EDITOR_ROLE}>
            <Link
              to={`/sources/${source.id}/manage-sources/new`}
              className="btn btn-sm btn-primary"
            >
               Add Source
            </Link>
          </Authorized>

                Source Name & Host

                  Active Kapacitor{' '}
                  <QuestionMarkTooltip
                    tipID="kapacitor-node-helper"
                    tipContent={
                      '
Kapacitor Configurations are
scoped per InfluxDB Source.
Only one can be active at a time.
'
                    }
                  />

              {sources.map(s => {
                return (

                      {s.id === source.id
                        ?

                            Connected

                        : <Link
                            className="btn btn-default btn-xs source-table--connect"
                            to={`/sources/${s.id}/hosts`}
                          >
                            Connect
                          </Link>}

                        <Authorized
                          requiredRole={EDITOR_ROLE}
                          replaceWithIfNotAuthorized={

                              {s.name}

                          }
                        >
                          <Link
                            to={`${location.pathname}/${s.id}/edit`}
                            className={
                              s.id === source.id ? 'link-success' : null
                            }
                          >

                              {s.name}

                            {s.default ? ' (Default)' : null}
                          </Link>
                        </Authorized>

                        {s.url}

                      <Authorized requiredRole={EDITOR_ROLE}>

                          Delete Source

                      </Authorized>

                      {kapacitorDropdown(
                        s.kapacitors,
                        s,
                        router,
                        setActiveKapacitor,
                        handleDeleteKapacitor
                      )}

                )
              })}

const {array, bool, func, shape, string} = PropTypes

InfluxTable.propTypes = {
  handleDeleteSource: func.isRequired,
  location: shape({
    pathname: string.isRequired,
  }).isRequired,
  router: PropTypes.shape({
    push: PropTypes.func.isRequired,
  }).isRequired,
  source: shape({
    id: string.isRequired,
    links: shape({
      proxy: string.isRequired,
      self: string.isRequired,
    }),
  }),
  sources: array.isRequired,
  setActiveKapacitor: func.isRequired,
  handleDeleteKapacitor: func.isRequired,
  me: shape({
    currentOrganization: shape({
      id: string.isRequired,
      name: string.isRequired,
    }),
  }),
  isUsingAuth: bool,
}

const mapStateToProps = ({auth: {isUsingAuth, me}}) => ({isUsingAuth, me})

export default connect(mapStateToProps)(withRouter(InfluxTable))
<|endoftext|>


<commit_before>Array.prototype.flatMap = function(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};
Array.prototype.distinct = function() {
  return Array.from(new Set(this))
};

function WordTree() {
  this.root = null;
  this.fromPath = function(jsonPath, callback) {
    var thisWt = this
    d3.json(jsonPath, function(error, root) {
      if(error){
        alert(error)
        console.log(error)
      } else {
        thisWt.root = root
        if(callback) callback(thisWt);
      }
    });
    return this;
  };
  this.sameHierarchy = function(h1, h2) {
    return h1.length===h2.length && h1.every((v,i) => v === h2[i])
  };
  this.getRatioRange = function(node) {
    return node.children.map(c =>this.getRatioRange(c))
                    .concat({"min":node.density, "max":node.density})
                    .reduce((p1, p2)=> r = {"min":p1.min<p2.min?p1.min:p2.min, "max":p1.max>p2.max?p1.max:p2.max});
  };

  this.toLeafOnlyHierarchy = function(node, level = 10) {
    var ret = {};
    ret.name=node.name;
    ret.size=node.size;
    ret.docCount=node.size;
    ret.id=node.hierarchy.join(",");
    ret.childrenHidden=node.childrenHidden;
    ret.leaf=node.leaf;
    ret.isWord=false;

    var index = node.words.length;
    var length = node.words.length;
    if(node.children == 0)
    	ret.children = node.words.map(w => r = {"name":w, "docCount":node.size , "noCount":(index<length)
                                                , "size":(node.size * ((index--)+length*0.2)/(1.2*length))|0
                                                , "id":ret.id+":"+w, "isWord":true}
                                     )

    else
        ret.children = [];

    ret.children = ret.children.concat(node.children.map(c => this.toLeafOnlyHierarchy(c, level - 1)))
    return ret;
  };
  this.toFullHierarchy = function(node) {
    var ret = {};
    ret.name=node.name;
    ret.size=node.size;

    ret.children = node.words.map(w => r = {"name":w, "docCount":node.size , "size":node.size })

    ret.children = ret.children.concat(node.children.map(c => this.toFullHierarchy(c)))
    return ret;
  };
  this.slice = function(node, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, parentVisible) {
    var nodeId = node.hierarchy.join(",");
    var parentId = node.hierarchy.slice(0, node.hierarchy.length-1).join(",");
    var isSelected = selectedNodes.includes(nodeId)
    var isCollapsed = collapsedNodes.includes(nodeId)
    var isExpanded = expandedNodes.includes(nodeId)
    var isParentExpanded = expandedNodes.includes(parentId) && parentVisible
    var isTagged = Boolean(taggedNodes[nodeId]) && taggedNodes[nodeId].length > 0
    var removedByTag =
          (!isTagged && !includeNoTag)
          | ( isTagged && Object.keys(tags).filter(t => tags[t].withinSearch && taggedNodes[nodeId].includes(t)).length == 0 )
    var matchingTag = isTagged && Object.keys(tags).filter(t => tags[t].withinSearch && taggedNodes[nodeId].includes(t)).length > 0
    var ignoreLevel = (!isParentExpanded) &&
                      ( node.hierarchy.length<startLevel
                         || node.size > maxSize
                         || node.density < minRatio || node.density > maxRatio
                         || Boolean(wordFilter) && node.words.filter(p => p.match(wordFilter)).length == 0
                         || removedByTag
                      )
    var canSplit = node.children.length>1
                   && !isCollapsed
                   && ((node.children.filter(c => c.size<minSize).length == 0
                       && node.hierarchy.length<endLevel
                       && !(matchingTag)
                      ) || isExpanded)
    //Looking for focus node
    if(node.hierarchy.length < hierarchy.length) {
      var child = node.children.filter(c => c.hierarchy.slice(0, node.hierarchy.length+1).join(",") === hierarchy.slice(0, node.hierarchy.length+1).join(","))[0]
      return this.slice(child, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, false);
    }
    //focus node found
    else if(node.hierarchy.length==hierarchy.length && node.hierarchy.length<startLevel)
      return {"hierarchy":node.hierarchy, "name":node.name, "size":node.size, "words":[]
              , "children":node.children.flatMap(c => this.slice(c, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, true))
              , "childrenHidden":false, "leaf":node.children.length==0, "selected":isSelected}
    //Ignoring nodes out of limits but giving a chance to children
    else if(ignoreLevel && canSplit) {
      return node.children.flatMap(c => this.slice(c, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, false))
    }
    else if(!ignoreLevel)
    {
      return {"hierarchy":node.hierarchy, "name":node.name, "size":node.size, "words":node.words
              , "children": canSplit?node.children.flatMap(c => [].concat(this.slice(c, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, true))):[]
              , "childrenHidden":(node.children.length>0 && !canSplit), "leaf":node.children.length==0, "selected":isSelected}
    }
    return [];
  }

}
<commit_msg>adding changes for new phrase format<commit_after>Array.prototype.flatMap = function(lambda) {
  return Array.prototype.concat.apply([], this.map(lambda));
};
Array.prototype.distinct = function() {
  return Array.from(new Set(this))
};

function WordTree() {
  this.root = null;
  this.fromPath = function(jsonPath, callback) {
    var thisWt = this
    d3.json(jsonPath, function(error, root) {
      if(error){
        alert(error)
        console.log(error)
      } else {
	thisWt.root = root;
        if(callback) callback(thisWt);
      }
    });
    return this;
  };
  this.sameHierarchy = function(h1, h2) {
    return h1.length===h2.length && h1.every((v,i) => v === h2[i])
  };
  this.getRatioRange = function(node) {
    return node.children.map(c =>this.getRatioRange(c))
                    .concat({"min":node.density, "max":node.density})
                    .reduce((p1, p2)=> r = {"min":p1.min<p2.min?p1.min:p2.min, "max":p1.max>p2.max?p1.max:p2.max});
  };

  this.toLeafOnlyHierarchy = function(node, level = 10) {
    var ret = {};
    ret.name=node.name;
    ret.size=node.size;
    ret.docCount=node.size;
    ret.id=node.hierarchy.join(",");
    ret.childrenHidden=node.childrenHidden;
    ret.leaf=node.leaf;
    ret.isWord=false;

    var index = node.words.length;
    var length = node.words.length;
    if(node.children == 0)
    	ret.children = node.words.map(w => r = {"name":w, "docCount":node.size , "noCount":(index<length)
                                                , "size":(node.size * ((index--)+length*0.2)/(1.2*length))|0
                                                , "id":ret.id+":"+w, "isWord":true}
                                     )

    else
        ret.children = [];

    ret.children = ret.children.concat(node.children.map(c => this.toLeafOnlyHierarchy(c, level - 1)))
    return ret;
  };

  this.toFullHierarchy = function(node) {
    var ret = {};
    ret.name=node.name;
    ret.size=node.size;

    ret.children = node.words.map(w => r = {"name":w, "docCount":node.size , "size":node.size })

    ret.children = ret.children.concat(node.children.map(c => this.toFullHierarchy(c)))
    return ret;
  };
  this.slice = function(node, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, parentVisible) {
    var nodeId = node.hierarchy.join(",");
    var parentId = node.hierarchy.slice(0, node.hierarchy.length-1).join(",");
    var isSelected = selectedNodes.includes(nodeId)
    var isCollapsed = collapsedNodes.includes(nodeId)
    var isExpanded = expandedNodes.includes(nodeId)
    var isParentExpanded = expandedNodes.includes(parentId) && parentVisible
    var isTagged = Boolean(taggedNodes[nodeId]) && taggedNodes[nodeId].length > 0
    var removedByTag =
          (!isTagged && !includeNoTag)
          | ( isTagged && Object.keys(tags).filter(t => tags[t].withinSearch && taggedNodes[nodeId].includes(t)).length == 0 )
    var matchingTag = isTagged && Object.keys(tags).filter(t => tags[t].withinSearch && taggedNodes[nodeId].includes(t)).length > 0
    var ignoreLevel = (!isParentExpanded) &&
                      ( node.hierarchy.length<startLevel
                         || node.size > maxSize
                         || node.density < minRatio || node.density > maxRatio
                         || Boolean(wordFilter) && node.words.filter(p => p.match(wordFilter)).length == 0
                         || removedByTag
                      )
    var canSplit = node.children.length>1
                   && !isCollapsed
                   && ((node.children.filter(c => c.size<minSize).length == 0
                       && node.hierarchy.length<endLevel
                       && !(matchingTag)
                      ) || isExpanded)
    //Looking for focus node
    if(node.hierarchy.length < hierarchy.length) {
      var child = node.children.filter(c => c.hierarchy.slice(0, node.hierarchy.length+1).join(",") === hierarchy.slice(0, node.hierarchy.length+1).join(","))[0]
      return this.slice(child, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, false);
    }
    //focus node found
    else if(node.hierarchy.length==hierarchy.length && node.hierarchy.length<startLevel)
      return {"hierarchy":node.hierarchy, "name":node.name, "size":node.size, "words":[]
              , "children":node.children.flatMap(c => this.slice(c, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, true))
              , "childrenHidden":false, "leaf":node.children.length==0, "selected":isSelected}
    //Ignoring nodes out of limits but giving a chance to children
    else if(ignoreLevel && canSplit) {
      return node.children.flatMap(c => this.slice(c, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, false))
    }
    else if(!ignoreLevel)
    {
      return {"hierarchy":node.hierarchy, "name":node.name, "size":node.size, "words":node.words
              , "children": canSplit?node.children.flatMap(c => [].concat(this.slice(c, hierarchy, startLevel, endLevel, minSize, maxSize, minRatio, maxRatio, wordFilter, expandedNodes, collapsedNodes, selectedNodes, taggedNodes, tags, includeNoTag, true))):[]
              , "childrenHidden":(node.children.length>0 && !canSplit), "leaf":node.children.length==0, "selected":isSelected}
    }
    return [];
  };

}
<|endoftext|>


<commit_before>;
var scripts = scripts || {};

scripts.Common = {

	initializeCache: function() {

		var $cache = {};

		$cache.html = $('html');
		$cache.body = $('body');
		$cache.cloneWrapper = $('.js-clone-wrapper');

		this.$cache = $cache;
	},

	detecting: function () {
		this.$cache.html.removeClass('no-js');
	},

	isModernBrowser: function () {
		if ( // modernizer alternative
		'querySelector' in document &&
		'localStorage' in window &&
		'addEventListener' in window
		) {
			return true;
		} else {
			return false;
		}
	},

	globalInit: function() {
		this.$cache.body.on('click', ".weiss-form__input-act input[type='checkbox']", function() {
			var self = $(this);

			self.parent().toggleClass('js-ico-checked');
			self.parents('.weiss-form__input-w-ico').toggleClass('weiss-form__input-act_' + self.data('input-type') );
		});
	},

	jsPlaceholderInit: function () {
		$('input[placeholder], textarea[placeholder]').placeholder();
	},

	toggleFormSection: function(enableOnValue) {
		var trueValue = (typeof enableOnValue === "undefined") ? "other" : enableOnValue,
			ctrlInput = $(".js-related-control").find("input[type='checkbox'], select");

		function enabled(el) {
			return (el.value == "other" || el.checked);
		}

		function toggleSection(el, checked) {
			var sectionBlc = el.parents(".js-related-control").next(".js-related-section");

			sectionBlc[checked ? "removeClass" : "addClass"]("i-inputs_disabled");
			sectionBlc.find("input, select, textarea").attr("disabled", !checked);
		}

		ctrlInput.each(function() {
			toggleSection($(this), enabled(this));
		});

		ctrlInput.on('change', function() {
			toggleSection($(this), enabled(this));
		});
	},

	inputActions: function() {
		var $inputs = $('input[data-inp-act], select[data-inp-act], textarea[data-inp-act]');

		$inputs.wrap("");
		$('').insertAfter($inputs);

		$inputs.each(function() {
			var $input = $(this),
				$inputName = $input.attr('name'),
				$inputActions = $input.data('inp-act').split(',');

			$.each($inputActions, function (key, value) {
				var title;

				switch (value) {
					case "hidden":
						var title = 'Поле містить приховану інформацію';
						break;
					case "unclear":
						var title = 'Поле містить нерозбірливу інформацію';
						break;
				}

				$($input.next('.weiss-form__input-w-ico__ico'))
					.append('' +
					'<input type="checkbox" name="'+ $inputName.replace(/\]$/, "") + '_' + value +']" tabindex="-1" data-input-type="' + value +'" />');
			});
		});
	},

	inputActionsReInit: function(container) {
		var input = container.find(".weiss-form__input-act input[type='checkbox']");

		input.each(function() {
			var self =$(this);

			if (self.checked) {
				self.parent().addClass('js-ico-checked');
				self.parents('.weiss-form__input-w-ico').addClass('weiss-form__input-act_' + self.data('input-type') );
			} else {
				self.parent().removeClass('js-ico-checked');
				self.parents('.weiss-form__input-w-ico').removeClass('weiss-form__input-act_' + self.data('input-type') );
			}
		});
	},

	autoCompliteInit: function () {
		var autoCompliteData = {
				"#general__last-name": scripts.Data.autocompliteData.lastname,
				"#general__name": scripts.Data.autocompliteData.firstname,
				"#general__patronymic": scripts.Data.autocompliteData.patronymic,
				".general__place_district": scripts.Data.autocompliteData.districts,
				"#general__post_office": scripts.Data.autocompliteData.offices,
				".vehicle__35__brand": scripts.Data.autocompliteData.cars,
				".vehicle__36__brand": scripts.Data.autocompliteData.trucks,
				".vehicle__37__brand": scripts.Data.autocompliteData.boats,
				".vehicle__39__brand": scripts.Data.autocompliteData.motos
			},
			addAutoComplite = function (selector, data) {
				$(selector).autocomplete({
					source: function(request, response) {
						var results = $.ui.autocomplete.filter(data, request.term);
						response(results.slice(0, 7));
					},
					appendTo: $(selector).parent()
				});
			};

		$.each(autoCompliteData, addAutoComplite);

		this.$cache.cloneWrapper
			.on('clone_before_clone', function (event, toclone) {
				$.each(autoCompliteData, function(element, data) {
					var $elem = toclone.find(element);

					if ($elem.length > 0)
						$elem.autocomplete('destroy');
				});
			})
			.on('clone_after_append', function (event, toclone, newclone) {
				//newclone.addClass('js-cloned');
				var $container = $(newclone).parent('.js-clone-wrapper');

				$.each(autoCompliteData, function(element, data) {
					var $elem = $container.find(element);

					if ($elem.length > 0) {
						addAutoComplite($elem, data);
					}
				});
			});
	},

	cloneyaInit: function () {
		this.$cache.cloneWrapper.cloneya({
			serializeID: false,
			cloneThis: '.js-toclone',
			cloneButton: '.js-clone',
			deleteButton: '.js-clone-delete',
			ignore: '.weiss-form__msg, .js-clone-ignore, .ui-autocomplete'
		});
	},

	dateSelectBoxesInit: function () {
		$().dateSelectBoxes({
			monthElement: $('#declaration__date_month'),
			dayElement: $('#declaration__date_day'),
			yearElement: $('#declaration__date_year'),
			keepLabels: true,
			yearLabel: 'Рік',
			monthLabel: 'Місяць',
			dayLabel: 'День'
		});
	},

	jqueryValidateInit: function () {

		$.validator.addMethod("lettersonly", function(value, element) {
			return this.optional(element) || /^[а-яА-ЯёЁіІїЇєЄ’`'ґҐa-zA-Z]+$/i.test(value);
		}, "Tільки букви, будьласка");

		$.validator.addMethod("lastnameonly", function(value, element) {
			return this.optional(element) || /^[а-яА-ЯёЁіІїЇєЄ’`'ґҐa-zA-Z\-]+$/i.test(value);
		}, "Tільки букви, будьласка");

		$.validator.addMethod("fractdigitsonly", function(value, element) {
			return this.optional(element) || /^\d+([\.,]\d+)?$/i.test(value);
		}, "Вводити потрібно лише цифри");

		$.validator.addClassRules({
			'js-is-LettersOnly': {
				lettersonly: true
			},
			'js-is-DigitsOnly': {
				fractdigitsonly: true
			},
			'js-is-lastnameonly': {
				lastnameonly: true
			},
			'js-is-strictDigitsOnly': {
				digits: true
			}
		});

		var $form = $('#form-declaration'),
			validateSettings = {
				errorClass: "js-invalid",
				errorElement: "p",
				errorPlacement: function (error, element) {
					if (element.attr('required')) {
						error.insertBefore(element).addClass('weiss-form__msg weiss-form__msg_error');
					} else {
						error.insertBefore(element).addClass('weiss-form__msg weiss-form__msg_warn');
					}
				},
				focusInvalid: false,
				invalidHandler: function(form, validator) {
					if (!validator.numberOfInvalids())
						return;

					$('html, body').animate({
						scrollTop: $(validator.errorList[0].element).offset().top - 60
					}, 200);

				}
			},
			validateThis = $form.validate(validateSettings),
			current = 0,
			content = $('.js-tab-content');

		this.$cache.body.on('reset', $form, function () {
			$form.validate().resetForm();
		}).on('click', '#intro__isnotdeclaration', function () {
			if($(this).is(':checked')) {
				$form.validate().settings.ignore = "*"; // disable all validation
			} else {
				$form.validate().settings.ignore = "";
			}
		});

		content.hide();
		$(content[0]).show();

		this.$cache.body.on('click', '.js-section-go', function(e) {
			if (!$(this).is('[type="reset"]')) {
				e.preventDefault();
			}

			var self = $(this),
				section = self.data('section-go'),
				goTo = '#section-' + section,
				showSection = function () {
					current = section;
					content.hide();
					$(goTo).fadeIn(400);
					$('html, body').animate({scrollTop:0}, 500);
				};

			if (validateThis.form()) { // this validate only current section. If we skip some sections they dont validating.
				showSection();
			} else {
				return false;
			}
		});

	},

	init: function () {
		var scrpt = this;

		scrpt.initializeCache();
		scrpt.detecting();
		scrpt.globalInit();

		$(function () { // DOM Ready
			var template = Handlebars.compile($('#decl_form_template').html()),
				output = $("#form-wrapper");

			scrpt.$cache.body.on("vulyk.next", function(e, data) {
				scrpt.$cache.html.scrollTop(0);
				output.html(template(data.result.task.data));
				scrpt.jqueryValidateInit();
				scrpt.toggleFormSection();
				scrpt.inputActions();
				scrpt.autoCompliteInit();
				scrpt.cloneyaInit();
				scrpt.dateSelectBoxesInit();
			}).on("vulyk.save", function(e, callback) {
				var $form = $('#form-declaration'),
					data = $form.serializeJSON();

				if ($("#section-4").is(":visible") || $("#intro__isnotdeclaration").is(":checked")) {
					$form.remove();
					callback(data);
				} else {
					scrpt.$cache.html.scrollTop(0);
				}
			}).on("vulyk.skip", function(e, callback) {
				$('#form-declaration').remove();
				callback();
			});
		});

		return scrpt;
	}
};

scripts.Common.init();
<commit_msg>Typo changes, and a good message to show when we are ran out of tasks<commit_after>;
var scripts = scripts || {};

scripts.Common = {

	initializeCache: function() {

		var $cache = {};

		$cache.html = $('html');
		$cache.body = $('body');
		$cache.cloneWrapper = $('.js-clone-wrapper');

		this.$cache = $cache;
	},

	detecting: function () {
		this.$cache.html.removeClass('no-js');
	},

	isModernBrowser: function () {
		if ( // modernizer alternative
		'querySelector' in document &&
		'localStorage' in window &&
		'addEventListener' in window
		) {
			return true;
		} else {
			return false;
		}
	},

	globalInit: function() {
		this.$cache.body.on('click', ".weiss-form__input-act input[type='checkbox']", function() {
			var self = $(this);

			self.parent().toggleClass('js-ico-checked');
			self.parents('.weiss-form__input-w-ico').toggleClass('weiss-form__input-act_' + self.data('input-type') );
		});
	},

	jsPlaceholderInit: function () {
		$('input[placeholder], textarea[placeholder]').placeholder();
	},

	toggleFormSection: function(enableOnValue) {
		var trueValue = (typeof enableOnValue === "undefined") ? "other" : enableOnValue,
			ctrlInput = $(".js-related-control").find("input[type='checkbox'], select");

		function enabled(el) {
			return (el.value == "other" || el.checked);
		}

		function toggleSection(el, checked) {
			var sectionBlc = el.parents(".js-related-control").next(".js-related-section");

			sectionBlc[checked ? "removeClass" : "addClass"]("i-inputs_disabled");
			sectionBlc.find("input, select, textarea").attr("disabled", !checked);
		}

		ctrlInput.each(function() {
			toggleSection($(this), enabled(this));
		});

		ctrlInput.on('change', function() {
			toggleSection($(this), enabled(this));
		});
	},

	inputActions: function() {
		var $inputs = $('input[data-inp-act], select[data-inp-act], textarea[data-inp-act]');

		$inputs.wrap("");
		$('').insertAfter($inputs);

		$inputs.each(function() {
			var $input = $(this),
				$inputName = $input.attr('name'),
				$inputActions = $input.data('inp-act').split(',');

			$.each($inputActions, function (key, value) {
				var title;

				switch (value) {
					case "hidden":
						var title = 'Поле містить приховану інформацію';
						break;
					case "unclear":
						var title = 'Поле містить нерозбірливу інформацію';
						break;
				}

				$($input.next('.weiss-form__input-w-ico__ico'))
					.append('' +
					'<input type="checkbox" name="'+ $inputName.replace(/\]$/, "") + '_' + value +']" tabindex="-1" data-input-type="' + value +'" />');
			});
		});
	},

	inputActionsReInit: function(container) {
		var input = container.find(".weiss-form__input-act input[type='checkbox']");

		input.each(function() {
			var self =$(this);

			if (self.checked) {
				self.parent().addClass('js-ico-checked');
				self.parents('.weiss-form__input-w-ico').addClass('weiss-form__input-act_' + self.data('input-type') );
			} else {
				self.parent().removeClass('js-ico-checked');
				self.parents('.weiss-form__input-w-ico').removeClass('weiss-form__input-act_' + self.data('input-type') );
			}
		});
	},

	autoCompliteInit: function () {
		var autoCompliteData = {
				"#general__last-name": scripts.Data.autocompliteData.lastname,
				"#general__name": scripts.Data.autocompliteData.firstname,
				"#general__patronymic": scripts.Data.autocompliteData.patronymic,
				".general__place_district": scripts.Data.autocompliteData.districts,
				"#general__post_office": scripts.Data.autocompliteData.offices,
				".vehicle__35__brand": scripts.Data.autocompliteData.cars,
				".vehicle__36__brand": scripts.Data.autocompliteData.trucks,
				".vehicle__37__brand": scripts.Data.autocompliteData.boats,
				".vehicle__39__brand": scripts.Data.autocompliteData.motos
			},
			addAutoComplite = function (selector, data) {
				$(selector).autocomplete({
					source: function(request, response) {
						var results = $.ui.autocomplete.filter(data, request.term);
						response(results.slice(0, 7));
					},
					appendTo: $(selector).parent()
				});
			};

		$.each(autoCompliteData, addAutoComplite);

		this.$cache.cloneWrapper
			.on('clone_before_clone', function (event, toclone) {
				$.each(autoCompliteData, function(element, data) {
					var $elem = toclone.find(element);

					if ($elem.length > 0)
						$elem.autocomplete('destroy');
				});
			})
			.on('clone_after_append', function (event, toclone, newclone) {
				//newclone.addClass('js-cloned');
				var $container = $(newclone).parent('.js-clone-wrapper');

				$.each(autoCompliteData, function(element, data) {
					var $elem = $container.find(element);

					if ($elem.length > 0) {
						addAutoComplite($elem, data);
					}
				});
			});
	},

	cloneyaInit: function () {
		this.$cache.cloneWrapper.cloneya({
			serializeID: false,
			cloneThis: '.js-toclone',
			cloneButton: '.js-clone',
			deleteButton: '.js-clone-delete',
			ignore: '.weiss-form__msg, .js-clone-ignore, .ui-autocomplete'
		});
	},

	dateSelectBoxesInit: function () {
		$().dateSelectBoxes({
			monthElement: $('#declaration__date_month'),
			dayElement: $('#declaration__date_day'),
			yearElement: $('#declaration__date_year'),
			keepLabels: true,
			yearLabel: 'Рік',
			monthLabel: 'Місяць',
			dayLabel: 'День'
		});
	},

	jqueryValidateInit: function () {

		$.validator.addMethod("lettersonly", function(value, element) {
			return this.optional(element) || /^[а-яА-ЯёЁіІїЇєЄ’`'ґҐa-zA-Z]+$/i.test(value);
		}, "Tільки букви, будь-ласка");

		$.validator.addMethod("lastnameonly", function(value, element) {
			return this.optional(element) || /^[а-яА-ЯёЁіІїЇєЄ’`'ґҐa-zA-Z\-]+$/i.test(value);
		}, "Tільки букви, будь-ласка");

		$.validator.addMethod("fractdigitsonly", function(value, element) {
			return this.optional(element) || /^\d+([\.,]\d+)?$/i.test(value);
		}, "Вводити потрібно лише цифри");

		$.validator.addClassRules({
			'js-is-LettersOnly': {
				lettersonly: true
			},
			'js-is-DigitsOnly': {
				fractdigitsonly: true
			},
			'js-is-lastnameonly': {
				lastnameonly: true
			},
			'js-is-strictDigitsOnly': {
				digits: true
			}
		});

		var $form = $('#form-declaration'),
			validateSettings = {
				errorClass: "js-invalid",
				errorElement: "p",
				errorPlacement: function (error, element) {
					if (element.attr('required')) {
						error.insertBefore(element).addClass('weiss-form__msg weiss-form__msg_error');
					} else {
						error.insertBefore(element).addClass('weiss-form__msg weiss-form__msg_warn');
					}
				},
				focusInvalid: false,
				invalidHandler: function(form, validator) {
					if (!validator.numberOfInvalids())
						return;

					$('html, body').animate({
						scrollTop: $(validator.errorList[0].element).offset().top - 60
					}, 200);

				}
			},
			validateThis = $form.validate(validateSettings),
			current = 0,
			content = $('.js-tab-content');

		this.$cache.body.on('reset', $form, function () {
			$form.validate().resetForm();
		}).on('click', '#intro__isnotdeclaration', function () {
			if($(this).is(':checked')) {
				$form.validate().settings.ignore = "*"; // disable all validation
			} else {
				$form.validate().settings.ignore = "";
			}
		});

		content.hide();
		$(content[0]).show();

		this.$cache.body.on('click', '.js-section-go', function(e) {
			if (!$(this).is('[type="reset"]')) {
				e.preventDefault();
			}

			var self = $(this),
				section = self.data('section-go'),
				goTo = '#section-' + section,
				showSection = function () {
					current = section;
					content.hide();
					$(goTo).fadeIn(400);
					$('html, body').animate({scrollTop:0}, 500);
				};

			if (validateThis.form()) { // this validate only current section. If we skip some sections they dont validating.
				showSection();
			} else {
				return false;
			}
		});

	},

	init: function () {
		var scrpt = this;

		scrpt.initializeCache();
		scrpt.detecting();
		scrpt.globalInit();

		$(function () { // DOM Ready
			var template = Handlebars.compile($('#decl_form_template').html()),
				output = $("#form-wrapper");

			scrpt.$cache.body.on("vulyk.next", function(e, data) {
				scrpt.$cache.html.scrollTop(0);
				output.html(template(data.result.task.data));
				scrpt.jqueryValidateInit();
				scrpt.toggleFormSection();
				scrpt.inputActions();
				scrpt.autoCompliteInit();
				scrpt.cloneyaInit();
				scrpt.dateSelectBoxesInit();
			}).on("vulyk.save", function(e, callback) {
				var $form = $('#form-declaration'),
					data = $form.serializeJSON();

				if ($("#section-4").is(":visible") || $("#intro__isnotdeclaration").is(":checked")) {
					$form.remove();
					callback(data);
				} else {
					scrpt.$cache.html.scrollTop(0);
				}
			}).on("vulyk.skip", function(e, callback) {
				$('#form-declaration').remove();
				callback();
			}).on("vulyk.task_error", function(e, data) {
				$.magnificPopup.open({
				  items: {
				    src: '
' +
				    		'
Привет!
Первый пакет деклараций обработан.
Сейчас мы внесем немного исправлений и вот-вот тут появится 100 тысяч документов. не забывайте нас, зайдите завтра.
' +
				    	  '
',
                    type: 'inline',
				  }
				});
			});
		});

		return scrpt;
	}
};

scripts.Common.init();
<|endoftext|>


<commit_before>/*global define*/

define(function () {
    return {
        main: function() {
            this.bindPostApi();
        },

        bindPostApi: function() {
            var _this = this;
            $j('#btnSubmit').on('click', function(e) {
                _this.postApiFields();
            });
        },

        /**
         * Make the request to the ps-reg-php server that handles the enroll student REST call
         */
        postApiFields: function() {
            var apiFields = {
                first_name: $j('#first-name').val(),
                middle_name: $j('#middle-name').val(),
                last_name: $j('#last-name').val(),
                ssn: $j('#ssn').val(),
                email: $j('#email-address').val(),
                gender: $j('#gender').val(),
                grade_level: $j('#current-grade').val(),
                number: $j('#home-phone-number').val(),
                mailing_street: $j('#mailing-address').val(),
                mailing_city: $j('#mailing-city').val(),
                mailing_state: $j('#mailing-state option:selected').val(),
                mailing_zip: $j('#mailing-zip').val(),
                residence_street: $j('#residence-address').val(),
                residence_city: $j('#residence-city').val(),
                residence_state: $j('#residence-state option:selected').val(),
                residence_zip: $j('#residence-zip').val(),
                scheduling_reporting_ethnicity: $j('#race').val()
            };

            if ($j('#hisp-latino-yes').is(':checked')) {
                apiFields['federal_ethnicity'] = 'YES'
            } else {
                apiFields['federal_ethnicity'] = 'NO'
            }

            $j.ajax({
                url: 'http://205.125.100.99/enroll',
                type: 'POST',
                crossDomain: true,
                dataType: 'json',
                data: apiFields
            }).done(function(resp) {
                console.dir(resp);
            });
        }
    };
});<commit_msg>Use psit.irondistrict.org instead of image server IP address when making API request.<commit_after>/*global define*/

define(function () {
    return {
        main: function() {
            this.bindPostApi();
        },

        bindPostApi: function() {
            var _this = this;
            $j('#btnSubmit').on('click', function(e) {
                _this.postApiFields();
            });
        },

        /**
         * Make the request to the ps-reg-php server that handles the enroll student REST call
         */
        postApiFields: function() {
            var apiFields = {
                first_name: $j('#first-name').val(),
                middle_name: $j('#middle-name').val(),
                last_name: $j('#last-name').val(),
                ssn: $j('#ssn').val(),
                email: $j('#email-address').val(),
                gender: $j('#gender').val(),
                grade_level: $j('#current-grade').val(),
                number: $j('#home-phone-number').val(),
                mailing_street: $j('#mailing-address').val(),
                mailing_city: $j('#mailing-city').val(),
                mailing_state: $j('#mailing-state option:selected').val(),
                mailing_zip: $j('#mailing-zip').val(),
                residence_street: $j('#residence-address').val(),
                residence_city: $j('#residence-city').val(),
                residence_state: $j('#residence-state option:selected').val(),
                residence_zip: $j('#residence-zip').val(),
                scheduling_reporting_ethnicity: $j('#race').val()
            };

            if ($j('#hisp-latino-yes').is(':checked')) {
                apiFields['federal_ethnicity'] = 'YES'
            } else {
                apiFields['federal_ethnicity'] = 'NO'
            }

            $j.ajax({
                url: 'http://psit.irondistrict.org/enroll',
                type: 'POST',
                crossDomain: true,
                dataType: 'json',
                data: apiFields
            }).done(function(resp) {
                console.dir(resp);
            });
        }
    };
});<|endoftext|>


<commit_before>(function(utils, undefined){

  $(document).ready(function(){
    window.onhashchange = processHash;

    processHash()
  });

  // Called when the hash changes
  function processHash() {

    // Always hide the page action icon when the hash change
    // If we navigated to a new person we need time to load their data
    chrome.extension.sendRequest({
      'type': 'hide'
    });

    // Remove previous search links and show the ajax loader
    var hashParts = utils.getHashParts();

    if( hashParts['view'] == 'ancestor' ) {

      // Get personId and spouseId
      var personId = hashParts['person'];
      var spouseId = hashParts['spouse'];

      // If we have a personId and we are in the ancestor view, build the urls
      if(personId) {

        // Get person info; process it when both ajax calls return
        $.when(getPersonSummary(personId), getRelationships(personId,spouseId)).done(function(summary, relationships) {

          try {
            // Get actual return data
            summary = summary[0];
            relationships = relationships[0];

            // Check to see if we have person data
            if(summary.data){
              var personData = normalizeData(summary, relationships);
              chrome.extension.sendRequest({
                'type': 'person_info',
                'data': personData
              });
            }
          } catch(e) {
            utils.reportError(e, window.location.href);
          }
        });
      }
    }
  }

  function normalizeData(summary, relationships) {
    var gender = summary.data.gender,
        fatherName = ['',''],
        motherName = ['',''],
        spouseName = ['',''];

    // Process parents if there is a relationship
    if(relationships.data && relationships.data.parents.length) {
      var fatherName = utils.splitName(relationships.data.parents[0].husband.name);
      var motherName = utils.splitName(relationships.data.parents[0].wife.name);
    }

    // Process spouse if there is a spouse relationship
    if(relationships.data && relationships.data.spouses.length) {
      if(gender == 'MALE' && relationships.data.spouses[0].wife) {
        spouseName = utils.splitName(relationships.data.spouses[0].wife.name);
      } else if(gender == 'FEMALE' && relationships.data.spouses[0].husband) {
        spouseName = utils.splitName(relationships.data.spouses[0].husband.name);
      }
    }

    var data = {
      'givenName': getSummaryInfo(summary, ['data', 'nameConclusion', 'details', 'nameForms', 0, 'givenPart']),
      'familyName': getSummaryInfo(summary, ['data', 'nameConclusion', 'details', 'nameForms', 0, 'familyPart']),
      'birthPlace': getConclusionPlace(getSummaryInfo(summary, ['data', 'birthConclusion'])),
      'birthDate': getConclusionDate(getSummaryInfo(summary, ['data', 'birthConclusion'])),
      'deathPlace': getConclusionPlace(getSummaryInfo(summary, ['data', 'deathConclusion'])),
      'deathDate': getConclusionDate(getSummaryInfo(summary, ['data', 'deathConclusion'])),
      'fatherGivenName': fatherName[0],
      'fatherFamilyName': fatherName[1],
      'motherGivenName': motherName[0],
      'motherFamilyName': motherName[1],
      'spouseGivenName': spouseName[0],
      'spouseFamilyName': spouseName[1]
    };

    if(relationships.data.spouses[0].event) {
      data.marriageDate = relationships.data.spouses[0].event.standardDate;
      data.marriagePlace = relationships.data.spouses[0].event.standardPlace;
    }

    return data;
  }

  function getConclusionPlace(conclusion){
    if(conclusion){
      return getSummaryInfo(conclusion, ['details', 'place', 'normalizedText']) || getSummaryInfo(conclusion, ['details', 'place', 'originalText']);
    }
  };

  function getConclusionDate(conclusion){
    if(conclusion){
      return getSummaryInfo(conclusion, ['details', 'date', 'normalizedText']) || getSummaryInfo(conclusion, ['details', 'date', 'originalText']);
    }
  };

  // Iterate over a list of attributes which define the path
  // through an object to a desired piece of data. Stop when
  // we reach the last attribute (and return its value)
  // or when we find something that is undefined (return undefined)
  function getSummaryInfo(summary, attributes) {
    var current = summary;
    for(var i = 0; i < attributes.length; i++) {
      current = current[attributes[i]];
      if( current == undefined ) {
        return undefined;
      }
    }
    return current;
  }

  // Makes an ajax call to retrieve the persons summary data and returns a promise
  function getPersonSummary(personId) {
    return $.getJSON('https://familysearch.org/tree-data/person/'+personId+'/summary');
  }

  // Makes an ajax call to retrieve relationship info and returns a promise
  function getRelationships(personId, spouseId) {
    var url = 'https://familysearch.org/tree-data/family-members/person/'+personId;
    if(spouseId)
      url += '?spouseId='+spouseId;
    return $.getJSON(url);
  }
}(utils));<commit_msg>Fix fs bug<commit_after>(function(utils, undefined){

  $(document).ready(function(){
    window.onhashchange = processHash;

    processHash()
  });

  // Called when the hash changes
  function processHash() {

    // Always hide the page action icon when the hash change
    // If we navigated to a new person we need time to load their data
    chrome.extension.sendRequest({
      'type': 'hide'
    });

    // Remove previous search links and show the ajax loader
    var hashParts = utils.getHashParts();

    if( hashParts['view'] == 'ancestor' ) {

      // Get personId and spouseId
      var personId = hashParts['person'];
      var spouseId = hashParts['spouse'];

      // If we have a personId and we are in the ancestor view, build the urls
      if(personId) {

        // Get person info; process it when both ajax calls return
        $.when(getPersonSummary(personId), getRelationships(personId,spouseId)).done(function(summary, relationships) {

          try {
            // Get actual return data
            summary = summary[0];
            relationships = relationships[0];

            // Check to see if we have person data
            if(summary.data){
              var personData = normalizeData(summary, relationships);
              chrome.extension.sendRequest({
                'type': 'person_info',
                'data': personData
              });
            }
          } catch(e) {
            utils.reportError(e, window.location.href);
          }
        });
      }
    }
  }

  function normalizeData(summary, relationships) {
    var gender = summary.data.gender,
        fatherName = ['',''],
        motherName = ['',''],
        spouseName = ['',''];

    // Process parents if there is a relationship
    if(relationships.data && relationships.data.parents.length) {
      var fatherName = utils.splitName(relationships.data.parents[0].husband.name);
      var motherName = utils.splitName(relationships.data.parents[0].wife.name);
    }

    // Process spouse if there is a spouse relationship
    if(relationships.data && relationships.data.spouses.length) {
      if(gender == 'MALE' && relationships.data.spouses[0].wife) {
        spouseName = utils.splitName(relationships.data.spouses[0].wife.name);
      } else if(gender == 'FEMALE' && relationships.data.spouses[0].husband) {
        spouseName = utils.splitName(relationships.data.spouses[0].husband.name);
      }
    }

    var data = {
      'givenName': getSummaryInfo(summary, ['data', 'nameConclusion', 'details', 'nameForms', 0, 'givenPart']),
      'familyName': getSummaryInfo(summary, ['data', 'nameConclusion', 'details', 'nameForms', 0, 'familyPart']),
      'birthPlace': getConclusionPlace(getSummaryInfo(summary, ['data', 'birthConclusion'])),
      'birthDate': getConclusionDate(getSummaryInfo(summary, ['data', 'birthConclusion'])),
      'deathPlace': getConclusionPlace(getSummaryInfo(summary, ['data', 'deathConclusion'])),
      'deathDate': getConclusionDate(getSummaryInfo(summary, ['data', 'deathConclusion'])),
      'fatherGivenName': fatherName[0],
      'fatherFamilyName': fatherName[1],
      'motherGivenName': motherName[0],
      'motherFamilyName': motherName[1],
      'spouseGivenName': spouseName[0],
      'spouseFamilyName': spouseName[1]
    };

    if(relationships.data && relationships.data.spouses[0].event) {
      data.marriageDate = relationships.data.spouses[0].event.standardDate;
      data.marriagePlace = relationships.data.spouses[0].event.standardPlace;
    }

    return data;
  }

  function getConclusionPlace(conclusion){
    if(conclusion){
      return getSummaryInfo(conclusion, ['details', 'place', 'normalizedText']) || getSummaryInfo(conclusion, ['details', 'place', 'originalText']);
    }
  };

  function getConclusionDate(conclusion){
    if(conclusion){
      return getSummaryInfo(conclusion, ['details', 'date', 'normalizedText']) || getSummaryInfo(conclusion, ['details', 'date', 'originalText']);
    }
  };

  // Iterate over a list of attributes which define the path
  // through an object to a desired piece of data. Stop when
  // we reach the last attribute (and return its value)
  // or when we find something that is undefined (return undefined)
  function getSummaryInfo(summary, attributes) {
    var current = summary;
    for(var i = 0; i < attributes.length; i++) {
      current = current[attributes[i]];
      if( current == undefined ) {
        return undefined;
      }
    }
    return current;
  }

  // Makes an ajax call to retrieve the persons summary data and returns a promise
  function getPersonSummary(personId) {
    return $.getJSON('https://familysearch.org/tree-data/person/'+personId+'/summary');
  }

  // Makes an ajax call to retrieve relationship info and returns a promise
  function getRelationships(personId, spouseId) {
    var url = 'https://familysearch.org/tree-data/family-members/person/'+personId;
    if(spouseId)
      url += '?spouseId='+spouseId;
    return $.getJSON(url);
  }
}(utils));<|endoftext|>


<commit_before>/**
 * AMP Latest Stories edit component, mainly forked from the Gutenberg 'Latest Posts' class LatestPostsEdit.
 */

/**
 * External dependencies
 */
import { isUndefined, pickBy } from 'lodash';
import classnames from 'classnames';

/**
 * WordPress dependencies
 */
import {
	Component,
	Fragment,
	RawHTML,
} from '@wordpress/element';
import {
	PanelBody,
	Placeholder,
	QueryControls,
	ServerSideRender,
	Spinner,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import {
	InspectorControls,
} from '@wordpress/editor';
import { withSelect } from '@wordpress/data';

const blockName = 'amp/amp-latest-stories';

class LatestStoriesEdit extends Component {
	componentWillMount() {
		this.isStillMounted = true;
	}

	componentWillUnmount() {
		this.isStillMounted = false;
	}

	render() {
		const { attributes, setAttributes, latestStories } = this.props;
		const { order, orderBy, storiesToShow } = attributes;

		const inspectorControls = (
			<InspectorControls>
				<PanelBody title={ __( 'Latest Stories Settings', 'amp' ) }>
					<QueryControls
						{ ...{ order, orderBy } }
						numberOfItems={ storiesToShow }
						onOrderChange={ ( value ) => setAttributes( { order: value } ) }
						onOrderByChange={ ( value ) => setAttributes( { orderBy: value } ) }
						onNumberOfItemsChange={ ( value ) => setAttributes( { storiesToShow: value } ) }
					/>
				</PanelBody>
			</InspectorControls>
		);

		const hasStories = Array.isArray( latestStories ) && latestStories.length;
		if ( ! hasStories ) {
			return (
				<Fragment>
					{ inspectorControls }
					<Placeholder
						icon="admin-post"
						label={ __( 'Latest Stories', 'amp' ) }
					>
						{ ! Array.isArray( latestStories ) ?
							<Spinner /> :
							__( 'No stories found.', 'amp' )
						}
					</Placeholder>
				</Fragment>
			);
		}

		// Removing posts from display should be instant.
		const displayStories = latestStories.length > storiesToShow ?
			latestStories.slice( 0, storiesToShow ) :
			latestStories;

		return (
			<Fragment>
				{ inspectorControls }
				<ServerSideRender
					block={ blockName }
					attributes={ attributes }
				/>
			</Fragment>
		);
	}
}

export default withSelect( ( select, props ) => {
	const { storiesToShow, order, orderBy } = props.attributes;
	const { getEntityRecords } = select( 'core' );
	const latestStoriesQuery = pickBy( {
		order,
		orderby: orderBy,
		per_page: storiesToShow,
	}, ( value ) => ! isUndefined( value ) );
	return {
		latestStories: getEntityRecords( 'postType', 'amp_story', latestStoriesQuery ),
	};
} )( LatestStoriesEdit );
<commit_msg>Remove unused classnames variable and displayStories constant<commit_after>/**
 * AMP Latest Stories edit component, mainly forked from the Gutenberg 'Latest Posts' class LatestPostsEdit.
 */

/**
 * External dependencies
 */
import { isUndefined, pickBy } from 'lodash';

/**
 * WordPress dependencies
 */
import {
	Component,
	Fragment,
	RawHTML,
} from '@wordpress/element';
import {
	PanelBody,
	Placeholder,
	QueryControls,
	ServerSideRender,
	Spinner,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import {
	InspectorControls,
} from '@wordpress/editor';
import { withSelect } from '@wordpress/data';

const blockName = 'amp/amp-latest-stories';

class LatestStoriesEdit extends Component {
	componentWillMount() {
		this.isStillMounted = true;
	}

	componentWillUnmount() {
		this.isStillMounted = false;
	}

	render() {
		const { attributes, setAttributes, latestStories } = this.props;
		const { order, orderBy, storiesToShow } = attributes;

		const inspectorControls = (
			<InspectorControls>
				<PanelBody title={ __( 'Latest Stories Settings', 'amp' ) }>
					<QueryControls
						{ ...{ order, orderBy } }
						numberOfItems={ storiesToShow }
						onOrderChange={ ( value ) => setAttributes( { order: value } ) }
						onOrderByChange={ ( value ) => setAttributes( { orderBy: value } ) }
						onNumberOfItemsChange={ ( value ) => setAttributes( { storiesToShow: value } ) }
					/>
				</PanelBody>
			</InspectorControls>
		);

		const hasStories = Array.isArray( latestStories ) && latestStories.length;
		if ( ! hasStories ) {
			return (
				<Fragment>
					{ inspectorControls }
					<Placeholder
						icon="admin-post"
						label={ __( 'Latest Stories', 'amp' ) }
					>
						{ ! Array.isArray( latestStories ) ?
							<Spinner /> :
							__( 'No stories found.', 'amp' )
						}
					</Placeholder>
				</Fragment>
			);
		}

		return (
			<Fragment>
				{ inspectorControls }
				<ServerSideRender
					block={ blockName }
					attributes={ attributes }
				/>
			</Fragment>
		);
	}
}

export default withSelect( ( select, props ) => {
	const { storiesToShow, order, orderBy } = props.attributes;
	const { getEntityRecords } = select( 'core' );
	const latestStoriesQuery = pickBy( {
		order,
		orderby: orderBy,
		per_page: storiesToShow,
	}, ( value ) => ! isUndefined( value ) );
	return {
		latestStories: getEntityRecords( 'postType', 'amp_story', latestStoriesQuery ),
	};
} )( LatestStoriesEdit );
<|endoftext|>


<commit_before>// Copyright 2015 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

function firstWindowClient() {
  return clients.matchAll({ type: 'window' }).then(function(windowClients) {
    return windowClients.length ? windowClients[0] : Promise.reject("No clients");
  });
}

self.addEventListener('install', function(event) {
  event.waitUntil(skipWaiting());
});

self.addEventListener('activate', function(event) {
  event.waitUntil(clients.claim());
});

self.addEventListener('notificationclick', function(event) {
  var notification = event.notification;

  if (!notification.data.hasOwnProperty('options'))
    return;

  var options = notification.data.options;

  // Close the notification if the setting has been set to do so.

  if (options.close)
    event.notification.close();

  var promise = Promise.resolve();

  // Available settings for |options.action| are:
  //
  //    'default'      First try to focus an existing window for the URL, open a
  //                   new one if none could be found.
  //
  //    'focus-only'   Only try to focus existing windows for the URL, don't do
  //                   anything if none exists.
  //
  //    'message'      Sends a message to all clients about this notification
  //                   having been clicked, with the notification's information.
  //
  //    'open-only'    Do not try to find existing windows, always open a new
  //                   window for the given URL.
  //

  if (options.action == 'message') {
    firstWindowClient().then(function(client) {
      var message = 'Clicked on "' + notification.title + '"';
      if (event.action)
        message += ' (action "' + event.action + '")';

      client.postMessage(message);
    });

    return;
  }

  if (options.action == 'default' || options.action == 'focus-only') {
    promise =
        promise.then(function() { return firstWindowClient(); })
               .then(function(client) { return client.focus(); });
    if (options.action == 'default') {
      promise = promise.catch(function() { clients.openWindow(options.url); });
    }
  } else if (options.action == 'open-only') {
    promise = promise.then(function() { clients.openWindow(options.url); });
  }

  event.waitUntil(promise);
});

self.addEventListener('notificationclose', function(event) {
  var notification = event.notification;
  var options = notification.data.options;
  var message = 'Closed "' + notification.title + '"';

  firstWindowClient().then(function(client) {
    // Available settings for |options.notificationCloseEvent| are:
    //  true: alert will be raised in the client to show the event firing.
    //  flase: no message will be sent back to the client
    if (options.notificationCloseEvent)
      client.postMessage(message);
  });
});
<commit_msg>Notification Generator: Don't call firstWindowClient unnecessarily<commit_after>// Copyright 2015 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

function firstWindowClient() {
  return clients.matchAll({ type: 'window' }).then(function(windowClients) {
    return windowClients.length ? windowClients[0] : Promise.reject("No clients");
  });
}

self.addEventListener('install', function(event) {
  event.waitUntil(skipWaiting());
});

self.addEventListener('activate', function(event) {
  event.waitUntil(clients.claim());
});

self.addEventListener('notificationclick', function(event) {
  var notification = event.notification;

  if (!notification.data.hasOwnProperty('options'))
    return;

  var options = notification.data.options;

  // Close the notification if the setting has been set to do so.

  if (options.close)
    event.notification.close();

  var promise = Promise.resolve();

  // Available settings for |options.action| are:
  //
  //    'default'      First try to focus an existing window for the URL, open a
  //                   new one if none could be found.
  //
  //    'focus-only'   Only try to focus existing windows for the URL, don't do
  //                   anything if none exists.
  //
  //    'message'      Sends a message to all clients about this notification
  //                   having been clicked, with the notification's information.
  //
  //    'open-only'    Do not try to find existing windows, always open a new
  //                   window for the given URL.
  //

  if (options.action == 'message') {
    firstWindowClient().then(function(client) {
      var message = 'Clicked on "' + notification.title + '"';
      if (event.action)
        message += ' (action "' + event.action + '")';

      client.postMessage(message);
    });

    return;
  }

  if (options.action == 'default' || options.action == 'focus-only') {
    promise =
        promise.then(function() { return firstWindowClient(); })
               .then(function(client) { return client.focus(); });
    if (options.action == 'default') {
      promise = promise.catch(function() { clients.openWindow(options.url); });
    }
  } else if (options.action == 'open-only') {
    promise = promise.then(function() { clients.openWindow(options.url); });
  }

  event.waitUntil(promise);
});

self.addEventListener('notificationclose', function(event) {
  var notification = event.notification;
  var options = notification.data.options;

  // Available settings for |options.notificationCloseEvent| are:
  //  true: alert will be raised in the client to show the event firing.
  //  flase: no message will be sent back to the client
  if (!options.notificationCloseEvent)
    return;

  var message = 'Closed "' + notification.title + '"';
  firstWindowClient().then(function(client) {
    client.postMessage(message);
  });
});
<|endoftext|>


<commit_before>"use strict";
let Caf = require("caffeine-script-runtime");
Caf.defMod(module, () => {
  let createObjectTreeFactory,
    BaseStn,
    BaseClass,
    log,
    Object,
    Error,
    merge,
    objectWithout,
    toInspectedObjects,
    objectKeyCount,
    compactFlatten,
    isString;
  ({
    BaseClass,
    log,
    Object,
    Error,
    merge,
    objectWithout,
    toInspectedObjects,
    objectKeyCount,
    compactFlatten,
    isString
  } = Caf.import(
    [
      "BaseClass",
      "log",
      "Object",
      "Error",
      "merge",
      "objectWithout",
      "toInspectedObjects",
      "objectKeyCount",
      "compactFlatten",
      "isString"
    ],
    [require("../StandardImport"), global]
  ));
  ({ createObjectTreeFactory } = require("art-object-tree-factory"));
  return BaseStn = Caf.defClass(
    class BaseStn extends BaseClass {
      constructor(props, children = noChildren) {
        super(...arguments);
        this.children = children;
        this.parseTreeNode = props.parseTreeNode;
        this.props = objectWithout(props, "parseTreeNode");
        this.initLabeledChildren();
      }
    },
    function(BaseStn, classSuper, instanceSuper) {
      let noChildren, applyRequiredParens, applyParens;
      if (!(require("caffeine-script-runtime").getSuper(this) === BaseClass)) {
        log({
          self: this,
          selfName: this.getName(),
          "Object.getPrototypeOf@": Object.getPrototypeOf(this),
          badSuper: require("caffeine-script-runtime").getSuper(this),
          BaseClass,
          "selfIsBaseObject?": this === BaseClass
        });
        throw new Error("bad super");
      }
      this.abstractClass();
      this.prototype.toJsParenExpression = function(options) {
        return this.toJs(merge(options, { expression: true }));
      };
      noChildren = [];
      this.prototype.initLabeledChildren = function() {
        this.labeledChildren = this.children && {};
        return Caf.each(this.children, undefined, (child, k, into) => {
          let label, pluralLabel, cafBase;
          child.parent = this;
          ({ label, pluralLabel } = child);
          this.labeledChildren[label] = child;
          if (pluralLabel) {
            ((cafBase = this.labeledChildren)[pluralLabel] ||
              (cafBase[pluralLabel] = [])).push(child);
          }
        });
      };
      this.getter({
        parser: function() {
          return this.parseTreeNode.parser.rootParser;
        },
        sourceFile: function() {
          return this.parser.sourceFile;
        },
        label: function() {
          return this.props.label;
        },
        pluralLabel: function() {
          return this.props.pluralLabel;
        },
        inspectedObjects: function() {
          let label, props, name, a;
          ({ label } = this);
          props = objectWithout(this.props, "label", "pluralLabel");
          name = this.class.getName();
          if (label) {
            name = `${Caf.toString(label)}.${Caf.toString(name)}`;
          }
          return {
            [`${Caf.toString(name)}`]: this.children.length === 0
              ? toInspectedObjects(props)
              : (a = [], objectKeyCount(props) > 0
                  ? a.push(props)
                  : undefined, a.concat(
                  Caf.each(this.children, [], (c, k, into) => {
                    into.push(c.inspectedObjects);
                  })
                ))
          };
        },
        type: function() {
          return this.class.type;
        }
      });
      this.postCreate = function() {
        let s;
        s = this.getName().split(/Stn$/);
        this.type = s[0];
        return classSuper.postCreate.apply(this, arguments);
      };
      this.newInstance = function(props, children) {
        return new this(props, children);
      };
      this.postCreateConcreteClass = function(options) {
        let classModuleState, hotReloadEnabled;
        ({ classModuleState, hotReloadEnabled } = options);
        classSuper.postCreateConcreteClass.apply(this, arguments);
        return require("../StnRegistry").register(
          createObjectTreeFactory({ class: this }, (props, children) => {
            return this.newInstance(props, children);
          })
        );
      };
      this.prototype.findParent = function(stnTypePattern) {
        let parent, found;
        ({ parent } = this);
        found = null;
        while (parent && !found) {
          if (parent.type.match(stnTypePattern)) {
            found = parent;
          } else {
            ({ parent } = parent);
          }
        }
        return found;
      };
      this.prototype.find = function(stnTypePattern) {
        let a;
        a = compactFlatten(
          Caf.each(this.children, [], (child, k, into) => {
            into.push(
              child.type.match(stnTypePattern)
                ? child
                : child.find(stnTypePattern)
            );
          })
        );
        return a.length === 0 ? null : a;
      };
      this.prototype.childrenToJs = function(joiner = "") {
        return Caf
          .each(this.children, [], (c, k, into) => {
            into.push(c.toJs());
          })
          .join(joiner);
      };
      this.prototype.toJs = function(options) {
        return (() => {
          throw new Error(
            `must override one of the toJs* functions: ${Caf.toString(
              this.className
            )}`
          );
        })();
      };
      this.prototype.doJs = function(args, body) {
        if (args) {
          throw "TODO";
        }
        if (!isString(body)) {
          body = body.toFunctionBodyJs();
        }
        return `(() => {${Caf.toString(body)};})()`;
      };
      this.prototype.toFunctionBodyJsArray = function(returnAction = true) {
        return returnAction
          ? [`return ${Caf.toString(this.toJsExpression())}`]
          : [this.toJs()];
      };
      this.prototype.toFunctionBodyJs = function(returnAction = true) {
        return this.toFunctionBodyJsArray(returnAction).join("");
      };
      this.prototype.toJsExpression = function(options) {
        return this.toJs(merge(options, { expression: true }));
      };
      this.prototype.toInterpolatedJsStringPart = function() {
        return `\${Caf.toString(${Caf.toString(this.toJsExpression())})}`;
      };
      this.prototype.transformChildren = function() {
        let ret;
        ret = null;
        Caf.each(this.children, undefined, (child, i, into) => {
          let newChild;
          if (child !== (newChild = child.transform())) {
            ret != null ? ret : ret = this.children.slice();
            newChild.props.label = child.label;
            ret[i] = newChild;
          }
        });
        return ret || this.children;
      };
      this.prototype.postTransform = function() {
        return this;
      };
      this.prototype.transform = function() {
        let newChildren;
        return (this.children !== (newChildren = this.transformChildren())
          ? new this.class(this.props, newChildren)
          : this).postTransform();
      };
      this.prototype.needsParens = true;
      this.prototype.needsParensAsStatement = false;
      this.prototype.getNeedsParens = function() {
        return this.needsParens;
      };
      this.prototype.getNeedsParensAsStatement = function() {
        return this.needsParensAsStatement;
      };
      this.applyRequiredParens = applyRequiredParens = function(expr) {
        return `(${Caf.toString(expr)})`;
      };
      this.applyParens = applyParens = function(expr) {
        return expr.match(
          /^(\([^)]*\)|\[[^\]]*\]|([!~-]*[_a-z0-9.]*)(\([^)]*\))?)$/i
        )
          ? expr
          : `(${Caf.toString(expr)})`;
      };
      this.prototype.applyRequiredParens = applyRequiredParens;
      this.prototype.applyParens = applyParens;
      this.getter({
        normalizedOperand: function() {
          let op;
          return (() => {
            switch (op = this.props.operand) {
              case "and":
                return "&&";
              case "or":
                return "||";
              case "==":
              case "is":
                return "===";
              case "!=":
              case "isnt":
                return "!==";
              case "not":
                return "!";
              default:
                return op;
            }
          })();
        }
      });
      this.prototype.updateScope = function(scope) {
        this.scope = scope;
        return Caf.each(this.children, undefined, (child, k, into) => {
          child.updateScope(this.scope);
        });
      };
    }
  );
});
<commit_msg>rebuilt<commit_after>"use strict";
let Caf = require("caffeine-script-runtime");
Caf.defMod(module, () => {
  let createObjectTreeFactory,
    BaseStn,
    BaseClass,
    log,
    Object,
    Error,
    merge,
    objectWithout,
    toInspectedObjects,
    objectKeyCount,
    compactFlatten,
    isString,
    noChildren;
  ({
    BaseClass,
    log,
    Object,
    Error,
    merge,
    objectWithout,
    toInspectedObjects,
    objectKeyCount,
    compactFlatten,
    isString,
    noChildren
  } = Caf.import(
    [
      "BaseClass",
      "log",
      "Object",
      "Error",
      "merge",
      "objectWithout",
      "toInspectedObjects",
      "objectKeyCount",
      "compactFlatten",
      "isString",
      "noChildren"
    ],
    [require("../StandardImport"), global]
  ));
  ({ createObjectTreeFactory } = require("art-object-tree-factory"));
  return BaseStn = Caf.defClass(
    class BaseStn extends BaseClass {
      constructor(props, children = noChildren) {
        super(...arguments);
        this.children = children;
        this.parseTreeNode = props.parseTreeNode;
        this.props = objectWithout(props, "parseTreeNode");
        this.initLabeledChildren();
      }
    },
    function(BaseStn, classSuper, instanceSuper) {
      let applyRequiredParens, applyParens;
      if (!(require("caffeine-script-runtime").getSuper(this) === BaseClass)) {
        log({
          self: this,
          selfName: this.getName(),
          "Object.getPrototypeOf@": Object.getPrototypeOf(this),
          badSuper: require("caffeine-script-runtime").getSuper(this),
          BaseClass,
          "selfIsBaseObject?": this === BaseClass
        });
        throw new Error("bad super");
      }
      this.abstractClass();
      this.prototype.toJsParenExpression = function(options) {
        return this.toJs(merge(options, { expression: true }));
      };
      noChildren = [];
      this.prototype.initLabeledChildren = function() {
        this.labeledChildren = this.children && {};
        return Caf.each(this.children, undefined, (child, k, into) => {
          let label, pluralLabel, cafBase;
          child.parent = this;
          ({ label, pluralLabel } = child);
          this.labeledChildren[label] = child;
          if (pluralLabel) {
            ((cafBase = this.labeledChildren)[pluralLabel] ||
              (cafBase[pluralLabel] = [])).push(child);
          }
        });
      };
      this.getter({
        parser: function() {
          return this.parseTreeNode.parser.rootParser;
        },
        sourceFile: function() {
          return this.parser.sourceFile;
        },
        label: function() {
          return this.props.label;
        },
        pluralLabel: function() {
          return this.props.pluralLabel;
        },
        inspectedObjects: function() {
          let label, props, name, a;
          ({ label } = this);
          props = objectWithout(this.props, "label", "pluralLabel");
          name = this.class.getName();
          if (label) {
            name = `${Caf.toString(label)}.${Caf.toString(name)}`;
          }
          return {
            [`${Caf.toString(name)}`]: this.children.length === 0
              ? toInspectedObjects(props)
              : (a = [], objectKeyCount(props) > 0
                  ? a.push(props)
                  : undefined, a.concat(
                  Caf.each(this.children, [], (c, k, into) => {
                    into.push(c.inspectedObjects);
                  })
                ))
          };
        },
        type: function() {
          return this.class.type;
        }
      });
      this.postCreate = function() {
        let s;
        s = this.getName().split(/Stn$/);
        this.type = s[0];
        return classSuper.postCreate.apply(this, arguments);
      };
      this.newInstance = function(props, children) {
        return new this(props, children);
      };
      this.postCreateConcreteClass = function(options) {
        let classModuleState, hotReloadEnabled;
        ({ classModuleState, hotReloadEnabled } = options);
        classSuper.postCreateConcreteClass.apply(this, arguments);
        return require("../StnRegistry").register(
          createObjectTreeFactory({ class: this }, (props, children) => {
            return this.newInstance(props, children);
          })
        );
      };
      this.prototype.findParent = function(stnTypePattern) {
        let parent, found;
        ({ parent } = this);
        found = null;
        while (parent && !found) {
          if (parent.type.match(stnTypePattern)) {
            found = parent;
          } else {
            ({ parent } = parent);
          }
        }
        return found;
      };
      this.prototype.find = function(stnTypePattern) {
        let a;
        a = compactFlatten(
          Caf.each(this.children, [], (child, k, into) => {
            into.push(
              child.type.match(stnTypePattern)
                ? child
                : child.find(stnTypePattern)
            );
          })
        );
        return a.length === 0 ? null : a;
      };
      this.prototype.childrenToJs = function(joiner = "") {
        return Caf
          .each(this.children, [], (c, k, into) => {
            into.push(c.toJs());
          })
          .join(joiner);
      };
      this.prototype.toJs = function(options) {
        return (() => {
          throw new Error(
            `must override one of the toJs* functions: ${Caf.toString(
              this.className
            )}`
          );
        })();
      };
      this.prototype.doJs = function(args, body) {
        if (args) {
          throw "TODO";
        }
        if (!isString(body)) {
          body = body.toFunctionBodyJs();
        }
        return `(() => {${Caf.toString(body)};})()`;
      };
      this.prototype.toFunctionBodyJsArray = function(returnAction = true) {
        return returnAction
          ? [`return ${Caf.toString(this.toJsExpression())}`]
          : [this.toJs()];
      };
      this.prototype.toFunctionBodyJs = function(returnAction = true) {
        return this.toFunctionBodyJsArray(returnAction).join("");
      };
      this.prototype.toJsExpression = function(options) {
        return this.toJs(merge(options, { expression: true }));
      };
      this.prototype.toInterpolatedJsStringPart = function() {
        return `\${Caf.toString(${Caf.toString(this.toJsExpression())})}`;
      };
      this.prototype.transformChildren = function() {
        let ret;
        ret = null;
        Caf.each(this.children, undefined, (child, i, into) => {
          let newChild;
          if (child !== (newChild = child.transform())) {
            ret != null ? ret : ret = this.children.slice();
            newChild.props.label = child.label;
            ret[i] = newChild;
          }
        });
        return ret || this.children;
      };
      this.prototype.postTransform = function() {
        return this;
      };
      this.prototype.transform = function() {
        let newChildren;
        return (this.children !== (newChildren = this.transformChildren())
          ? new this.class(this.props, newChildren)
          : this).postTransform();
      };
      this.prototype.needsParens = true;
      this.prototype.needsParensAsStatement = false;
      this.prototype.getNeedsParens = function() {
        return this.needsParens;
      };
      this.prototype.getNeedsParensAsStatement = function() {
        return this.needsParensAsStatement;
      };
      this.applyRequiredParens = applyRequiredParens = function(expr) {
        return `(${Caf.toString(expr)})`;
      };
      this.applyParens = applyParens = function(expr) {
        return expr.match(
          /^(\([^)]*\)|\[[^\]]*\]|([!~-]*[_a-z0-9.]*)(\([^)]*\))?)$/i
        )
          ? expr
          : `(${Caf.toString(expr)})`;
      };
      this.prototype.applyRequiredParens = applyRequiredParens;
      this.prototype.applyParens = applyParens;
      this.getter({
        normalizedOperand: function() {
          let op;
          return (() => {
            switch (op = this.props.operand) {
              case "and":
                return "&&";
              case "or":
                return "||";
              case "==":
              case "is":
                return "===";
              case "!=":
              case "isnt":
                return "!==";
              case "not":
                return "!";
              default:
                return op;
            }
          })();
        }
      });
      this.prototype.updateScope = function(scope) {
        this.scope = scope;
        return Caf.each(this.children, undefined, (child, k, into) => {
          child.updateScope(this.scope);
        });
      };
    }
  );
});
<|endoftext|>


<commit_before>/* global emit */
import Ember from 'ember';
import { configurations, registerModels, registerQueries, registerRelationships, cleanup, next, wait } from '../helpers/setup';
import { Relationship, Query, Model, prefix, belongsTo } from 'sofa';

const {
  computed,
  RSVP: { all }
} = Ember;

const ddoc = {
  views: {
    'all': {
      map(doc) {
        if(doc.type !== 'duck') {
          return;
        }
        emit(doc._id, null);
      }
    }
  }
};

configurations(({ module, test, createStore }) => {

  let store;
  let db;

  let AllDucks = Query.extend({
    find: computed(function() {
      return { ddoc: 'ducks', view: 'all' };
    })
  });

  let AllDucksRelationship = Relationship.extend({
    query: 'all-ducks'
  });

  let Duck = Model.extend({
    id: prefix(),
  });

  let Root = Model.extend({
    duck: belongsTo('duck', { inverse: null, relationship: 'all-ducks' })
  });

  const saveDuckAndFlush = () => {
    return db.model('duck', { id: 'random' }).save().then(() => {
      flush();
    });
  }

  function flush() {
    store = createStore();
    db = store.get('db.main');
    db.set('modelNames', [ 'root', 'duck' ]);
  }

  module('belongs-to-collection', () => {
    registerModels({ Duck, Root });
    registerQueries({ AllDucks });
    registerRelationships({ AllDucks: AllDucksRelationship });
    flush();
    return cleanup(store, [ 'main' ]).then(() => {
      return db.get('documents.design').save('ducks', ddoc);
    });
  });

  test('model is initially matched and matched after load', assert => {
    let root;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      assert.equal(db.transient('root', 'one').get('duck.docId'), 'duck:yellow');
      flush();
      root = db.transient('root', 'one');
      assert.equal(root.get('duck.content'), null);
      return root.get('duck.promise');
    }).then(() => {
      assert.equal(root.get('duck.docId'), 'duck:green');
    });
  });

  test('model is matched on create', assert => {
    db.model('duck', { id: 'yellow' });
    let root = db.model('root');
    assert.equal(root.get('duck.id'), 'yellow');
    return root.get('ducks.promise');
  });

  test('created model model is matched', assert => {
    return saveDuckAndFlush().then(() => {
      let root = db.model('root');
      assert.equal(root.get('duck.id'), undefined);
      db.model('duck', { id: 'yellow' });
      assert.equal(root.get('duck.id'), 'yellow');
      return root.get('ducks.promise');
    });
  });

  test('destroyed isNew model is removed from coll', assert => {
    let duck = db.model('duck', { id: 'yellow' });
    let root = db.model('root');
    assert.equal(root.get('duck.id'), 'yellow');
    duck.destroy();
    return next().then(() => {
      assert.equal(root.get('duck.id'), null);
      duck = db.model('duck', { id: 'green' });
      assert.equal(root.get('duck.id'), 'green');
    });
  });

  test('assign database after model creation', assert => {
    db.model('duck', { id: 'yellow' });
    let root = store.model('root');
    assert.deepEqual(root.get('duck.id'), undefined);
    root.set('database', db);
    assert.deepEqual(root.get('duck.id'), 'yellow');
  });

  test('load', assert => {
    let root;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      flush();
      root = db.model('root');
      return root.get('duck.promise');
    }).then(() => {
      assert.deepEqual(root.get('duck.id'), 'green');
    });
  });

  test('autoload', assert => {
    let root;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      flush();
      root = db.model('root');
      assert.equal(root.get('duck.id'), undefined);
      return wait(null, 100);
    }).then(() => {
      assert.equal(root.get('duck.id'), 'green');
    });
  });

  test('destroy', assert => {
    let root;
    let relation;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      flush();
      root = db.model('root');
      return root.get('duck.promise');
    }).then(() => {
      assert.equal(root.get('duck.id'), 'green');
      relation = root.get('duck._relation');
      assert.ok(relation);
      root.get('duck').destroy();
      return next();
    }).then(() => {
      assert.ok(!relation.value);
      assert.ok(!root.get('duck').isDestroying);
      assert.ok(relation.value);
    });
  });

});
<commit_msg>tests -- make sure proxy autoload finishes before tearing down store<commit_after>/* global emit */
import Ember from 'ember';
import { configurations, registerModels, registerQueries, registerRelationships, cleanup, next, wait } from '../helpers/setup';
import { Relationship, Query, Model, prefix, belongsTo } from 'sofa';

const {
  computed,
  RSVP: { all }
} = Ember;

const ddoc = {
  views: {
    'all': {
      map(doc) {
        if(doc.type !== 'duck') {
          return;
        }
        emit(doc._id, null);
      }
    }
  }
};

configurations(({ module, test, createStore }) => {

  let store;
  let db;

  let AllDucks = Query.extend({
    find: computed(function() {
      return { ddoc: 'ducks', view: 'all' };
    })
  });

  let AllDucksRelationship = Relationship.extend({
    query: 'all-ducks'
  });

  let Duck = Model.extend({
    id: prefix(),
  });

  let Root = Model.extend({
    duck: belongsTo('duck', { inverse: null, relationship: 'all-ducks' })
  });

  const saveDuckAndFlush = () => {
    return db.model('duck', { id: 'random' }).save().then(() => {
      flush();
    });
  }

  function flush() {
    store = createStore();
    db = store.get('db.main');
    db.set('modelNames', [ 'root', 'duck' ]);
  }

  module('belongs-to-collection', () => {
    registerModels({ Duck, Root });
    registerQueries({ AllDucks });
    registerRelationships({ AllDucks: AllDucksRelationship });
    flush();
    return cleanup(store, [ 'main' ]).then(() => {
      return db.get('documents.design').save('ducks', ddoc);
    });
  });

  test('model is initially matched and matched after load', assert => {
    let root;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      root = db.transient('root', 'one');
      assert.equal(root.get('duck.docId'), 'duck:yellow');
      return root.get('duck.promise');
    }).then(() => {
      flush();
      root = db.model('root', 'one');
      assert.equal(root.get('duck.content'), null);
      return root.get('duck.promise');
    }).then(() => {
      assert.equal(root.get('duck.docId'), 'duck:green');
    });
  });

  test('model is matched on create', assert => {
    return saveDuckAndFlush().then(() => {
      db.model('duck', { id: 'yellow' });
      let root = db.model('root');
      assert.equal(root.get('duck.id'), 'yellow');
      return root.get('duck.promise');
    });
  });

  test('created model is matched', assert => {
    return saveDuckAndFlush().then(() => {
      let root = db.model('root');
      assert.equal(root.get('duck.id'), undefined);
      db.model('duck', { id: 'yellow' });
      assert.equal(root.get('duck.id'), 'yellow');
      return root.get('duck.promise');
    });
  });

  test('destroyed isNew model is removed from coll', assert => {
    let root;
    let duck;
    return saveDuckAndFlush().then(() => {
      duck = db.model('duck', { id: 'yellow' });
      root = db.model('root');
      assert.equal(root.get('duck.id'), 'yellow');
      duck.destroy();
      return next();
    }).then(() => {
      assert.equal(root.get('duck.id'), null);
      duck = db.model('duck', { id: 'green' });
      assert.equal(root.get('duck.id'), 'green');
      return root.get('duck.promise');
    });
  });

  test('assign database after model creation', assert => {
    return saveDuckAndFlush().then(() => {
      db.model('duck', { id: 'yellow' });
      let root = store.model('root');
      assert.deepEqual(root.get('duck.id'), undefined);
      root.set('database', db);
      assert.deepEqual(root.get('duck.id'), 'yellow');
      return root.get('duck.promise');
    });
  });

  test('load', assert => {
    let root;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      flush();
      root = db.model('root');
      return root.get('duck.promise');
    }).then(() => {
      assert.deepEqual(root.get('duck.id'), 'green');
    });
  });

  test('autoload', assert => {
    let root;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      flush();
      root = db.model('root');
      assert.deepEqual(root.get('duck').getProperties('isLoaded', 'id'), { isLoaded: false, id: undefined });
      return wait(null, 300);
    }).then(() => {
      assert.deepEqual(root.get('duck').getProperties('isLoaded', 'id'), { isLoaded: true, id: 'green' });
      return root.get('duck.promise');
    });
  });

  test('destroy', assert => {
    let root;
    let relation;
    return all([ 'yellow', 'red', 'green' ].map(id => db.model('duck', { id }).save())).then(() => {
      flush();
      root = db.model('root');
      return root.get('duck.promise');
    }).then(() => {
      assert.equal(root.get('duck.id'), 'green');
      relation = root.get('duck._relation');
      assert.ok(relation);
      root.get('duck').destroy();
      return next();
    }).then(() => {
      assert.ok(!relation.value);
      assert.ok(!root.get('duck').isDestroying);
      assert.ok(relation.value);
    });
  });

});
<|endoftext|>