Compare commits
3
Commits
29dd6dd351
...
d6204d320a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6204d320a | ||
|
|
0ecff7eeb9 | ||
|
|
921c0a47bd |
@@ -86,9 +86,9 @@ fun derivedTint(id: String): String {
|
||||
* Deriving has no mint points to miss and no backfill for the tags already out there.
|
||||
* The cost is that renaming a tag recolours it, which is fair: the name IS the tag.
|
||||
*
|
||||
* Lowercased because tags dedupe case-insensitively — `#Todo` renamed to `#todo` is
|
||||
* the same tag and should not change colour. Kotlin's `lowercase()` and the web's
|
||||
* `toLowerCase()` are both locale-independent, so the mirror holds.
|
||||
* Folded because `#Todo` renamed to `#todo` is the same tag and should not change
|
||||
* colour. [foldTag] and the web's are both locale-independent lowercasing, so the
|
||||
* mirror holds.
|
||||
*/
|
||||
fun resolvedLabelColor(
|
||||
name: String,
|
||||
@@ -98,5 +98,12 @@ fun resolvedLabelColor(
|
||||
when {
|
||||
color.isNotEmpty() && color != "default" && color in known -> color
|
||||
name.isEmpty() -> "default"
|
||||
else -> derivedTint(name.lowercase())
|
||||
else -> derivedTint(foldTag(name))
|
||||
}
|
||||
|
||||
/**
|
||||
* How two tag names compare: equal once every letter is lowercased, accented ones
|
||||
* included, so `#Café` and `#CAFÉ` are one tag. The core's `derive::fold`, the server's
|
||||
* `labeling.named` and the web's `foldTag` fold the same way (#5385).
|
||||
*/
|
||||
fun foldTag(name: String): String = name.lowercase()
|
||||
|
||||
@@ -366,11 +366,11 @@ private fun tintTags(
|
||||
// A tag the note does not carry as a label yet — just typed, not yet
|
||||
// derived — still gets a colour: `labelTint` falls back to deriving one
|
||||
// from the name, which is what the chip would have shown anyway.
|
||||
val picked = note.labels.associate { it.name.lowercase() to it.color }
|
||||
val picked = note.labels.associate { foldTag(it.name) to it.color }
|
||||
buildAnnotatedString {
|
||||
append(text)
|
||||
spans.forEach { tag ->
|
||||
val tint = labelTint(tag.name, picked[tag.name.lowercase()].orEmpty())
|
||||
val tint = labelTint(tag.name, picked[foldTag(tag.name)].orEmpty())
|
||||
addStyle(
|
||||
SpanStyle(color = tint.tagInk(dark), fontWeight = FontWeight.Medium),
|
||||
tag.start.toInt(),
|
||||
|
||||
@@ -39,6 +39,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -203,7 +204,7 @@ fun TagsScreen(
|
||||
body =
|
||||
open.tag.count
|
||||
?.takeIf { it > 0 }
|
||||
?.let { stringResource(R.string.tags_delete_body_counted, it) }
|
||||
?.let { pluralStringResource(R.plurals.tags_delete_body_counted, it.toInt(), it.toInt()) }
|
||||
?: stringResource(R.string.tags_delete_body),
|
||||
footnote = stringResource(R.string.tags_delete_from_text),
|
||||
confirm = stringResource(R.string.tags_delete_confirm),
|
||||
@@ -378,8 +379,7 @@ private fun countLabel(count: Long?): String =
|
||||
when {
|
||||
count == null -> ""
|
||||
count <= 0L -> stringResource(R.string.tags_count_none)
|
||||
count == 1L -> stringResource(R.string.tags_count_one)
|
||||
else -> stringResource(R.string.tags_count, count.toInt())
|
||||
else -> pluralStringResource(R.plurals.tags_count, count.toInt(), count.toInt())
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -401,7 +401,7 @@ private fun RenameDialog(
|
||||
var text by remember(tag.id) { mutableStateOf(tag.name) }
|
||||
val trimmed = text.trim()
|
||||
val clash =
|
||||
others.firstOrNull { it.id != tag.id && it.name.equals(trimmed, ignoreCase = true) }
|
||||
others.firstOrNull { it.id != tag.id && foldTag(it.name) == foldTag(trimmed) }
|
||||
val submit = {
|
||||
when {
|
||||
trimmed.isEmpty() -> Unit
|
||||
|
||||
@@ -137,8 +137,10 @@
|
||||
<string name="tags_back">Back</string>
|
||||
<string name="tags_new_hint">New tag</string>
|
||||
<string name="tags_create">Create</string>
|
||||
<string name="tags_count">%1$d notes</string>
|
||||
<string name="tags_count_one">1 note</string>
|
||||
<plurals name="tags_count">
|
||||
<item quantity="one">%d note</item>
|
||||
<item quantity="other">%d notes</item>
|
||||
</plurals>
|
||||
<string name="tags_count_none">No notes yet</string>
|
||||
<string name="tags_empty_title">No tags yet</string>
|
||||
<string name="tags_empty_body">Create one above, or write a #tag in a note and it becomes one.</string>
|
||||
@@ -166,7 +168,10 @@
|
||||
<string name="tags_delete">Delete</string>
|
||||
<string name="tags_delete_title">Delete %1$s?</string>
|
||||
<string name="tags_delete_body">It will be removed from every note that has it, on every device you sync with. The notes themselves are kept.</string>
|
||||
<string name="tags_delete_body_counted">It is on %1$d notes. It will be removed from all of them, on every device you sync with. The notes themselves are kept.</string>
|
||||
<plurals name="tags_delete_body_counted">
|
||||
<item quantity="one">It is on %d note. It will be removed from it, on every device you sync with. The note itself is kept.</item>
|
||||
<item quantity="other">It is on %d notes. It will be removed from all of them, on every device you sync with. The notes themselves are kept.</item>
|
||||
</plurals>
|
||||
<string name="tags_delete_confirm">Delete</string>
|
||||
<!-- A tag written as #tag in a note's body is owned by that text. Deleting the
|
||||
row cannot un-write the word, so it comes back on that note's next edit —
|
||||
|
||||
+3
-1
@@ -11,7 +11,9 @@ serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Local-first store (M10.4): bundled = compile SQLite in, so there's no system
|
||||
# libsqlite dependency to vary across the AppImage / native / Windows / Android builds.
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
# functions = the `fold` SQL function tag names are compared and indexed by (#5385):
|
||||
# SQLite's own lower() folds ASCII only, and the server folds every letter.
|
||||
rusqlite = { version = "0.32", features = ["bundled", "functions"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
# RFC3339 timestamps for created_at/updated_at/remind_at (Date.parse-able on the JS side).
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
||||
|
||||
@@ -205,10 +205,10 @@ pub fn lift_standalone_tags(body: &str) -> (Vec<String>, Vec<String>, String) {
|
||||
|
||||
// A tag that ALSO appears in prose stays derived: the prose copy still backs it,
|
||||
// so deleting that copy should still detach the label.
|
||||
let inline_lower: Vec<String> = inline.iter().map(|n| n.to_lowercase()).collect();
|
||||
let inline_folded: Vec<String> = inline.iter().map(|n| fold(n)).collect();
|
||||
let standalone = standalone
|
||||
.into_iter()
|
||||
.filter(|n| !inline_lower.contains(&n.to_lowercase()))
|
||||
.filter(|n| !inline_folded.contains(&fold(n)))
|
||||
.collect();
|
||||
(standalone, inline, lifted)
|
||||
}
|
||||
@@ -217,8 +217,17 @@ fn is_tag_char(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_' || c == '-'
|
||||
}
|
||||
|
||||
/// How two tag names compare: equal once every letter is lowercased, accented ones
|
||||
/// included, so "Café" and "CAFÉ" are one tag. The server's `labeling.named` folds
|
||||
/// the same way (Postgres `lower`, Python `str.lower`), and the store's `fold` SQL
|
||||
/// function is this (#5385).
|
||||
pub(crate) fn fold(name: &str) -> String {
|
||||
name.to_lowercase()
|
||||
}
|
||||
|
||||
fn push_unique(out: &mut Vec<String>, candidate: &str) {
|
||||
if !out.iter().any(|x| x.eq_ignore_ascii_case(candidate)) {
|
||||
let folded = fold(candidate);
|
||||
if !out.iter().any(|x| fold(x) == folded) {
|
||||
out.push(candidate.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
+177
-1
@@ -7,6 +7,7 @@
|
||||
//! Migrations are gated on `PRAGMA user_version`; a change is a new entry at the end of
|
||||
//! [`STEPS`].
|
||||
|
||||
use rusqlite::functions::FunctionFlags;
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
|
||||
use crate::local::derive;
|
||||
@@ -331,6 +332,62 @@ const SCHEMA_V13: &str = r#"
|
||||
DROP TABLE saved_filters;
|
||||
"#;
|
||||
|
||||
// v14 (#5385): tag names compare by `fold`, which lowercases every letter. Until now
|
||||
// the index and the queries used SQLite's lower(), which folds ASCII only, so "Café"
|
||||
// and "CAFÉ" could be two tags on a device while the server held one.
|
||||
//
|
||||
// Pairs that already exist are merged before the index can be rebuilt. THE OLDER ROW
|
||||
// SURVIVES, as in `store::rename_label`, so every device holding the same pair picks
|
||||
// the same one. The merge is written out here rather than calling
|
||||
// `store::merge_labels`: a migration replays on an old database before every later
|
||||
// step, and store code is free to start reading a column a later step adds. What it
|
||||
// does is that merge's: memberships move to the survivor (keeping `via_tag`, since
|
||||
// the body's `#CAFÉ` now derives the survivor), the affected notes are marked dirty so
|
||||
// their label sets reach the server, and the merged-away row is a pending delete.
|
||||
fn migrate_v14(conn: &Connection) -> rusqlite::Result<()> {
|
||||
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
|
||||
{
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT id, name FROM labels ORDER BY created_at ASC, id ASC")?;
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let id: String = row.get(0)?;
|
||||
let key = derive::fold(&row.get::<_, String>(1)?);
|
||||
match groups.iter_mut().find(|(k, _)| *k == key) {
|
||||
Some((_, ids)) => ids.push(id),
|
||||
None => groups.push((key, vec![id])),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (_, ids) in groups.into_iter().filter(|(_, ids)| ids.len() > 1) {
|
||||
let survivor = &ids[0];
|
||||
for doomed in &ids[1..] {
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO note_labels (note_id, label_id, via_tag)
|
||||
SELECT note_id, ?2, via_tag FROM note_labels WHERE label_id = ?1",
|
||||
params![doomed, survivor],
|
||||
)?;
|
||||
conn.execute(
|
||||
"UPDATE notes SET dirty = 1
|
||||
WHERE id IN (SELECT note_id FROM note_labels WHERE label_id = ?1)",
|
||||
[doomed],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO pending_deletes (entity, id, deleted_at)
|
||||
VALUES ('label', ?1, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))",
|
||||
[doomed],
|
||||
)?;
|
||||
conn.execute("DELETE FROM labels WHERE id = ?1", [doomed])?;
|
||||
}
|
||||
}
|
||||
|
||||
conn.execute_batch(
|
||||
"DROP INDEX idx_labels_name;
|
||||
CREATE UNIQUE INDEX idx_labels_name ON labels (fold(name));",
|
||||
)
|
||||
}
|
||||
|
||||
/// One schema version's change: SQL, or code for a change SQL alone can't make.
|
||||
enum Step {
|
||||
Sql(&'static str),
|
||||
@@ -353,10 +410,16 @@ const STEPS: &[Step] = &[
|
||||
Step::Sql(SCHEMA_V11),
|
||||
Step::Sql(SCHEMA_V12),
|
||||
Step::Sql(SCHEMA_V13),
|
||||
Step::Code(migrate_v14),
|
||||
];
|
||||
|
||||
/// Bring the database up to the latest schema. Idempotent.
|
||||
///
|
||||
/// Also gives the connection the `fold` function first. The label index is built on
|
||||
/// it, so a connection without it can't write a label at all, and every connection
|
||||
/// the core opens comes through here.
|
||||
pub fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||
register_fold(conn)?;
|
||||
conn.execute_batch("PRAGMA foreign_keys = ON;")?;
|
||||
let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
|
||||
for (to, step) in (1..).zip(STEPS) {
|
||||
@@ -372,6 +435,19 @@ pub fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `fold(name)`: [`derive::fold`] in SQL. Deterministic, so an index may use it, and
|
||||
/// innocuous (no side effects), so the schema may name it.
|
||||
fn register_fold(conn: &Connection) -> rusqlite::Result<()> {
|
||||
conn.create_scalar_function(
|
||||
"fold",
|
||||
1,
|
||||
FunctionFlags::SQLITE_UTF8
|
||||
| FunctionFlags::SQLITE_DETERMINISTIC
|
||||
| FunctionFlags::SQLITE_INNOCUOUS,
|
||||
|ctx| Ok(ctx.get::<Option<String>>(0)?.map(|s| derive::fold(&s))),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -483,7 +559,7 @@ mod tests {
|
||||
let version: i64 = conn
|
||||
.query_row("PRAGMA user_version", [], |r| r.get(0))
|
||||
.expect("version");
|
||||
assert_eq!(version, 13);
|
||||
assert_eq!(version, 14);
|
||||
}
|
||||
|
||||
/// Every attachment that predates v10 came down the feed, so it is already on the
|
||||
@@ -550,4 +626,104 @@ mod tests {
|
||||
.expect("count");
|
||||
assert_eq!(tables, 0);
|
||||
}
|
||||
|
||||
/// A database at v13: the last schema whose label index folded ASCII only.
|
||||
fn v13_db() -> Connection {
|
||||
let conn = Connection::open_in_memory().expect("open");
|
||||
conn.execute_batch("PRAGMA foreign_keys = ON;").expect("fk");
|
||||
for step in &STEPS[..13] {
|
||||
match step {
|
||||
Step::Sql(sql) => conn.execute_batch(sql).expect("batch"),
|
||||
Step::Code(apply) => apply(&conn).expect("step"),
|
||||
}
|
||||
}
|
||||
conn.execute_batch("PRAGMA user_version = 13;")
|
||||
.expect("v13");
|
||||
conn
|
||||
}
|
||||
|
||||
fn add_label(conn: &Connection, id: &str, name: &str, created: &str) {
|
||||
conn.execute(
|
||||
"INSERT INTO labels (id, name, created_at, updated_at, dirty)
|
||||
VALUES (?1, ?2, ?3, ?3, 0)",
|
||||
params![id, name, created],
|
||||
)
|
||||
.expect("label");
|
||||
}
|
||||
|
||||
fn tag(conn: &Connection, note: &str, label: &str, via_tag: bool) {
|
||||
conn.execute(
|
||||
"INSERT INTO note_labels (note_id, label_id, via_tag) VALUES (?1, ?2, ?3)",
|
||||
params![note, label, via_tag],
|
||||
)
|
||||
.expect("membership");
|
||||
}
|
||||
|
||||
/// One string per row, as `sql` builds it.
|
||||
fn rows(conn: &Connection, sql: &str) -> Vec<String> {
|
||||
conn.prepare(sql)
|
||||
.expect("prepare")
|
||||
.query_map([], |r| r.get(0))
|
||||
.expect("query")
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
.expect("rows")
|
||||
}
|
||||
|
||||
/// Before v14 the index was on lower(name), which leaves É alone, so a device
|
||||
/// could hold both of these. The older one survives and gains the other's notes.
|
||||
#[test]
|
||||
fn v14_merges_tags_that_differ_only_in_an_accented_letter() {
|
||||
let conn = v13_db();
|
||||
add_label(&conn, "old", "Café", "2026-01-01T00:00:00.000Z");
|
||||
add_label(&conn, "new", "CAFÉ", "2026-02-01T00:00:00.000Z");
|
||||
add_label(&conn, "other", "Tea", "2026-03-01T00:00:00.000Z");
|
||||
add_note(&conn, "derived", "#CAFÉ");
|
||||
add_note(&conn, "both", "both");
|
||||
add_note(&conn, "untouched", "tea");
|
||||
conn.execute("UPDATE notes SET dirty = 0", [])
|
||||
.expect("clean");
|
||||
tag(&conn, "derived", "new", true);
|
||||
tag(&conn, "both", "old", false);
|
||||
tag(&conn, "both", "new", false);
|
||||
tag(&conn, "untouched", "other", false);
|
||||
|
||||
migrate(&conn).expect("migrate");
|
||||
|
||||
assert_eq!(
|
||||
rows(&conn, "SELECT id || ' ' || name FROM labels ORDER BY id"),
|
||||
["old Café", "other Tea"]
|
||||
);
|
||||
assert_eq!(
|
||||
rows(
|
||||
&conn,
|
||||
"SELECT note_id || ' ' || label_id || ' ' || via_tag FROM note_labels ORDER BY note_id"
|
||||
),
|
||||
// `derived` stays derived: the body's #CAFÉ now names the survivor.
|
||||
["both old 0", "derived old 1", "untouched other 0"]
|
||||
);
|
||||
assert_eq!(
|
||||
rows(&conn, "SELECT id FROM notes WHERE dirty = 1 ORDER BY id"),
|
||||
["both", "derived"]
|
||||
);
|
||||
assert_eq!(
|
||||
rows(
|
||||
&conn,
|
||||
"SELECT id FROM pending_deletes WHERE entity = 'label'"
|
||||
),
|
||||
["new"]
|
||||
);
|
||||
}
|
||||
|
||||
/// The rebuilt index is what keeps the pair from coming back.
|
||||
#[test]
|
||||
fn after_v14_a_name_differing_only_in_an_accented_letter_is_refused() {
|
||||
let conn = Connection::open_in_memory().expect("open");
|
||||
migrate(&conn).expect("migrate");
|
||||
add_label(&conn, "a", "Café", "2026-01-01T00:00:00.000Z");
|
||||
let twin = conn.execute(
|
||||
"INSERT INTO labels (id, name, created_at, updated_at) VALUES ('b', 'CAFÉ', 'x', 'x')",
|
||||
[],
|
||||
);
|
||||
assert!(twin.is_err(), "the index let CAFÉ in beside Café");
|
||||
}
|
||||
}
|
||||
|
||||
+14
-2
@@ -248,7 +248,7 @@ fn touch(conn: &Connection, id: &str) -> rusqlite::Result<()> {
|
||||
fn find_or_create_label(conn: &Connection, name: &str) -> rusqlite::Result<String> {
|
||||
let existing: Option<String> = conn
|
||||
.query_row(
|
||||
"SELECT id FROM labels WHERE lower(name) = lower(?1)",
|
||||
"SELECT id FROM labels WHERE fold(name) = fold(?1)",
|
||||
[name],
|
||||
|r| r.get(0),
|
||||
)
|
||||
@@ -1039,7 +1039,7 @@ pub fn create_label(conn: &Connection, name: &str) -> rusqlite::Result<Label> {
|
||||
pub fn rename_label(conn: &Connection, id: &str, name: &str) -> rusqlite::Result<Label> {
|
||||
let clash: Option<(String, String)> = conn
|
||||
.query_row(
|
||||
"SELECT id, created_at FROM labels WHERE lower(name) = lower(?1) AND id <> ?2",
|
||||
"SELECT id, created_at FROM labels WHERE fold(name) = fold(?1) AND id <> ?2",
|
||||
params![name, id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
@@ -1580,6 +1580,18 @@ mod tests {
|
||||
assert!(edited.labels.is_empty());
|
||||
}
|
||||
|
||||
/// Every letter folds, accented ones included, as on the server (#5385). With
|
||||
/// SQLite's lower() the second note minted a "CAFÉ" tag of its own.
|
||||
#[test]
|
||||
fn a_tag_spelled_with_different_accented_capitals_is_the_same_tag() {
|
||||
let conn = db();
|
||||
let first = note(&conn, "coffee at #Café");
|
||||
let second = note(&conn, "coffee at #CAFÉ");
|
||||
assert_eq!(second.labels.len(), 1);
|
||||
assert_eq!(second.labels[0].id, first.labels[0].id);
|
||||
assert_eq!(list_labels(&conn).expect("labels").len(), 1);
|
||||
}
|
||||
|
||||
// ---- writes ----------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -175,7 +175,7 @@ fn is_dirty(conn: &Connection, note_id: &str) -> rusqlite::Result<bool> {
|
||||
|
||||
fn upsert_label(conn: &Connection, label: &wire::Label) -> rusqlite::Result<()> {
|
||||
// One label per name is enforced on both sides (locally a UNIQUE index on
|
||||
// lower(name); on the server, per owner). A label created offline can therefore
|
||||
// fold(name); on the server, per owner). A label created offline can therefore
|
||||
// collide with one the server already had under a different id — "work" typed on
|
||||
// this machine and "work" that already existed.
|
||||
//
|
||||
@@ -186,7 +186,7 @@ fn upsert_label(conn: &Connection, label: &wire::Label) -> rusqlite::Result<()>
|
||||
// memberships onto it, then drop the husk.
|
||||
let duplicates: Vec<String> = {
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT id FROM labels WHERE lower(name) = lower(?1) AND id <> ?2")?;
|
||||
conn.prepare("SELECT id FROM labels WHERE fold(name) = fold(?1) AND id <> ?2")?;
|
||||
let rows = stmt.query_map(params![label.name, label.id], |r| r.get::<_, String>(0))?;
|
||||
rows.collect::<rusqlite::Result<Vec<String>>>()?
|
||||
};
|
||||
@@ -219,7 +219,7 @@ fn upsert_label(conn: &Connection, label: &wire::Label) -> rusqlite::Result<()>
|
||||
|
||||
for old in &duplicates {
|
||||
// OR IGNORE guards a (note_id, label_id) collision. Today the unique index on
|
||||
// lower(name) makes that unreachable — two same-name labels can't coexist
|
||||
// fold(name) makes that unreachable — two same-name labels can't coexist
|
||||
// locally — so this is belt-and-braces against that index changing, not a
|
||||
// case we've seen. Anything it skips cascades away with the husk below, which
|
||||
// is correct: those are duplicates of a membership that now exists.
|
||||
|
||||
Vendored
+1
@@ -44,6 +44,7 @@
|
||||
{ "body": "#todo buy milk", "tags": ["todo"] },
|
||||
{ "body": "buy #milk and #eggs", "tags": ["milk", "eggs"] },
|
||||
{ "body": "#Todo and #todo", "tags": ["Todo"] },
|
||||
{ "body": "#café and #CAFÉ", "tags": ["café"] },
|
||||
{ "body": "line one\n#two", "tags": ["two"] },
|
||||
{ "body": "#tag, and #more.", "tags": ["tag", "more"] },
|
||||
{ "body": "#x-y_z9", "tags": ["x-y_z9"] },
|
||||
|
||||
@@ -7,6 +7,7 @@ import BaseButton from "./BaseButton.vue";
|
||||
import BaseInput from "./BaseInput.vue";
|
||||
import Icon from "./Icon.vue";
|
||||
import { useRowAction, useLoad } from "../composables/useAction";
|
||||
import { counted } from "../counted";
|
||||
|
||||
// Admin: groups of people a note can be shared with in one go (#5177). A group is
|
||||
// the instance's; anyone can share with it, and a note shared with it reaches whoever
|
||||
@@ -133,7 +134,7 @@ onMounted(() => {
|
||||
<div class="min-w-0">
|
||||
<p class="truncate text-sm font-medium text-neutral-800 dark:text-neutral-100">{{ g.name }}</p>
|
||||
<p class="text-xs text-neutral-400">
|
||||
{{ g.members.length }} {{ g.members.length === 1 ? "person" : "people" }}
|
||||
{{ counted(g.members.length, "person", "people") }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useNotesStore } from "../stores/notes";
|
||||
import { useLabelsStore } from "../stores/labels";
|
||||
import { useUiStore } from "../stores/ui";
|
||||
import { useAction } from "../composables/useAction";
|
||||
import { counted } from "../counted";
|
||||
|
||||
// Sidebar counterpart to Export: pick a .zip (an Inkwell export for round-trip,
|
||||
// or a Google Keep Takeout archive) and import its notes. Additive — never
|
||||
@@ -27,9 +28,8 @@ async function onFile(e: Event) {
|
||||
await act(async () => {
|
||||
const res = await notes.importNotes(file);
|
||||
await labels.load(); // surface any labels the import created
|
||||
const noun = res.imported === 1 ? "note" : "notes";
|
||||
const tail = res.skipped ? ` (${res.skipped} skipped)` : "";
|
||||
ui.showToast(`Imported ${res.imported} ${noun}${tail}.`);
|
||||
ui.showToast(`Imported ${counted(res.imported, "note", "notes")}${tail}.`);
|
||||
}, "Import failed.");
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useLabelsStore, type Label } from "../stores/labels";
|
||||
import Icon from "./Icon.vue";
|
||||
import type { NoteLabel } from "../stores/notes";
|
||||
import { foldTag } from "../notes/tags";
|
||||
|
||||
// A label attached via the picker is manual (via_tag: false).
|
||||
const asManual = (lb: Label): NoteLabel => ({ id: lb.id, name: lb.name, color: lb.color, via_tag: false });
|
||||
@@ -21,7 +22,7 @@ const shown = computed(() =>
|
||||
);
|
||||
const canCreate = computed(() => {
|
||||
const name = filter.value.trim();
|
||||
return name.length > 0 && !labels.items.some((lb) => lb.name.toLowerCase() === name.toLowerCase());
|
||||
return name.length > 0 && !labels.items.some((lb) => foldTag(lb.name) === foldTag(name));
|
||||
});
|
||||
|
||||
function toggle(lb: Label) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "../notes/colors";
|
||||
import BaseModal from "./BaseModal.vue";
|
||||
import Icon from "./Icon.vue";
|
||||
import { counted } from "../counted";
|
||||
|
||||
const emit = defineEmits<{ (e: "close"): void }>();
|
||||
const labels = useLabelsStore();
|
||||
@@ -86,7 +87,7 @@ async function doMerge(sourceId: string, targetId: string) {
|
||||
/>
|
||||
<span
|
||||
class="shrink-0 tabular-nums text-xs text-neutral-400"
|
||||
:title="`${lb.count ?? 0} note${(lb.count ?? 0) === 1 ? '' : 's'}`"
|
||||
:title="counted(lb.count ?? 0, 'note', 'notes')"
|
||||
>{{ lb.count ?? 0 }}</span
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import { formatShortDateTime, formatTrashCountdown, isOverdue, trashDaysLeft } from "../notes/datetime";
|
||||
import { useConfigStore } from "../stores/config";
|
||||
import { canEditText, isOwnNote } from "../notes/sharing";
|
||||
import { foldTag } from "../notes/tags";
|
||||
|
||||
const props = defineProps<{ note: Note; reorderable?: boolean; active?: boolean }>();
|
||||
const emit = defineEmits<{
|
||||
@@ -200,12 +201,12 @@ watch(
|
||||
// through the picker.
|
||||
const chipLabels = computed(() => props.note.labels.filter((lb) => !lb.via_tag));
|
||||
|
||||
// The colour the operator stored for each of this note's tags, keyed by lowercased
|
||||
// The colour the operator stored for each of this note's tags, keyed by folded
|
||||
// name — what MarkdownInline needs to tint a `#tag` the same as its chip would be.
|
||||
// Lowercased because tags dedupe case-insensitively, so `#Todo` and `#todo` are one.
|
||||
// Folded because `#Todo` and `#todo` are one tag.
|
||||
const tagColors = computed<Record<string, string>>(() => {
|
||||
const map: Record<string, string> = {};
|
||||
for (const lb of props.note.labels) map[lb.name.toLowerCase()] = lb.color;
|
||||
for (const lb of props.note.labels) map[foldTag(lb.name)] = lb.color;
|
||||
return map;
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { errorMessage } from "../api/errors";
|
||||
import { useNotesStore } from "../stores/notes";
|
||||
import BaseModal from "./BaseModal.vue";
|
||||
import Icon from "./Icon.vue";
|
||||
import { counted } from "../counted";
|
||||
|
||||
// Share a note with other people on this instance (#5174). The owner picks a member,
|
||||
// or a group the admin made (#5177), and says whether they may only read it or also
|
||||
@@ -53,8 +54,7 @@ function nameOf(share: NoteShare): string {
|
||||
|
||||
function detailOf(share: NoteShare): string {
|
||||
if (!share.group) return share.member?.email ?? "";
|
||||
const n = share.group.member_count;
|
||||
return `Group · ${n} ${n === 1 ? "person" : "people"}`;
|
||||
return `Group · ${counted(share.group.member_count, "person", "people")}`;
|
||||
}
|
||||
|
||||
async function load() {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { counted } from "./counted";
|
||||
|
||||
describe("counted", () => {
|
||||
it("uses the singular for exactly one", () => {
|
||||
expect(counted(1, "note", "notes")).toBe("1 note");
|
||||
});
|
||||
|
||||
it("uses the plural for everything else, zero included", () => {
|
||||
expect(counted(0, "note", "notes")).toBe("0 notes");
|
||||
expect(counted(3, "person", "people")).toBe("3 people");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
// A number and its noun: "1 note", "3 notes". The web is English-only, and English
|
||||
// has two forms; Android's <plurals> carry the same two (quantity "one" and "other").
|
||||
export function counted(n: number, one: string, other: string): string {
|
||||
return `${n} ${n === 1 ? one : other}`;
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
// here (frontend concern). Class strings are full literals so Tailwind's content
|
||||
// scanner (src/**/*.ts) keeps them in the build.
|
||||
|
||||
import { foldTag } from "./tags";
|
||||
|
||||
export const NOTE_COLOR_KEYS = [
|
||||
"default",
|
||||
"red",
|
||||
@@ -82,13 +84,13 @@ export const TAG_TEXT_CLASSES: Record<NoteColor, string> = {
|
||||
/**
|
||||
* The classes for one `#tag` in a note's own words.
|
||||
*
|
||||
* `picked` maps a lowercased tag name to the colour stored on that label, so a tag the
|
||||
* `picked` maps a folded tag name (`foldTag`) to the colour stored on that label, so a tag the
|
||||
* operator has recoloured reads the same inline as it does on a chip. A tag the note
|
||||
* does not carry as a label yet — just typed, not yet derived — is not in the map, and
|
||||
* `resolveLabelColor` derives one from the name exactly as the chip would have.
|
||||
*/
|
||||
export function tagTextClasses(name: string, picked?: Record<string, string>): string {
|
||||
return TAG_TEXT_CLASSES[resolveLabelColor({ name, color: picked?.[name.toLowerCase()] })];
|
||||
return TAG_TEXT_CLASSES[resolveLabelColor({ name, color: picked?.[foldTag(name)] })];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -200,15 +202,15 @@ export function derivedTint(id: string): NoteColor {
|
||||
* An explicitly-picked colour is still stored and still wins, so tag colours stay
|
||||
* editable exactly as asked.
|
||||
*
|
||||
* Lowercased because tags dedupe case-insensitively — `#Todo` renamed to `#todo` is
|
||||
* the same tag and should not change colour. Both `toLowerCase` here and Kotlin's
|
||||
* `lowercase()` are locale-independent, so the mirror holds.
|
||||
* Folded because `#Todo` renamed to `#todo` is the same tag and should not change
|
||||
* colour. `foldTag` here and Android's are both locale-independent lowercasing, so
|
||||
* the mirror holds.
|
||||
*/
|
||||
export function resolveLabelColor(label: { name: string; color?: string | null }): NoteColor {
|
||||
const picked = label.color as NoteColor | undefined | null;
|
||||
if (picked && picked !== "default" && KNOWN_COLORS.has(picked)) return picked;
|
||||
if (!label.name) return "default";
|
||||
return derivedTint(label.name.toLowerCase());
|
||||
return derivedTint(foldTag(label.name));
|
||||
}
|
||||
|
||||
// The fixture (four UUID hashes and seven tag names) lives in
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// How two tag names compare: equal once every letter is lowercased, accented ones
|
||||
// included, so `#Café` and `#CAFÉ` are one tag. The core's `derive::fold`, the
|
||||
// server's `labeling.named` and Android's `foldTag` fold the same way (#5385).
|
||||
export function foldTag(name: string): string {
|
||||
return name.toLowerCase();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { ref } from "vue";
|
||||
import { repo } from "../adapters";
|
||||
import { foldTag } from "../notes/tags";
|
||||
|
||||
export interface Label {
|
||||
id: string;
|
||||
@@ -45,7 +46,7 @@ export const useLabelsStore = defineStore("labels", () => {
|
||||
// the response: the survivor is whichever row is older, so it may well be the
|
||||
// one we asked to rename, and an id that still matches proves nothing happened.
|
||||
const absorbing = items.value.find(
|
||||
(lb) => lb.id !== id && lb.name.toLowerCase() === name.toLowerCase(),
|
||||
(lb) => lb.id !== id && foldTag(lb.name) === foldTag(name),
|
||||
);
|
||||
if (absorbing) {
|
||||
// A merge cannot be undone by repeating it, and here it is reachable by a
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { errorMessage } from "../api/errors";
|
||||
import { formatDateTime } from "../notes/datetime";
|
||||
import { toastOnFailure } from "../composables/useAction";
|
||||
import { counted } from "../counted";
|
||||
|
||||
// Opt-in server sync for the desktop app. Being UNLINKED is the normal resting
|
||||
// state, not an incomplete setup — the app is local-first and fully usable having
|
||||
@@ -313,14 +314,15 @@ function showOutcome(outcome: SyncOutcome) {
|
||||
const parts: string[] = [];
|
||||
if (sent > 0) parts.push(`sent ${sent}`);
|
||||
const up = outcome.push.uploaded;
|
||||
if (up > 0) parts.push(`uploaded ${up} file${up === 1 ? "" : "s"}`);
|
||||
if (up > 0) parts.push(`uploaded ${counted(up, "file", "files")}`);
|
||||
if (received > 0) parts.push(`received ${received}`);
|
||||
if (blobs > 0) parts.push(`${blobs} attachment${blobs === 1 ? "" : "s"}`);
|
||||
if (blobs > 0) parts.push(counted(blobs, "attachment", "attachments"));
|
||||
lastResult.value = parts.length ? `Synced — ${parts.join(", ")}.` : "Already up to date.";
|
||||
// Attachments that didn't arrive are retried next sync, so this is a note, not
|
||||
// an error — but saying nothing would leave a missing image unexplained.
|
||||
if (outcome.pull.blobs_failed > 0) {
|
||||
lastResult.value += ` ${outcome.pull.blobs_failed} attachment(s) didn't download — they'll retry on the next sync.`;
|
||||
const failed = counted(outcome.pull.blobs_failed, "attachment", "attachments");
|
||||
lastResult.value += ` ${failed} didn't download — they'll retry on the next sync.`;
|
||||
}
|
||||
// Rejections are the server refusing a specific change — surfaced, never
|
||||
// swallowed, because only the person can resolve them. The background cycle does
|
||||
@@ -328,8 +330,8 @@ function showOutcome(outcome: SyncOutcome) {
|
||||
// A file refused for good is listed once, here, and not retried; the editor says so
|
||||
// on the file itself from then on.
|
||||
const problems: string[] = [];
|
||||
if (outcome.push.rejected > 0) problems.push(`${outcome.push.rejected} change(s) the server wouldn't accept`);
|
||||
if (outcome.push.upload_failed > 0) problems.push(`${outcome.push.upload_failed} file(s) didn't upload`);
|
||||
if (outcome.push.rejected > 0) problems.push(`${counted(outcome.push.rejected, "change", "changes")} the server wouldn't accept`);
|
||||
if (outcome.push.upload_failed > 0) problems.push(`${counted(outcome.push.upload_failed, "file", "files")} didn't upload`);
|
||||
syncError.value = problems.length ? `${problems.join(" and ")}: ${outcome.push.errors.join("; ")}` : "";
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user