basic useItems hook

This commit is contained in:
AT 2022-08-04 11:51:04 +02:00
parent 654d066587
commit aef9f56148
9 changed files with 221 additions and 93 deletions

5
LICENSE.md Normal file
View File

@ -0,0 +1,5 @@
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -14,7 +14,7 @@
], ],
"keywords": [], "keywords": [],
"author": "Anton Tranelis", "author": "Anton Tranelis",
"license": "ISC", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/leaflet": "^1.7.11", "@types/leaflet": "^1.7.11",
"@types/react": "^18.0.14", "@types/react": "^18.0.14",

View File

@ -3,12 +3,13 @@ import { Marker } from 'react-leaflet'
import { Item, Tag } from '../../types' import { Item, Tag } from '../../types'
import MarkerIconFactory from '../../Utils/MarkerIconFactory' import MarkerIconFactory from '../../Utils/MarkerIconFactory'
import { Popup } from './Popup' import { Popup } from './Popup'
import { useItems } from './useItems'
export interface LayerProps { export interface LayerProps {
data: Item[], data: Item[],
children?: React.ReactNode children?: React.ReactNode
name : string, name: string,
menuIcon: string, menuIcon: string,
menuColor: string, menuColor: string,
menuText: string, menuText: string,
@ -18,42 +19,43 @@ export interface LayerProps {
tags?: Tag[] tags?: Tag[]
} }
export const Layer = (props: LayerProps) => { export const Layer = (props: LayerProps) => {
// create a JS-Map with all Tags // create a JS-Map with all Tags
let tagMap = new Map(props.tags?.map(key => [key.id, key])); let tagMap = new Map(props.tags?.map(key => [key.id, key]));
// returns all tags for passed item // returns all tags for passed item
const getTags = (item: Item) => { const getTags = (item: Item) => {
let tags: Tag[] = []; let tags: Tag[] = [];
item.tags && item.tags.forEach(element => { item.tags && item.tags.forEach(element => {
if (tagMap.has(element)) { tags.push(tagMap.get(element)!); }; if (tagMap.has(element)) { tags.push(tagMap.get(element)!); };
}); });
return tags; return tags;
}; };
let items = useItems();
return ( return (
<> <>
{ {
props.data.map((place: Item) => { items.map((place: Item) => {
let tags = getTags(place); console.log("Items check in Layer: " + items);
let color1 = "#666"; let tags = getTags(place);
let color2 = "RGBA(35, 31, 32, 0.2)"; let color1 = "#666";
if (tags[0]) { let color2 = "RGBA(35, 31, 32, 0.2)";
color1 = tags[0].color; if (tags[0]) {
} color1 = tags[0].color;
if (tags[1]) { }
color2 = tags[1].color; if (tags[1]) {
} color2 = tags[1].color;
return ( }
<Marker icon={MarkerIconFactory(props.markerShape, color1, color2, props.markerIcon)} key={place.id} position={[place.position.coordinates[1], place.position.coordinates[0]]}> return (
<Popup item={place} tags={tags} /> <Marker icon={MarkerIconFactory(props.markerShape, color1, color2, props.markerIcon)} key={place.id} position={[place.position.coordinates[1], place.position.coordinates[0]]}>
</Marker> <Popup item={place} tags={tags} />
); </Marker>
}) );
} })
{props.children} }
{props.children}
</> </>
) )
} }

View File

@ -1,22 +1,39 @@
import * as React from 'react' import * as React from 'react'
import { LatLng } from 'leaflet' import { LatLng } from 'leaflet'
import { Popup as LeafletPopup } from 'react-leaflet' import { Popup as LeafletPopup, useMap } from 'react-leaflet'
import { useState } from 'react'
import { useAddItem } from './useItems'
import { Item } from './UtopiaMap'
import { Geometry } from '../../types'
export interface NewItemPopupProps { export interface NewItemPopupProps {
position: LatLng, position: LatLng,
itemType: string, layer: string,
onSubmit: (name: string, text: string, position : LatLng, layer : string) => void
} }
export default function NewItemPopup(props: NewItemPopupProps) { export default function NewItemPopup(props: NewItemPopupProps) {
console.log(props.itemType); const [name, setName] = useState('')
const [text, setText] = useState('')
const map = useMap();
const addItem = useAddItem();
const handleSubmit = async (evt: any) => {
evt.preventDefault()
addItem(new Item(123213, name, text, new Geometry(props.position.lng, props.position.lat)))
map.closePopup();
}
return ( return (
<LeafletPopup maxHeight={300} minWidth={275} maxWidth={275} autoPanPadding={[20, 5]} <LeafletPopup maxHeight={300} minWidth={275} maxWidth={275} autoPanPadding={[20, 5]}
position={props.position}> position={props.position}>
<div className='flex justify-center'><b className="text-xl font-bold">New {props.itemType}</b></div> <form onSubmit={handleSubmit}>
<input type="text" placeholder="Name" className="input input-bordered w-full max-w-xs mt-5" /> <div className='flex justify-center'><b className="text-xl font-bold">New {props.layer}</b></div>
<textarea className="textarea textarea-bordered w-full mt-5" placeholder="Text"></textarea> <input type="text" placeholder="Name" className="input input-bordered w-full max-w-xs mt-5" value={name} onChange={e => setName(e.target.value)} />
<div className='flex justify-center'><button className="btn mt-5 place-self-center">Save</button></div> <textarea className="textarea textarea-bordered w-full mt-5" placeholder="Text" value={text} onChange={e => setText(e.target.value)}></textarea>
<div className='flex justify-center'><button className="btn mt-5 place-self-center">Save</button></div>
</form>
</LeafletPopup> </LeafletPopup>
) )
} }

View File

@ -1,14 +1,15 @@
import { TileLayer, MapContainer, useMapEvents } from "react-leaflet"; import { TileLayer, MapContainer, useMapEvents } from "react-leaflet";
import "leaflet/dist/leaflet.css"; import "leaflet/dist/leaflet.css";
import * as React from "react"; import * as React from "react";
import { Item, Tag } from "../../types" import { Item, Tag, API, Geometry } from "../../types"
import "../../index.css" import "../../index.css"
import { LatLng } from "leaflet"; import { LatLng } from "leaflet";
import MarkerClusterGroup from 'react-leaflet-cluster' import MarkerClusterGroup from 'react-leaflet-cluster'
import AddButton from "./AddButton"; import AddButton from "./AddButton";
import { Layer, LayerProps } from "./Layer"; import { LayerProps } from "./Layer";
import { useState } from "react"; import { useCallback, useState } from "react";
import NewItemPopup, { NewItemPopupProps } from "./NewItemPopup"; import NewItemPopup, { NewItemPopupProps } from "./NewItemPopup";
import { ItemsProvider, useAddItem, useItems } from "./useItems";
export interface UtopiaMapProps { export interface UtopiaMapProps {
height?: string, height?: string,
@ -18,9 +19,11 @@ export interface UtopiaMapProps {
places?: Item[], places?: Item[],
events?: Item[], events?: Item[],
tags?: Tag[], tags?: Tag[],
children?: React.ReactNode children?: React.ReactNode,
api?: API
} }
export interface MapEventListenerProps { export interface MapEventListenerProps {
selectMode: string | null, selectMode: string | null,
setSelectMode: React.Dispatch<React.SetStateAction<any>>, setSelectMode: React.Dispatch<React.SetStateAction<any>>,
@ -32,9 +35,9 @@ function MapEventListener(props: MapEventListenerProps) {
click: (e) => { click: (e) => {
console.log(e.latlng.lat + ',' + e.latlng.lng); console.log(e.latlng.lat + ',' + e.latlng.lng);
console.log(props.selectMode); console.log(props.selectMode);
if (props.selectMode != null) { if (props.selectMode != null) {
props.setNewItemPopup({ itemType: props.selectMode, position: e.latlng }) props.setNewItemPopup({ layer: props.selectMode, position: e.latlng })
props.setSelectMode(null) props.setSelectMode(null)
} }
}, },
@ -45,7 +48,7 @@ function MapEventListener(props: MapEventListenerProps) {
return null return null
} }
function UtopiaMap(this: any, props: UtopiaMapProps) { function UtopiaMap(props: UtopiaMapProps) {
// init / set default values // init / set default values
let center: LatLng = new LatLng(50.6, 9.5); let center: LatLng = new LatLng(50.6, 9.5);
if (props.center) if (props.center)
@ -60,51 +63,66 @@ function UtopiaMap(this: any, props: UtopiaMapProps) {
if (props.width) if (props.width)
width = props.width; width = props.width;
const [selectMode, setSelectMode] = useState<string | null>(null); const [selectMode, setSelectMode] = useState<string | null>(null);
const [newItemPopup, setNewItemPopup] = useState<NewItemPopupProps | undefined>(undefined); const [newItemPopup, setNewItemPopup] = useState<NewItemPopupProps | null>(null);
const addItem = useAddItem();
const items = useItems();
// all the layers const handleSubmit = useCallback((name: string, text: string, position : LatLng, layer : string) => {
const layers: LayerProps[] = []; addItem(new Item(123,name,text,new Geometry(position.lng,position.lat)));
// put places / events if provided as props console.log(layer);
if (props.events) layers.push({ name: 'event', menuIcon: 'CalendarIcon', menuText: 'add new event', menuColor: '#f9a825', markerIcon: 'calendar-days-solid', markerShape: 'square', markerDefaultColor: '#777', data: props.events }); console.log("Items check in Callback: " + items);
if (props.places) layers.push({ name: 'place', menuIcon: 'LocationMarkerIcon', menuText: 'add new place', menuColor: '#2E7D32', markerIcon: 'circle-solid', markerShape: 'circle', markerDefaultColor: '#777', data: props.places });
}, [addItem]);
let layers:LayerProps[] = [];
React.Children.toArray(props.children).map(layer => {
console.log(layer);
if (React.isValidElement<LayerProps>(layer))
layers.push(layer.props)
})
let initial:Item[] = [];
if (props.events) initial = props.events;
console.log("Items check in Map 1: " + items);
return ( return (
<ItemsProvider initialItems={initial}>
<div className={(selectMode != null ? "crosshair-cursor-enabled" : undefined)}> <div className={(selectMode != null ? "crosshair-cursor-enabled" : undefined)}>
<MapContainer style={{ height: height, width: width }} center={center} zoom={zoom}> <MapContainer style={{ height: height, width: width }} center={center} zoom={zoom}>
<TileLayer <TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<MarkerClusterGroup showCoverageOnHover chunkedLoading maxClusterRadius={50}> <MarkerClusterGroup showCoverageOnHover chunkedLoading maxClusterRadius={50}>
{layers && {props.children}
layers.map(layer => (
<Layer
key={layer.name}
name={layer.name}
menuIcon={layer.menuIcon}
menuText={layer.menuText}
menuColor={layer.menuColor}
markerIcon={layer.markerIcon}
markerShape={layer.markerShape}
markerDefaultColor={layer.markerDefaultColor}
data={layer.data}
tags={props.tags} />
))
}
{console.log("children of UtopiaMap: " + props.children)}
</MarkerClusterGroup> </MarkerClusterGroup>
<MapEventListener setSelectMode={setSelectMode} selectMode={selectMode} setNewItemPopup={setNewItemPopup} /> <MapEventListener setSelectMode={setSelectMode} selectMode={selectMode} setNewItemPopup={setNewItemPopup} />
{newItemPopup && {newItemPopup &&
<NewItemPopup position={newItemPopup.position} itemType={newItemPopup.itemType}/> <NewItemPopup position={newItemPopup.position} layer={newItemPopup.layer} onSubmit={handleSubmit} />
} }
</MapContainer> </MapContainer>
<AddButton layers={layers} setSelectMode={setSelectMode}></AddButton> <AddButton layers={layers} setSelectMode={setSelectMode}></AddButton>
{selectMode != null &&
<div className="button z-500 absolute right-5 top-5 drop-shadow-md">
<div className="alert bg-white text-green-900">
<div>
<span>Select {selectMode} position!</span>
</div>
</div>
</div>
}
</div> </div>
</ItemsProvider>
); );
} }
export { UtopiaMap, Item, Tag }; export { UtopiaMap, Item, Tag, API };

View File

@ -0,0 +1 @@
export { UtopiaMap, Item, Tag, API } from './UtopiaMap'

View File

@ -0,0 +1,73 @@
import { useCallback, useReducer, createContext, useContext } from "react";
import * as React from "react";
import { Item } from "../../types";
type ActionType =
| { type: "ADD"; item: Item }
| { type: "REMOVE"; id: number };
type UseItemManagerResult = ReturnType<typeof useItemsManager>;
const ItemContext = createContext<UseItemManagerResult>({
items: [],
addItem: () => {},
removeItem: () => {}
});
function useItemsManager (initialItems: Item[]): {
items: Item[];
addItem: (item: Item) => void;
removeItem: (id: number) => void;
} {
const [items, dispatch] = useReducer((state: Item[], action: ActionType) => {
switch (action.type) {
case "ADD":
return [
...state,
action.item,
];
case "REMOVE":
return state.filter(({ id }) => id !== action.id);
default:
throw new Error();
}
}, initialItems);
const addItem = useCallback((item: Item) => {
dispatch({
type: "ADD",
item,
});
}, []);
const removeItem = useCallback((id: number) => {
dispatch({
type: "REMOVE",
id,
});
}, []);
return { items, addItem, removeItem };
}
export const ItemsProvider: React.FunctionComponent<{
initialItems: Item[], children?: React.ReactNode
}> = ({ initialItems, children }) => (
<ItemContext.Provider value={useItemsManager(initialItems)}>
{children}
</ItemContext.Provider>
);
export const useItems = (): Item[] => {
const { items } = useContext(ItemContext);
return items;
};
export const useAddItem = (): UseItemManagerResult["addItem"] => {
const { addItem } = useContext(ItemContext);
return addItem;
};
export const useRemoveItem = (): UseItemManagerResult["removeItem"] => {
const { removeItem } = useContext(ItemContext);
return removeItem;
};

View File

@ -1,3 +1,2 @@
import { UtopiaMap, Item, Tag } from './Components/Map/UtopiaMap' export { UtopiaMap, Item, Tag, API } from './Components/Map/index'
import { Layer } from './Components/Map/Layer'; export { Layer } from './Components/Map/Layer';
export { UtopiaMap, Item, Tag, Layer };

View File

@ -1,27 +1,35 @@
export interface Item { export class Item {
id: number, id: number;
date_created?: string, date_created?: string;
date_updated?: string | null, date_updated?: string | null;
name: string, name: string;
text: string, text: string;
position: Geometry, position: Geometry;
start?: string, start?: string;
end?: string, end?: string;
tags?: number[], tags?: number[];
[key: string]: any [key: string]: any;
constructor(id:number,name:string,text:string,position:Geometry){
this.id = id;
this.name = name;
this.text = text;
this.position = position;
}
} }
export interface Geometry { export class Geometry {
type: string; type: string;
coordinates: number[]; coordinates: number[];
constructor(lng: number, lat: number) {
this.coordinates = [lng,lat];
this.type = "Point";
}
} }
export interface Tag { export interface Tag {
color: string; color: string;
id: number; id: number;
name: string; name: string;
} }
@ -32,4 +40,9 @@ export interface Layer {
menuText: string, menuText: string,
markerIcon: string, markerIcon: string,
markerShape: string markerShape: string
}
export interface API {
getAll(): Promise<void>,
add(item : Item): Promise<void>,
} }