Skip to content

Commit

Permalink
feat(source): add Source Component
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxingkang committed Aug 31, 2022
1 parent 2c8673f commit 687e6be
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './map';
export * from './marker';
export * from './source';
export * from './hooks/useMap';
11 changes: 11 additions & 0 deletions src/source/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { GeoJSONSource } from 'mapbox-gl';

export const setterMap = {
data(data: any, source: GeoJSONSource) {
if (!source) return;

source.setData(data);
},
};

export const converterMap = {};
2 changes: 2 additions & 0 deletions src/source/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { Source } from './source';
export type { SourceProps } from './types';
42 changes: 42 additions & 0 deletions src/source/source.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { forwardRef, useEffect, useState, useImperativeHandle } from 'react';

import { useMap } from '@/hooks/useMap';
import { useReact } from '@/hooks/useReact';

import { setterMap, converterMap } from './config';

import type { FC } from 'react';
import type { GeoJSONSource } from 'mapbox-gl';
import type { SourceProps, EventMapping } from './types';

export const Source: FC<SourceProps> = forwardRef<GeoJSONSource, SourceProps>((props, ref) => {
const { id, ...rest } = props;
const map = useMap();
const [source, setSource] = useState<GeoJSONSource>();

useImperativeHandle(ref, () => source as GeoJSONSource, [source]);

const { onInstanceCreated } = useReact<SourceProps, any, EventMapping>(props, {
ins: source,
events: {},
setterMap,
converterMap,
unmount: () => {
map && map.removeSource(id);
},
});

useEffect(() => {
if (map) {
map.addSource(props.id, {
...rest,
type: 'geojson',
});

setSource(map.getSource(id) as GeoJSONSource);
onInstanceCreated();
}
}, [map]);

return null;
});
9 changes: 9 additions & 0 deletions src/source/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { GeoJSONSourceOptions } from 'mapbox-gl';

export type SourceEvents = {};

export type EventMapping = { [T in keyof SourceEvents]: string };

export interface SourceProps extends GeoJSONSourceOptions {
id: string;
}

0 comments on commit 687e6be

Please sign in to comment.