Improvement in Subs and FireMap Union

This commit is contained in:
vjrj 2017-12-19 20:02:14 +01:00
parent 497724443f
commit 1742cd4913
19 changed files with 390 additions and 299 deletions

View file

@ -42,7 +42,8 @@ Subscriptions.schema = new SimpleSchema({
'location.lat': Number, 'location.lat': Number,
'location.lon': Number, 'location.lon': Number,
distance: Number, distance: Number,
owner: String owner: String,
type: String
}); });
Subscriptions.attachSchema(Subscriptions.schema); Subscriptions.attachSchema(Subscriptions.schema);

View file

@ -9,9 +9,10 @@ Meteor.methods({
location: Match.ObjectIncluding({ lat: Number, lon: Number }), location: Match.ObjectIncluding({ lat: Number, lon: Number }),
distance: Number distance: Number
}); });
const type = 'web';
try { try {
return Subscriptions.insert({ owner: this.userId, ...doc }); return Subscriptions.insert({ owner: this.userId, type, ...doc });
} catch (exception) { } catch (exception) {
throw new Meteor.Error('500', exception); throw new Meteor.Error('500', exception);
} }

View file

@ -18,21 +18,24 @@ Meteor.publishTransformed('userSubsToFires', function transform() {
const location = doc.location; const location = doc.location;
/* doc.lat = location.lat; /* doc.lat = location.lat;
* doc.lon = location.lon; */ * doc.lon = location.lon; */
let lat;
let lon;
if (location) { if (location) {
doc.lat = Math.round(location.lat * 10) / 10; lat = Math.round(location.lat * 10) / 10;
doc.lon = Math.round(location.lon * 10) / 10; lon = Math.round(location.lon * 10) / 10;
// console.log(`[${lat}, ${lon}]`);
const noiseBase = Perlin.perlin2(lat, lon);
const noise = Math.abs(noiseBase / 3);
// console.log(`Noise ${noise}, abs: ${Math.abs(noise)}`);
lat += noise;
lon += noise;
doc.location.lat = lat;
doc.location.lon = lon;
doc.distance += noiseBase;
} }
// console.log(`[${doc.lat}, ${doc.lon}]`);
const noiseBase = Perlin.perlin2(doc.lat, doc.lon);
const noise = Math.abs(noiseBase / 3);
// console.log(`Noise ${noise}, abs: ${Math.abs(noise)}`);
doc.lat += noise;
doc.lon += noise;
doc.distance += noiseBase;
// console.log(`with noise: [${doc.lat}, ${doc.lon}]`); // console.log(`with noise: [${doc.lat}, ${doc.lon}]`);
delete doc.chatId; delete doc.chatId;
delete doc.geo; delete doc.geo;
delete doc.location;
return doc; return doc;
}); });
}); });

View file

@ -5,6 +5,9 @@ import LngDetector from 'i18next-browser-languagedetector';
import Cache from 'i18next-localstorage-cache'; import Cache from 'i18next-localstorage-cache';
import { T9n } from 'meteor-accounts-t9n'; import { T9n } from 'meteor-accounts-t9n';
import moment from 'moment'; import moment from 'moment';
import 'moment/locale/es';
import 'moment/locale/pt';
import 'moment/locale/gl';
import i18nOpts from '../common/i18n'; import i18nOpts from '../common/i18n';
// Adapted from: https://github.com/appigram/ryfma-boilerplate/blob/44c1eabfb9928b5623afab36a23997969e5beb02/imports/startup/client/i18n.js // Adapted from: https://github.com/appigram/ryfma-boilerplate/blob/44c1eabfb9928b5623afab36a23997969e5beb02/imports/startup/client/i18n.js
@ -61,6 +64,8 @@ i18n.use(backend)
T9n.setLanguage(i18n.language); T9n.setLanguage(i18n.language);
// console.log(T9n.get('error.accounts.User not found')); // console.log(T9n.get('error.accounts.User not found'));
moment.locale(i18n.language);
// cookies eu consent // cookies eu consent
const cookiesOpt = { const cookiesOpt = {
cookieTitle: t('Uso de Cookies'), cookieTitle: t('Uso de Cookies'),

View file

@ -16,12 +16,12 @@ import NavItem from '../NavItem/NavItem';
const AuthenticatedNavigation = ({ name, history, props }) => ( const AuthenticatedNavigation = ({ name, history, props }) => (
<ul className="navbar-nav"> <ul className="navbar-nav">
{/* <Nav pullRight> */} {/* <Nav pullRight> */}
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/documents"> {/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/documents">
<NavItem eventKey={5} href="/documents">Documents</NavItem> <NavItem eventKey={5} href="/documents">Documents</NavItem>
</LinkContainer> </LinkContainer> */}
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/documents"> {/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/subscriptions">
<NavItem eventKey={5.01} href="/subscriptions">Subscriptions</NavItem> <NavItem eventKey={5} href="/subscriptions"><Trans>Mis alertas</Trans></NavItem>
</LinkContainer> </LinkContainer> */}
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/profile"> <LinkContainer className="nav-item" anchorClassName="nav-link" to="/profile">
<NavItem eventKey={5.1} href="/profile">{name}</NavItem> <NavItem eventKey={5.1} href="/profile">{name}</NavItem>
</LinkContainer> </LinkContainer>
@ -34,7 +34,6 @@ const AuthenticatedNavigation = ({ name, history, props }) => (
AuthenticatedNavigation.propTypes = { AuthenticatedNavigation.propTypes = {
name: PropTypes.string.isRequired name: PropTypes.string.isRequired
}; };
export default translate([], { wait: true })(withRouter(AuthenticatedNavigation)); export default translate([], { wait: true })(withRouter(AuthenticatedNavigation));

View file

@ -0,0 +1,78 @@
/* eslint-disable react/jsx-indent-props */
/* eslint-disable import/no-absolute-path */
/* eslint-disable import/no-absolute-path */
/* global L */
import { Map } from 'react-leaflet';
import LGeo from 'leaflet-geodesy';
import tunion from '@turf/union';
import { check, Match } from 'meteor/check';
// https://stackoverflow.com/questions/35394577/leaflet-js-union-merge-circles
function unify(polyList) {
let unionTemp;
for (let i = 0; i < polyList.length; i += 1) {
if (i === 0) {
unionTemp = polyList[i].toGeoJSON();
} else {
unionTemp = tunion(unionTemp, polyList[i].toGeoJSON());
}
}
return unionTemp;
}
const subsUnion = (union, options) => {
// check(union, Match.Optional(Object));
check(options, {
map: Map,
show: Boolean,
subs: [Object],
color: Match.Optional(String),
fillcolor: Match.Optional(String),
opacity: Match.Optional(Number),
fit: Boolean
});
const color = options.color || '#145A32';
const fillColor = options.fillColor || 'green';
const opacity = options.options || 0.1;
if (options.subs.length > 0) {
const lmap = options.map.leafletElement;
// http://leafletjs.com/reference-1.2.0.html#layergroup
// FeatureGroup has getBounds
const unionGroup = new L.FeatureGroup();
if (union) {
lmap.removeLayer(union);
}
union = null;
if (options.show) {
// http://leafletjs.com/reference-1.2.0.html#path
const copts = {
parts: 144
};
options.subs.forEach((sub) => {
const circle = LGeo.circle([sub.location.lat, sub.location.lon], sub.distance * 1000, copts);
circle.addTo(unionGroup);
});
const unionJson = unify(unionGroup.getLayers());
union = L.geoJson(unionJson);
union.setStyle({
color,
fillColor,
fillOpacity: opacity
});
union.addTo(lmap);
if (options.fit) {
options.map.leafletElement.fitBounds(unionGroup.getBounds());
}
return union;
}
}
return union;
};
export default subsUnion;

View file

@ -1,15 +0,0 @@
/* global L */
// https://stackoverflow.com/questions/35394577/leaflet-js-union-merge-circles
import union from '@turf/union';
export function unify(polyList) {
let unionTemp;
for (let i = 0; i < polyList.length; i += 1) {
if (i === 0) {
unionTemp = polyList[i].toGeoJSON();
} else {
unionTemp = union(unionTemp, polyList[i].toGeoJSON());
}
}
return L.geoJson(unionTemp);
}

View file

@ -35,7 +35,7 @@ const Navigation = props => (
</LinkContainer> */} </LinkContainer> */}
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/subscriptions"> <LinkContainer className="nav-item" anchorClassName="nav-link" to="/subscriptions">
<NavItem eventKey={1.2} href="/subscriptions"> <NavItem eventKey={1.2} href="/subscriptions">
{props.authenticated ? <Trans>Mis alertas</Trans> : <Trans>Participar</Trans>} {props.authenticated ? <Trans>Mis zonas</Trans> : <Trans>Participar</Trans>}
</NavItem> </NavItem>
</LinkContainer> </LinkContainer>
<LinkContainer className="nav-item" anchorClassName="nav-link" to="/fires"> <LinkContainer className="nav-item" anchorClassName="nav-link" to="/fires">

View file

@ -1,5 +1,6 @@
/* global setTimeout */ /* global setTimeout */
/* eslint-disable react/jsx-indent-props */ /* eslint-disable react/jsx-indent-props */
/* eslint-disable react/jsx-indent */
/* eslint-disable import/no-absolute-path */ /* eslint-disable import/no-absolute-path */
/* eslint-disable import/no-absolute-path */ /* eslint-disable import/no-absolute-path */
@ -7,7 +8,7 @@ import React, { Component } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Map, TileLayer, Marker, CircleMarker, Circle } from 'react-leaflet'; import { Map, TileLayer, Marker, CircleMarker, Circle } from 'react-leaflet';
import Leaflet from 'leaflet'; import Leaflet from 'leaflet';
import { Trans, translate } from 'react-i18next'; import { translate } from 'react-i18next';
import { withTracker } from 'meteor/react-meteor-data'; import { withTracker } from 'meteor/react-meteor-data';
import update from 'immutability-helper'; import update from 'immutability-helper';
import geolocation from '/imports/startup/client/geolocation'; import geolocation from '/imports/startup/client/geolocation';
@ -16,9 +17,8 @@ import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js'; import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
import 'leaflet-sleep/Leaflet.Sleep.js'; import 'leaflet-sleep/Leaflet.Sleep.js';
import Control from 'react-leaflet-control'; import Control from 'react-leaflet-control';
import { Button, ButtonToolbar } from 'react-bootstrap'; import { Button, ButtonGroup } from 'react-bootstrap';
import { Sidebar, Tab } from 'react-leaflet-sidebarv2'; import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
import '/imports/ui/stylesheets/leaflet-sidebar.min.css';
import './SelectionMap.scss'; import './SelectionMap.scss';
class SelectionMap extends Component { class SelectionMap extends Component {
@ -27,11 +27,9 @@ class SelectionMap extends Component {
this.state = { this.state = {
center: props.center, center: props.center,
marker: props.center, marker: props.center,
zoom: 11, zoom: props.zoom,
distance: props.distance, distance: props.distance,
draggable: true, draggable: true
sidebarCollapsed: true,
sidebarSelected: 'home'
}; };
this.getMap = this.getMap.bind(this); this.getMap = this.getMap.bind(this);
@ -39,7 +37,8 @@ class SelectionMap extends Component {
this.updatePosition = this.updatePosition.bind(this); this.updatePosition = this.updatePosition.bind(this);
this.fit = this.fit.bind(this); this.fit = this.fit.bind(this);
this.addScale = this.addScale.bind(this); this.addScale = this.addScale.bind(this);
this.onSubs = this.onSubs.bind(this); this.onFstBtn = this.onFstBtn.bind(this);
this.onViewportChanged = this.onViewportChanged.bind(this);
} }
componentDidMount() { componentDidMount() {
@ -56,20 +55,30 @@ class SelectionMap extends Component {
marker: nextMarker, marker: nextMarker,
distance: nextProps.distance || this.state.distance distance: nextProps.distance || this.state.distance
}); });
this.fit(); // this.fit();
} }
componentDidUpdate() { componentDidUpdate() {
this.fit(); // this.fit();
} }
onSubs() { onFstBtn() {
this.props.onSubs({ this.props.onFstBtn({
location: { lat: this.state.center[0], lon: this.state.center[1] }, location: { lat: this.state.center[0], lon: this.state.center[1] },
distance: this.state.distance distance: this.state.distance
}); });
} }
onSndBtn() {
this.props.onSndBtn();
}
onViewportChanged(viewport) {
if (this.props.onViewportChanged) {
this.props.onViewportChanged(viewport);
}
}
getMap() { getMap() {
return this.selectionMap.leafletElement; return this.selectionMap.leafletElement;
} }
@ -83,101 +92,66 @@ class SelectionMap extends Component {
// console.log(`New marker lat ${lat} and lng ${lng}`); // console.log(`New marker lat ${lat} and lng ${lng}`);
const currentDistance = this.state.distance; const currentDistance = this.state.distance;
this.setState(update(this.state, { $merge: { marker: [lat, lng] } })); this.setState(update(this.state, { $merge: { marker: [lat, lng] } }));
this.props.onSelection({ lat, lng, currentDistance }); if (this.props.onSelection) {
this.props.onSelection({ lat, lng, currentDistance });
}
this.fit(); this.fit();
// this.addScale();
} }
fit() { fit() {
// console.log("fit!"); // console.log("fit!");
if (this.selectionMap && this.distanceCircle) { if (this.subsUnionElement) {
// has autofit
} else if (this.selectionMap && this.distanceCircle) {
this.getMap().fitBounds(this.distanceCircle.leafletElement.getBounds(), [70, 70]); this.getMap().fitBounds(this.distanceCircle.leafletElement.getBounds(), [70, 70]);
} }
} }
addScale() { addScale() {
// https://www.npmjs.com/package/leaflet-graphicscale if (this.selectionMap) {
const map = this.getMap(); // https://www.npmjs.com/package/leaflet-graphicscale
const options = { const map = this.getMap();
fill: 'fill', const options = {
showSubunits: true fill: 'fill',
}; showSubunits: true
// var graphicScale = };
Leaflet.control.graphicScale([options]).addTo(map); // var graphicScale =
Leaflet.control.graphicScale([options]).addTo(map);
}
} }
isValidState() { isValidState() {
return this.state.center && this.state.center[0] && this.state.distance; return this.state.center && this.state.center[0];
} }
onSidebarClose() { handleLeafletLoad(map) {
this.setState({ sidebarCollapsed: true }); if (this.props.readOnly && this.props.currentSubs && map && !this.props.loadingSubs) {
} this.state.union = subsUnion(this.state.union, {
map,
onSidebarOpen(id) { show: true,
this.setState({ fit: true,
sidebarCollapsed: false, subs: this.props.currentSubs
sidebarSelected: id });
}); }
}
aTab(oid, name) {
return (
<Tab id={`sidetab-${oid}`} header={name} icon="fa fa-map-marker">
<div className="btn-group-vertical sidebar-tab-btn-group">
<Button
bsStyle="default"
><i className="fa fa-pencil-square-o" />
<Trans>Editar</Trans>
</Button>
<Button
bsStyle="default"
><i className="icons icon-target" />
<Trans>Centrar aquí</Trans>
</Button>
<Button
bsStyle="default"
>
<Trans>Desahabilitar</Trans>
</Button>
<Button
bsStyle="danger"
><i className="fa fa-times" />
<Trans>Borrar</Trans>
</Button>
</div>
</Tab>
);
} }
render() { render() {
// console.log('render map called');
return ( return (
<div> <div>
{ this.isValidState() && { this.isValidState() &&
<div className="leaflet-container"> <div className="leaflet-container">
<Sidebar
id="sidebar"
collapsed={this.state.sidebarCollapsed}
selected={this.state.sidebarSelected}
closeIcon="fa fa-chevron-left"
onOpen={this.onSidebarOpen.bind(this)}
onClose={this.onSidebarClose.bind(this)}
>
<Tab id="home" header="Suscripciones" icon="fa fa-bars">
<p>Pulsa en alguna de tus suscripciones para editarlas, etc.</p>
</Tab>
{this.aTab('someid2', 'Some fire')}
{this.aTab('someid3', 'Some another fire')}
</Sidebar>
<Map <Map
className="sidebar-map" /* className="sidebar-map" */
center={this.state.center} center={this.state.center}
zoom={this.state.zoom} zoom={this.state.zoom}
ref={(map) => { this.selectionMap = map; }} ref={(map) => {
this.selectionMap = map;
this.handleLeafletLoad(map);
}}
sleep={window.location.pathname === '/'} sleep={window.location.pathname === '/'}
sleepTime={10750} sleepTime={10750}
wakeTime={750} wakeTime={750}
onViewportChanged={this.onViewportChanged}
sleepNote sleepNote
hoverToWake hoverToWake
wakeMessage={this.props.t('Pulsa para activar')} wakeMessage={this.props.t('Pulsa para activar')}
@ -187,6 +161,7 @@ class SelectionMap extends Component {
attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors" attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/> />
{!this.props.readOnly &&
<Marker <Marker
draggable={this.state.draggable} draggable={this.state.draggable}
onDragend={this.updatePosition} onDragend={this.updatePosition}
@ -194,7 +169,8 @@ class SelectionMap extends Component {
icon={positionIcon} icon={positionIcon}
title={this.props.t('Arrastrar para seleccionar otro punto')} title={this.props.t('Arrastrar para seleccionar otro punto')}
ref={(ref) => { this.marker = ref; }} ref={(ref) => { this.marker = ref; }}
/> /> }
{!this.props.readOnly &&
<CircleMarker <CircleMarker
center={this.state.marker} center={this.state.marker}
color="red" color="red"
@ -202,7 +178,8 @@ class SelectionMap extends Component {
fillOpacity="1" fillOpacity="1"
fill fill
radius={3} radius={3}
/> /> }
{!this.props.readOnly &&
<Circle <Circle
center={this.state.marker} center={this.state.marker}
ref={(ref) => { this.distanceCircle = ref; }} ref={(ref) => { this.distanceCircle = ref; }}
@ -210,16 +187,24 @@ class SelectionMap extends Component {
fillColor="green" fillColor="green"
fillOpacity={0.1} fillOpacity={0.1}
radius={this.state.distance * 1000} radius={this.state.distance * 1000}
/> /> }
<Control position="topright" > <Control position="topright" >
<ButtonToolbar> <ButtonGroup>
<Button { this.props.sndBtn && this.props.onSndBtn &&
bsStyle="success" <Button
onClick={event => this.onSubs(event)} bsStyle="warning"
> onClick={event => this.onSndBtn(event)}
{this.props.subsBtn} >
</Button> {this.props.sndBtn}
</ButtonToolbar> </Button>
}
<Button
bsStyle="success"
onClick={event => this.onFstBtn(event)}
>
{this.props.fstBtn}
</Button>
</ButtonGroup>
</Control> </Control>
</Map> </Map>
</div> </div>
@ -229,13 +214,28 @@ class SelectionMap extends Component {
} }
} }
SelectionMap.defaultProps = {
zoom: 11
};
SelectionMap.propTypes = { SelectionMap.propTypes = {
t: PropTypes.func.isRequired, t: PropTypes.func.isRequired,
center: PropTypes.arrayOf(PropTypes.number), center: PropTypes.arrayOf(PropTypes.number),
zoom: PropTypes.number,
distance: PropTypes.number, distance: PropTypes.number,
onSelection: PropTypes.func.isRequired, onSelection: PropTypes.func,
subsBtn: PropTypes.string.isRequired, onViewportChanged: PropTypes.func,
onSubs: PropTypes.func.isRequired fstBtn: PropTypes.string.isRequired,
onFstBtn: PropTypes.func.isRequired,
sndBtn: PropTypes.string,
onSndBtn: PropTypes.func,
readOnly: PropTypes.bool.isRequired,
edit: PropTypes.bool.isRequired,
loadingSubs: PropTypes.bool,
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 => ({ export default translate([], { wait: true })(withTracker(props => ({

View file

@ -26,9 +26,10 @@ class SubscriptionEditor extends React.Component {
if (error) { if (error) {
Bert.alert(error.reason, 'danger'); Bert.alert(error.reason, 'danger');
} else { } else {
const confirmation = existingSubscription ? t('Suscripción actualizada') : t('Suscripción añadida'); const confirmation = existingSubscription ? t('Zona actualizada') : t('Zona añadida');
Bert.alert(confirmation, 'success'); Bert.alert(confirmation, 'success');
history.push(`/subscriptions/${subscriptionId}`); // history.push(`/subscriptions/${subscriptionId}`);
history.push('/subscriptions');
} }
}); });
} }
@ -36,11 +37,12 @@ class SubscriptionEditor extends React.Component {
render() { render() {
const { doc, t } = this.props; const { doc, t } = this.props;
const isEdit = doc && doc._id; const isEdit = doc && doc._id;
const focus = typeof this.props.focusInput !== 'undefined' ? this.props.focusInput : !isEdit;
return ( return (
<FireSubscription <FireSubscription
center={[doc.location.lat, doc.location.lon]} center={[doc.location.lat, doc.location.lon]}
distance={doc.distance} distance={doc.distance}
focusInput={this.props.focusInput ? this.props.focusInput : !isEdit} focusInput={focus}
subsBtn={isEdit ? t('Actualizar') : t('Subscribirme a fuegos en este rádio')} subsBtn={isEdit ? t('Actualizar') : t('Subscribirme a fuegos en este rádio')}
onSubs={state => this.onSubs(state)} onSubs={state => this.onSubs(state)}
/> />

View file

@ -24,10 +24,6 @@ import Navigation from '../../components/Navigation/Navigation';
import Authenticated from '../../components/Authenticated/Authenticated'; import Authenticated from '../../components/Authenticated/Authenticated';
import Public from '../../components/Public/Public'; import Public from '../../components/Public/Public';
import Index from '../../pages/Index/Index'; import Index from '../../pages/Index/Index';
import Documents from '../../pages/Documents/Documents';
import NewDocument from '../../pages/NewDocument/NewDocument';
import ViewDocument from '../../pages/ViewDocument/ViewDocument';
import EditDocument from '../../pages/EditDocument/EditDocument';
import Subscriptions from '../../pages/Subscriptions/Subscriptions'; import Subscriptions from '../../pages/Subscriptions/Subscriptions';
import NewSubscription from '../../pages/NewSubscription/NewSubscription'; import NewSubscription from '../../pages/NewSubscription/NewSubscription';
import ViewSubscription from '../../pages/ViewSubscription/ViewSubscription'; import ViewSubscription from '../../pages/ViewSubscription/ViewSubscription';
@ -68,11 +64,11 @@ const App = props => (
<Grid> {/* bsClass="previously-container-but-disabled" > */} <Grid> {/* bsClass="previously-container-but-disabled" > */}
<Switch> <Switch>
<Route exact name="index" path="/" component={Index} /> <Route exact name="index" path="/" component={Index} />
<Authenticated exact path="/documents" component={Documents} {...props} /> {/* <Authenticated exact path="/documents" component={Documents} {...props} />
<Authenticated exact path="/documents/new" component={NewDocument} {...props} /> <Authenticated exact path="/documents/new" component={NewDocument} {...props} />
<Authenticated exact path="/documents/:_id" component={ViewDocument} {...props} /> <Authenticated exact path="/documents/:_id" component={ViewDocument} {...props} />
<Authenticated exact path="/documents/:_id/edit" component={EditDocument} {...props} /> <Authenticated exact path="/documents/:_id/edit" component={EditDocument} {...props} />
*/}
<Authenticated exact path="/subscriptions" component={Subscriptions} {...props} /> <Authenticated exact path="/subscriptions" component={Subscriptions} {...props} />
<Authenticated exact path="/subscriptions/new" component={NewSubscription} {...props} /> <Authenticated exact path="/subscriptions/new" component={NewSubscription} {...props} />
<Authenticated exact path="/subscriptions/:_id" component={ViewSubscription} {...props} /> <Authenticated exact path="/subscriptions/:_id" component={ViewSubscription} {...props} />

View file

@ -28,6 +28,16 @@ class FireSubscription extends React.Component {
}); });
} }
shouldComponentUpdate(nextProps, nextState) {
if (this.state.init &&
nextState.center === this.state.center &&
nextState.distance === this.state.distance) {
return false;
}
return true;
}
onAutocompleteChange(value) { onAutocompleteChange(value) {
this.setState({ center: [value.lat, value.lng] }); this.setState({ center: [value.lat, value.lng] });
} }
@ -51,7 +61,7 @@ class FireSubscription extends React.Component {
render() { render() {
// https://developers.google.com/places/web-service/search // https://developers.google.com/places/web-service/search
// https://github.com/kenny-hibino/react-places-autocomplete/blob/master/demo/Demo.js // https://github.com/kenny-hibino/react-places-autocomplete/blob/master/demo/Demo.js
console.log(`Focus autocomplete input: ${this.props.focusInput}`);
if (!this.state.init) { if (!this.state.init) {
return <div />; return <div />;
} }
@ -77,9 +87,11 @@ class FireSubscription extends React.Component {
<SelectionMap <SelectionMap
center={this.state.center} center={this.state.center}
distance={this.state.distance} distance={this.state.distance}
subsBtn={this.props.subsBtn} fstBtn={this.props.subsBtn}
onFstBtn={state => this.onSubs(state)}
onSelection={state => this.onSelection(state)} onSelection={state => this.onSelection(state)}
onSubs={state => this.onSubs(state)} readOnly={false}
edit={false}
/> />
</Row> </Row>
</div> </div>

View file

@ -60,7 +60,7 @@ class SubsAutocomplete extends React.Component {
<form> <form>
<FormGroup> <FormGroup>
<ControlLabel> <ControlLabel>
<Trans parent="span">Indícanos la posición a vigilar (por ej. tu pueblo, una calle, etc):</Trans> <Trans parent="span">Indícanos la posición de la zona a vigilar (por ej. tu pueblo, una calle, etc):</Trans>
</ControlLabel> </ControlLabel>
<PlacesAutocomplete <PlacesAutocomplete
styles={myStyles} styles={myStyles}
@ -90,7 +90,7 @@ class SubsAutocomplete extends React.Component {
autoFocus: this.props.focusInput autoFocus: this.props.focusInput
}} }}
/> />
<HelpBlock><Trans parent="span">También puedes seleccionar el lugar en el mapa arrastrando el puntero naranja.</Trans></HelpBlock> <HelpBlock><Trans parent="span">También puedes seleccionar la zona en el mapa arrastrando el puntero naranja.</Trans></HelpBlock>
</FormGroup> </FormGroup>
</form> </form>
); );

View file

@ -10,7 +10,6 @@ import { ReactiveVar } from 'meteor/reactive-var';
import { withTracker } from 'meteor/react-meteor-data'; import { withTracker } from 'meteor/react-meteor-data';
import { Trans, translate } from 'react-i18next'; import { Trans, translate } from 'react-i18next';
import { Map, TileLayer, LayersControl } from 'react-leaflet'; import { Map, TileLayer, LayersControl } from 'react-leaflet';
import LGeo from 'leaflet-geodesy';
import _ from 'lodash'; import _ from 'lodash';
import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css'; import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
@ -19,7 +18,7 @@ import 'leaflet-sleep/Leaflet.Sleep.js';
import geolocation from '/imports/startup/client/geolocation'; import geolocation from '/imports/startup/client/geolocation';
import CenterInMyPosition from '/imports/ui/components/CenterInMyPosition/CenterInMyPosition'; import CenterInMyPosition from '/imports/ui/components/CenterInMyPosition/CenterInMyPosition';
import FireList from '/imports/ui/components/Maps/FireList'; import FireList from '/imports/ui/components/Maps/FireList';
import { unify } from '/imports/ui/components/Maps/Utils'; import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
import Loading from '/imports/ui/components/Loading/Loading'; import Loading from '/imports/ui/components/Loading/Loading';
import ActiveFiresCollection from '/imports/api/ActiveFires/ActiveFires'; import ActiveFiresCollection from '/imports/api/ActiveFires/ActiveFires';
import FireAlertsCollection from '/imports/api/FireAlerts/FireAlerts'; import FireAlertsCollection from '/imports/api/FireAlerts/FireAlerts';
@ -61,68 +60,24 @@ class FiresMap extends React.Component {
self.setState({ gkey: key }); self.setState({ gkey: key });
}); });
mapSize.set([this.divElement.clientHeight, this.divElement.clientWidth]); mapSize.set([this.divElement.clientHeight, this.divElement.clientWidth]);
this.addScale(); if (this.fireMap) {
this.addScale();
}
} }
/* componentWillReceiveProps(nextProps) {
* if (nextProps.loading) {
* // console.log('Loading new fires');
* }
* // this.setState({ loading: nextProps.loading });
* }
*/
/* shouldComponentUpdate(nextProps, nextState) {
* if (nextProps.loading) {
* return true; // false;
* }
* return true;
* }
*/
onViewportChanged(viewport) { onViewportChanged(viewport) {
this.debounceView(viewport); this.debounceView(viewport);
} }
onClickReset() { onClickReset() {
// console.log("onclick");
// this.setState({ viewport: DEFAULT_VIEWPORT })
} }
getMap() { getMap() {
return this.fireMap.leafletElement; return this.fireMap.leafletElement;
} }
setShowSubsUnion(show) { setShowSubsUnion(showSubsUnion) {
this.showSubsUnion(show); this.setState({ showSubsUnion });
}
showSubsUnion(show) {
const map = this.getMap();
// http://leafletjs.com/reference-1.2.0.html#layergroup
const unionGroup = new L.LayerGroup();
if (this.union) {
map.removeLayer(this.union);
}
if (show) {
// http://leafletjs.com/reference-1.2.0.html#path
const copts = {
parts: 144
};
UserSubsToFiresCollection.find().forEach((subs) => {
const circle = LGeo.circle([subs.lat, subs.lon], subs.distance * 1000, copts);
circle.addTo(unionGroup);
});
this.union = unify(unionGroup.getLayers());
this.union.setStyle({
color: '#145A32',
fillColor: 'green',
fillOpacity: 0.1
});
this.union.addTo(map);
}
} }
handleViewportChange(viewport) { handleViewportChange(viewport) {
@ -135,14 +90,10 @@ class FiresMap extends React.Component {
zoom.set(viewport.zoom); zoom.set(viewport.zoom);
center.set(viewport.center); center.set(viewport.center);
this.setState({ viewport }); this.setState({ viewport });
if (this.props.subsready && this.fireMap) {
this.showSubsUnion(this.state.showSubsUnion);
}
} }
centerOnUserLocation(viewport) { centerOnUserLocation(viewport) {
this.setState({ viewport }); this.setState({ viewport });
// this.handleViewportChange(viewport);
} }
useMarkers(use) { useMarkers(use) {
@ -150,22 +101,29 @@ class FiresMap extends React.Component {
} }
addScale() { addScale() {
if (this.fireMap) { // https://www.npmjs.com/package/leaflet-graphicscale
// https://www.npmjs.com/package/leaflet-graphicscale const map = this.getMap();
const map = this.getMap(); const options = {
const options = { fill: 'fill',
fill: 'fill', showSubunits: true
showSubunits: true };
}; L.control.graphicScale([options]).addTo(map);
L.control.graphicScale([options]).addTo(map); }
handleLeafletLoad(map) {
console.log('Map loading');
console.log(map);
if (map) {
this.state.union = subsUnion(this.state.union, {
map,
subs: this.props.userSubs,
show: this.state.showSubsUnion,
fit: false
});
} }
} }
render() { render() {
if (this.props.subsready && this.fireMap) {
// Show union of users
this.showSubsUnion(this.state.showSubsUnion);
}
console.log(`Rendering ${this.props.loading ? 'loading' : 'LOADED'} map ${this.props.activefires.length} of ${this.props.activefirestotal} total. Subs users ready ${this.props.subsready}, reactive ${this.state.viewport.zoom >= MAXZOOMREACTIVE}`); console.log(`Rendering ${this.props.loading ? 'loading' : 'LOADED'} map ${this.props.activefires.length} of ${this.props.activefirestotal} total. Subs users ready ${this.props.subsready}, reactive ${this.state.viewport.zoom >= MAXZOOMREACTIVE}`);
const { t } = this.props; const { t } = this.props;
const osmlayer = ( const osmlayer = (
@ -181,7 +139,7 @@ class FiresMap extends React.Component {
<div <div
ref={(divElement) => { this.divElement = divElement; }} ref={(divElement) => { this.divElement = divElement; }}
> >
{this.props.loading ? {this.props.loading || !this.props.subsready ?
<Row className="align-items-center justify-content-center"> <Row className="align-items-center justify-content-center">
<Loading /> <Loading />
</Row> </Row>
@ -217,9 +175,11 @@ class FiresMap extends React.Component {
</Row> </Row>
<Row> <Row>
{/* https://github.com/CliffCloud/Leaflet.Sleep */} {/* https://github.com/CliffCloud/Leaflet.Sleep */}
<Map <Map
ref={(map) => { this.fireMap = map; }} ref={(map) => {
this.fireMap = map;
this.handleLeafletLoad(map);
}}
animate animate
minZoom={5} minZoom={5}
preferCanvas preferCanvas
@ -277,6 +237,7 @@ class FiresMap extends React.Component {
FiresMap.propTypes = { FiresMap.propTypes = {
loading: PropTypes.bool.isRequired, loading: PropTypes.bool.isRequired,
subsready: PropTypes.bool.isRequired, subsready: PropTypes.bool.isRequired,
userSubs: PropTypes.arrayOf(PropTypes.object).isRequired,
activefires: PropTypes.arrayOf(PropTypes.object).isRequired, activefires: PropTypes.arrayOf(PropTypes.object).isRequired,
firealerts: PropTypes.arrayOf(PropTypes.object).isRequired, firealerts: PropTypes.arrayOf(PropTypes.object).isRequired,
activefirestotal: PropTypes.number.isRequired, activefirestotal: PropTypes.number.isRequired,
@ -312,7 +273,7 @@ export default translate([], { wait: true })(withTracker(() => {
// Warning with the performance of this log: // Warning with the performance of this log:
// console.log(`Active fires ${ActiveFiresCollection.find().count()} of ${Counter.get('countActiveFires')}`); // console.log(`Active fires ${ActiveFiresCollection.find().count()} of ${Counter.get('countActiveFires')}`);
// console.log(`Active neighborhood fires ${FireAlertsCollection.find().fetch().length} and users subscribed ${UserSubsToFiresCollection.find().fetch().length}`); // console.log(`Active neighborhood fires ${FireAlertsCollection.find().fetch().length} and users subscribed ${UserSubsToFiresCollection.find().fetch().length}`);
// console.log(UserSubsToFiresCollection.find().fetch()); console.log(UserSubsToFiresCollection.find().fetch());
return { return {
loading: !subscription.ready(), loading: !subscription.ready(),
userSubs: UserSubsToFiresCollection.find().fetch(), userSubs: UserSubsToFiresCollection.find().fetch(),

View file

@ -32,3 +32,7 @@
.mark-checkbox { .mark-checkbox {
margin-left: 5px; margin-left: 5px;
} }
.leaflet-control-layers-toggle {
background-image: url(/images/layers.png);
}

View file

@ -5,7 +5,7 @@ import SubscriptionEditor from '../../components/SubscriptionEditor/Subscription
const NewSubscription = ({ history }) => ( const NewSubscription = ({ history }) => (
<div className="NewSubscription"> <div className="NewSubscription">
<h4 className="page-header"><Trans>Nueva suscripción</Trans></h4> <h4 className="page-header"><Trans>Nueva zona</Trans></h4>
<SubscriptionEditor history={history} /> <SubscriptionEditor history={history} />
</div> </div>
); );

View file

@ -2,99 +2,143 @@
/* eslint-disable import/no-absolute-path */ /* eslint-disable import/no-absolute-path */
/* eslint-disable react/jsx-indent */ /* eslint-disable react/jsx-indent */
import React from 'react'; import React, { Component } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { Table, Alert, Button, Row } from 'react-bootstrap'; import { Table, Alert, Button } from 'react-bootstrap';
import { timeago, monthDayYearAtTime } from '@cleverbeagle/dates'; import { timeago } from '@cleverbeagle/dates';
import { Meteor } from 'meteor/meteor'; import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data'; import { withTracker } from 'meteor/react-meteor-data';
import { Trans, translate } from 'react-i18next'; import { Trans, translate } from 'react-i18next';
import { Bert } from 'meteor/themeteorchef:bert'; import { Bert } from 'meteor/themeteorchef:bert';
import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions'; import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions';
import SelectionMap from '/imports/ui/components/SelectionMap/SelectionMap';
import Loading from '../../components/Loading/Loading'; import Loading from '../../components/Loading/Loading';
import './Subscriptions.scss'; import './Subscriptions.scss';
const handleRemove = (subscriptionId) => { class Subscriptions extends Component {
if (confirm('Are you sure? This is permanent!')) { constructor(props) {
Meteor.call('subscriptions.remove', subscriptionId, (error) => { super(props);
if (error) { this.t = props.t;
Bert.alert(error.reason, 'danger'); this.state = {
} else { edit: false
Bert.alert('Subscription deleted!', 'success'); };
} this.onViewportChanged = this.onViewportChanged.bind(this);
}); this.onFstBtn = this.onFstBtn.bind(this);
this.onSndBtn = this.onSndBtn.bind(this);
} }
};
const Subscriptions = ({ onFstBtn(value) {
loading, // ${match.url}/new
subscriptions, }
match,
history onSndBtn() {
}) => (!loading ? ( this.state.edit = true;
<div className="Subscriptions"> }
<div className="page-header clearfix">
<h4 className="pull-left"><Trans>Suscripciones a fuegos en áreas de mi interés</Trans></h4> onViewportChanged(viewport) {
<Link className="btn btn-success pull-right" to={`${match.url}/new`}><Trans>Añadir suscripción</Trans></Link> this.state.center = viewport.center;
</div> this.state.zoom = viewport.zoom;
<br /> }
{subscriptions.length ?
<Table responsive> handleRemove(subscriptionId) {
<thead> if (confirm('Are you sure? This is permanent!')) {
<tr> Meteor.call('subscriptions.remove', subscriptionId, (error) => {
<th>Location</th> if (error) {
<th>Last Updated</th> Bert.alert(error.reason, 'danger');
<th>Created</th> } else {
<th /> Bert.alert('Subscription deleted!', 'success');
<th /> }
</tr> });
</thead>
<tbody>
{subscriptions.map(({
_id,
location,
createdAt,
updatedAt
}) => (
<tr key={_id}>
<td>{location.lat},{location.lon}</td>
<td>{timeago(updatedAt)}</td>
<td>{monthDayYearAtTime(createdAt)}</td>
<td>
<Button
bsStyle="primary"
onClick={() => history.push(`${match.url}/${_id}`)}
block
>View
</Button>
</td>
<td>
<Button
bsStyle="danger"
onClick={() => handleRemove(_id)}
block
>Delete
</Button>
</td>
</tr>
))}
</tbody>
</Table> :
<Alert bsStyle="warning"><Trans>Todavía sin suscriptiones</Trans></Alert>
} }
</div> }
) : <Loading />);
render() {
const {
loading,
t,
subscriptions,
match,
history
} = this.props;
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>
<Link className="btn btn-success pull-right" to={`${match.url}/new`}><Trans>Añadir zona</Trans></Link>
</div>
<br />
<SelectionMap
center={[null, null]}
zoom={11}
readOnly
edit={this.state.edit}
fstBtn={t('Añadir zona')}
onFstBtn={state => this.onFstBtn(state)}
sndBtn={this.props.subscriptions.length > 1 ? t('Editar') : null}
onSndBtn={() => this.onSndBtn()}
onViewportChanged={viewport => this.onViewportChanged(viewport)}
loadingSubs={this.props.loading}
currentSubs={this.props.subscriptions}
/>
{subscriptions.length ?
<Table responsive>
<thead>
<tr>
<th><Trans>Lugar</Trans></th>
<th><Trans>Actualizado</Trans></th>
<th><Trans>Creado</Trans>
</th>
<th />
<th />
</tr>
</thead>
<tbody>
{subscriptions.map(({
_id,
location,
createdAt,
updatedAt
}) => (
<tr key={_id}>
<td>{location.lat},{location.lon}</td>
<td>{timeago(updatedAt)}</td>
<td>{timeago(createdAt)}</td>
<td>
<Button
bsStyle="primary"
onClick={() => history.push(`${match.url}/${_id}`)}
block
>View
</Button>
</td>
<td>
<Button
bsStyle="danger"
onClick={() => this.handleRemove(_id)}
block
>Delete
</Button>
</td>
</tr>
))}
</tbody>
</Table> :
<Alert bsStyle="warning"><Trans>No estás suscrito a fuegos en ninguna zona</Trans></Alert>
}
</div>
) : <Loading />);
}
}
Subscriptions.propTypes = { Subscriptions.propTypes = {
loading: PropTypes.bool.isRequired, loading: PropTypes.bool.isRequired,
subscriptions: PropTypes.arrayOf(PropTypes.object).isRequired, subscriptions: PropTypes.arrayOf(PropTypes.object).isRequired,
match: PropTypes.object.isRequired, match: PropTypes.object.isRequired,
t: PropTypes.func.isRequired,
history: PropTypes.object.isRequired history: PropTypes.object.isRequired
}; };
export default translate([], { wait: true })(withTracker(() => { export default translate([], { wait: true })(withTracker(() => {
const subscription = Meteor.subscribe('mysubscriptions'); const subscription = Meteor.subscribe('mysubscriptions');
// console.log(UserSubsToFiresCollection.find().fetch()); // console.log(UserSubsToFiresCollection.find().fetch());

22
package-lock.json generated
View file

@ -21,17 +21,17 @@
} }
}, },
"@turf/helpers": { "@turf/helpers": {
"version": "5.1.0", "version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/helpers/-/helpers-5.1.0.tgz", "resolved": "https://registry.npmjs.org/@turf/helpers/-/helpers-5.1.5.tgz",
"integrity": "sha1-4whphlTb93C0rxOV34TkPEkmFL0=" "integrity": "sha1-FTQFInq5M9AEpbuWQantmZ/L4M8="
}, },
"@turf/union": { "@turf/union": {
"version": "5.1.0", "version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/union/-/union-5.1.0.tgz", "resolved": "https://registry.npmjs.org/@turf/union/-/union-5.1.5.tgz",
"integrity": "sha1-UAT1fxZasGIPvmRMpaoksBKCATg=", "integrity": "sha1-UyhbYJQEf8WNlqrA6pCGXsNNRUs=",
"requires": { "requires": {
"@turf/helpers": "5.1.0", "@turf/helpers": "5.1.5",
"turf-jsts": "1.2.0" "turf-jsts": "1.2.2"
} }
}, },
"@types/node": { "@types/node": {
@ -11337,9 +11337,9 @@
} }
}, },
"turf-jsts": { "turf-jsts": {
"version": "1.2.0", "version": "1.2.2",
"resolved": "https://registry.npmjs.org/turf-jsts/-/turf-jsts-1.2.0.tgz", "resolved": "https://registry.npmjs.org/turf-jsts/-/turf-jsts-1.2.2.tgz",
"integrity": "sha1-EnxOQzKlns7pF/yjHUk5luglS+A=" "integrity": "sha1-uZkjZZpGc3uBQT7P+b1w42C6F1M="
}, },
"tweetnacl": { "tweetnacl": {
"version": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", "version": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",

View file

@ -8,7 +8,7 @@
"dependencies": { "dependencies": {
"@cleverbeagle/dates": "^0.5.1", "@cleverbeagle/dates": "^0.5.1",
"@cleverbeagle/seeder": "^1.3.1", "@cleverbeagle/seeder": "^1.3.1",
"@turf/union": "^5.1.0", "@turf/union": "^5.1.5",
"babel-runtime": "^6.26.0", "babel-runtime": "^6.26.0",
"bcrypt": "^1.0.3", "bcrypt": "^1.0.3",
"commonmark": "^0.28.1", "commonmark": "^0.28.1",