summaryrefslogtreecommitdiff
path: root/src/App.tsx
blob: d7b0bdb87c094defcf0e4c6c0ea2f65a8d6d047b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { useEffect, useState } from 'react';

import { Paint } from '@/pages/Paint';
import { LoadScreen } from '@/components/LoadScreen';

import { gridFromAscii, gridFromAnsi } from '@/utils/grid';
import type { Grid } from '@/types/grid';

export const App: React.FC = () => {
    const [route, setRoute] = useState(window.location.hash || '#home');
    const [chosenArt, setChosenArt] = useState<null | string>(null);
    const [loadedGrid, setLoadedGrid] = useState<Grid | null>(null);

    useEffect(() => {
        const handleHashChange = () => {
            setRoute(window.location.hash || '#home');
        };
        window.addEventListener('hashchange', handleHashChange);
        return () => window.removeEventListener('hashchange', handleHashChange);
    }, []);

    const handleLoad = (grid: Grid) => {
        setLoadedGrid(grid);
        window.location.hash = '#paint';
    };

    const handleNew = () => {
        setChosenArt('');
        window.location.hash = '#paint';
    };

    const handlePaste = (ansiText: string) => {
        const importedGrid = gridFromAnsi(ansiText);
        setLoadedGrid(importedGrid);
        window.location.hash = '#paint';
    };

    const handleGoHome = () => {
        setLoadedGrid(null);
        setChosenArt(null);
        window.location.hash = '#home';
    };

    if (route === '#paint') {
        if (loadedGrid !== null) {
            return <Paint grid={loadedGrid} onGoHome={handleGoHome} />;
        }
        if (chosenArt !== null) {
            return <Paint grid={gridFromAscii(chosenArt)} onGoHome={handleGoHome} />;
        }
    }

    return <LoadScreen onLoad={handleLoad} onNew={handleNew} onPaste={handlePaste} />;
};