Memoising `<TileSet>`

This commit is contained in:
Eric van der Vlist 2022-10-30 20:23:12 +01:00
parent edca3f0d1b
commit 7322e5f5c4
1 changed files with 47 additions and 46 deletions

View File

@ -1,5 +1,5 @@
import react, { } from 'react'; import react, { memo } from 'react';
import { range } from 'lodash'; import { isEqual, range } from 'lodash';
import { Rectangle, TileKeyObject } from './types'; import { Rectangle, TileKeyObject } from './types';
import tileUri from './uris'; import tileUri from './uris';
@ -51,52 +51,53 @@ export interface TileSetProperties {
* *
* *
*/ */
export const TileSet: react.FC<TileSetProperties> = ( export const TileSet: react.FC<TileSetProperties> = memo(
props: TileSetProperties (props: TileSetProperties) => {
) => { // console.log(`Rendering TiledLayer: ${JSON.stringify(props)}`);
// console.log(`Rendering TiledLayer: ${JSON.stringify(props)}`);
const key = tileUri({ const key = tileUri({
provider: props.keyObject.provider, provider: props.keyObject.provider,
zoomLevel: props.keyObject.zoomLevel, zoomLevel: props.keyObject.zoomLevel,
}); });
const tiles: any = globalThis.cacheForTileSet.get(key) ?? new Map(); const tiles: any = globalThis.cacheForTileSet.get(key) ?? new Map();
if (props.viewPort !== undefined) { if (props.viewPort !== undefined) {
range(props.viewPort.topLeft.y, props.viewPort.bottomRight.y + 1).forEach( range(props.viewPort.topLeft.y, props.viewPort.bottomRight.y + 1).forEach(
(row) => { (row) => {
range( range(
props.viewPort!.topLeft.x, props.viewPort!.topLeft.x,
props.viewPort!.bottomRight.x + 1 props.viewPort!.bottomRight.x + 1
).forEach((col) => { ).forEach((col) => {
const keyObject = { const keyObject = {
provider: props.keyObject.provider, provider: props.keyObject.provider,
zoomLevel: props.keyObject.zoomLevel, zoomLevel: props.keyObject.zoomLevel,
x: props.keyObject.x + col, x: props.keyObject.x + col,
y: props.keyObject.y + row, y: props.keyObject.y + row,
}; };
const key = tileUri(keyObject); const key = tileUri(keyObject);
if (!tiles.has(key)) { if (!tiles.has(key)) {
tiles.set( tiles.set(
key, key,
<Tile <Tile
key={key} key={key}
keyObject={{ keyObject={{
provider: props.keyObject.provider, provider: props.keyObject.provider,
zoomLevel: props.keyObject.zoomLevel, zoomLevel: props.keyObject.zoomLevel,
x: col, x: col,
y: row, y: row,
}} }}
/> />
); );
} }
}); });
} }
); );
globalThis.cacheForTileSet.set(key, tiles); globalThis.cacheForTileSet.set(key, tiles);
} }
return <>{Array.from(tiles.values())}</>; return <>{Array.from(tiles.values())}</>;
}; },
isEqual
);
export default TileSet; export default TileSet;