Skip to content

High performance self-hosted photo and video management solution.

6.9 KB
Raw Blame
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/extensions/datetime_extensions.dart';
import 'package:immich_mobile/extensions/duration_extensions.dart';
import 'package:immich_mobile/generated/translations.g.dart';
import 'package:immich_mobile/widgets/common/dropdown_search_menu.dart';
import 'package:intl/intl.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/timezone.dart';

part 'date_time_picker.freezed.dart';

Future<String?> showDateTimePicker({
  required BuildContext context,
  DateTime? initialDateTime,
  String? initialTZ,
  Duration? initialTZOffset,
}) {
  return showDialog<String?>(
    context: context,
    builder: (context) =>
        _DateTimePicker(initialDateTime: initialDateTime, initialTZ: initialTZ, initialTZOffset: initialTZOffset),
  );
}

String _getFormattedOffset(int offsetInMilli, tz.Location location) {
  return "${location.name} (${Duration(milliseconds: offsetInMilli).formatAsOffset()})";
}

class _DateTimePicker extends HookWidget {
  final DateTime? initialDateTime;
  final String? initialTZ;
  final Duration? initialTZOffset;

  const _DateTimePicker({this.initialDateTime, this.initialTZ, this.initialTZOffset});

  _TimeZoneOffset _getInitiationLocation() {
    if (initialTZ != null) {
      try {
        return _TimeZoneOffset.fromLocation(tz.timeZoneDatabase.get(initialTZ!));
      } on LocationNotFoundException {
        // no-op
      }
    }

    final Duration? tzOffset = initialTZOffset ?? initialDateTime?.timeZoneOffset;

    if (tzOffset != null) {
      final offsetInMilli = tzOffset.inMilliseconds;
      // get all locations with matching offset
      final locations = tz.timeZoneDatabase.locations.values.where(
        (location) => location.currentTimeZone.offset == offsetInMilli,
      );
      // Prefer locations with abbreviation first
      final location =
          locations.firstWhereOrNull((e) => !e.currentTimeZone.abbreviation.contains("0")) ?? locations.firstOrNull;
      if (location != null) {
        return _TimeZoneOffset.fromLocation(location);
      }
    }

    return _TimeZoneOffset.fromLocation(tz.getLocation("UTC"));
  }

  // returns a list of location<name> along with it's offset in duration
  List<_TimeZoneOffset> getAllTimeZones() {
    return tz.timeZoneDatabase.locations.values.map(_TimeZoneOffset.fromLocation).sorted().toList();
  }

  @override
  Widget build(BuildContext context) {
    final date = useState<DateTime>(initialDateTime ?? DateTime.now());
    final tzOffset = useState<_TimeZoneOffset>(_getInitiationLocation());
    final timeZones = useMemoized(() => getAllTimeZones(), const []);
    final menuEntries = timeZones
        .map(
          (timezone) => DropdownMenuEntry<_TimeZoneOffset>(
            value: timezone,
            label: timezone.display,
            style: ButtonStyle(textStyle: WidgetStatePropertyAll(context.textTheme.bodyMedium)),
          ),
        )
        .toList();

    Future<void> pickDate() async {
      final now = DateTime.now();
      // Handles cases where the date from the asset is far off in the future
      final initialDate = date.value.isAfter(now) ? now : date.value;
      final newDate = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: DateTime(1800),
        lastDate: now,
      );
      if (newDate == null || !context.mounted) {
        return;
      }

      final newTime = await showTimePicker(context: context, initialTime: TimeOfDay.fromDateTime(date.value));

      if (newTime == null) {
        return;
      }

      date.value = newDate.copyWith(hour: newTime.hour, minute: newTime.minute);
    }

    void popWithDateTime() {
      final formattedDateTime = DateFormat("yyyy-MM-dd'T'HH:mm:ss", 'en').format(date.value);
      final dtWithOffset =
          formattedDateTime + Duration(milliseconds: tzOffset.value.offsetInMilliseconds).formatAsOffset();
      context.pop(dtWithOffset);
    }

    return AlertDialog(
      contentPadding: const EdgeInsets.symmetric(vertical: 32, horizontal: 18),
      actions: [
        TextButton(
          onPressed: () => context.pop(),
          child: Text(
            context.t.cancel,
            style: context.textTheme.bodyMedium?.copyWith(
              fontWeight: FontWeight.w600,
              color: context.colorScheme.error,
            ),
          ),
        ),
        TextButton(
          onPressed: popWithDateTime,
          child: Text(
            context.t.action_common_update,
            style: context.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: context.primaryColor),
          ),
        ),
      ],
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(context.t.date_and_time, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
          const SizedBox(height: 32),
          ListTile(
            tileColor: context.colorScheme.surfaceContainerHighest,
            shape: ShapeBorder.lerp(
              const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
              const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
              1,
            ),
            trailing: Icon(Icons.edit_outlined, size: 18, color: context.primaryColor),
            title: Text(
              DateFormat("dd-MM-yyyy hh:mm a", resolvedDateTimeLocale()).format(date.value),
              style: context.textTheme.bodyMedium,
            ),
            onTap: pickDate,
          ),
          const SizedBox(height: 24),
          DropdownSearchMenu(
            trailingIcon: Icon(Icons.arrow_drop_down, color: context.primaryColor),
            hintText: context.t.timezone,
            label: Text(context.t.timezone),
            textStyle: context.textTheme.bodyMedium,
            onSelected: (value) => tzOffset.value = value,
            initialSelection: tzOffset.value,
            dropdownMenuEntries: menuEntries,
          ),
        ],
      ),
    );
  }
}

@freezed
abstract class _TimeZoneOffset with _$TimeZoneOffset implements Comparable<_TimeZoneOffset> {
  const _TimeZoneOffset._();

  const factory _TimeZoneOffset({required String display, required Location location}) = __TimeZoneOffset;

  factory _TimeZoneOffset.fromLocation(tz.Location l) =>
      _TimeZoneOffset(display: _getFormattedOffset(l.currentTimeZone.offset, l), location: l);

  int get offsetInMilliseconds => location.currentTimeZone.offset;

  @override
  int compareTo(_TimeZoneOffset other) {
    final offset = offsetInMilliseconds.compareTo(other.offsetInMilliseconds);
    return offset != 0 ? offset : location.name.compareTo(other.location.name);
  }
}