mirror of
https://github.com/utopia-os/utopia-ui.git
synced 2025-12-13 07:46:10 +00:00
basic useItems hook
This commit is contained in:
parent
654d066587
commit
aef9f56148
5
LICENSE.md
Normal file
5
LICENSE.md
Normal 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.
|
||||
@ -14,7 +14,7 @@
|
||||
],
|
||||
"keywords": [],
|
||||
"author": "Anton Tranelis",
|
||||
"license": "ISC",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/leaflet": "^1.7.11",
|
||||
"@types/react": "^18.0.14",
|
||||
|
||||
@ -3,12 +3,13 @@ import { Marker } from 'react-leaflet'
|
||||
import { Item, Tag } from '../../types'
|
||||
import MarkerIconFactory from '../../Utils/MarkerIconFactory'
|
||||
import { Popup } from './Popup'
|
||||
import { useItems } from './useItems'
|
||||
|
||||
|
||||
export interface LayerProps {
|
||||
data: Item[],
|
||||
children?: React.ReactNode
|
||||
name : string,
|
||||
children?: React.ReactNode
|
||||
name: string,
|
||||
menuIcon: string,
|
||||
menuColor: string,
|
||||
menuText: string,
|
||||
@ -18,42 +19,43 @@ export interface LayerProps {
|
||||
tags?: Tag[]
|
||||
}
|
||||
|
||||
|
||||
|
||||
export const Layer = (props: LayerProps) => {
|
||||
// create a JS-Map with all Tags
|
||||
let tagMap = new Map(props.tags?.map(key => [key.id, key]));
|
||||
// create a JS-Map with all Tags
|
||||
let tagMap = new Map(props.tags?.map(key => [key.id, key]));
|
||||
|
||||
// returns all tags for passed item
|
||||
const getTags = (item: Item) => {
|
||||
let tags: Tag[] = [];
|
||||
item.tags && item.tags.forEach(element => {
|
||||
if (tagMap.has(element)) { tags.push(tagMap.get(element)!); };
|
||||
});
|
||||
return tags;
|
||||
};
|
||||
// returns all tags for passed item
|
||||
const getTags = (item: Item) => {
|
||||
let tags: Tag[] = [];
|
||||
item.tags && item.tags.forEach(element => {
|
||||
if (tagMap.has(element)) { tags.push(tagMap.get(element)!); };
|
||||
});
|
||||
return tags;
|
||||
};
|
||||
|
||||
let items = useItems();
|
||||
|
||||
return (
|
||||
<>
|
||||
{
|
||||
props.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>
|
||||
);
|
||||
})
|
||||
}
|
||||
{props.children}
|
||||
{
|
||||
items.map((place: Item) => {
|
||||
console.log("Items check in Layer: " + items);
|
||||
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}
|
||||
</>
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@ -1,22 +1,39 @@
|
||||
import * as React from 'react'
|
||||
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 {
|
||||
position: LatLng,
|
||||
itemType: string,
|
||||
layer: string,
|
||||
onSubmit: (name: string, text: string, position : LatLng, layer : string) => void
|
||||
}
|
||||
|
||||
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 (
|
||||
<LeafletPopup maxHeight={300} minWidth={275} maxWidth={275} autoPanPadding={[20, 5]}
|
||||
position={props.position}>
|
||||
<div className='flex justify-center'><b className="text-xl font-bold">New {props.itemType}</b></div>
|
||||
<input type="text" placeholder="Name" className="input input-bordered w-full max-w-xs mt-5" />
|
||||
<textarea className="textarea textarea-bordered w-full mt-5" placeholder="Text"></textarea>
|
||||
<div className='flex justify-center'><button className="btn mt-5 place-self-center">Save</button></div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='flex justify-center'><b className="text-xl font-bold">New {props.layer}</b></div>
|
||||
<input type="text" placeholder="Name" className="input input-bordered w-full max-w-xs mt-5" value={name} onChange={e => setName(e.target.value)} />
|
||||
<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>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,14 +1,15 @@
|
||||
import { TileLayer, MapContainer, useMapEvents } from "react-leaflet";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
import * as React from "react";
|
||||
import { Item, Tag } from "../../types"
|
||||
import { Item, Tag, API, Geometry } from "../../types"
|
||||
import "../../index.css"
|
||||
import { LatLng } from "leaflet";
|
||||
import MarkerClusterGroup from 'react-leaflet-cluster'
|
||||
import AddButton from "./AddButton";
|
||||
import { Layer, LayerProps } from "./Layer";
|
||||
import { useState } from "react";
|
||||
import { LayerProps } from "./Layer";
|
||||
import { useCallback, useState } from "react";
|
||||
import NewItemPopup, { NewItemPopupProps } from "./NewItemPopup";
|
||||
import { ItemsProvider, useAddItem, useItems } from "./useItems";
|
||||
|
||||
export interface UtopiaMapProps {
|
||||
height?: string,
|
||||
@ -18,9 +19,11 @@ export interface UtopiaMapProps {
|
||||
places?: Item[],
|
||||
events?: Item[],
|
||||
tags?: Tag[],
|
||||
children?: React.ReactNode
|
||||
children?: React.ReactNode,
|
||||
api?: API
|
||||
}
|
||||
|
||||
|
||||
export interface MapEventListenerProps {
|
||||
selectMode: string | null,
|
||||
setSelectMode: React.Dispatch<React.SetStateAction<any>>,
|
||||
@ -32,9 +35,9 @@ function MapEventListener(props: MapEventListenerProps) {
|
||||
click: (e) => {
|
||||
console.log(e.latlng.lat + ',' + e.latlng.lng);
|
||||
console.log(props.selectMode);
|
||||
|
||||
|
||||
if (props.selectMode != null) {
|
||||
props.setNewItemPopup({ itemType: props.selectMode, position: e.latlng })
|
||||
props.setNewItemPopup({ layer: props.selectMode, position: e.latlng })
|
||||
props.setSelectMode(null)
|
||||
}
|
||||
},
|
||||
@ -45,7 +48,7 @@ function MapEventListener(props: MapEventListenerProps) {
|
||||
return null
|
||||
}
|
||||
|
||||
function UtopiaMap(this: any, props: UtopiaMapProps) {
|
||||
function UtopiaMap(props: UtopiaMapProps) {
|
||||
// init / set default values
|
||||
let center: LatLng = new LatLng(50.6, 9.5);
|
||||
if (props.center)
|
||||
@ -60,51 +63,66 @@ function UtopiaMap(this: any, props: UtopiaMapProps) {
|
||||
if (props.width)
|
||||
width = props.width;
|
||||
|
||||
|
||||
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 layers: LayerProps[] = [];
|
||||
// put places / events if provided as props
|
||||
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 });
|
||||
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 });
|
||||
const handleSubmit = useCallback((name: string, text: string, position : LatLng, layer : string) => {
|
||||
addItem(new Item(123,name,text,new Geometry(position.lng,position.lat)));
|
||||
console.log(layer);
|
||||
console.log("Items check in Callback: " + items);
|
||||
|
||||
}, [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 (
|
||||
<ItemsProvider initialItems={initial}>
|
||||
<div className={(selectMode != null ? "crosshair-cursor-enabled" : undefined)}>
|
||||
<MapContainer style={{ height: height, width: width }} center={center} zoom={zoom}>
|
||||
<TileLayer
|
||||
attribution='© <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}>
|
||||
{layers &&
|
||||
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)}
|
||||
{props.children}
|
||||
</MarkerClusterGroup>
|
||||
<MapEventListener setSelectMode={setSelectMode} selectMode={selectMode} setNewItemPopup={setNewItemPopup} />
|
||||
{newItemPopup &&
|
||||
<NewItemPopup position={newItemPopup.position} itemType={newItemPopup.itemType}/>
|
||||
<NewItemPopup position={newItemPopup.position} layer={newItemPopup.layer} onSubmit={handleSubmit} />
|
||||
}
|
||||
</MapContainer>
|
||||
<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>
|
||||
</ItemsProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export { UtopiaMap, Item, Tag };
|
||||
export { UtopiaMap, Item, Tag, API };
|
||||
|
||||
|
||||
1
src/Components/Map/index.tsx
Normal file
1
src/Components/Map/index.tsx
Normal file
@ -0,0 +1 @@
|
||||
export { UtopiaMap, Item, Tag, API } from './UtopiaMap'
|
||||
73
src/Components/Map/useItems.tsx
Normal file
73
src/Components/Map/useItems.tsx
Normal 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;
|
||||
};
|
||||
@ -1,3 +1,2 @@
|
||||
import { UtopiaMap, Item, Tag } from './Components/Map/UtopiaMap'
|
||||
import { Layer } from './Components/Map/Layer';
|
||||
export { UtopiaMap, Item, Tag, Layer };
|
||||
export { UtopiaMap, Item, Tag, API } from './Components/Map/index'
|
||||
export { Layer } from './Components/Map/Layer';
|
||||
41
src/types.ts
41
src/types.ts
@ -1,27 +1,35 @@
|
||||
export interface Item {
|
||||
id: number,
|
||||
date_created?: string,
|
||||
date_updated?: string | null,
|
||||
name: string,
|
||||
text: string,
|
||||
position: Geometry,
|
||||
start?: string,
|
||||
end?: string,
|
||||
tags?: number[],
|
||||
[key: string]: any
|
||||
export class Item {
|
||||
id: number;
|
||||
date_created?: string;
|
||||
date_updated?: string | null;
|
||||
name: string;
|
||||
text: string;
|
||||
position: Geometry;
|
||||
start?: string;
|
||||
end?: string;
|
||||
tags?: number[];
|
||||
[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;
|
||||
coordinates: number[];
|
||||
constructor(lng: number, lat: number) {
|
||||
this.coordinates = [lng,lat];
|
||||
this.type = "Point";
|
||||
}
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
|
||||
color: string;
|
||||
id: number;
|
||||
name: string;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -32,4 +40,9 @@ export interface Layer {
|
||||
menuText: string,
|
||||
markerIcon: string,
|
||||
markerShape: string
|
||||
}
|
||||
|
||||
export interface API {
|
||||
getAll(): Promise<void>,
|
||||
add(item : Item): Promise<void>,
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user