All files / public/snap-details map.ts

68.18% Statements 30/44
50% Branches 5/10
61.53% Functions 8/13
68.18% Lines 30/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                              5x   5x                       5x 5x   5x   5x           5x   5x     5x   5x   5x       5x         5x   5x                           5x   5x       885x   885x 6x     879x       885x   885x 6x 6x                             885x       885x                                                                   5x       3010x               5x       5x                
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { select, pointer, Selection, BaseType } from "d3-selection";
import { json } from "d3-fetch";
import { geoNaturalEarth1, geoPath } from "d3-geo";
import { feature, mesh } from "topojson-client";
 
import { GeoJsonProperties } from "geojson";
import { Topology, Objects } from "topojson-specification";
 
import type { TerritoriesMetricsData } from "../../publisher/types/shared";
 
export default function renderMap(
  el: string,
  snapData: TerritoriesMetricsData,
) {
  const mapEl = select(el);
 
  json("/static/js/world-110m.v1.json")
    // @ts-expect-error
    .then(ready)
    .catch((error) => {
      throw new Error(error);
    });
 
  function render(
    mapEl: Selection<BaseType, unknown, HTMLElement, unknown>,
    snapData: TerritoriesMetricsData,
    world: Topology<Objects<GeoJsonProperties>>,
  ) {
    const width = mapEl.property("clientWidth");
    const height = width * 0.5;
    // some offset position center of the map properly
    const offset = width * 0.1;
 
    const projection = geoNaturalEarth1()
      .scale(width * 0.2)
      .translate([width / 2, (height + offset) / 2])
      .precision(0.1);
 
    // rotate not to split Asia
    projection.rotate([-10, 0]);
 
    const path = geoPath().projection(projection);
 
    // clean up HTML before rendering map
    mapEl.html("");
 
    const svg = mapEl.append("svg").attr("width", width).attr("height", height);
 
    const tooltip = mapEl
      .append("div")
      .attr("class", "snapcraft-territories__tooltip u-no-margin");
 
    const tooltipMsg = tooltip
      .append("div")
      .attr("class", "p-tooltip__message");
 
    // @ts-expect-error
    const countries = feature(world, world.objects.countries).features;
 
    const g = svg.append("g");
    const country: Selection<
      BaseType,
      {
        geometry: {
          type: string;
          coordinates: Array<Array<number>>;
        };
        id: number;
        properties: object;
        type: string;
      },
      SVGGElement,
      unknown
    > = g.selectAll(".snapcraft-territories__country").data(countries);
 
    country
      .enter()
      .insert("path")
      .attr("class", (countryData) => {
        const countrySnapData = snapData[countryData.id];
 
        if (countrySnapData) {
          return `snapcraft-territories__country snapcraft-territories__country-default`;
        }
 
        return "snapcraft-territories__country";
      })
      // @ts-expect-error
      .attr("style", (countryData) => {
        const countrySnapData = snapData[countryData.id];
 
        if (countrySnapData) {
          Eif (countrySnapData.color_rgb) {
            return (
              "fill: rgb(" +
              countrySnapData.color_rgb[0] +
              "," +
              countrySnapData.color_rgb[1] +
              "," +
              countrySnapData.color_rgb[2] +
              ")"
            );
          }
        }
      })
      // @ts-expect-error
      .attr("d", path)
      .attr("id", function (d) {
        return d.id;
      })
      .attr("title", function (d) {
        // @ts-expect-error
        return d.properties.name;
      })
      .on("mousemove", (event) => {
        const pos = pointer(event, event.currentTarget);
        const countrySnapData = snapData[event.currentTarget.id];
 
        if (countrySnapData) {
          tooltip
            .style("top", pos[1] + "px")
            .style("left", pos[0] + "px")
            .style("display", "block");
 
          const content = [
            '<span class="u-no-margin--top">',
            countrySnapData.name,
          ];
          if (countrySnapData["number_of_users"] !== undefined) {
            content.push(`<br />${countrySnapData["number_of_users"]} active`);
          }
          content.push("</span>");
          tooltipMsg.html(
            `<span
               class="snapcraft-territories__swatch"
               style="background-color: rgb(${countrySnapData.color_rgb[0]}, ${
                 countrySnapData.color_rgb[1]
               }, ${countrySnapData.color_rgb[2]})"></span>
             ${content.join(" ")}`,
          );
        }
      })
      .on("mouseout", function () {
        tooltip.style("display", "none");
      });
 
    g.append("path")
      .datum(
        // @ts-expect-error
        mesh(world, world.objects.countries, function (a, b) {
          return a !== b;
        }),
      )
      .attr("class", "snapcraft-territories__boundary")
      .attr("d", path);
  }
 
  function ready(world: Topology<Objects<GeoJsonProperties>>) {
    render(mapEl, snapData, world);
 
    let resizeTimeout: string | number | NodeJS.Timeout | undefined;
 
    window.addEventListener("resize", () => {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(function () {
        render(mapEl, snapData, world);
      }, 100);
    });
  }
}