Set location: offer places already used in the photo's trips

505dc9b · gmorell · 2026-11-24 05:41

12 files +231 -2
Message
{commit_body(@commit)}

Files changed

modified lib/cartosnap_app/photos.ex
+69 −0
@@ -272,6 +272,75 @@ defmodule CartosnapApp.Photos do
272 272 end
273 273 end
274 274
275 + @doc """
276 + Places to offer when pinning `photo` by hand, so the same spot isn't
277 + searched for again for every photo of a trip. From the photos of `trips`
278 + (the ones it's in, which the viewer can see), or the owner's own photos
279 + when it's in none:
280 +
281 + * `:before` / `:after`: the nearest located photo taken just before and
282 + just after it (a photo is most likely where the last one was);
283 + * `:places`: the named places already used, most used first.
284 +
285 + Each is `%{name, lat, lon}`; the neighbours also carry `:date`.
286 + """
287 + def place_suggestions(%Scope{} = scope, %Photo{} = photo, trips, limit \\ 8) do
288 + base = suggestion_base(scope, photo, trips)
289 +
290 + %{
291 + before: neighbour_place(base, photo, :before),
292 + after: neighbour_place(base, photo, :after),
293 + places: named_places(base, limit)
294 + }
295 + end
296 +
297 + defp suggestion_base(_scope, photo, [_ | _] = trips) do
298 + trip_ids = Enum.map(trips, & &1.id)
299 +
300 + from p in Photo,
301 + where: p.id != ^photo.id and not is_nil(p.geo_point),
302 + where: p.id in subquery(from pt in PhotoTrip, where: pt.trip in ^trip_ids, select: pt.photo)
303 + end
304 +
305 + defp suggestion_base(%Scope{user: user}, photo, []) do
306 + from p in Photo, where: p.id != ^photo.id and not is_nil(p.geo_point) and p.user == ^user.id
307 + end
308 +
309 + defp neighbour_place(_base, %Photo{date: nil}, _side), do: nil
310 +
311 + defp neighbour_place(base, %Photo{date: date}, side) do
312 + query =
313 + case side do
314 + :before -> from p in base, where: p.date <= ^date, order_by: [desc: p.date, desc: p.id]
315 + :after -> from p in base, where: p.date >= ^date, order_by: [asc: p.date, asc: p.id]
316 + end
317 +
318 + case Repo.one(from p in query, limit: 1) do
319 + nil ->
320 + nil
321 +
322 + neighbour ->
323 + {lat, lon} = Photo.lat_lon(neighbour)
324 + %{name: neighbour.place_name, lat: lat, lon: lon, date: neighbour.date}
325 + end
326 + end
327 +
328 + # Where a name was used in more than one spot, the latest one.
329 + defp named_places(base, limit) do
330 + from(p in base,
331 + where: not is_nil(p.place_name) and p.place_name != "",
332 + group_by: p.place_name,
333 + order_by: [desc: count(p.id), asc: p.place_name],
334 + limit: ^limit,
335 + select: %{
336 + name: p.place_name,
337 + lat: fragment("(array_agg(ST_Y(?) ORDER BY ? DESC NULLS LAST))[1]", p.geo_point, p.date),
338 + lon: fragment("(array_agg(ST_X(?) ORDER BY ? DESC NULLS LAST))[1]", p.geo_point, p.date)
339 + }
340 + )
341 + |> Repo.all()
342 + end
343 +
275 344 @doc """
276 345 Pins a photo to `{lat, lon}` (labelled `place_name`, when picked from a
277 346 search), or unpins it with nil. Replaces whatever position it had,
modified lib/cartosnap_app_web/live/photo_live/show.ex
+110 −2
@@ -82,10 +82,65 @@ defmodule CartosnapAppWeb.PhotoLive.Show do
82 82 |> assign(:place_query, "")
83 83 |> assign(:place_form, to_form(%{"q" => ""}, as: :place))
84 84 |> assign(:places, [])
85 + |> assign(:suggestions, [])
85 86 |> assign(:searching, false)
86 87 |> assign(:search_failed, false)
87 88 end
88 89
90 + # Places from this photo's trips (or the owner's own photos), offered
91 + # before searching: the photos just before and after it, then the named
92 + # places already used. Picked like a search result.
93 + defp suggestions(socket) do
94 + %{current_scope: scope, photo: photo, trips: trips} = socket.assigns
95 + %{before: before, after: next, places: places} = Photos.place_suggestions(scope, photo, trips)
96 +
97 + neighbours =
98 + [{"before", before}, {"after", next}]
99 + |> Enum.reject(fn {_id, place} -> is_nil(place) end)
100 + |> Enum.uniq_by(fn {_id, place} -> {place.lat, place.lon} end)
101 + |> Enum.map(fn {id, place} ->
102 + Map.merge(place, %{id: id, hint: neighbour_hint(id, place, photo)})
103 + end)
104 +
105 + taken = MapSet.new(neighbours, & &1.name)
106 +
107 + named =
108 + places
109 + |> Enum.reject(&MapSet.member?(taken, &1.name))
110 + |> Enum.with_index(fn place, i -> Map.merge(place, %{id: "used-#{i}", hint: nil}) end)
111 +
112 + neighbours ++ named
113 + end
114 +
115 + defp suggestions_from([]), do: "From your photos"
116 + defp suggestions_from([trip]), do: "From #{trip.name}"
117 + defp suggestions_from(_trips), do: "From its trips"
118 +
119 + defp neighbour_hint(side, place, photo) do
120 + gap = place.date && photo.date && abs(DateTime.diff(photo.date, place.date, :minute))
121 + label = if side == "before", do: "Photo before", else: "Photo after"
122 +
123 + if gap,
124 + do: "#{label} · #{gap_text(gap)} #{if side == "before", do: "earlier", else: "later"}",
125 + else: label
126 + end
127 +
128 + defp gap_text(minutes) when minutes < 1, do: "moments"
129 + defp gap_text(minutes) when minutes < 60, do: "#{minutes} min"
130 + defp gap_text(minutes) when minutes < 48 * 60, do: "#{div(minutes, 60)} h"
131 + defp gap_text(minutes), do: "#{div(minutes, 60 * 24)} days"
132 +
133 + # While searching, only the used places whose names match.
134 + defp shown_suggestions(suggestions, query) do
135 + case String.trim(query) |> String.downcase() do
136 + "" ->
137 + suggestions
138 +
139 + q ->
140 + Enum.filter(suggestions, &(&1.name && String.contains?(String.downcase(&1.name), q)))
141 + end
142 + end
143 +
89 144 # The map shows the pending pin while one is being chosen, else the photo's own.
90 145 defp assign_points(socket) do
91 146 photo = socket.assigns.photo
@@ -527,6 +582,8 @@ defmodule CartosnapAppWeb.PhotoLive.Show do
527 582 place_form={@place_form}
528 583 place_query={@place_query}
529 584 places={@places}
585 + suggestions={@suggestions}
586 + suggestions_from={suggestions_from(@trips)}
530 587 searching={@searching}
531 588 search_failed={@search_failed}
532 589 />
@@ -545,11 +602,16 @@ defmodule CartosnapAppWeb.PhotoLive.Show do
545 602 attr :place_form, :any, required: true
546 603 attr :place_query, :string, required: true
547 604 attr :places, :list, required: true
605 + attr :suggestions, :list, default: []
606 + attr :suggestions_from, :string, default: nil
548 607 attr :searching, :boolean, required: true
549 608 attr :search_failed, :boolean, required: true
550 609
551 610 defp location_panel(assigns) do
552 − assigns = assign(assigns, :position, Photo.lat_lon(assigns.photo))
611 + assigns =
612 + assigns
613 + |> assign(:position, Photo.lat_lon(assigns.photo))
614 + |> assign(:shown_suggestions, shown_suggestions(assigns.suggestions, assigns.place_query))
553 615
554 616 ~H"""
555 617 <section id="photo-location" class="space-y-2">
@@ -601,6 +663,40 @@ defmodule CartosnapAppWeb.PhotoLive.Show do
601 663 </label>
602 664 </.form>
603 665
666 + <div :if={@shown_suggestions != []} id="place-suggestions" class="space-y-1">
667 + <p class="px-1 text-[0.65rem] font-semibold uppercase tracking-wider text-base-content/50">
668 + {@suggestions_from}
669 + </p>
670 + <div class="flex flex-wrap gap-1.5">
671 + <button
672 + :for={place <- @shown_suggestions}
673 + type="button"
674 + id={"suggestion-#{place.id}"}
675 + phx-click="pick-suggestion"
676 + phx-value-id={place.id}
677 + title={place.hint}
678 + class={[
679 + "flex max-w-full flex-col items-start rounded-box border px-2.5 py-1 text-left text-xs transition hover:border-primary/60 hover:bg-base-100",
680 + if(@pending && @pending.id == "suggestion-#{place.id}",
681 + do: "border-primary bg-primary/10",
682 + else: "border-base-300 bg-base-100/60"
683 + )
684 + ]}
685 + >
686 + <span class="flex max-w-full items-center gap-1 font-medium">
687 + <.icon
688 + name={if place.hint, do: "hero-clock-micro", else: "hero-map-pin-micro"}
689 + class="size-3 shrink-0 opacity-60"
690 + />
691 + <span class="truncate">
692 + {place.name || format_coords(place.lat, place.lon)}
693 + </span>
694 + </span>
695 + <span :if={place.hint} class="text-[0.65rem] opacity-60">{place.hint}</span>
696 + </button>
697 + </div>
698 + </div>
699 +
604 700 <ul
605 701 :if={@places != []}
606 702 id="place-results"
@@ -842,7 +938,19 @@ defmodule CartosnapAppWeb.PhotoLive.Show do
842 938 end
843 939
844 940 def handle_event("locate", _params, socket) do
845 − {:noreply, socket |> reset_locating() |> assign(:locating, true) |> assign_points()}
941 + socket = socket |> reset_locating() |> assign(:locating, true)
942 + {:noreply, socket |> assign(:suggestions, suggestions(socket)) |> assign_points()}
943 + end
944 +
945 + def handle_event("pick-suggestion", %{"id" => id}, socket) do
946 + case Enum.find(socket.assigns.suggestions, &(&1.id == id)) do
947 + nil ->
948 + {:noreply, socket}
949 +
950 + place ->
951 + pending = %{id: "suggestion-#{id}", lat: place.lat, lon: place.lon, name: place.name}
952 + {:noreply, socket |> assign(:pending, pending) |> assign_points()}
953 + end
846 954 end
847 955
848 956 def handle_event("cancel-locate", _params, socket) do
modified test/cartosnap_app_web/live/photo_live/show_test.exs
+52 −0
@@ -268,6 +268,58 @@ defmodule CartosnapAppWeb.PhotoLive.ShowTest do
268 268 assert saved.place_name == "Fenway Park, Boston"
269 269 end
270 270
271 + test "offers places already used in the trip, and the photos either side",
272 + %{conn: conn, scope: scope} do
273 + trip = trip_fixture(scope)
274 + at = ~U[2025-06-02 12:00:00Z]
275 +
276 + pinned = fn attrs, name ->
277 + photo = photo_fixture(scope, attrs)
278 + photo |> Ecto.Changeset.change(place_name: name) |> CartosnapApp.Repo.update!()
279 + end
280 +
281 + pinned.(
282 + %{lat: 42.35, lon: -71.10, date: DateTime.add(at, -20, :minute)},
283 + "Fenway Park, Boston"
284 + )
285 +
286 + pinned.(%{lat: 42.36, lon: -71.06, date: DateTime.add(at, -3, :day)}, "Boston Common")
287 + pinned.(%{lat: 42.36, lon: -71.06, date: DateTime.add(at, -4, :day)}, "Boston Common")
288 + # Unnamed, after: offered by its coordinates.
289 + photo_fixture(scope, %{lat: 41.5, lon: -70.5, date: DateTime.add(at, 2, :hour)})
290 + # Not in the trip: never offered.
291 + pinned.(%{lat: 10.0, lon: 10.0, date: DateTime.add(at, -1, :minute)}, "Elsewhere")
292 +
293 + photo = photo_fixture(scope, %{date: at})
294 + album = Photos.list_photos(scope) |> Enum.reject(&(&1.place_name == "Elsewhere"))
295 + {:ok, _} = CartosnapApp.Trips.add_photos(scope, trip.id, Enum.map(album, & &1.id))
296 +
297 + {:ok, view, _html} = live(conn, ~p"/photos/#{photo}?#{[trip: trip.id]}")
298 + view |> element("#locate-photo") |> render_click()
299 +
300 + assert has_element?(view, "#place-suggestions", "From #{trip.name}")
301 + assert has_element?(view, "#suggestion-before", "Fenway Park")
302 + assert has_element?(view, "#suggestion-before", "20 min earlier")
303 + assert has_element?(view, "#suggestion-after", "2 h later")
304 + assert has_element?(view, "#suggestion-used-0", "Boston Common")
305 + refute has_element?(view, "#place-suggestions", "Elsewhere")
306 + # Fenway is the photo before; it isn't offered twice.
307 + refute has_element?(view, "[id^=suggestion-used]", "Fenway")
308 +
309 + # Typing narrows them to the matching names.
310 + view |> form("#place-search-form", place: %{q: "comm"}) |> render_change()
311 + assert has_element?(view, "#suggestion-used-0")
312 + refute has_element?(view, "#suggestion-before")
313 +
314 + view |> element("#suggestion-used-0") |> render_click()
315 + assert has_element?(view, "#pending-location", "Boston Common")
316 + view |> element("#save-location") |> render_click()
317 +
318 + saved = Photos.get_photo!(scope, photo.id)
319 + assert Photo.lat_lon(saved) == {42.36, -71.06}
320 + assert saved.place_name == "Boston Common"
321 + end
322 +
271 323 test "drops a pin where the map is clicked", %{conn: conn, scope: scope} do
272 324 photo = photo_fixture(scope)
273 325 {:ok, view, _html} = live(conn, ~p"/photos/#{photo}")

Parents: 8445167