diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 2a695034..fa7d0073 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -585,6 +585,9 @@ Year Duration in seconds Number + Date + Latest year + Earliest year Propose event Paste an unsigned Nostr event for the group to sign. It is filed by kind: a profile (kind 0), a post (kind 1), a relay list, or a curated schema (kind 31889). The group signs it, so it takes a quorum. The author is the group and the time is now, whatever the paste says about either. @@ -637,8 +640,12 @@ Pick one of the options. A whole number. More than zero. + A date, as YYYY, YYYY-MM or YYYY-MM-DD. At least %1$s. At most %1$s. + %1$s or later. + %1$s or earlier. + This list uses a field type this app doesn't support (%1$s). At most %1$s characters. Must match %1$s. At least one of these is needed: %1$s. diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedSchema.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedSchema.kt index 8c84e0fe..4ff20a7f 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedSchema.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/GroupCuratedSchema.kt @@ -131,10 +131,13 @@ data class GroupCuratedSchema( * The same check `CuratedSuggestion.queueOf` makes on a kind 31890 off a * relay, made before the group is asked to sign one: a signature is the * most expensive thing this app does, and an entry the queue would then - * refuse to count is a quorum spent on nothing. + * refuse to count is a quorum spent on nothing. And one check the queue + * does not make, first: a required field this app cannot write is one + * every other client's queue would refuse the entry for, see + * [CuratedEntryEvent.verifyWritable]. */ fun verifyCanonical(template: EventTemplate<*>): List = - CuratedEntryEvent.verifyCanonical( + CuratedEntryEvent.verifyWritable(schema) + CuratedEntryEvent.verifyCanonical( event = CuratedEntryEvent.preview(template, publicKey), schema = schema, coordinate = coordinate(), diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedEntryEvent.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedEntryEvent.kt index 31fa6940..4c46ccf6 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedEntryEvent.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedEntryEvent.kt @@ -152,6 +152,25 @@ object CuratedEntryEvent { } } + /** + * Every reason this app cannot compose an entry under [schema], or nothing: + * one problem per required field whose type it does not know. + * + * The reader's blind spot, seen from the write side. A field of a type this + * app does not know is left out of the reading -- an entry is checked + * against the fields a reader understands, and that tolerance is the NIP's + * -- but an entry *written* without one the schema requires is refused by + * every client that does know the type, for the field it lacks. So it is a + * reason to refuse before a quorum is spent, filed under the field and + * named for what it is, so the member knows it is the app and not the + * entry that falls short. An optional one is left out the way the reading + * leaves it out. + */ + fun verifyWritable(schema: CuratedSchema): List = + schema.unsupportedFields + .filter { it.isRequired } + .map { CuratedEntryProblem(it.name, CuratedEntryProblem.Reason.UnsupportedType) } + /** * The unsigned canonical entry for the curator to sign: [values] laid out as * the schema's tags, rooted at the schema's [coordinate], and pointing back @@ -278,11 +297,11 @@ object CuratedEntryEvent { * One value against its field's type and config, or the first thing wrong * with it. * - * `max` is a bound on numeric types and a length on everything else, and a - * numeric field returns before the length check so the two never meet. - * A pattern the platform cannot compile counts as not matched: the schema - * asked for a check this reader cannot make, and an entry it cannot check - * is one it cannot vouch for. + * `max` is a bound on numeric types -- and on the year of a date -- and a + * length on everything else, and a bounded field returns before the length + * check so the two never meet. A pattern the platform cannot compile counts + * as not matched: the schema asked for a check this reader cannot make, and + * an entry it cannot check is one it cannot vouch for. */ fun checkValue(field: CuratedField, value: String): CuratedEntryProblem.Reason? { val trimmed = value.trim() @@ -319,6 +338,14 @@ object CuratedEntryEvent { // A numeric `max` is a bound, not a length cap. return null } + + CuratedFieldType.Date -> { + val date = CuratedDate.parse(trimmed) ?: return CuratedEntryProblem.Reason.NotADate + config.min?.let { if (date.year < it) return CuratedEntryProblem.Reason.BelowMinimum } + config.max?.let { if (date.year > it) return CuratedEntryProblem.Reason.AboveMaximum } + // A date's `max` bounds the year, not the length. + return null + } } config.max?.let { if (trimmed.length > it) return CuratedEntryProblem.Reason.TooLong } @@ -555,11 +582,21 @@ data class CuratedEntryProblem(val field: String, val reason: Reason) { NotAnOption, NotAWholeNumber, NotPositive, + + /** Not `YYYY`, `YYYY-MM` or `YYYY-MM-DD`, or a day the calendar does not have. */ + NotADate, + + /** Under `min`: a number, or the year of a date. */ BelowMinimum, + + /** Over `max`: a number, or the year of a date. */ AboveMaximum, TooLong, PatternMismatch, + /** A required field of a type this app cannot write. See [CuratedEntryEvent.verifyWritable]. */ + UnsupportedType, + /** None of a `require-any` group's fields is present. */ RequireAnyUnmet, @@ -574,6 +611,45 @@ data class CuratedEntryProblem(val field: String, val reason: Reason) { } } +/** + * A `date` value: a calendar date at whatever precision the record allows. + * + * `YYYY`, `YYYY-MM` or `YYYY-MM-DD`, and the precision is whatever was + * written -- [month] and [day] are null when the value stops short of them, + * and nothing here turns a `2010-07` into the first of the month. The month + * has to be one and the day has to be on the calendar for that month and year, + * leap days included, so `2014-02-30` is not a date and `2016-02-29` is. The + * calendar is the proleptic Gregorian one, which is what ISO 8601 means. + * + * What a reader keeps is the string as written; this is the check on it, and + * [year] is what the schema's `min` and `max` bound. + */ +data class CuratedDate(val year: Int, val month: Int? = null, val day: Int? = null) { + companion object { + private val SHAPE = Regex("^(\\d{4})(?:-(\\d{2})(?:-(\\d{2}))?)?$") + + /** The three parts, or null for anything that is not a date at one of the three precisions. */ + fun parse(value: String): CuratedDate? { + val match = SHAPE.matchEntire(value.trim()) ?: return null + + val year = match.groupValues[1].toInt() + val month = match.groupValues[2].ifEmpty { null }?.toInt() + val day = match.groupValues[3].ifEmpty { null }?.toInt() + + if (month != null && month !in 1..12) return null + if (day != null && day !in 1..daysIn(year, month!!)) return null + + return CuratedDate(year, month, day) + } + + private fun daysIn(year: Int, month: Int): Int = when (month) { + 2 -> if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) 29 else 28 + 4, 6, 9, 11 -> 30 + else -> 31 + } + } +} + /** * An addressable coordinate, `::`, split the one way the NIP * allows: on the first two colons only. A `d` may itself contain colons -- diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchema.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchema.kt index bcaa1f37..74d48ca1 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchema.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchema.kt @@ -79,6 +79,11 @@ data class CuratedSchema( /** The kind suggestions are published under. There is only one. */ val suggestionKind: Kind = CuratedSchemaEvent.SUGGESTION_KIND, val fields: List = emptyList(), + /** + * Fields of a type this app does not know, kept aside from [fields] so that + * a reader ignores them and a writer cannot. See [CuratedUnsupportedField]. + */ + val unsupportedFields: List = emptyList(), /** * Groups of field names of which at least one must be present on an entry. * @@ -224,9 +229,10 @@ enum class CuratedVisibility(val value: String) { * What kind of value a field takes. One validation rule each, in the NIP's * table; a form picks its input from this. * - * [isNumeric] decides what `max` means: a maximum *value* for these, a maximum - * *length* for everything else. The double duty is safe because a field is one - * or the other, never both. + * [isNumeric] says the value is a whole number. [isBounded] says what `max` + * means: a bound on the value -- the number itself, or the year of a date -- + * for these, and a maximum *length* for everything else. The double duty is + * safe because a field is one or the other, never both. */ enum class CuratedFieldType(val value: String, val isNumeric: Boolean = false) { /** Single-line string, length-capped. */ @@ -255,8 +261,23 @@ enum class CuratedFieldType(val value: String, val isNumeric: Boolean = false) { /** An integer, bounded by `min` and `max`. */ Number("number", isNumeric = true), + + /** + * An ISO 8601 calendar date at whatever precision the record allows -- + * `YYYY`, `YYYY-MM` or `YYYY-MM-DD` -- with `min` and `max` bounding the + * year. Not numeric: the value is kept as written, since `2010-07` is a + * month and not a day somebody left off. + */ + Date("date"), ; + /** + * Whether `min` and `max` bound the value rather than cap its length: the + * numeric types, and a date, whose bounds are years. What the NIP means by + * a date counting as numeric for `max`'s double duty. + */ + val isBounded: Boolean get() = isNumeric || this == Date + companion object { fun parse(value: String): CuratedFieldType? = entries.firstOrNull { it.value == value } } @@ -417,10 +438,11 @@ data class CuratedField( * The tag read back, or null for one that is not a field. * * Null for a blank name or an unknown type, which are the two things a - * form cannot do anything with. Everything after them is optional: a - * missing placeholder is empty, a missing label falls back to the name, - * and a missing or malformed config is no config -- see - * [CuratedFieldConfig.fromJson]. + * form cannot do anything with -- though the second is not forgotten: + * [parseUnsupported] reads the same tag as the field this app cannot + * use. Everything after them is optional: a missing placeholder is + * empty, a missing label falls back to the name, and a missing or + * malformed config is no config -- see [CuratedFieldConfig.fromJson]. */ fun parse(tag: Array): CuratedField? { if (tag.size < 3 || tag[0] != TAG_NAME) return null @@ -440,6 +462,28 @@ data class CuratedField( ) } + /** + * The tag read back as a field this app cannot use, or null for + * anything else: the exact complement of [parse] over named fields, so + * that between the two every named `field` tag lands somewhere. + */ + fun parseUnsupported(tag: Array): CuratedUnsupportedField? { + if (tag.size < 3 || tag[0] != TAG_NAME) return null + + val name = tag[1].trim() + if (name.isEmpty()) return null + + if (CuratedFieldType.parse(tag[2]) != null) return null + + return CuratedUnsupportedField( + name = name, + type = tag[2].trim(), + isRequired = tag.getOrNull(3) == REQUIRED, + label = tag.getOrNull(5) ?: "", + tag = tag.toList(), + ) + } + /** The `title` field a schema gets when it left its own out. */ val TITLE = CuratedField( name = "title", @@ -473,3 +517,29 @@ data class CuratedField( ) } } + +/** + * A `field` tag whose type this app does not know, kept rather than dropped. + * + * The NIP's tolerance for a field that will not parse is a reader's: an entry + * is checked against the fields a reader understands, and one it does not is + * left out of the reading. A writer cannot be so easy. An entry published + * without a field the schema requires is refused by every client that does + * know the type -- fourteen went out that way from a build that could not see + * a `date` -- and a schema re-signed without one has quietly changed the + * list's rules. So the tag is kept whole: [CuratedEntryEvent.verifyWritable] + * refuses to compose under a required one, naming [type], and + * [CuratedSchemaEvent.template] writes [tag] back as it came, the way + * [CuratedFieldConfig.others] keeps the config keys it does not know. + */ +data class CuratedUnsupportedField( + val name: String, + /** The type word as the tag has it: what a newer client would know it by. */ + val type: String, + val isRequired: Boolean, + val label: String = "", + /** The whole tag, for writing back unchanged. */ + val tag: List, +) { + fun labelOrName(): String = label.ifBlank { name } +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEvent.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEvent.kt index 83a833de..89abfdbf 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEvent.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEvent.kt @@ -62,8 +62,9 @@ object CuratedSchemaEvent { * [CuratedSchema.problems] is null -- a schema that would be rejected on * publish is rejected on read, and for the same reasons. A `field` tag that * will not parse is dropped and the rest are kept, which is the one place - * the NIP asks for tolerance; a `require-any` naming fewer than two fields - * says nothing and goes the same way. + * the NIP asks for tolerance -- except that one of a type this app does not + * know is kept aside rather than lost, see [CuratedUnsupportedField]; a + * `require-any` naming fewer than two fields says nothing and is dropped. * * What comes back is [CuratedSchema.normalized]: the two mandatory fields * forced in, whatever the event said. @@ -102,6 +103,7 @@ object CuratedSchemaEvent { domain = first(TAG_DOMAIN)?.trim()?.ifEmpty { null }?.let(::normalizeDomain), suggestionKind = first(TAG_KIND)?.trim()?.toIntOrNull() ?: SUGGESTION_KIND, fields = tags.mapNotNull(CuratedField::parse), + unsupportedFields = tags.mapNotNull(CuratedField::parseUnsupported), requireAny = tags .filter { it.isNotEmpty() && it[0] == TAG_REQUIRE_ANY } .map { group -> group.drop(1).map { it.trim() }.filter { it.isNotEmpty() } } @@ -123,6 +125,10 @@ object CuratedSchemaEvent { * * The content mirrors the description so that a client reading content * rather than tags still shows something; the tag is the authoritative one. + * + * A field of a type this app does not know goes out as it came in, after + * the fields it does: the editor cannot show it, and a schema re-signed + * without it would have changed the list's rules behind the member's back. */ fun template( schema: CuratedSchema, @@ -146,6 +152,7 @@ object CuratedSchemaEvent { normalized.domain?.let { add(arrayOf(TAG_DOMAIN, normalizeDomain(it))) } normalized.fields.forEach { add(it.toTagArray()) } + normalized.unsupportedFields.forEach { add(it.tag.toTypedArray()) } normalized.requireAny.forEach { group -> add(arrayOf(TAG_REQUIRE_ANY, *group.toTypedArray())) } normalized.suggesters.forEach { add(arrayOf(TAG_SUGGESTER, it)) } normalized.relays.forEach { add(arrayOf(TAG_RELAY, it)) } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/AcceptCuratedSuggestionScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/AcceptCuratedSuggestionScreen.kt index 06bf3866..9cea276d 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/AcceptCuratedSuggestionScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/AcceptCuratedSuggestionScreen.kt @@ -53,6 +53,7 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.lifecycle.viewmodel.compose.viewModel import com.vitorpamplona.quartz.nip01Core.core.HexKey import curare.composeapp.generated.resources.Res +import curare.composeapp.generated.resources.a_date_as_yyyy_yyyy_mm_or_yyyy_mm_dd import curare.composeapp.generated.resources.a_whole_number import curare.composeapp.generated.resources.add_another import curare.composeapp.generated.resources.at_least_n @@ -65,6 +66,8 @@ import curare.composeapp.generated.resources.filled_in_by_the_suggester_s_app_an import curare.composeapp.generated.resources.kept_from_the_suggestion import curare.composeapp.generated.resources.more_than_zero import curare.composeapp.generated.resources.must_match_the_pattern +import curare.composeapp.generated.resources.n_or_earlier +import curare.composeapp.generated.resources.n_or_later import curare.composeapp.generated.resources.one_word_without_spaces import curare.composeapp.generated.resources.only_one_value_for_this_field import curare.composeapp.generated.resources.pick_one_of_the_options @@ -79,6 +82,7 @@ import curare.composeapp.generated.resources.the_group_signs_an_entry_so_it_take import curare.composeapp.generated.resources.this_entry_cannot_be_signed_as_it_is import curare.composeapp.generated.resources.this_field_is_required import curare.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_an_entry +import curare.composeapp.generated.resources.this_list_uses_a_field_type_this_app_does_not_support import org.jetbrains.compose.resources.stringResource import to.curare.compose.database.model.ChatRoom import to.curare.compose.database.model.GroupSignedEvent @@ -391,11 +395,12 @@ internal fun AcceptCuratedSuggestionForm( entryProblems.forEach { problem -> val field = schema.fields.firstOrNull { it.name == problem.field } + val unsupported = schema.unsupportedFields.firstOrNull { it.name == problem.field } Text( text = stringResource( Res.string.field_and_problem, - field?.labelOrName() ?: problem.field, + field?.labelOrName() ?: unsupported?.labelOrName() ?: problem.field, problem.message(field, schema) ), style = MaterialTheme.typography.bodySmall, @@ -568,8 +573,10 @@ private fun EnumInput( * schema labels it and placeholdered as the schema says. * * The keyboard follows the type -- digits for a year, a URL keyboard for a - * link -- and a long text gets room to be one. The supporting line is the - * problem when there is one and the schema's hint when there is not. + * link, and the plain one for a date, whose `2010-07` needs a hyphen the + * number pad does not always have -- and a long text gets room to be one. The + * supporting line is the problem when there is one and the schema's hint when + * there is not. */ @Composable private fun EntryTextField( @@ -656,12 +663,18 @@ internal fun CuratedEntryProblem.message(field: CuratedField?, schema: CuratedSc CuratedEntryProblem.Reason.NotAnOption -> stringResource(Res.string.pick_one_of_the_options) CuratedEntryProblem.Reason.NotAWholeNumber -> stringResource(Res.string.a_whole_number) CuratedEntryProblem.Reason.NotPositive -> stringResource(Res.string.more_than_zero) + CuratedEntryProblem.Reason.NotADate -> stringResource(Res.string.a_date_as_yyyy_yyyy_mm_or_yyyy_mm_dd) - CuratedEntryProblem.Reason.BelowMinimum -> - stringResource(Res.string.at_least_n, field?.config?.min?.toString() ?: "") + // A date's bounds are years, and "at least 2009" is not how anyone says it. + CuratedEntryProblem.Reason.BelowMinimum -> stringResource( + if (field?.type == CuratedFieldType.Date) Res.string.n_or_later else Res.string.at_least_n, + field?.config?.min?.toString() ?: "" + ) - CuratedEntryProblem.Reason.AboveMaximum -> - stringResource(Res.string.at_most_n, field?.config?.max?.toString() ?: "") + CuratedEntryProblem.Reason.AboveMaximum -> stringResource( + if (field?.type == CuratedFieldType.Date) Res.string.n_or_earlier else Res.string.at_most_n, + field?.config?.max?.toString() ?: "" + ) CuratedEntryProblem.Reason.TooLong -> stringResource(Res.string.at_most_n_characters, field?.config?.max?.toString() ?: "") @@ -676,6 +689,13 @@ internal fun CuratedEntryProblem.message(field: CuratedField?, schema: CuratedSc .joinToString { name -> schema.fields.firstOrNull { it.name == name }?.labelOrName() ?: name } ) + // The one problem the schema has and the entry does not: a required field + // is of a type this build cannot write, named so the member knows which. + CuratedEntryProblem.Reason.UnsupportedType -> stringResource( + Res.string.this_list_uses_a_field_type_this_app_does_not_support, + schema.unsupportedFields.firstOrNull { it.name == this.field }?.type ?: "" + ) + // None of these can come out of the form: the builder writes the kind, the // root and the source, and the group is the curator. Named all the same, // since a check that cannot fail is the one that does. diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/EditGroupCuratedSchemaScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/EditGroupCuratedSchemaScreen.kt index 836dedf2..c64103f3 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/EditGroupCuratedSchemaScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/EditGroupCuratedSchemaScreen.kt @@ -142,6 +142,7 @@ import curare.composeapp.generated.resources.domain import curare.composeapp.generated.resources.done import curare.composeapp.generated.resources.edit_field import curare.composeapp.generated.resources.edit_schema +import curare.composeapp.generated.resources.earliest_year import curare.composeapp.generated.resources.eg_1900 import curare.composeapp.generated.resources.eg_200 import curare.composeapp.generated.resources.eg_2100 @@ -158,6 +159,7 @@ import curare.composeapp.generated.resources.eg_watch_reference_url import curare.composeapp.generated.resources.eg_watchurl import curare.composeapp.generated.resources.eg_wss_relay_example_com import curare.composeapp.generated.resources.field_name +import curare.composeapp.generated.resources.field_type_date import curare.composeapp.generated.resources.field_type_duration import curare.composeapp.generated.resources.field_type_enum import curare.composeapp.generated.resources.field_type_image @@ -174,6 +176,7 @@ import curare.composeapp.generated.resources.hint import curare.composeapp.generated.resources.https_only import curare.composeapp.generated.resources.identifier import curare.composeapp.generated.resources.label +import curare.composeapp.generated.resources.latest_year import curare.composeapp.generated.resources.marker import curare.composeapp.generated.resources.maximum_characters import curare.composeapp.generated.resources.maximum_value @@ -841,9 +844,9 @@ private fun CuratedVisibility.purpose(): StringResource = when (this) { * The name of a field type, for the chips and the rows. * * A `when` rather than a field on each entry so that the enum stays what it is - * -- the NIP's nine words and their one rule each -- with no catalogue behind - * it, and so that a tenth type is a compile error here rather than a chip with - * no name. + * -- the NIP's ten words and their one rule each -- with no catalogue behind + * it, and so that an eleventh type is a compile error here rather than a chip + * with no name. */ private fun CuratedFieldType.label(): StringResource = when (this) { CuratedFieldType.Text -> Res.string.field_type_text @@ -855,6 +858,7 @@ private fun CuratedFieldType.label(): StringResource = when (this) { CuratedFieldType.Year -> Res.string.field_type_year CuratedFieldType.Duration -> Res.string.field_type_duration CuratedFieldType.Number -> Res.string.field_type_number + CuratedFieldType.Date -> Res.string.field_type_date } /** @@ -1299,22 +1303,29 @@ internal fun FieldEditorSheetContent( ) ) + // What `max` means follows the type: a cap on the characters, a bound + // on the number, or the latest year of a date. `min` only exists for + // the last two. SchemaTextField( state = maxFieldState, icon = Icons.Default.Numbers, iconDescription = "Maximum", label = stringResource( - if (type.isNumeric) Res.string.maximum_value else Res.string.maximum_characters + when { + type.isNumeric -> Res.string.maximum_value + type.isBounded -> Res.string.latest_year + else -> Res.string.maximum_characters + } ), - placeholder = stringResource(if (type.isNumeric) Res.string.eg_2100 else Res.string.eg_200) + placeholder = stringResource(if (type.isBounded) Res.string.eg_2100 else Res.string.eg_200) ) - if (type.isNumeric) { + if (type.isBounded) { SchemaTextField( state = minFieldState, icon = Icons.Default.Numbers, iconDescription = "Minimum", - label = stringResource(Res.string.minimum_value), + label = stringResource(if (type.isNumeric) Res.string.minimum_value else Res.string.earliest_year), placeholder = stringResource(Res.string.eg_1900) ) } @@ -1409,7 +1420,7 @@ internal fun FieldEditorSheetContent( }, marker = markerFieldState.text.toString().trim().ifEmpty { null }, max = maxFieldState.text.toString().trim().toLongOrNull(), - min = if (type.isNumeric) { + min = if (type.isBounded) { minFieldState.text.toString().trim().toLongOrNull() } else { null diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModel.kt index deebe2bc..f5c0bcb0 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModel.kt @@ -21,6 +21,7 @@ import to.curare.compose.nostr.curated.CuratedSchema import to.curare.compose.nostr.curated.CuratedSchemaEvent import to.curare.compose.nostr.curated.CuratedSchemaProblem import to.curare.compose.nostr.curated.CuratedSchemaTemplate +import to.curare.compose.nostr.curated.CuratedUnsupportedField import to.curare.compose.nostr.curated.CuratedVisibility import to.curare.compose.repository.ChatRepository import to.curare.compose.repository.FrostSigningRepository @@ -99,6 +100,13 @@ class EditGroupCuratedSchemaViewModel( /** The working copy of the schema's fields, in the order they will be written. */ val fields = mutableStateListOf() + /** + * The fields of an existing schema this build cannot show, carried through + * unchanged so that an edit here does not sign them away. Not state: the + * editor has no control over them, which is the point. + */ + private val unsupportedFields = mutableListOf() + /** * The working copy of the `require-any` rules, each a set of field names. * @@ -240,6 +248,7 @@ class EditGroupCuratedSchemaViewModel( if (schema != null) { visibility = schema.visibility ?: CuratedVisibility.Public fields.addAll(schema.fields) + unsupportedFields.addAll(schema.unsupportedFields) requireAny.addAll(schema.requireAny) suggesters.addAll(schema.suggesters) relays.addAll(schema.relays) @@ -428,6 +437,7 @@ class EditGroupCuratedSchemaViewModel( picture = picture.trim().ifEmpty { null }, domain = domain.trim().ifEmpty { null }?.let(CuratedSchemaEvent::normalizeDomain), fields = fields.toList(), + unsupportedFields = unsupportedFields.toList(), requireAny = requireAny.filter { it.size > 1 }, suggesters = suggesters.toList(), relays = relays.toList(), diff --git a/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedEntryEventTest.kt b/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedEntryEventTest.kt index 16e57211..18999ca6 100644 --- a/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedEntryEventTest.kt +++ b/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedEntryEventTest.kt @@ -334,6 +334,46 @@ class CuratedEntryEventTest { assertNull(CuratedEntryEvent.checkValue(strict, "https://example.com")) } + @Test + fun `a date is checked at whatever precision it was written`() { + val died = CuratedField("died", CuratedFieldType.Date, isRequired = true, config = CuratedFieldConfig(min = 2009, max = 2100)) + + // The three precisions the NIP allows, and a leap day on a leap year. + listOf("2014", "2014-02", "2014-02-28", "2016-02-29", " 2014-02-28 ").forEach { value -> + assertNull(CuratedEntryEvent.checkValue(died, value), "\"$value\" was refused") + } + + // Not one of the three shapes, or a day the calendar does not have. + listOf("2014-13", "2014-00", "2014-02-30", "2014-02-00", "2015-02-29", "2100-02-29", "14-02-28", "2014/02/28", "2014-2-28", "2014-02-28T00:00", "twenty fourteen").forEach { value -> + assertEquals(CuratedEntryProblem.Reason.NotADate, CuratedEntryEvent.checkValue(died, value), "\"$value\" was accepted") + } + + // `min` and `max` bound the year, at whatever precision. + assertEquals(CuratedEntryProblem.Reason.BelowMinimum, CuratedEntryEvent.checkValue(died, "2008-12-31")) + assertEquals(CuratedEntryProblem.Reason.BelowMinimum, CuratedEntryEvent.checkValue(died, "2008")) + assertEquals(CuratedEntryProblem.Reason.AboveMaximum, CuratedEntryEvent.checkValue(died, "2101-01")) + assertNull(CuratedEntryEvent.checkValue(died, "2009-01-03")) + assertNull(CuratedEntryEvent.checkValue(died, "2100")) + + // A date's `max` is a year and never a length: ten characters under a + // bound of eight is fine. And the year 2000 was a leap year, unlike 1900. + val early = died.copy(config = CuratedFieldConfig(max = 8)) + assertNull(CuratedEntryEvent.checkValue(early, "0005-06-07")) + assertNull(CuratedEntryEvent.checkValue(died.copy(config = CuratedFieldConfig()), "2000-02-29")) + assertEquals(CuratedEntryProblem.Reason.NotADate, CuratedEntryEvent.checkValue(died.copy(config = CuratedFieldConfig()), "1900-02-29")) + + assertEquals(CuratedEntryProblem.Reason.Empty, CuratedEntryEvent.checkValue(died, " ")) + } + + @Test + fun `a date keeps the precision it was written at`() { + assertEquals(CuratedDate(2014), CuratedDate.parse("2014")) + assertEquals(CuratedDate(2010, 7), CuratedDate.parse("2010-07")) + assertEquals(CuratedDate(2014, 2, 28), CuratedDate.parse(" 2014-02-28 ")) + assertNull(CuratedDate.parse("2014-")) + assertNull(CuratedDate.parse("")) + } + @Test fun `a coordinate splits on the first two colons only`() { val parsed = assertNotNull(CuratedCoordinate.parse("31888:${suggester.uppercase()}:imdb:tt2821314")) @@ -488,6 +528,95 @@ class CuratedEntryEventTest { assertNull(entry.source) } + @Test + fun `an entry keeps its dates from the suggestion to the list`() { + // The case behind bitcoin.necropolis.report's fourteen dateless entries: + // a build that could not see a `date` field accepted suggestions that + // had one and signed entries that did not. The two dates have to make + // it through the reading and the template both. + val necropolis = assertNotNull( + CuratedSchemaEvent.parse( + Event( + id = "a".repeat(64), + pubKey = curator, + createdAt = 1735689600, + kind = CuratedSchemaEvent.KIND, + tags = arrayOf( + arrayOf("d", "bitcoin.necropolis.report"), + arrayOf("title", "bitcoin.necropolis.report suggestion"), + arrayOf("name", "bitcoin.necropolis.report"), + arrayOf("description", "Bitcoin companies that are no more."), + arrayOf("visibility", "public"), + arrayOf("field", "identifier", "token", "required", "", "Identifier", "{\"tag\":\"d\",\"max\":80,\"derived\":true}"), + arrayOf("field", "title", "text", "required", "", "Title", "{\"max\":200}"), + arrayOf("field", "founded", "date", "optional", "2010-07", "Founded", "{\"min\":1900,\"max\":2100}"), + arrayOf("field", "died", "date", "required", "2014-02-28", "Died", "{\"min\":2009,\"max\":2100}"), + ), + content = "", + sig = "b".repeat(128), + ) + ) + ) + val necropolisCoordinate = "31889:$curator:bitcoin.necropolis.report" + + val mtGox = suggestion( + tags = arrayOf( + arrayOf("d", "domain:mtgox.com"), + arrayOf("title", "Mt. Gox"), + arrayOf("founded", "2010-07"), + arrayOf("died", "2014-02-28"), + arrayOf("a", necropolisCoordinate, "", "root"), + ), + content = "", + ) + assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(mtGox, necropolis, necropolisCoordinate)) + + val suggested = CuratedEntryEvent.read(mtGox, necropolis) + assertEquals("2010-07", suggested.value("founded")) + assertEquals("2014-02-28", suggested.value("died")) + + val template = CuratedEntryEvent.canonicalTemplate(necropolis, necropolisCoordinate, curator, suggested.values, CuratedSuggestionRef.of(suggested)) + val tags = template.tags.map { it.toList() } + assertEquals(listOf(listOf("founded", "2010-07")), tags.filter { it[0] == "founded" }) + assertEquals(listOf(listOf("died", "2014-02-28")), tags.filter { it[0] == "died" }) + + val entry = assertNotNull( + CuratedEntryEvent.canonical(CuratedEntryEvent.preview(template, curator), necropolis, necropolisCoordinate, curator) + ) + assertEquals(suggested.values, entry.values) + + // And without the `died`, the entry is refused for the field it lacks -- + // which is what every conforming client did to the fourteen. + val dateless = CuratedEntryEvent.canonicalTemplate(necropolis, necropolisCoordinate, curator, suggested.values - "died") + assertEquals( + listOf(CuratedEntryProblem("died", CuratedEntryProblem.Reason.Missing)), + CuratedEntryEvent.verifyCanonical(CuratedEntryEvent.preview(dateless, curator), necropolis, necropolisCoordinate, curator) + ) + } + + @Test + fun `a required field of a type this app cannot write is a reason not to`() { + // What the fourteen should have run into. A type this build does not + // know is left out of the reading, as the NIP allows; an entry written + // without it, when the schema requires it, is one every other client + // refuses. So the write side refuses first, and names the field. + val stars = arrayOf("field", "rating", "stars", "required", "5", "Rating", "{}") + val withStars = CuratedSchemaEvent.read(schemaTags() + stars, "").normalized() + assertEquals( + listOf(CuratedEntryProblem("rating", CuratedEntryProblem.Reason.UnsupportedType)), + CuratedEntryEvent.verifyWritable(withStars) + ) + + // Reading is untouched: the NIP's suggestion still satisfies the schema, + // rating or no rating. + assertEquals(emptyList(), CuratedEntryEvent.verifySuggestion(suggestion(), withStars, coordinate)) + + // An optional one is left out the way the reading leaves it out. + val optional = CuratedSchemaEvent.read(schemaTags() + arrayOf("field", "rating", "stars", "optional", "", "", "{}"), "").normalized() + assertEquals(emptyList(), CuratedEntryEvent.verifyWritable(optional)) + assertEquals(emptyList(), CuratedEntryEvent.verifyWritable(schema)) + } + @Test fun `only a suggestion can be pointed at`() { val theListsOwn = assertNotNull(CuratedEntryEvent.canonical(canonical(), schema, coordinate, curator)) @@ -505,6 +634,9 @@ class CuratedEntryEventTest { assertEquals(emptyMap(), entry.values) } + /** The NIP's schema's tags, for a test that wants one more of them. */ + private fun schemaTags(): Array> = CuratedSchemaEvent.template(schema, createdAt = 1735689600).tags + private fun suggestion( tags: Array> = riseAndRise, content: String = review, diff --git a/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEventTest.kt b/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEventTest.kt index 89e0579a..1dd44fa5 100644 --- a/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEventTest.kt +++ b/composeApp/src/commonTest/kotlin/to/curare/compose/nostr/curated/CuratedSchemaEventTest.kt @@ -175,13 +175,54 @@ class CuratedSchemaEventTest { } @Test - fun `a field with an unknown type or no name is dropped and the rest are kept`() { + fun `a date field reads as one, with its bounds on the year`() { + // bitcoin.necropolis.report's two, as published. Fourteen of its + // entries lost their `died` to a build that dropped the type on the + // way in and then wrote entries without it. val schema = assertNotNull( CuratedSchemaEvent.parse( event( tags = bitcoinMov.plus( listOf( - arrayOf("field", "rating", "stars", "optional", "", "", "{}"), + arrayOf("field", "founded", "date", "optional", "2010-07", "Founded", "{\"min\":1900,\"max\":2100,\"hint\":\"YYYY, YYYY-MM or YYYY-MM-DD.\"}"), + arrayOf("field", "died", "date", "required", "2014-02-28", "Died", "{\"min\":2009,\"max\":2100}"), + ) + ) + ) + ) + ) + + val died = schema.fields.first { it.name == "died" } + assertEquals(CuratedFieldType.Date, died.type) + assertTrue(died.isRequired) + assertEquals("2014-02-28", died.placeholder) + assertEquals("Died", died.label) + assertEquals(2009L, died.config.min) + assertEquals(2100L, died.config.max) + + // Its bounds are years, so `max` is a bound and not a length -- but the + // value is not a number, and no keyboard should think it is. + assertTrue(died.type.isBounded) + assertFalse(died.type.isNumeric) + + assertEquals(listOf("founded", "died"), schema.formFields().takeLast(2).map { it.name }) + assertEquals(emptyList(), schema.unsupportedFields) + + assertEquals( + listOf("field", "died", "date", "required", "2014-02-28", "Died", "{\"max\":2100,\"min\":2009}"), + died.toTagArray().toList() + ) + } + + @Test + fun `a field with an unknown type is kept aside, one with no name is dropped, and the rest are kept`() { + val stars = arrayOf("field", "rating", "stars", "required", "5", "Rating", "{\"max\":5}") + val schema = assertNotNull( + CuratedSchemaEvent.parse( + event( + tags = bitcoinMov.plus( + listOf( + stars, arrayOf("field", " ", "text", "optional", "", "", "{}"), arrayOf("field", "short"), ) @@ -191,6 +232,22 @@ class CuratedSchemaEventTest { ) assertEquals(9, schema.fields.size) + + // A type this build does not know is not a type nobody knows. The + // reader says which field it could not read rather than forgetting + // it, so a writer can refuse to publish an entry without it. + assertEquals( + listOf(CuratedUnsupportedField("rating", "stars", isRequired = true, label = "Rating", tag = stars.toList())), + schema.unsupportedFields + ) + + // And the template writes it back as it came, after the fields it does + // know, so that an edit here cannot sign the list's rules away. + val template = CuratedSchemaEvent.template(schema, createdAt = 1735689600) + val fields = template.tags.filter { it[0] == "field" } + assertEquals(10, fields.size) + assertEquals(stars.toList(), fields.last().toList()) + assertEquals(schema, CuratedSchemaEvent.parse(event(tags = template.tags, content = template.content))) } @Test diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/AcceptCuratedSuggestionViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/AcceptCuratedSuggestionViewModelJvmTest.kt index 4a47a75d..98e4906f 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/AcceptCuratedSuggestionViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/AcceptCuratedSuggestionViewModelJvmTest.kt @@ -28,6 +28,7 @@ import to.curare.compose.nostr.curated.CuratedFieldConfig import to.curare.compose.nostr.curated.CuratedFieldType import to.curare.compose.nostr.curated.CuratedSchema import to.curare.compose.nostr.curated.CuratedSchemaEvent +import to.curare.compose.nostr.curated.CuratedUnsupportedField import to.curare.compose.nostr.curated.CuratedVisibility import to.curare.compose.repository.ChatRepository import to.curare.compose.repository.FrostSigningRepository @@ -296,6 +297,35 @@ class AcceptCuratedSuggestionViewModelJvmTest { assertFalse(viewModel.isActionPending.value) } + @Test + fun `a list with a required field this build cannot write is refused before a quorum is spent`() { + // The schema was written by a client that knows a type this build does + // not. The reading is fine without it; an entry written without it is + // not, and the refusal has no input to sit under, so it goes at the top + // with the field's own label. + val stars = listOf("field", "rating", "stars", "required", "5", "Rating", "{}") + val state = loaded().copy( + schema = schema.copy( + schema = schema.schema.copy( + unsupportedFields = listOf(CuratedUnsupportedField("rating", "stars", isRequired = true, label = "Rating", tag = stars)) + ) + ) + ) + val signing = RecordingSigning(session()) + val viewModel = viewModel(signing) + viewModel.seedWorkingCopy(state) + + var invalid = false + viewModel.proposeEntry(state, onSuccess = { error("proposed") }, onInvalid = { invalid = true }, onFailure = { error("failed") }) + + assertTrue(invalid) + assertEquals( + listOf(CuratedEntryProblem("rating", CuratedEntryProblem.Reason.UnsupportedType)), + viewModel.problemsAboutTheEntry(state) + ) + assertNull(signing.kind, "an entry the list's other readers would refuse was proposed anyway") + } + @Test fun `a require-any rule the edit broke is filed under its first field`() { val state = loaded() diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModelJvmTest.kt index 8f536e85..7255e0e0 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/EditGroupCuratedSchemaViewModelJvmTest.kt @@ -12,6 +12,7 @@ import to.curare.compose.nostr.curated.CuratedSchema import to.curare.compose.nostr.curated.CuratedSchemaEvent import to.curare.compose.nostr.curated.CuratedSchemaProblem import to.curare.compose.nostr.curated.CuratedSchemaTemplate +import to.curare.compose.nostr.curated.CuratedUnsupportedField import to.curare.compose.nostr.curated.CuratedVisibility import to.curare.compose.repository.ChatRepository import to.curare.compose.repository.FrostSigningRepository @@ -335,6 +336,40 @@ class EditGroupCuratedSchemaViewModelJvmTest { assertEquals(emptyList(), viewModel.problems) } + @Test + fun `a field of a type this build cannot show survives an edit, and is not an edit by itself`() { + // A schema another client wrote may use a type this build does not know. + // The editor cannot show it, and must neither sign it away nor mistake + // its own blind spot for a change the member made. + val stars = listOf("field", "rating", "stars", "required", "5", "Rating", "{\"max\":5}") + val withStars = films.copy( + unsupportedFields = listOf(CuratedUnsupportedField("rating", "stars", isRequired = true, label = "Rating", tag = stars)) + ) + val viewModel = viewModel("films") + viewModel.seedWorkingCopy(editing(withStars)) + + var outcome = "" + viewModel.proposeSchema( + localChatRoom = localChatRoom, + existing = existing(withStars), + identifier = films.identifier, + title = films.title, + name = films.name, + description = films.description, + picture = "", + domain = "", + onSuccess = { outcome = "proposed" }, + onInvalid = { outcome = "invalid" }, + onNothingToPropose = { outcome = "nothing" }, + onFailure = { outcome = "failed" }, + ) + assertEquals("nothing", outcome) + + // And what an edit would sign carries the tag as it came. + val draft = viewModel.draft(films.identifier, films.title, films.name, films.description, picture = "", domain = "") + assertEquals(stars, GroupCuratedSchema.template(draft).tags.first { it[0] == "field" && it[1] == "rating" }.toList()) + } + @Test fun `an edit keeps the identifier whatever the field says`() { val viewModel = viewModel("films")