Starting again with what has been developed as sandbox/map.

This commit is contained in:
Eric van der Vlist 2022-09-11 20:01:12 +02:00
parent f81c436f7d
commit 716d05fb3e
17 changed files with 807 additions and 268 deletions

View File

@ -19,18 +19,13 @@ import '@ionic/react/css/display.css';
/* Theme variables */
import './theme/variables.css';
/* Components */
import Map from './components/map';
import React from 'react';
setupIonicReact();
const App: React.FC = () => (
<IonApp>
<React.StrictMode>
<Map />
</React.StrictMode>
<Map />
</IonApp>
);

View File

@ -0,0 +1,135 @@
import react, { useCallback, useState } from 'react';
import _ from 'lodash';
import { Transformation } from './viewport';
interface DoubleTouchHandlerProps {
applyTransformations: (transformations: Transformation[]) => void;
children: any;
}
const DoubleTouchHandler: react.FC<DoubleTouchHandlerProps> = (
props: DoubleTouchHandlerProps
) => {
const initialTouchState = {
state: 'up',
touches: [
{ x: -1, y: -1 },
{ x: -1, y: -1 },
],
distance: -1,
initialZoom: 1,
};
const [touchState, setTouchState] = useState(initialTouchState);
console.log('DoubleTouchHandler, touchState: ' + JSON.stringify(touchState));
const genericHandler = (event: any) => {
console.log('Log - Event: ' + event.type);
if (event.type.startsWith('touch')) {
if (event.touches.length > 1) {
console.log(
`${event.touches.length} touches, (${event.touches[0].pageX}, ${event.touches[0].pageY}), (${event.touches[1].pageX}, ${event.touches[1].pageY})`
);
}
console.log('touchState: ' + JSON.stringify(touchState));
return;
}
};
const touchCancelHandler = (event: any) => {
genericHandler(event);
throtteledTouchMoveHandler.cancel();
setTouchState(initialTouchState);
};
const touchStartHandler = (event: any) => {
genericHandler(event);
if (event.touches.length === 2) {
setTouchState({
state: 'double',
touches: [
{ x: event.touches[0].pageX, y: event.touches[0].pageY },
{ x: event.touches[1].pageX, y: event.touches[1].pageY },
],
distance: Math.sqrt(
(event.touches[0].pageX - event.touches[1].pageX) ** 2 +
(event.touches[0].pageY - event.touches[1].pageY) ** 2
),
initialZoom: 1,
});
}
};
const touchEndHandler = (event: any) => {
genericHandler(event);
setTouchState(initialTouchState);
throtteledTouchMoveHandler.cancel();
};
const touchMoveHandler = (event: any) => {
if (touchState.state === 'double') {
if (event.touches.length === 2) {
genericHandler(event);
const newDistance = Math.sqrt(
(event.touches[0].pageX - event.touches[1].pageX) ** 2 +
(event.touches[0].pageY - event.touches[1].pageY) ** 2
);
const factor = newDistance / touchState.distance;
console.log(`+++++++++ ZOOM Factor is ${factor} ++++++++++`);
setTouchState({
state: 'double',
touches: [
{ x: event.touches[0].pageX, y: event.touches[0].pageY },
{ x: event.touches[1].pageX, y: event.touches[1].pageY },
],
distance: touchState.distance,
initialZoom: 1,
});
const previousCenter = {
x: (touchState.touches[0].x + touchState.touches[1].x) / 2,
y: (touchState.touches[0].y + touchState.touches[1].y) / 2,
};
const currentCenter = {
x: (event.touches[0].pageX + event.touches[1].pageX) / 2,
y: (event.touches[0].pageY + event.touches[1].pageY) / 2,
};
props.applyTransformations([
{
scale: {
factor: factor,
center: currentCenter,
},
},
{
translate: {
x: currentCenter.x - previousCenter.x,
y: currentCenter.y - previousCenter.y,
},
},
]);
}
}
};
const throtteledTouchMoveHandler = useCallback(
_.throttle(touchMoveHandler, 100),
[touchState.state]
);
return (
<div
className='viewport double-touch-handler'
onTouchStart={touchStartHandler}
onTouchMove={throtteledTouchMoveHandler}
onTouchEnd={touchEndHandler}
onTouchCancel={touchCancelHandler}
>
{props.children}
</div>
);
};
export default DoubleTouchHandler;

26
src/components/layer.tsx Normal file
View File

@ -0,0 +1,26 @@
import react from 'react';
import { ViewportState } from './viewport';
import '../theme/layer.css';
const Layer: react.FC<{
viewportState: ViewportState;
children?: JSX.Element;
}> = (props: { viewportState: ViewportState; children?: JSX.Element }) => {
const { children: children, ...argProps } = props;
console.log(`--- Rendering layer, props: ${JSON.stringify(argProps)} ---`);
return (
<div
className='background'
style={{
transform: `translate(${props.viewportState.translation.x}px, ${props.viewportState.translation.y}px) scale(${props.viewportState.scale})`,
}}
>
{props.children}
</div>
);
};
export default Layer;

View File

@ -1,179 +1,91 @@
import _, { round } from 'lodash';
import react, { useState, useEffect, useMemo, useRef } from 'react';
import Tile from './tile';
import '../theme/map.css';
export const tileSize = 256;
// cf https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#ECMAScript_(JavaScript/ActionScript,_etc.)
const lon2tile = (lon: number, zoom: number) => {
const real = ((lon + 180) / 360) * Math.pow(2, zoom);
const floor = Math.floor(real);
return [floor, real - floor];
};
const lat2tile = (lat: number, zoom: number) => {
const real =
((1 -
Math.log(
Math.tan((lat * Math.PI) / 180) + 1 / Math.cos((lat * Math.PI) / 180)
) /
Math.PI) /
2) *
Math.pow(2, zoom);
const floor = Math.floor(real);
return [floor, real - floor];
};
function tile2long(x: number, z: number) {
return (x / Math.pow(2, z)) * 360 - 180;
}
function tile2lat(y: number, z: number) {
var n = Math.PI - (2 * Math.PI * y) / Math.pow(2, z);
return (180 / Math.PI) * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
}
const Map: react.FC = () => {
console.log('Log - Rendering <Map />');
const initialCenter: [number, number] = [43.57029965, 3.94242897];
const initialZoom: number = 17;
const [center, setCenter] = useState(initialCenter);
const [zoom, setZoom] = useState(initialZoom);
const [dimensions, setDimensions] = useState({
height: window.innerHeight,
width: window.innerWidth,
});
const resizeHandler = () => {
setDimensions({
height: window.innerHeight,
width: window.innerWidth,
});
};
const debouncedResizeHandler = useMemo(
() => _.debounce(resizeHandler, 300),
[dimensions, zoom, center]
);
useEffect(() => {
window.addEventListener('resize', debouncedResizeHandler);
}, []);
const nbTilesY = _.ceil(dimensions.height / tileSize) + 4;
const nbTilesX = _.ceil(dimensions.width / tileSize) + 4;
const [tileCenterY, reminderY] = lat2tile(center[0], zoom);
const [tileCenterX, reminderX] = lon2tile(center[1], zoom);
const firstTileY = tileCenterY - _.round(nbTilesY / 2);
const firstTileX = tileCenterX - _.round(nbTilesX / 2);
const locationY = (tileCenterY + reminderY - firstTileY) * tileSize;
const locationX = (tileCenterX + reminderX - firstTileX) * tileSize;
const targetLocationY = dimensions.height / 2;
const targetLocationX = dimensions.width / 2;
const deltaY = -targetLocationY + locationY;
const deltaX = -targetLocationX + locationX;
const [delta, setDelta] = useState({ X: deltaX, Y: deltaY });
const genericHandler = (event: any) => {
console.log('Log - Event: ' + event.type);
};
const initialMouseState = {
down: false,
starting: { x: -1, y: -1 },
};
const mouseState = useRef(initialMouseState);
const mouseDownHandler = (event: any) => {
event.preventDefault();
mouseState.current = {
down: true,
starting: { x: event.pageX, y: event.pageY },
};
genericHandler(event);
};
const mouseUpHandler = (event: any) => {
event.preventDefault();
console.log('Log - Up, now do something ! ');
const newCenterY =
tileCenterY +
reminderY +
(deltaX + mouseState.current.starting.x - event.pageX);
const newCenterX =
tileCenterX +
reminderX +
(deltaY + mouseState.current.starting.y - event.pageY);
setCenter([tile2lat(newCenterY, zoom), tile2long(newCenterX, zoom)]);
mouseState.current = initialMouseState;
genericHandler(event);
};
const mouseMoveHandler = (event: any) => {
if (mouseState.current.down) {
event.preventDefault();
console.log('Log - Moving...' + event.pageX);
setDelta({
X: deltaX + mouseState.current.starting.x - event.pageX,
Y: deltaY + mouseState.current.starting.y - event.pageY,
});
genericHandler(event);
}
};
const debouncedMouseMoveHandler = useMemo(
() => _.throttle(mouseMoveHandler, 100),
[]
);
const pointerDownHandler = (event: any) => {
event.preventDefault();
console.log('PointerDown');
};
const pointerUpHandler = (event: any) => {
event.preventDefault();
console.log('PointerUp');
};
const pointerMoveHandler = (event: any) => {
event.preventDefault();
console.log('PointerMove');
};
import react from 'react';
import Viewport from './viewport';
const Map: react.FC<{}> = (props: {}) => {
return (
<div
className='tiles'
onMouseDown={mouseDownHandler}
onMouseMove={debouncedMouseMoveHandler}
onMouseUp={mouseUpHandler}
onTouchStart={genericHandler}
onTouchMove={genericHandler}
onTouchCancel={genericHandler}
onTouchEnd={genericHandler}
>
{_.range(nbTilesY).map((iy) => (
<div key={'y' + iy} className='tilesRow'>
{_.range(nbTilesX).map((ix) => (
<Tile
key={'x' + ix + 'y' + iy}
iy={iy}
ix={ix}
x={firstTileX + ix}
y={firstTileY + iy}
delta={delta}
zoom={zoom}
/>
))}
<Viewport>
<div>
<div style={{ height: '256px' }}>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11720/10052.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11721/10052.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11722/10052.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11723/10052.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
</div>
))}
</div>
<div style={{ height: '256px' }}>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11720/10053.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11721/10053.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11722/10053.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11723/10053.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
</div>
<div style={{ height: '256px' }}>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11720/10054.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11721/10054.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11722/10054.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
<img
alt=''
role='presentation'
src='https://tile.openstreetmap.org/14/11723/10054.png'
style={{ width: '256px', height: '256px', opacity: 1 }}
/>
</div>
</div>
</Viewport>
);
};

View File

@ -0,0 +1,107 @@
import react, { useCallback, useState } from 'react';
import _ from 'lodash';
import { Transformation } from './viewport';
interface MouseHandlerProps {
applyTransformations: (transformations: Transformation[]) => void;
children: any;
}
const MouseHandler: react.FC<MouseHandlerProps> = (
props: MouseHandlerProps
) => {
const initialMouseState = {
down: false,
starting: { x: -1, y: -1 },
};
const [mouseState, setMouseState] = useState(initialMouseState);
console.log('MouseHandler, mouseState: ' + JSON.stringify(mouseState));
const genericHandler = (event: any) => {
console.log('Log - Event: ' + event.type);
if (event.pageX !== undefined) {
console.log(`Mouse : ${event.pageX}, ${event.pageY}`);
console.log('mouseState: ' + JSON.stringify(mouseState));
return;
}
};
const mouseLeaveHandler = (event: any) => {
genericHandler(event);
throtteledMouseMoveHandler.cancel();
setMouseState(initialMouseState);
};
const mouseDownHandler = (event: any) => {
event.preventDefault();
genericHandler(event);
setMouseState({
down: true,
starting: { x: event.pageX, y: event.pageY },
});
};
const mouseUpHandler = (event: any) => {
genericHandler(event);
event.preventDefault();
setMouseState(initialMouseState);
};
const mouseMoveHandler = (event: any) => {
event.preventDefault();
if (mouseState.down) {
genericHandler(event);
props.applyTransformations([
{
translate: {
x: event.pageX - mouseState.starting.x,
y: event.pageY - mouseState.starting.y,
},
},
]);
setMouseState({
down: true,
starting: {
x: event.pageX,
y: event.pageY,
},
});
}
};
const throtteledMouseMoveHandler = useCallback(
_.throttle(mouseMoveHandler, 50),
[mouseState.down]
);
const doubleClickHandler = (event: any) => {
genericHandler(event);
props.applyTransformations([
{
scale: {
factor: 2,
center: { x: event.pageX, y: event.pageY },
},
},
]);
};
return (
<div
className='viewport mouse-handler'
onMouseDown={mouseDownHandler}
onMouseMove={throtteledMouseMoveHandler}
onMouseUp={mouseUpHandler}
onMouseLeave={mouseLeaveHandler}
onDoubleClick={doubleClickHandler}
>
{props.children}
</div>
);
};
export default MouseHandler;

View File

@ -0,0 +1,103 @@
import react, { useCallback, useState } from 'react';
import _ from 'lodash';
import { Transformation } from './viewport';
interface SingleTouchHandlerProps {
applyTransformations: (transformations: Transformation[]) => void;
children: any;
}
const SingleTouchHandler: react.FC<SingleTouchHandlerProps> = (
props: SingleTouchHandlerProps
) => {
const initialTouchState = {
state: 'up',
touch: { x: -1, y: -1 },
};
const [touchState, setTouchState] = useState(initialTouchState);
console.log('SingleTouchHandler, touchState: ' + JSON.stringify(touchState));
const genericHandler = (event: any) => {
console.log('Log - Event: ' + event.type);
if (event.type.startsWith('touch')) {
if (event.touches.length > 0) {
console.log(
`Touch1 : (${event.touches[0].pageX}, ${event.touches[0].pageY})`
);
}
console.log('touchState: ' + JSON.stringify(touchState));
return;
}
};
const touchCancelHandler = (event: any) => {
genericHandler(event);
throtteledTouchMoveHandler.cancel();
setTouchState(initialTouchState);
};
const touchStartHandler = (event: any) => {
genericHandler(event);
// event.preventDefault();
if (event.touches.length === 1) {
setTouchState({
state: 'pointer',
touch: { x: event.touches[0].pageX, y: event.touches[0].pageY },
});
}
};
const touchEndHandler = (event: any) => {
genericHandler(event);
// event.preventDefault();
setTouchState(initialTouchState);
throtteledTouchMoveHandler.cancel();
};
const touchMoveHandler = (event: any) => {
// event.preventDefault();
if (touchState.state === 'pointer') {
if (event.touches.length === 1) {
genericHandler(event);
props.applyTransformations([
{
translate: {
x: event.touches[0].pageX - touchState.touch.x,
y: event.touches[0].pageY - touchState.touch.y,
},
},
]);
setTouchState({
state: 'pointer',
touch: {
x: event.touches[0].pageX,
y: event.touches[0].pageY,
},
});
}
}
};
const throtteledTouchMoveHandler = useCallback(
_.throttle(touchMoveHandler, 100),
[touchState.state]
);
return (
<div
className='viewport single-touch-handler'
onTouchStart={touchStartHandler}
onTouchMove={throtteledTouchMoveHandler}
onTouchEnd={touchEndHandler}
onTouchCancel={touchCancelHandler}
>
{props.children}
</div>
);
};
export default SingleTouchHandler;

View File

@ -1,41 +0,0 @@
import React from 'react';
import { tileSize } from './map';
const tileProvider = (zoom: number, x: number, y: number) =>
'https://tile.openstreetmap.org/' + zoom + '/' + x + '/' + y + '.png';
const Tile: React.FC<{
ix: number;
iy: number;
x: number;
y: number;
delta: any;
zoom: number;
}> = (props: {
ix: number;
iy: number;
x: number;
y: number;
delta: any;
zoom: number;
}) => {
const style = {
width: tileSize + 'px',
height: tileSize + 'px',
transform:
'translate3d(' +
(props.ix * tileSize - props.delta.X) +
'px, ' +
(props.iy * tileSize - props.delta.Y) +
'px, 0px)',
};
return (
<img
src={tileProvider(props.zoom, props.x, props.y)}
style={style}
alt=''
/>
);
};
export default Tile;

100
src/components/viewport.tsx Normal file
View File

@ -0,0 +1,100 @@
import react, { useCallback, useState } from 'react';
import _, { constant } from 'lodash';
import MouseHandler from './mouse-handler';
import Layer from './layer';
import '../theme/viewport.css';
import SingleTouchHandler from './single-touch-handler';
import DoubleTouchHandler from './double-touch-handler';
export interface Point {
x: number;
y: number;
}
export interface Translation {
translate: Point;
}
export interface Scale {
scale: {
center: Point;
factor: number;
};
}
export type Transformation = Translation | Scale;
// const transform1: Transformation = { translate: { x: 0, y: 1 } };
// const transform2: Transformation = {
// scale: { center: { x: 10, y: 20 }, factor: 2 },
// };
interface ViewportProps {
children: any;
}
export interface ViewportState {
scale: number;
translation: Point;
}
const Viewport: react.FC<ViewportProps> = (props: ViewportProps) => {
//console.log(`--- Rendering viewport, props: ${JSON.stringify(props)} ---`);
const initialState: ViewportState = { scale: 1, translation: { x: 0, y: 0 } };
const [state, setState] = useState(initialState);
const genericHandler = (event: any) => {
console.log('Log - Event: ' + event.type);
return;
};
const applyTransformations = (transformations: Transformation[]) => {
const newState = transformations.reduce(
(previousState: ViewportState, transformation): ViewportState => {
if ('scale' in transformation) {
return {
scale: previousState.scale * transformation.scale.factor,
translation: {
x:
previousState.translation.x +
(previousState.translation.x - transformation.scale.center.x) *
(transformation.scale.factor - 1),
y:
previousState.translation.y +
(previousState.translation.y - transformation.scale.center.y) *
(transformation.scale.factor - 1),
},
};
}
return {
scale: previousState.scale,
translation: {
x: previousState.translation.x + transformation.translate.x,
y: previousState.translation.y + transformation.translate.y,
},
};
},
state
);
setState(newState);
};
return (
<div className='viewport'>
<MouseHandler applyTransformations={applyTransformations}>
<SingleTouchHandler applyTransformations={applyTransformations}>
<DoubleTouchHandler applyTransformations={applyTransformations}>
<Layer viewportState={state}>{props.children}</Layer>
</DoubleTouchHandler>
</SingleTouchHandler>
</MouseHandler>
</div>
);
};
export default Viewport;

View File

@ -1 +0,0 @@
declare module 'gpx-parser-builder'

View File

@ -1,9 +1,13 @@
import React from 'react';
import App from './App';
import { createRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('root');
const root = createRoot(container!);
root.render(<App />);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View File

@ -1,26 +0,0 @@
import _ from 'lodash';
const initialState: any = {
current: {
$: {},
trk: [
{
trkseg: [{ trkpt: [] }],
},
],
},
};
export const appendTrkpt = (gpx:any , trkpt:any) => {
var updatedGpx = _.cloneDeep(gpx);
updatedGpx.trk[0].trkseg[0].trkpt.push(trkpt);
return updatedGpx;
};
export const clearTrkpt = (gpx:any) => {
var updatedGpx = _.cloneDeep(gpx);
updatedGpx.trk[0]=[];
return updatedGpx;
};

1
src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

80
src/service-worker.ts Normal file
View File

@ -0,0 +1,80 @@
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope;
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
}
// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
}
// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// Any other custom service worker logic can go here.

View File

@ -0,0 +1,142 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://cra.link/PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}

8
src/theme/layer.css Normal file
View File

@ -0,0 +1,8 @@
.background {
position: fixed;
width: 4032px;
height: 2268px;
z-index: -1;
transform-origin: top left;
}

View File

@ -1,17 +0,0 @@
.tiles {
position: relative;
width: 100%;
height: 100%;
}
.tiles p {
z-index: 20;
position: relative;
width: 100%;
height: 100%;
}
.tiles img {
max-width: none;
position: absolute;
}

11
src/theme/viewport.css Normal file
View File

@ -0,0 +1,11 @@
.viewport {
position: fixed;
width: 100%;
height: 100%;
}
.background img {
width: 4032px;
height: 2268px;
}