state management

This commit is contained in:
AT 2022-08-10 12:44:27 +02:00
parent b532eca956
commit 3f540ff2d4
10 changed files with 223 additions and 110 deletions

View File

@ -3,13 +3,15 @@ import { Marker } from 'react-leaflet'
import { Item, Tag, Layer as LayerProps } from '../../types'
import MarkerIconFactory from '../../Utils/MarkerIconFactory'
import { Popup } from './Subcomponents/Popup'
import { useLayers, useAddLayer } from './hooks/useLayers'
import { useTags } from './hooks/useTags'
import { useAddItem, useItems } from './hooks/useItems'
import { useEffect } from 'react'
import { useAddLayer } from './hooks/useLayers'
export const Layer = (props: LayerProps) => {
const tags = useTags();
const tags = useTags();
// create a JS-Map with all Tags
let tagMap = new Map(tags?.map(key => [key.id, key]));
@ -22,28 +24,36 @@ export const Layer = (props: LayerProps) => {
return tags;
};
const items = useItems();
const addItem = useAddItem()
const addLayer = useAddLayer();
useEffect(() => {
props.data.map(item => {
item.layer = props;
addItem(item);
})
}, [])
addLayer(props);
const layers = useLayers();
return (
<>
{layers.get(props.name)?.data?.map((place: Item) => {
let tags = getTags(place);
let color1 = "#666";
let color2 = "RGBA(35, 31, 32, 0.2)";
if (tags[0]) {
color1 = tags[0].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]]}>
<Popup item={place} tags={tags} />
</Marker>
);
})
{items.filter(item => item.layer?.name === props.name)?.map((place: Item) => {
let tags = getTags(place);
let color1 = "#666";
let color2 = "RGBA(35, 31, 32, 0.2)";
if (tags[0]) {
color1 = tags[0].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]]}>
<Popup item={place} tags={tags} />
</Marker>
);
})
}
{props.children}
</>

View File

@ -6,6 +6,8 @@ import { useLayers } from '../hooks/useLayers'
export default function AddButton({setSelectMode} : {setSelectMode: React.Dispatch<React.SetStateAction<any>>}) {
const layers = useLayers();
console.log(layers);
console.log(useLayers());
return (
<div className="dropdown dropdown-top dropdown-end dropdown-hover z-500 absolute right-5 bottom-5" >
@ -16,9 +18,8 @@ export default function AddButton({setSelectMode} : {setSelectMode: React.Dispat
C15.952,9,16,9.447,16,10z" />
</svg>
</button>
{layers &&
<ul tabIndex={0} className="dropdown-content pr-2 mb-0 list-none">
{Array.from(layers.values()).map((layer) => (
{layers.map((layer) => (
<li key={layer.name} >
<a>
<div className="tooltip tooltip-left" data-tip={layer.menuText}>
@ -33,7 +34,7 @@ export default function AddButton({setSelectMode} : {setSelectMode: React.Dispat
</li>
))}
</ul>
}
</div>
)
}

View File

@ -2,7 +2,7 @@ import * as React from 'react'
import { LatLng } from 'leaflet'
import { Popup as LeafletPopup, useMap } from 'react-leaflet'
import { useState } from 'react'
import { useAddItem } from '../hooks/useLayers'
import { useAddItem } from '../hooks/useItems'
import { Geometry, Layer, Item} from '../../../types'
export interface NewItemPopupProps {
@ -22,7 +22,7 @@ export default function NewItemPopup(props: NewItemPopupProps) {
evt.preventDefault()
console.log("New Item Popup is adding Item ...");
addItem(new Item(Math.floor(Math.random() * 1000) + 200, name, text, new Geometry(props.position.lng, props.position.lat)), props.layer)
addItem(new Item(Math.floor(Math.random() * 1000) + 200, name, text, new Geometry(props.position.lng, props.position.lat), props.layer))
map.closePopup();
props.setNewItemPopup(null);

View File

@ -1,20 +1,59 @@
import * as React from 'react'
import { Popup as LeafletPopup} from 'react-leaflet'
import { Popup as LeafletPopup, useMap } from 'react-leaflet'
import { Item, Tag } from '../../../types'
import { replaceURLs } from '../../../Utils/ReplaceURLs'
import { useRemoveItem } from '../hooks/useItems'
export interface UtopiaPopupProps {
item: Item,
tags: Tag[]
tags: Tag[],
}
const Popup = (props: UtopiaPopupProps) => {
const item: Item = props.item;
const tags: Tag[] = props.tags;
const removeItem = useRemoveItem();
const map = useMap();
const removeItemFromMap = (event: React.MouseEvent<HTMLElement>) => {
removeItem(item)
event.stopPropagation()
map.closePopup();
}
return (
<LeafletPopup maxHeight={300} minWidth={275} maxWidth={275} autoPanPadding={[20, 5]}>
<b className="text-xl font-bold">{item.name}</b>
<div className='flex flex-row'>
<div className='basis-5/6'>
<b className="text-xl font-bold">{item.name}</b>
</div>
<div className='basis-1/6'>
<div className="dropdown dropdown-right">
<label tabIndex={0} className="btn m-1 bg-white hover:bg-white text-gray-500 hover:text-gray-700 leading-3">
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
</svg>
</label>
<ul tabIndex={0} className="dropdown-content menu p-2 shadow bg-base-100 rounded-box">
<li>
<a className='bg-white hover:bg-white text-gray-500 hover:text-gray-700'>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
</svg>
</a>
</li>
<li>
<a className='bg-white hover:bg-white text-gray-500 hover:text-gray-700' onClick={removeItemFromMap }>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clipRule="evenodd" />
</svg>
</a>
</li>
</ul>
</div>
</div>
</div>
{item.start && item.end &&
<div className="flex flex-row">
<div className="basis-2/5">
@ -48,6 +87,6 @@ const Popup = (props: UtopiaPopupProps) => {
)
}
export {Popup};
export { Popup };

View File

@ -5,11 +5,8 @@ import { useAddTag } from './hooks/useTags'
export function Tags({data} : {data: Tag[]}) {
const addTag = useAddTag();
useEffect(() => {
data.map(tag => {
console.log("Tag added: " + tag.name);
addTag(tag)
})
}, [])

View File

@ -8,10 +8,9 @@ import MarkerClusterGroup from 'react-leaflet-cluster'
import AddButton from "./Subcomponents/AddButton";
import { useState } from "react";
import NewItemPopup, { NewItemPopupProps } from "./Subcomponents/NewItemPopup";
import { LayersProvider } from "./hooks/useLayers";
import { ItemsProvider } from "./hooks/useItems";
import { TagsProvider } from "./hooks/useTags";
import { LayersProvider } from "./hooks/useLayers";
export interface MapEventListenerProps {
selectMode: Layer | null,
@ -46,35 +45,38 @@ function UtopiaMap({
const [newItemPopup, setNewItemPopup] = useState<NewItemPopupProps | null>(null);
return (
<TagsProvider initialTags={[]}>
<LayersProvider initialLayers={new Map()}>
<div className={(selectMode != null ? "crosshair-cursor-enabled" : undefined)}>
<MapContainer style={{ height: height, width: width }} center={center} zoom={zoom}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<MarkerClusterGroup showCoverageOnHover chunkedLoading maxClusterRadius={50}>
{children}
</MarkerClusterGroup>
<MapEventListener setSelectMode={setSelectMode} selectMode={selectMode} setNewItemPopup={setNewItemPopup} />
{newItemPopup &&
<NewItemPopup position={newItemPopup.position} layer={newItemPopup.layer} setNewItemPopup={setNewItemPopup} />
}
<AddButton setSelectMode={setSelectMode}></AddButton>
</MapContainer>
{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.name} position!</span>
<LayersProvider initialLayers={[]}>
<TagsProvider initialTags={[]}>
<ItemsProvider initialItems={[]}>
<div className={(selectMode != null ? "crosshair-cursor-enabled" : undefined)}>
<MapContainer style={{ height: height, width: width }} center={center} zoom={zoom}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<MarkerClusterGroup showCoverageOnHover chunkedLoading maxClusterRadius={50}>
{children}
</MarkerClusterGroup>
<MapEventListener setSelectMode={setSelectMode} selectMode={selectMode} setNewItemPopup={setNewItemPopup} />
{newItemPopup &&
<NewItemPopup position={newItemPopup.position} layer={newItemPopup.layer} setNewItemPopup={setNewItemPopup} />
}
<AddButton setSelectMode={setSelectMode}></AddButton>
</MapContainer>
{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.name} position!</span>
</div>
</div>
</div>
</div>
}
}
</div>
</ItemsProvider>
</TagsProvider>
</LayersProvider>
</div>
</LayersProvider>
</TagsProvider>
);
}

View File

@ -70,7 +70,24 @@ export const events : Item[] = [
"end": "2022-10-08T12:00:00",
"tags": [5,6,11],
}
},
{
"id": 247,
"name": "anderes Event",
"text": "Zu den Vollmonden vom März bis Oktober treffen sich traditionell Menschen zum gemeinsamen Musizieren, Tanzen, Spielen, Grillen und Entspannen am Gerloser Häuschen im Niesiger Wald.\r\n\r\nUhrzeit: immer ab 17 Uhr\r\n\r\nhttps://trommeln-fulda.de/vollmondtrommeln/",
"position": {
"type": "Point",
"coordinates": [
9.67,
50.589
]
},
"start": "2022-03-18T12:00:00",
"end": "2022-10-08T12:00:00",
"tags": [5,6,11],
}
];
export const places : Item[] = [

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"; item: Item };
type UseItemManagerResult = ReturnType<typeof useItemsManager>;
const ItemContext = createContext<UseItemManagerResult>({
items: [],
addItem: () => {},
removeItem: () => {}
});
function useItemsManager (initialItems: Item[]): {
items: Item[];
addItem: (item: Item) => void;
removeItem: (item: Item) => void;
} {
const [items, dispatch] = useReducer((state: Item[], action: ActionType) => {
switch (action.type) {
case "ADD":
return [
...state,
action.item,
];
case "REMOVE":
return state.filter(item => item !== action.item);
default:
throw new Error();
}
}, initialItems);
const addItem = useCallback((item: Item) => {
dispatch({
type: "ADD",
item,
});
}, []);
const removeItem = useCallback((item: Item) => {
dispatch({
type: "REMOVE",
item,
});
}, []);
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

@ -4,37 +4,33 @@ import { Item, Layer } from "../../../types";
type ActionType =
| { type: "ADD LAYER"; layer: Layer }
| { type: "ADD ITEM"; item: Item; layer: Layer }
| { type: "REMOVE ITEM"; id: number; layer: Layer };
| { type: "ADD ITEM"; item: Item; layer: Layer };
type UseItemManagerResult = ReturnType<typeof useLayerManager>;
const LayerContext = createContext<UseItemManagerResult>({
layers: new Map([]),
layers: [],
addLayer: () => { },
addItem: () => { },
removeItem: () => { }
});
function useLayerManager(initialLayers: Map<string, Layer>): {
layers: Map<string, Layer>;
function useLayerManager(initialLayers: Layer[]): {
layers: Layer[];
addLayer: (layer: Layer) => void;
addItem: (item: Item, layer: Layer) => void;
removeItem: (id: number, layer: Layer) => void;
} {
const [layers, dispatch] = useReducer((state: Map<string, Layer>, action: ActionType) => {
const [layers, dispatch] = useReducer((state: Layer[], action: ActionType) => {
switch (action.type) {
case "ADD LAYER":
{
return state.set(action.layer.name, action.layer);
if (!state.includes(action.layer))
state.push(action.layer);
return state;
}
case "ADD ITEM":
{
if(!state.get(action.layer.name)?.data?.includes(action.item))
state.get(action.layer.name)?.data?.push(action.item);
if(!state.find(layer => layer.name === action.layer.name)?.data.find(item => item.id === action.item.id))
state.find(layer => layer.name === action.layer.name)?.data.push(action.item)
return state;
}
case "REMOVE ITEM":
{ return state; }
default:
throw new Error();
}
@ -47,33 +43,18 @@ function useLayerManager(initialLayers: Map<string, Layer>): {
});
}, []);
const addItem = useCallback((item: Item, layer: Layer) => {
dispatch({
type: "ADD ITEM",
item,
layer
});
}, []);
const removeItem = useCallback((id: number, layer: Layer) => {
dispatch({
type: "REMOVE ITEM",
id,
layer
});
}, []);
return { layers, addLayer, addItem, removeItem };
return { layers, addLayer};
}
export const LayersProvider: React.FunctionComponent<{
initialLayers: Map<string, Layer>, children?: React.ReactNode
initialLayers: Layer[], children?: React.ReactNode
}> = ({ initialLayers, children }) => (
<LayerContext.Provider value={useLayerManager(initialLayers)}>
{children}
</LayerContext.Provider>
);
export const useLayers = (): Map<string, Layer> => {
export const useLayers = (): Layer[] => {
const { layers } = useContext(LayerContext);
return layers;
};
@ -82,13 +63,3 @@ export const useAddLayer = (): UseItemManagerResult["addLayer"] => {
const { addLayer } = useContext(LayerContext);
return addLayer;
};
export const useAddItem = (): UseItemManagerResult["addItem"] => {
const { addItem } = useContext(LayerContext);
return addItem;
};
export const useRemoveItem = (): UseItemManagerResult["removeItem"] => {
const { removeItem } = useContext(LayerContext);
return removeItem;
};

View File

@ -11,7 +11,7 @@ export interface UtopiaMap {
}
export interface Layer {
data?: Item[],
data: Item[],
children?: React.ReactNode
name: string,
menuIcon: string,
@ -20,7 +20,7 @@ export interface Layer {
markerIcon: string,
markerShape: string,
markerDefaultColor: string,
tags?: Tag[]
tags?: Tag[],
}
export class Item {
@ -30,15 +30,16 @@ export class Item {
name: string;
text: string;
position: Geometry;
layer?: Layer;
start?: string;
end?: string;
tags?: number[];
[key: string]: any;
constructor(id:number,name:string,text:string,position:Geometry){
constructor(id:number,name:string,text:string,position:Geometry, layer: Layer){
this.id = id;
this.name = name;
this.text = text;
this.position = position;
this.layer = layer;
}
}
@ -60,4 +61,6 @@ export interface Tag {
export interface API {
getAll(): Promise<void>,
add(item : Item): Promise<void>,
update(item : Item): Promise<void>,
remove(id : number): Promise<void>,
}