Many improvements in SelectionMap

This commit is contained in:
vjrj 2017-12-21 10:57:00 +01:00
parent 7a672bca87
commit e3eddd6b85
13 changed files with 173 additions and 132 deletions

View file

@ -37,10 +37,42 @@ Subscriptions.deny({
* }
* */
// https://stackoverflow.com/questions/24492333/meteor-simple-schema-for-mongo-geo-location-data
// https://github.com/aldeed/meteor-simple-schema/issues/606
const LocationSchema = new SimpleSchema({
type: {
type: String,
allowedValues: ['Point']
},
coordinates: {
type: Array,
minCount: 2,
maxCount: 2,
custom: function custom() {
if (!(this.value[0] >= -90 && this.value[0] <= 90)) {
return 'lngOutOfRange';
}
if (!(this.value[1] >= -180 && this.value[1] <= 180)) {
return 'latOutOfRange';
}
return true;
}
},
'coordinates.$': {
type: Number
}
});
LocationSchema.messageBox.messages({
lonOutOfRange: '[label] longitude should be between -90 and 90',
latOutOfRange: '[label] latitude should be between -180 and 180'
});
Subscriptions.schema = new SimpleSchema({
location: Object,
'location.lat': Number,
'location.lon': Number,
geo: LocationSchema,
distance: Number,
owner: String,
type: String

View file

@ -3,6 +3,13 @@ import { check, Match } from 'meteor/check';
import Subscriptions from './Subscriptions';
import rateLimit from '../../modules/rate-limit';
function geo(doc) {
return {
type: 'Point',
coordinates: [doc.location.lon, doc.location.lat]
};
}
Meteor.methods({
'subscriptions.insert': function subscriptionsInsert(doc) {
check(doc, {
@ -10,10 +17,17 @@ Meteor.methods({
distance: Number
});
const type = 'web';
try {
return Subscriptions.insert({ owner: this.userId, type, ...doc });
const newDoc = {
owner: this.userId,
type,
geo: geo(doc),
...doc
};
// console.log(newDoc);
return Subscriptions.insert(newDoc);
} catch (exception) {
console.error(exception);
throw new Meteor.Error('500', exception);
}
},
@ -25,8 +39,10 @@ Meteor.methods({
});
try {
const dup = doc;
const subscriptionId = doc._id;
Subscriptions.update(subscriptionId, { $set: doc });
dup.geo = geo(doc);
Subscriptions.update(subscriptionId, { $set: dup });
return subscriptionId; // Return _id so we can redirect to subscription after update.
} catch (exception) {
throw new Meteor.Error('500', exception);
@ -38,6 +54,7 @@ Meteor.methods({
try {
return Subscriptions.remove(subscriptionId);
} catch (exception) {
console.error(exception);
throw new Meteor.Error('500', exception);
}
}

View file

@ -35,13 +35,13 @@ Meteor.publishTransformed('userSubsToFires', function transform() {
}
// console.log(`with noise: [${doc.lat}, ${doc.lon}]`);
delete doc.chatId;
delete doc.geo;
// delete doc.geo;
return doc;
});
});
Meteor.publish('mysubscriptions', function subscriptions() {
return Subscriptions.find({ owner: this.userId });
return Subscriptions.find({ owner: this.userId, type: 'web' });
});
// Note: subscriptions.view is also used when editing an existing subscription.
@ -49,5 +49,5 @@ Meteor.publish('subscriptions.view', function subscriptionsView(subscriptionId)
check(subscriptionId, String);
const id = new Mongo.ObjectID(subscriptionId);
check(id, Meteor.Collection.ObjectID);
return Subscriptions.find({ _id: id, owner: this.userId });
return Subscriptions.find({ _id: id, owner: this.userId, type: 'web' });
});

View file

@ -56,7 +56,7 @@ class DistanceSlider extends React.Component {
<div className="dist-slider">
<p><Trans parent="span">¿A que distancia a la redonda quieres recibir notificaciones?</Trans></p>
<Slider
min={5}
min={1}
max={105}
value={this.state.value}
trackStyle={{ backgroundColor: 'green', height: 8 }}
@ -68,7 +68,8 @@ class DistanceSlider extends React.Component {
height: 8
}}
marks={{
10: { label: '10км' },
1: { label: '1км' },
10: { label: '10' },
20: { label: '20' },
30: { label: '30' },
40: { label: '40' },
@ -90,7 +91,7 @@ class DistanceSlider extends React.Component {
onAfterChange={this.onAfterChange}
onChange={this.onSliderChange}
defaultValue={10}
step={5}
step={1}
handle={handle}
/>
</div>

View file

@ -7,56 +7,8 @@ import PropTypes from 'prop-types';
import { Modal, Button } from 'react-bootstrap';
import { confirmable } from 'react-confirm';
// https://github.com/haradakunihiko/react-confirm/blob/master/example/react-bootstrap/src/components/Confirmation.js
class Prompt extends Component {
// constructor(props) {
/* super(props);
* this.state = {
* open: true
* };
}
componentDidMount() {
* console.log(this.prompt);
* this.setState({ open: true });
}
*/
render2() {
const {
show,
proceed,
dismiss,
cancel,
confirmation,
okBtn,
cancelBtn
} = this.props;
return (
<div
className="modal"
tabIndex="-1"
role="dialog"
>
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">Modal title</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div className="modal-body">
<p>Modal body text goes here.</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-primary">Save changes</button>
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
);
}
render() {
const {
show,
@ -66,6 +18,7 @@ role="dialog"
confirmation,
okBtn,
cancelBtn,
title,
enableEscape = true
} = this.props;
return (
@ -78,9 +31,11 @@ role="dialog"
backdrop={enableEscape ? true : 'static'}
keyboard={enableEscape}
>
<Modal.Header closeButton>
<Modal.Title id="ModalHeader" />
</Modal.Header>
{title &&
<Modal.Header closeButton>
<Modal.Title id="ModalHeader">{title}</Modal.Title>
</Modal.Header>
}
<Modal.Body>
<p>{confirmation}</p>
</Modal.Body>
@ -100,6 +55,7 @@ Prompt.propTypes = {
cancel: PropTypes.func, // from confirmable. call to close the dialog with promise rejected.
dismiss: PropTypes.func, // from confirmable. call to only close the dialog.
confirmation: PropTypes.string, // arguments of your confirm function
title: PropTypes.string,
okBtn: PropTypes.string.isRequired,
cancelBtn: PropTypes.string.isRequired,
enableEscape: PropTypes.bool

View file

@ -6,7 +6,8 @@
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { Map, Marker, CircleMarker, Circle } from 'react-leaflet';
import { Meteor } from 'meteor/meteor';
import { Map, Marker, CircleMarker, Circle, Tooltip } from 'react-leaflet';
import Leaflet from 'leaflet';
import { translate } from 'react-i18next';
import { withTracker } from 'meteor/react-meteor-data';
@ -20,6 +21,7 @@ import 'leaflet-sleep/Leaflet.Sleep.js';
import Control from 'react-leaflet-control';
import { Button, ButtonGroup } from 'react-bootstrap';
import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions';
import './SelectionMap.scss';
export const action = {
@ -114,7 +116,12 @@ class SelectionMap extends Component {
if (this.props.currentSubs.length > 0 && this.state.subsFit) {
// has autofit, do nothing
} else if (this.selectionMap && this.distanceCircle) {
this.getMap().fitBounds(this.distanceCircle.leafletElement.getBounds(), [70, 70]);
if (!this.getMap().getBounds().contains(this.distanceCircle.leafletElement.getBounds())) {
// console.log('New area circle not visible');
this.getMap().fitBounds(this.distanceCircle.leafletElement.getBounds()); // padding , [70, 70]);
} else {
// console.log('New area circle visible');
}
}
}
@ -132,7 +139,7 @@ class SelectionMap extends Component {
}
isValidState() {
return this.state.center && this.state.center[0];
return !this.props.loadingSubs && this.state.center && this.state.center[0];
}
handleLeafletLoad(map) {
@ -175,7 +182,7 @@ class SelectionMap extends Component {
>
<DefMapLayers gray={false} />
{this.props.action === action.edit &&
this.props.currentSubs.map(subs => (
this.props.currentSubs.map((subs, index) => (
<Marker
key={subs._id}
draggable={false}
@ -183,7 +190,18 @@ class SelectionMap extends Component {
icon={removeIcon}
title={t('Pulsa para borrar')}
onClick={() => { onRemove(subs._id); }}
/>
>
{index === 0 &&
<Tooltip
permanent
direction="right"
/* Use .openTooltip(); in the future */
offset={[10, -10]}
>
<span>{t('Pulsa aquí para borrar la zona')}</span>
</Tooltip>
}
</Marker>
))
}
{this.props.action === action.add &&
@ -257,14 +275,20 @@ SelectionMap.propTypes = {
onSndBtn: PropTypes.func,
onRemove: PropTypes.func,
action: PropTypes.number.isRequired,
loadingSubs: PropTypes.bool,
loadingSubs: PropTypes.bool.isRequired,
currentSubs: PropTypes.arrayOf(PropTypes.shape({
location: PropTypes.shape({ latitude: PropTypes.number, longitude: PropTypes.number }).isRequired,
distance: PropTypes.number.isRequired
}))
};
export default translate([], { wait: true })(withTracker(props => ({
center: props.center[0] !== null ? props.center : geolocation.get(),
distance: props.distance
}))(SelectionMap));
export default translate([], { wait: true })(withTracker((props) => {
const subscription = Meteor.subscribe('mysubscriptions');
// console.log(props.loadingSubs);
return {
center: props.center[0] !== null ? props.center : geolocation.get(),
distance: props.distance,
loadingSubs: !subscription.ready(),
currentSubs: UserSubsToFiresCollection.find({ owner: Meteor.userId(), type: 'web' }).fetch()
};
})(SelectionMap));

View file

@ -30,16 +30,22 @@ class SubscriptionEditor extends React.Component {
if (existingSubscription) doc._id = existingSubscription;
Meteor.call(methodToCall, doc, (error, subscriptionId) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
const confirmation = existingSubscription ? t('Zona actualizada') : t('Zona añadida');
Bert.alert(confirmation, 'success');
// history.push(`/subscriptions/${subscriptionId}`);
history.push('/subscriptions');
}
});
const authenticated = !!Meteor.userId();
if (authenticated) {
Meteor.call(methodToCall, doc, (error, subscriptionId) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
const confirmation = existingSubscription ? t('Zona actualizada') : t('Zona añadida');
Bert.alert(confirmation, 'success');
// history.push(`/subscriptions/${subscriptionId}`);
history.push('/subscriptions');
}
});
} else {
this.props.history.push('/signup', doc);
}
}
render() {

View file

@ -2,7 +2,6 @@
/* eslint-disable react/jsx-indent-props */
import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { Row, Col } from 'react-bootstrap';
import { translate } from 'react-i18next';
@ -10,7 +9,6 @@ import DistanceSlider from '/imports/ui/components/DistanceSlider/DistanceSlider
import SelectionMap, { action } from '/imports/ui/components/SelectionMap/SelectionMap';
import Gkeys from '/imports/startup/client/Gkeys';
import CenterInMyPosition from '/imports/ui/components/CenterInMyPosition/CenterInMyPosition.js';
import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions';
import SubsAutocomplete from './SubsAutocomplete';
class FireSubscription extends React.Component {
@ -96,8 +94,6 @@ class FireSubscription extends React.Component {
onFstBtn={state => this.onSubs(state)}
onSelection={state => this.onSelection(state)}
action={action.add}
loadingSubs={this.props.loading}
currentSubs={this.props.subscriptions}
/>
</Row>
</div>
@ -106,9 +102,6 @@ class FireSubscription extends React.Component {
}
FireSubscription.propTypes = {
t: PropTypes.func.isRequired,
loading: PropTypes.bool.isRequired,
subscriptions: PropTypes.arrayOf(PropTypes.object).isRequired,
center: PropTypes.arrayOf(PropTypes.number),
zoom: PropTypes.number,
distance: PropTypes.number,
@ -117,11 +110,4 @@ FireSubscription.propTypes = {
onSubs: PropTypes.func.isRequired
};
export default translate([], { wait: true })(withTracker(() => {
const subscription = Meteor.subscribe('mysubscriptions');
// console.log(UserSubsToFiresCollection.find().fetch());
return {
loading: !subscription.ready(),
subscriptions: UserSubsToFiresCollection.find({ owner: Meteor.userId() }).fetch()
};
})(FireSubscription));
export default translate([], { wait: true })(FireSubscription);

View file

@ -219,7 +219,10 @@ class Index extends Component {
<Section className="">
<div className="container">
<h4 className="page-header"><Trans parent="span">Suscríbete a alertas de fuegos</Trans></h4>
<SubscriptionEditor history={this.props.history} focusInput={false} />
<SubscriptionEditor
focusInput={false}
history={this.props.history}
/>
</div>
<div className="overlay" />
</Section>

View file

@ -16,7 +16,7 @@ class Login extends React.Component {
super(props);
this.t = props.t;
this.handleSubmit = this.handleSubmit.bind(this);
console.log(this.props.location.state);
// console.log(this.props.location.state);
}
componentDidMount() {

View file

@ -17,8 +17,10 @@ import { T9n } from 'meteor-accounts-t9n';
class Signup extends React.Component {
constructor(props) {
super(props);
this.t = this.props.t;
this.t = props.t;
this.handleSubmit = this.handleSubmit.bind(this);
// console.log(props.location.state);
this.state = props.location.state;
}
componentDidMount() {
@ -27,37 +29,37 @@ class Signup extends React.Component {
validate(component.form, {
rules: {
firstName: {
required: true,
required: true
},
lastName: {
required: true,
required: true
},
emailAddress: {
required: true,
email: true,
email: true
},
password: {
required: true,
minlength: 6,
},
minlength: 6
}
},
messages: {
firstName: {
required: this.t("¿Cuál es tu nombre?"),
required: this.t('¿Cuál es tu nombre?')
},
lastName: {
required: this.t("¿Cuál es tu apellido?"),
required: this.t('¿Cuál es tu apellido?')
},
emailAddress: {
required: this.t("Necesitamos una contraseña aquí."),
email: this.t("¿Es correcto este correo?"),
required: this.t('Necesitamos una contraseña aquí.'),
email: this.t('¿Es correcto este correo?')
},
password: {
required: this.t("Necesitamos una contraseña aquí."),
minlength: this.t("Usa al menos seis caracteres."),
},
required: this.t('Necesitamos una contraseña aquí.'),
minlength: this.t('Usa al menos seis caracteres.')
}
},
submitHandler() { component.handleSubmit(); },
submitHandler() { component.handleSubmit(); }
});
}
@ -70,16 +72,16 @@ class Signup extends React.Component {
profile: {
name: {
first: this.firstName.value,
last: this.lastName.value,
},
},
last: this.lastName.value
}
}
}, (error) => {
if (error) {
Bert.alert(T9n.get(`error.accounts.${error.reason}`), 'danger');
} else {
Meteor.call('users.sendVerificationEmail');
Bert.alert('Welcome!', 'success');
history.push('/documents');
history.push('/subscriptions');
}
});
}
@ -88,7 +90,7 @@ class Signup extends React.Component {
return (<div className="Signup">
<Row className="align-items-center justify-content-center">
<Col xs={12} sm={6} md={5} lg={4}>
<h4 className="page-header">{this.t("Registrarse")}</h4>
<h4 className="page-header">{this.t('Registrarse')}</h4>
<Row>
{/* <Col xs={12}>
<button
@ -102,7 +104,7 @@ class Signup extends React.Component {
services={['telegram', 'google']}
emailMessage={{
offset: 97,
text: this.t('o regístrate con un correo'),
text: this.t('o regístrate con un correo')
}}
/>
</Col>
@ -111,7 +113,7 @@ class Signup extends React.Component {
<Row>
<Col xs={6}>
<FormGroup>
<ControlLabel>{this.t("Nombre")}</ControlLabel>
<ControlLabel>{this.t('Nombre')}</ControlLabel>
<input
type="text"
name="firstName"
@ -122,7 +124,7 @@ class Signup extends React.Component {
</Col>
<Col xs={6}>
<FormGroup>
<ControlLabel>{this.t("Apellidos")}</ControlLabel>
<ControlLabel>{this.t('Apellidos')}</ControlLabel>
<input
type="text"
name="lastName"
@ -133,7 +135,7 @@ class Signup extends React.Component {
</Col>
</Row>
<FormGroup>
<ControlLabel>{this.t("Correo electrónico")}</ControlLabel>
<ControlLabel>{this.t('Correo electrónico')}</ControlLabel>
<input
type="email"
name="emailAddress"
@ -142,18 +144,18 @@ class Signup extends React.Component {
/>
</FormGroup>
<FormGroup>
<ControlLabel>{this.t("Contraseña")}</ControlLabel>
<ControlLabel>{this.t('Contraseña')}</ControlLabel>
<input
type="password"
name="password"
ref={password => (this.password = password)}
className="form-control"
/>
<InputHint>{this.t("Usa al menos seis caracteres.")}</InputHint>
<InputHint>{this.t('Usa al menos seis caracteres.')}</InputHint>
</FormGroup>
<Button type="submit" bsStyle="success">{this.t("Registrarse")}</Button>
<Button type="submit" bsStyle="success">{this.t('Registrarse')}</Button>
<AccountPageFooter>
<p>{this.t("¿Ya tienes un cuenta?")} <Link to="/login">{this.t("Iniciar sesión")}</Link>.</p>
<p>{this.t('¿Ya tienes un cuenta?')} <Link to={{ pathname: '/login', state: this.state }} >{this.t('Iniciar sesión')}</Link>.</p>
</AccountPageFooter>
</form>
</Col>

View file

@ -29,7 +29,11 @@ class Subscriptions extends Component {
onFstBtn() {
// console.log(this.state);
this.props.history.push(`${this.props.match.url}/new`, { center: this.state.center, zoom: this.state.zoom });
if (this.state.action === action.view) {
this.props.history.push(`${this.props.match.url}/new`, { center: this.state.center, zoom: this.state.zoom });
} else if (this.state.action === action.edit) {
this.setState({ action: action.view });
}
}
onSndBtn() {
@ -42,15 +46,19 @@ class Subscriptions extends Component {
}
handleRemove(subscriptionId) {
const { t } = this.props;
const { t, subscriptions } = this.props;
confirm(t('Dejarás de recibir notificaciones de fuegos en esa área ¿Estás seguro/a? '), { okBtn: t('Sí'), cancelBtn: t('No') }).then(
() => {
// `proceed` callback
const num = subscriptions.length;
Meteor.call('subscriptions.remove', subscriptionId, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
Bert.alert('Subscription deleted!', 'success');
if (num === 1) { // it was 1, now deleted
this.setState({ action: action.view });
}
}
});
},
@ -66,23 +74,25 @@ class Subscriptions extends Component {
t,
subscriptions
} = this.props;
const firstBtnTitle = ['Añadir zona', '', 'Terminar']; // view, add, edit
return (!loading ? (
<div className="Subscriptions">
<div className="page-header clearfix">
<h4 className="pull-left"><Trans>Suscripciones a fuegos en zonas de mi interés</Trans></h4>
<h4 className="pull-left"><Trans>Suscripciones a alertas de fuegos en zonas de mi interés</Trans></h4>
</div>
<br />
{ subscriptions.length === 0 &&
<Alert bsStyle="warning"><Trans>No estás suscrito a fuegos en ninguna zona</Trans></Alert>
{ subscriptions.length === 0 ?
<Alert bsStyle="warning"><Trans>No estás suscrito a fuegos en ninguna zona</Trans></Alert> :
<Alert bsStyle="success"><Trans>En verde, áreas de las que recibirás alertas de fuegos</Trans></Alert>
}
<br />
<SelectionMap
center={[null, null]}
zoom={11}
action={this.state.action}
fstBtn={t('Añadir zona')}
fstBtn={t(firstBtnTitle[this.state.action])}
onFstBtn={state => this.onFstBtn(state)}
sndBtn={this.props.subscriptions.length >= 1 ? t('Editar') : null}
sndBtn={this.state.action === action.view && this.props.subscriptions.length >= 1 ? t('Editar') : null}
onSndBtn={() => this.onSndBtn()}
onViewportChanged={viewport => this.onViewportChanged(viewport)}
loadingSubs={this.props.loading}

View file

@ -19,3 +19,7 @@ body {
.navbar-nav .nav-link {
white-space: nowrap;
}
.modal-dialog {
margin-top: 70px;
}