Skip to content

Commit 8878cf7

Browse files
authored
refactor generating new attachment names (#505)
1 parent 0fc34a3 commit 8878cf7

File tree

2 files changed

+15
-12
lines changed

2 files changed

+15
-12
lines changed

toolkit/featureforms/src/main/java/com/arcgismaps/toolkit/featureforms/internal/components/attachment/AttachmentElementState.kt

+14-11
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ internal class FormAttachmentState(
272272
* The name of the attachment. Setting the name will update the [FormAttachment.name] property.
273273
* This is backed by a [MutableState] and can be observed by the composition.
274274
*/
275-
var name : String
275+
var name: String
276276
get() = _name.value
277277
set(value) {
278278
formAttachment?.name = value
@@ -523,15 +523,18 @@ internal fun FormAttachmentType.getIcon(): ImageVector = when (this) {
523523
/**
524524
* Returns a new attachment name based on the content type.
525525
*/
526-
internal fun List<FormAttachmentState>.getNewAttachmentNameForContentType(contentType: String): String {
527-
val prefix = when {
528-
contentType.startsWith("image/") -> "Image"
529-
contentType.startsWith("video/") -> "Video"
530-
else -> "Attachment"
531-
}
532-
val count = this.count { entry ->
533-
entry.contentType.split("/").firstOrNull()
534-
.equals(contentType.split("/").firstOrNull(), ignoreCase = true)
526+
internal fun AttachmentElementState.getNewAttachmentNameForContentType(contentType: String): String {
527+
// use the content type prefix to generate a new attachment name
528+
val prefix = contentType.split("/").firstOrNull()?.replaceFirstChar(Char::titlecase)
529+
?: "Attachment"
530+
var count = attachments.count { entry ->
531+
// count the number of attachments with the same content type
532+
entry.contentType == contentType
535533
} + 1
536-
return "$prefix $count"
534+
// create a set of attachment names to check for duplicates
535+
val names = attachments.mapTo(hashSetOf()) { it.name }
536+
while (names.contains("${prefix}$count")) {
537+
count++
538+
}
539+
return "${prefix}$count"
537540
}

toolkit/featureforms/src/main/java/com/arcgismaps/toolkit/featureforms/internal/utils/Dialog.kt

+1-1
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ private suspend fun AttachmentElementState.addAttachmentFromUri(
387387
return@withContext Result.failure(Exception(context.getString(R.string.attachment_error)))
388388
}
389389
// generate a name for the attachment
390-
var name = "${attachments.getNewAttachmentNameForContentType(contentType)}.$extension"
390+
var name = "${getNewAttachmentNameForContentType(contentType)}.$extension"
391391
// size of the attachment
392392
var size = 0L
393393
// get the name and size of the attachment

0 commit comments

Comments
 (0)