Compare commits

..

7 Commits

Author SHA1 Message Date
Thomas Way d416e225e6 feat: sort smart search
Smart search currently returns a list of assets by their score. It would
be nice if we could instead filter assets, and then list them by date.
This is the default behaviour of other platforms.
2026-02-24 10:28:56 +00:00
Mert 1d25267f22 fix(mobile): buffer width/height referenced after recycling (#26415)
recycle after getters
2026-02-21 09:41:44 -06:00
Michel Heusschen a4d95b7aba fix(web): prevent side panel overlap during transition (#26398) 2026-02-21 09:14:53 -06:00
Min Idzelis 25d0bdc9f5 chore: replace remaining usages of npm with pnpm (#26411) 2026-02-21 08:44:33 -05:00
Michel Heusschen 905b9bd560 fix(web): album description auto height (#26420) 2026-02-21 08:43:23 -05:00
Michel Heusschen 672743f543 fix(web): escape handling on album page (#26419) 2026-02-21 08:42:31 -05:00
Michel Heusschen 27c45b5ddb fix(web): restore close action for asset viewer (#26418) 2026-02-21 10:31:30 +00:00
75 changed files with 1413 additions and 743 deletions
+1 -1
View File
@@ -511,7 +511,7 @@ jobs:
run: pnpm install --frozen-lockfile
if: ${{ !cancelled() }}
- name: Install Playwright Browsers
run: npx playwright install chromium --only-shell
run: pnpm exec playwright install chromium --only-shell
if: ${{ !cancelled() }}
- name: Docker build
run: docker compose up -d --build --renew-anon-volumes --force-recreate --remove-orphans --wait --wait-timeout 300
+1 -1
View File
@@ -52,7 +52,7 @@ attach-server:
docker exec -it docker_immich-server_1 sh
renovate:
LOG_LEVEL=debug npx renovate --platform=local --repository-cache=reset
LOG_LEVEL=debug pnpm exec renovate --platform=local --repository-cache=reset
# Directories that need to be created for volumes or build output
VOLUME_DIRS = \
+2 -2
View File
@@ -45,8 +45,8 @@
"build": "vite build",
"build:dev": "vite build --sourcemap true",
"lint": "eslint \"src/**/*.ts\" --max-warnings 0",
"lint:fix": "npm run lint -- --fix",
"prepack": "npm run build",
"lint:fix": "pnpm run lint --fix",
"prepack": "pnpm run build",
"test": "vitest",
"test:cov": "vitest --coverage",
"format": "prettier --check .",
+1 -1
View File
@@ -8,7 +8,7 @@
"format:fix": "prettier --write .",
"start": "docusaurus start --port 3005",
"copy:openapi": "jq -c < ../open-api/immich-openapi-specs.json > ./static/openapi.json || exit 0",
"build": "npm run copy:openapi && docusaurus build",
"build": "pnpm run copy:openapi && docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
+7 -7
View File
@@ -8,16 +8,16 @@
"test": "vitest --run",
"test:watch": "vitest",
"test:maintenance": "vitest --run --config vitest.maintenance.config.ts",
"test:web": "npx playwright test --project=web",
"test:web:maintenance": "npx playwright test --project=maintenance",
"test:web:ui": "npx playwright test --project=ui",
"start:web": "npx playwright test --ui --project=web",
"start:web:maintenance": "npx playwright test --ui --project=maintenance",
"start:web:ui": "npx playwright test --ui --project=ui",
"test:web": "pnpm exec playwright test --project=web",
"test:web:maintenance": "pnpm exec playwright test --project=maintenance",
"test:web:ui": "pnpm exec playwright test --project=ui",
"start:web": "pnpm exec playwright test --ui --project=web",
"start:web:maintenance": "pnpm exec playwright test --ui --project=maintenance",
"start:web:ui": "pnpm exec playwright test --ui --project=ui",
"format": "prettier --check .",
"format:fix": "prettier --write .",
"lint": "eslint \"src/**/*.ts\" --max-warnings 0",
"lint:fix": "npm run lint -- --fix",
"lint:fix": "pnpm run lint --fix",
"check": "tsc --noEmit"
},
"keywords": [],
+4
View File
@@ -689,6 +689,7 @@
"backup_settings_subtitle": "Manage upload settings",
"backup_upload_details_page_more_details": "Tap for more details",
"backward": "Backward",
"best_match": "Best match",
"biometric_auth_enabled": "Biometric authentication enabled",
"biometric_locked_out": "You are locked out of biometric authentication",
"biometric_no_options": "No biometric options available",
@@ -1945,6 +1946,8 @@
"search_filter_media_type_title": "Select media type",
"search_filter_ocr": "Search by OCR",
"search_filter_people_title": "Select people",
"search_filter_sort_order": "Sort Order",
"search_filter_sort_order_title": "Select sort order",
"search_filter_star_rating": "Star Rating",
"search_filter_tags_title": "Select tags",
"search_for": "Search for",
@@ -2160,6 +2163,7 @@
"sort_modified": "Date modified",
"sort_newest": "Newest photo",
"sort_oldest": "Oldest photo",
"sort_order": "Sort order",
"sort_people_by_similarity": "Sort people by similarity",
"sort_recent": "Most recent photo",
"sort_title": "Title",
+1 -1
View File
@@ -15,7 +15,7 @@ config_roots = [
[tools]
node = "24.13.1"
flutter = "3.41.2"
flutter = "3.35.7"
pnpm = "10.29.3"
terragrunt = "0.98.0"
opentofu = "1.11.4"
@@ -48,7 +48,6 @@ fun Bitmap.toNativeBuffer(): Map<String, Long> {
try {
val buffer = NativeBuffer.wrap(pointer, size)
copyPixelsToBuffer(buffer)
recycle()
return mapOf(
"pointer" to pointer,
"width" to width.toLong(),
@@ -57,8 +56,9 @@ fun Bitmap.toNativeBuffer(): Map<String, Long> {
)
} catch (e: Exception) {
NativeBuffer.free(pointer)
recycle()
throw e
} finally {
recycle()
}
}
+16 -22
View File
@@ -38,10 +38,10 @@ PODS:
- local_auth_darwin (0.0.1):
- Flutter
- FlutterMacOS
- MapLibre (6.23.0)
- maplibre_ios (0.0.1):
- MapLibre (6.14.0)
- maplibre_gl (0.0.1):
- Flutter
- MapLibre (~> 6.21)
- MapLibre (= 6.14.0)
- native_video_player (1.0.0):
- Flutter
- network_info_plus (0.0.1):
@@ -58,8 +58,6 @@ PODS:
- photo_manager (3.7.1):
- Flutter
- FlutterMacOS
- pointer_interceptor_ios (0.0.1):
- Flutter
- SAMKeychain (1.5.3)
- share_handler_ios (0.0.14):
- Flutter
@@ -77,16 +75,16 @@ PODS:
- sqflite_darwin (0.0.4):
- Flutter
- FlutterMacOS
- sqlite3 (3.49.2):
- sqlite3/common (= 3.49.2)
- sqlite3/common (3.49.2)
- sqlite3/dbstatvtab (3.49.2):
- sqlite3 (3.49.1):
- sqlite3/common (= 3.49.1)
- sqlite3/common (3.49.1)
- sqlite3/dbstatvtab (3.49.1):
- sqlite3/common
- sqlite3/fts5 (3.49.2):
- sqlite3/fts5 (3.49.1):
- sqlite3/common
- sqlite3/perf-threadsafe (3.49.2):
- sqlite3/perf-threadsafe (3.49.1):
- sqlite3/common
- sqlite3/rtree (3.49.2):
- sqlite3/rtree (3.49.1):
- sqlite3/common
- sqlite3_flutter_libs (0.0.1):
- Flutter
@@ -120,7 +118,7 @@ DEPENDENCIES:
- integration_test (from `.symlinks/plugins/integration_test/ios`)
- isar_community_flutter_libs (from `.symlinks/plugins/isar_community_flutter_libs/ios`)
- local_auth_darwin (from `.symlinks/plugins/local_auth_darwin/darwin`)
- maplibre_ios (from `.symlinks/plugins/maplibre_ios/ios`)
- maplibre_gl (from `.symlinks/plugins/maplibre_gl/ios`)
- native_video_player (from `.symlinks/plugins/native_video_player/ios`)
- network_info_plus (from `.symlinks/plugins/network_info_plus/ios`)
- objective_c (from `.symlinks/plugins/objective_c/ios`)
@@ -128,7 +126,6 @@ DEPENDENCIES:
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
- permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
- photo_manager (from `.symlinks/plugins/photo_manager/ios`)
- pointer_interceptor_ios (from `.symlinks/plugins/pointer_interceptor_ios/ios`)
- share_handler_ios (from `.symlinks/plugins/share_handler_ios/ios`)
- share_handler_ios_models (from `.symlinks/plugins/share_handler_ios/ios/Models`)
- share_plus (from `.symlinks/plugins/share_plus/ios`)
@@ -181,8 +178,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/isar_community_flutter_libs/ios"
local_auth_darwin:
:path: ".symlinks/plugins/local_auth_darwin/darwin"
maplibre_ios:
:path: ".symlinks/plugins/maplibre_ios/ios"
maplibre_gl:
:path: ".symlinks/plugins/maplibre_gl/ios"
native_video_player:
:path: ".symlinks/plugins/native_video_player/ios"
network_info_plus:
@@ -197,8 +194,6 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/permission_handler_apple/ios"
photo_manager:
:path: ".symlinks/plugins/photo_manager/ios"
pointer_interceptor_ios:
:path: ".symlinks/plugins/pointer_interceptor_ios/ios"
share_handler_ios:
:path: ".symlinks/plugins/share_handler_ios/ios"
share_handler_ios_models:
@@ -235,8 +230,8 @@ SPEC CHECKSUMS:
integration_test: 4a889634ef21a45d28d50d622cf412dc6d9f586e
isar_community_flutter_libs: bede843185a61a05ff364a05c9b23209523f7e0d
local_auth_darwin: 553ce4f9b16d3fdfeafce9cf042e7c9f77c1c391
MapLibre: c0fcafabb341f230657d959970c6eb47fb55750e
maplibre_ios: 05031d5f79702672d2c01cc77b6ba3187d4bf896
MapLibre: 69e572367f4ef6287e18246cfafc39c80cdcabcd
maplibre_gl: 3c924e44725147b03dda33430ad216005b40555f
native_video_player: b65c58951ede2f93d103a25366bdebca95081265
network_info_plus: cf61925ab5205dce05a4f0895989afdb6aade5fc
objective_c: 89e720c30d716b036faf9c9684022048eee1eee2
@@ -244,14 +239,13 @@ SPEC CHECKSUMS:
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
photo_manager: 1d80ae07a89a67dfbcae95953a1e5a24af7c3e62
pointer_interceptor_ios: da06a662d5bfd329602b45b2ab41bc0fb5fdb0f0
SAMKeychain: 483e1c9f32984d50ca961e26818a534283b4cd5c
share_handler_ios: e2244e990f826b2c8eaa291ac3831569438ba0fb
share_handler_ios_models: fc638c9b4330dc7f082586c92aee9dfa0b87b871
share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
sqlite3: 3c950dc86011117c307eb0b28c4a7bb449dce9f1
sqlite3: fc1400008a9b3525f5914ed715a5d1af0b8f4983
sqlite3_flutter_libs: f8fc13346870e73fe35ebf6dbb997fbcd156b241
url_launcher_ios: 694010445543906933d732453a59da0a173ae33d
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
@@ -446,7 +446,6 @@
packageReferences = (
FEE084F62EC172460045228E /* XCRemoteSwiftPackageReference "sqlite-data" */,
FEE084F92EC1725A0045228E /* XCRemoteSwiftPackageReference "swift-http-structured-headers" */,
A1B2C3D4E5F6A7B8C9D0E1F2 /* XCRemoteSwiftPackageReference "maplibre-gl-native-distribution" */,
);
preferredProjectObjectVersion = 77;
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
@@ -1251,14 +1250,6 @@
minimumVersion = 1.5.0;
};
};
A1B2C3D4E5F6A7B8C9D0E1F2 /* XCRemoteSwiftPackageReference "maplibre-gl-native-distribution" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/maplibre/maplibre-gl-native-distribution";
requirement = {
kind = upToNextMinorVersion;
minimumVersion = 6.21.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
@@ -10,15 +10,6 @@
"version" : "1.0.3"
}
},
{
"identity" : "maplibre-gl-native-distribution",
"kind" : "remoteSourceControl",
"location" : "https://github.com/maplibre/maplibre-gl-native-distribution",
"state" : {
"revision" : "2aefb4dd47ca6e897c93086f348a457839aac2fe",
"version" : "6.23.0"
}
},
{
"identity" : "grdb.swift",
"kind" : "remoteSourceControl",
+2 -2
View File
@@ -1,7 +1,7 @@
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class Marker {
final Geographic location;
final LatLng location;
final String assetId;
const Marker({required this.location, required this.assetId});
+3 -3
View File
@@ -1,9 +1,9 @@
import 'package:immich_mobile/domain/models/map.model.dart';
import 'package:immich_mobile/infrastructure/repositories/map.repository.dart';
import 'package:immich_mobile/infrastructure/repositories/timeline.repository.dart';
import 'package:maplibre/maplibre.dart' hide Marker;
import 'package:maplibre_gl/maplibre_gl.dart';
typedef MapMarkerSource = Future<List<Marker>> Function(LngLatBounds? bounds);
typedef MapMarkerSource = Future<List<Marker>> Function(LatLngBounds? bounds);
typedef MapQuery = ({MapMarkerSource markerSource});
@@ -21,5 +21,5 @@ class MapService {
MapService(MapQuery query) : _markerSource = query.markerSource;
Future<List<Marker>> Function(LngLatBounds? bounds) get getMarkers => _markerSource;
Future<List<Marker>> Function(LatLngBounds? bounds) get getMarkers => _markerSource;
}
@@ -1,23 +1,20 @@
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
extension WithinBounds on LngLatBounds {
extension WithinBounds on LatLngBounds {
/// Checks whether [point] is inside bounds
bool contains(Geographic point) {
return containsBounds(
LngLatBounds(
longitudeWest: point.lon,
longitudeEast: point.lon,
latitudeSouth: point.lat,
latitudeNorth: point.lat,
),
);
bool contains(LatLng point) {
final sw = point;
final ne = point;
return containsBounds(LatLngBounds(southwest: sw, northeast: ne));
}
/// Checks whether [bounds] is contained inside bounds
bool containsBounds(LngLatBounds bounds) {
return (bounds.latitudeSouth >= latitudeSouth) &&
(bounds.latitudeNorth <= latitudeNorth) &&
(bounds.longitudeWest >= longitudeWest) &&
(bounds.longitudeEast <= longitudeEast);
bool containsBounds(LatLngBounds bounds) {
final sw = bounds.southwest;
final ne = bounds.northeast;
return (sw.latitude >= southwest.latitude) &&
(ne.latitude <= northeast.latitude) &&
(sw.longitude >= southwest.longitude) &&
(ne.longitude <= northeast.longitude);
}
}
@@ -1,19 +1,19 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:immich_mobile/models/map/map_marker.model.dart';
import 'package:immich_mobile/utils/map_utils.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
extension MapMarkers on MapController {
extension MapMarkers on MapLibreMapController {
static var _completer = Completer()..complete();
Future<void> addGeoJSONSourceForMarkers(List<MapMarker> markers) async {
return style!.addSource(
GeoJsonSource(
id: MapUtils.defaultSourceId,
data: jsonEncode(MapUtils.generateGeoJsonForMarkers(markers.toList())),
),
return addSource(
MapUtils.defaultSourceId,
GeojsonSourceProperties(data: MapUtils.generateGeoJsonForMarkers(markers.toList())),
);
}
@@ -27,28 +27,63 @@ extension MapMarkers on MapController {
// !! Make sure to remove layers before sources else the native
// maplibre library would crash when removing the source saying that
// the source is still in use
try {
await style!.removeLayer(MapUtils.defaultHeatMapLayerId);
} catch (_) {
// Layer may not exist
final existingLayers = await getLayerIds();
if (existingLayers.contains(MapUtils.defaultHeatMapLayerId)) {
await removeLayer(MapUtils.defaultHeatMapLayerId);
}
try {
await style!.removeSource(MapUtils.defaultSourceId);
} catch (_) {
// Source may not exist
final existingSources = await getSourceIds();
if (existingSources.contains(MapUtils.defaultSourceId)) {
await removeSource(MapUtils.defaultSourceId);
}
await addGeoJSONSourceForMarkers(markers);
await style!.addLayer(
const HeatmapStyleLayer(
id: MapUtils.defaultHeatMapLayerId,
sourceId: MapUtils.defaultSourceId,
paint: MapUtils.defaultHeatMapLayerPaint,
),
);
if (Platform.isAndroid) {
await addCircleLayer(
MapUtils.defaultSourceId,
MapUtils.defaultHeatMapLayerId,
const CircleLayerProperties(
circleRadius: 10,
circleColor: "rgba(150,86,34,0.7)",
circleBlur: 1.0,
circleOpacity: 0.7,
circleStrokeWidth: 0.1,
circleStrokeColor: "rgba(203,46,19,0.5)",
circleStrokeOpacity: 0.7,
),
);
}
if (Platform.isIOS) {
await addHeatmapLayer(
MapUtils.defaultSourceId,
MapUtils.defaultHeatMapLayerId,
MapUtils.defaultHeatMapLayerProperties,
);
}
_completer.complete();
}
Future<Symbol?> addMarkerAtLatLng(LatLng centre) async {
// no marker is displayed if asset-path is incorrect
try {
final ByteData bytes = await rootBundle.load("assets/location-pin.png");
await addImage("mapMarker", bytes.buffer.asUint8List());
return addSymbol(SymbolOptions(geometry: centre, iconImage: "mapMarker", iconSize: 0.15, iconAnchor: "bottom"));
} finally {
// no-op
}
}
Future<LatLngBounds> getBoundsFromPoint(Point<double> point, double distance) async {
final southWestPx = Point(point.x - distance, point.y + distance);
final northEastPx = Point(point.x + distance, point.y - distance);
final southWest = await toLatLng(southWestPx);
final northEast = await toLatLng(northEastPx);
return LatLngBounds(southwest: southWest, northeast: northEast);
}
}
@@ -1,4 +1,3 @@
// ignore_for_file: experimental_member_use
import 'dart:async';
import 'package:drift/drift.dart';
@@ -6,7 +6,7 @@ import 'package:immich_mobile/infrastructure/entities/exif.entity.drift.dart';
import 'package:immich_mobile/infrastructure/entities/remote_asset.entity.drift.dart';
import 'package:immich_mobile/infrastructure/repositories/db.repository.dart';
import 'package:immich_mobile/infrastructure/repositories/timeline.repository.dart';
import 'package:maplibre/maplibre.dart' hide Marker;
import 'package:maplibre_gl/maplibre_gl.dart';
class DriftMapRepository extends DriftDatabaseRepository {
final Drift _db;
@@ -42,7 +42,7 @@ class DriftMapRepository extends DriftDatabaseRepository {
Future<List<Marker>> _watchMapMarker({
Expression<bool> Function($RemoteAssetEntityTable row)? assetFilter,
LngLatBounds? bounds,
LatLngBounds? bounds,
}) async {
final assetId = _db.remoteExifEntity.assetId;
final latitude = _db.remoteExifEntity.latitude;
@@ -66,21 +66,20 @@ class DriftMapRepository extends DriftDatabaseRepository {
final rows = await query.get();
return List.generate(rows.length, (i) {
final row = rows[i];
return Marker(
assetId: row.read(assetId)!,
location: Geographic(lat: row.read(latitude)!, lon: row.read(longitude)!),
);
return Marker(assetId: row.read(assetId)!, location: LatLng(row.read(latitude)!, row.read(longitude)!));
}, growable: false);
}
}
extension MapBounds on $RemoteExifEntityTable {
Expression<bool> inBounds(LngLatBounds bounds) {
final latInBounds = latitude.isBetweenValues(bounds.latitudeSouth, bounds.latitudeNorth);
final longInBounds = bounds.longitudeWest <= bounds.longitudeEast
? longitude.isBetweenValues(bounds.longitudeWest, bounds.longitudeEast)
: (longitude.isBiggerOrEqualValue(bounds.longitudeWest) |
longitude.isSmallerOrEqualValue(bounds.longitudeEast));
Expression<bool> inBounds(LatLngBounds bounds) {
final southwest = bounds.southwest;
final northeast = bounds.northeast;
final latInBounds = latitude.isBetweenValues(southwest.latitude, northeast.latitude);
final longInBounds = southwest.longitude <= northeast.longitude
? longitude.isBetweenValues(southwest.longitude, northeast.longitude)
: (longitude.isBiggerOrEqualValue(southwest.longitude) | longitude.isSmallerOrEqualValue(northeast.longitude));
return latInBounds & longInBounds;
}
}
@@ -8,7 +8,7 @@ import 'package:immich_mobile/infrastructure/entities/remote_asset.entity.dart';
import 'package:immich_mobile/infrastructure/entities/remote_asset.entity.drift.dart';
import 'package:immich_mobile/infrastructure/entities/stack.entity.drift.dart';
import 'package:immich_mobile/infrastructure/repositories/db.repository.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class RemoteAssetRepository extends DriftDatabaseRepository {
final Drift _db;
@@ -170,12 +170,12 @@ class RemoteAssetRepository extends DriftDatabaseRepository {
});
}
Future<void> updateLocation(List<String> ids, Geographic location) {
Future<void> updateLocation(List<String> ids, LatLng location) {
return _db.batch((batch) async {
for (final id in ids) {
batch.update(
_db.remoteExifEntity,
RemoteExifEntityCompanion(latitude: Value(location.lat), longitude: Value(location.lon)),
RemoteExifEntityCompanion(latitude: Value(location.latitude), longitude: Value(location.longitude)),
where: (e) => e.assetId.equals(id),
);
}
@@ -37,6 +37,7 @@ class SearchApiRepository extends ApiRepository {
personIds: filter.people.map((e) => e.id).toList(),
tagIds: filter.tagIds,
type: type,
order: filter.order,
page: page,
size: 100,
),
@@ -62,6 +63,7 @@ class SearchApiRepository extends ApiRepository {
personIds: filter.people.map((e) => e.id).toList(),
tagIds: filter.tagIds,
type: type,
order: filter.order ?? AssetOrder.desc,
page: page,
size: 1000,
),
@@ -12,11 +12,11 @@ import 'package:immich_mobile/infrastructure/entities/remote_asset.entity.dart';
import 'package:immich_mobile/infrastructure/entities/remote_asset.entity.drift.dart';
import 'package:immich_mobile/infrastructure/repositories/db.repository.dart';
import 'package:immich_mobile/infrastructure/repositories/map.repository.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
import 'package:stream_transform/stream_transform.dart';
class TimelineMapOptions {
final LngLatBounds bounds;
final LatLngBounds bounds;
final bool onlyFavorites;
final bool includeArchived;
final bool withPartners;
+4 -4
View File
@@ -1,16 +1,16 @@
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
import 'package:openapi/api.dart';
class MapMarker {
final Geographic latLng;
final LatLng latLng;
final String assetRemoteId;
const MapMarker({required this.latLng, required this.assetRemoteId});
MapMarker copyWith({Geographic? latLng, String? assetRemoteId}) {
MapMarker copyWith({LatLng? latLng, String? assetRemoteId}) {
return MapMarker(latLng: latLng ?? this.latLng, assetRemoteId: assetRemoteId ?? this.assetRemoteId);
}
MapMarker.fromDto(MapMarkerResponseDto dto) : latLng = Geographic(lat: dto.lat, lon: dto.lon), assetRemoteId = dto.id;
MapMarker.fromDto(MapMarkerResponseDto dto) : latLng = LatLng(dto.lat, dto.lon), assetRemoteId = dto.id;
@override
String toString() => 'MapMarker(latLng: $latLng, assetRemoteId: $assetRemoteId)';
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:immich_mobile/domain/models/person.model.dart';
import 'package:immich_mobile/entities/asset.entity.dart';
import 'package:openapi/api.dart' show AssetOrder;
class SearchLocationFilter {
String? country;
@@ -221,6 +222,7 @@ class SearchFilter {
SearchDateFilter date;
SearchRatingFilter rating;
SearchDisplayFilters display;
AssetOrder? order;
// Enum
AssetType mediaType;
@@ -233,6 +235,7 @@ class SearchFilter {
this.language,
this.assetId,
this.tagIds,
this.order,
required this.people,
required this.location,
required this.camera,
@@ -279,6 +282,7 @@ class SearchFilter {
SearchDisplayFilters? display,
SearchRatingFilter? rating,
AssetType? mediaType,
AssetOrder? Function()? order,
}) {
return SearchFilter(
context: context ?? this.context,
@@ -295,12 +299,13 @@ class SearchFilter {
rating: rating ?? this.rating,
mediaType: mediaType ?? this.mediaType,
tagIds: tagIds ?? this.tagIds,
order: order != null ? order() : this.order,
);
}
@override
String toString() {
return 'SearchFilter(context: $context, filename: $filename, description: $description, language: $language, ocr: $ocr, people: $people, location: $location, tagIds: $tagIds, camera: $camera, date: $date, display: $display, rating: $rating, mediaType: $mediaType, assetId: $assetId)';
return 'SearchFilter(context: $context, filename: $filename, description: $description, language: $language, ocr: $ocr, people: $people, location: $location, tagIds: $tagIds, camera: $camera, date: $date, display: $display, rating: $rating, mediaType: $mediaType, assetId: $assetId, order: $order)';
}
@override
@@ -320,7 +325,8 @@ class SearchFilter {
other.date == date &&
other.display == display &&
other.rating == rating &&
other.mediaType == mediaType;
other.mediaType == mediaType &&
other.order == order;
}
@override
@@ -338,6 +344,7 @@ class SearchFilter {
date.hashCode ^
display.hashCode ^
rating.hashCode ^
mediaType.hashCode;
mediaType.hashCode ^
order.hashCode;
}
}
+2 -2
View File
@@ -17,7 +17,7 @@ import 'package:immich_mobile/widgets/album/album_thumbnail_card.dart';
import 'package:immich_mobile/widgets/common/immich_app_bar.dart';
import 'package:immich_mobile/widgets/common/user_avatar.dart';
import 'package:immich_mobile/widgets/map/map_thumbnail.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
@RoutePage()
class LibraryPage extends ConsumerWidget {
@@ -325,7 +325,7 @@ class PlacesCollectionCard extends StatelessWidget {
child: IgnorePointer(
child: MapThumbnail(
zoom: 8,
centre: const Geographic(lat: 21.44950, lon: -157.91959),
centre: const LatLng(21.44950, -157.91959),
showAttribution: false,
themeMode: context.isDarkTheme ? ThemeMode.dark : ThemeMode.light,
),
@@ -15,12 +15,12 @@ import 'package:immich_mobile/providers/search/search_page_state.provider.dart';
import 'package:immich_mobile/routing/router.dart';
import 'package:immich_mobile/widgets/common/search_field.dart';
import 'package:immich_mobile/widgets/map/map_thumbnail.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
@RoutePage()
class PlacesCollectionPage extends HookConsumerWidget {
const PlacesCollectionPage({super.key, this.currentLocation});
final Geographic? currentLocation;
final LatLng? currentLocation;
@override
Widget build(BuildContext context, WidgetRef ref) {
final places = ref.watch(getAllPlacesProvider);
@@ -61,7 +61,7 @@ class PlacesCollectionPage extends HookConsumerWidget {
child: MapThumbnail(
onTap: (_, __) => context.pushRoute(MapRoute(initialLocation: currentLocation)),
zoom: 8,
centre: currentLocation ?? const Geographic(lat: 21.44950, lon: -157.91959),
centre: currentLocation ?? const LatLng(21.44950, -157.91959),
showAttribution: false,
themeMode: context.isDarkTheme ? ThemeMode.dark : ThemeMode.light,
),
+128 -115
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:math';
import 'package:auto_route/auto_route.dart';
import 'package:collection/collection.dart';
@@ -11,9 +12,8 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:immich_mobile/entities/asset.entity.dart';
import 'package:immich_mobile/extensions/asyncvalue_extensions.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/extensions/latlngbounds_extension.dart';
import 'package:immich_mobile/extensions/maplibrecontroller_extensions.dart';
import 'package:immich_mobile/models/map/map_event.model.dart' as app;
import 'package:immich_mobile/models/map/map_event.model.dart';
import 'package:immich_mobile/models/map/map_marker.model.dart';
import 'package:immich_mobile/providers/asset_viewer/current_asset.provider.dart';
import 'package:immich_mobile/providers/asset_viewer/show_controls.provider.dart';
@@ -26,25 +26,25 @@ import 'package:immich_mobile/utils/immich_loading_overlay.dart';
import 'package:immich_mobile/utils/map_utils.dart';
import 'package:immich_mobile/widgets/asset_grid/asset_grid_data_structure.dart';
import 'package:immich_mobile/widgets/common/immich_toast.dart';
import 'package:immich_mobile/widgets/map/asset_marker_icon.dart';
import 'package:immich_mobile/widgets/map/map_app_bar.dart';
import 'package:immich_mobile/widgets/map/map_asset_grid.dart';
import 'package:immich_mobile/widgets/map/map_bottom_sheet.dart';
import 'package:immich_mobile/widgets/map/map_theme_override.dart';
import 'package:maplibre/maplibre.dart';
import 'package:immich_mobile/widgets/map/positioned_asset_marker_icon.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
@RoutePage()
class MapPage extends HookConsumerWidget {
const MapPage({super.key, this.initialLocation});
final Geographic? initialLocation;
final LatLng? initialLocation;
@override
Widget build(BuildContext context, WidgetRef ref) {
final mapController = useRef<MapController?>(null);
final mapController = useRef<MapLibreMapController?>(null);
final markers = useRef<List<MapMarker>>([]);
final markersInBounds = useRef<List<MapMarker>>([]);
final bottomSheetStreamController = useStreamController<app.MapEvent>();
final selectedMarker = useValueNotifier<MapMarker?>(null);
final bottomSheetStreamController = useStreamController<MapEvent>();
final selectedMarker = useValueNotifier<_AssetMarkerMeta?>(null);
final assetsDebouncer = useDebouncer();
final layerDebouncer = useDebouncer(interval: const Duration(seconds: 1));
final isLoading = useProcessingOverlay();
@@ -55,17 +55,19 @@ class MapPage extends HookConsumerWidget {
// updates the markersInBounds value with the map markers that are visible in the current
// map camera bounds
void updateAssetsInBounds() {
if (mapController.value == null) return;
Future<void> updateAssetsInBounds() async {
// Guard map not created
if (mapController.value == null) {
return;
}
final bounds = mapController.value!.getVisibleRegion();
final bounds = await mapController.value!.getVisibleRegion();
final inBounds = markers.value
.where((m) => bounds.contains(Geographic(lat: m.latLng.lat, lon: m.latLng.lon)))
.where((m) => bounds.contains(LatLng(m.latLng.latitude, m.latLng.longitude)))
.toList();
// Notify bottom sheet to update asset grid only when there are new assets
if (markersInBounds.value.length != inBounds.length) {
bottomSheetStreamController.add(app.MapAssetsInBoundsUpdated(inBounds.map((e) => e.assetRemoteId).toList()));
bottomSheetStreamController.add(MapAssetsInBoundsUpdated(inBounds.map((e) => e.assetRemoteId).toList()));
}
markersInBounds.value = inBounds;
}
@@ -97,67 +99,57 @@ class MapPage extends HookConsumerWidget {
// Refetch markers when map state is changed
ref.listen(mapStateNotifierProvider, (_, current) {
if (!current.shouldRefetchMarkers) return;
markerDebouncer.run(() {
ref.invalidate(mapMarkersProvider);
// Reset marker
selectedMarker.value = null;
loadMarkers();
ref.read(mapStateNotifierProvider.notifier).setRefetchMarkers(false);
});
if (current.shouldRefetchMarkers) {
markerDebouncer.run(() {
ref.invalidate(mapMarkersProvider);
// Reset marker
selectedMarker.value = null;
loadMarkers();
ref.read(mapStateNotifierProvider.notifier).setRefetchMarkers(false);
});
}
});
void selectMarker(MapMarker marker) {
selectedMarker.value = marker;
// updates the selected markers position based on the current map camera
Future<void> updateAssetMarkerPosition(MapMarker marker, {bool shouldAnimate = true}) async {
final assetPoint = await mapController.value!.toScreenLocation(marker.latLng);
selectedMarker.value = _AssetMarkerMeta(point: assetPoint, marker: marker, shouldAnimate: shouldAnimate);
(assetPoint, marker, shouldAnimate);
}
// finds the nearest asset marker from the tap point and store it as the selectedMarker
void onMarkerClicked(Offset point) {
if (mapController.value == null) return;
final features = mapController.value!.featuresInRect(
Rect.fromCircle(center: point, radius: 50),
layerIds: [MapUtils.defaultHeatMapLayerId],
Future<void> onMarkerClicked(Point<double> point, LatLng _) async {
// Guard map not created
if (mapController.value == null) {
return;
}
final latlngBound = await mapController.value!.getBoundsFromPoint(point, 50);
final marker = markersInBounds.value.firstWhereOrNull(
(m) => latlngBound.contains(LatLng(m.latLng.latitude, m.latLng.longitude)),
);
final featureId = features.firstOrNull?.id?.toString();
final marker = featureId != null
? markersInBounds.value.firstWhereOrNull((m) => m.assetRemoteId == featureId)
: null;
if (marker != null) {
selectMarker(marker);
return;
await updateAssetMarkerPosition(marker);
} else {
// If no asset was previously selected and no new asset is available, close the bottom sheet
if (selectedMarker.value == null) {
bottomSheetStreamController.add(const MapCloseBottomSheet());
}
selectedMarker.value = null;
}
if (selectedMarker.value == null) {
// If no asset was previously selected and no new asset is available,
// close the bottom sheet.
bottomSheetStreamController.add(const app.MapCloseBottomSheet());
return;
}
selectedMarker.value = null;
}
void onMapCreated(MapController controller) {
void onMapCreated(MapLibreMapController controller) async {
mapController.value = controller;
}
void onMapEvent(MapEvent event) {
switch (event) {
case MapEventClick():
onMarkerClicked(event.screenPoint);
case MapEventCameraIdle():
assetsDebouncer.run(updateAssetsInBounds);
default:
}
controller.addListener(() {
if (controller.isCameraMoving && selectedMarker.value != null) {
updateAssetMarkerPosition(selectedMarker.value!.marker, shouldAnimate: false);
}
});
}
Future<void> onMarkerTapped() async {
final assetId = selectedMarker.value?.assetRemoteId;
final assetId = selectedMarker.value?.marker.assetRemoteId;
if (assetId == null) {
return;
}
@@ -179,10 +171,14 @@ class MapPage extends HookConsumerWidget {
/// BOTTOM SHEET CALLBACKS
Future<void> onMapMoved() async {
assetsDebouncer.run(updateAssetsInBounds);
}
void onBottomSheetScrolled(String assetRemoteId) {
final assetMarker = markersInBounds.value.firstWhereOrNull((m) => m.assetRemoteId == assetRemoteId);
if (assetMarker != null) {
selectMarker(assetMarker);
updateAssetMarkerPosition(assetMarker);
}
}
@@ -191,11 +187,10 @@ class MapPage extends HookConsumerWidget {
if (mapController.value != null && assetMarker != null) {
// Offset the latitude a little to show the marker just above the viewports center
final offset = context.isMobile ? 0.02 : 0;
final latlng = Geographic(lat: assetMarker.latLng.lat - offset, lon: assetMarker.latLng.lon);
final latlng = LatLng(assetMarker.latLng.latitude - offset, assetMarker.latLng.longitude);
mapController.value!.animateCamera(
center: latlng,
zoom: mapZoomToAssetLevel,
nativeDuration: Durations.extralong2,
CameraUpdate.newLatLngZoom(latlng, mapZoomToAssetLevel),
duration: const Duration(milliseconds: 800),
);
}
}
@@ -216,9 +211,8 @@ class MapPage extends HookConsumerWidget {
if (mapController.value != null && location != null) {
await mapController.value!.animateCamera(
center: Geographic(lat: location.latitude, lon: location.longitude),
zoom: mapZoomToAssetLevel,
nativeDuration: Durations.extralong2,
CameraUpdate.newLatLngZoom(LatLng(location.latitude, location.longitude), mapZoomToAssetLevel),
duration: const Duration(milliseconds: 800),
);
}
}
@@ -240,8 +234,9 @@ class MapPage extends HookConsumerWidget {
style: style,
selectedMarker: selectedMarker,
onMapCreated: onMapCreated,
onMapEvent: onMapEvent,
onStyleLoaded: (_) => reloadLayers(),
onMapMoved: onMapMoved,
onMapClicked: onMarkerClicked,
onStyleLoaded: reloadLayers,
onMarkerTapped: onMarkerTapped,
),
// Should be a part of the body and not scaffold::bottomsheet for the
@@ -271,8 +266,9 @@ class MapPage extends HookConsumerWidget {
style: style,
selectedMarker: selectedMarker,
onMapCreated: onMapCreated,
onMapEvent: onMapEvent,
onStyleLoaded: (_) => reloadLayers(),
onMapMoved: onMapMoved,
onMapClicked: onMarkerClicked,
onStyleLoaded: reloadLayers,
onMarkerTapped: onMarkerTapped,
),
Positioned(
@@ -306,19 +302,32 @@ class MapPage extends HookConsumerWidget {
}
}
class _AssetMarkerMeta {
final Point<num> point;
final MapMarker marker;
final bool shouldAnimate;
const _AssetMarkerMeta({required this.point, required this.marker, required this.shouldAnimate});
@override
String toString() => '_AssetMarkerMeta(point: $point, marker: $marker, shouldAnimate: $shouldAnimate)';
}
class _MapWithMarker extends StatelessWidget {
final AsyncValue<String> style;
final void Function(MapController) onMapCreated;
final void Function(MapEvent) onMapEvent;
final void Function(StyleController) onStyleLoaded;
final MapCreatedCallback onMapCreated;
final OnCameraIdleCallback onMapMoved;
final OnMapClickCallback onMapClicked;
final OnStyleLoadedCallback onStyleLoaded;
final Function()? onMarkerTapped;
final ValueNotifier<MapMarker?> selectedMarker;
final Geographic? initialLocation;
final ValueNotifier<_AssetMarkerMeta?> selectedMarker;
final LatLng? initialLocation;
const _MapWithMarker({
required this.style,
required this.onMapCreated,
required this.onMapEvent,
required this.onMapMoved,
required this.onMapClicked,
required this.onStyleLoaded,
required this.selectedMarker,
this.onMarkerTapped,
@@ -327,44 +336,48 @@ class _MapWithMarker extends StatelessWidget {
@override
Widget build(BuildContext context) {
return style.widgetWhen(
onData: (style) => MapLibreMap(
options: MapOptions(
initCenter: initialLocation ?? const Geographic(lat: 0, lon: 0),
initZoom: initialLocation != null ? 12 : 0,
initStyle: style,
gestures: const MapGestures.all(pitch: false, rotate: false),
return LayoutBuilder(
builder: (ctx, constraints) => SizedBox(
height: constraints.maxHeight,
width: constraints.maxWidth,
child: Stack(
children: [
style.widgetWhen(
onData: (style) => MapLibreMap(
attributionButtonMargins: const Point(8, kToolbarHeight),
initialCameraPosition: CameraPosition(
target: initialLocation ?? const LatLng(0, 0),
zoom: initialLocation != null ? 12 : 0,
),
styleString: style,
// This is needed to update the selectedMarker's position on map camera updates
// The changes are notified through the mapController ValueListener which is added in [onMapCreated]
trackCameraPosition: true,
onMapCreated: onMapCreated,
onCameraIdle: onMapMoved,
onMapClick: onMapClicked,
onStyleLoadedCallback: onStyleLoaded,
tiltGesturesEnabled: false,
dragEnabled: false,
myLocationEnabled: false,
attributionButtonPosition: AttributionButtonPosition.topRight,
rotateGesturesEnabled: false,
),
),
ValueListenableBuilder(
valueListenable: selectedMarker,
builder: (ctx, value, _) => value != null
? PositionedAssetMarkerIcon(
point: value.point,
assetRemoteId: value.marker.assetRemoteId,
assetThumbhash: '',
durationInMilliseconds: value.shouldAnimate ? 100 : 0,
onTap: onMarkerTapped,
)
: const SizedBox.shrink(),
),
],
),
onMapCreated: onMapCreated,
onStyleLoaded: onStyleLoaded,
onEvent: onMapEvent,
children: [
ValueListenableBuilder<MapMarker?>(
valueListenable: selectedMarker,
builder: (ctx, marker, _) => marker != null
? WidgetLayer(
markers: [
Marker(
point: marker.latLng,
size: const Size(100, 100),
alignment: Alignment.bottomCenter,
child: GestureDetector(
onTap: () => onMarkerTapped?.call(),
child: SizedBox.square(
dimension: 100,
child: AssetMarkerIcon(
id: marker.assetRemoteId,
thumbhash: '',
key: Key(marker.assetRemoteId),
),
),
),
),
],
)
: const SizedBox.shrink(),
),
],
),
);
}
@@ -1,3 +1,5 @@
import 'dart:math';
import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
@@ -5,34 +7,36 @@ import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:immich_mobile/extensions/asyncvalue_extensions.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/extensions/maplibrecontroller_extensions.dart';
import 'package:immich_mobile/utils/map_utils.dart';
import 'package:immich_mobile/widgets/map/map_theme_override.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
@RoutePage()
class MapLocationPickerPage extends HookConsumerWidget {
final Geographic initialLatLng;
final LatLng initialLatLng;
const MapLocationPickerPage({super.key, this.initialLatLng = const Geographic(lat: 0, lon: 0)});
const MapLocationPickerPage({super.key, this.initialLatLng = const LatLng(0, 0)});
@override
Widget build(BuildContext context, WidgetRef ref) {
final selectedLatLng = useValueNotifier<Geographic>(initialLatLng);
final currentLatLng = useValueListenable(selectedLatLng);
final controller = useRef<MapController?>(null);
final selectedLatLng = useValueNotifier<LatLng>(initialLatLng);
final controller = useRef<MapLibreMapController?>(null);
final marker = useRef<Symbol?>(null);
Future<void> onStyleLoaded(StyleController style) async {
await style.addImageFromAssets(id: 'mapMarker', asset: 'assets/location-pin.png');
Future<void> onStyleLoaded() async {
marker.value = await controller.value?.addMarkerAtLatLng(initialLatLng);
}
void onEvent(MapEvent event) {
if (event is! MapEventClick) return;
selectedLatLng.value = event.point;
controller.value?.animateCamera(center: event.point);
Future<void> onMapClick(Point<num> _, LatLng centre) async {
selectedLatLng.value = centre;
await controller.value?.animateCamera(CameraUpdate.newLatLng(centre));
if (marker.value != null) {
await controller.value?.updateSymbol(marker.value!, SymbolOptions(geometry: centre));
}
}
void onClose([Geographic? selected]) {
void onClose([LatLng? selected]) {
context.maybePop(selected);
}
@@ -43,9 +47,9 @@ class MapLocationPickerPage extends HookConsumerWidget {
return;
}
var currentLatLng = Geographic(lat: currentLocation.latitude, lon: currentLocation.longitude);
var currentLatLng = LatLng(currentLocation.latitude, currentLocation.longitude);
selectedLatLng.value = currentLatLng;
await controller.value?.animateCamera(center: currentLatLng, zoom: 12);
await controller.value?.animateCamera(CameraUpdate.newLatLngZoom(currentLatLng, 12));
}
return MapThemeOverride(
@@ -62,24 +66,18 @@ class MapLocationPickerPage extends HookConsumerWidget {
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(40), bottomRight: Radius.circular(40)),
),
child: MapLibreMap(
options: MapOptions(
initCenter: initialLatLng,
initZoom: (initialLatLng.lat == 0 && initialLatLng.lon == 0) ? 1 : 12,
initStyle: style,
gestures: const MapGestures.all(pitch: false),
initialCameraPosition: CameraPosition(
target: initialLatLng,
zoom: (initialLatLng.latitude == 0 && initialLatLng.longitude == 0) ? 1 : 12,
),
styleString: style,
onMapCreated: (mapController) => controller.value = mapController,
onStyleLoaded: onStyleLoaded,
onEvent: onEvent,
layers: [
MarkerLayer(
points: [Feature(geometry: Point(currentLatLng))],
iconImage: 'mapMarker',
iconSize: 0.15,
iconAnchor: IconAnchor.bottom,
iconAllowOverlap: true,
),
],
onStyleLoadedCallback: onStyleLoaded,
onMapClick: onMapClick,
dragEnabled: false,
tiltGesturesEnabled: false,
myLocationEnabled: false,
attributionButtonMargins: const Point(20, 15),
),
),
),
@@ -119,7 +117,7 @@ class _AppBar extends StatelessWidget implements PreferredSizeWidget {
}
class _BottomBar extends StatelessWidget {
final ValueNotifier<Geographic> selectedLatLng;
final ValueNotifier<LatLng> selectedLatLng;
final Function() onUseLocation;
final Function() onGetCurrentLocation;
@@ -142,7 +140,8 @@ class _BottomBar extends StatelessWidget {
const SizedBox(width: 15),
ValueListenableBuilder(
valueListenable: selectedLatLng,
builder: (_, value, __) => Text("${value.lat.toStringAsFixed(4)}, ${value.lon.toStringAsFixed(4)}"),
builder: (_, value, __) =>
Text("${value.latitude.toStringAsFixed(4)}, ${value.longitude.toStringAsFixed(4)}"),
),
],
),
+56 -3
View File
@@ -11,6 +11,7 @@ import 'package:immich_mobile/entities/asset.entity.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/models/search/search_filter.model.dart';
import 'package:immich_mobile/providers/search/paginated_search.provider.dart';
import 'package:immich_mobile/widgets/asset_grid/asset_grid_data_structure.dart';
import 'package:immich_mobile/providers/search/search_input_focus.provider.dart';
import 'package:immich_mobile/routing/router.dart';
import 'package:immich_mobile/widgets/asset_grid/multiselect_grid.dart';
@@ -23,6 +24,8 @@ import 'package:immich_mobile/widgets/search/search_filter/media_type_picker.dar
import 'package:immich_mobile/widgets/search/search_filter/people_picker.dart';
import 'package:immich_mobile/widgets/search/search_filter/search_filter_chip.dart';
import 'package:immich_mobile/widgets/search/search_filter/search_filter_utils.dart';
import 'package:immich_mobile/widgets/search/search_filter/sort_order_picker.dart';
import 'package:openapi/api.dart' show AssetOrder;
@RoutePage()
class SearchPage extends HookConsumerWidget {
@@ -56,6 +59,7 @@ class SearchPage extends HookConsumerWidget {
final locationCurrentFilterWidget = useState<Widget?>(null);
final mediaTypeCurrentFilterWidget = useState<Widget?>(null);
final displayOptionCurrentFilterWidget = useState<Widget?>(null);
final sortOrderCurrentFilterWidget = useState<Widget?>(null);
final isSearching = useState(false);
@@ -78,6 +82,8 @@ class SearchPage extends HookConsumerWidget {
}
isSearching.value = true;
ref.read(searchGroupByProvider.notifier).state =
filter.value.order != null ? GroupAssetsBy.day : GroupAssetsBy.none;
ref.watch(paginatedSearchProvider.notifier).clear();
final hasResult = await ref.watch(paginatedSearchProvider.notifier).search(filter.value);
@@ -387,6 +393,37 @@ class SearchPage extends HookConsumerWidget {
);
}
// SORT ORDER
showSortOrderPicker() {
handleOnSelect(AssetOrder? value) {
filter.value = filter.value.copyWith(order: () => value);
if (value == null) {
sortOrderCurrentFilterWidget.value = null;
} else if (value == AssetOrder.desc) {
sortOrderCurrentFilterWidget.value = Text('newest_first'.tr(), style: context.textTheme.labelLarge);
} else {
sortOrderCurrentFilterWidget.value = Text('oldest_first'.tr(), style: context.textTheme.labelLarge);
}
}
handleClear() {
filter.value = filter.value.copyWith(order: () => null);
sortOrderCurrentFilterWidget.value = null;
search();
}
showFilterBottomSheet(
context: context,
child: FilterBottomSheetScaffold(
title: 'search_filter_sort_order_title'.tr(),
onSearch: search,
onClear: handleClear,
child: SortOrderPicker(onSelect: handleOnSelect, order: filter.value.order),
),
);
}
handleTextSubmitted(String value) {
switch (textSearchType.value) {
case TextSearchType.context:
@@ -594,6 +631,12 @@ class SearchPage extends HookConsumerWidget {
label: 'search_filter_display_options'.tr(),
currentFilter: displayOptionCurrentFilterWidget.value,
),
SearchFilterChip(
icon: Icons.sort_outlined,
onTap: showSortOrderPicker,
label: 'search_filter_sort_order'.tr(),
currentFilter: sortOrderCurrentFilterWidget.value,
),
],
),
),
@@ -601,7 +644,11 @@ class SearchPage extends HookConsumerWidget {
if (isSearching.value)
const Expanded(child: Center(child: CircularProgressIndicator()))
else
SearchResultGrid(onScrollEnd: loadMoreSearchResult, isSearching: isSearching.value),
SearchResultGrid(
onScrollEnd: loadMoreSearchResult,
isSearching: isSearching.value,
dragScrollLabelEnabled: filter.value.order != null,
),
],
),
);
@@ -611,8 +658,14 @@ class SearchPage extends HookConsumerWidget {
class SearchResultGrid extends StatelessWidget {
final VoidCallback onScrollEnd;
final bool isSearching;
final bool dragScrollLabelEnabled;
const SearchResultGrid({super.key, required this.onScrollEnd, this.isSearching = false});
const SearchResultGrid({
super.key,
required this.onScrollEnd,
this.isSearching = false,
this.dragScrollLabelEnabled = false,
});
@override
Widget build(BuildContext context) {
@@ -640,7 +693,7 @@ class SearchResultGrid extends StatelessWidget {
editEnabled: true,
favoriteEnabled: true,
stackEnabled: false,
dragScrollLabelEnabled: false,
dragScrollLabelEnabled: dragScrollLabelEnabled,
emptyIndicator: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: !isSearching ? const SearchEmptyContent() : const SizedBox.shrink(),
@@ -17,7 +17,7 @@ import 'package:immich_mobile/routing/router.dart';
import 'package:immich_mobile/utils/image_url_builder.dart';
import 'package:immich_mobile/widgets/common/immich_sliver_app_bar.dart';
import 'package:immich_mobile/widgets/map/map_thumbnail.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
@RoutePage()
class DriftLibraryPage extends ConsumerWidget {
@@ -230,7 +230,7 @@ class _PlacesCollectionCard extends StatelessWidget {
child: IgnorePointer(
child: MapThumbnail(
zoom: 8,
centre: const Geographic(lat: 21.44950, lon: -157.91959),
centre: const LatLng(21.44950, -157.91959),
showAttribution: false,
themeMode: context.isDarkTheme ? ThemeMode.dark : ThemeMode.light,
),
@@ -3,11 +3,11 @@ import 'package:flutter/material.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/presentation/widgets/map/map.widget.dart';
import 'package:immich_mobile/presentation/widgets/map/map_settings_sheet.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
@RoutePage()
class DriftMapPage extends StatelessWidget {
final Geographic? initialLocation;
final LatLng? initialLocation;
const DriftMapPage({super.key, this.initialLocation});
@@ -10,13 +10,13 @@ import 'package:immich_mobile/providers/infrastructure/asset.provider.dart';
import 'package:immich_mobile/routing/router.dart';
import 'package:immich_mobile/widgets/common/search_field.dart';
import 'package:immich_mobile/widgets/map/map_thumbnail.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
@RoutePage()
class DriftPlacePage extends StatelessWidget {
const DriftPlacePage({super.key, this.currentLocation});
final Geographic? currentLocation;
final LatLng? currentLocation;
@override
Widget build(BuildContext context) {
@@ -82,7 +82,7 @@ class _Map extends StatelessWidget {
const _Map({required this.search, this.currentLocation});
final ValueNotifier<String?> search;
final Geographic? currentLocation;
final LatLng? currentLocation;
@override
Widget build(BuildContext context) {
@@ -96,7 +96,7 @@ class _Map extends StatelessWidget {
child: MapThumbnail(
onTap: (_, __) => context.pushRoute(DriftMapRoute(initialLocation: currentLocation)),
zoom: 8,
centre: currentLocation ?? const Geographic(lat: 21.44950, lon: -157.91959),
centre: currentLocation ?? const LatLng(21.44950, -157.91959),
showAttribution: false,
themeMode: context.isDarkTheme ? ThemeMode.dark : ThemeMode.light,
),
@@ -10,7 +10,7 @@ import 'package:immich_mobile/presentation/widgets/asset_viewer/sheet_tile.widge
import 'package:immich_mobile/providers/infrastructure/action.provider.dart';
import 'package:immich_mobile/providers/infrastructure/asset_viewer/asset.provider.dart';
import 'package:immich_mobile/widgets/asset_viewer/detail_panel/exif_map.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class LocationDetails extends ConsumerStatefulWidget {
const LocationDetails({super.key});
@@ -20,7 +20,7 @@ class LocationDetails extends ConsumerStatefulWidget {
}
class _LocationDetailsState extends ConsumerState<LocationDetails> {
MapController? _mapController;
MapLibreMapController? _mapController;
String? _getLocationName(ExifInfo? exifInfo) {
if (exifInfo == null) {
@@ -36,16 +36,14 @@ class _LocationDetailsState extends ConsumerState<LocationDetails> {
return null;
}
void _onMapCreated(MapController controller) {
void _onMapCreated(MapLibreMapController controller) {
_mapController = controller;
}
void _onExifChanged(AsyncValue<ExifInfo?>? previous, AsyncValue<ExifInfo?> current) {
final currentExif = current.valueOrNull;
if (currentExif != null && currentExif.hasCoordinates) {
_mapController?.moveCamera(
center: Geographic(lat: currentExif.latitude!, lon: currentExif.longitude!),
);
_mapController?.moveCamera(CameraUpdate.newLatLng(LatLng(currentExif.latitude!, currentExif.longitude!)));
}
}
@@ -7,11 +7,11 @@ import 'package:immich_mobile/providers/app_settings.provider.dart';
import 'package:immich_mobile/providers/infrastructure/map.provider.dart';
import 'package:immich_mobile/providers/map/map_state.provider.dart';
import 'package:immich_mobile/services/app_settings.service.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class MapState {
final ThemeMode themeMode;
final LngLatBounds bounds;
final LatLngBounds bounds;
final bool onlyFavorites;
final bool includeArchived;
final bool withPartners;
@@ -35,7 +35,7 @@ class MapState {
int get hashCode => bounds.hashCode;
MapState copyWith({
LngLatBounds? bounds,
LatLngBounds? bounds,
ThemeMode? themeMode,
bool? onlyFavorites,
bool? includeArchived,
@@ -64,7 +64,7 @@ class MapState {
class MapStateNotifier extends Notifier<MapState> {
MapStateNotifier();
bool setBounds(LngLatBounds bounds) {
bool setBounds(LatLngBounds bounds) {
if (state.bounds == bounds) {
return false;
}
@@ -113,14 +113,14 @@ class MapStateNotifier extends Notifier<MapState> {
includeArchived: appSettingsService.getSetting(AppSettingsEnum.mapIncludeArchived),
withPartners: appSettingsService.getSetting(AppSettingsEnum.mapwithPartners),
relativeDays: appSettingsService.getSetting(AppSettingsEnum.mapRelativeDate),
bounds: const LngLatBounds(longitudeWest: 0, longitudeEast: 0, latitudeSouth: 0, latitudeNorth: 0),
bounds: LatLngBounds(northeast: const LatLng(0, 0), southwest: const LatLng(0, 0)),
);
}
}
// This provider watches the markers from the map service and serves the markers.
// It should be used only after the map service provider is overridden
final mapMarkerProvider = FutureProvider.family<Map<String, dynamic>, LngLatBounds?>((ref, bounds) async {
final mapMarkerProvider = FutureProvider.family<Map<String, dynamic>, LatLngBounds?>((ref, bounds) async {
final mapService = ref.watch(mapServiceProvider);
final markers = await mapService.getMarkers(bounds);
final features = List.filled(markers.length, const <String, dynamic>{});
@@ -131,7 +131,7 @@ final mapMarkerProvider = FutureProvider.family<Map<String, dynamic>, LngLatBoun
'id': marker.assetId,
'geometry': {
'type': 'Point',
'coordinates': [marker.location.lon, marker.location.lat],
'coordinates': [marker.location.longitude, marker.location.latitude],
},
};
}
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
@@ -19,10 +20,27 @@ import 'package:immich_mobile/utils/async_mutex.dart';
import 'package:immich_mobile/utils/debounce.dart';
import 'package:immich_mobile/widgets/common/immich_toast.dart';
import 'package:immich_mobile/widgets/map/map_theme_override.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class CustomSourceProperties implements SourceProperties {
final Map<String, dynamic> data;
const CustomSourceProperties({required this.data});
@override
Map<String, dynamic> toJson() {
return {
"type": "geojson",
"data": data,
// "cluster": true,
// "clusterRadius": 1,
// "clusterMinPoints": 5,
// "tolerance": 0.1,
};
}
}
class DriftMap extends ConsumerStatefulWidget {
final Geographic? initialLocation;
final LatLng? initialLocation;
const DriftMap({super.key, this.initialLocation});
@@ -31,7 +49,7 @@ class DriftMap extends ConsumerStatefulWidget {
}
class _DriftMapState extends ConsumerState<DriftMap> {
MapController? mapController;
MapLibreMapController? mapController;
final _reloadMutex = AsyncMutex();
final _debouncer = Debouncer(interval: const Duration(milliseconds: 500), maxWaitTime: const Duration(seconds: 2));
final ValueNotifier<double> bottomSheetOffset = ValueNotifier(0.25);
@@ -51,7 +69,7 @@ class _DriftMapState extends ConsumerState<DriftMap> {
super.dispose();
}
void onMapCreated(MapController controller) {
void onMapCreated(MapLibreMapController controller) {
mapController = controller;
}
@@ -63,23 +81,43 @@ class _DriftMapState extends ConsumerState<DriftMap> {
return;
}
await controller.style!.addSource(
GeoJsonSource(id: MapUtils.defaultSourceId, data: jsonEncode({'type': 'FeatureCollection', 'features': []})),
await controller.addSource(
MapUtils.defaultSourceId,
const CustomSourceProperties(data: {'type': 'FeatureCollection', 'features': []}),
);
await controller.style!.addLayer(
const HeatmapStyleLayer(
id: MapUtils.defaultHeatMapLayerId,
sourceId: MapUtils.defaultSourceId,
paint: MapUtils.defaultHeatmapLayerPaint,
),
);
if (Platform.isAndroid) {
await controller.addCircleLayer(
MapUtils.defaultSourceId,
MapUtils.defaultHeatMapLayerId,
const CircleLayerProperties(
circleRadius: 10,
circleColor: "rgba(150,86,34,0.7)",
circleBlur: 1.0,
circleOpacity: 0.7,
circleStrokeWidth: 0.1,
circleStrokeColor: "rgba(203,46,19,0.5)",
circleStrokeOpacity: 0.7,
),
);
}
if (Platform.isIOS) {
await controller.addHeatmapLayer(
MapUtils.defaultSourceId,
MapUtils.defaultHeatMapLayerId,
MapUtils.defaultHeatmapLayerProperties,
);
}
_debouncer.run(() => setBounds(forceReload: true));
controller.addListener(onMapMoved);
}
void onMapEvent(MapEvent event) {
if (event is! MapEventCameraIdle || !mounted) return;
void onMapMoved() {
if (mapController!.isCameraMoving || !mounted) {
return;
}
_debouncer.run(setBounds);
}
@@ -98,7 +136,7 @@ class _DriftMapState extends ConsumerState<DriftMap> {
return;
}
final bounds = controller.getVisibleRegion();
final bounds = await controller.getVisibleRegion();
unawaited(
_reloadMutex.run(() async {
if (mounted && (ref.read(mapStateProvider.notifier).setBounds(bounds) || forceReload)) {
@@ -115,7 +153,7 @@ class _DriftMapState extends ConsumerState<DriftMap> {
return;
}
await controller.style!.updateGeoJsonSource(id: MapUtils.defaultSourceId, data: jsonEncode(markers));
await controller.setGeoJsonSource(MapUtils.defaultSourceId, markers);
}
Future<void> onZoomToLocation() async {
@@ -135,9 +173,8 @@ class _DriftMapState extends ConsumerState<DriftMap> {
final controller = mapController;
if (controller != null && location != null) {
await controller.animateCamera(
center: Geographic(lat: location.latitude, lon: location.longitude),
zoom: MapUtils.mapZoomToAssetLevel,
nativeDuration: Durations.extralong2,
CameraUpdate.newLatLngZoom(LatLng(location.latitude, location.longitude), MapUtils.mapZoomToAssetLevel),
duration: const Duration(milliseconds: 800),
);
}
}
@@ -146,12 +183,7 @@ class _DriftMapState extends ConsumerState<DriftMap> {
Widget build(BuildContext context) {
return Stack(
children: [
_Map(
initialLocation: widget.initialLocation,
onMapCreated: onMapCreated,
onMapReady: onMapReady,
onMapEvent: onMapEvent,
),
_Map(initialLocation: widget.initialLocation, onMapCreated: onMapCreated, onMapReady: onMapReady),
_DynamicBottomSheet(bottomSheetOffset: bottomSheetOffset),
_DynamicMyLocationButton(onZoomToLocation: onZoomToLocation, bottomSheetOffset: bottomSheetOffset),
],
@@ -160,13 +192,13 @@ class _DriftMapState extends ConsumerState<DriftMap> {
}
class _Map extends StatelessWidget {
final Geographic? initialLocation;
final LatLng? initialLocation;
const _Map({this.initialLocation, required this.onMapCreated, required this.onMapReady, required this.onMapEvent});
const _Map({this.initialLocation, required this.onMapCreated, required this.onMapReady});
final MapCreatedCallback onMapCreated;
final void Function(MapController) onMapCreated;
final VoidCallback onMapReady;
final void Function(MapEvent) onMapEvent;
@override
Widget build(BuildContext context) {
@@ -174,15 +206,16 @@ class _Map extends StatelessWidget {
return MapThemeOverride(
mapBuilder: (style) => style.widgetWhen(
onData: (style) => MapLibreMap(
options: MapOptions(
initCenter: initialLocation ?? const Geographic(lat: 0, lon: 0),
initZoom: initialLocation == null ? 0 : MapUtils.mapZoomToAssetLevel,
initStyle: style,
gestures: const MapGestures.all(rotate: false),
),
initialCameraPosition: initialLocation == null
? const CameraPosition(target: LatLng(0, 0), zoom: 0)
: CameraPosition(target: initialLocation, zoom: MapUtils.mapZoomToAssetLevel),
compassEnabled: false,
rotateGesturesEnabled: false,
styleString: style,
onMapCreated: onMapCreated,
onStyleLoaded: (_) => onMapReady(),
onEvent: onMapEvent,
onStyleLoadedCallback: onMapReady,
attributionButtonPosition: AttributionButtonPosition.topRight,
attributionButtonMargins: const Point(8, kToolbarHeight),
),
),
);
@@ -5,6 +5,7 @@ import 'package:geolocator/geolocator.dart';
import 'package:immich_mobile/extensions/translate_extensions.dart';
import 'package:immich_mobile/widgets/common/confirm_dialog.dart';
import 'package:logging/logging.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class MapUtils {
static final Logger _logger = Logger("MapUtils");
@@ -12,37 +13,49 @@ class MapUtils {
static const mapZoomToAssetLevel = 12.0;
static const defaultSourceId = 'asset-map-markers';
static const defaultHeatMapLayerId = 'asset-heatmap-layer';
static const defaultHeatmapLayerPaint = <String, Object>{
'heatmap-color': [
'interpolate',
['linear'],
['heatmap-density'],
static var markerCompleter = Completer()..complete();
static const defaultCircleLayerLayerProperties = CircleLayerProperties(
circleRadius: 10,
circleColor: "rgba(150,86,34,0.7)",
circleBlur: 1.0,
circleOpacity: 0.7,
circleStrokeWidth: 0.1,
circleStrokeColor: "rgba(203,46,19,0.5)",
circleStrokeOpacity: 0.7,
);
static const defaultHeatmapLayerProperties = HeatmapLayerProperties(
heatmapColor: [
Expressions.interpolate,
["linear"],
["heatmap-density"],
0.0,
'rgba(103,58,183,0.0)',
"rgba(103,58,183,0.0)",
0.3,
'rgb(103,58,183)',
"rgb(103,58,183)",
0.5,
'rgb(33,149,243)',
"rgb(33,149,243)",
0.7,
'rgb(76,175,79)',
"rgb(76,175,79)",
0.95,
'rgb(255,235,59)',
"rgb(255,235,59)",
1.0,
'rgb(255,86,34)',
"rgb(255,86,34)",
],
'heatmap-intensity': [
'interpolate',
['linear'],
['zoom'],
heatmapIntensity: [
Expressions.interpolate,
["linear"],
[Expressions.zoom],
0,
0.5,
9,
2,
],
'heatmap-radius': [
'interpolate',
['linear'],
['zoom'],
heatmapRadius: [
Expressions.interpolate,
["linear"],
[Expressions.zoom],
0,
4,
4,
@@ -50,8 +63,8 @@ class MapUtils {
9,
16,
],
'heatmap-opacity': 0.7,
};
heatmapOpacity: 0.7,
);
static Future<(Position?, LocationPermission?)> checkPermAndGetLocation({
required BuildContext context,
@@ -8,6 +8,8 @@ import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'paginated_search.provider.g.dart';
final searchGroupByProvider = StateProvider<GroupAssetsBy>((ref) => GroupAssetsBy.none);
final paginatedSearchProvider = StateNotifierProvider<PaginatedSearchNotifier, SearchResult>(
(ref) => PaginatedSearchNotifier(ref.watch(searchServiceProvider)),
);
@@ -41,6 +43,7 @@ class PaginatedSearchNotifier extends StateNotifier<SearchResult> {
@riverpod
Future<RenderList> paginatedSearchRenderList(Ref ref) {
final result = ref.watch(paginatedSearchProvider);
final groupBy = ref.watch(searchGroupByProvider);
final timelineService = ref.watch(timelineServiceProvider);
return timelineService.getTimelineFromAssets(result.assets, GroupAssetsBy.none);
return timelineService.getTimelineFromAssets(result.assets, groupBy);
}
@@ -7,7 +7,7 @@ part of 'paginated_search.provider.dart';
// **************************************************************************
String _$paginatedSearchRenderListHash() =>
r'22d715ff7864e5a946be38322ce7813616f899c2';
r'bb1ea9153b2a186778420426f1fb1add6d6a9140';
/// See also [paginatedSearchRenderList].
@ProviderFor(paginatedSearchRenderList)
@@ -5,7 +5,7 @@ import 'package:immich_mobile/domain/models/stack.model.dart';
import 'package:immich_mobile/entities/asset.entity.dart';
import 'package:immich_mobile/providers/api.provider.dart';
import 'package:immich_mobile/repositories/api.repository.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
import 'package:openapi/api.dart';
final assetApiRepositoryProvider = Provider(
@@ -62,8 +62,8 @@ class AssetApiRepository extends ApiRepository {
return _api.updateAssets(AssetBulkUpdateDto(ids: ids, isFavorite: isFavorite));
}
Future<void> updateLocation(List<String> ids, Geographic location) async {
return _api.updateAssets(AssetBulkUpdateDto(ids: ids, latitude: location.lat, longitude: location.lon));
Future<void> updateLocation(List<String> ids, LatLng location) async {
return _api.updateAssets(AssetBulkUpdateDto(ids: ids, latitude: location.latitude, longitude: location.longitude));
}
Future<void> updateDateTime(List<String> ids, DateTime dateTime) async {
+1 -1
View File
@@ -123,7 +123,7 @@ import 'package:immich_mobile/services/api.service.dart';
import 'package:immich_mobile/services/local_auth.service.dart';
import 'package:immich_mobile/services/secure_storage.service.dart';
import 'package:immich_mobile/widgets/asset_grid/asset_grid_data_structure.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
part 'router.gr.dart';
+16 -19
View File
@@ -1226,7 +1226,7 @@ class DriftLockedFolderRoute extends PageRouteInfo<void> {
class DriftMapRoute extends PageRouteInfo<DriftMapRouteArgs> {
DriftMapRoute({
Key? key,
Geographic? initialLocation,
LatLng? initialLocation,
List<PageRouteInfo>? children,
}) : super(
DriftMapRoute.name,
@@ -1252,7 +1252,7 @@ class DriftMapRouteArgs {
final Key? key;
final Geographic? initialLocation;
final LatLng? initialLocation;
@override
String toString() {
@@ -1461,7 +1461,7 @@ class DriftPlaceDetailRouteArgs {
class DriftPlaceRoute extends PageRouteInfo<DriftPlaceRouteArgs> {
DriftPlaceRoute({
Key? key,
Geographic? currentLocation,
LatLng? currentLocation,
List<PageRouteInfo>? children,
}) : super(
DriftPlaceRoute.name,
@@ -1490,7 +1490,7 @@ class DriftPlaceRouteArgs {
final Key? key;
final Geographic? currentLocation;
final LatLng? currentLocation;
@override
String toString() {
@@ -2011,7 +2011,7 @@ class MainTimelineRoute extends PageRouteInfo<void> {
class MapLocationPickerRoute extends PageRouteInfo<MapLocationPickerRouteArgs> {
MapLocationPickerRoute({
Key? key,
Geographic initialLatLng = const Geographic(lat: 0, lon: 0),
LatLng initialLatLng = const LatLng(0, 0),
List<PageRouteInfo>? children,
}) : super(
MapLocationPickerRoute.name,
@@ -2041,12 +2041,12 @@ class MapLocationPickerRoute extends PageRouteInfo<MapLocationPickerRouteArgs> {
class MapLocationPickerRouteArgs {
const MapLocationPickerRouteArgs({
this.key,
this.initialLatLng = const Geographic(lat: 0, lon: 0),
this.initialLatLng = const LatLng(0, 0),
});
final Key? key;
final Geographic initialLatLng;
final LatLng initialLatLng;
@override
String toString() {
@@ -2057,15 +2057,12 @@ class MapLocationPickerRouteArgs {
/// generated route for
/// [MapPage]
class MapRoute extends PageRouteInfo<MapRouteArgs> {
MapRoute({
Key? key,
Geographic? initialLocation,
List<PageRouteInfo>? children,
}) : super(
MapRoute.name,
args: MapRouteArgs(key: key, initialLocation: initialLocation),
initialChildren: children,
);
MapRoute({Key? key, LatLng? initialLocation, List<PageRouteInfo>? children})
: super(
MapRoute.name,
args: MapRouteArgs(key: key, initialLocation: initialLocation),
initialChildren: children,
);
static const String name = 'MapRoute';
@@ -2085,7 +2082,7 @@ class MapRouteArgs {
final Key? key;
final Geographic? initialLocation;
final LatLng? initialLocation;
@override
String toString() {
@@ -2406,7 +2403,7 @@ class PinAuthRouteArgs {
class PlacesCollectionRoute extends PageRouteInfo<PlacesCollectionRouteArgs> {
PlacesCollectionRoute({
Key? key,
Geographic? currentLocation,
LatLng? currentLocation,
List<PageRouteInfo>? children,
}) : super(
PlacesCollectionRoute.name,
@@ -2438,7 +2435,7 @@ class PlacesCollectionRouteArgs {
final Key? key;
final Geographic? currentLocation;
final LatLng? currentLocation;
@override
String toString() {
+3 -3
View File
@@ -22,7 +22,7 @@ import 'package:immich_mobile/routing/router.dart';
import 'package:immich_mobile/utils/timezone.dart';
import 'package:immich_mobile/widgets/common/date_time_picker.dart';
import 'package:immich_mobile/widgets/common/location_picker.dart';
import 'package:maplibre/maplibre.dart' as maplibre;
import 'package:maplibre_gl/maplibre_gl.dart' as maplibre;
import 'package:riverpod_annotation/riverpod_annotation.dart';
final actionServiceProvider = Provider<ActionService>(
@@ -131,12 +131,12 @@ class ActionService {
}
Future<bool> editLocation(List<String> remoteIds, BuildContext context) async {
maplibre.Geographic? initialLatLng;
maplibre.LatLng? initialLatLng;
if (remoteIds.length == 1) {
final exif = await _remoteAssetRepository.getExif(remoteIds[0]);
if (exif?.latitude != null && exif?.longitude != null) {
initialLatLng = maplibre.Geographic(lat: exif!.latitude!, lon: exif.longitude!);
initialLatLng = maplibre.LatLng(exif!.latitude!, exif.longitude!);
}
}
+4 -4
View File
@@ -23,7 +23,7 @@ import 'package:immich_mobile/services/api.service.dart';
import 'package:immich_mobile/services/backup.service.dart';
import 'package:immich_mobile/services/sync.service.dart';
import 'package:logging/logging.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
import 'package:openapi/api.dart';
import 'package:immich_mobile/utils/debug_print.dart';
@@ -236,12 +236,12 @@ class AssetService {
}
}
Future<List<Asset>?> changeLocation(List<Asset> assets, Geographic location) async {
Future<List<Asset>?> changeLocation(List<Asset> assets, LatLng location) async {
try {
await updateAssets(assets, UpdateAssetDto(latitude: location.lat, longitude: location.lon));
await updateAssets(assets, UpdateAssetDto(latitude: location.latitude, longitude: location.longitude));
for (var element in assets) {
element.exifInfo = element.exifInfo?.copyWith(latitude: location.lat, longitude: location.lon);
element.exifInfo = element.exifInfo?.copyWith(latitude: location.latitude, longitude: location.longitude);
}
await _syncService.upsertAssetsWithExif(assets);
+10 -1
View File
@@ -1,14 +1,23 @@
import 'package:immich_mobile/mixins/error_logger.mixin.dart';
import 'package:immich_mobile/models/map/map_marker.model.dart';
import 'package:immich_mobile/services/api.service.dart';
import 'package:immich_mobile/utils/user_agent.dart';
import 'package:logging/logging.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class MapService with ErrorLoggerMixin {
final ApiService _apiService;
@override
final logger = Logger("MapService");
MapService(this._apiService);
MapService(this._apiService) {
_setMapUserAgentHeader();
}
Future<void> _setMapUserAgentHeader() async {
final userAgent = await getUserAgentString();
await setHttpHeaders({'User-Agent': userAgent});
}
Future<Iterable<MapMarker>> getMapMarkers({
bool? isFavorite,
+26 -32
View File
@@ -6,6 +6,7 @@ import 'package:geolocator/geolocator.dart';
import 'package:immich_mobile/models/map/map_marker.model.dart';
import 'package:immich_mobile/widgets/common/confirm_dialog.dart';
import 'package:logging/logging.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class MapUtils {
const MapUtils._();
@@ -14,53 +15,46 @@ class MapUtils {
static const defaultSourceId = 'asset-map-markers';
static const defaultHeatMapLayerId = 'asset-heatmap-layer';
static const defaultHeatMapLayerPaint = <String, Object>{
'heatmap-color': [
'interpolate',
['linear'],
['heatmap-density'],
static const defaultHeatMapLayerProperties = HeatmapLayerProperties(
heatmapColor: [
Expressions.interpolate,
["linear"],
["heatmap-density"],
0.0,
'rgba(103,58,183,0.0)',
"rgba(103,58,183,0.0)",
0.3,
'rgb(103,58,183)',
"rgb(103,58,183)",
0.5,
'rgb(33,149,243)',
"rgb(33,149,243)",
0.7,
'rgb(76,175,79)',
"rgb(76,175,79)",
0.95,
'rgb(255,235,59)',
"rgb(255,235,59)",
1.0,
'rgb(255,86,34)',
"rgb(255,86,34)",
],
'heatmap-intensity': [
'interpolate',
['linear'],
['zoom'],
0,
0.5,
9,
2,
heatmapIntensity: [
Expressions.interpolate, ["linear"], //
[Expressions.zoom],
0, 0.5,
9, 2,
],
'heatmap-radius': [
'interpolate',
['linear'],
['zoom'],
0,
4,
4,
8,
9,
16,
heatmapRadius: [
Expressions.interpolate, ["linear"], //
[Expressions.zoom],
0, 4,
4, 8,
9, 16,
],
'heatmap-opacity': 0.7,
};
heatmapOpacity: 0.7,
);
static Map<String, dynamic> _addFeature(MapMarker marker) => {
'type': 'Feature',
'id': marker.assetRemoteId,
'geometry': {
'type': 'Point',
'coordinates': [marker.latLng.lon, marker.latLng.lat],
'coordinates': [marker.latLng.longitude, marker.latLng.latitude],
},
};
+3 -3
View File
@@ -14,7 +14,7 @@ import 'package:immich_mobile/widgets/common/date_time_picker.dart';
import 'package:immich_mobile/widgets/common/immich_toast.dart';
import 'package:immich_mobile/widgets/common/location_picker.dart';
import 'package:immich_mobile/widgets/common/share_dialog.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
void handleShareAssets(WidgetRef ref, BuildContext context, Iterable<Asset> selection) {
showDialog(
@@ -105,12 +105,12 @@ Future<void> handleEditDateTime(WidgetRef ref, BuildContext context, List<Asset>
}
Future<void> handleEditLocation(WidgetRef ref, BuildContext context, List<Asset> selection) async {
Geographic? initialLatLng;
LatLng? initialLatLng;
if (selection.length == 1) {
final asset = selection.first;
final assetWithExif = await ref.watch(assetServiceProvider).loadExif(asset);
if (assetWithExif.exifInfo?.latitude != null && assetWithExif.exifInfo?.longitude != null) {
initialLatLng = Geographic(lat: assetWithExif.exifInfo!.latitude!, lon: assetWithExif.exifInfo!.longitude!);
initialLatLng = LatLng(assetWithExif.exifInfo!.latitude!, assetWithExif.exifInfo!.longitude!);
}
}
@@ -5,7 +5,7 @@ import 'package:flutter/material.dart';
import 'package:immich_mobile/domain/models/exif.model.dart';
import 'package:immich_mobile/utils/debug_print.dart';
import 'package:immich_mobile/widgets/map/map_thumbnail.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
import 'package:url_launcher/url_launcher.dart';
class ExifMap extends StatelessWidget {
@@ -15,7 +15,7 @@ class ExifMap extends StatelessWidget {
// reusing this component
final String? markerId;
final String? markerAssetThumbhash;
final void Function(MapController)? onMapCreated;
final MapCreatedCallback? onMapCreated;
const ExifMap({
super.key,
@@ -66,7 +66,7 @@ class ExifMap extends StatelessWidget {
return LayoutBuilder(
builder: (context, constraints) {
return MapThumbnail(
centre: Geographic(lat: exifInfo.latitude ?? 0, lon: exifInfo.longitude ?? 0),
centre: LatLng(exifInfo.latitude ?? 0, exifInfo.longitude ?? 0),
height: 150,
width: constraints.maxWidth,
zoom: 12.0,
+10 -10
View File
@@ -6,10 +6,10 @@ import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/extensions/string_extensions.dart';
import 'package:immich_mobile/routing/router.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
Future<Geographic?> showLocationPicker({required BuildContext context, Geographic? initialLatLng}) {
return showDialog<Geographic?>(
Future<LatLng?> showLocationPicker({required BuildContext context, LatLng? initialLatLng}) {
return showDialog<LatLng?>(
context: context,
useRootNavigator: false,
builder: (ctx) => _LocationPicker(initialLatLng: initialLatLng),
@@ -17,7 +17,7 @@ Future<Geographic?> showLocationPicker({required BuildContext context, Geographi
}
class _LocationPicker extends HookWidget {
final Geographic? initialLatLng;
final LatLng? initialLatLng;
const _LocationPicker({this.initialLatLng});
@@ -33,9 +33,9 @@ class _LocationPicker extends HookWidget {
@override
Widget build(BuildContext context) {
final latitude = useState(initialLatLng?.lat ?? 0.0);
final longitude = useState(initialLatLng?.lon ?? 0.0);
final latlng = Geographic(lat: latitude.value, lon: longitude.value);
final latitude = useState(initialLatLng?.latitude ?? 0.0);
final longitude = useState(initialLatLng?.longitude ?? 0.0);
final latlng = LatLng(latitude.value, longitude.value);
final latitiudeFocusNode = useFocusNode();
final longitudeFocusNode = useFocusNode();
final latitudeController = useTextEditingController(text: latitude.value.toStringAsFixed(4));
@@ -48,10 +48,10 @@ class _LocationPicker extends HookWidget {
}, [latitude.value, longitude.value]);
Future<void> onMapTap() async {
final newLatLng = await context.pushRoute<Geographic?>(MapLocationPickerRoute(initialLatLng: latlng));
final newLatLng = await context.pushRoute<LatLng?>(MapLocationPickerRoute(initialLatLng: latlng));
if (newLatLng != null) {
latitude.value = newLatLng.lat;
longitude.value = newLatLng.lon;
latitude.value = newLatLng.latitude;
longitude.value = newLatLng.longitude;
}
}
+25 -24
View File
@@ -51,35 +51,36 @@ class MapAssetGrid extends HookConsumerWidget {
final assetCache = useRef<Map<String, Asset>>({});
void handleMapEvents(MapEvent event) async {
if (event is! MapAssetsInBoundsUpdated) return;
if (event is MapAssetsInBoundsUpdated) {
final assetIds = event.assetRemoteIds;
final missingIds = <String>[];
final currentAssets = <Asset>[];
final assetIds = event.assetRemoteIds;
final missingIds = <String>[];
final currentAssets = <Asset>[];
for (final id in assetIds) {
final asset = assetCache.value[id];
if (asset != null) {
currentAssets.add(asset);
} else {
missingIds.add(id);
}
}
// Only fetch missing assets
if (missingIds.isNotEmpty) {
final newAssets = await ref.read(dbProvider).assets.getAllByRemoteId(missingIds);
// Add new assets to cache and current list
for (final asset in newAssets) {
if (asset.remoteId != null) {
assetCache.value[asset.remoteId!] = asset;
for (final id in assetIds) {
final asset = assetCache.value[id];
if (asset != null) {
currentAssets.add(asset);
} else {
missingIds.add(id);
}
}
}
assetsInBounds.value = currentAssets;
// Only fetch missing assets
if (missingIds.isNotEmpty) {
final newAssets = await ref.read(dbProvider).assets.getAllByRemoteId(missingIds);
// Add new assets to cache and current list
for (final asset in newAssets) {
if (asset.remoteId != null) {
assetCache.value[asset.remoteId!] = asset;
currentAssets.add(asset);
}
}
}
assetsInBounds.value = currentAssets;
return;
}
}
useOnStreamChange<MapEvent>(mapEventStream, onData: handleMapEvents);
+7 -3
View File
@@ -33,9 +33,13 @@ class MapBottomSheet extends HookConsumerWidget {
final isBottomSheetOpened = useRef(false);
void handleMapEvents(MapEvent event) async {
if (event is! MapCloseBottomSheet) return;
await sheetController.animateTo(0.1, duration: const Duration(milliseconds: 200), curve: Curves.linearToEaseOut);
if (event is MapCloseBottomSheet) {
await sheetController.animateTo(
0.1,
duration: const Duration(milliseconds: 200),
curve: Curves.linearToEaseOut,
);
}
}
useOnStreamChange<MapEvent>(mapEventStream, onData: handleMapEvents);
@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/extensions/translate_extensions.dart';
import 'package:immich_mobile/widgets/map/map_thumbnail.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class MapThemePicker extends StatelessWidget {
final ThemeMode themeMode;
@@ -78,7 +78,7 @@ class _BorderedMapThumbnail extends StatelessWidget {
),
child: MapThumbnail(
zoom: 2,
centre: const Geographic(lat: 47, lon: 5),
centre: const LatLng(47, 5),
onTap: (_, __) => onThemeChange(mode),
themeMode: mode,
showAttribution: false,
@@ -84,13 +84,8 @@ class _MapThemeOverrideState extends ConsumerState<MapThemeOverride> with Widget
data: _isDarkTheme
? getThemeData(colorScheme: appTheme.dark, locale: locale)
: getThemeData(colorScheme: appTheme.light, locale: locale),
// Key on _isDarkTheme to force MapLibreMap recreation on theme change,
// since initStyle is only applied on creation.
child: KeyedSubtree(
key: ValueKey(_isDarkTheme),
child: widget.mapBuilder.call(
ref.watch(mapStateNotifierProvider.select((v) => _isDarkTheme ? v.darkStyleFetched : v.lightStyleFetched)),
),
child: widget.mapBuilder.call(
ref.watch(mapStateNotifierProvider.select((v) => _isDarkTheme ? v.darkStyleFetched : v.lightStyleFetched)),
),
);
}
+51 -45
View File
@@ -1,11 +1,14 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:immich_mobile/extensions/asyncvalue_extensions.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/extensions/maplibrecontroller_extensions.dart';
import 'package:immich_mobile/widgets/map/map_theme_override.dart';
import 'package:immich_mobile/widgets/map/asset_marker_icon.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
/// A non-interactive thumbnail of a map in the given coordinates with optional markers
///
@@ -13,8 +16,8 @@ import 'package:maplibre/maplibre.dart';
/// [showMarkerPin] to true which would display a marker pin instead. If both are provided,
/// [assetMarkerRemoteId] will take precedence
class MapThumbnail extends HookConsumerWidget {
final Function(Offset, Geographic)? onTap;
final Geographic centre;
final Function(Point<double>, LatLng)? onTap;
final LatLng centre;
final String? assetMarkerRemoteId;
final String? assetThumbhash;
final bool showMarkerPin;
@@ -23,7 +26,7 @@ class MapThumbnail extends HookConsumerWidget {
final double width;
final ThemeMode? themeMode;
final bool showAttribution;
final void Function(MapController)? onCreated;
final MapCreatedCallback? onCreated;
const MapThumbnail({
super.key,
@@ -42,19 +45,26 @@ class MapThumbnail extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final controller = useRef<MapLibreMapController?>(null);
final styleLoaded = useState(false);
Future<void> onStyleLoaded(StyleController style) async {
if (showMarkerPin) {
await style.addImageFromAssets(id: 'mapMarker', asset: 'assets/location-pin.png');
}
styleLoaded.value = true;
Future<void> onMapCreated(MapLibreMapController mapController) async {
controller.value = mapController;
styleLoaded.value = false;
onCreated?.call(mapController);
}
void onEvent(MapEvent event) {
if (event is MapEventClick && onTap != null) {
onTap!(event.screenPoint, event.point);
Future<void> onStyleLoaded() async {
try {
if (showMarkerPin && controller.value != null) {
await controller.value?.addMarkerAtLatLng(centre);
}
} finally {
// Calling methods on the controller after it is disposed will throw an error
// We do not have a way to check if the controller is disposed for now
// https://github.com/maplibre/flutter-maplibre-gl/issues/192
}
styleLoaded.value = true;
}
return MapThemeOverride(
@@ -70,41 +80,37 @@ class MapThumbnail extends HookConsumerWidget {
width: width,
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(15)),
child: style.widgetWhen(
onData: (style) => MapLibreMap(
options: MapOptions(
initCenter: Geographic(lat: centre.lat + 0.002, lon: centre.lon),
initZoom: zoom,
initStyle: style,
gestures: const MapGestures.none(),
child: Stack(
alignment: AlignmentGeometry.topCenter,
children: [
style.widgetWhen(
onData: (style) => MapLibreMap(
initialCameraPosition: CameraPosition(target: centre, zoom: zoom),
styleString: style,
onMapCreated: onMapCreated,
onStyleLoadedCallback: onStyleLoaded,
onMapClick: onTap,
doubleClickZoomEnabled: false,
dragEnabled: false,
zoomGesturesEnabled: false,
tiltGesturesEnabled: false,
scrollGesturesEnabled: false,
rotateGesturesEnabled: false,
myLocationEnabled: false,
attributionButtonMargins: showAttribution == false ? const Point(-100, 0) : null,
),
),
onMapCreated: onCreated,
onStyleLoaded: onStyleLoaded,
onEvent: onEvent,
layers: [
if (showMarkerPin)
MarkerLayer(
points: [Feature(geometry: Point(centre))],
iconImage: 'mapMarker',
iconSize: 0.15,
iconAnchor: IconAnchor.bottom,
iconAllowOverlap: true,
if (assetMarkerRemoteId != null && assetThumbhash != null)
Container(
width: width,
height: height / 2,
alignment: Alignment.bottomCenter,
child: SizedBox.square(
dimension: height / 2.5,
child: AssetMarkerIcon(id: assetMarkerRemoteId!, thumbhash: assetThumbhash!),
),
],
children: [
if (assetMarkerRemoteId != null && assetThumbhash != null)
WidgetLayer(
markers: [
Marker(
point: centre,
size: Size.square(height / 2),
alignment: Alignment.bottomCenter,
child: AssetMarkerIcon(id: assetMarkerRemoteId!, thumbhash: assetThumbhash!),
),
],
),
],
),
),
],
),
),
),
@@ -0,0 +1,43 @@
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/widgets/map/asset_marker_icon.dart';
class PositionedAssetMarkerIcon extends StatelessWidget {
final Point<num> point;
final String assetRemoteId;
final String assetThumbhash;
final double size;
final int durationInMilliseconds;
final Function()? onTap;
const PositionedAssetMarkerIcon({
required this.point,
required this.assetRemoteId,
required this.assetThumbhash,
this.size = 100,
this.durationInMilliseconds = 100,
this.onTap,
super.key,
});
@override
Widget build(BuildContext context) {
final ratio = Platform.isIOS ? 1.0 : context.devicePixelRatio;
return AnimatedPositioned(
left: point.x / ratio - size / 2,
top: point.y / ratio - size,
duration: Duration(milliseconds: durationInMilliseconds),
child: GestureDetector(
onTap: () => onTap?.call(),
child: SizedBox.square(
dimension: size,
child: AssetMarkerIcon(id: assetRemoteId, thumbhash: assetThumbhash, key: Key(assetRemoteId)),
),
),
);
}
}
@@ -0,0 +1,42 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:openapi/api.dart' show AssetOrder;
enum _SortOption { bestMatch, newest, oldest }
class SortOrderPicker extends HookWidget {
const SortOrderPicker({super.key, required this.onSelect, this.order});
final Function(AssetOrder?) onSelect;
final AssetOrder? order;
@override
Widget build(BuildContext context) {
final selected = useState<_SortOption>(switch (order) {
AssetOrder.desc => _SortOption.newest,
AssetOrder.asc => _SortOption.oldest,
_ => _SortOption.bestMatch,
});
return RadioGroup<_SortOption>(
onChanged: (value) {
if (value == null) return;
selected.value = value;
onSelect(switch (value) {
_SortOption.bestMatch => null,
_SortOption.newest => AssetOrder.desc,
_SortOption.oldest => AssetOrder.asc,
});
},
groupValue: selected.value,
child: Column(
children: [
RadioListTile(title: const Text('best_match').tr(), value: _SortOption.bestMatch),
RadioListTile(title: const Text('newest_first').tr(), value: _SortOption.newest),
RadioListTile(title: const Text('oldest_first').tr(), value: _SortOption.oldest),
],
),
);
}
}
@@ -4,7 +4,7 @@ import 'package:flutter/material.dart';
import 'package:immich_mobile/routing/router.dart';
import 'package:immich_mobile/widgets/map/map_thumbnail.dart';
import 'package:immich_mobile/widgets/search/thumbnail_with_info_container.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
class SearchMapThumbnail extends StatelessWidget {
const SearchMapThumbnail({super.key, this.size = 60.0});
@@ -20,13 +20,7 @@ class SearchMapThumbnail extends StatelessWidget {
context.pushRoute(MapRoute());
},
child: IgnorePointer(
child: MapThumbnail(
zoom: 2,
centre: const Geographic(lat: 47, lon: 5),
height: size,
width: size,
showAttribution: false,
),
child: MapThumbnail(zoom: 2, centre: const LatLng(47, 5), height: size, width: size, showAttribution: false),
),
);
}
+1 -1
View File
@@ -1,5 +1,5 @@
[tools]
flutter = "3.41.2"
flutter = "3.35.7"
[tools."github:CQLabs/homebrew-dcm"]
version = "1.30.0"
+19 -1
View File
@@ -30,6 +30,7 @@ class SmartSearchDto {
this.make,
this.model,
this.ocr,
this.order,
this.page,
this.personIds = const [],
this.query,
@@ -167,6 +168,15 @@ class SmartSearchDto {
///
String? ocr;
/// Sort order by date. If not provided, results are sorted by relevance.
///
/// Please note: This property should have been non-nullable! Since the specification file
/// does not include a default value (using the "default:" property), however, the generated
/// source code must fall back to having a nullable type.
/// Consider adding a "default:" property in the specification file to hide this note.
///
AssetOrder? order;
/// Page number
///
/// Minimum value: 1
@@ -338,6 +348,7 @@ class SmartSearchDto {
other.make == make &&
other.model == model &&
other.ocr == ocr &&
other.order == order &&
other.page == page &&
_deepEquality.equals(other.personIds, personIds) &&
other.query == query &&
@@ -377,6 +388,7 @@ class SmartSearchDto {
(make == null ? 0 : make!.hashCode) +
(model == null ? 0 : model!.hashCode) +
(ocr == null ? 0 : ocr!.hashCode) +
(order == null ? 0 : order!.hashCode) +
(page == null ? 0 : page!.hashCode) +
(personIds.hashCode) +
(query == null ? 0 : query!.hashCode) +
@@ -397,7 +409,7 @@ class SmartSearchDto {
(withExif == null ? 0 : withExif!.hashCode);
@override
String toString() => 'SmartSearchDto[albumIds=$albumIds, city=$city, country=$country, createdAfter=$createdAfter, createdBefore=$createdBefore, deviceId=$deviceId, isEncoded=$isEncoded, isFavorite=$isFavorite, isMotion=$isMotion, isNotInAlbum=$isNotInAlbum, isOffline=$isOffline, language=$language, lensModel=$lensModel, libraryId=$libraryId, make=$make, model=$model, ocr=$ocr, page=$page, personIds=$personIds, query=$query, queryAssetId=$queryAssetId, rating=$rating, size=$size, state=$state, tagIds=$tagIds, takenAfter=$takenAfter, takenBefore=$takenBefore, trashedAfter=$trashedAfter, trashedBefore=$trashedBefore, type=$type, updatedAfter=$updatedAfter, updatedBefore=$updatedBefore, visibility=$visibility, withDeleted=$withDeleted, withExif=$withExif]';
String toString() => 'SmartSearchDto[albumIds=$albumIds, city=$city, country=$country, createdAfter=$createdAfter, createdBefore=$createdBefore, deviceId=$deviceId, isEncoded=$isEncoded, isFavorite=$isFavorite, isMotion=$isMotion, isNotInAlbum=$isNotInAlbum, isOffline=$isOffline, language=$language, lensModel=$lensModel, libraryId=$libraryId, make=$make, model=$model, ocr=$ocr, order=$order, page=$page, personIds=$personIds, query=$query, queryAssetId=$queryAssetId, rating=$rating, size=$size, state=$state, tagIds=$tagIds, takenAfter=$takenAfter, takenBefore=$takenBefore, trashedAfter=$trashedAfter, trashedBefore=$trashedBefore, type=$type, updatedAfter=$updatedAfter, updatedBefore=$updatedBefore, visibility=$visibility, withDeleted=$withDeleted, withExif=$withExif]';
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
@@ -482,6 +494,11 @@ class SmartSearchDto {
} else {
// json[r'ocr'] = null;
}
if (this.order != null) {
json[r'order'] = this.order;
} else {
// json[r'order'] = null;
}
if (this.page != null) {
json[r'page'] = this.page;
} else {
@@ -599,6 +616,7 @@ class SmartSearchDto {
make: mapValueOfType<String>(json, r'make'),
model: mapValueOfType<String>(json, r'model'),
ocr: mapValueOfType<String>(json, r'ocr'),
order: AssetOrder.fromJson(json[r'order']),
page: num.parse('${json[r'page']}'),
personIds: json[r'personIds'] is Iterable
? (json[r'personIds'] as Iterable).cast<String>().toList(growable: false)
+24 -144
View File
@@ -229,10 +229,10 @@ packages:
dependency: transitive
description:
name: characters
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
url: "https://pub.dev"
source: hosted
version: "1.4.1"
version: "1.4.0"
charcode:
dependency: transitive
description:
@@ -273,14 +273,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
code_builder:
dependency: transitive
description:
@@ -784,14 +776,6 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
geobase:
dependency: transitive
description:
name: geobase
sha256: "3a4e2eb17a7ab452dda78fb45ee498a3ab02469ded749a5f4a9abea21fc95919"
url: "https://pub.dev"
source: hosted
version: "1.5.0"
geoclue:
dependency: transitive
description:
@@ -888,14 +872,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.8.1"
hooks:
dependency: transitive
description:
name: hooks
sha256: "7a08a0d684cb3b8fb604b78455d5d352f502b68079f7b80b831c62220ab0a4f6"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
hooks_riverpod:
dependency: "direct main"
description:
@@ -1149,14 +1125,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.1.1"
lists:
dependency: transitive
description:
name: lists
sha256: "4ca5c19ae4350de036a7e996cdd1ee39c93ac0a2b840f4915459b7d0a7d4ab27"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
local_auth:
dependency: "direct main"
description:
@@ -1205,78 +1173,54 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.3.0"
maplibre:
maplibre_gl:
dependency: "direct main"
description:
name: maplibre
sha256: "03aad98086ef8e24caf9abcbbacf43f7ceb6267a6b914d907f57fb05ccb65e09"
name: maplibre_gl
sha256: "5c7b1008396b2a321bada7d986ed60f9423406fbc7bd16f7ce91b385dfa054cd"
url: "https://pub.dev"
source: hosted
version: "0.3.4"
maplibre_android:
version: "0.22.0"
maplibre_gl_platform_interface:
dependency: transitive
description:
name: maplibre_android
sha256: be8a9c29b20c10f4b2207790e8ab35489955a29cb69df10e38bdf993b44f1547
name: maplibre_gl_platform_interface
sha256: "08ee0a2d0853ea945a0ab619d52c0c714f43144145cd67478fc6880b52f37509"
url: "https://pub.dev"
source: hosted
version: "0.3.4"
maplibre_ios:
version: "0.22.0"
maplibre_gl_web:
dependency: transitive
description:
name: maplibre_ios
sha256: "3e261d99697cc191e64ceb256acec5d96662d429059057bb6c1740dd11eaa7c3"
name: maplibre_gl_web
sha256: "2b13d4b1955a9a54e38a718f2324e56e4983c080fc6de316f6f4b5458baacb58"
url: "https://pub.dev"
source: hosted
version: "0.3.4"
maplibre_platform_interface:
dependency: transitive
description:
name: maplibre_platform_interface
sha256: "7d912d82d41a31daed4e91a243a1324f483f7ffbf3671c229b98328beab854b4"
url: "https://pub.dev"
source: hosted
version: "0.3.4"
maplibre_web:
dependency: transitive
description:
name: maplibre_web
sha256: "7e79427cdb0098c1e054fb90f5f35f4538c69e8d170c0e92f6abe7c61e106461"
url: "https://pub.dev"
source: hosted
version: "0.3.4"
version: "0.22.0"
matcher:
dependency: transitive
description:
name: matcher
sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6"
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
url: "https://pub.dev"
source: hosted
version: "0.12.18"
version: "0.12.17"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
url: "https://pub.dev"
source: hosted
version: "0.13.0"
version: "0.11.1"
meta:
dependency: transitive
description:
name: meta
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
url: "https://pub.dev"
source: hosted
version: "1.17.0"
mgrs_dart:
dependency: transitive
description:
name: mgrs_dart
sha256: fb89ae62f05fa0bb90f70c31fc870bcbcfd516c843fb554452ab3396f78586f7
url: "https://pub.dev"
source: hosted
version: "2.0.0"
version: "1.16.0"
mime:
dependency: transitive
description:
@@ -1293,14 +1237,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.4"
native_toolchain_c:
dependency: transitive
description:
name: native_toolchain_c
sha256: "89e83885ba09da5fdf2cdacc8002a712ca238c28b7f717910b34bcd27b0d03ac"
url: "https://pub.dev"
source: hosted
version: "0.17.4"
native_video_player:
dependency: "direct main"
description:
@@ -1541,38 +1477,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
pointer_interceptor:
dependency: transitive
description:
name: pointer_interceptor
sha256: "57210410680379aea8b1b7ed6ae0c3ad349bfd56fe845b8ea934a53344b9d523"
url: "https://pub.dev"
source: hosted
version: "0.10.1+2"
pointer_interceptor_ios:
dependency: transitive
description:
name: pointer_interceptor_ios
sha256: "03c5fa5896080963ab4917eeffda8d28c90f22863a496fb5ba13bc10943e40e4"
url: "https://pub.dev"
source: hosted
version: "0.10.1+1"
pointer_interceptor_platform_interface:
dependency: transitive
description:
name: pointer_interceptor_platform_interface
sha256: "0597b0560e14354baeb23f8375cd612e8bd4841bf8306ecb71fcd0bb78552506"
url: "https://pub.dev"
source: hosted
version: "0.10.0+1"
pointer_interceptor_web:
dependency: transitive
description:
name: pointer_interceptor_web
sha256: "460b600e71de6fcea2b3d5f662c92293c049c4319e27f0829310e5a953b3ee2a"
url: "https://pub.dev"
source: hosted
version: "0.10.3"
pool:
dependency: transitive
description:
@@ -1597,14 +1501,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.3"
proj4dart:
dependency: transitive
description:
name: proj4dart
sha256: c8a659ac9b6864aa47c171e78d41bbe6f5e1d7bd790a5814249e6b68bc44324e
url: "https://pub.dev"
source: hosted
version: "2.1.0"
protobuf:
dependency: transitive
description:
@@ -2014,10 +1910,10 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636"
sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00"
url: "https://pub.dev"
source: hosted
version: "0.7.9"
version: "0.7.6"
thumbhash:
dependency: "direct main"
description:
@@ -2058,14 +1954,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
unicode:
dependency: transitive
description:
name: unicode
sha256: "0f69e46593d65245774d4f17125c6084d2c20b4e473a983f6e21b7d7762218f1"
url: "https://pub.dev"
source: hosted
version: "0.3.1"
universal_io:
dependency: transitive
description:
@@ -2274,14 +2162,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.0.3"
wkt_parser:
dependency: transitive
description:
name: wkt_parser
sha256: "8a555fc60de3116c00aad67891bcab20f81a958e4219cc106e3c037aa3937f13"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
worker_manager:
dependency: "direct main"
description:
@@ -2323,5 +2203,5 @@ packages:
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.11.0 <4.0.0"
flutter: "3.41.2"
dart: ">=3.9.0 <4.0.0"
flutter: ">=3.35.7"
+3 -3
View File
@@ -5,8 +5,8 @@ publish_to: 'none'
version: 2.5.6+3037
environment:
sdk: '>=3.11.0 <4.0.0'
flutter: 3.41.2
sdk: '>=3.8.0 <4.0.0'
flutter: 3.35.7
dependencies:
async: ^2.13.0
@@ -52,7 +52,7 @@ dependencies:
isar_community_flutter_libs: 3.3.0-dev.3
local_auth: ^2.3.0
logging: ^1.3.0
maplibre: ^0.3.4
maplibre_gl: ^0.22.0
native_video_player:
git:
+4 -4
View File
@@ -1,7 +1,7 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:immich_mobile/entities/asset.entity.dart';
import 'package:immich_mobile/services/asset.service.dart';
import 'package:maplibre/maplibre.dart';
import 'package:maplibre_gl/maplibre_gl.dart';
import 'package:mocktail/mocktail.dart';
import 'package:openapi/api.dart';
@@ -85,9 +85,9 @@ void main() {
expect(receivedDatetime.every((d) => d == dateTime), isTrue);
});
test("asset is updated with Geographic", () async {
test("asset is updated with LatLng", () async {
final assets = [AssetStub.image1, AssetStub.image2];
final latLng = const Geographic(lat: 37.7749, lon: -122.4194);
final latLng = const LatLng(37.7749, -122.4194);
await sut.changeLocation(assets, latLng);
verify(() => assetsApi.updateAssets(any())).called(1);
@@ -95,7 +95,7 @@ void main() {
upsertExifCallback.called(1);
final receivedAssets = upsertExifCallback.captured.firstOrNull as List<Object>? ?? [];
final receivedCoords = receivedAssets.cast<Asset>().map(
(a) => Geographic(lat: a.exifInfo?.latitude ?? 0, lon: a.exifInfo?.longitude ?? 0),
(a) => LatLng(a.exifInfo?.latitude ?? 0, a.exifInfo?.longitude ?? 0),
);
expect(receivedCoords.every((l) => l == latLng), isTrue);
});
+8
View File
@@ -22063,6 +22063,14 @@
"description": "Filter by OCR text content",
"type": "string"
},
"order": {
"allOf": [
{
"$ref": "#/components/schemas/AssetOrder"
}
],
"description": "Sort order by date. If not provided, results are sorted by relevance."
},
"page": {
"description": "Page number",
"minimum": 1,
@@ -1893,6 +1893,8 @@ export type SmartSearchDto = {
model?: string | null;
/** Filter by OCR text content */
ocr?: string;
/** Sort order by date. If not provided, results are sorted by relevance. */
order?: AssetOrder;
/** Page number */
page?: number;
/** Filter by person IDs */
+1 -1
View File
@@ -59,7 +59,7 @@ RUN if [ "$(dpkg --print-architecture)" = "arm64" ]; then \
# Flutter SDK
# https://flutter.dev/docs/development/tools/sdk/releases?tab=linux
ENV FLUTTER_CHANNEL="stable"
ENV FLUTTER_VERSION="3.41.2"
ENV FLUTTER_VERSION="3.35.7"
ENV FLUTTER_HOME=/flutter
ENV PATH=${PATH}:${FLUTTER_HOME}/bin
+5 -5
View File
@@ -9,15 +9,15 @@
"build": "nest build",
"format": "prettier --check .",
"format:fix": "prettier --write .",
"start": "npm run start:dev",
"start": "pnpm run start:dev",
"nest": "nest",
"start:dev": "nest start --watch --",
"start:debug": "nest start --debug 0.0.0.0:9230 --watch --",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\" --max-warnings 0",
"lint:fix": "npm run lint -- --fix",
"lint:fix": "pnpm run lint --fix",
"check": "tsc --noEmit",
"check:code": "npm run format && npm run lint && npm run check",
"check:all": "npm run check:code && npm run test:cov",
"check:code": "pnpm run format && pnpm run lint && pnpm run check",
"check:all": "pnpm run check:code && pnpm run test:cov",
"test": "vitest --config test/vitest.config.mjs",
"test:cov": "vitest --config test/vitest.config.mjs --coverage",
"test:medium": "vitest --config test/vitest.config.medium.mjs",
@@ -28,7 +28,7 @@
"migrations:run": "node ./dist/bin/migrations.js run",
"migrations:revert": "node ./dist/bin/migrations.js revert",
"schema:drop": "node ./dist/bin/migrations.js query 'DROP schema public cascade; CREATE schema public;'",
"schema:reset": "npm run schema:drop && npm run migrations:run",
"schema:reset": "pnpm run schema:drop && pnpm run migrations:run",
"sync:open-api": "node ./dist/bin/sync-open-api.js",
"sync:sql": "node ./dist/bin/sync-sql.js",
"email:dev": "email dev -p 3050 --dir src/emails"
+8
View File
@@ -237,6 +237,14 @@ export class SmartSearchDto extends BaseSearchWithResultsDto {
@Type(() => Number)
@Optional()
page?: number;
@ValidateEnum({
enum: AssetOrder,
name: 'AssetOrder',
optional: true,
description: 'Sort order by date. If not provided, results are sorted by relevance.',
})
order?: AssetOrder;
}
export class SearchPlacesDto {
+7 -1
View File
@@ -129,6 +129,7 @@ export type SmartSearchOptions = SearchDateOptions &
SearchEmbeddingOptions &
SearchExifOptions &
SearchOneToOneRelationOptions &
SearchOrderOptions &
SearchStatusOptions &
SearchUserIdOptions &
SearchPeopleOptions &
@@ -300,7 +301,12 @@ export class SearchRepository {
const items = await searchAssetBuilder(trx, options)
.selectAll('asset')
.innerJoin('smart_search', 'asset.id', 'smart_search.assetId')
.orderBy(sql`smart_search.embedding <=> ${options.embedding}`)
.$if(!options.orderDirection, (qb) => qb.orderBy(sql`smart_search.embedding <=> ${options.embedding}`))
.$if(!!options.orderDirection, (qb) =>
qb
.where(sql`(smart_search.embedding <=> ${options.embedding}) <= 0.9`)
.orderBy('asset.fileCreatedAt', options.orderDirection as OrderByDirection),
)
.limit(pagination.size + 1)
.offset((pagination.page - 1) * pagination.size)
.execute();
+1 -1
View File
@@ -139,7 +139,7 @@ export class SearchService extends BaseService {
const size = dto.size || 100;
const { hasNextPage, items } = await this.searchRepository.searchSmart(
{ page, size },
{ ...dto, userIds: await userIds, embedding },
{ ...dto, userIds: await userIds, embedding, orderDirection: dto.order },
);
return this.mapResponse(items, hasNextPage ? (page + 1).toString() : null, { auth });
@@ -94,7 +94,7 @@
const sharedLink = getSharedLink();
</script>
<CommandPaletteDefaultProvider name={$t('assets')} actions={withoutIcons([Cast, ...Object.values(Actions)])} />
<CommandPaletteDefaultProvider name={$t('assets')} actions={withoutIcons([Close, Cast, ...Object.values(Actions)])} />
<div
class="flex h-16 place-items-center justify-between bg-linear-to-b from-black/40 px-3 transition-transform duration-200"
@@ -432,6 +432,12 @@
);
const { Tag } = $derived(getAssetActions($t, asset));
const showDetailPanel = $derived(
asset.hasMetadata &&
$slideshowState === SlideshowState.None &&
assetViewerManager.isShowDetailPanel &&
!assetViewerManager.isShowEditor,
);
</script>
<CommandPaletteDefaultProvider name={$t('assets')} actions={[Tag]} />
@@ -571,25 +577,22 @@
</div>
{/if}
{#if asset.hasMetadata && $slideshowState === SlideshowState.None && assetViewerManager.isShowDetailPanel && !assetViewerManager.isShowEditor}
{#if showDetailPanel || assetViewerManager.isShowEditor}
<div
transition:fly={{ duration: 150 }}
id="detail-panel"
class="row-start-1 row-span-4 w-90 overflow-y-auto transition-all dark:border-l dark:border-s-immich-dark-gray bg-light"
class="row-start-1 row-span-4 overflow-y-auto transition-all dark:border-l dark:border-s-immich-dark-gray bg-light"
translate="yes"
>
<DetailPanel {asset} currentAlbum={album} albums={appearsInAlbums} />
</div>
{/if}
{#if assetViewerManager.isShowEditor}
<div
transition:fly={{ duration: 150 }}
id="editor-panel"
class="row-start-1 row-span-4 w-100 overflow-y-auto transition-all dark:border-l dark:border-s-immich-dark-gray"
translate="yes"
>
<EditorPanel {asset} onClose={closeEditor} />
{#if showDetailPanel}
<div class="w-90 h-full">
<DetailPanel {asset} currentAlbum={album} albums={appearsInAlbums} />
</div>
{:else if assetViewerManager.isShowEditor}
<div class="w-100 h-full">
<EditorPanel {asset} onClose={closeEditor} />
</div>
{/if}
</div>
{/if}
@@ -0,0 +1,459 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { shortcuts, type ShortcutOptions } from '$lib/actions/shortcut';
import type { Action } from '$lib/components/asset-viewer/actions/action';
import Thumbnail from '$lib/components/assets/thumbnail/thumbnail.svelte';
import { AssetAction } from '$lib/constants';
import Portal from '$lib/elements/Portal.svelte';
import { featureFlagsManager } from '$lib/managers/feature-flags-manager.svelte';
import type { TimelineAsset, Viewport } from '$lib/managers/timeline-manager/types';
import AssetDeleteConfirmModal from '$lib/modals/AssetDeleteConfirmModal.svelte';
import ShortcutsModal from '$lib/modals/ShortcutsModal.svelte';
import { Route } from '$lib/route';
import type { AssetInteraction } from '$lib/stores/asset-interaction.svelte';
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
import { showDeleteModal } from '$lib/stores/preferences.store';
import { handlePromiseError } from '$lib/utils';
import { deleteAssets } from '$lib/utils/actions';
import { archiveAssets, cancelMultiselect, getNextAsset, getPreviousAsset, navigateToAsset } from '$lib/utils/asset-utils';
import { moveFocus } from '$lib/utils/focus-util';
import { handleError } from '$lib/utils/handle-error';
import type { CommonJustifiedLayout } from '$lib/utils/layout-utils';
import { getJustifiedLayoutFromAssets } from '$lib/utils/layout-utils';
import { navigate } from '$lib/utils/navigation';
import { formatGroupTitle, toTimelineAsset } from '$lib/utils/timeline-util';
import { AssetVisibility, type AssetResponseDto } from '@immich/sdk';
import { modalManager, Text } from '@immich/ui';
import { DateTime } from 'luxon';
import { debounce } from 'lodash-es';
import { t } from 'svelte-i18n';
type DateGroup = {
date: DateTime;
title: string;
assets: AssetResponseDto[];
geometry: CommonJustifiedLayout;
offsetTop: number;
};
type Props = {
assets: AssetResponseDto[];
assetInteraction: AssetInteraction;
disableAssetSelect?: boolean;
showArchiveIcon?: boolean;
viewport: Viewport;
onIntersected?: (() => void) | undefined;
onReload?: (() => void) | undefined;
slidingWindowOffset?: number;
};
let {
assets = $bindable(),
assetInteraction,
disableAssetSelect = false,
showArchiveIcon = false,
viewport,
onIntersected = undefined,
onReload = undefined,
slidingWindowOffset = 0,
}: Props = $props();
const HEADER_HEIGHT = 48;
let { isViewing: isViewerOpen, asset: viewingAsset } = assetViewingStore;
function groupAssetsByDate(items: AssetResponseDto[]): DateGroup[] {
const groupEntries: { key: string; assets: AssetResponseDto[] }[] = [];
for (const asset of items) {
const date = DateTime.fromISO(asset.localDateTime, { zone: 'UTC' });
const key = date.toISODate() ?? 'unknown';
const last = groupEntries.at(-1);
if (last && last.key === key) {
last.assets.push(asset);
} else {
groupEntries.push({ key, assets: [asset] });
}
}
const groups: DateGroup[] = [];
let offsetTop = 0;
const rowWidth = Math.floor(viewport.width);
const rowHeight = rowWidth < 850 ? 100 : 235;
for (const { key, assets: groupAssets } of groupEntries) {
const date = DateTime.fromISO(key, { zone: 'local' });
const geometry = getJustifiedLayoutFromAssets(groupAssets, {
spacing: 2,
heightTolerance: 0.5,
rowHeight,
rowWidth,
});
groups.push({
date: date as DateTime<true>,
title: formatGroupTitle(date),
assets: groupAssets,
geometry,
offsetTop,
});
offsetTop += HEADER_HEIGHT + geometry.containerHeight;
}
return groups;
}
const dateGroups = $derived(groupAssetsByDate(assets));
const totalHeight = $derived(
dateGroups.length > 0
? dateGroups.at(-1)!.offsetTop + HEADER_HEIGHT + dateGroups.at(-1)!.geometry.containerHeight
: 0,
);
let shiftKeyIsDown = $state(false);
let lastAssetMouseEvent: TimelineAsset | null = $state(null);
let scrollTop = $state(0);
let slidingWindow = $derived.by(() => {
const top = (scrollTop || 0) - slidingWindowOffset;
const bottom = top + viewport.height + slidingWindowOffset;
return { top, bottom };
});
const updateSlidingWindow = () => (scrollTop = document.scrollingElement?.scrollTop ?? 0);
const debouncedOnIntersected = debounce(() => onIntersected?.(), 750, { maxWait: 100, leading: true });
let lastIntersectedHeight = 0;
$effect(() => {
if (totalHeight - slidingWindow.bottom <= viewport.height && lastIntersectedHeight !== totalHeight) {
debouncedOnIntersected();
lastIntersectedHeight = totalHeight;
}
});
function isGroupVisible(group: DateGroup): boolean {
const groupTop = group.offsetTop;
const groupBottom = groupTop + HEADER_HEIGHT + group.geometry.containerHeight;
return groupTop < slidingWindow.bottom && groupBottom > slidingWindow.top;
}
function isAssetVisible(group: DateGroup, assetIndex: number): boolean {
const assetTop = group.offsetTop + HEADER_HEIGHT + group.geometry.getTop(assetIndex);
const assetBottom = assetTop + group.geometry.getHeight(assetIndex);
return assetTop < slidingWindow.bottom && assetBottom > slidingWindow.top;
}
const selectAllAssets = () => {
assetInteraction.selectAssets(assets.map((a) => toTimelineAsset(a)));
};
const deselectAllAssets = () => {
cancelMultiselect(assetInteraction);
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Shift') {
event.preventDefault();
shiftKeyIsDown = true;
}
};
const onKeyUp = (event: KeyboardEvent) => {
if (event.key === 'Shift') {
event.preventDefault();
shiftKeyIsDown = false;
}
};
const handleSelectAssets = (asset: TimelineAsset) => {
if (!asset) {
return;
}
const deselect = assetInteraction.hasSelectedAsset(asset.id);
if (deselect) {
for (const candidate of assetInteraction.assetSelectionCandidates) {
assetInteraction.removeAssetFromMultiselectGroup(candidate.id);
}
assetInteraction.removeAssetFromMultiselectGroup(asset.id);
} else {
for (const candidate of assetInteraction.assetSelectionCandidates) {
assetInteraction.selectAsset(candidate);
}
assetInteraction.selectAsset(asset);
}
assetInteraction.clearAssetSelectionCandidates();
assetInteraction.setAssetSelectionStart(deselect ? null : asset);
};
const handleSelectAssetCandidates = (asset: TimelineAsset | null) => {
if (asset) {
selectAssetCandidates(asset);
}
lastAssetMouseEvent = asset;
};
const selectAssetCandidates = (endAsset: TimelineAsset) => {
if (!shiftKeyIsDown) {
return;
}
const startAsset = assetInteraction.assetSelectionStart;
if (!startAsset) {
return;
}
let start = assets.findIndex((a) => a.id === startAsset.id);
let end = assets.findIndex((a) => a.id === endAsset.id);
if (start > end) {
[start, end] = [end, start];
}
assetInteraction.setAssetSelectionCandidates(assets.slice(start, end + 1).map((a) => toTimelineAsset(a)));
};
const onSelectStart = (event: Event) => {
if (assetInteraction.selectionActive && shiftKeyIsDown) {
event.preventDefault();
}
};
const onDelete = () => {
const hasTrashedAsset = assetInteraction.selectedAssets.some((asset) => asset.isTrashed);
handlePromiseError(trashOrDelete(hasTrashedAsset));
};
const trashOrDelete = async (force: boolean = false) => {
const forceOrNoTrash = force || !featureFlagsManager.value.trash;
const selectedAssets = assetInteraction.selectedAssets;
if ($showDeleteModal && forceOrNoTrash) {
const confirmed = await modalManager.show(AssetDeleteConfirmModal, { size: selectedAssets.length });
if (!confirmed) {
return;
}
}
await deleteAssets(
forceOrNoTrash,
(assetIds) => (assets = assets.filter((asset) => !assetIds.includes(asset.id))),
selectedAssets,
onReload,
);
assetInteraction.clearMultiselect();
};
const toggleArchive = async () => {
const ids = await archiveAssets(
assetInteraction.selectedAssets,
assetInteraction.isAllArchived ? AssetVisibility.Timeline : AssetVisibility.Archive,
);
if (ids) {
assets = assets.filter((asset) => !ids.includes(asset.id));
deselectAllAssets();
}
};
const focusNextAsset = () => moveFocus((element) => element.dataset.thumbnailFocusContainer !== undefined, 'next');
const focusPreviousAsset = () =>
moveFocus((element) => element.dataset.thumbnailFocusContainer !== undefined, 'previous');
let isShortcutModalOpen = false;
const handleOpenShortcutModal = async () => {
if (isShortcutModalOpen) {
return;
}
isShortcutModalOpen = true;
await modalManager.show(ShortcutsModal, {});
isShortcutModalOpen = false;
};
const shortcutList = $derived(
(() => {
if ($isViewerOpen) {
return [];
}
const sc: ShortcutOptions[] = [
{ shortcut: { key: '?', shift: true }, onShortcut: handleOpenShortcutModal },
{ shortcut: { key: '/' }, onShortcut: () => goto(Route.explore()) },
{ shortcut: { key: 'A', ctrl: true }, onShortcut: () => selectAllAssets() },
{ shortcut: { key: 'ArrowRight' }, preventDefault: false, onShortcut: focusNextAsset },
{ shortcut: { key: 'ArrowLeft' }, preventDefault: false, onShortcut: focusPreviousAsset },
];
if (assetInteraction.selectionActive) {
sc.push(
{ shortcut: { key: 'Escape' }, onShortcut: deselectAllAssets },
{ shortcut: { key: 'Delete' }, onShortcut: onDelete },
{ shortcut: { key: 'Delete', shift: true }, onShortcut: () => trashOrDelete(true) },
{ shortcut: { key: 'D', ctrl: true }, onShortcut: () => deselectAllAssets() },
{ shortcut: { key: 'a', shift: true }, onShortcut: toggleArchive },
);
}
return sc;
})(),
);
const handleRandom = async (): Promise<{ id: string } | undefined> => {
if (assets.length === 0) {
return;
}
try {
const randomIndex = Math.floor(Math.random() * assets.length);
const asset = assets[randomIndex];
await navigateToAsset(asset);
return asset;
} catch (error) {
handleError(error, $t('errors.cannot_navigate_next_asset'));
return;
}
};
const updateCurrentAsset = (asset: AssetResponseDto) => {
const index = assets.findIndex((oldAsset) => oldAsset.id === asset.id);
assets[index] = asset;
};
const handleAction = async (action: Action) => {
switch (action.type) {
case AssetAction.ARCHIVE:
case AssetAction.DELETE:
case AssetAction.TRASH: {
const nextAsset = assetCursor.nextAsset ?? assetCursor.previousAsset;
assets.splice(
assets.findIndex((currentAsset) => currentAsset.id === action.asset.id),
1,
);
if (assets.length === 0) {
return await goto(Route.photos());
}
if (nextAsset) {
await navigateToAsset(nextAsset);
}
break;
}
}
};
const assetMouseEventHandler = (asset: TimelineAsset | null) => {
if (assetInteraction.selectionActive) {
handleSelectAssetCandidates(asset);
}
};
$effect(() => {
if (!lastAssetMouseEvent) {
assetInteraction.clearAssetSelectionCandidates();
}
});
$effect(() => {
if (!shiftKeyIsDown) {
assetInteraction.clearAssetSelectionCandidates();
}
});
$effect(() => {
if (shiftKeyIsDown && lastAssetMouseEvent) {
selectAssetCandidates(lastAssetMouseEvent);
}
});
const assetCursor = $derived({
current: $viewingAsset,
nextAsset: getNextAsset(assets, $viewingAsset),
previousAsset: getPreviousAsset(assets, $viewingAsset),
});
</script>
<svelte:document
onkeydown={onKeyDown}
onkeyup={onKeyUp}
onselectstart={onSelectStart}
use:shortcuts={shortcutList}
onscroll={() => updateSlidingWindow()}
/>
{#if assets.length > 0}
<div style:position="relative" style:height={totalHeight + 'px'} style:width={viewport.width + 'px'}>
{#each dateGroups as group (group.date.toISODate())}
{#if isGroupVisible(group)}
<!-- Date header -->
<div
class="absolute flex items-center px-2"
style:top={group.offsetTop + 'px'}
style:height={HEADER_HEIGHT + 'px'}
style:width="100%"
>
<Text fontWeight="medium" class="text-sm md:text-base">{group.title}</Text>
</div>
<!-- Thumbnails -->
<div
class="absolute"
style:top={group.offsetTop + HEADER_HEIGHT + 'px'}
style:height={group.geometry.containerHeight + 'px'}
style:width={group.geometry.containerWidth + 'px'}
>
{#each group.assets as asset, i (asset.id)}
{#if isAssetVisible(group, i)}
{@const currentAsset = toTimelineAsset(asset)}
<div
class="absolute"
style:overflow="clip"
style:top={group.geometry.getTop(i) + 'px'}
style:left={group.geometry.getLeft(i) + 'px'}
style:width={group.geometry.getWidth(i) + 'px'}
style:height={group.geometry.getHeight(i) + 'px'}
>
<Thumbnail
readonly={disableAssetSelect}
onClick={() => {
if (assetInteraction.selectionActive) {
handleSelectAssets(currentAsset);
return;
}
void navigateToAsset(asset);
}}
onSelect={() => handleSelectAssets(currentAsset)}
onMouseEvent={() => assetMouseEventHandler(currentAsset)}
{showArchiveIcon}
asset={currentAsset}
selected={assetInteraction.hasSelectedAsset(currentAsset.id)}
selectionCandidate={assetInteraction.hasSelectionCandidate(currentAsset.id)}
thumbnailWidth={group.geometry.getWidth(i)}
thumbnailHeight={group.geometry.getHeight(i)}
/>
</div>
{/if}
{/each}
</div>
{/if}
{/each}
</div>
{/if}
<!-- Overlay Asset Viewer -->
{#if $isViewerOpen}
<Portal target="body">
{#await import('$lib/components/asset-viewer/asset-viewer.svelte') then { default: AssetViewer }}
<AssetViewer
cursor={assetCursor}
onAction={handleAction}
onRandom={handleRandom}
onAssetChange={updateCurrentAsset}
onClose={() => {
assetViewingStore.showAssetViewer(false);
handlePromiseError(navigate({ targetRoute: 'current', assetId: null }));
}}
/>
{/await}
</Portal>
{/if}
@@ -0,0 +1,41 @@
<script lang="ts">
import RadioButton from '$lib/elements/RadioButton.svelte';
import { Text } from '@immich/ui';
import { t } from 'svelte-i18n';
interface Props {
sortOrder: 'best-match' | 'newest' | 'oldest';
}
let { sortOrder = $bindable() }: Props = $props();
</script>
<div id="sort-order-selection">
<fieldset>
<Text class="mb-2" fontWeight="medium">{$t('sort_order')}</Text>
<div class="flex flex-wrap gap-x-5 gap-y-2 mt-1">
<RadioButton
name="sort-order"
id="sort-best-match"
bind:group={sortOrder}
label={$t('best_match')}
value="best-match"
/>
<RadioButton
name="sort-order"
id="sort-newest"
bind:group={sortOrder}
label={$t('newest_first')}
value="newest"
/>
<RadioButton
name="sort-order"
id="sort-oldest"
bind:group={sortOrder}
label={$t('oldest_first')}
value="oldest"
/>
</div>
</fieldset>
</div>
+1 -2
View File
@@ -3,7 +3,6 @@
import HeaderActionButton from '$lib/components/HeaderActionButton.svelte';
import OnEvents from '$lib/components/OnEvents.svelte';
import UserAvatar from '$lib/components/shared-components/user-avatar.svelte';
import { AlbumPageViewMode } from '$lib/constants';
import {
getAlbumActions,
handleRemoveUserFromAlbum,
@@ -56,7 +55,7 @@
sharedLinks = sharedLinks.filter(({ id }) => sharedLink.id !== id);
};
const { AddUsers, CreateSharedLink } = $derived(getAlbumActions($t, album, AlbumPageViewMode.OPTIONS));
const { AddUsers, CreateSharedLink } = $derived(getAlbumActions($t, album));
let sharedLinks: SharedLinkResponseDto[] = $state([]);
+17 -1
View File
@@ -16,6 +16,7 @@
display: SearchDisplayFilters;
mediaType: MediaType;
rating?: number;
sortOrder: 'best-match' | 'newest' | 'oldest';
};
</script>
@@ -28,13 +29,14 @@
import SearchLocationSection from '$lib/components/shared-components/search-bar/search-location-section.svelte';
import SearchMediaSection from '$lib/components/shared-components/search-bar/search-media-section.svelte';
import SearchPeopleSection from '$lib/components/shared-components/search-bar/search-people-section.svelte';
import SearchSortSection from '$lib/components/shared-components/search-bar/search-sort-section.svelte';
import SearchRatingsSection from '$lib/components/shared-components/search-bar/search-ratings-section.svelte';
import SearchTagsSection from '$lib/components/shared-components/search-bar/search-tags-section.svelte';
import SearchTextSection from '$lib/components/shared-components/search-bar/search-text-section.svelte';
import { preferences } from '$lib/stores/user.store';
import { parseUtcDate } from '$lib/utils/date-time';
import { generateId } from '$lib/utils/generate-id';
import { AssetTypeEnum, AssetVisibility, type MetadataSearchDto, type SmartSearchDto } from '@immich/sdk';
import { AssetOrder, AssetTypeEnum, AssetVisibility, type MetadataSearchDto, type SmartSearchDto } from '@immich/sdk';
import { Button, HStack, Modal, ModalBody, ModalFooter } from '@immich/ui';
import { mdiTune } from '@mdi/js';
import type { DateTime } from 'luxon';
@@ -111,6 +113,12 @@
? MediaType.Video
: MediaType.All,
rating: searchQuery.rating,
sortOrder:
'order' in searchQuery && searchQuery.order
? searchQuery.order === AssetOrder.Asc
? 'oldest'
: 'newest'
: 'best-match',
});
const resetForm = () => {
@@ -130,6 +138,7 @@
},
mediaType: MediaType.All,
rating: undefined,
sortOrder: 'best-match',
};
};
@@ -143,6 +152,9 @@
const query = filter.query || undefined;
const order =
filter.sortOrder === 'newest' ? AssetOrder.Desc : filter.sortOrder === 'oldest' ? AssetOrder.Asc : undefined;
let payload: SmartSearchDto | MetadataSearchDto = {
query: filter.queryType === 'smart' ? query : undefined,
ocr: filter.queryType === 'ocr' ? query : undefined,
@@ -163,6 +175,7 @@
tagIds: filter.tagIds === null ? null : filter.tagIds.size > 0 ? [...filter.tagIds] : undefined,
type,
rating: filter.rating,
order,
};
onClose(payload);
@@ -218,6 +231,9 @@
<!-- DISPLAY OPTIONS -->
<SearchDisplaySection bind:filters={filter.display} />
<!-- SORT ORDER -->
<SearchSortSection bind:sortOrder={filter.sortOrder} />
</div>
</div>
</form>
+3 -13
View File
@@ -1,6 +1,5 @@
import { goto } from '$app/navigation';
import ToastAction from '$lib/components/ToastAction.svelte';
import { AlbumPageViewMode } from '$lib/constants';
import { authManager } from '$lib/managers/auth-manager.svelte';
import { eventManager } from '$lib/managers/event-manager.svelte';
import type { TimelineAsset } from '$lib/managers/timeline-manager/types';
@@ -32,7 +31,7 @@ import {
type UserResponseDto,
} from '@immich/sdk';
import { modalManager, toastManager, type ActionItem } from '@immich/ui';
import { mdiArrowLeft, mdiLink, mdiPlus, mdiPlusBoxOutline, mdiShareVariantOutline, mdiUpload } from '@mdi/js';
import { mdiLink, mdiPlus, mdiPlusBoxOutline, mdiShareVariantOutline, mdiUpload } from '@mdi/js';
import { type MessageFormatter } from 'svelte-i18n';
import { get } from 'svelte/store';
@@ -46,7 +45,7 @@ export const getAlbumsActions = ($t: MessageFormatter) => {
return { Create };
};
export const getAlbumActions = ($t: MessageFormatter, album: AlbumResponseDto, viewMode: AlbumPageViewMode) => {
export const getAlbumActions = ($t: MessageFormatter, album: AlbumResponseDto) => {
const isOwned = get(user).id === album.ownerId;
const Share: ActionItem = {
@@ -73,16 +72,7 @@ export const getAlbumActions = ($t: MessageFormatter, album: AlbumResponseDto, v
onAction: () => modalManager.show(SharedLinkCreateModal, { albumId: album.id }),
};
const Close: ActionItem = {
title: $t('go_back'),
type: $t('command'),
icon: mdiArrowLeft,
onAction: () => goto(Route.albums()),
$if: () => viewMode === AlbumPageViewMode.VIEW,
shortcuts: { key: 'Escape' },
};
return { Share, AddUsers, CreateSharedLink, Close };
return { Share, AddUsers, CreateSharedLink };
};
export const getAlbumAssetsActions = ($t: MessageFormatter, album: AlbumResponseDto, assets: TimelineAsset[]) => {
@@ -127,10 +127,6 @@
await handleCloseSelectAssets();
return;
}
if (viewMode === AlbumPageViewMode.OPTIONS) {
viewMode = AlbumPageViewMode.VIEW;
return;
}
if ($showAssetViewer) {
return;
}
@@ -138,7 +134,7 @@
cancelMultiselect(assetInteraction);
return;
}
return;
await goto(Route.albums());
};
const refreshAlbum = async () => {
@@ -305,14 +301,24 @@
return;
}
album.albumUsers = album.albumUsers.map((albumUser) =>
const albumUsers = album.albumUsers.map((albumUser) =>
albumUser.user.id === userId ? { ...albumUser, role } : albumUser,
);
album = { ...album, albumUsers };
};
const { Cast } = $derived(getGlobalActions($t));
const { Share, Close } = $derived(getAlbumActions($t, album, viewMode));
const { Share } = $derived(getAlbumActions($t, album));
const { AddAssets, Upload } = $derived(getAlbumAssetsActions($t, album, timelineInteraction.selectedAssets));
const Close = $derived({
title: $t('go_back'),
type: $t('command'),
icon: mdiArrowLeft,
onAction: handleEscape,
$if: () => !$showAssetViewer,
shortcuts: { key: 'Escape' },
});
</script>
<OnEvents
@@ -352,7 +358,7 @@
id={album.id}
albumName={album.albumName}
{isOwned}
onUpdate={(albumName) => (album.albumName = albumName)}
onUpdate={(albumName) => (album = { ...album, albumName })}
/>
{#if album.assetCount > 0}
@@ -401,8 +407,11 @@
<ActionButton action={Share} />
</div>
{/if}
<!-- ALBUM DESCRIPTION -->
<AlbumDescription id={album.id} bind:description={album.description} {isOwned} />
<AlbumDescription
id={album.id}
{isOwned}
bind:description={() => album.description, (description) => (album = { ...album, description })}
/>
</section>
{/if}
@@ -5,6 +5,7 @@
import OnEvents from '$lib/components/OnEvents.svelte';
import ButtonContextMenu from '$lib/components/shared-components/context-menu/button-context-menu.svelte';
import ControlAppBar from '$lib/components/shared-components/control-app-bar.svelte';
import DateGroupedGalleryViewer from '$lib/components/shared-components/gallery-viewer/date-grouped-gallery-viewer.svelte';
import GalleryViewer from '$lib/components/shared-components/gallery-viewer/gallery-viewer.svelte';
import SearchBar from '$lib/components/shared-components/search-bar/search-bar.svelte';
import ArchiveAction from '$lib/components/timeline/actions/ArchiveAction.svelte';
@@ -68,6 +69,7 @@
let searchQuery = $derived(page.url.searchParams.get(QueryParameter.QUERY));
let smartSearchEnabled = $derived(featureFlagsManager.value.smartSearch);
let terms = $derived(searchQuery ? JSON.parse(searchQuery) : {});
let isSortedByDate = $derived(!!terms.order);
const isAllUserOwned = $derived(
$user && assetInteraction.selectedAssets.every((asset) => asset.ownerId === $user.id),
@@ -196,6 +198,7 @@
description: $t('description'),
queryAssetId: $t('query_asset_id'),
ocr: $t('ocr'),
order: $t('sort_order'),
};
return keyMap[key] || key;
}
@@ -296,15 +299,27 @@
>
<section id="search-content">
{#if searchResultAssets.length > 0}
<GalleryViewer
assets={searchResultAssets}
{assetInteraction}
onIntersected={loadNextPage}
showArchiveIcon={true}
{viewport}
onReload={onSearchQueryUpdate}
slidingWindowOffset={searchResultsElement.offsetTop}
/>
{#if isSortedByDate}
<DateGroupedGalleryViewer
assets={searchResultAssets}
{assetInteraction}
onIntersected={loadNextPage}
showArchiveIcon={true}
{viewport}
onReload={onSearchQueryUpdate}
slidingWindowOffset={searchResultsElement.offsetTop}
/>
{:else}
<GalleryViewer
assets={searchResultAssets}
{assetInteraction}
onIntersected={loadNextPage}
showArchiveIcon={true}
{viewport}
onReload={onSearchQueryUpdate}
slidingWindowOffset={searchResultsElement.offsetTop}
/>
{/if}
{:else if !isLoading}
<div class="flex min-h-[calc(66vh-11rem)] w-full place-content-center items-center dark:text-white">
<div class="flex flex-col content-center items-center text-center">