diff --git a/lib/core/databases/adapters/objectbox/entities.dart b/lib/core/databases/adapters/objectbox/entities.dart index ab9fdda78..7b46d8b97 100644 --- a/lib/core/databases/adapters/objectbox/entities.dart +++ b/lib/core/databases/adapters/objectbox/entities.dart @@ -212,6 +212,7 @@ class TagObjectBox extends BaseObjectBox { String? emoji; int? categoryId; + int? colorSeedValue; @override @Property(type: PropertyType.date) @@ -235,6 +236,7 @@ class TagObjectBox extends BaseObjectBox { required this.version, required this.emoji, required this.categoryId, + required this.colorSeedValue, required this.createdAt, required this.updatedAt, required this.permanentlyDeletedAt, diff --git a/lib/core/databases/adapters/objectbox/helpers/tags_box_transformer.dart b/lib/core/databases/adapters/objectbox/helpers/tags_box_transformer.dart index ba001830d..536e72699 100644 --- a/lib/core/databases/adapters/objectbox/helpers/tags_box_transformer.dart +++ b/lib/core/databases/adapters/objectbox/helpers/tags_box_transformer.dart @@ -20,6 +20,7 @@ TagObjectBox _modelToObject(Map options) { version: model.version, emoji: model.emoji, categoryId: model.categoryId, + colorSeedValue: model.colorSeedValue, createdAt: model.createdAt, updatedAt: model.updatedAt, lastSavedDeviceId: model.lastSavedDeviceId, @@ -37,6 +38,7 @@ TagDbModel _objectToModel(Map options) { title: object.title, emoji: object.emoji, categoryId: object.categoryId, + colorSeedValue: object.colorSeedValue, createdAt: object.createdAt, updatedAt: object.updatedAt, lastSavedDeviceId: object.lastSavedDeviceId, diff --git a/lib/core/databases/adapters/objectbox/stories_box.dart b/lib/core/databases/adapters/objectbox/stories_box.dart index 261dce481..c38264f29 100644 --- a/lib/core/databases/adapters/objectbox/stories_box.dart +++ b/lib/core/databases/adapters/objectbox/stories_box.dart @@ -252,12 +252,19 @@ class StoriesBox extends BaseBox { AppLogger.info('🔍 Reindexed Stories: $count (Failed: $failed)'); } + /// With [namedOnly], only stories whose place has a name: filtered before [limit], so unnamed stories can't + /// crowd out a named one. Future> getStoriesWithLocation({ SpLatLngBounds? bounds, int? limit, + bool namedOnly = false, }) async { Condition conditions = _storiesWithLocationConditions(); + if (namedOnly) { + conditions = conditions.and(StoryObjectBox_.placeName.notNull()).and(StoryObjectBox_.placeName.notEquals('')); + } + if (bounds != null) { conditions = conditions .and(StoryObjectBox_.latitude.between(bounds.south, bounds.north)) @@ -308,6 +315,76 @@ class StoriesBox extends BaseBox { return result.map(_objectToMapStoryObject).toList(); } + /// Every named place from stories (only those in [bounds], when given), each identical place once — for + /// picking a place by name, or the nearest one. Never limited: many stories at one place still come back as + /// that one place, so none nearby is left out. Reads only the place column (no story content), decoded off + /// the main isolate. + Future> getNamedPlaces({SpLatLngBounds? bounds}) async { + var conditions = _storiesWithLocationConditions() + .and(StoryObjectBox_.placeName.notNull()) + .and(StoryObjectBox_.placeName.notEquals('')); + if (bounds != null) { + conditions = conditions + .and(StoryObjectBox_.latitude.between(bounds.south, bounds.north)) + .and(StoryObjectBox_.longitude.between(bounds.west, bounds.east)); + } + final query = box.query(conditions).build(); + + try { + final placeJsons = (query.property(StoryObjectBox_.place)..distinct = true).find(); + return await Isolate.run(() { + final places = []; + for (final json in placeJsons) { + try { + if (jsonDecode(json) case final Map map) places.add(PlaceDbModel.fromJson(map)); + } catch (_) { + // One malformed place mustn't empty the whole list. + } + } + return places; + }); + } finally { + query.close(); + } + } + + /// Sets story [id]'s place to [place] in one write transaction, only while its saved place still passes + /// [isExpected]: a place that arrives late (a GPS fix, a name lookup) can neither write back an older copy of + /// the story nor replace a place changed meanwhile. Only the place (and [StoryObjectBox.updatedAt]) changes. + /// [exists] is false when there's no such story (not saved yet, or permanently deleted); [updated] is the + /// story as saved, null when nothing was written. + Future<({bool exists, StoryDbModel? updated})> setPlaceIf( + int id, + PlaceDbModel place, { + required bool Function(PlaceDbModel? saved) isExpected, + }) async { + final written = store.runInTransaction(TxMode.write, () { + final object = box.get(id); + if (object == null || object.permanentlyDeletedAt != null) return null; + + final saved = object.place != null ? PlaceDbModel.fromJson(jsonDecode(object.place!)) : null; + if (!isExpected(saved)) return false; + + object + ..latitude = place.latitude + ..longitude = place.longitude + ..placeName = place.placeName + ..place = jsonEncode(place.toJson()) + ..updatedAt = DateTime.now() + // The place name is searched: reindexed when the search view opens. + ..searchMetadata = null + ..setDeviceId(); + box.put(object, mode: PutMode.update); + return true; + }); + + if (written != true) return (exists: written != null, updated: null); + + final updated = await find(id); + await afterCommit(id, updated); + return (exists: true, updated: updated); + } + Condition _storiesWithLocationConditions() { return StoryObjectBox_.id .notNull() diff --git a/lib/core/databases/models/place_db_model.dart b/lib/core/databases/models/place_db_model.dart index 093ffce8a..4609a51d2 100644 --- a/lib/core/databases/models/place_db_model.dart +++ b/lib/core/databases/models/place_db_model.dart @@ -46,6 +46,15 @@ class PlaceDbModel extends BaseDbModel { return '${latitude.toStringAsFixed(4)}, ${longitude.toStringAsFixed(4)}'; } + /// "Locality, Country", or null when neither is known. + String? get areaLabel { + final parts = [locality?.trim(), country?.trim()].whereType().where((e) => e.isNotEmpty); + return parts.isEmpty ? null : parts.join(', '); + } + + /// A place's second line: its area, or its coordinates when the area isn't known. + String get areaOrCoordinatesLabel => areaLabel ?? '${latitude.toStringAsFixed(5)}, ${longitude.toStringAsFixed(5)}'; + @override int get id => 0; diff --git a/lib/core/databases/models/tag_db_model.dart b/lib/core/databases/models/tag_db_model.dart index 27fc67f54..43923c47f 100644 --- a/lib/core/databases/models/tag_db_model.dart +++ b/lib/core/databases/models/tag_db_model.dart @@ -1,3 +1,5 @@ +import 'dart:ui'; + import 'package:copy_with_extension/copy_with_extension.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:storypad/core/databases/adapters/objectbox/tags_box.dart'; @@ -21,6 +23,10 @@ class TagDbModel extends BaseDbModel { final DateTime createdAt; final int? categoryId; + /// The picked color, as ARGB. Its chip and dot colors are derived per brightness by + /// `TagColorService`, so only the seed is stored. + final int? colorSeedValue; + @override final DateTime updatedAt; final String? lastSavedDeviceId; @@ -40,16 +46,19 @@ class TagDbModel extends BaseDbModel { required this.updatedAt, required this.lastSavedDeviceId, required this.permanentlyDeletedAt, + this.colorSeedValue, int? index, }) : index = index ?? 0; bool get feeling => categoryId == TagCategoryDbModel.feeling().id; bool get isPerson => categoryId == TagCategoryDbModel.peopleId; + Color? get colorSeed => colorSeedValue != null ? Color(colorSeedValue!) : null; TagDbModel.fromIDTitle(this.id, this.title) : version = 0, emoji = null, categoryId = null, + colorSeedValue = null, index = 0, createdAt = DateTime.now(), updatedAt = DateTime.now(), diff --git a/lib/core/databases/models/tag_db_model.g.dart b/lib/core/databases/models/tag_db_model.g.dart index 0a60a67dc..e89ff4e24 100644 --- a/lib/core/databases/models/tag_db_model.g.dart +++ b/lib/core/databases/models/tag_db_model.g.dart @@ -25,6 +25,8 @@ abstract class _$TagDbModelCWProxy { TagDbModel permanentlyDeletedAt(DateTime? permanentlyDeletedAt); + TagDbModel colorSeedValue(int? colorSeedValue); + TagDbModel index(int? index); /// Creates a new instance with the provided field values. @@ -44,6 +46,7 @@ abstract class _$TagDbModelCWProxy { DateTime updatedAt, String? lastSavedDeviceId, DateTime? permanentlyDeletedAt, + int? colorSeedValue, int? index, }); } @@ -85,9 +88,12 @@ class _$TagDbModelCWProxyImpl implements _$TagDbModelCWProxy { call(permanentlyDeletedAt: permanentlyDeletedAt); @override - TagDbModel index(int? index) => call(index: index); + TagDbModel colorSeedValue(int? colorSeedValue) => + call(colorSeedValue: colorSeedValue); @override + TagDbModel index(int? index) => call(index: index); + /// Creates a new instance with the provided field values. /// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `TagDbModel(...).copyWith.fieldName(value)`. /// @@ -95,6 +101,7 @@ class _$TagDbModelCWProxyImpl implements _$TagDbModelCWProxy { /// ```dart /// TagDbModel(...).copyWith(id: 12, name: "My name") /// ``` + @override TagDbModel call({ Object? id = const $CopyWithPlaceholder(), Object? version = const $CopyWithPlaceholder(), @@ -105,6 +112,7 @@ class _$TagDbModelCWProxyImpl implements _$TagDbModelCWProxy { Object? updatedAt = const $CopyWithPlaceholder(), Object? lastSavedDeviceId = const $CopyWithPlaceholder(), Object? permanentlyDeletedAt = const $CopyWithPlaceholder(), + Object? colorSeedValue = const $CopyWithPlaceholder(), Object? index = const $CopyWithPlaceholder(), }) { return TagDbModel( @@ -144,6 +152,10 @@ class _$TagDbModelCWProxyImpl implements _$TagDbModelCWProxy { ? _value.permanentlyDeletedAt // ignore: cast_nullable_to_non_nullable : permanentlyDeletedAt as DateTime?, + colorSeedValue: colorSeedValue == const $CopyWithPlaceholder() + ? _value.colorSeedValue + // ignore: cast_nullable_to_non_nullable + : colorSeedValue as int?, index: index == const $CopyWithPlaceholder() ? _value.index // ignore: cast_nullable_to_non_nullable @@ -175,6 +187,7 @@ TagDbModel _$TagDbModelFromJson(Map json) => TagDbModel( permanentlyDeletedAt: json['permanently_deleted_at'] == null ? null : DateTime.parse(json['permanently_deleted_at'] as String), + colorSeedValue: (json['color_seed_value'] as num?)?.toInt(), index: (json['index'] as num?)?.toInt(), )..storiesCount = (json['stories_count'] as num?)?.toInt(); @@ -188,6 +201,7 @@ Map _$TagDbModelToJson( 'emoji': instance.emoji, 'created_at': instance.createdAt.toIso8601String(), 'category_id': instance.categoryId, + 'color_seed_value': instance.colorSeedValue, 'updated_at': instance.updatedAt.toIso8601String(), 'last_saved_device_id': instance.lastSavedDeviceId, 'permanently_deleted_at': instance.permanentlyDeletedAt?.toIso8601String(), diff --git a/lib/core/mixins/debounched_callback.dart b/lib/core/mixins/debounched_callback.dart index 78f17784e..f834f173b 100644 --- a/lib/core/mixins/debounched_callback.dart +++ b/lib/core/mixins/debounched_callback.dart @@ -5,10 +5,8 @@ mixin DebounchedCallback { final Map _timers = {}; Timer? _singleTimer; - Timer? _timer(String? key) { - if (_timers.containsKey(key)) return _timers[key]; - return _singleTimer; - } + // With a key: only that key's timer (a key not used yet has none). Without: the last one started. + Timer? _timer(String? key) => key == null ? _singleTimer : _timers[key]; void debouncedCallback( VoidCallback callback, { diff --git a/lib/core/objects/sp_latlng.dart b/lib/core/objects/sp_latlng.dart index 9fc96fcc6..5f934a11b 100644 --- a/lib/core/objects/sp_latlng.dart +++ b/lib/core/objects/sp_latlng.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + /// Platform-agnostic latitude/longitude coordinate. /// /// Keeps the [MapAdapter] interface free from package-specific types like @@ -8,6 +10,21 @@ class SpLatLng { final double latitude; final double longitude; + /// Great-circle distance in meters (haversine). + double distanceTo(SpLatLng other) { + const double earthRadius = 6371000.0; + double rad(double degrees) => degrees * math.pi / 180.0; + + final dLat = rad(other.latitude - latitude); + final dLng = rad(other.longitude - longitude); + // Clamped: rounding can push it just past 1 for antipodal points, and sqrt(1 - a) would be NaN. + final a = + (math.pow(math.sin(dLat / 2), 2) + + math.cos(rad(latitude)) * math.cos(rad(other.latitude)) * math.pow(math.sin(dLng / 2), 2)) + .clamp(0.0, 1.0); + return earthRadius * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)); + } + @override String toString() => 'SpLatLng($latitude, $longitude)'; diff --git a/lib/core/services/export/export_stories_to_markdown_service.dart b/lib/core/services/export/export_stories_to_markdown_service.dart index 148f537bf..3276bd066 100644 --- a/lib/core/services/export/export_stories_to_markdown_service.dart +++ b/lib/core/services/export/export_stories_to_markdown_service.dart @@ -1,7 +1,15 @@ import 'dart:io'; import 'package:storypad/core/databases/models/story_content_db_model.dart'; import 'package:storypad/core/databases/models/story_db_model.dart'; +import 'package:storypad/core/databases/models/story_page_db_model.dart'; import 'package:storypad/core/services/quill/quill_delta_to_plain_text_service.dart'; +import 'package:storypad/core/types/asset_type.dart'; +import 'package:storypad/widgets/rich_editor/embeds/sp_audio_embed.dart'; +import 'package:storypad/widgets/rich_editor/embeds/sp_media_embed.dart'; +import 'package:storypad/widgets/rich_editor/embeds/sp_date_embed.dart'; +import 'package:storypad/widgets/rich_editor/sp_embeds.dart'; +import 'package:storypad_editor/storypad_editor.dart'; +import 'package:storypad_editor/super_editor.dart'; /// Service to export stories to Obsidian-compatible markdown files /// organized by year with proper YAML frontmatter. @@ -20,7 +28,7 @@ class ExportStoriesToMarkdownService { /// /// Each markdown file contains: /// - YAML frontmatter with metadata - /// - Story content with page headers + /// - Each page's stored Markdown, embeds as their stored HTML tags /// - Page separators using `---` /// /// [tagNameGetter] - Optional callback to resolve tag ID to tag name @@ -152,47 +160,67 @@ class ExportStoriesToMarkdownService { return buffer.toString(); } + /// Each page's stored Markdown (title included, as its leading heading), pages separated by `---`. static String _buildMarkdownContent(StoryContentDbModel content) { - final buffer = StringBuffer(); - - if (content.richPages != null && content.richPages!.isNotEmpty) { - for (int i = 0; i < content.richPages!.length; i++) { - final page = content.richPages![i]; + final pages = content.richPages ?? const []; + return pages.map(_pageMarkdown).where((markdown) => markdown.isNotEmpty).join('\n\n---\n\n'); + } - // Add page title as header - if (page.title?.isNotEmpty == true) { - buffer.write('# ${page.title}\n'); - } else if (content.richPages!.length > 1) { - buffer.write('# Page ${i + 1}\n'); - } + /// Writes Markdown like `SpEmbeds.codec`, except that asset paths are relative to the year folder each file is + /// written to (see [_ExportMediaEmbed]). + static final _exportCodec = StoryCodec( + embeds: const [ + _ExportMediaEmbed(), + _ExportAudioEmbed(), + SpDateEmbed(), + ], + ); + + /// [page]'s Markdown as stored: embeds stay the HTML tags they're stored as (``, `