localisation.tsx 6.51 KB
Newer Older
Fabien Amarger's avatar
Fabien Amarger committed
1
2
3
import * as React from 'react';
import * as ReactDOM from 'react-dom';

4
5
import 'bootstrap/dist/css/bootstrap.min.css';
import Badge from 'react-bootstrap/Badge';
6
7
8
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import * as L from 'leaflet';
import 'leaflet/dist/leaflet.css';
9

Fabien Amarger's avatar
Fabien Amarger committed
10
11
12
import { application, implementation, definition } from '@logilab/libview';
import * as $rdf from 'rdflib';

13
14
import './localisation.css';

15
16
const RDF = $rdf.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
const RDFS = $rdf.Namespace('http://www.w3.org/2000/01/rdf-schema#');
17
const CULT = $rdf.Namespace('http://graphe-culture.fr/');
18

Fabien Amarger's avatar
Fabien Amarger committed
19
20
21
22
23
24
25
26
27
const DESCRIPTOR_LOCALISATION: definition.ViewDescriptor = {
    identifier: '::Culture::Localisation',
    name: 'Culture: Localisation de bien culturel',
    description:
        'Affiche une carte contenant la localisation des biens culturels dans les données ouvertes du ministère de la culture',
    entrypoint: 'VIEW_ENTRYPOINT',
    resourceCss: [],
    resourceJs: [],
    resourceMain: {
28
        uri: `${process.env.DOMAIN ?? 'http://localhost:8080'}/view_localisation.js`,
29
    },
Fabien Amarger's avatar
Fabien Amarger committed
30
31
};

32
33
34
interface BienCulturelProps {
    typeUris: string[];
    label: string;
35
    locationUri: string;
36
    dataFetcher?: implementation.DataFetcher;
37
38
}

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
interface BienCulturelInfoProps {
    types: string[];
    label: string;
}

interface Location {
    lat: number;
    lng: number;
}

const BienCulturelInfo: React.FC<BienCulturelInfoProps> = ({ types, label }) => (
    <>
        <h1>{label}</h1>
        <h5>
            {types.map((typeLabel) => (
                <Badge style={{ margin: '5px' }} key={typeLabel} variant="primary">
                    {typeLabel}
                </Badge>
            ))}
        </h5>
    </>
);

const BienCulturel: React.FC<BienCulturelProps> = ({ typeUris, label, locationUri, dataFetcher }) => {
63
64
65
    const [urisLabel, setUrisLabel] = React.useState<{ uri: string; label: string | null }[]>(
        typeUris.map((typeUri) => ({ uri: typeUri, label: null }))
    );
66
    const [location, setLocation] = React.useState<Location | null>(null);
67
68
69
70
71
72
73
    React.useEffect(() => {
        if (dataFetcher !== undefined) {
            Promise.all(
                typeUris.map((typeUri) =>
                    dataFetcher.fetchDataFromURI(typeUri, { label: 'http://www.w3.org/2000/01/rdf-schema#label' })
                )
            )
74
                .then((fetchedLabels: { label?: string | string[] }[]) => {
75
                    const newUrisLabel: { uri: string; label: string }[] = [];
76
77
78
79
                    for (const [i, { label }] of fetchedLabels.entries()) {
                        if (label === undefined) {
                            continue;
                        }
80
                        if (i >= 0 && i < typeUris.length) {
81
82
83
84
                            newUrisLabel.push({
                                uri: typeUris[i],
                                label: label instanceof Array ? label[0] : label,
                            });
85
86
87
88
89
90
91
92
                        }
                    }
                    setUrisLabel(newUrisLabel);
                })
                .catch((e) => console.error(e));
        }
    }, [dataFetcher, typeUris]);

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    React.useEffect(() => {
        if (dataFetcher !== undefined) {
            dataFetcher
                .fetchDataFromURI(locationUri, {
                    lat: 'http://www.w3.org/2003/01/geo/wgs84_pos#latitude',
                    lng: 'http://www.w3.org/2003/01/geo/wgs84_pos#longitude',
                })
                .then(({ lat, lng }) =>
                    setLocation({
                        lat: Number(lat),
                        lng: Number(lng),
                    })
                );
        }
    }, [locationUri, dataFetcher]);

    const typesLabel = urisLabel.map((uriLabel) => uriLabel.label ?? uriLabel.uri);

    let locationComponent = <></>;
    if (location !== null) {
        L.Icon.Default.imagePath = `${process.env.DOMAIN}/images/`;
        const position = { lat: location.lat, lng: location.lng };
        locationComponent = (
            <Map zoom={13} center={position} style={{ height: '600px' }}>
                <TileLayer
                    attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                    url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
                />
                <Marker position={position}>
                    <Popup>
                        <BienCulturelInfo types={typesLabel} label={label} />
                    </Popup>
                </Marker>
            </Map>
        );
    }

130
131
    return (
        <>
132
133
            <BienCulturelInfo types={typesLabel} label={label} />
            <div>{locationComponent}</div>
134
135
136
        </>
    );
};
137

Fabien Amarger's avatar
Fabien Amarger committed
138
139
class LocalisationRendering implements implementation.ViewImplementation {
    descriptor: definition.ViewDescriptor = DESCRIPTOR_LOCALISATION;
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    priorityFor(context: $rdf.Formula, target: application.Resource): number {
        let score = 0;

        const targetSym = $rdf.sym(target.uri);

        // has at least one type
        const firstType = context.any(targetSym, RDF('type'));
        if (firstType !== null) {
            score += 10;
        }

        // has at least one label
        const firstLabel = context.any(targetSym, RDFS('label'));
        if (firstLabel !== null) {
            score += 10;
        }
        return score;
Fabien Amarger's avatar
Fabien Amarger committed
157
158
159
160
161
162
163
164
    }

    render(
        renderer: application.ViewRenderer,
        context: application.RenderingContext,
        target: application.Resource
    ): implementation.ViewRendering {
        return {
165
            dom: this.simpleRender('TODO', context.store, target.uri),
Fabien Amarger's avatar
Fabien Amarger committed
166
167
168
169
            suggestedResources: [],
        };
    }

170
171
172
173
174
175
    simpleRender(
        nodeId: string,
        context: $rdf.Formula,
        target: string,
        dataFetcher?: implementation.DataFetcher
    ): Element {
Fabien Amarger's avatar
Fabien Amarger committed
176
177
        const targetSym = $rdf.sym(target);

178
        const bienCulturel: BienCulturelProps = {
179
            typeUris: context.each(targetSym, RDF('type')).map((node) => node.value) as string[],
180
            label: context.anyJS(targetSym, RDFS('label')),
181
            locationUri: context.anyJS(targetSym, CULT('aPourLocalisation')).value,
182
            dataFetcher,
Fabien Amarger's avatar
Fabien Amarger committed
183
184
185
        };

        const result = document.createElement('div');
186
        ReactDOM.render(<BienCulturel {...bienCulturel} />, document.getElementById(nodeId));
Fabien Amarger's avatar
Fabien Amarger committed
187
188
189
190
191
192
193
194
195
        return result;
    }
}

/**
 * Export the view
 */
export const VIEW_LOCALISATION_ENTRYPOINT: LocalisationRendering = new LocalisationRendering();
export const VIEW_ENTRYPOINT = VIEW_LOCALISATION_ENTRYPOINT;