Subs form (wip)

This commit is contained in:
vjrj 2017-12-06 11:04:34 +01:00
parent 3d86418d22
commit df96b6e51e
14 changed files with 530 additions and 75 deletions

View file

@ -0,0 +1,18 @@
import { Meteor } from 'meteor/meteor';
const geolocation = new ReactiveVar();
Meteor.startup(function() {
Meteor.call("geo", function (error, response) {
if (error) {
console.warn(error);
} else {
var pos = [
response.location.latitude,
response.location.longitude
];
geolocation.set(pos);
}
});
});
export default geolocation;

View file

@ -0,0 +1,34 @@
import { Meteor } from 'meteor/meteor';
import i18n from 'i18next';
const gmapkey = new ReactiveVar();
Meteor.startup(function() {
Meteor.call('getMapKey', function (error, key) {
if (typeof key !== 'undefined') {
// console.log(key);
gmapkey.set(key);
} else {
callback(error, null)
}
})
});
var getGKeys = function (callback) {
Meteor.autorun(function() {
var key = gmapkey.get();
if (typeof key !== 'undefined') {
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function () {
// console.log(key);
callback(null, key);
};
// https://stackoverflow.com/questions/28130114/google-maps-places-autocomplete-language-output
script.src = `https://maps.googleapis.com/maps/api/js?key=${key}&libraries=places&language=${i18n.language}`
document.body.appendChild(script);
}
});
}
export default getGKeys;

View file

@ -75,7 +75,7 @@ i18n.use(backend)
whitelist: false,
// whitelist: ['es', 'en'], // allowed languages
load: 'all', // es-ES -> es, en-US -> en
debug: true,
debug: false,
ns: 'common',
defaultNS: 'common',
saveMissing: true, // if true seems it's fails to getResourceBundle

View file

@ -40,4 +40,11 @@ Meteor.methods({
})
return promise.await();
},
getMapKey: function () {
// http://meteorpedia.com/read/Environment_Variables
// https://developers.google.com/maps/documentation/javascript/get-api-key
// https://console.developers.google.com/
// export GMAPS_KEY=SomeGMapsKey
return process.env.GMAPS_KEY || Meteor.settings.gmaps.key;;
},
});

View file

@ -0,0 +1,96 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Trans, translate } from 'react-i18next';
import Slider, { Range } from 'rc-slider';
import Tooltip from 'rc-tooltip';
// We can just import Slider or Range to reduce bundle size
// import Slider from 'rc-slider/lib/Slider';
// import Range from 'rc-slider/lib/Range';
import 'rc-slider/assets/index.css';
// https://www.npmjs.com/package/rc-slider
const createSliderWithTooltip = Slider.createSliderWithTooltip;
const Handle = Slider.Handle;
const handle = (props) => {
const { value, dragging, index, ...restProps } = props;
return (
<Tooltip
prefixCls="rc-slider-tooltip"
overlay={value}
visible={dragging}
placement="top"
key={index}
>
<Handle value={value} {...restProps} />
</Tooltip>
);
};
const wrapperStyle = { width: 400, margin: 50 };
// https://github.com/react-component/slider/tree/master/examples
class DistanceSlider extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 10,
};
}
onSliderChange = (value) => {
// console.log(value);
this.setState({
value,
});
this.props.onChange(value);
}
onAfterChange = (value) => {
// console.log(`After change: ${value}`); //eslint-disable-line
this.props.onChange(value);
}
render() {
return (
<div style={wrapperStyle}>
<p><Trans parent="span">¿A que distancia a la redonda quieres recibir notificaciones?</Trans></p>
<Slider min={5}
max={105}
value={this.state.value}
trackStyle={{ backgroundColor: 'green', height: 8 }}
railStyle={{ backgroundColor: 'orange', height: 8 }}
dotStyle={{ top: 0, marginLeft: -1, width: 2, height: 8 }}
marks={{
10: {style: {}, label: "10"},
20: {style: {}, label: "20"},
30: {style: {}, label: "30"},
40: {style: {}, label: "40"},
50: {style: {}, label: "50"},
60: {style: {}, label: "60"},
70: {style: {}, label: "70"},
80: {style: {}, label: "80"},
90: {style: {}, label: "90"},
100: {style: {}, label: "100"}
}}
handleStyle={{
borderColor: 'green',
height: 20,
width: 20,
marginLeft: -10,
marginTop: -6,
/* backgroundColor: 'gray', */
}}
onAfterChange={this.onAfterChange}
onChange={this.onSliderChange}
defaultValue={10}
step={5}
handle={handle} />
</div>
)
}
}
export default translate([], { wait: true })(DistanceSlider);

View file

@ -0,0 +1,119 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Map, TileLayer, Marker, Popup, CircleMarker, Circle} from 'react-leaflet';
import Leaflet from 'leaflet';
import { withTracker } from 'meteor/react-meteor-data';
import { translate } from 'react-i18next';
import geolocation from '/imports/startup/client/geolocation';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
const positionIcon = new Leaflet.Icon({
iconUrl: "/your-position.png",
/* shadowUrl: require('../public/marker-shadow.png'), */
iconSize: [50, 77], // size of the icon
/* shadowSize: [50, 64], // size of the shadow */
iconAnchor: [25, 82], // point of the icon which will correspond to marker's location
/* shadowAnchor: [4, 62], // the same for the shadow
* popupAnchor: [-3, -76]// point from which the popup should open relative to the iconAnchor*/
})
class SelectionMap extends Component {
constructor(props) {
super(props);
this.state = {
center: geolocation.get(),
marker: geolocation.get(),
zoom: 11,
draggable: true,
modified: false
};
// console.log(this.state);
}
componentDidUpdate = () => {
this.fit();
}
getMap = () => {
return this.refs.selectionMap.leafletElement;
}
toggleDraggable = () => {
this.setState({ draggable: !this.state.draggable })
}
updatePosition = () => {
const { lat, lng } = this.refs.marker.leafletElement.getLatLng()
this.setState({
marker: [ lat, lng ],
modified: true
});
}
fit() {
// console.log("fit!");
this.getMap().fitBounds(this.refs.distanceCircle.leafletElement.getBounds(), [70, 70]);
}
componentDidMount() {
this.addScale();
}
addScale = () => {
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
var options = {
fill: 'fill',
showSubunits: true,
}
var graphicScale = L.control.graphicScale([options]).addTo(map);
}
render() {
this.state.center = !this.state.modified && this.props.lat?
[this.props.lat, this.props.lng]: this.state.center;
this.state.marker = !this.state.modified && this.props.lat?
[this.props.lat, this.props.lng]: this.state.marker;
this.state.distance = this.props.distance;
this.state.modified = false;
return (
<div>
{ this.state && this.state.center &&
<Map center={this.state.center} zoom={this.state.zoom} ref="selectionMap">
<TileLayer
attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
draggable={this.state.draggable}
onDragend={this.updatePosition}
position={this.state.marker}
icon={positionIcon}
ref="marker">
</Marker>
<CircleMarker
center={this.state.marker} color="red"
stroke={false}
fillOpacity="1"
fill={true}
radius={3} />
<Circle center={this.state.marker}
ref="distanceCircle"
color="#145A32"
fillColor="green"
fillOpacity={.1}
radius={this.state.distance * 1000} />
</Map> }
</div>
)
}
}
SelectionMap.propTypes = {
lat: PropTypes.number,
lng: PropTypes.number,
distance: PropTypes.number
};
export default translate([], { wait: true })(SelectionMap);

View file

@ -35,6 +35,7 @@ import { I18nextProvider } from 'react-i18next';
import i18n from '/imports/startup/client/i18n';
import '/imports/startup/client/piwik-start.js';
import ravenLogger from '/imports/startup/client/ravenLogger';
import geolocation from '/imports/startup/client/geolocation';
// https://github.com/gadicc/meteor-blaze-react-component/
import Blaze from 'meteor/gadicc:blaze-react-component';
import createHistory from 'history/createBrowserHistory';

View file

@ -16,6 +16,7 @@ import LGeo from 'leaflet-geodesy';
import union from 'turf-union';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
import _ from 'lodash';
// https://stackoverflow.com/questions/35394577/leaflet-js-union-merge-circles
function unify(polyList) {
@ -163,17 +164,22 @@ class FiresMap extends React.Component {
height.set(this.divElement.clientHeight);
width.set(this.divElement.clientWidth);
this.addScale();
const self = this;
this.handleViewportChangeDebounced = _.debounce(function (viewport) {
console.log(`Viewport changed: ${JSON.stringify(this.state.viewport)}`);
zoom.set(viewport.zoom);
lat.set(viewport.center[0]);
lng.set(viewport.center[1]);
self.state.viewport = viewport;
self.state.modified = true;
self.showSubsUnion(self.state.showSubsUnion);
}, 2000);
}
onViewportChanged = viewport => {
// console.log(`Viewport changed: ${JSON.stringify(this.state.viewport)}`);
zoom.set(viewport.zoom);
lat.set(viewport.center[0]);
lng.set(viewport.center[1]);
this.state.viewport = viewport;
this.state.modified = true;
this.showSubsUnion(this.state.showSubsUnion);
}
// https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js
onViewportChanged = (viewport) => {
this.handleViewportChangeDebounced(viewport);
};
onClickReset = () => {
// console.log("onclick");
@ -297,7 +303,7 @@ class FiresMap extends React.Component {
</Map>
</Row>
<Row>
(*)&nbsp;<Trans parent="span"><em>Para preservar la privacidad de nuestros usuarios/as, los datos reflejados están aleatoriamente alterados y son solo orientativos.</em></Trans>
(*)&nbsp;<Trans i18nKey="mapPrivacy" parent="span"><em>Para preservar la privacidad de nuestros usuarios/as, los datos reflejados están aleatoriamente alterados y son solo orientativos.</em></Trans>
</Row>
</div>
);

View file

@ -1,58 +1,145 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Button } from 'react-bootstrap';
import { FormGroup, ControlLabel, Button, Row, Col, HelpBlock } from 'react-bootstrap';
import { Trans, translate } from 'react-i18next';
import Slider, { Range } from 'rc-slider';
import Tooltip from 'rc-tooltip';
// We can just import Slider or Range to reduce bundle size
// import Slider from 'rc-slider/lib/Slider';
// import Range from 'rc-slider/lib/Range';
import 'rc-slider/assets/index.css';
import DistanceSlider from '/imports/ui/components/DistanceSlider/DistanceSlider';
import SelectionMap from '/imports/ui/components/SelectionMap/SelectionMap';
import getGKeys from '/imports/startup/client/gkeys';
import PlacesAutocomplete, { geocodeByAddress, geocodeByPlaceId, getLatLng } from 'react-places-autocomplete'
import update from 'immutability-helper';
import { withTracker } from 'meteor/react-meteor-data';
// https://www.npmjs.com/package/rc-slider
const createSliderWithTooltip = Slider.createSliderWithTooltip;
const Handle = Slider.Handle;
class Sandbox extends React.Component {
constructor(props) {
super(props);
this.state = {
adddress: ''
};
self = this;
// this.handleSelect = this.handleSelect.bind(this)
// this.handleChange = this.handleChange.bind(this)
}
const handle = (props) => {
const { value, dragging, index, ...restProps } = props;
return (
<Tooltip
prefixCls="rc-slider-tooltip"
overlay={value}
visible={dragging}
placement="top"
key={index}
>
<Handle value={value} {...restProps} />
</Tooltip>
);
};
const wrapperStyle = { width: 400, margin: 50 };
onChange = (address) => { this.setState({ address }) }
const Sandbox = props => (
<div style={wrapperStyle}>
<Slider min={5}
max={100}
trackStyle={{ backgroundColor: 'green', height: 8 }}
railStyle={{ backgroundColor: 'orange', height: 8 }}
handleStyle={{
borderColor: 'green',
height: 20,
width: 20,
marginLeft: -14,
marginTop: -6,
/* backgroundColor: 'gray', */
}}
defaultValue={10}
step={5}
handle={handle} />
</div>
);
handleSelect = (address) => {
geocodeByAddress(address)
.then((results) => getLatLng(results[0]))
.then(({ lat, lng }) => {
// console.log('Success Yay', { lat, lng })
const newState = update(this.state, {$merge: {lat: lat, lng: lng}});
// console.log(newState);
this.setState(newState);
// console.log(this.state);
})
.catch(error => {
console.log(error);
if (error === 'ZERO_RESULTS') {
console.log("No results");
}
});
}
Sandbox.defaultProps = {
};
onSliderChange = (value) => {
this.setState(update(this.state, {$merge: {distance: value}}));
}
render() {
// https://www.npmjs.com/package/react-places-autocomplete
// https://github.com/kenny-hibino/react-places-autocomplete/issues/103
const myStyles = {
autocompleteContainer: {
paddingBottom: '20px',
backgroundSize: 'auto 12px',
backgroundPosition: 'bottom left 10px',
backgroundRepeat: 'no-repeat',
backgroundImage: "url('https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white3_hdpi.png')",
},
}
const AutocompleteItem = ({ formattedSuggestion }) => (
<div className="suggestion-item">
<i className='fa fa-map-marker suggestion-icon'/>{' '}
<strong>{formattedSuggestion.mainText}</strong>{' '}
<small className="text-muted">{formattedSuggestion.secondaryText}</small>
</div>)
// https://developers.google.com/places/web-service/search
// https://github.com/kenny-hibino/react-places-autocomplete/blob/master/demo/Demo.js
return (
<div>
<Row>
<Col xs={12} sm={12} md={6} lg={6} >
{ typeof this.props.gkey === 'string' &&
<div>
<h4 className="page-header"><Trans parent="span">Suscríbete a alertas de fuegos</Trans></h4>
<form onSubmit={this.handleSelectEnd}>
<FormGroup>
<ControlLabel>
<Trans parent="span">Indícanos la posición a vigilar (por ej. tu pueblo, una calle, etc):</Trans>
</ControlLabel>
<PlacesAutocomplete
styles={myStyles}
classNames={{
root: 'form-group',
input: 'form-control',
autocompleteContainer: 'autocomplete-container'}}
googleLogo={false}
highlightFirstSuggestion={true}
onSelect={this.handleSelect}
onEnterKeyDown={this.handleSelect}
autocompleteItem={AutocompleteItem}
options={{
// location: new google.maps.LatLng(-34, 151),
// radius: 2000,
// type: ['address'],
language: this.props.i18n.language
}}
inputProps={
{
value: this.state.address,
onChange: this.onChange,
placeholder: this.props.t("Escribe aquí un lugar "),
onBlur:() => { console.log('Blur event!'); },
onFocus:() => { console.log('Focused!'); },
autoFocus:true
}} />
<HelpBlock><Trans parent="span">También puedes seleccionar el lugar en el mapa arrastrando el puntero naranja.</Trans></HelpBlock>
</FormGroup>
</form>
</div>
}
</Col>
<Col xs={12} sm={12} md={6} lg={6} >
<DistanceSlider onChange={this.onSliderChange} />
<Button bsStyle="success" type="submit"><Trans parent="span">Subscribir</Trans></Button>
</Col>
</Row>
<Row className="align-items-center justify-content-center">
<SelectionMap lat={this.state.lat} lng={this.state.lng} distance={this.state.distance || 10} />
</Row>
</div>
)
}
}
Sandbox.propTypes = {
};
gkey: PropTypes.string
}
export default translate([], { wait: true })(Sandbox);
const gkey = new ReactiveVar();
getGKeys(function(err, key) {
if (err) {
console.log(err);
} else {
gkey.set(key);
}
});
export default translate([], { wait: true }) (withTracker(() => {
return {
gkey: gkey.get()
};
})(Sandbox));