aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/LocationsMap.svelte
blob: 36223b756e1f7e6959c91d7e4460496a1821ca24 (plain) (blame) pre { line-height: 125%; } td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888 } /* Comment */ .highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */ .highlight .k { color: #080; font-weight: bold } /* Keyword */ .highlight .ch { color: #888 } /* Comment.Hashbang */ .highlight .cm { color: #888 } /* Comment.Multiline */ .highlight .cp { color: #C00; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888 } /* Comment.Single */ .highlight .cs { color: #C00; font-weight: bold; background-color: #FFF0F0 } /* Comment.Special */ .highlight .gd { color: #000; background-color: #FDD } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #A00 } /* Generic.Error */ .highlight .gh { color: #333 } /* Generic.Heading */ .highlight .gi { color: #000; background-color: #DFD } /* Generic.Inserted */ .highlight .go { color: #888 } /* Generic.Output */ .highlight .gp { color: #555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666 } /* Generic.Subheading */ .highlight .gt { color: #A00 } /* Generic.Traceback */ .highlight .kc { color: #080; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #080; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #080; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #080 } /* Keyword.Pseudo */ .highlight .kr { color: #080; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #00D; font-weight: bold } /* Literal.Number */ .highlight .s { color: #D20; background-color: #FFF0F0 } /* Literal.String */ .highlight .na { color: #369 } /* Name.Attribute */ .highlight .nb { color: #038 } /* Name.Builtin */ .highlight .nc { color: #B06; font-weight: bold } /* Name.Class */ .highlight .no { color: #036; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555 } /* Name.Decorator */ .highlight .ne { color: #B06; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #06B; font-weight: bold } /* Name.Function */ .highlight .nl { color: #369; font-style: italic } /* Name.Label */ .highlight .nn { color: #B06; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #369; font-weight: bold } /* Name.Property */ .highlight .nt { color: #B06; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #369 } /* Name.Variable */ .highlight .ow { color: #080 } /* Operator.Word */ .highlight .w { color: #BBB } /* Text.Whitespace */ .highlight .mb { color: #00D; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #00D; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #00D; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #00D; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #00D; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #D20; background-color: #FFF0F0 } /* Literal.String.Affix */ .highlight .sb { color: #D20; background-color: #FFF0F0 } /* Literal.String.Backtick */ .highlight .sc { color: #D20; background-color: #FFF0F0 } /* Literal.String.Char */ .highlight .dl { color: #D20; background-color: #FFF0F0 } /* Literal.String.Delimiter */ .highlight .sd { color: #D20; background-color: #FFF0F0 } /* Literal.String.Doc */ .highlight .s2 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Double */ .highlight .se { color: #04D; background-color: #FFF0F0 } /* Literal.String.Escape */ .highlight .sh { color: #D20; background-color: #FFF0F0 } /* Literal.String.Heredoc */ .highlight .si { color: #33B; background-color: #FFF0F0 } /* Literal.String.Interpol */ .highlight .sx { color: #2B2; background-color: #F0FFF0 } /* Literal.String.Other */ .highlight .sr { color: #080; background-color: #FFF0FF } /* Literal.String.Regex */ .highlight .s1 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Single */ .highlight .ss { color: #A60; background-color: #FFF0F0 } /* Literal.String.Symbol */ .highlight .bp { color: #038 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #06B; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #369 } /* Name.Variable.Class */ .highlight .vg { color: #D70 } /* Name.Variable.Global */ .highlight .vi { color: #33B } /* Name.Variable.Instance */ .highlight .vm { color: #369 } /* Name.Variable.Magic */ .highlight .il { color: #00D; font-weight: bold } /* Literal.Number.Integer.Long */
<script>
  import { tick, onMount, onDestroy, mount } from "svelte";
  import { browser } from "$app/environment";
  import Popup from "$comp/Popup.svelte";
  import { back } from "$lib/utils";

  import "maplibre-gl/dist/maplibre-gl.css";

  let { locations } = $props();
  let map;
  let mapContainer = $state(),
    mapWrapper = $state();
  let markers = [];
  let search = $state();
  let clearSearch = (e) => (search = "");

  let currentIndex = -1;
  let timeout = $state();

  let full = () => {
    if (!document.fullscreenElement) {
      if (mapWrapper.requestFullscreen) {
        mapWrapper.requestFullscreen();
      } else if (mapWrapper.mozRequestFullScreen) {
        /* Firefox */
        mapWrapper.mozRequestFullScreen();
      } else if (mapWrapper.webkitRequestFullscreen) {
        /* Chrome, Safari & Opera */
        mapWrapper.webkitRequestFullscreen();
      } else if (mapWrapper.msRequestFullscreen) {
        /* IE/Edge */
        mapWrapper.msRequestFullscreen();
      }

      map.resize();
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        /* Firefox */
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        /* Chrome, Safari and Opera */
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {
        /* IE/Edge */
        document.msExitFullscreen();
      }
    }
  };

  let scroll = () => {
    const el = document.querySelector(".selected");
    if (el)
      el.scrollIntoView({
        behavior: "smooth",
        block: "nearest",
        inline: "nearest",
      });
  };

  let selected = $state();
  function select(m) {
    selected = m;
    stopFlying();
    currentIndex = inview.indexOf(m);
    flyToMarker(m, 500);
  }

  async function flyToMarker(marker, duration = 1500) {
    if (!marker) return;
    map.flyTo({
      zoom: 12,
      center: marker.getLngLat(),
      essential: true,
      easing: function (t) {
        return 1 - Math.pow(1 - t, 3);
      },
      duration,
    });

    await new Promise((r) => setTimeout(r, duration));
    marker.getElement().click();
    updateLabelVisibility();
    await new Promise((r) => setTimeout(r, 2500));

    if (!timeout) return;
    //
    // map.flyTo({
    //   zoom: 10.5,
    //   center: marker.getLngLat(),
    //   essential: true,
    //   easing: function (t) {
    //     return 1 - Math.pow(1 - t, 3);
    //   },
    //   duration: 1000,
    // });
  }

  let toggle = () => {
    if (timeout) stopFlying();
    else startFlying();
  };

  let toggleList = () => (showList = !showList);
  let showList = $state();

  let currentPopup;
  function startFlying() {
    currentIndex++;

    for (let p in popups) popups[p].remove();
    if (currentIndex >= inview.length) currentIndex = 0;
    flyToMarker(inview[currentIndex]);

    timeout = setTimeout(startFlying, 4000);
  }

  function debounce(func, delay) {
    let timeout;
    let immediate = true;

    return function (...args) {
      const context = this;

      if (immediate) {
        func.apply(context, args);
        immediate = false;
      }

      clearTimeout(timeout);

      timeout = setTimeout(() => {
        immediate = true;
      }, delay);
    };
  }

  function stopFlying() {
    updateLabelVisibility();
    if (!timeout) return;
    timeout = clearTimeout(timeout);

    if (currentPopup) {
      currentPopup.remove();
    }

    map.jumpTo({ center: map.getCenter(), zoom: map.getZoom() });
    map.off("moveend");
  }

  let inview = $state([]);

  let updateLabelVisibility = debounce(() => {
    inview = [];
    if (!map) return;
    let zoom = map.getZoom();
    let bounds = map.getBounds();

    for (let marker of markers) {
      let isInView = bounds.contains(marker.getLngLat());
      let { tags } = marker;

      if (isInView) {
        inview.push(marker);
      }
    }

    inview = inview.sort((a, b) => a.tags.name.localeCompare(b.tags.name));
  }, 200);

  let locationMarkers = {};
  let popups = {};
  let counter = 0;

  onMount(() => {
    if (browser) {
      import("maplibre-gl").then(({ default: maplibre }) => {
        map = new maplibre.Map({
          container: mapContainer,
          style: "https://tiles.stadiamaps.com/styles/stamen_toner.json",
          center: [-123.05, 49.26],
          zoom: 10.5,
        });

        map.on("load", () => {
          locations.forEach((location) => {
            if (location["deleted_at"]) return;

            let { lat, lon, tags } = location["osm_json"];
            if (!(lat && lon)) return;

            let element = document.createElement("div");
            element.className = "marker";

            let popupContainer = document.createElement("div");

            mount(Popup, {
              target: popupContainer,
              props: { tags },
            });

            let marker = new maplibre.Marker({ color: "#F7931A", scale: 0.65 })
              .setLngLat([lon, lat])
              .setPopup(new maplibre.Popup().setDOMContent(popupContainer))
              .addTo(map);

            marker.id = counter++;

            marker.getElement().addEventListener("click", () => {
              let p = marker.getPopup();
              popups[marker.id] = p;
              p.setDOMContent(popupContainer);
              setTimeout(() => {
                selected = marker;
                setTimeout(scroll, 10);
              }, 50);
              p.on("close", () => {
                selected = undefined;
                delete popups[marker.id];
              });
            });

            marker.tags = tags;
            locationMarkers[location.id] = marker;

            markers.push(marker);
          });

          updateLabelVisibility();
        });

        map.on("mousedown", stopFlying);
        map.on("touchstart", stopFlying);
        map.on("wheel", stopFlying);
        map.on("dragstart", stopFlying);

        let resize = () => map && map.resize();

        document.addEventListener("fullscreenchange", resize, false);
        document.addEventListener("webkitfullscreenchange", resize, false);
        document.addEventListener("mozfullscreenchange", resize, false);
        document.addEventListener("MSFullscreenChange", resize, false);
      });
    }
  });

  onDestroy(() => map && map.remove());
  let list = $derived(
    search
      ? markers.filter((m) =>
          m.tags.name.toLowerCase().includes(search.toLowerCase()),
        )
      : inview,
  );
</script>

<div class="w-screen h-dvh flex" id="map" bind:this={mapWrapper}>
  <div
    id="map-container"
    class="mx-auto h-full w-full z-0"
    bind:this={mapContainer}
  ></div>
  <div class="absolute flex top-2 left-2 gap-2">
    <button
      class="rounded-full border-2 border-black bg-base-100 w-16 h-16 flex items-center justify-center bg-opacity-80"
      onclick={back}
    >
      <iconify-icon icon="ph:arrow-left-bold" width="24"></iconify-icon>
    </button>
  </div>
  <div class="relative">
    {#if !showList}
      <div
        class="space-y-1 text-sm w-[300px] max-w-[calc(100vw*0.5)] h-[300px] max-h-[calc(100vh*0.4)] overflow-y-scroll p-4 bg-opacity-90 bg-base-100 absolute right-4 bottom-8 rounded-2xl shadow text-ellipsis overflow-x-hidden"
      >
        <div class="relative mb-4 sticky top-0 bg-base-100 z-10">
          <input bind:value={search} class="w-full" />
          <div class="flex gap-1 absolute right-6 top-3">
            {#if search}
              <button onclick={clearSearch}>
                <iconify-icon icon="ph:x-bold" width="32"></iconify-icon>
              </button>
            {:else}
              <iconify-icon icon="ph:search-bold" width="32"></iconify-icon>
            {/if}
          </div>
        </div>

        {#each list as marker, i}
          <button
            onclick={() => select(marker)}
            class:font-bold={selected === marker}
            class:selected={selected === marker}
            class="block whitespace-nowrap text-ellipsis text-left w-full overflow-hidden"
          >
            {marker.tags.name}
          </button>
        {/each}
      </div>
    {/if}
    <div class="absolute flex top-2 right-2 gap-2">
      <button
        class="rounded-full border-2 border-primary bg-base-100 w-16 h-16 flex items-center justify-center bg-opacity-80"
        onclick={toggleList}
      >
        <iconify-icon icon="ph:list-bold" width="24"></iconify-icon>
      </button>
      <button
        class="rounded-full border-2 border-primary bg-base-100 w-16 h-16 flex items-center justify-center bg-opacity-80"
        onclick={toggle}
      >
        {#if timeout}
          <iconify-icon icon="ph:pause-bold" width="24"></iconify-icon>
        {:else}
          <iconify-icon icon="ph:play-bold" width="24"></iconify-icon>
        {/if}
      </button>
    </div>
  </div>
</div>

<style>
  #map:fullscreen,
  #map-container:fullscreen {
    width: 100% !important;
    height: 100% !important;
  }

  :global(.maplibregl-popup-close-button) {
    font-size: 24px;
    padding: 8px;
  }

  :global(.maplibregl-popup :focus) {
    outline: none;
  }

  :global(.maplibregl-ctrl-attrib) {
    display: none;
  }

  :global(.maplibregl-popup-content) {
    padding: 1em 2em;
    border-radius: 4px;
    font-size: 14px;
    color: black;
    background-color: white;
    overflow: hidden;
    width: 280px;
  }
</style>
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
@tailwind base;
@tailwind components;
@tailwind utilities;

@font-face {
	font-family: 'PublicSans';
	src: url('/fonts/Public_Sans/static/PublicSans-Regular.ttf') format('truetype');
}

html {
	font-family: PublicSans, sans-serif;
}

::selection {
	color: black;
	background: #eaf2ff;
}

:fullscreen {
	background-color: white;
}

input,
textarea {
	@apply block border rounded-2xl px-5 py-4 w-full;
}

button.primary {
	@apply rounded-full border py-2 font-bold my-4 flex px-4 bg-white mx-auto hover:opacity-80;
}

.select-styles {
	@apply border rounded-2xl py-4 px-5;
	cursor: pointer;
	-webkit-appearance: none;
	-moz-appearance: none;
	background: transparent;
	background-image: url('/icons/down.svg');
	background-repeat: no-repeat;
	background-position-x: 95%;
	background-position-y: 1em;
}