11 Commits
Author SHA1 Message Date
bvandeusenandClaude Opus 5.5 f2b48069e3 The AppImage tree is readable by everyone before it is repackaged
CI & Build / Build now, or wait for Android? (push) Successful in 2s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 3s
CI & Build / Web typecheck and unit tests (push) Successful in 10s
CI & Build / Python lint (push) Successful in 1s
Android / Build, or is the channel already serving this? (push) Successful in 3s
Android / Core and FFI clippy and tests (push) Skipped
Android / Kotlin + Rust (APK) (push) Skipped
Android / Build the server image (push) Skipped
CI & Build / Python tests (push) Successful in 13s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Successful in 1m45s
Desktop (Tauri) / Windows installer (cross-compiled) (push) Successful in 1m56s
Desktop (Tauri) / Update manifest (push) Successful in 4s
CI & Build / integration (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 14s
Desktop (Tauri) / Tauri desktop (Linux) (push) Successful in 2m59s
appimagetool's continuous build from 2026-10-29 rejects a tree that not every
user can read and run, which failed the desktop Linux lane. Extraction keeps the
build's restrictive modes (0700 directories, a 0770 AppRun.wrapped), and an
AppImage runs as whichever user launches it, so the modes are corrected rather
than the check skipped.

Issue #6712.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 10:09:58 -04:00
bvandeusenandClaude Opus 5.5 0f787c6363 The board places each card in the shortest column, instead of leaving it to CSS columns
Android / Build, or is the channel already serving this? (push) Successful in 2s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Build now, or wait for Android? (push) Successful in 2s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
CI & Build / Web typecheck and unit tests (push) Successful in 8s
CI & Build / integration (push) Successful in 1m37s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Successful in 1m58s
CI & Build / Python tests (push) Successful in 13s
Android / Core and FFI clippy and tests (push) Successful in 40s
CI & Build / Build & push image (push) Skipped
Android / Kotlin + Rust (APK) (push) Successful in 7m38s
Android / Build the server image (push) Successful in 1s
Desktop (Tauri) / Windows installer (cross-compiled) (push) Successful in 2m47s
Desktop (Tauri) / Tauri desktop (Linux) (push) Failing after 3m43s
Desktop (Tauri) / Update manifest (push) Skipped
CSS multi-column decides placement by balancing column heights, so the same
notes could land differently at the same width: an edit left two cards alone in
the fourth column with the middle two empty, and a refresh left the fourth empty
beside a stack of three in the first.

Cards now go, in board order, into the shortest column, leftmost on a tie, so the
same notes at the same width always land the same way and every column fills
before any stacks. This changes the reading order to match Android: the second
note sits top-right rather than under the first.

useMasonry measures the cards and watches them for height changes. Placement is a
pure function, tested in notes/masonry.test.ts. Cards are absolutely placed, so
TransitionGroup's move animation carries on working unchanged.

Issue #6709.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:56:58 -04:00
bvandeusenandClaude Opus 5.5 7fca1f6c7f A forwarding header shorter than the hop count is read from its leftmost entry
CI & Build / Python lint (push) Successful in 2s
CI & Build / Build now, or wait for Android? (push) Successful in 3s
Android / Build, or is the channel already serving this? (push) Successful in 3s
Android / Core and FFI clippy and tests (push) Skipped
Android / Kotlin + Rust (APK) (push) Skipped
Android / Build the server image (push) Skipped
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Skipped
Desktop (Tauri) / Tauri desktop (Linux) (push) Skipped
Desktop (Tauri) / Windows installer (cross-compiled) (push) Skipped
Desktop (Tauri) / Update manifest (push) Skipped
CI & Build / Web typecheck and unit tests (push) Successful in 9s
CI & Build / Python tests (push) Successful in 17s
CI & Build / integration (push) Successful in 1m30s
CI & Build / Build & push image (push) Successful in 45s
At Trusted proxy hops 2 (Cloudflare → Traefik → app), a LAN request reaching
Traefik directly carries one X-Forwarded-For entry. trusted_entry returned None
for it, so every LAN visitor was filed under Traefik's overlay address in the
throttles and the audit log. Cloudflare's single X-Forwarded-Proto: https read
as plain HTTP, so the public road lost the Secure cookie and HSTS.

A short header now clamps to its leftmost entry, the one the first proxy wrote,
as family canon #5004 does in Minstrel, Librarian and Forge. A caller's own
entries can only make the header longer, so this trusts nothing more than before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 08:37:14 -04:00
bvandeusenandClaude Opus 5.5 b74dc7c1fe One app fixture for the tests, and ViewModels built where they are used
CI & Build / Python lint (push) Successful in 2s
CI & Build / Build now, or wait for Android? (push) Successful in 2s
Android / Build, or is the channel already serving this? (push) Successful in 3s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Skipped
Desktop (Tauri) / Tauri desktop (Linux) (push) Skipped
Desktop (Tauri) / Windows installer (cross-compiled) (push) Skipped
Desktop (Tauri) / Update manifest (push) Skipped
CI & Build / Web typecheck and unit tests (push) Successful in 8s
CI & Build / Python tests (push) Successful in 13s
Android / Core and FFI clippy and tests (push) Successful in 25s
CI & Build / integration (push) Successful in 1m31s
CI & Build / Build & push image (push) Skipped
Android / Kotlin + Rust (APK) (push) Successful in 6m41s
Android / Build the server image (push) Successful in 1s
The tests' `app` fixture, the same two lines in eleven files, now lives once in
tests/conftest.py.

On Android each ViewModel carried a companion `factory` that only wrapped its
constructor in viewModelFactory { initializer { … } }. MainActivity now builds
each one with Compose's viewModel { … } builder, so the five factories and their
imports are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 21:25:05 -04:00
bvandeusenandClaude Opus 5.5 463b22bbe4 A push that loses a create race applies its change instead of failing
CI & Build / Python lint (push) Successful in 2s
CI & Build / Build now, or wait for Android? (push) Successful in 3s
Android / Build, or is the channel already serving this? (push) Successful in 3s
Android / Core and FFI clippy and tests (push) Skipped
Android / Kotlin + Rust (APK) (push) Skipped
Android / Build the server image (push) Skipped
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 3s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Skipped
Desktop (Tauri) / Tauri desktop (Linux) (push) Skipped
Desktop (Tauri) / Windows installer (cross-compiled) (push) Skipped
Desktop (Tauri) / Update manifest (push) Skipped
CI & Build / Web typecheck and unit tests (push) Successful in 9s
CI & Build / Python tests (push) Successful in 12s
CI & Build / integration (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 34s
Two devices pushing the same new note or tag at the same moment both found
no row and both inserted it; the slower insert hit the primary key and the
whole push answered 500. Each pushed note or label change now runs in a
savepoint. If its insert loses the race, only that change is rolled back,
and it is applied again against the row the other push committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 20:34:04 -04:00
bvandeusenandClaude Opus 5.5 c6f10f157d Timeline shows archived notes too, each one labelled Archived
CI & Build / Python lint (push) Successful in 2s
CI & Build / Build now, or wait for Android? (push) Successful in 3s
Android / Build, or is the channel already serving this? (push) Successful in 3s
Android / Core and FFI clippy and tests (push) Skipped
Android / Kotlin + Rust (APK) (push) Skipped
Android / Build the server image (push) Skipped
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 3s
CI & Build / Web typecheck and unit tests (push) Successful in 9s
CI & Build / Python tests (push) Successful in 13s
CI & Build / integration (push) Successful in 1m34s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Successful in 1m48s
CI & Build / Build & push image (push) Successful in 30s
Desktop (Tauri) / Windows installer (cross-compiled) (push) Successful in 2m2s
Desktop (Tauri) / Tauri desktop (Linux) (push) Successful in 3m10s
Desktop (Tauri) / Update manifest (push) Successful in 3s
Timeline lists everything not in Trash. The card's Archived label is now
hidden only on the Archive page, read off the route: Timeline keeps its
own list and never sets the board's view, so arriving from the Archive
used to leave the store saying "archived".

Task #6318.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:29:40 -04:00
bvandeusenandClaude Opus 5.5 66fd5707b7 tagQueryAt decides in one check, within detekt's return limit
CI & Build / Python lint (push) Successful in 2s
CI & Build / Build now, or wait for Android? (push) Successful in 2s
Android / Build, or is the channel already serving this? (push) Successful in 3s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Skipped
Desktop (Tauri) / Tauri desktop (Linux) (push) Skipped
Desktop (Tauri) / Windows installer (cross-compiled) (push) Skipped
Desktop (Tauri) / Update manifest (push) Skipped
CI & Build / Web typecheck and unit tests (push) Successful in 9s
CI & Build / Python tests (push) Successful in 12s
Android / Core and FFI clippy and tests (push) Successful in 25s
CI & Build / integration (push) Successful in 1m29s
CI & Build / Build & push image (push) Skipped
Android / Kotlin + Rust (APK) (push) Successful in 6m56s
Android / Build the server image (push) Successful in 1s
Task #6316.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:38:36 -04:00
bvandeusenandClaude Opus 5.5 7e96683f01 The archive-search tests sign in and keep the listed notes alive
CI & Build / Python lint (push) Successful in 2s
CI & Build / Build now, or wait for Android? (push) Successful in 2s
Android / Build, or is the channel already serving this? (push) Successful in 2s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
CI & Build / Web typecheck and unit tests (push) Successful in 8s
CI & Build / Python tests (push) Successful in 14s
Android / Core and FFI clippy and tests (push) Successful in 31s
CI & Build / integration (push) Successful in 1m38s
CI & Build / Build & push image (push) Skipped
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Successful in 1m52s
Desktop (Tauri) / Windows installer (cross-compiled) (push) Successful in 3m5s
Desktop (Tauri) / Tauri desktop (Linux) (push) Successful in 3m44s
Android / Kotlin + Rust (APK) (push) Failing after 5m10s
Android / Build the server image (push) Skipped
Desktop (Tauri) / Update manifest (push) Successful in 4s
The integration test registers the owner before writing notes, and the
core test binds the "all" listing before borrowing ids from it.

Task #6315.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:28:01 -04:00
bvandeusenandClaude Opus 5.5 ba97003ea0 Android editor suggests existing tags while a #tag is typed
CI & Build / Python lint (push) Successful in 2s
Android / Build, or is the channel already serving this? (push) Successful in 3s
CI & Build / Build now, or wait for Android? (push) Successful in 2s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
CI & Build / Web typecheck and unit tests (push) Successful in 8s
CI & Build / Python tests (push) Successful in 11s
Android / Core and FFI clippy and tests (push) Failing after 33s
Android / Kotlin + Rust (APK) (push) Skipped
Android / Build the server image (push) Skipped
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Failing after 1m11s
Desktop (Tauri) / Tauri desktop (Linux) (push) Skipped
Desktop (Tauri) / Windows installer (cross-compiled) (push) Skipped
Desktop (Tauri) / Update manifest (push) Skipped
CI & Build / integration (push) Failing after 1m29s
CI & Build / Build & push image (push) Skipped
The web editor's `#` suggestions, ported: with the caret in a `#tag`,
a row of chips under the field offers the existing tags that finish it,
prefix matches first and busiest first. A tap puts in the whole name and
a space. The rules are the web's tags.ts, with the same test cases.

Task #6316.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:23:08 -04:00
bvandeusenandClaude Opus 5.5 b98a0c315f Search and tags look through the Archive, and archived cards say so
A search or a tag filter on the main board, and a tag's own view, now
list every note not in Trash (a new `all` board view on the server and in
the core), so finished work can still be looked up. Archive and Trash
keep a search inside themselves.

An archived note met anywhere but the Archive carries an "Archived" chip
at the top of its card, on the web and on Android.

Task #6315.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:23:08 -04:00
bvandeusenandClaude Opus 5.5 5780220ff1 The image build stops pruning the runner's shared Docker daemon
CI & Build / Build now, or wait for Android? (push) Successful in 2s
Android / Build, or is the channel already serving this? (push) Successful in 2s
Android / Core and FFI clippy and tests (push) Skipped
Android / Kotlin + Rust (APK) (push) Skipped
Android / Build the server image (push) Skipped
CI & Build / Python lint (push) Successful in 2s
CI & Build / Web typecheck and unit tests (push) Successful in 8s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Skipped
Desktop (Tauri) / Tauri desktop (Linux) (push) Skipped
Desktop (Tauri) / Windows installer (cross-compiled) (push) Skipped
Desktop (Tauri) / Update manifest (push) Skipped
CI & Build / Python tests (push) Successful in 12s
CI & Build / integration (push) Successful in 1m25s
CI & Build / Build & push image (push) Successful in 34s
The build job ran `docker system prune -af` on the runner's shared Docker
daemon. That deletes every image no container is using at that moment,
including images other repos' jobs had just pulled and were about to start.
Jobs with a service container wait ~14s for it to become healthy between
pull and create, and fail with "No such image" when a prune lands inside
that wait (CI-runner #16). The runner host prunes nightly instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 10:20:33 -04:00
44 changed files with 684 additions and 202 deletions
+4 -4
View File
@@ -326,10 +326,10 @@ jobs:
echo "value=$TAGS" >> $GITHUB_OUTPUT echo "value=$TAGS" >> $GITHUB_OUTPUT
echo "build_version=$BUILD_VERSION" >> $GITHUB_OUTPUT echo "build_version=$BUILD_VERSION" >> $GITHUB_OUTPUT
- name: Free disk space # No disk-space prune step: the runner's Docker daemon is shared, and
run: | # `docker system prune -af` here deleted images other repos' jobs had
docker system prune -af || true # just pulled and were about to start (CI-runner #16). The runner host
docker builder prune --keep-storage 5g -f || true # prunes nightly instead.
# Bake EVERY client in, on every image build, so a self-hoster gets a working # Bake EVERY client in, on every image build, so a self-hoster gets a working
# app for their machine from the server holding their notes, with no trip to a # app for their machine from the server holding their notes, with no trip to a
@@ -219,15 +219,16 @@ private fun App(
) { ) {
val context = LocalContext.current val context = LocalContext.current
val board: BoardViewModel = val board: BoardViewModel =
viewModel( viewModel {
factory = BoardViewModel(
BoardViewModel.factory(core, readFile = files::read) { core,
// Any store write can have moved the next reminder. Called on // Any store write can have moved the next reminder. Called on the IO
// the IO dispatcher by the view model, which is where it has to // dispatcher by the view model, which is where it has to be — this
// be — this reads every note carrying a reminder. // reads every note carrying a reminder.
Reminders.refresh(context, core) onRemindersChanged = { Reminders.refresh(context, core) },
}, readFile = files::read,
) )
}
// Consumed, not just read: without clearing it, every later recomposition // Consumed, not just read: without clearing it, every later recomposition
// would reopen the same note and make the editor impossible to leave. // would reopen the same note and make the editor impossible to leave.
@@ -251,7 +252,7 @@ private fun App(
// A pull can rewrite every note the board is holding, so a sync that changed // A pull can rewrite every note the board is holding, so a sync that changed
// anything tells it to reload. Wired here, at the one place that owns both. // anything tells it to reload. Wired here, at the one place that owns both.
val sync: SyncViewModel = val sync: SyncViewModel =
viewModel(factory = SyncViewModel.factory(core, onStoreChanged = board::refresh)) viewModel { SyncViewModel(core, onStoreChanged = board::refresh) }
// Screen visibility is view STATE, not view-model state: it is about what is on // Screen visibility is view STATE, not view-model state: it is about what is on
// the display, and nothing in the store cares. Saveable so a rotation does not // the display, and nothing in the store cares. Saveable so a rotation does not
@@ -266,14 +267,14 @@ private fun App(
// board may be LOOKING at one that a delete or a merge just removed. Both are // board may be LOOKING at one that a delete or a merge just removed. Both are
// `refreshLabels`, which also leaves a lens whose tag stopped existing. // `refreshLabels`, which also leaves a lens whose tag stopped existing.
val tags: TagsViewModel = val tags: TagsViewModel =
viewModel(factory = TagsViewModel.factory(core, onStoreChanged = board::refreshLabels)) viewModel { TagsViewModel(core, onStoreChanged = board::refreshLabels) }
// A share landing changes the note's `shared` flag, which the board's card chip // A share landing changes the note's `shared` flag, which the board's card chip
// reads, so the board reloads after one. // reads, so the board reloads after one.
val share: ShareViewModel = val share: ShareViewModel =
viewModel(factory = ShareViewModel.factory(core, onStoreChanged = board::refresh)) viewModel { ShareViewModel(core, onStoreChanged = board::refresh) }
val update: UpdateViewModel = viewModel(factory = UpdateViewModel.factory(core, context)) val update: UpdateViewModel = viewModel { UpdateViewModel(core, context.applicationContext) }
val settings = remember(context) { SyncSettings(context) } val settings = remember(context) { SyncSettings(context) }
var automatic by remember { mutableStateOf(settings.automatic) } var automatic by remember { mutableStateOf(settings.automatic) }
@@ -1,11 +1,14 @@
package com.fabledsword.inkwell.ui package com.fabledsword.inkwell.ui
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
@@ -16,6 +19,7 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalMinimumInteractiveComponentSize import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.CompositionLocalProvider
@@ -32,12 +36,14 @@ import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.fabledsword.inkwell.R import com.fabledsword.inkwell.R
import com.fabledsword.inkwell.core.Label
/** /**
* The note's body, as fields and checkboxes rather than as markup. * The note's body, as fields and checkboxes rather than as markup.
@@ -50,6 +56,8 @@ fun BlockBody(
blocks: List<EditorBlock>, blocks: List<EditorBlock>,
readOnly: Boolean, readOnly: Boolean,
focus: Long?, focus: Long?,
/** Every tag there is, offered while a `#tag` is typed (see [TagSuggestions]). */
tags: List<Label>,
onChange: (List<EditorBlock>) -> Unit, onChange: (List<EditorBlock>) -> Unit,
onFocus: (Long?) -> Unit, onFocus: (Long?) -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
@@ -80,6 +88,7 @@ fun BlockBody(
TaskBlock( TaskBlock(
block = block, block = block,
readOnly = readOnly, readOnly = readOnly,
tags = tags,
requester = requester, requester = requester,
onChange = { replace(index, it) }, onChange = { replace(index, it) },
onEnter = { onEnter = {
@@ -102,6 +111,7 @@ fun BlockBody(
ProseBlock( ProseBlock(
block = block, block = block,
readOnly = readOnly, readOnly = readOnly,
tags = tags,
requester = requester, requester = requester,
onChange = { replace(index, it) }, onChange = { replace(index, it) },
onBlur = { onBlur = {
@@ -132,20 +142,30 @@ fun BlockBody(
private fun ProseBlock( private fun ProseBlock(
block: EditorBlock, block: EditorBlock,
readOnly: Boolean, readOnly: Boolean,
tags: List<Label>,
requester: FocusRequester, requester: FocusRequester,
onChange: (EditorBlock) -> Unit, onChange: (EditorBlock) -> Unit,
onBlur: () -> Unit, onBlur: () -> Unit,
) { ) {
var focused by remember { mutableStateOf(false) }
Column {
BlockField( BlockField(
value = block.value, value = block.value,
onValueChange = { onChange(block.copy(value = it)) }, onValueChange = { onChange(block.copy(value = it)) },
modifier = modifier =
Modifier Modifier
.focusRequester(requester) .focusRequester(requester)
.onFocusChanged { if (!it.isFocused) onBlur() }, .onFocusChanged {
focused = it.isFocused
if (!it.isFocused) onBlur()
},
enabled = !readOnly, enabled = !readOnly,
hint = R.string.editor_body_hint, hint = R.string.editor_body_hint,
) )
if (focused && !readOnly) {
TagSuggestions(value = block.value, tags = tags, onPick = { onChange(block.copy(value = it)) })
}
}
} }
/** /**
@@ -159,11 +179,13 @@ private fun ProseBlock(
private fun TaskBlock( private fun TaskBlock(
block: EditorBlock, block: EditorBlock,
readOnly: Boolean, readOnly: Boolean,
tags: List<Label>,
requester: FocusRequester, requester: FocusRequester,
onChange: (EditorBlock) -> Unit, onChange: (EditorBlock) -> Unit,
onEnter: () -> Unit, onEnter: () -> Unit,
onDelete: () -> Unit, onDelete: () -> Unit,
) { ) {
var focused by remember { mutableStateOf(false) }
// Material sizes every interactive component to a 48dp touch target, and on a // Material sizes every interactive component to a 48dp touch target, and on a
// checklist that IS the row height. // checklist that IS the row height.
CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides ROW_TOUCH) { CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides ROW_TOUCH) {
@@ -176,7 +198,11 @@ private fun TaskBlock(
BlockField( BlockField(
value = block.value, value = block.value,
onValueChange = { onChange(block.copy(value = it)) }, onValueChange = { onChange(block.copy(value = it)) },
modifier = Modifier.weight(1f).focusRequester(requester), modifier =
Modifier
.weight(1f)
.focusRequester(requester)
.onFocusChanged { focused = it.isFocused },
enabled = !readOnly, enabled = !readOnly,
singleLine = true, singleLine = true,
textStyle = textStyle =
@@ -198,6 +224,57 @@ private fun TaskBlock(
} }
} }
} }
if (focused && !readOnly) {
// Indented past the box, so the row reads as belonging to this item's text.
TagSuggestions(
value = block.value,
tags = tags,
onPick = { onChange(block.copy(value = it)) },
modifier = Modifier.padding(start = ROW_TOUCH),
)
}
}
/**
* The existing tags that finish the `#tag` the caret is in, as a row of chips under
* the field; nothing when the caret is not in a tag or no tag fits.
*
* So a note is filed under `#groceries` rather than a new `#grocery` beside it. Which
* text counts as a tag being typed, which tags are offered and how one is put in are
* in TagSuggest.kt, where they are tested; this is only the row. A tap swaps the token
* for the whole name and a space, and leaves the caret after it to keep typing.
*
* A row rather than a dropdown, because a popup over the field would sit on the very
* line being typed, and on a phone the keyboard already owns the bottom of the screen.
*/
@Composable
private fun TagSuggestions(
value: TextFieldValue,
tags: List<Label>,
onPick: (TextFieldValue) -> Unit,
modifier: Modifier = Modifier,
) {
val caret = value.selection.end
val at = if (value.selection.collapsed) tagQueryAt(value.text, caret) else null
val matches =
remember(at?.query, tags) {
at?.let { suggestTags(tags, it.query, { t -> t.name }, { t -> t.count ?: 0L }) }.orEmpty()
}
if (at == null || matches.isEmpty()) return
Row(
modifier = modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
matches.forEach { tag ->
SuggestionChip(
onClick = {
val (text, end) = insertTag(value.text, at, tag.name)
onPick(TextFieldValue(text, TextRange(end)))
},
label = { Text("#${tag.name}") },
)
}
}
} }
/** /**
@@ -258,6 +258,7 @@ fun BoardScreen(
onNoteAction = onCardAction, onNoteAction = onCardAction,
onConfirmDelete = { confirmingDelete = it }, onConfirmDelete = { confirmingDelete = it },
reorderable = state.reorderable, reorderable = state.reorderable,
marksArchived = state.marksArchived,
onReorder = onReorder, onReorder = onReorder,
) )
} }
@@ -529,7 +530,7 @@ private fun DrawerRow(
* Staggered rather than a uniform grid because notes are wildly different heights * Staggered rather than a uniform grid because notes are wildly different heights
* — a one-line thought beside a twelve-item checklist — and forcing them to a * — a one-line thought beside a twelve-item checklist — and forcing them to a
* common height either clips the long ones or strands whitespace under the short * common height either clips the long ones or strands whitespace under the short
* ones. This is the Compose equivalent of the CSS multi-column `NoteGrid.vue` uses. * ones. `NoteGrid.vue` places cards the same way, each into the shortest column.
*/ */
@Composable @Composable
private fun NoteBoard( private fun NoteBoard(
@@ -540,6 +541,8 @@ private fun NoteBoard(
onConfirmDelete: (Note) -> Unit, onConfirmDelete: (Note) -> Unit,
/** Whether cards can be dragged into a new order: the plain main board only. */ /** Whether cards can be dragged into a new order: the plain main board only. */
reorderable: Boolean, reorderable: Boolean,
/** Whether an archived card carries the Archived chip (BoardState.marksArchived). */
marksArchived: Boolean,
onReorder: (List<String>) -> Unit, onReorder: (List<String>) -> Unit,
) { ) {
// The web's breakpoints (NoteGrid.vue: three columns from `lg`, 1024px, four from // The web's breakpoints (NoteGrid.vue: three columns from `lg`, 1024px, four from
@@ -635,6 +638,7 @@ private fun NoteBoard(
onAction = { onNoteAction(note, it) }, onAction = { onNoteAction(note, it) },
onConfirmDelete = { onConfirmDelete(note) }, onConfirmDelete = { onConfirmDelete(note) },
dragging = carried, dragging = carried,
marksArchived = marksArchived,
) )
} }
DisposableEffect(note.id) { onDispose { bounds.forget(note.id) } } DisposableEffect(note.id) { onDispose { bounds.forget(note.id) } }
@@ -5,10 +5,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.fabledsword.inkwell.core.Inkwell import com.fabledsword.inkwell.core.Inkwell
import com.fabledsword.inkwell.core.Label import com.fabledsword.inkwell.core.Label
import com.fabledsword.inkwell.core.Note import com.fabledsword.inkwell.core.Note
@@ -91,6 +88,14 @@ data class BoardState(
* filtered subset, whose order would be renumbered against notes it can't see. * filtered subset, whose order would be renumbered against notes it can't see.
*/ */
val reorderable: Boolean get() = filterable && filters.count == 0 && !searching val reorderable: Boolean get() = filterable && filters.count == 0 && !searching
/**
* Whether an archived card says so: anywhere the Archive is not the whole view. A
* search or a tag looks through the Archive as well as the board, so finished
* work can still be looked up, and the chip is what keeps it from reading as
* current.
*/
val marksArchived: Boolean get() = destination != Destination.Archive
} }
/** /**
@@ -183,15 +188,18 @@ class BoardViewModel(
): List<Note> { ): List<Note> {
// Only the main board has filters; every board view takes the search text. // Only the main board has filters; every board view takes the search text.
val searchOnly = BoardFilters().facets(text) val searchOnly = BoardFilters().facets(text)
// A search or a tag looks through the Archive too, as on the web; Archive and
// Trash keep a search inside themselves.
val notesView = if (text.isNotBlank() || filters.labelIds.isNotEmpty()) VIEW_ALL else VIEW_NOTES
return when (destination) { return when (destination) {
Destination.Notes -> core.listNotes(query(VIEW_NOTES, facets = filters.facets(text))) Destination.Notes -> core.listNotes(query(notesView, facets = filters.facets(text)))
Destination.Archive -> core.listNotes(query(VIEW_ARCHIVE, facets = searchOnly)) Destination.Archive -> core.listNotes(query(VIEW_ARCHIVE, facets = searchOnly))
Destination.Trash -> core.listNotes(query(VIEW_TRASH, facets = searchOnly)) Destination.Trash -> core.listNotes(query(VIEW_TRASH, facets = searchOnly))
// Not a board view: the core models reminders as its own query, since // Not a board view: the core models reminders as its own query, since
// "has a reminder" cuts across archived and active alike. `search` moves // "has a reminder" cuts across archived and active alike. `search` moves
// a search off this view, so it never has text to apply. // a search off this view, so it never has text to apply.
Destination.Reminders -> core.reminderNotes() Destination.Reminders -> core.reminderNotes()
is Destination.WithLabel -> core.listNotes(query(VIEW_NOTES, labelId = destination.id, facets = searchOnly)) is Destination.WithLabel -> core.listNotes(query(VIEW_ALL, labelId = destination.id, facets = searchOnly))
} }
} }
@@ -647,12 +655,8 @@ class BoardViewModel(
private const val VIEW_ARCHIVE = "archived" private const val VIEW_ARCHIVE = "archived"
private const val VIEW_TRASH = "trash" private const val VIEW_TRASH = "trash"
fun factory( /** The board and the Archive together — everything not in Trash. */
core: Inkwell, private const val VIEW_ALL = "all"
readFile: (Uri) -> PickedFile,
onRemindersChanged: () -> Unit,
): ViewModelProvider.Factory =
viewModelFactory { initializer { BoardViewModel(core, onRemindersChanged, readFile) } }
} }
} }
@@ -55,6 +55,8 @@ fun NoteCard(
onConfirmDelete: () -> Unit, onConfirmDelete: () -> Unit,
/** The board is carrying this card (BoardDrag.kt). */ /** The board is carrying this card (BoardDrag.kt). */
dragging: Boolean = false, dragging: Boolean = false,
/** Whether an archived note says so — everywhere but the Archive itself. */
marksArchived: Boolean = true,
) { ) {
val dark = isSystemInDarkTheme() val dark = isSystemInDarkTheme()
val haptics = LocalHapticFeedback.current val haptics = LocalHapticFeedback.current
@@ -107,7 +109,11 @@ fun NoteCard(
.border(1.dp, if (dark) CARD_EDGE_DARK else CARD_EDGE_LIGHT, RoundedCornerShape(CARD_RADIUS)) .border(1.dp, if (dark) CARD_EDGE_DARK else CARD_EDGE_LIGHT, RoundedCornerShape(CARD_RADIUS))
.padding(12.dp), .padding(12.dp),
) { ) {
CardContents(note = note, onToggleItem = onToggleItem) CardContents(
note = note,
onToggleItem = onToggleItem,
archivedChip = marksArchived && note.archived && !note.trashed,
)
} }
NoteMenu( NoteMenu(
@@ -120,12 +126,23 @@ fun NoteCard(
} }
} }
/** What a card shows, top to bottom: tags, body, links, attachments, reminder, sharing. */ /**
* What a card shows, top to bottom: archived or not, tags, body, links, attachments,
* reminder, sharing.
*/
@Composable @Composable
private fun CardContents( private fun CardContents(
note: Note, note: Note,
onToggleItem: (Int, Boolean) -> Unit, onToggleItem: (Int, Boolean) -> Unit,
archivedChip: Boolean,
) { ) {
// Above everything, tags included: whether a note is put away is the first thing
// to know about a search result or a tag's note, before what it says.
if (archivedChip) {
TintChip(stringResource(R.string.card_archived), "default")
Spacer(Modifier.height(8.dp))
}
// TAGS FIRST, on a row of their own above the body: a board is scanned, and // TAGS FIRST, on a row of their own above the body: a board is scanned, and
// what a note is about should be the first thing the eye lands on. Not beside // what a note is about should be the first thing the eye lands on. Not beside
// the body, whose first line is the note's name. // the body, whose first line is the note's name.
@@ -243,6 +243,7 @@ fun NoteEditorScreen(
blocks = blocks, blocks = blocks,
readOnly = readOnly, readOnly = readOnly,
focus = focus, focus = focus,
tags = labels,
onChange = { blocks = it }, onChange = { blocks = it },
onFocus = { focus = it }, onFocus = { focus = it },
) )
@@ -4,10 +4,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.fabledsword.inkwell.core.CoreException import com.fabledsword.inkwell.core.CoreException
import com.fabledsword.inkwell.core.Inkwell import com.fabledsword.inkwell.core.Inkwell
import com.fabledsword.inkwell.core.Member import com.fabledsword.inkwell.core.Member
@@ -132,11 +129,4 @@ class ShareViewModel(
} }
} }
} }
companion object {
fun factory(
core: Inkwell,
onStoreChanged: () -> Unit,
): ViewModelProvider.Factory = viewModelFactory { initializer { ShareViewModel(core, onStoreChanged) } }
}
} }
@@ -4,10 +4,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.fabledsword.inkwell.core.Compatibility import com.fabledsword.inkwell.core.Compatibility
import com.fabledsword.inkwell.core.Inkwell import com.fabledsword.inkwell.core.Inkwell
import com.fabledsword.inkwell.core.ProbeResult import com.fabledsword.inkwell.core.ProbeResult
@@ -315,13 +312,6 @@ class SyncViewModel(
fun dismissSyncError() { fun dismissSyncError() {
state = state.copy(syncError = null) state = state.copy(syncError = null)
} }
companion object {
fun factory(
core: Inkwell,
onStoreChanged: () -> Unit,
): ViewModelProvider.Factory = viewModelFactory { initializer { SyncViewModel(core, onStoreChanged) } }
}
} }
/** /**
@@ -0,0 +1,98 @@
package com.fabledsword.inkwell.ui
/**
* Suggesting existing tags while a `#tag` is typed, so a note is filed under
* `#groceries` rather than a new `#grocery` beside it.
*
* The same rules as the web's `frontend/src/notes/tags.ts` (`tagQueryAt`,
* `suggestTags`, `insertTag`), and the same body-tag grammar as `line_tags` in
* core/src/local/derive.rs: a `#` at the start or after whitespace, a letter, then
* letters, digits, `_` and `-`.
*/
private val TAG_CHAR = Regex("[\\p{IsAlphabetic}\\p{N}_-]")
private val WHOLE_TAG = Regex("^\\p{IsAlphabetic}[\\p{IsAlphabetic}\\p{N}_-]*$")
private fun Char.isTagChar() = TAG_CHAR.matches(toString())
/**
* The `#tag` the caret is in the middle of typing: where its `#` is, where the token
* ends (it may run on past the caret), and the part typed so far.
*/
data class TagQuery(
val start: Int,
val end: Int,
val query: String,
)
/**
* The tag being typed at [caret], or null when the caret is not in one.
*
* A bare `#` counts, with an empty query: that is the moment a suggestion list is most
* use, because it is the moment someone has not yet decided what to type. Anything
* the grammar would not derive (`a#b`, `#2024`, `##x`) is not a tag here either, so
* the row never offers to finish something the core would ignore.
*/
fun tagQueryAt(
text: String,
caret: Int,
): TagQuery? {
var i = caret
while (i > 0 && text[i - 1].isTagChar()) i--
val hash = i - 1
val query = text.substring(i, caret)
val inTag =
hash >= 0 &&
text[hash] == '#' &&
(hash == 0 || text[hash - 1].isWhitespace()) &&
(query.isEmpty() || Character.isAlphabetic(query[0].code))
if (!inTag) return null
var end = caret
while (end < text.length && text[end].isTagChar()) end++
return TagQuery(start = hash, end = end, query = query)
}
/**
* The existing tags worth offering for [query], best first.
*
* Names that start with what was typed come before names that merely contain it;
* within each, the tag on the most notes first. A tag already typed out in full is
* left out, so there is nothing to offer once `#grocery` is finished. A tag whose
* name the body grammar can't hold (one made in the picker as "to do") is left out
* too: inserting `#to do` would derive `#to`.
*/
fun <T> suggestTags(
tags: List<T>,
query: String,
name: (T) -> String,
count: (T) -> Long,
limit: Int = SUGGESTION_LIMIT,
): List<T> {
val q = foldTag(query)
val prefix = { t: T -> if (foldTag(name(t)).startsWith(q)) 0 else 1 }
return tags
.filter { t ->
val f = foldTag(name(t))
WHOLE_TAG.matches(name(t)) && f != q && f.contains(q)
}.sortedWith(
compareBy<T> { prefix(it) }
.thenByDescending { count(it) }
.thenBy { name(it) },
).take(limit)
}
/**
* [text] with the tag at [at] replaced by `#name`, and where the caret goes after it.
* A space follows unless one is already there, so typing simply continues.
*/
fun insertTag(
text: String,
at: TagQuery,
name: String,
): Pair<String, Int> {
val after = text.substring(at.end)
val insertion = "#$name" + if (after.firstOrNull()?.isWhitespace() == true) "" else " "
return (text.substring(0, at.start) + insertion + after) to (at.start + insertion.length)
}
private const val SUGGESTION_LIMIT = 8
@@ -4,10 +4,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.fabledsword.inkwell.core.Inkwell import com.fabledsword.inkwell.core.Inkwell
import com.fabledsword.inkwell.core.Label import com.fabledsword.inkwell.core.Label
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -163,11 +160,4 @@ class TagsViewModel(
onStoreChanged() onStoreChanged()
} }
} }
companion object {
fun factory(
core: Inkwell,
onStoreChanged: () -> Unit,
): ViewModelProvider.Factory = viewModelFactory { initializer { TagsViewModel(core, onStoreChanged) } }
}
} }
@@ -5,10 +5,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.fabledsword.inkwell.AppUpdate import com.fabledsword.inkwell.AppUpdate
import com.fabledsword.inkwell.UpdateOutcome import com.fabledsword.inkwell.UpdateOutcome
import com.fabledsword.inkwell.core.ClientUpdate import com.fabledsword.inkwell.core.ClientUpdate
@@ -214,14 +211,6 @@ class UpdateViewModel(
fun dismissError() { fun dismissError() {
state = state.copy(error = null) state = state.copy(error = null)
} }
companion object {
fun factory(
core: Inkwell,
context: Context,
): ViewModelProvider.Factory =
viewModelFactory { initializer { UpdateViewModel(core, context.applicationContext) } }
}
} }
private const val FALLBACK = "The update couldn't be checked." private const val FALLBACK = "The update couldn't be checked."
@@ -27,6 +27,7 @@
<!-- Board --> <!-- Board -->
<string name="board_empty_note">Empty note</string> <string name="board_empty_note">Empty note</string>
<string name="card_archived">Archived</string>
<!-- The long-press menu. Its ITEMS are the editor_* strings, deliberately: a <!-- The long-press menu. Its ITEMS are the editor_* strings, deliberately: a
note has one vocabulary of things you can do to it, and a board that said note has one vocabulary of things you can do to it, and a board that said
@@ -0,0 +1,79 @@
package com.fabledsword.inkwell.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Test
/** The same cases as `frontend/src/notes/tags.test.ts`. */
class TagSuggestTest {
private data class Tag(
val name: String,
val count: Long,
)
private val tags =
listOf(
Tag("grocery", 3),
Tag("groceries", 9),
Tag("hungry", 1),
Tag("to do", 50),
Tag("Café", 2),
)
private fun suggest(query: String) = suggestTags(tags, query, { it.name }, { it.count }).map { it.name }
@Test
fun `the tag being typed is found at the caret, with what has been typed so far`() {
assertEquals(TagQuery(start = 9, end = 13, query = "gro"), tagQueryAt("buy milk #gro", 13))
}
@Test
fun `a bare hash counts at the start or after a space`() {
assertEquals(TagQuery(0, 1, ""), tagQueryAt("#", 1))
assertEquals(TagQuery(5, 6, ""), tagQueryAt("milk #", 6))
}
@Test
fun `the tag runs on past the caret to the end of the word`() {
assertEquals(TagQuery(0, 8, "gr"), tagQueryAt("#grocery list", 3))
}
@Test
fun `it is not a tag where the grammar says it is not`() {
assertNull(tagQueryAt("a#b", 3)) // no space before the #
assertNull(tagQueryAt("#2024", 5)) // starts with a digit
assertNull(tagQueryAt("##x", 3))
assertNull(tagQueryAt("# heading", 9)) // a space ends it
assertNull(tagQueryAt("plain words", 5))
}
@Test
fun `names that start with the query come first, busiest first`() {
assertEquals(listOf("groceries", "grocery", "hungry"), suggest("gr"))
}
@Test
fun `matching ignores case`() {
assertEquals(listOf("Café"), suggest("CAF"))
}
@Test
fun `a tag already typed in full, and names the body can't hold, are left out`() {
assertEquals(emptyList<String>(), suggest("grocery"))
assertFalse("to do" in suggest(""))
}
@Test
fun `a picked tag replaces the whole token and leaves the caret after a space`() {
val text = "buy #gr milk"
val at = tagQueryAt(text, 7)!!
assertEquals("buy #groceries milk" to 14, insertTag(text, at, "groceries"))
}
@Test
fun `a picked tag at the end of the text gets a space after it`() {
val at = tagQueryAt("#gr", 3)!!
assertEquals("#grocery " to 9, insertTag("#gr", at, "grocery"))
}
}
+9
View File
@@ -355,6 +355,9 @@ pub fn list_notes(conn: &Connection, q: &ListQuery) -> rusqlite::Result<Vec<Note
// without turning up in their Trash, where they could do nothing with it. // without turning up in their Trash, where they could do nothing with it.
"trash" => "trashed = 1 AND permission = 'owner'", "trash" => "trashed = 1 AND permission = 'owner'",
"archived" => "trashed = 0 AND archived = 1", "archived" => "trashed = 0 AND archived = 1",
// The board and the Archive together: what a search or a tag looks through,
// so finished work stays findable after it has been put away.
"all" => "trashed = 0",
_ => "trashed = 0 AND archived = 0", _ => "trashed = 0 AND archived = 0",
}); });
@@ -1495,6 +1498,12 @@ mod tests {
ids(&list(&conn, json!({"view": "trash"}))), ids(&list(&conn, json!({"view": "trash"}))),
vec![trashed.id.as_str()] vec![trashed.id.as_str()]
); );
let everything = list(&conn, json!({"view": "all"}));
let mut all = ids(&everything);
all.sort();
let mut expected = vec![kept.id.as_str(), archived.id.as_str()];
expected.sort();
assert_eq!(all, expected);
} }
#[test] #[test]
@@ -109,6 +109,11 @@ chmod +x "$APPIMAGETOOL"
echo "==> Repackaging AppImage (overwriting original)" echo "==> Repackaging AppImage (overwriting original)"
rm -f "$APPIMAGE" rm -f "$APPIMAGE"
# appimagetool refuses a tree it can't be sure everyone can read and run: the
# AppImage runs as whichever user launches it, and extraction keeps the build's
# restrictive modes.
chmod -R a+rX "$WORK/squashfs-root"
chmod a+rx "$WORK/squashfs-root/AppRun"
# APPIMAGE_EXTRACT_AND_RUN lets appimagetool (itself an AppImage) run without # APPIMAGE_EXTRACT_AND_RUN lets appimagetool (itself an AppImage) run without
# FUSE in the CI container; ARCH is required by the embedded runtime. # FUSE in the CI container; ARCH is required by the embedded runtime.
export APPIMAGE_EXTRACT_AND_RUN=1 export APPIMAGE_EXTRACT_AND_RUN=1
+4 -1
View File
@@ -60,7 +60,10 @@ traverses, so the rightmost entries are the ones your own infrastructure wrote a
anything a caller forged sits to the left of them. Counting in from the right by the anything a caller forged sits to the left of them. Counting in from the right by the
number of proxies you actually run means a forged prefix can never be selected. Set it number of proxies you actually run means a forged prefix can never be selected. Set it
too HIGH and it starts trusting entries no proxy of yours wrote; too low and several too HIGH and it starts trusting entries no proxy of yours wrote; too low and several
callers share one rate-limit bucket, which is merely inconvenient. callers share one rate-limit bucket, which is merely inconvenient. A request that
passed fewer proxies than the count — a LAN visitor reaching your proxy directly while
it is set to `2` for the CDN — is read from the header's leftmost entry, which your
first proxy wrote.
**4. Stop reaching the app except through the proxy.** The default compose binds **4. Stop reaching the app except through the proxy.** The default compose binds
`0.0.0.0:5000` so LAN clients can reach it directly — which is right for a LAN install `0.0.0.0:5000` so LAN clients can reach it directly — which is right for a LAN install
+16 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from "vue"; import { computed, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useNotesStore } from "../stores/notes"; import { useNotesStore } from "../stores/notes";
import { NOTE_CARD_SURFACE, labelChipClasses } from "../notes/colors"; import { NOTE_CARD_SURFACE, labelChipClasses } from "../notes/colors";
import { rendersInline } from "../notes/attachments"; import { rendersInline } from "../notes/attachments";
@@ -52,6 +53,12 @@ const sharedLine = computed(() => {
return props.note.shared ? "Shared" : ""; return props.note.shared ? "Shared" : "";
}); });
// A search, a tag or the Timeline reaches into the Archive, so an archived card met
// anywhere but the Archive itself says so: put away, not current. Read off the route,
// since a page with its own list (Timeline) never sets the notes store's view.
const route = useRoute();
const showArchived = computed(() => props.note.archived && !props.note.trashed && route.name !== "archive");
// --- Retention countdown, so someone browsing Trash can restore a note in time. // --- Retention countdown, so someone browsing Trash can restore a note in time.
// Null when not trashed or retention is off. --- // Null when not trashed or retention is off. ---
const trashDays = computed(() => const trashDays = computed(() =>
@@ -199,7 +206,7 @@ const tagColors = computed<Record<string, string>>(() => {
<template> <template>
<div <div
ref="root" ref="root"
class="group relative mb-2 break-inside-avoid sm:mb-4 rounded-xl border border-[#b8b8b8] p-3 shadow-sm transition hover:shadow-md dark:border-[#404040]" class="group relative rounded-xl border border-[#b8b8b8] p-3 shadow-sm transition hover:shadow-md dark:border-[#404040]"
:class="[ :class="[
NOTE_CARD_SURFACE, NOTE_CARD_SURFACE,
dragging ? 'opacity-40' : '', dragging ? 'opacity-40' : '',
@@ -217,6 +224,14 @@ const tagColors = computed<Record<string, string>>(() => {
<!-- Tags first: a board is scanned, and tags say what a note is about. Above the <!-- Tags first: a board is scanned, and tags say what a note is about. Above the
body rather than beside it, so they don't compete with its first line, the body rather than beside it, so they don't compete with its first line, the
note's name. --> note's name. -->
<div v-if="showArchived" class="mb-2">
<span
class="inline-flex items-center gap-1 rounded-full bg-black/5 px-2 py-0.5 text-xs font-medium text-neutral-600 dark:bg-white/10 dark:text-neutral-300"
>
<Icon name="archive" class="!h-3 !w-3" />
Archived
</span>
</div>
<div v-if="chipLabels.length" class="mb-2 flex flex-wrap gap-1"> <div v-if="chipLabels.length" class="mb-2 flex flex-wrap gap-1">
<!-- Every chip carries the `#`, so a lifted chip reads as the `#todo` somebody <!-- Every chip carries the `#`, so a lifted chip reads as the `#todo` somebody
typed, as on Android. --> typed, as on Android. -->
+9 -3
View File
@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import NoteCard from "./NoteCard.vue"; import NoteCard from "./NoteCard.vue";
import { useMasonry } from "../composables/useMasonry";
import type { Note } from "../stores/notes"; import type { Note } from "../stores/notes";
/** /**
@@ -9,7 +10,7 @@ import type { Note } from "../stores/notes";
* `activeId` rather than an index, because the board splits its notes across two * `activeId` rather than an index, because the board splits its notes across two
* grids. * grids.
*/ */
defineProps<{ const props = defineProps<{
notes: Note[]; notes: Note[];
/** The keyboard-focused note, if any. */ /** The keyboard-focused note, if any. */
activeId?: string | null; activeId?: string | null;
@@ -24,22 +25,27 @@ defineEmits<{
(e: "drop", targetId: string): void; (e: "drop", targetId: string): void;
(e: "reminder-changed"): void; (e: "reminder-changed"): void;
}>(); }>();
const { grid, gridStyle, cardStyle } = useMasonry(() => props.notes.map((n) => n.id));
</script> </script>
<template> <template>
<!-- `board` is the transition name defined in style.css; `appear` covers first <!-- `board` is the transition name defined in style.css; `appear` covers first
paint so a lens arrives eased rather than snapping in. paint so a lens arrives eased rather than snapping in.
Two columns even on a phone, as on Android, with a tighter gap there. Two columns even on a phone, as on Android, with a tighter gap there.
NoteCard's bottom margin is the vertical half of this gap. --> useMasonry reads the column count and the gap back from these classes. -->
<TransitionGroup <TransitionGroup
ref="grid"
tag="div" tag="div"
name="board" name="board"
appear appear
class="columns-2 gap-2 sm:gap-4 lg:columns-3 xl:columns-4" class="relative [--board-columns:2] [--board-gap:0.5rem] [column-gap:var(--board-gap)] sm:[--board-gap:1rem] lg:[--board-columns:3] xl:[--board-columns:4]"
:style="gridStyle"
> >
<NoteCard <NoteCard
v-for="n in notes" v-for="n in notes"
:key="n.id" :key="n.id"
:style="cardStyle(n.id)"
:note="n" :note="n"
:active="activeId === n.id" :active="activeId === n.id"
:reorderable="reorderable" :reorderable="reorderable"
+2 -2
View File
@@ -25,8 +25,8 @@ export function endCardDrag(): void {
/** /**
* The id of the card under this point, ignoring `self`. * The id of the card under this point, ignoring `self`.
* *
* Reads the DOM rather than tracking geometry: in a CSS masonry (`columns-*`) the * Reads the DOM rather than tracking geometry: in a masonry the visual order isn't
* visual order isn't derivable from the model order. * derivable from the model order.
*/ */
export function cardIdAt(x: number, y: number, self: string): string | null { export function cardIdAt(x: number, y: number, self: string): string | null {
const el = document.elementFromPoint(x, y)?.closest<HTMLElement>("[data-note-id]"); const el = document.elementFromPoint(x, y)?.closest<HTMLElement>("[data-note-id]");
+91
View File
@@ -0,0 +1,91 @@
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from "vue";
import type { ComponentPublicInstance } from "vue";
import { placeCards } from "../notes/masonry";
import type { CardSlot } from "../notes/masonry";
/** A slot as inline style. The column count and gap stay in CSS, on the grid's own
* classes, so a card has the right width before anything has been measured. */
function slotStyle(slot: CardSlot | undefined): Record<string, string> {
return {
position: "absolute",
top: `${slot?.top ?? 0}px`,
left: `calc(${slot?.column ?? 0} * (100% + var(--board-gap)) / var(--board-columns))`,
width: "calc((100% - (var(--board-columns) - 1) * var(--board-gap)) / var(--board-columns))",
};
}
/**
* Lays out a NoteGrid: measures its cards and places each one with `placeCards`.
*
* `grid` is the template ref for the TransitionGroup. Its cards are found by
* `data-note-id`, which NoteCard sets on its root.
*/
export function useMasonry(ids: () => string[]) {
const grid = ref<ComponentPublicInstance | null>(null);
const heights = shallowRef<ReadonlyMap<string, number>>(new Map());
const columns = ref(1);
const gap = ref(0);
const layout = computed(() => placeCards(ids(), heights.value, columns.value, gap.value));
const gridStyle = computed(() => ({ height: `${layout.value.height}px` }));
const cardStyle = (id: string) => slotStyle(layout.value.slots.get(id));
const gridEl = () => (grid.value?.$el ?? null) as HTMLElement | null;
const cardEls = () => [...(gridEl()?.querySelectorAll<HTMLElement>(":scope > [data-note-id]") ?? [])];
function readTracks(): void {
const el = gridEl();
if (!el) return;
const style = getComputedStyle(el);
columns.value = parseInt(style.getPropertyValue("--board-columns"), 10) || 1;
gap.value = parseFloat(style.columnGap) || 0;
}
function measure(): void {
const cards = cardEls();
const wanted = new Set(ids());
const next = new Map<string, number>();
for (const card of cards) {
const id = card.dataset.noteId as string;
// A card on its way out is still in the DOM, and no longer takes up room.
if (wanted.has(id)) next.set(id, card.offsetHeight);
}
const same = next.size === heights.value.size && [...next].every(([id, h]) => heights.value.get(id) === h);
if (same) return;
// A card seen for the first time goes straight to its place. Left to the next
// render, TransitionGroup would see it move there from the top of the board and
// fly it across.
const { slots } = placeCards(ids(), next, columns.value, gap.value);
for (const card of cards) {
const id = card.dataset.noteId as string;
if (wanted.has(id) && !heights.value.has(id)) Object.assign(card.style, slotStyle(slots.get(id)));
}
heights.value = next;
}
// Height follows content that has no event of its own: an edit, an image loading,
// a width change rewrapping the text.
const cardObserver = new ResizeObserver(measure);
const gridObserver = new ResizeObserver(readTracks);
function observeCards(): void {
cardObserver.disconnect();
for (const card of cardEls()) cardObserver.observe(card);
measure();
}
onMounted(() => {
const el = gridEl();
if (el) gridObserver.observe(el);
readTracks();
observeCards();
});
watch(() => ids().join("\n"), observeCards, { flush: "post" });
onBeforeUnmount(() => {
cardObserver.disconnect();
gridObserver.disconnect();
});
return { grid, gridStyle, cardStyle };
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { placeCards } from "./masonry";
const heights = (entries: Record<string, number>) => new Map(Object.entries(entries));
describe("placing cards on the board", () => {
it("uses every column before stacking", () => {
const { slots } = placeCards(["a", "b", "c", "d"], heights({ a: 100, b: 100, c: 100, d: 100 }), 4, 16);
expect([...slots.values()].map((s) => s.column)).toEqual([0, 1, 2, 3]);
});
it("puts the next card under the shortest column, with the gap above it", () => {
const { slots } = placeCards(["a", "b", "c"], heights({ a: 300, b: 50, c: 80 }), 2, 16);
expect(slots.get("c")).toEqual({ column: 1, top: 66 });
});
it("takes the leftmost column on a tie", () => {
const { slots } = placeCards(["a", "b", "c"], heights({ a: 100, b: 100, c: 10 }), 2, 16);
expect(slots.get("c")).toEqual({ column: 0, top: 116 });
});
it("reports the tallest column as the board's height", () => {
const { height } = placeCards(["a", "b", "c"], heights({ a: 300, b: 50, c: 80 }), 2, 16);
expect(height).toBe(316);
});
it("counts an unmeasured card as zero tall", () => {
const { slots } = placeCards(["a", "b"], heights({ b: 100 }), 1, 16);
expect(slots.get("b")).toEqual({ column: 0, top: 16 });
});
it("is an empty board with no cards", () => {
const { slots, height } = placeCards([], new Map(), 4, 16);
expect(slots.size).toBe(0);
expect(height).toBe(0);
});
});
+33
View File
@@ -0,0 +1,33 @@
/** Where one card sits on the board. */
export interface CardSlot {
column: number;
top: number;
}
export interface BoardLayout {
slots: Map<string, CardSlot>;
/** The tallest column, so the board can reserve its own height. */
height: number;
}
/**
* Places cards in board order, each into the column that is currently shortest and
* the leftmost of any tie. The same notes at the same width always land the same way.
*
* A card with no measured height yet counts as zero.
*/
export function placeCards(
ids: string[],
heights: ReadonlyMap<string, number>,
columns: number,
gap: number,
): BoardLayout {
const bottoms = new Array<number>(Math.max(columns, 1)).fill(0);
const slots = new Map<string, CardSlot>();
for (const id of ids) {
const column = bottoms.indexOf(Math.min(...bottoms));
slots.set(id, { column, top: bottoms[column] });
bottoms[column] += (heights.get(id) ?? 0) + gap;
}
return { slots, height: Math.max(...bottoms) };
}
+10 -2
View File
@@ -3,7 +3,9 @@ import { ref } from "vue";
import { repo } from "../adapters"; import { repo } from "../adapters";
import { useUiStore } from "./ui"; import { useUiStore } from "./ui";
export type NoteView = "active" | "archived" | "trash"; // `all` is the board and the Archive together: what a search or a tag looks through,
// so finished work stays findable after it has been put away. Never Trash.
export type NoteView = "active" | "archived" | "trash" | "all";
// Combinable facet filters for the board (mirrors the GET /api/notes query). All // Combinable facet filters for the board (mirrors the GET /api/notes query). All
// optional; empty = the plain, unfiltered board. The date bounds are Timeline's. // optional; empty = the plain, unfiltered board. The date bounds are Timeline's.
export interface NoteFacets { export interface NoteFacets {
@@ -118,7 +120,13 @@ export const useNotesStore = defineStore("notes", () => {
function belongsHere(n: Note): boolean { function belongsHere(n: Note): boolean {
const v = view.value; const v = view.value;
const inView = const inView =
v === "trash" ? n.trashed : v === "archived" ? !n.trashed && n.archived : !n.trashed && !n.archived; v === "trash"
? n.trashed
: v === "archived"
? !n.trashed && n.archived
: v === "all"
? !n.trashed
: !n.trashed && !n.archived;
if (!inView) return false; if (!inView) return false;
if (activeFacets.value.shared === "with_me" && (n.permission ?? "owner") === "owner") return false; if (activeFacets.value.shared === "with_me" && (n.permission ?? "owner") === "owner") return false;
if (activeLabel.value) return n.labels.some((lb) => lb.id === activeLabel.value); if (activeLabel.value) return n.labels.some((lb) => lb.id === activeLabel.value);
+2 -4
View File
@@ -131,10 +131,8 @@ body {
* Vue's TransitionGroup does the FLIP itself; this supplies only the curve, fast and * Vue's TransitionGroup does the FLIP itself; this supplies only the curve, fast and
* small, so a card reads as having MOVED rather than performed. * small, so a card reads as having MOVED rather than performed.
* *
* Leavers are NOT taken out of flow with `position: absolute`, the usual trick: this * Cards are absolutely placed (useMasonry), so a leaver fades where it stands while
* masonry is CSS multi-column, and an absolutely positioned child escapes its column * the others move up. The leave is the shortest of the three.
* to the container's origin. Staying in flow costs a small settle on removal, so the
* leave is the shortest of the three.
* *
* Reduced motion needs no case here: the global guard above collapses every duration. */ * Reduced motion needs no case here: the global guard above collapses every duration. */
.board-move { .board-move {
+14 -9
View File
@@ -53,20 +53,25 @@ async function openFromQuery(id: string) {
void router.replace({ query: q }); void router.replace({ query: q });
} }
function viewForRoute(name: unknown): NoteView {
if (name === "archive") return "archived";
if (name === "trash") return "trash";
return "active"; // board + label views
}
const currentView = computed<NoteView>(() => viewForRoute(route.name));
const currentLabel = computed<string | null>(() => (route.name === "label" ? String(route.params.id) : null));
// Facet filters live in the URL query on the board route (a filtered board = a lens). // Facet filters live in the URL query on the board route (a filtered board = a lens).
const facets = computed(() => facetsFromQuery(route.query)); const facets = computed(() => facetsFromQuery(route.query));
const facetKey = computed(() => JSON.stringify(facetsToQuery(facets.value))); // stable; ignores ?open= const facetKey = computed(() => JSON.stringify(facetsToQuery(facets.value))); // stable; ignores ?open=
const filtered = computed(() => route.name === "board" && facetCount(facets.value) > 0); const filtered = computed(() => route.name === "board" && facetCount(facets.value) > 0);
// A search or a tag looks through the Archive as well as the board, so finished work
// can still be looked up; each archived card says so. Archive and Trash keep a search
// inside themselves.
function viewForRoute(name: unknown): NoteView {
if (name === "archive") return "archived";
if (name === "trash") return "trash";
if (name === "label") return "all";
const f = facets.value;
return name === "board" && (f.q || f.label?.length) ? "all" : "active";
}
const currentView = computed<NoteView>(() => viewForRoute(route.name));
const currentLabel = computed<string | null>(() => (route.name === "label" ? String(route.params.id) : null));
// Quick-add + pinned/others split only on the main board (not archive/trash/label). // Quick-add + pinned/others split only on the main board (not archive/trash/label).
const isMainBoard = computed(() => route.name === "board"); const isMainBoard = computed(() => route.name === "board");
const pinnedNotes = computed(() => notes.items.filter((n) => n.pinned)); const pinnedNotes = computed(() => notes.items.filter((n) => n.pinned));
+3 -2
View File
@@ -13,7 +13,8 @@ import NoteEditor from "../components/NoteEditor.vue";
// The "find by WHEN" recall lens: your notes grouped by when you captured them, // The "find by WHEN" recall lens: your notes grouped by when you captured them,
// newest first, with an optional date range. A distinct recall axis from search / // newest first, with an optional date range. A distinct recall axis from search /
// labels — memory is often temporal even when the content is fuzzy. // labels — memory is often temporal even when the content is fuzzy. Archived notes
// are included (each card says so), since finished work is what gets looked back on.
// Optional local date-range filter (YYYY-MM-DD from <input type="date">). // Optional local date-range filter (YYYY-MM-DD from <input type="date">).
const fromDate = ref(""); const fromDate = ref("");
@@ -24,7 +25,7 @@ function buildQuery(): NoteListQuery {
const from = parseLocalDate(fromDate.value); const from = parseLocalDate(fromDate.value);
const to = parseLocalDate(toDate.value); const to = parseLocalDate(toDate.value);
return { return {
view: "active", view: "all",
sort: "created", sort: "created",
facets: { facets: {
created_after: from ? from.toISOString() : undefined, created_after: from ? from.toISOString() : undefined,
+8 -3
View File
@@ -25,7 +25,7 @@ logger = logging.getLogger(__name__)
ALLOWED_IMAGE_MIMES = {"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"} ALLOWED_IMAGE_MIMES = {"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"}
VALID_FILTERS = {"active", "archived", "trash"} VALID_FILTERS = {"active", "archived", "trash", "all"}
DISPLAY_TITLE_CAP = 200 DISPLAY_TITLE_CAP = 200
@@ -72,9 +72,14 @@ def apply_filter(stmt, filter_name: str, archived):
Every branch excludes purge tombstones — content-less rows kept only so the sync Every branch excludes purge tombstones — content-less rows kept only so the sync
feed can tell offline clients a note is gone (see `retention.purge_note`). The feed can tell offline clients a note is gone (see `retention.purge_note`). The
active/archived branches get that for free from `deleted_at IS NULL`, since a active/archived/all branches get that for free from `deleted_at IS NULL`, since
tombstone keeps the timestamp; Trash is the one view that has to say so. a tombstone keeps the timestamp; Trash is the one view that has to say so.
`all` is the board and the Archive together: what a search or a tag looks
through, so finished work stays findable after it has been put away.
""" """
if filter_name == "all":
return stmt.where(Note.deleted_at.is_(None))
if filter_name == "archived": if filter_name == "archived":
return stmt.where(Note.deleted_at.is_(None), archived.is_(True)) return stmt.where(Note.deleted_at.is_(None), archived.is_(True))
if filter_name == "trash": if filter_name == "trash":
+8 -4
View File
@@ -9,7 +9,10 @@ right by the **Trusted proxy hops** setting (default 1), and a forged prefix is
selected. selected.
Too high a count is the dangerous direction: it believes entries no proxy of ours Too high a count is the dangerous direction: it believes entries no proxy of ours
wrote. When the header is shorter than configured, the socket address is used. wrote. A header shorter than the count is read from its leftmost entry: the request
passed fewer proxies (a LAN visitor straight to the reverse proxy, behind a count set
for the CDN road), and a caller's own entries could only have made it longer. That
holds while the first proxy drops a forwarding header from a client it doesn't trust.
""" """
from __future__ import annotations from __future__ import annotations
@@ -19,16 +22,17 @@ from .settings import live
def trusted_entry(header: str, hops: int) -> str | None: def trusted_entry(header: str, hops: int) -> str | None:
"""The nth-from-the-right entry of a forwarding header, or None if there isn't one. """The nth-from-the-right entry of a forwarding header, its leftmost if it is
shorter than that, or None when no proxy is trusted or there is no header.
Pure, so the trust boundary is testable without a request context. Pure, so the trust boundary is testable without a request context.
""" """
if hops <= 0: if hops <= 0:
return None return None
entries = [part.strip() for part in header.split(",") if part.strip()] entries = [part.strip() for part in header.split(",") if part.strip()]
if len(entries) < hops: if not entries:
return None return None
return entries[-hops] return entries[-min(hops, len(entries))]
def forwarded_for(header: str, remote_addr: str | None, hops: int) -> str: def forwarded_for(header: str, remote_addr: str | None, hops: int) -> str:
+24 -2
View File
@@ -19,6 +19,7 @@ from datetime import datetime, timezone
from quart import Blueprint, g, jsonify, request from quart import Blueprint, g, jsonify, request
from sqlalchemy import select from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from .auth import login_required from .auth import login_required
from .colors import normalize_color from .colors import normalize_color
@@ -446,6 +447,27 @@ async def _apply_child_delete(db, ch: dict, removed_files: list[str]) -> dict:
return _result(str(child_id), entity, "applied") return _result(str(child_id), entity, "applied")
async def _apply_raced(db, apply, previews: list[tuple[uuid.UUID, str]]) -> dict:
"""Apply one note or label change in a savepoint, and once more if its insert lost
a race.
Two devices can push the same new note or tag at the same moment, or one device
can retry a push whose reply it never got. Both requests look the id up, find
nothing, and insert, and the slower insert hits the primary key (or a live tag's
name). Rolling back to the savepoint drops only that one change, along with any
link previews it queued. Applying it again finds the row the other push committed,
so the change goes through the usual last-write-wins path instead of failing the
whole batch with a 500.
"""
queued = len(previews)
try:
async with db.begin_nested():
return await apply()
except IntegrityError:
del previews[queued:]
return await apply()
@bp.post("/push") @bp.post("/push")
@login_required @login_required
async def push(): async def push():
@@ -468,9 +490,9 @@ async def push():
continue continue
entity = ch.get("entity") entity = ch.get("entity")
if entity == "note": if entity == "note":
results.append(await _apply_note(db, ch, previews)) results.append(await _apply_raced(db, lambda: _apply_note(db, ch, previews), previews))
elif entity == "label": elif entity == "label":
results.append(await _apply_label(db, ch)) results.append(await _apply_raced(db, lambda: _apply_label(db, ch), previews))
elif entity in _CHILD_ENTITIES: elif entity in _CHILD_ENTITIES:
results.append(await _apply_child_delete(db, ch, removed_files)) results.append(await _apply_child_delete(db, ch, removed_files))
else: else:
+7
View File
@@ -1,5 +1,6 @@
import pytest import pytest
from inkwell.app import create_app
from inkwell.config import Config from inkwell.config import Config
@@ -10,3 +11,9 @@ def _isolated_data_dir(tmp_path, monkeypatch):
signing key from env-or-random, not a file), but this stays defensive.""" signing key from env-or-random, not a file), but this stays defensive."""
monkeypatch.setattr(Config, "DATA_DIR", str(tmp_path / "data")) monkeypatch.setattr(Config, "DATA_DIR", str(tmp_path / "data"))
yield yield
@pytest.fixture
def app():
"""A fresh app for a test that drives routes through `app.test_client()`."""
return create_app()
-10
View File
@@ -1,13 +1,3 @@
import pytest
from inkwell.app import create_app
@pytest.fixture
def app():
return create_app()
async def test_settings_requires_auth(app): async def test_settings_requires_auth(app):
# require_admin returns 401 before any DB access when unauthenticated. # require_admin returns 401 before any DB access when unauthenticated.
client = app.test_client() client = app.test_client()
-7
View File
@@ -1,13 +1,6 @@
import pytest
from inkwell.app import create_app from inkwell.app import create_app
@pytest.fixture
def app():
return create_app()
async def test_health_ok(app): async def test_health_ok(app):
client = app.test_client() client = app.test_client()
resp = await client.get("/api/health") resp = await client.get("/api/health")
-6
View File
@@ -4,7 +4,6 @@ from pathlib import Path
import pytest import pytest
from inkwell import client_dist from inkwell import client_dist
from inkwell.app import create_app
from inkwell.client_dist import ( from inkwell.client_dist import (
BY_ID, BY_ID,
PLATFORMS, PLATFORMS,
@@ -54,11 +53,6 @@ def _empty_baked_client(tmp_path, monkeypatch):
yield yield
@pytest.fixture
def app():
return create_app()
def place( def place(
platform_id: str = "android", platform_id: str = "android",
payload: bytes = PAYLOAD, payload: bytes = PAYLOAD,
-10
View File
@@ -1,13 +1,3 @@
import pytest
from inkwell.app import create_app
@pytest.fixture
def app():
return create_app()
async def test_create_device_requires_auth(app): async def test_create_device_requires_auth(app):
# No session cookie and no bearer header → 401 before any DB access. # No session cookie and no bearer header → 401 before any DB access.
client = app.test_client() client = app.test_client()
-6
View File
@@ -1,7 +1,6 @@
import pytest import pytest
from inkwell import installer, settings from inkwell import installer, settings
from inkwell.app import create_app
from inkwell.installer import PLACEHOLDER, SOURCE_SCRIPT, render, server_address from inkwell.installer import PLACEHOLDER, SOURCE_SCRIPT, render, server_address
# DB-free, like test_client_dist: the route reads `public_url` from the live cache # DB-free, like test_client_dist: the route reads `public_url` from the live cache
@@ -17,11 +16,6 @@ def _defaults():
settings.reset_live() settings.reset_live()
@pytest.fixture
def app():
return create_app()
def test_the_published_script_carries_the_line_the_server_rewrites_exactly_once(): def test_the_published_script_carries_the_line_the_server_rewrites_exactly_once():
"""The forge-served script and the server-served one are the same file; this is """The forge-served script and the server-served one are the same file; this is
the one line that differs. Edit it and the server stops serving rather than the one line that differs. Edit it and the server stops serving rather than
+65 -1
View File
@@ -29,7 +29,7 @@ from inkwell.models.invite import Invite
from inkwell.models.password_reset import PasswordReset from inkwell.models.password_reset import PasswordReset
from inkwell.models.settings import Setting from inkwell.models.settings import Setting
from inkwell.models.share import Share from inkwell.models.share import Share
from inkwell.models.label import NoteLabel from inkwell.models.label import Label, NoteLabel
from inkwell.models.note import Note from inkwell.models.note import Note
from inkwell.models.note_attachment import NoteAttachment from inkwell.models.note_attachment import NoteAttachment
from inkwell.models.user import User from inkwell.models.user import User
@@ -805,6 +805,54 @@ async def test_a_pushed_edit_keeps_the_clients_edit_time_when_a_tag_is_lifted(ap
assert datetime.fromisoformat(note["updated_at"]) == datetime(2026, 1, 1, tzinfo=timezone.utc) assert datetime.fromisoformat(note["updated_at"]) == datetime(2026, 1, 1, tzinfo=timezone.utc)
@pytest.mark.parametrize("entity", ["label", "note"])
async def test_a_push_that_loses_a_create_race_applies_the_change_instead_of_failing(app_client, db, entity):
"""Two devices push the same new tag or note at once. The other push's row is
held here, inserted but not committed, so this push finds no row, inserts, and
waits on it. Once it commits, this push's insert fails on the primary key. That
change has to be applied to the stored row, not fail the batch with a 500."""
await _signed_in(app_client, f"race-{entity}")
owner_id = await db.scalar(select(User.id).where(User.email == f"race-{entity}@example.test"))
rid = uuid.uuid4()
first = datetime(2026, 1, 1, tzinfo=timezone.utc)
if entity == "label":
theirs = Label(id=rid, owner_id=owner_id, name="groceries", updated_at=first)
change = {"name": "groceries", "color": "teal"}
else:
theirs = Note(id=rid, owner_id=owner_id, body="pushed first", display_title="pushed first", updated_at=first)
change = {"body": "pushed second", "created_at": "2026-01-01T00:00:00Z"}
change |= {"entity": entity, "id": str(rid), "op": "upsert", "edited_at": "2026-01-02T00:00:00Z"}
async with session_scope() as other:
other.add(theirs)
await other.flush()
push = asyncio.create_task(app_client.post("/api/sync/push", json={"changes": [change]}))
# Commit only once the push's insert is blocked on that row. Committing
# earlier would let it find the row and never race at all. A fresh session per
# look: pg_stat_activity is read once per transaction and then held.
for _ in range(100):
async with session_scope() as probe:
waiting = await probe.scalar(text(
"SELECT count(*) FROM pg_stat_activity"
" WHERE datname = current_database() AND wait_event_type = 'Lock'"
))
if waiting or push.done():
break
await asyncio.sleep(0.1)
assert waiting and not push.done(), "the push should be waiting on the other push's uncommitted row"
await other.commit()
resp = await asyncio.wait_for(push, timeout=10)
assert resp.status_code == 200
assert (await resp.get_json())["results"][0]["status"] == "applied"
model = Label if entity == "label" else Note
stored = await db.scalar(select(model).where(model.id == rid).execution_options(populate_existing=True))
if entity == "label":
assert stored.color == "teal", "the later edit won"
else:
assert stored.body == "pushed second", "the later edit won"
# --- attachments as a sync entity ----------------------------------------------- # --- attachments as a sync entity -----------------------------------------------
@@ -1673,6 +1721,22 @@ async def test_owner_and_recipient_each_pin_archive_and_order_their_own(app_clie
assert await _board_ids(app_client) == [nid, older] assert await _board_ids(app_client) == [nid, older]
async def test_search_and_tags_look_through_the_archive_but_not_the_trash(app_client, db):
await _admin_with_invite(app_client)
kept = await _owners_note(app_client, "ferry times #travel")
archived = await _owners_note(app_client, "ferry booked last summer #travel")
trashed = await _owners_note(app_client, "ferry refund #travel")
await app_client.patch(f"/api/notes/{archived}", json={"archived": True})
await app_client.post(f"/api/notes/{trashed}/trash")
labels = (await (await app_client.get("/api/labels")).get_json())["labels"]
travel = next(lb["id"] for lb in labels if lb["name"] == "travel")
# The board alone still keeps the archive out of the way.
assert await _board_ids(app_client, "q=ferry") == [kept]
assert sorted(await _board_ids(app_client, "filter=all&q=ferry")) == sorted([kept, archived])
assert sorted(await _board_ids(app_client, f"filter=all&label={travel}")) == sorted([kept, archived])
async def test_unsharing_trashing_and_deleting_each_end_access(app_client, db): async def test_unsharing_trashing_and_deleting_each_end_access(app_client, db):
recipient, _, people = await _three_people(app_client) recipient, _, people = await _three_people(app_client)
nid = await _owners_note(app_client) nid = await _owners_note(app_client)
-8
View File
@@ -1,17 +1,9 @@
import uuid import uuid
import pytest
from inkwell.app import create_app
from inkwell.models.label import Label from inkwell.models.label import Label
from inkwell.serialize import serialize_label from inkwell.serialize import serialize_label
@pytest.fixture
def app():
return create_app()
def test_serialize_label_shape(): def test_serialize_label_shape():
# The base {id, name, color} shape the labels API and (S4) sync deltas both build on. # The base {id, name, color} shape the labels API and (S4) sync deltas both build on.
lid = uuid.uuid4() lid = uuid.uuid4()
-6
View File
@@ -5,7 +5,6 @@ from datetime import datetime, timezone
import pytest import pytest
from inkwell.app import create_app
from inkwell.common import coerce_bool, parse_dt from inkwell.common import coerce_bool, parse_dt
from inkwell.colors import NOTE_COLORS from inkwell.colors import NOTE_COLORS
from inkwell.models.note import Note from inkwell.models.note import Note
@@ -34,11 +33,6 @@ from inkwell.notes.recurrence import next_occurrence, normalize_recurrence
from inkwell.notes.tags import parse_tags, split_body_tags from inkwell.notes.tags import parse_tags, split_body_tags
@pytest.fixture
def app():
return create_app()
def test_all_note_routes_registered(app): def test_all_note_routes_registered(app):
# Guards the notes package split: every route handler must still be attached to the # Guards the notes package split: every route handler must still be attached to the
# blueprint. A route whose module isn't imported by notes/__init__ would silently # blueprint. A route whose module isn't imported by notes/__init__ would silently
+12 -4
View File
@@ -41,13 +41,21 @@ def test_two_hops_sees_past_a_cdn():
assert forwarded_for("1.2.3.4, 203.0.113.7, 172.16.0.5", PEER, 2) == "203.0.113.7" assert forwarded_for("1.2.3.4, 203.0.113.7, 172.16.0.5", PEER, 2) == "203.0.113.7"
def test_a_short_header_falls_back_rather_than_reaching_left(): def test_a_short_header_is_read_from_its_leftmost_entry():
# Fewer proxies than configured: the socket address, rather than an entry no # Fewer proxies than configured — a LAN visitor straight to our proxy, behind a
# proxy of ours wrote. # count set for the CDN road. The leftmost entry is what the first proxy wrote; a
assert forwarded_for("203.0.113.7", PEER, 2) == PEER # caller's own entries could only have made the header longer. Falling back to the
# socket address here would file every LAN visitor under the proxy's address.
assert forwarded_for("192.168.0.20", PEER, 2) == "192.168.0.20"
assert forwarded_for("", PEER, 1) == PEER assert forwarded_for("", PEER, 1) == PEER
def test_a_single_https_from_the_cdn_counts_at_two_hops():
# Cloudflare sends one `X-Forwarded-Proto: https` and our proxy passes it on
# without appending, so at hops 2 it is a one-entry header — and still HTTPS.
assert trusted_entry("https", 2) == "https"
def test_malformed_headers_do_not_crash_or_leak_empties(): def test_malformed_headers_do_not_crash_or_leak_empties():
assert forwarded_for(",,,", PEER, 1) == PEER assert forwarded_for(",,,", PEER, 1) == PEER
assert forwarded_for(" , 203.0.113.7 , ", PEER, 1) == "203.0.113.7" assert forwarded_for(" , 203.0.113.7 , ", PEER, 1) == "203.0.113.7"
-6
View File
@@ -10,7 +10,6 @@ import pytest
from inkwell import ratelimit from inkwell import ratelimit
from inkwell.settings import live from inkwell.settings import live
from inkwell.app import create_app
from inkwell.ratelimit import SlidingWindow from inkwell.ratelimit import SlidingWindow
@@ -28,11 +27,6 @@ def _clean_counters():
ratelimit.reset_all() ratelimit.reset_all()
@pytest.fixture
def app():
return create_app()
def test_under_the_limit_is_not_blocked(): def test_under_the_limit_is_not_blocked():
w = window(3, 60) w = window(3, 60)
for i in range(3): for i in range(3):
-8
View File
@@ -4,14 +4,6 @@ Asserted on /api/health because it is the one route that needs no database and n
session — the headers are set in an after_request hook, so any response proves the session — the headers are set in an after_request hook, so any response proves the
hook, and this suite has no Postgres. hook, and this suite has no Postgres.
""" """
import pytest
from inkwell.app import create_app
@pytest.fixture
def app():
return create_app()
async def test_content_security_policy_locks_scripts_to_self(app): async def test_content_security_policy_locks_scripts_to_self(app):
-8
View File
@@ -1,8 +1,5 @@
from datetime import datetime, timezone from datetime import datetime, timezone
import pytest
from inkwell.app import create_app
from inkwell.sync import ( from inkwell.sync import (
DEFAULT_LIMIT, DEFAULT_LIMIT,
MAX_LIMIT, MAX_LIMIT,
@@ -17,11 +14,6 @@ from inkwell.sync import (
) )
@pytest.fixture
def app():
return create_app()
async def test_changes_requires_auth(app): async def test_changes_requires_auth(app):
client = app.test_client() client = app.test_client()
resp = await client.get("/api/sync/changes") resp = await client.get("/api/sync/changes")
-6
View File
@@ -2,15 +2,9 @@ import ipaddress
import pytest import pytest
from inkwell.app import create_app
from inkwell.unfurl import UnfurlError, extract_preview, is_public_ip, validate_url from inkwell.unfurl import UnfurlError, extract_preview, is_public_ip, validate_url
@pytest.fixture
def app():
return create_app()
def test_is_public_ip_blocks_internal_ranges(): def test_is_public_ip_blocks_internal_ranges():
assert is_public_ip(ipaddress.ip_address("8.8.8.8")) assert is_public_ip(ipaddress.ip_address("8.8.8.8"))
assert is_public_ip(ipaddress.ip_address("2606:4700:4700::1111")) assert is_public_ip(ipaddress.ip_address("2606:4700:4700::1111"))