<commit_before>import React, { Component, PropTypes } from 'react';
import { compose, graphql } from 'react-apollo';
import {Tabs, Tab} from 'material-ui/Tabs';
import FontIcon from 'material-ui/FontIcon';
const camelCase = require('camelcase');

import ManageCampaignInfoForm from 'components/ManageCampaignInfoForm';
import Link from 'components/Link';

import history from 'lib/history';
import states from 'lib/states-list';
import {
  validateString,
  validateWebsiteUrl,
  validateState,
  validatePhoneNumber
} from 'lib/validateComponentForms';

import {
  MeQuery,
  CampaignQuery
} from 'schemas/queries';

import {
  EditCampaignMutation
} from 'schemas/mutations';

import s from 'styles/Organize.scss';

const statesList = Object.keys(states);

class ManageCampaignInfoContainer extends Component {

  static PropTypes = {
    campaignSlug: PropTypes.string.isRequired
  }

  constructor(props) {
    super(props);

    const initialState = {
      formData: {
        title: '',
        streetAddress: '',
        streetAddress2: '',
        websiteUrl: '',
        phoneNumber: '',
        email: '',
        city: '',
        state: '',
        zipcode: '',
      },
      errors: {},
      refs: {},
    }

    this.state = Object.assign({}, initialState, this.defaultErrorText);
  }

  defaultErrorText = {
    titleErrorText: null,
    streetAddressErrorText: null,
    websiteUrlErrorText: null,
    phoneNumberErrorText: null,
    cityErrorText: null,
    stateErrorText: null,
    zipcodeErrorText: null,
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.campaign) {

      // Just camel-casing property keys and checking for null/undefined
      const campaign = Object.assign(...Object.keys(nextProps.campaign).map(k => ({
          [camelCase(k)]: nextProps.campaign[k] || ''
      })));

      Object.keys(campaign).forEach( (k) => {
        if (!Object.keys(this.state.formData).includes(camelCase(k))) {
          delete campaign[k];
        }
      });

      this.setState( (prevState) => ({
        formData: Object.assign({}, prevState.formData, campaign)
      }));
    }
  }

  resetErrorText = () => {
    this.setState({ errors: this.defaultErrorText });
  }

  handleInputChange = (event, type, value) => {
    let valid = true;

    if (type === 'state') {
      valid = false;

      statesList.forEach( (state) => {
        if (state.toLowerCase().includes(value.toLowerCase())) {
          valid = true;
        }
      });
      value = value.toUpperCase();

      // Hack for AutoComplete
      if (!valid) {
        this.state.refs.stateInput.setState( (prevState) => ({
          searchText: prevState.formData.state
        }));
      }
    }

    if (valid) {
      this.setState( (prevState) => ({
        formData: Object.assign({},
          prevState.formData,
          { [type]: value }
        )
      }));
    }
  }

  formSubmit = async (event) => {
    (typeof event === 'object' && typeof event.preventDefault === 'function') && event.preventDefault();

    this.resetErrorText();
    this.hasErrors = false;

    validateString(this, 'title', 'titleErrorText', 'Campaign Name is Required');
    validateWebsiteUrl(this);
    validatePhoneNumber(this);
    validateState(this);

    if (!this.hasErrors) {
      console.log('lets edit this campaign');

      const { formData } = this.state;

      formData.id = this.props.campaign.id;

      try {

        const results = await this.props.editCampaignMutation({
          variables: {
            data: formData
          },
          // TODO: decide between refetch and update
          refetchQueries: ['CampaignQuery', 'CampaignsQuery', 'MyCampaignsQuery'],
        });

        console.log('edited campaign');

      } catch (e) {
        console.error(e);
      }
    }
  }

  render() {
    const { state, formSubmit, handleInputChange } = this;
    const { user, ...props } = this.props;
    const { formData, errors, refs } = state;

    const campaign = props.campaign || {
      title: '',
      slug: ''
    };

    return (

{campaign.title}

        <Link to={'/organize/' + campaign.slug + '/settings'}>

            <FontIcon
              className={["material-icons", s.backArrow].join(' ')}
            >arrow_back</FontIcon>
            Settings

        </Link>

Info

        <ManageCampaignInfoForm
          handleInputChange={handleInputChange}
          formSubmit={formSubmit}
          campaign={campaign}
          data={formData}
          errors={errors}
          user={user}
          refs={refs}
        />

    );
  }
}

const withMeQuery = graphql(MeQuery, {
  props: ({ data }) => ({
    user: !data.loading && data.me ? data.me : {
      email: '',
    },
  })
});

const withCampaignQuery = graphql(CampaignQuery, {
  options: (ownProps) => ({
    variables: {
      search: {
        slug: ownProps.campaignSlug
      }
    }
  }),
  props: ({ data }) => ({
    campaign: data.campaign
  })
});

export default compose(
  withMeQuery,
  withCampaignQuery,
  graphql(EditCampaignMutation, { name: 'editCampaignMutation' })
)(ManageCampaignInfoContainer);
<commit_msg>Removing stupid console.logs<commit_after>import React, { Component, PropTypes } from 'react';
import { compose, graphql } from 'react-apollo';
import {Tabs, Tab} from 'material-ui/Tabs';
import FontIcon from 'material-ui/FontIcon';
const camelCase = require('camelcase');

import ManageCampaignInfoForm from 'components/ManageCampaignInfoForm';
import Link from 'components/Link';

import history from 'lib/history';
import states from 'lib/states-list';
import {
  validateString,
  validateWebsiteUrl,
  validateState,
  validatePhoneNumber
} from 'lib/validateComponentForms';

import {
  MeQuery,
  CampaignQuery
} from 'schemas/queries';

import {
  EditCampaignMutation
} from 'schemas/mutations';

import s from 'styles/Organize.scss';

const statesList = Object.keys(states);

class ManageCampaignInfoContainer extends Component {

  static PropTypes = {
    campaignSlug: PropTypes.string.isRequired
  }

  constructor(props) {
    super(props);

    const initialState = {
      formData: {
        title: '',
        streetAddress: '',
        streetAddress2: '',
        websiteUrl: '',
        phoneNumber: '',
        email: '',
        city: '',
        state: '',
        zipcode: '',
      },
      errors: {},
      refs: {},
    }

    this.state = Object.assign({}, initialState, this.defaultErrorText);
  }

  defaultErrorText = {
    titleErrorText: null,
    streetAddressErrorText: null,
    websiteUrlErrorText: null,
    phoneNumberErrorText: null,
    cityErrorText: null,
    stateErrorText: null,
    zipcodeErrorText: null,
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.campaign) {

      // Just camel-casing property keys and checking for null/undefined
      const campaign = Object.assign(...Object.keys(nextProps.campaign).map(k => ({
          [camelCase(k)]: nextProps.campaign[k] || ''
      })));

      Object.keys(campaign).forEach( (k) => {
        if (!Object.keys(this.state.formData).includes(camelCase(k))) {
          delete campaign[k];
        }
      });

      this.setState( (prevState) => ({
        formData: Object.assign({}, prevState.formData, campaign)
      }));
    }
  }

  resetErrorText = () => {
    this.setState({ errors: this.defaultErrorText });
  }

  handleInputChange = (event, type, value) => {
    let valid = true;

    if (type === 'state') {
      valid = false;

      statesList.forEach( (state) => {
        if (state.toLowerCase().includes(value.toLowerCase())) {
          valid = true;
        }
      });
      value = value.toUpperCase();

      // Hack for AutoComplete
      if (!valid) {
        this.state.refs.stateInput.setState( (prevState) => ({
          searchText: prevState.formData.state
        }));
      }
    }

    if (valid) {
      this.setState( (prevState) => ({
        formData: Object.assign({},
          prevState.formData,
          { [type]: value }
        )
      }));
    }
  }

  formSubmit = async (event) => {
    (typeof event === 'object' && typeof event.preventDefault === 'function') && event.preventDefault();

    this.resetErrorText();
    this.hasErrors = false;

    validateString(this, 'title', 'titleErrorText', 'Campaign Name is Required');
    validateWebsiteUrl(this);
    validatePhoneNumber(this);
    validateState(this);

    if (!this.hasErrors) {

      const { formData } = this.state;

      formData.id = this.props.campaign.id;

      try {

        const results = await this.props.editCampaignMutation({
          variables: {
            data: formData
          },
          // TODO: decide between refetch and update
          refetchQueries: ['CampaignQuery', 'CampaignsQuery', 'MyCampaignsQuery'],
        });

      } catch (e) {
        console.error(e);
      }
    }
  }

  render() {
    const { state, formSubmit, handleInputChange } = this;
    const { user, ...props } = this.props;
    const { formData, errors, refs } = state;

    const campaign = props.campaign || {
      title: '',
      slug: ''
    };

    return (

{campaign.title}

        <Link to={'/organize/' + campaign.slug + '/settings'}>

            <FontIcon
              className={["material-icons", s.backArrow].join(' ')}
            >arrow_back</FontIcon>
            Settings

        </Link>

Info

        <ManageCampaignInfoForm
          handleInputChange={handleInputChange}
          formSubmit={formSubmit}
          campaign={campaign}
          data={formData}
          errors={errors}
          user={user}
          refs={refs}
        />

    );
  }
}

const withMeQuery = graphql(MeQuery, {
  props: ({ data }) => ({
    user: !data.loading && data.me ? data.me : {
      email: '',
    },
  })
});

const withCampaignQuery = graphql(CampaignQuery, {
  options: (ownProps) => ({
    variables: {
      search: {
        slug: ownProps.campaignSlug
      }
    }
  }),
  props: ({ data }) => ({
    campaign: data.campaign
  })
});

export default compose(
  withMeQuery,
  withCampaignQuery,
  graphql(EditCampaignMutation, { name: 'editCampaignMutation' })
)(ManageCampaignInfoContainer);
<|endoftext|>


<commit_before>/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
 *
 * (c) 2011-2013, Alexander C. Gessler
 *  https://github.com/acgessler/medea.js
 *
 * Made available under the terms and conditions of a 3-clause BSD license.
 *
 */

medealib.define('lodmesh',['mesh'],function(medealib, undefined) {
	"use strict";
	var medea = this, gl = medea.gl;

	// Special render job that selects the most suitable LOD before
	// dispatching the draw command to the renderer.
	//
	// This ensures that, if a mesh is drawn multiple times in a scene,
	// the correct LOD is selected for each instance.
	//
	// See |medea.LODMesh._SelectLOD|
	medea.LODMeshRenderJob = medea.MeshRenderJob.extend({

		Draw : function(renderer, statepool) {
			// This implicitly assumes that MeshRenderJob's distance
			// estimate is indeed the squared distance.
			this.mesh._SelectLOD(this.DistanceEstimate());
			renderer.DrawMesh(this, statepool);
		},
	});

	// Mesh with a simple LOD implementation that changes the index
	// buffer (but not the vertex buffer) depending on a function
	// of the distance to the camera.
	//
	// To tweak the LOD selection logic, override |_SelectLOD|
	medea.LODMesh = medea.Mesh.extend({

		lod_attenuation_scale : 1,
		ibo_levels : null,
		ibo_creation_flags : 0,
		lod_offset : 0,

		init : function(vbo, ibo_levels, material, rq, pt, line_ibo, ibo_creation_flags) {
			// Submit a null IBO to the base class, we will update
			// |this.ibo| before drawing.
			this._super(vbo, null, material, rq, pt, line_ibo);

			this.ibo_creation_flags = ibo_creation_flags | 0;
			this.ibo_levels = ibo_levels;
		},

		Render : function(viewport, node, rqmanager) {
			// Construct a renderable capable of drawing this mesh with the correct LOD
			rqmanager.Push(this.rq_idx, new medea.LODMeshRenderJob(this, node, viewport));
		},

		LODAttenuationScale :  medealib.Property('lod_attenuation_scale'),
		LODOffset :  medealib.Property('lod_offset'),

		_Clone : function(material_or_color) {
			var mesh = medea.CreateLODMesh(this.vbo, this.ibo_levels,
				material_or_color || this.Material(),
				this.rq,
				this.pt,
				this.line_ibo,
				this.ibo_creation_flags);

			// Copy BB: this is necessary if this.BB has been
			// manually specified as opposed to the BB being
			// derived from the VBO's extents.
			mesh.BB(this.BB());
			mesh.LODAttenuationScale(this.LODAttenuationScale());
			mesh.LODOffset(this.LODOffset());
			return mesh;
		},

		_SelectLOD : function(sq_distance) {
			// Multiply by two to undo the square in log space
			var log_distance = Math.log(sq_distance * 0.0001) * 2 * this.lod_attenuation_scale;
			var lod = Math.max(0, Math.min(this.ibo_levels.length - 1,
				~~log_distance + this.lod_offset));

			// Eval the LOD level as needed
			var indices = this.ibo_levels[lod];

			if (typeof indices == "function") {
				indices = this.ibo_levels[lod] = indices();
			}
			if (Array.isArray(indices) && typeof indices === 'object' && !(indices instanceof medealib.Class)) {
				indices = this.ibo_levels[lod] = medea.CreateIndexBuffer(indices, this.ibo_creation_flags);
			}

			this.ibo = indices;
			return 0;
		}
	});

	// Variant of |medea.CreateSimpleMesh| for creating LOD meshes.
	//
	// |ibo_levels| is an array of the index buffer sources for all
	// supported LOD levels. Each entry can be one of:
	//
	//  1) Array of indices
	//  2) medea.IndexBuffer
	//  3) function() -> |medea.IndexBuffer|
	//
	//  Unlike CreateSimpleMesh(), 1) and 3) are not evaluated immediately but
	//  the first time the respective LOD level is requested.
	//
	// Supports both index- and vertexbuffer specific |flags|.
	//
	// Mesh will not be cached unless |cache_name| is given.
	medea.CreateLODMesh = function(vertices, ibo_levels, material_or_color, flags, cache_name, rq, pt, line_ibo) {
		if (typeof vertices === 'object' && !(vertices instanceof medealib.Class)) {
			vertices = medea.CreateVertexBuffer(vertices,flags);
		}

		if (Array.isArray(material_or_color)) {
			material_or_color = medea.CreateSimpleMaterialFromColor(material_or_color);
		}

		var mesh = new medea.LODMesh(vertices, ibo_levels, material_or_color, rq, pt, line_ibo);
		if (cache_name !== undefined) {
			medea._mesh_cache[cache_name] = mesh;
		}
		return mesh;
	};
});<commit_msg>LODMesh: more flexible API to make it easier to override LOD selection logic.<commit_after>/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
 *
 * (c) 2011-2013, Alexander C. Gessler
 *  https://github.com/acgessler/medea.js
 *
 * Made available under the terms and conditions of a 3-clause BSD license.
 *
 */

medealib.define('lodmesh',['mesh'],function(medealib, undefined) {
	"use strict";
	var medea = this, gl = medea.gl;

	// Special render job that selects the most suitable LOD before
	// dispatching the draw command to the renderer.
	//
	// This ensures that, if a mesh is drawn multiple times in a scene,
	// the correct LOD is selected for each instance.
	//
	// See |medea.LODMesh._SelectLOD|, |medea.LODMesh._ComputeLODLevel|
	medea.LODMeshRenderJob = medea.MeshRenderJob.extend({

		Draw : function(renderer, statepool) {
			// This implicitly assumes that MeshRenderJob's distance
			// estimate is indeed the squared distance.
			this.mesh._SelectLOD(this.DistanceEstimate());
			renderer.DrawMesh(this, statepool);
		},
	});

	// Mesh with a simple LOD implementation that changes the index
	// buffer (but not the vertex buffer) depending on a function
	// of the distance to the camera.
	//
	// To tweak the LOD selection logic, yu have two options:
	//   1) Override |_SelectLOD| for full control. As control returns,
	//      |this.ibo| should be the actual IBO to use for rendering.
	//   2) Override |_ComputeLODLevel| to tweak the selection of the
	//      LOD index, but not change the way how this maps to IBOs.
	medea.LODMesh = medea.Mesh.extend({

		lod_attenuation_scale : 1,
		ibo_levels : null,
		ibo_creation_flags : 0,
		lod_offset : 0,

		init : function(vbo, ibo_levels, material, rq, pt, line_ibo, ibo_creation_flags) {
			// Submit a null IBO to the base class, we will update
			// |this.ibo| before drawing.
			this._super(vbo, null, material, rq, pt, line_ibo);

			this.ibo_creation_flags = ibo_creation_flags | 0;
			this.ibo_levels = ibo_levels;
		},

		Render : function(viewport, node, rqmanager) {
			// Construct a renderable capable of drawing this mesh with the correct LOD
			rqmanager.Push(this.rq_idx, new medea.LODMeshRenderJob(this, node, viewport));
		},

		LODAttenuationScale :  medealib.Property('lod_attenuation_scale'),
		LODOffset :  medealib.Property('lod_offset'),

		_Clone : function(material_or_color) {
			var mesh = medea.CreateLODMesh(this.vbo, this.ibo_levels,
				material_or_color || this.Material(),
				this.rq,
				this.pt,
				this.line_ibo,
				this.ibo_creation_flags);

			// Copy BB: this is necessary if this.BB has been
			// manually specified as opposed to the BB being
			// derived from the VBO's extents.
			mesh.BB(this.BB());
			mesh.LODAttenuationScale(this.LODAttenuationScale());
			mesh.LODOffset(this.LODOffset());
			return mesh;
		},

		_ComputeLODLevel : function(sq_distance) {
			// Multiply by two to undo the square in log space
			var log_distance = Math.log(sq_distance * 0.0001) * 2 * this.lod_attenuation_scale;
			return Math.max(0, Math.min(this.ibo_levels.length - 1,
				~~log_distance + this.lod_offset));
		},

		_SelectLOD : function(sq_distance) {
			var lod = this._ComputeLODLevel(sq_distance);

			// Eval the LOD level as needed
			var indices = this.ibo_levels[lod];

			if (typeof indices == "function") {
				indices = this.ibo_levels[lod] = indices();
			}
			if (Array.isArray(indices) && typeof indices === 'object' && !(indices instanceof medealib.Class)) {
				indices = this.ibo_levels[lod] = medea.CreateIndexBuffer(indices, this.ibo_creation_flags);
			}

			this.ibo = indices;
			return 0;
		}
	});

	// Variant of |medea.CreateSimpleMesh| for creating LOD meshes.
	//
	// |ibo_levels| is an array of the index buffer sources for all
	// supported LOD levels. Each entry can be one of:
	//
	//  1) Array of indices
	//  2) medea.IndexBuffer
	//  3) function() -> |medea.IndexBuffer|
	//
	//  Unlike CreateSimpleMesh(), 1) and 3) are not evaluated immediately but
	//  the first time the respective LOD level is requested.
	//
	// Supports both index- and vertexbuffer specific |flags|.
	//
	// Mesh will not be cached unless |cache_name| is given.
	medea.CreateLODMesh = function(vertices, ibo_levels, material_or_color, flags, cache_name, rq, pt, line_ibo) {
		if (typeof vertices === 'object' && !(vertices instanceof medealib.Class)) {
			vertices = medea.CreateVertexBuffer(vertices,flags);
		}

		if (Array.isArray(material_or_color)) {
			material_or_color = medea.CreateSimpleMaterialFromColor(material_or_color);
		}

		var mesh = new medea.LODMesh(vertices, ibo_levels, material_or_color, rq, pt, line_ibo);
		if (cache_name !== undefined) {
			medea._mesh_cache[cache_name] = mesh;
		}
		return mesh;
	};
});<|endoftext|>


<commit_before>function BaseService() {

}

BaseService.prototype.getContents = function (options) {
    console.log("getContents called on base service", this.type, options);
    if (!options) options = {};
    if (!options.forceRefresh && this.cachedContents) {
        return Promise.resolve(this.cachedContents);
    }
    return this.findAvailableContents(options).then(function (contents) {
        console.log("Caching content for ", this.type, contents.length);
        this.cachedContents = contents;
        return contents;
    }.bind(this));
};

BaseService.prototype.start = function (content) {
    var thiz = this;

    return new Promise(function (resolve, reject) {
        if (thiz.converter) {
            try {
                thiz.converter.destroy();
            } catch (e) {}
        } else {
            thiz.converter = thiz.createConverter();
        }

        thiz.converter.convert(content.url).then(function (url) {
            resolve({
                url: url,
                live: thiz.isLiveContent(content),
                content: content
            })
        }).catch(function (e) {
            reject(e);
        });
    });
};
BaseService.prototype.terminate = function () {
    if (this.converter) {
        try {
            this.converter.destroy();
        } catch (e) {}
    }
};
BaseService.prototype.isLiveContent = function (content) {
    return false;
};

BaseService.prototype.findCachedContent = function (url) {
    return this.cache ? this.cache[url] : {
        title: url,
        contentType: "video",
        type: this.type,
        duration: null,
        description: "",
        thumbnails: [],
        url: url,
        extras: {}
    };
};

BaseService.prototype.getCurrentStatus = function () {
    return this.converter ? this.converter.status : State.Idle;
};
BaseService.prototype.getBackendStatus = function () {
    return this.converter ? this.converter.getFullStatus() : null;
};

module.exports = BaseService;
<commit_msg>Fix 'Destroyed' status management<commit_after>function BaseService() {

}

BaseService.prototype.getContents = function (options) {
    console.log("getContents called on base service", this.type, options);
    if (!options) options = {};
    if (!options.forceRefresh && this.cachedContents) {
        return Promise.resolve(this.cachedContents);
    }
    return this.findAvailableContents(options).then(function (contents) {
        console.log("Caching content for ", this.type, contents.length);
        this.cachedContents = contents;
        return contents;
    }.bind(this));
};

BaseService.prototype.start = function (content) {
    var thiz = this;

    return new Promise(function (resolve, reject) {
        if (thiz.converter) {
            try {
                thiz.converter.destroy();
            } catch (e) {}
        }
        thiz.converter = thiz.createConverter();

        thiz.converter.convert(content.url).then(function (url) {
            resolve({
                url: url,
                live: thiz.isLiveContent(content),
                content: content
            })
        }).catch(function (e) {
            reject(e);
        });
    });
};
BaseService.prototype.terminate = function () {
    if (this.converter) {
        try {
            this.converter.destroy();
        } catch (e) {}
    }
};
BaseService.prototype.isLiveContent = function (content) {
    return false;
};

BaseService.prototype.findCachedContent = function (url) {
    return this.cache ? this.cache[url] : {
        title: url,
        contentType: "video",
        type: this.type,
        duration: null,
        description: "",
        thumbnails: [],
        url: url,
        extras: {}
    };
};

BaseService.prototype.getCurrentStatus = function () {
    return this.converter ? this.converter.status : State.Idle;
};
BaseService.prototype.getBackendStatus = function () {
    return this.converter ? this.converter.getFullStatus() : null;
};

module.exports = BaseService;
<|endoftext|>


<commit_before><commit_msg>add floatField<commit_after><|endoftext|>


<commit_before>// TODO Remove this file? Rename? Edits?

/**
 * # edits(socket, doc)
 *
 * This function is called edits because takes the diffs and create
 * "edits" to send to the server. But this is all code shared by both server
 * and client, so maybe it's not the best name.
 *
 * ### Params:
 *
 * **Socket.io** *socket*
 * **JSONDocument** *doc*
 * **JSONDocument** *shadow*
 * **StorageDriver** *storage*
 * **EventEmitter** *eventemitter* Optional
 */

/*! */

let JSONDocument = require('./document');
let EventEmitter = require('events').EventEmitter;

module.exports = function edits(socket, doc, shadow, storage, eventemitter = new EventEmitter) {
  let sendDiff = function sendDiff() {
    let diff = doc.diff(shadow);

    // Step 7, continue to send diff as long as the documents is not identical
    if (typeof diff !== 'undefined') {
      // Step 2, changes are copied to the shadow
      shadow.patch(diff);

      // Step 3a, changes are sent to server
      socket.emit('DIFF', diff);
      return true;
    }

    // Step 3b, nothing is sent to the server
    return false;
  };

  let patchDocs = function patchDocs(data) {
    doc.patch(data);
    shadow.patch(data);
    eventemitter.emit('update', doc.json());

    // Step 6, send new diff to all connected clients
    sendDiff();
  };

  // Create patch from received diff
  socket.on('DIFF', function edits(data) {
    // Step 4, a patch is created from the changes
    let patch = data;

    // Step 5, both the doc and shadow is patched
    if (typeof storage === 'undefined') {
      patchDocs(patch);
    } else {
      // TODO Handle error!
      storage.getJSON().then((json, error) => {
        if (error) {
          console.log(error);
        } else {
          doc.update(json);
          patchDocs(patch);
          // Save
          storage.setFromDocument(doc);
        }
      });
    }
  });

  return {

    /**
     * Send diff to clients/server
     *
     * @method sendDiff
     * @returns false if there is no diff, else true
     */

    sendDiff,

    /**
     * ## eventemitter
     *
     * EventEmitter
     *
     * ### Events:
     *
     * * update
     *
     * @type EventEmitter
     */

    eventemitter
  };
};
<commit_msg>Fix jslint error<commit_after>// TODO Remove this file? Rename? Edits?

/**
 * # edits(socket, doc)
 *
 * This function is called edits because takes the diffs and create
 * "edits" to send to the server. But this is all code shared by both server
 * and client, so maybe it's not the best name.
 *
 * ### Params:
 *
 * **Socket.io** *socket*
 * **JSONDocument** *doc*
 * **JSONDocument** *shadow*
 * **StorageDriver** *storage*
 * **EventEmitter** *eventemitter* Optional
 */

/*! */

let EventEmitter = require('events').EventEmitter;

module.exports = function edits(socket, doc, shadow, storage, eventemitter = new EventEmitter) {
  let sendDiff = function sendDiff() {
    let diff = doc.diff(shadow);

    // Step 7, continue to send diff as long as the documents is not identical
    if (typeof diff !== 'undefined') {
      // Step 2, changes are copied to the shadow
      shadow.patch(diff);

      // Step 3a, changes are sent to server
      socket.emit('DIFF', diff);
      return true;
    }

    // Step 3b, nothing is sent to the server
    return false;
  };

  let patchDocs = function patchDocs(data) {
    doc.patch(data);
    shadow.patch(data);
    eventemitter.emit('update', doc.json());

    // Step 6, send new diff to all connected clients
    sendDiff();
  };

  // Create patch from received diff
  socket.on('DIFF', function edits(data) {
    // Step 4, a patch is created from the changes
    let patch = data;

    // Step 5, both the doc and shadow is patched
    if (typeof storage === 'undefined') {
      patchDocs(patch);
    } else {
      // TODO Handle error!
      storage.getJSON().then((json, error) => {
        if (error) {
          console.log(error);
        } else {
          doc.update(json);
          patchDocs(patch);
          // Save
          storage.setFromDocument(doc);
        }
      });
    }
  });

  return {

    /**
     * Send diff to clients/server
     *
     * @method sendDiff
     * @returns false if there is no diff, else true
     */

    sendDiff,

    /**
     * ## eventemitter
     *
     * EventEmitter
     *
     * ### Events:
     *
     * * update
     *
     * @type EventEmitter
     */

    eventemitter
  };
};
<|endoftext|>


<commit_before>function navigateToMarketplace(projectId, solutionId) {
  const url = `https://console.cloud.google.com/marketplace/details/${projectId}/${solutionId}?project=${projectId}`;
  window.open(url, '_blank');
}

function navigateToDataset(projectId, datasetId) {
  const url = `https://console.cloud.google.com/bigquery?project=${projectId}&p=${projectId}&d=${datasetId}`;
  window.open(url, '_blank');
}

function navigateToTable(projectId, datasetId, tableId) {
  const url = `https://console.cloud.google.com/bigquery?project=${projectId}&p=${projectId}&d=${datasetId}&t=${tableId}&page=table`;
  window.open(url, '_blank');
}

export default {
  navigateToMarketplace,
  navigateToDataset,
  navigateToTable
};
<commit_msg>Navigate to dataset not opening dataset page (#458)<commit_after>function navigateToMarketplace(projectId, solutionId) {
  const url = `https://console.cloud.google.com/marketplace/details/${projectId}/${solutionId}?project=${projectId}`;
  window.open(url, '_blank');
}

function navigateToDataset(projectId, datasetId) {
  const url = `https://console.cloud.google.com/bigquery?project=${projectId}&p=${projectId}&d=${datasetId}&page=dataset`;
  window.open(url, '_blank');
}

function navigateToTable(projectId, datasetId, tableId) {
  const url = `https://console.cloud.google.com/bigquery?project=${projectId}&p=${projectId}&d=${datasetId}&t=${tableId}&page=table`;
  window.open(url, '_blank');
}

export default {
  navigateToMarketplace,
  navigateToDataset,
  navigateToTable
};
<|endoftext|>


<commit_before>"use strict";

const async = require("async");
const log = require('../utils/logger');
const toJson = require('../utils/to_json');
const _ = require('lodash');
const queue = require('../workers/queue');

module.exports = (sequelize, DataTypes) => {
  const AcNotification = sequelize.define("AcNotification", {
    priority: { type: DataTypes.INTEGER, allowNull: false },
    type: { type: DataTypes.STRING, allowNull: false },
    status: { type: DataTypes.STRING, allowNull: false, defaultValue: 'active' },
    sent_email: { type: DataTypes.INTEGER, default: false },
    sent_push: { type: DataTypes.INTEGER, default: false },
    processed_at: DataTypes.DATE,
    user_interaction_profile: DataTypes.JSONB,
    from_notification_setting: DataTypes.STRING,
    viewed: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
    deleted: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }
  }, {

    defaultScope: {
      where: {
        deleted: false
      }
    },

    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',

    indexes: [
      {
        name: 'notification_by_type_and_user_id',
        fields: ['type','user_id']
      },
      { name: 'notification_user_id_deleted_viewed',
        fields: ['user_id', 'deleted', 'viewed']
      },
      { name: 'ac_notifications_idx_user_id_type_deleted_created_at',
        fields: ['user_id','type','deleted','created_at']
      },
      {
        fields: ['user_interaction_profile'],
        using: 'gin',
        operator: 'jsonb_path_ops'
      },
      {
        name: 'ac_notifications_idx_deleted_id',
        fields: ['deleted','id']
      }
    ],

    // Add following index manually for high throughput sites
    // CREATE INDEX notification_activit_idx_ac_id ON notification_activities (ac_notification_id);

    underscored: true,

    tableName: 'ac_notifications'
  });

  AcNotification.associate = (models) => {
    AcNotification.belongsToMany(models.AcActivity, { as: 'AcActivities', through: 'notification_activities' });
    AcNotification.belongsToMany(models.AcDelayedNotification, { as: 'AcDelayedNotifications', through: 'delayed_notifications' });
    AcNotification.belongsTo(models.User,{ foreignKey: 'user_id' });
  };

  AcNotification.METHOD_MUTED = 0;
  AcNotification.METHOD_BROWSER = 1;
  AcNotification.METHOD_EMAIL = 2;
  AcNotification.METHOD_PUSH = 3;
  AcNotification.METHOD_SMS = 4;

  AcNotification.FREQUENCY_AS_IT_HAPPENS = 0;
  AcNotification.FREQUENCY_HOURLY = 1;
  AcNotification.FREQUENCY_DAILY = 2;
  AcNotification.FREQUENCY_WEEKLY = 3;
  AcNotification.FREQUENCY_BI_WEEKLY = 4;
  AcNotification.FREQUENCY_MONTHLY = 5;

  AcNotification.defaultNotificationSettings = {
    my_posts: {
      method: 2,
        frequency: 0
    },
    my_posts_endorsements: {
      method: 2,
        frequency: 2
    },
    my_points: {
      method: 2,
        frequency: 1
    },
    my_points_endorsements: {
      method: 2,
        frequency: 2
    },
    all_community: {
      method: 0,
        frequency: 3
    },
    all_group: {
      method: 0,
        frequency: 3
    },
    newsletter: {
      method: 2,
        frequency: 4
    }
  };

  AcNotification.anonymousNotificationSettings = {
    my_posts: {
      method: 1,
        frequency: 2
    },
    my_posts_endorsements: {
      method: 1,
        frequency: 2
    },
    my_points: {
      method: 1,
        frequency: 2
    },
    my_points_endorsements: {
      method: 1,
        frequency: 2
    },
    all_community: {
      method: 1,
        frequency: 3
    },
    all_group: {
      method: 1,
        frequency: 3
    },
    newsletter: {
      method: 1,
        frequency: 4
    }
  };

  AcNotification.ENDORSEMENT_GROUPING_TTL = 6 * 60 * 60 * 1000; // milliseconds

  AcNotification.processNotification = (notification, user, activity, callback) => {
    let queuePriority;
    if (user.last_login_at && ((new Date().getDate()-5)<user.last_login_at)) {
      queuePriority = 'high';
    } else {
      queuePriority = 'medium';
    }

    queue.create('process-notification-delivery', { id: notification.id }).priority(queuePriority).removeOnComplete(true).save();

    // Disabled for now
    //queue.create('process-notification-news-feed', { id: notification.id }).priority(queuePriority).removeOnComplete(true).save();

    // Its being updated and is not new
    if (callback) {
      notification.viewed = false;
      notification.changed('updated_at', true);
      notification.save().then((notificationIn) => {
        callback();
      }).catch((error) => {
        callback(error);
      });
    }
  };

  AcNotification.createReportNotifications = (user, activity, callback) => {
    log.info('createReportNotifications');

    let activityWithAdmins;
    let allAdmins;

    async.series([
      (seriesCallback) => {
        sequelize.models.AcActivity.findOne({
          where: { id: activity.id },
          include: [
            {
              model: sequelize.models.Community,
              required: true,
              include: [
                {
                  model: sequelize.models.User,
                  attributes: _.concat(sequelize.models.User.defaultAttributesWithSocialMediaPublicAndEmail, ['created_at', 'last_login_at']),
                  as: 'CommunityAdmins',
                  required: false
                }
              ]
            },
            {
              model: sequelize.models.Group,
              required: true,
              include: [
                {
                  model: sequelize.models.User,
                  attributes: _.concat(sequelize.models.User.defaultAttributesWithSocialMediaPublicAndEmail, ['created_at', 'last_login_at']),
                  as: 'GroupAdmins',
                  required: false
                }
              ]
            },
            {
              model: sequelize.models.Post,
              required: false
            },
            {
              model: sequelize.models.Point,
              required: false
            }
          ]
        }).then((results) => {
          if (results && (results.Community.CommunityAdmins || results.Community.GroupAdmins)) {
            activityWithAdmins = results;
            seriesCallback();
          } else {
            seriesCallback('Activity not found');
          }
        }).catch((error) => {
          seriesCallback(error);
        });
      },
      (seriesCallback)  =>{
        allAdmins = _.concat(activityWithAdmins.Community.CommunityAdmins, activityWithAdmins.Group.GroupAdmins);
        allAdmins = _.uniqBy(allAdmins, (admin) => {
          return admin.email;
        });
        async.eachSeries(allAdmins, (admin, innerSeriesCallback) => {
          sequelize.models.AcNotification.build({
            type: 'notification.report.content',
            priority: 100,
            status: 'active',
            ac_activity_id: activity.id,
            from_notification_setting: "reportContent",
            user_id: admin.id
          }).save().then((notification) => {
            if (notification) {
              notification.addAcActivities(activity).then((results) => {
                if (results) {
                  const notificationJson = { id: notification.id };
                  queue.create('process-notification-delivery', notificationJson).priority('high').removeOnComplete(true).save();
                  log.info('Notification Created', { notificationId: notification ?  notification.id : -1, userId: admin.id});
                  innerSeriesCallback();
                } else {
                  innerSeriesCallback("Notification Error Can't add activity");
                }
              });
            } else {
              log.error('Notification Creation Error', { err: "No notification", user: user.id});
              innerSeriesCallback("Could not create notification");
            }
          }).catch((error) => {
            log.error('Notification Creation Error', { err: error, user: user.id});
            innerSeriesCallback(error)
          });

        }, (error) => {
          seriesCallback(error);
        });
      }
    ],  (error) => {
      callback(error);
    });
  };

  AcNotification.createNotificationFromActivity = (user, activity, type, notification_setting_type, priority, callback) => {
    log.info('AcNotification Notification', {type: type, priority: priority });

    if (user==null) {
      user = { id: null };
    }

    if (typeof user == "number") {
      user = { id: user };
    }

    if (typeof user == "string" && user.length>0) {
      user = { id: user };
    }

    //TODO: Check AcMute and mute if needed

    sequelize.models.AcNotification.build({
      type: type,
      priority: priority,
      status: 'active',
      ac_activity_id: activity.id,
      from_notification_setting: notification_setting_type,
      user_id: user.id
    }).save().then( (notification) => {
      if (notification) {
        notification.addAcActivities(activity).then((results) => {
          if (results) {
            sequelize.models.AcNotification.processNotification(notification, user, activity);
            log.info('Notification Created', { notificationId: notification ?  notification.id : -1, userId: user.id});
            callback();
          } else {
            callback("Notification Error Can't add activity");
          }
        });
      } else {
        log.error('Notification Creation Error', { err: "No notification", user: user.id});
        callback("Notification Create Error");
      }
    }).catch((error) => {
      log.error('Notification Creation Error', { err: error, user: user.id});
      callback(error);
    });
  };

  return AcNotification;
};
<commit_msg>New default for anon user<commit_after>"use strict";

const async = require("async");
const log = require('../utils/logger');
const toJson = require('../utils/to_json');
const _ = require('lodash');
const queue = require('../workers/queue');

module.exports = (sequelize, DataTypes) => {
  const AcNotification = sequelize.define("AcNotification", {
    priority: { type: DataTypes.INTEGER, allowNull: false },
    type: { type: DataTypes.STRING, allowNull: false },
    status: { type: DataTypes.STRING, allowNull: false, defaultValue: 'active' },
    sent_email: { type: DataTypes.INTEGER, default: false },
    sent_push: { type: DataTypes.INTEGER, default: false },
    processed_at: DataTypes.DATE,
    user_interaction_profile: DataTypes.JSONB,
    from_notification_setting: DataTypes.STRING,
    viewed: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
    deleted: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }
  }, {

    defaultScope: {
      where: {
        deleted: false
      }
    },

    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',

    indexes: [
      {
        name: 'notification_by_type_and_user_id',
        fields: ['type','user_id']
      },
      { name: 'notification_user_id_deleted_viewed',
        fields: ['user_id', 'deleted', 'viewed']
      },
      { name: 'ac_notifications_idx_user_id_type_deleted_created_at',
        fields: ['user_id','type','deleted','created_at']
      },
      {
        fields: ['user_interaction_profile'],
        using: 'gin',
        operator: 'jsonb_path_ops'
      },
      {
        name: 'ac_notifications_idx_deleted_id',
        fields: ['deleted','id']
      }
    ],

    // Add following index manually for high throughput sites
    // CREATE INDEX notification_activit_idx_ac_id ON notification_activities (ac_notification_id);

    underscored: true,

    tableName: 'ac_notifications'
  });

  AcNotification.associate = (models) => {
    AcNotification.belongsToMany(models.AcActivity, { as: 'AcActivities', through: 'notification_activities' });
    AcNotification.belongsToMany(models.AcDelayedNotification, { as: 'AcDelayedNotifications', through: 'delayed_notifications' });
    AcNotification.belongsTo(models.User,{ foreignKey: 'user_id' });
  };

  AcNotification.METHOD_MUTED = 0;
  AcNotification.METHOD_BROWSER = 1;
  AcNotification.METHOD_EMAIL = 2;
  AcNotification.METHOD_PUSH = 3;
  AcNotification.METHOD_SMS = 4;

  AcNotification.FREQUENCY_AS_IT_HAPPENS = 0;
  AcNotification.FREQUENCY_HOURLY = 1;
  AcNotification.FREQUENCY_DAILY = 2;
  AcNotification.FREQUENCY_WEEKLY = 3;
  AcNotification.FREQUENCY_BI_WEEKLY = 4;
  AcNotification.FREQUENCY_MONTHLY = 5;

  AcNotification.defaultNotificationSettings = {
    my_posts: {
      method: 2,
        frequency: 0
    },
    my_posts_endorsements: {
      method: 2,
        frequency: 2
    },
    my_points: {
      method: 2,
        frequency: 1
    },
    my_points_endorsements: {
      method: 2,
        frequency: 2
    },
    all_community: {
      method: 0,
        frequency: 3
    },
    all_group: {
      method: 0,
        frequency: 3
    },
    newsletter: {
      method: 2,
        frequency: 4
    }
  };

  AcNotification.anonymousNotificationSettings = {
    my_posts: {
      method: 1,
        frequency: 2
    },
    my_posts_endorsements: {
      method: 1,
        frequency: 2
    },
    my_points: {
      method: 1,
        frequency: 2
    },
    my_points_endorsements: {
      method: 1,
        frequency: 2
    },
    all_community: {
      method: 0,
        frequency: 3
    },
    all_group: {
      method: 0,
        frequency: 3
    },
    newsletter: {
      method: 1,
        frequency: 4
    }
  };

  AcNotification.ENDORSEMENT_GROUPING_TTL = 6 * 60 * 60 * 1000; // milliseconds

  AcNotification.processNotification = (notification, user, activity, callback) => {
    let queuePriority;
    if (user.last_login_at && ((new Date().getDate()-5)<user.last_login_at)) {
      queuePriority = 'high';
    } else {
      queuePriority = 'medium';
    }

    queue.create('process-notification-delivery', { id: notification.id }).priority(queuePriority).removeOnComplete(true).save();

    // Disabled for now
    //queue.create('process-notification-news-feed', { id: notification.id }).priority(queuePriority).removeOnComplete(true).save();

    // Its being updated and is not new
    if (callback) {
      notification.viewed = false;
      notification.changed('updated_at', true);
      notification.save().then((notificationIn) => {
        callback();
      }).catch((error) => {
        callback(error);
      });
    }
  };

  AcNotification.createReportNotifications = (user, activity, callback) => {
    log.info('createReportNotifications');

    let activityWithAdmins;
    let allAdmins;

    async.series([
      (seriesCallback) => {
        sequelize.models.AcActivity.findOne({
          where: { id: activity.id },
          include: [
            {
              model: sequelize.models.Community,
              required: true,
              include: [
                {
                  model: sequelize.models.User,
                  attributes: _.concat(sequelize.models.User.defaultAttributesWithSocialMediaPublicAndEmail, ['created_at', 'last_login_at']),
                  as: 'CommunityAdmins',
                  required: false
                }
              ]
            },
            {
              model: sequelize.models.Group,
              required: true,
              include: [
                {
                  model: sequelize.models.User,
                  attributes: _.concat(sequelize.models.User.defaultAttributesWithSocialMediaPublicAndEmail, ['created_at', 'last_login_at']),
                  as: 'GroupAdmins',
                  required: false
                }
              ]
            },
            {
              model: sequelize.models.Post,
              required: false
            },
            {
              model: sequelize.models.Point,
              required: false
            }
          ]
        }).then((results) => {
          if (results && (results.Community.CommunityAdmins || results.Community.GroupAdmins)) {
            activityWithAdmins = results;
            seriesCallback();
          } else {
            seriesCallback('Activity not found');
          }
        }).catch((error) => {
          seriesCallback(error);
        });
      },
      (seriesCallback)  =>{
        allAdmins = _.concat(activityWithAdmins.Community.CommunityAdmins, activityWithAdmins.Group.GroupAdmins);
        allAdmins = _.uniqBy(allAdmins, (admin) => {
          return admin.email;
        });
        async.eachSeries(allAdmins, (admin, innerSeriesCallback) => {
          sequelize.models.AcNotification.build({
            type: 'notification.report.content',
            priority: 100,
            status: 'active',
            ac_activity_id: activity.id,
            from_notification_setting: "reportContent",
            user_id: admin.id
          }).save().then((notification) => {
            if (notification) {
              notification.addAcActivities(activity).then((results) => {
                if (results) {
                  const notificationJson = { id: notification.id };
                  queue.create('process-notification-delivery', notificationJson).priority('high').removeOnComplete(true).save();
                  log.info('Notification Created', { notificationId: notification ?  notification.id : -1, userId: admin.id});
                  innerSeriesCallback();
                } else {
                  innerSeriesCallback("Notification Error Can't add activity");
                }
              });
            } else {
              log.error('Notification Creation Error', { err: "No notification", user: user.id});
              innerSeriesCallback("Could not create notification");
            }
          }).catch((error) => {
            log.error('Notification Creation Error', { err: error, user: user.id});
            innerSeriesCallback(error)
          });

        }, (error) => {
          seriesCallback(error);
        });
      }
    ],  (error) => {
      callback(error);
    });
  };

  AcNotification.createNotificationFromActivity = (user, activity, type, notification_setting_type, priority, callback) => {
    log.info('AcNotification Notification', {type: type, priority: priority });

    if (user==null) {
      user = { id: null };
    }

    if (typeof user == "number") {
      user = { id: user };
    }

    if (typeof user == "string" && user.length>0) {
      user = { id: user };
    }

    //TODO: Check AcMute and mute if needed

    sequelize.models.AcNotification.build({
      type: type,
      priority: priority,
      status: 'active',
      ac_activity_id: activity.id,
      from_notification_setting: notification_setting_type,
      user_id: user.id
    }).save().then( (notification) => {
      if (notification) {
        notification.addAcActivities(activity).then((results) => {
          if (results) {
            sequelize.models.AcNotification.processNotification(notification, user, activity);
            log.info('Notification Created', { notificationId: notification ?  notification.id : -1, userId: user.id});
            callback();
          } else {
            callback("Notification Error Can't add activity");
          }
        });
      } else {
        log.error('Notification Creation Error', { err: "No notification", user: user.id});
        callback("Notification Create Error");
      }
    }).catch((error) => {
      log.error('Notification Creation Error', { err: error, user: user.id});
      callback(error);
    });
  };

  return AcNotification;
};
<|endoftext|>


<commit_before>(function ($) {
    'use strict';

    $.widget('ui.map_location', {
        _create: function () {

        var element = $(this.element),
                me = this,
                options = jQuery.parseJSON(element.data('options')),
                map,
                panorama;

            me.options = options;
            me.element = element;

            me.panorama = panorama;
            me.map = map;

            me.checkGoogleVar();

        },

        checkGoogleVar: function() {

            var me = this;

            window.setTimeout(function () {

                if (window.google) {
                    me.geocodeAddress();
                } else {
                    me.checkGoogleVar();
                }
            }, 100);
        },

        geocodeAddress: function () {

                var me = this,
                    geocoder = new google.maps.Geocoder(),
                    address,
                    regexp = new RegExp('^(.* [^0-9]*[0-9]+)(.*)$');

                address = [
                    me.element.attr('data-street').replace(regexp, '$1'),
                    me.element.attr('data-postcode'),
                    me.element.attr('data-city'),
                    me.element.attr('data-country')
                ];

                geocoder.geocode({
                    address: address.join(', ')
                }, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
                        me.initView(results[0].geometry);
                    }
                });
            },

            initView: function(geometry) {

                var me = this,
                    marker,
                    latLng = geometry.location;

                if (me.options.type.toLowerCase() == "streetview") {
                    me.buildStreetView(latLng);
                } else if (me.options.type.toLowerCase() == "map") {
                    me.buildMap(latLng);
                }

            },

            buildMap: function(latLng) {

                var me = this,
                    marker,
                    options = {
                        zoom: 14,
                        center: latLng,
                        disableDoubleClickZoom: true,
                        disableDefaultUI: true,
                        keyboardShortcuts: false,
                        draggable: false,
                        scrollwheel: false,
                        panControl: false,
                        rotateControl: false,
                        scaleControl: false,
                        componentRestrictions: {}
                    };

                if (me.options.blackwhite == true) {
                    options.styles = [{
                       "stylers": [
                             { "saturation": -100 },
                             { "lightness": -8 },
                             { "gamma": 1.18 }
                         ]
                      }
                    ];
                }

                me.map = new google.maps.Map(me.element[0], options);

                marker = new google.maps.Marker({
                    map: me.map,
                    draggable: true,
                    position: latLng,
                    icon: '/lib/images/marker-default.png'

                });

                if (me.options.recenter == true) {
                    google.maps.event.addListenerOnce(me.map, "projection_changed", function() {
                        me.recenterMap(me.map);
                    });
                }

            },

            buildStreetView: function(latLng) {

                var me = this,
                    streetViewService = new google.maps.StreetViewService(),
                    STREETVIEW_MAX_DISTANCE = 100;

                streetViewService.getPanoramaByLocation(latLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {

                    var panoramaLatLng = streetViewPanoramaData.location.latLng,
                        heading = google.maps.geometry.spherical.computeHeading(latLng, panoramaLatLng);

                    if (status === google.maps.StreetViewStatus.OK) {

                          me.panorama = new google.maps.StreetViewPanorama(
                          me.element[0], {
                            position: latLng,
                            pov: {heading: heading, pitch: 0},
                            zoom: 1,
                            disableDefaultUI: true
                          });
                    } else {
                        if (me.options.fallback == true) {
                            me.buildMap(latLng);
                        }
                    }
                });

            },

            recenterMap: function(map) {

                var me = this,
                    mainContentEl = $('.' + me.element.data('main-content-class'));

                    if (mainContentEl.size() == 0) return false;

                    var masthead = $(me.element),
                    mastheadHeight = masthead[0].clientHeight,
                    mastheadOffsetTop = masthead[0].offsetTop,
                    mainContentOffsetTop = mainContentEl[0].offsetTop,
                    offsetY = (mastheadHeight / 2) - ((mainContentOffsetTop - mastheadOffsetTop) / 2),
                    centerPoint = map.getProjection().fromLatLngToPoint(map.getCenter()),
                    offsetPoint = new google.maps.Point(0, offsetY / Math.pow(2, map.getZoom())),
                    newCenterPoint = new google.maps.Point(centerPoint.x, centerPoint.y + offsetPoint.y);

                    map.setCenter(map.getProjection().fromPointToLatLng(newCenterPoint));
            }

    });
})(jQuery);
<commit_msg>[base] more maps<commit_after>(function ($) {
    'use strict';

    $.widget('ui.map_location', {
        _create: function () {

        var element = $(this.element),
                me = this,
                options = jQuery.parseJSON(element.data('options')),
                map,
                panorama;

            me.options = options;
            me.element = element;

            me.panorama = panorama;
            me.map = map;

            me.checkGoogleVar();

        },

        checkGoogleVar: function() {

            var me = this;

            window.setTimeout(function () {

                if (window.google) {
                    me.geocodeAddress();
                } else {
                    me.checkGoogleVar();
                }
            }, 100);
        },

        geocodeAddress: function () {

                var me = this,
                    geocoder = new google.maps.Geocoder(),
                    address,
                    street = me.element.attr('data-street').trim();

                if (!street || street == '') return false;

                address = [
                    street = /\s*\w+(?:\s+\d+)?/.exec(street)[0],
                    me.element.attr('data-postcode'),
                    me.element.attr('data-city'),
                    me.element.attr('data-country')
                ];

                geocoder.geocode({
                    address: address.join(', ')
                }, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
                        me.initView(results[0].geometry);
                    }
                });
            },

            initView: function(geometry) {

                var me = this,
                    marker,
                    latLng = geometry.location;

                if (me.options.type.toLowerCase() == "streetview") {
                    me.buildStreetView(latLng);
                } else if (me.options.type.toLowerCase() == "map") {
                    me.buildMap(latLng);
                }

            },

            buildMap: function(latLng) {

                var me = this,
                    marker,
                    options = {
                        zoom: 14,
                        center: latLng,
                        disableDoubleClickZoom: true,
                        disableDefaultUI: true,
                        keyboardShortcuts: false,
                        draggable: false,
                        scrollwheel: false,
                        panControl: false,
                        rotateControl: false,
                        scaleControl: false,
                        componentRestrictions: {}
                    };

                if (me.options.blackwhite == true) {
                    options.styles = [{
                       "stylers": [
                             { "saturation": -100 },
                             { "lightness": -8 },
                             { "gamma": 1.18 }
                         ]
                      }
                    ];
                }

                me.map = new google.maps.Map(me.element[0], options);

                marker = new google.maps.Marker({
                    map: me.map,
                    draggable: true,
                    position: latLng,
                    icon: '/lib/images/marker-default.png'
                });

                if (me.options.recenter == true) {
                    google.maps.event.addListenerOnce(me.map, "projection_changed", function() {
                        me.recenterMap(me.map);
                    });
                }

            },

            buildStreetView: function(latLng) {

                var me = this,
                    streetViewService = new google.maps.StreetViewService(),
                    STREETVIEW_MAX_DISTANCE = 100;

                    streetViewService.getPanoramaByLocation(latLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {

                    var panoramaLatLng = streetViewPanoramaData.location.latLng,
                        heading = google.maps.geometry.spherical.computeHeading(latLng, panoramaLatLng);

                    if (status === google.maps.StreetViewStatus.OK) {

                          me.panorama = new google.maps.StreetViewPanorama(
                          me.element[0], {
                            position: latLng,
                            pov: {heading: heading, pitch: 0},
                            zoom: 1,
                            disableDefaultUI: true
                          });
                    } else {
                        if (me.options.fallback == true) {
                            me.buildMap(latLng);
                        }
                    }

                });

            },

            recenterMap: function(map) {

                var me = this,
                    mainContentEl = $('.' + me.element.data('main-content-class'));

                    if (mainContentEl.size() == 0) return false;

                    var masthead = $(me.element),
                    mastheadHeight = masthead[0].clientHeight,
                    mastheadOffsetTop = masthead[0].offsetTop,
                    mainContentOffsetTop = mainContentEl[0].offsetTop,
                    offsetY = (mastheadHeight / 2) - ((mainContentOffsetTop - mastheadOffsetTop) / 2),
                    centerPoint = map.getProjection().fromLatLngToPoint(map.getCenter()),
                    offsetPoint = new google.maps.Point(0, offsetY / Math.pow(2, map.getZoom())),
                    newCenterPoint = new google.maps.Point(centerPoint.x, centerPoint.y + offsetPoint.y);

                    map.setCenter(map.getProjection().fromPointToLatLng(newCenterPoint));
            }

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


<commit_before>'use strict';

// Fake database for the moment
const database = require('./data.json');
const { fireCommand } = require('./commands');

const executeDatabaseAction = function () {
  return async function executeDatabaseAction(input) {
    const { command, args = {}, modelName, jsl } = input;
    const {
      order_by: orderBy,
      limit,
      offset,
      dry_run: dryRun,
      no_output: noOutput,
      data,
      filter,
    } = args;
    const collection = database[modelName];

    const opts = {
      jsl,
      orderBy,
      limit,
      offset,
      dryRun,
      noOutput,
      modelName,
    };
    const commandInput = { command, collection, filter, data, opts };
    const response = fireCommand(commandInput);
    return response;
  };
};

module.exports = {
  executeDatabaseAction,
};
<commit_msg>Whitespace styling<commit_after>'use strict';

// Fake database for the moment
const database = require('./data.json');
const { fireCommand } = require('./commands');

const executeDatabaseAction = function () {
  return async function executeDatabaseAction(input) {
    const { command, args = {}, modelName, jsl } = input;
    const {
      order_by: orderBy,
      limit,
      offset,
      dry_run: dryRun,
      no_output: noOutput,
      data,
      filter,
    } = args;
    const collection = database[modelName];

    const opts = { jsl, orderBy, limit, offset, dryRun, noOutput, modelName };
    const commandInput = { command, collection, filter, data, opts };
    const response = fireCommand(commandInput);
    return response;
  };
};

module.exports = {
  executeDatabaseAction,
};
<|endoftext|>


<commit_before>angular.module('angular-meteor.reactive', ['angular-meteor.reactive-scope']).factory('$reactive', ['$rootScope', '$parse', ($rootScope, $parse) => {
  class ReactiveContext {
    constructor(context) {
      if (!context || !angular.isObject(context)) {
        throw new Error('[angular-meteor][ReactiveContext] The context for ReactiveContext is required and must be an object!');
      }

      this.context = context;

      if ((this.context.constructor || angular.noop).toString().indexOf('Scope') > -1) {
        this.scope = this.context;
      }

      this.stoppables = [];
      this.propertiesTrackerDeps = {};
    }

    attach(scope) {
      if (!this.scope && (scope.constructor || angular.noop).toString().indexOf('Scope') > -1) {
        this.scope = scope;
      }

      return this;
    }

    _handleCursor(cursor, name) {
      if (angular.isUndefined(this.context[name])) {
        this._declareReactiveProperty(name, cursor.fetch());
      }
      else {
        jsondiffpatch.patch(this.context[name], jsondiffpatch.diff(this.context[name], cursor.fetch()));
      }

      let initial = true;
      let handle = cursor.observe({
        addedAt: (doc, atIndex) => {
          if (!initial) {
            this.context[name].splice(atIndex, 0, doc);
            this._propertyChanged(name);
          }
        },
        changedAt: (doc, oldDoc, atIndex) => {
          jsondiffpatch.patch(this.context[name][atIndex], jsondiffpatch.diff(this.context[name][atIndex], doc));
          this._propertyChanged(name);
        },
        movedTo: (doc, fromIndex, toIndex) => {
          this.context[name].splice(fromIndex, 1);
          this.context[name].splice(toIndex, 0, doc);
          this._propertyChanged(name);
        },
        removedAt: (oldDoc, atIndex) => {
          this.context[name].splice(atIndex, 1);
          this._propertyChanged(name);
        }
      });
      initial = false;

      return handle;
    };

    _handleNonCursor(data, name) {
      if (angular.isUndefined(this.context[name])) {
        this._declareReactiveProperty(name, data);
      }
      else {
        if ((!_.isObject(data) && !_.isArray(data)) ||
          (!_.isObject(this.context[name]) && !_.isArray(this.context[name]))) {
          this.context[name] = data;
        }
        else {
          jsondiffpatch.patch(this.context[name], jsondiffpatch.diff(this.context[name], data));
          this._propertyChanged(name);
        }
      }
    }

    static _isMeteorCursor(obj) {
      return obj instanceof Mongo.Collection.Cursor;
    };

    helpers(props) {
      _.chain(props).map((propValue, propName) => {
        return {
          key: propName,
          value: propValue
        }
      }).sortBy((prop, index, arr) => {
        if (angular.isFunction(prop.value)) {
          return arr.length + index;
        }
        else {
          return index;
        }
      }).forEach((prop) => {
        if (!angular.isFunction(prop.value)) {
          this._declareReactiveProperty(prop.key, prop.value);
        }
        else {
          this.stoppables.push(Tracker.autorun((comp) => {
            let data = prop.value.apply(this.context);

            Tracker.nonreactive(() => {
              if (ReactiveContext._isMeteorCursor(data)) {
                let stoppableObservation = this._handleCursor(data, prop.key);

                comp.onInvalidate(() => {
                  stoppableObservation.stop();
                  while (this.context[prop.key].length > 0) {
                    this.context[prop.key].pop();
                  }
                });
              }
              else {
                this._handleNonCursor(data, prop.key);
              }

              this._propertyChanged(prop.key);
            });
          }));
        }
      });

      return this;
    }

    _declareReactiveProperty(name, initialValue) {
      this.propertiesTrackerDeps[name] = new Tracker.Dependency();
      let property = initialValue;
      let self = this;

      Object.defineProperty(this.context, name, {
        configurable: true,
        enumerable: true,

        get: function () {
          self.propertiesTrackerDeps[name].depend();
          return property;
        },
        set: function (newValue) {
          property = newValue;
          self.propertiesTrackerDeps[name].changed();
        }
      });
    }

    _propertyChanged(propName) {
      if (this.scope && !$rootScope.$$phase) {
        this.scope.$digest();
      }

      this.propertiesTrackerDeps[propName].changed();
    }

    subscribe(name, fn) {
      fn = fn || angular.noop;

      if (this.scope && this.scope !== this.context) {
        this.stoppables.push(this.scope.subscribe(name, fn));
      }
      else {
        this.autorun(() => {
          this.stoppables.push(Meteor.subscribe(name, ...(fn() || [])));
        });
      }

      return this;
    }

    autorun(fn) {
      if (this.scope && this.scope !== this.context) {
        this.scope.autorun(fn);
      }
      else {
        this.stoppables.push(Meteor.autorun(fn));
      }

      return this;
    }

    stop() {
      angular.forEach(this.stoppables, (stoppable) => {
        stoppable.stop();
      });

      this.stoppables = [];

      return this;
    }
  }

  return function (context) {
    let instance = new ReactiveContext(context);

    context.helpers = instance.helpers.bind(instance);
    context.attach = instance.attach.bind(instance);
    context.stop = instance.stop.bind(instance);
    context.autorun = instance.autorun.bind(instance);
    context.subscribe = instance.subscribe.bind(instance);

    return instance;
  };
}]);
<commit_msg>Refactor reactive context module<commit_after>angular.module('angular-meteor.reactive', ['angular-meteor.reactive-scope']).factory('$reactive', ['$rootScope', '$parse', ($rootScope, $parse) => {
  class ReactiveContext {
    constructor(context) {
      if (!context || !angular.isObject(context)) {
        throw new Error('[angular-meteor][ReactiveContext] The context for ReactiveContext is required and must be an object!');
      }

      this.context = context;

      if (this._isScope(this.context)) {
        this.scope = this.context;
      }

      this.stoppables = [];
      this.propertiesTrackerDeps = {};
    }

    attach(scope) {
      if (!this.scope && this._isScope(scope)) {
        this.scope = scope;
      }

      return this;
    }

    _isScope(obj) {
      return obj instanceof Object.getPrototypeOf($rootScope).constructor;
    }

    _handleCursor(cursor, name) {
      if (angular.isUndefined(this.context[name])) {
        this._setValHelper(cursor.fetch(), name);
      }
      else {
        let diff = jsondiffpatch.diff(this.context[name], cursor.fetch());
        jsondiffpatch.patch(this.context[name], diff);
      }

      let initial = true;
      let handle = cursor.observe({
        addedAt: (doc, atIndex) => {
          if (!initial) {
            this.context[name].splice(atIndex, 0, doc);
            this._propertyChanged(name);
          }
        },
        changedAt: (doc, oldDoc, atIndex) => {
          let diff = jsondiffpatch.diff(this.context[name][atIndex], doc);
          jsondiffpatch.patch(this.context[name][atIndex], diff);
          this._propertyChanged(name);
        },
        movedTo: (doc, fromIndex, toIndex) => {
          this.context[name].splice(fromIndex, 1);
          this.context[name].splice(toIndex, 0, doc);
          this._propertyChanged(name);
        },
        removedAt: (oldDoc, atIndex) => {
          this.context[name].splice(atIndex, 1);
          this._propertyChanged(name);
        }
      });
      initial = false;

      return handle;
    };

    _handleNonCursor(data, name) {
      if (angular.isUndefined(this.context[name])) {
        this._setValHelper(data, name);
      }
      else {
        if ((!_.isObject(data) && !_.isArray(data)) ||
          (!_.isObject(this.context[name]) && !_.isArray(this.context[name]))) {
          this.context[name] = data;
        }
        else {
          let diff = jsondiffpatch.diff(this.context[name], data)
          jsondiffpatch.patch(this.context[name], diff);
          this._propertyChanged(name);
        }
      }
    }

    helpers(props) {
      let fns = {};
      let vals = {};

      _.each(props, (v, k) => {
        if (_.isFunction(v))
          fns[k] = v;
        else
          vals[k] = v;
      });

      // note that variable helpers are set before function helpers
      _.each(vals, this._setValHelper.bind(this));
      _.each(fns, this._setFnHelper.bind(this));

      return this;
    }

    _setValHelper(v, k) {
      this.propertiesTrackerDeps[k] = new Tracker.Dependency();

      Object.defineProperty(this.context, k, {
        configurable: true,
        enumerable: true,

        get: () => {
          this.propertiesTrackerDeps[k].depend();
          return v;
        },
        set: (newValue) => {
          v = newValue;
          this.propertiesTrackerDeps[k].changed();
        }
      });
    }

    _setFnHelper(fn, k) {
      this.stoppables.push(Tracker.autorun((comp) => {
        let data = fn.apply(this.context);

        Tracker.nonreactive(() => {
          if (this._isMeteorCursor(data)) {
            let stoppableObservation = this._handleCursor(data, k);

            comp.onInvalidate(() => {
              stoppableObservation.stop();
              while (this.context[k].length > 0) {
                this.context[k].pop();
              }
            });
          }
          else {
            this._handleNonCursor(data, k);
          }

          this._propertyChanged(k);
        });
      }));
    }

    _isMeteorCursor(obj) {
      return obj instanceof Mongo.Collection.Cursor;
    }

    _propertyChanged(k) {
      if (this.scope && !$rootScope.$$phase) {
        this.scope.$digest();
      }

      this.propertiesTrackerDeps[k].changed();
    }

    subscribe(name, fn) {
      fn = fn || angular.noop;

      if (this.scope && this.scope !== this.context) {
        this.stoppables.push(this.scope.subscribe(name, fn));
      }
      else {
        this.autorun(() => {
          let args = fn() || [];
          this.stoppables.push(Meteor.subscribe(name, ...args));
        });
      }

      return this;
    }

    autorun(fn) {
      if (this.scope && this.scope !== this.context) {
        this.scope.autorun(fn);
      }
      else {
        this.stoppables.push(Meteor.autorun(fn));
      }

      return this;
    }

    stop() {
      angular.forEach(this.stoppables, (stoppable) => {
        stoppable.stop();
      });

      this.stoppables = [];

      return this;
    }
  }

  return function(context) {
    let reactiveContext = new ReactiveContext(context);

    // manipulates the original context so it could access reactive methods
    _.keys(ReactiveContext.prototype)
      .filter((k) => k.charAt(0) != '_')
      .forEach((k) => context[k] = reactiveContext[k].bind(reactiveContext));

    return reactiveContext;
  };
}]);
<|endoftext|>


<commit_before>export default {
  isoName: 'ja',
  nativeName: '日本語 (にほんご)',
  label: {
    clear: 'クリア', // 'Clear',
    ok: 'OK', // 'OK',
    cancel: 'キャンセル', // 'Cancel',
    close: '閉じる', // 'Close',
    set: '設定', // 'Set',
    select: '選択', // 'Select',
    reset: 'リセット', // 'Reset',
    remove: '削除', // 'Remove',
    update: '更新', // 'Update',
    create: '作成', // 'Create',
    search: '検索', // 'Search',
    filter: 'フィルタ', // 'Filter',
    refresh: '再読込' // 'Refresh'
  },
  date: {
    days: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), // 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    daysShort: '日_月_火_水_木_金_土'.split('_'), // 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), // 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), // 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    headerTitle: date => new Intl.DateTimeFormat('ja-JP', {
      weekday: 'short', month: 'short', day: 'numeric'
    }).format(date),
    firstDayOfWeek: 1, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: true, // true
    pluralDay: '日々'
  },
  table: {
    noData: 'データがありません', // 'No data available',
    noResults: '検索結果がありません', // 'No matching records found',
    loading: '読込中...', // 'Loading...',
    selectedRecords: rows => (rows > 0 ? rows + '行を選択中' : '行を選択'),
    recordsPerPage: 'ページあたりの行数', // 'Rows per page:',
    allRows: '全て', // 'All',
    pagination: (start, end, total) => start + '-' + end + ' ／ ' + total,
    columns: '列' // 'Columns'
  },
  editor: {
    url: 'URL', // 'URL',
    bold: '太字', // 'Bold',
    italic: '斜体', // 'Italic',
    strikethrough: '取り消し線', // 'Strikethrough',
    underline: '下線', // 'Underline',
    unorderedList: '箇条書き', // 'Unordered List',
    orderedList: '段落番号', // 'Ordered List',
    subscript: '下付き', // 'Subscript',
    superscript: '上付き', // 'Superscript',
    hyperlink: 'リンク', // 'Hyperlink',
    toggleFullscreen: '全画面表示', // 'Toggle Fullscreen',
    quote: '引用文', // 'Quote',
    left: '左揃え', // 'Left align',
    center: '中央揃え', // 'Center align',
    right: '右揃え', // 'Right align',
    justify: '両端揃え', // 'Justify align',
    print: '印刷', // 'Print',
    outdent: 'インデント解除', // 'Decrease indentation',
    indent: 'インデント', // 'Increase indentation',
    removeFormat: '書式解除', // 'Remove formatting',
    formatting: '書式', // 'Formatting',
    fontSize: 'フォントサイズ', // 'Font Size',
    align: '揃え', // 'Align',
    hr: '横線を投入', // 'Insert Horizontal Rule',
    undo: '元に戻す', // 'Undo',
    redo: 'やり直し', // 'Redo',
    heading1: 'ヘッダー 1', // 'Heading 1',
    heading2: 'ヘッダー 2', // 'Heading 2',
    heading3: 'ヘッダー 3', // 'Heading 3',
    heading4: 'ヘッダー 4', // 'Heading 4',
    heading5: 'ヘッダー 5', // 'Heading 5',
    heading6: 'ヘッダー 6', // 'Heading 6',
    paragraph: '段落', // 'Paragraph',
    code: 'コード', // 'Code',
    size1: '小さい', // 'Very small',
    size2: 'やや小さい', // 'A bit small',
    size3: '普通', // 'Normal',
    size4: 'やや大きい', // 'Medium-large',
    size5: '大きい', // 'Big',
    size6: 'とても大きい', // 'Very big',
    size7: '最大', // 'Maximum',
    defaultFont: '初期フォント', // 'Default Font',
    viewSource: 'ソースを見る'
  },
  tree: {
    noNodes: 'ノードがありません', // 'No nodes available',
    noResults: '該当するノードがありません' // 'No matching nodes found'
  }
}
<commit_msg>update ja.js (#9358)<commit_after>export default {
  isoName: 'ja',
  nativeName: '日本語 (にほんご)',
  label: {
    clear: 'クリア', // 'Clear',
    ok: 'OK', // 'OK',
    cancel: 'キャンセル', // 'Cancel',
    close: '閉じる', // 'Close',
    set: '設定', // 'Set',
    select: '選択', // 'Select',
    reset: 'リセット', // 'Reset',
    remove: '削除', // 'Remove',
    update: '更新', // 'Update',
    create: '作成', // 'Create',
    search: '検索', // 'Search',
    filter: 'フィルタ', // 'Filter',
    refresh: '再読込' // 'Refresh'
  },
  date: {
    days: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), // 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
    daysShort: '日_月_火_水_木_金_土'.split('_'), // 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
    months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), // 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
    monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), // 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
    headerTitle: date => new Intl.DateTimeFormat('ja-JP', {
      weekday: 'short', month: 'short', day: 'numeric'
    }).format(date),
    firstDayOfWeek: 1, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: true, // true
    pluralDay: '日間'
  },
  table: {
    noData: 'データがありません', // 'No data available',
    noResults: '検索結果がありません', // 'No matching records found',
    loading: '読込中...', // 'Loading...',
    selectedRecords: rows => (rows > 0 ? rows + '行を選択中' : '行を選択'),
    recordsPerPage: 'ページあたりの行数', // 'Rows per page:',
    allRows: '全て', // 'All',
    pagination: (start, end, total) => start + '-' + end + ' ／ ' + total,
    columns: '列' // 'Columns'
  },
  editor: {
    url: 'URL', // 'URL',
    bold: '太字', // 'Bold',
    italic: '斜体', // 'Italic',
    strikethrough: '取り消し線', // 'Strikethrough',
    underline: '下線', // 'Underline',
    unorderedList: '箇条書き', // 'Unordered List',
    orderedList: '段落番号', // 'Ordered List',
    subscript: '下付き', // 'Subscript',
    superscript: '上付き', // 'Superscript',
    hyperlink: 'リンク', // 'Hyperlink',
    toggleFullscreen: '全画面表示', // 'Toggle Fullscreen',
    quote: '引用文', // 'Quote',
    left: '左揃え', // 'Left align',
    center: '中央揃え', // 'Center align',
    right: '右揃え', // 'Right align',
    justify: '両端揃え', // 'Justify align',
    print: '印刷', // 'Print',
    outdent: 'インデント解除', // 'Decrease indentation',
    indent: 'インデント', // 'Increase indentation',
    removeFormat: '書式解除', // 'Remove formatting',
    formatting: '書式', // 'Formatting',
    fontSize: 'フォントサイズ', // 'Font Size',
    align: '揃え', // 'Align',
    hr: '横線を投入', // 'Insert Horizontal Rule',
    undo: '元に戻す', // 'Undo',
    redo: 'やり直し', // 'Redo',
    heading1: 'ヘッダー 1', // 'Heading 1',
    heading2: 'ヘッダー 2', // 'Heading 2',
    heading3: 'ヘッダー 3', // 'Heading 3',
    heading4: 'ヘッダー 4', // 'Heading 4',
    heading5: 'ヘッダー 5', // 'Heading 5',
    heading6: 'ヘッダー 6', // 'Heading 6',
    paragraph: '段落', // 'Paragraph',
    code: 'コード', // 'Code',
    size1: '小さい', // 'Very small',
    size2: 'やや小さい', // 'A bit small',
    size3: '普通', // 'Normal',
    size4: 'やや大きい', // 'Medium-large',
    size5: '大きい', // 'Big',
    size6: 'とても大きい', // 'Very big',
    size7: '最大', // 'Maximum',
    defaultFont: '初期フォント', // 'Default Font',
    viewSource: 'ソースを見る'
  },
  tree: {
    noNodes: 'ノードがありません', // 'No nodes available',
    noResults: '該当するノードがありません' // 'No matching nodes found'
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames/bind';

class SearchResultsItem extends React.Component {

    render() {
        const result = this.props.data;
        const imgpath = '/assets/images/search/';

        // console.log('RESULT: '+JSON.stringify(result));

        let IconNode = '';
        let ResultNode = '';

        const contentStyles = {
            fontStyle: 'italic',
            fontWeight: 400
        };
        const infoStyles = {
            fontWeight: 600
        };

        let item = result.revisions.docs[result.revisions.docs.length-1];
        IconNode = ( );
        let resultLink = '';
        let resultContent = '';

        switch (result.kind) {
            case 'slide':
                resultLink = '/deck/' + item.parent_deck + '/slide/' + item.parent_id + '-' + item.id;
                resultContent = (item.content) ? item.content.substring(0, 100) + '...' : '';
                break;
            case 'deck':
                resultLink = '/deck/' + item.parent_id + '-' + item.id;
                resultContent = (result.description) ? result.description.substring(0 ,100) + '...' : '';
                break;
        }
        ResultNode = (

                {result.kind} {item.title}

                {resultContent}

        );
        // switch (result.kind) {
        //     case 'slide':
        //
        //         ResultNode = (
        //

        //                 Slide {result.revisions.docs[result.revisions.docs.length-1].title}
        //

        //                 // {result.content[0].substring(0,100)+'...'}
        //

        //         );
        //
        //         break;
        //
        //     case 'deck':
        //         IconNode = ( );
        //         ResultNode = (
        //

        //                 Deck {result.revisions.docs[result.revisions.docs.length-1].title}
        //

        //

        //         );
        //         break;
        // }

        return (

                      {IconNode}

                      {ResultNode}

        );
    }
}

export default SearchResultsItem;
<commit_msg>show slideview when no usage<commit_after>import React from 'react';
import classNames from 'classnames/bind';

class SearchResultsItem extends React.Component {

    render() {
        const result = this.props.data;
        const imgpath = '/assets/images/search/';

        // console.log('RESULT: '+JSON.stringify(result));

        let IconNode = '';
        let ResultNode = '';

        const contentStyles = {
            fontStyle: 'italic',
            fontWeight: 400
        };
        const infoStyles = {
            fontWeight: 600
        };

        // results are sorted by relevance
        let item = result.revisions.docs[0];
        IconNode = ( );
        let resultLink = '';
        let resultContent = '';

        switch (result.kind) {
            case 'slide':
                if(item.parent_deck && item.parent_deck !== 'undefined'){
                    resultLink = '/deck/' + item.parent_deck + '/slide/' + item.parent_id + '-' + item.id;
                }
                else{
                    resultLink = '/slideview/' + item.parent_id + '-' + item.id;
                }

                resultContent = (item.content) ? item.content.substring(0, 100) + '...' : '';
                break;
            case 'deck':
                resultLink = '/deck/' + item.parent_id + '-' + item.id;
                resultContent = (result.description) ? result.description.substring(0 ,100) + '...' : '';
                break;
        }
        ResultNode = (

                {result.kind} {item.title}

                {resultContent}

        );
        // switch (result.kind) {
        //     case 'slide':
        //
        //         ResultNode = (
        //

        //                 Slide {result.revisions.docs[result.revisions.docs.length-1].title}
        //

        //                 // {result.content[0].substring(0,100)+'...'}
        //

        //         );
        //
        //         break;
        //
        //     case 'deck':
        //         IconNode = ( );
        //         ResultNode = (
        //

        //                 Deck {result.revisions.docs[result.revisions.docs.length-1].title}
        //

        //

        //         );
        //         break;
        // }

        return (

                      {IconNode}

                      {ResultNode}

        );
    }
}

export default SearchResultsItem;
<|endoftext|>