File size: 9,287 Bytes
4083225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { scaleLinear } from "d3-scale";
import { interpolateRgb } from "d3-interpolate";
import { Loader2 } from "lucide-react";
import WorldMap from "../components/WorldMap.jsx";
import {
  fetchCountryDivergence,
  fetchMapArticles,
} from "../api/client.js";
import {
  getCachedMapArticles,
  getCachedMapDivergence,
  setCachedMapArticles,
  setCachedMapDivergence,
} from "../utils/investigationCache.js";
import { viewportTooltipPosition } from "../utils/viewportTooltip.js";
import "./MapView.css";

const heatScale = scaleLinear()
  .domain([0, 0.5, 1])
  .range(["#1B202C", "#C8A96E", "#E05252"])
  .interpolate(interpolateRgb)
  .clamp(true);

const NO_DATA_FILL = "#1A1E29";

export default function MapView({ query }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [hover, setHover] = useState(null);
  const [selectedIso, setSelectedIso] = useState(null);
  const tooltipRef = useRef(null);
  const lastPointerRef = useRef({ x: 0, y: 0 });
  const [articles, setArticles] = useState([]);
  const [articlesLoading, setArticlesLoading] = useState(true);

  const topic = query?.topic?.trim() ?? "";
  const newsTimeframe = query?.newsTimeframe ?? "6m";
  const qParams = { topic, newsTimeframe };

  useEffect(() => {
    let cancelled = false;
    if (!topic) {
      setData(null);
      setLoading(false);
      return () => {
        cancelled = true;
      };
    }
    const cached = getCachedMapDivergence(topic, newsTimeframe);
    if (cached) {
      setData(cached);
      setLoading(false);
      return () => {
        cancelled = true;
      };
    }
    setLoading(true);
    setData(null);
    fetchCountryDivergence(qParams)
      .then((d) => {
        if (cancelled) return;
        setData(d);
        setCachedMapDivergence(topic, newsTimeframe, d);
      })
      .finally(() => !cancelled && setLoading(false));
    return () => {
      cancelled = true;
    };
  }, [topic, newsTimeframe]);

  useEffect(() => {
    let cancelled = false;
    if (!topic) {
      setArticles([]);
      setArticlesLoading(false);
      return () => {
        cancelled = true;
      };
    }
    const cached = getCachedMapArticles(topic, newsTimeframe, selectedIso);
    if (cached) {
      setArticles(cached);
      setArticlesLoading(false);
      return () => {
        cancelled = true;
      };
    }
    setArticlesLoading(true);
    fetchMapArticles(qParams, selectedIso)
      .then((d) => {
        if (cancelled) return;
        const list = d?.articles ?? [];
        setArticles(list);
        setCachedMapArticles(topic, newsTimeframe, selectedIso, list);
      })
      .finally(() => !cancelled && setArticlesLoading(false));
    return () => {
      cancelled = true;
    };
  }, [topic, newsTimeframe, selectedIso]);

  const byNumeric = useMemo(() => {
    const m = new Map();
    data?.countries?.forEach((c) => m.set(c.numericCode, c));
    return m;
  }, [data]);

  const selectedNumeric = useMemo(() => {
    if (!selectedIso || !data) return null;
    const c = data.countries.find((x) => x.iso3 === selectedIso);
    return c?.numericCode ?? null;
  }, [selectedIso, data]);

  const colorFor = useCallback(
    (numeric) => {
      if (!data) return NO_DATA_FILL;
      const c = byNumeric.get(numeric);
      return c ? heatScale(c.divergence) : NO_DATA_FILL;
    },
    [data, byNumeric]
  );

  const applyTooltipDom = useCallback((clientX, clientY) => {
    lastPointerRef.current = { x: clientX, y: clientY };
    const el = tooltipRef.current;
    if (!el) return;
    const { width, height } = el.getBoundingClientRect();
    const estWidth = width > 0 ? width : 236;
    const estHeight = height > 0 ? height : 92;
    const { left, top } = viewportTooltipPosition(clientX, clientY, {
      estWidth,
      estHeight,
    });
    el.style.left = `${left}px`;
    el.style.top = `${top}px`;
  }, []);

  const onCountryEnter = useCallback(
    (country, e) => {
      lastPointerRef.current = { x: e.clientX, y: e.clientY };
      const c = byNumeric.get(country.numericCode);
      setHover(c ? { ...c } : { name: country.name });
    },
    [byNumeric]
  );

  const onCountryMove = useCallback(
    (e) => {
      applyTooltipDom(e.clientX, e.clientY);
    },
    [applyTooltipDom]
  );

  const onCountryLeave = useCallback(() => {
    setHover(null);
  }, []);

  const onCountryClick = useCallback(
    (country) => {
      const c = byNumeric.get(country.numericCode);
      if (c) {
        setSelectedIso((prev) => (prev === c.iso3 ? null : c.iso3));
      }
    },
    [byNumeric]
  );

  useLayoutEffect(() => {
    if (!hover) return;
    const { x, y } = lastPointerRef.current;
    applyTooltipDom(x, y);
  }, [hover, applyTooltipDom]);

  return (
    <div className="map-view-page">
      <div className="map-view">
        <MapLegend />

        <WorldMap
          colorFor={colorFor}
          selectedNumeric={selectedNumeric}
          onCountryEnter={onCountryEnter}
          onCountryMove={onCountryMove}
          onCountryLeave={onCountryLeave}
          onCountryClick={onCountryClick}
        />

        {loading && (
          <div className="map-view__loading">
            <Loader2 size={14} strokeWidth={1.5} className="spin" />
            <span>compiling coverage</span>
          </div>
        )}

        <div className="map-view__hint">drag to pan 路 scroll to zoom 路 click a country</div>

        {hover && (
          <div
            ref={tooltipRef}
            className="map-tooltip"
            style={{ position: "fixed", left: 0, top: 0, transform: "none" }}
          >
            <div className="map-tooltip__name">{hover.name}</div>
            {hover.articleCount != null ? (
              <>
                <div className="map-tooltip__row">
                  <span className="label">Articles</span>
                  <span className="mono">{hover.articleCount}</span>
                </div>
                <div className="map-tooltip__row">
                  <span className="label">Density</span>
                  <span className="mono" style={{ color: heatScale(hover.divergence) }}>
                    {hover.divergence.toFixed(2)}
                  </span>
                </div>
              </>
            ) : (
              <div className="map-tooltip__row faint">no coverage indexed</div>
            )}
          </div>
        )}
      </div>

      <section className="map-articles">
        <div className="map-articles__head">
          <div>
            <div className="label">Articles</div>
            <h2 className="map-articles__title">
              {selectedIso ? `Coverage from ${selectedIso}` : "All indexed coverage"}
            </h2>
          </div>
          {selectedIso && (
            <button className="ghost" onClick={() => setSelectedIso(null)}>
              Clear country filter
            </button>
          )}
        </div>

        {articlesLoading ? (
          <div className="map-articles__loading">
            <Loader2 size={14} className="spin" />
            <span>loading articles</span>
          </div>
        ) : !articles.length ? (
          <div className="map-articles__loading">
            <span>no articles found for this selection</span>
          </div>
        ) : (
          <ul className="map-articles__list">
            {articles.map((article) => (
              <li key={article.id} className="map-article">
                <a href={article.url} target="_blank" rel="noreferrer" className="map-article__title">
                  {article.headline}
                </a>
                <div className="map-article__meta">
                  <span>{article.source || "unknown source"}</span>
                  {article.countryName && (
                    <>
                      <span className="faint"></span>
                      <span>{article.countryName}</span>
                    </>
                  )}
                  {article.publishedAt && (
                    <>
                      <span className="faint"></span>
                      <span>{article.publishedAt}</span>
                    </>
                  )}
                </div>
                {article.summary && <p className="map-article__summary">{article.summary}</p>}
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}

function MapLegend() {
  const stops = [0, 0.25, 0.5, 0.75, 1];
  return (
    <div className="map-legend">
      <div className="label map-legend__title">Article density</div>
      <div className="map-legend__bar">
        {stops.map((s, i) => (
          <div
            key={i}
            className="map-legend__cell"
            style={{ background: heatScale(s) }}
          />
        ))}
      </div>
      <div className="map-legend__scale" aria-label="Article density from low to high">
        <span className="map-legend__scale-label map-legend__scale-label--low">low density</span>
        <span className="map-legend__scale-gap" aria-hidden="true" />
        <span className="map-legend__scale-label map-legend__scale-label--high">high density</span>
      </div>
    </div>
  );
}