Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: add cross-platform tag picker (#235)

tianma-ife2a77b7c4cc3
diff --git a/apps/ios/EdgeEver/Data/Database/LocalMirrorRepository.swift b/apps/ios/EdgeEver/Data/Database/LocalMirrorRepository.swift
index 75513c8a..b49b30ce 100644
--- a/apps/ios/EdgeEver/Data/Database/LocalMirrorRepository.swift
+++ b/apps/ios/EdgeEver/Data/Database/LocalMirrorRepository.swift
@@ -69,6 +69,32 @@ final class LocalMirrorRepository: @unchecked Sendable {
}
}
+ func listTags(scope: String) throws -> [TagSummary] {
+ try dbQueue.read { db in
+ let rows = try Row.fetchAll(
+ db,
+ sql: "SELECT data_json FROM mobile_memos WHERE scope = ? AND is_deleted = 0",
+ arguments: [scope]
+ )
+ var summaries: [String: (memoCount: Int, updatedAt: String?)] = [:]
+ for row in rows {
+ let raw = row["data_json"] as String
+ guard let memo = try? EdgeEverJSON.decoder.decode(MemoDetail.self, from: Data(raw.utf8)) else { continue }
+ for name in Set(memo.tags.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }).filter({ !$0.isEmpty }) {
+ var summary = summaries[name] ?? (memoCount: 0, updatedAt: nil)
+ summary.memoCount += 1
+ if summary.updatedAt == nil || memo.updatedAt > summary.updatedAt! {
+ summary.updatedAt = memo.updatedAt
+ }
+ summaries[name] = summary
+ }
+ }
+ return summaries
+ .map { TagSummary(name: $0.key, memoCount: $0.value.memoCount, updatedAt: $0.value.updatedAt) }
+ .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
+ }
+ }
+
func listMemos(scope: String, params: LocalMemoListParams) throws -> LocalMemoListResult {
try dbQueue.read { db in
var conditions = ["scope = ?", "is_deleted = ?"]
diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift
index 45ca1033..6f0bc89f 100644
--- a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift
@@ -35,6 +35,7 @@ struct MemoEditView: View {
/// with empty defaults from overwriting a non-empty note via autosave / flush.
/// Snapshot of body when edit opened (or last intentional load). Used to reject empty clobbers.
@State private var showNotebookPicker = false
+ @State private var showTagPicker = false
@State private var showImageSourcePicker = false
@State private var imagePickerRoute: ImagePickerRoute?
@State private var showCameraAccessAlert = false
@@ -144,6 +145,13 @@ struct MemoEditView: View {
}
.presentationDetents([.medium, .large])
}
+ .sheet(isPresented: $showTagPicker) {
+ MemoTagPickerSheet(selectedTags: viewModel.tags) { tags in
+ tagsText = tags.joined(separator: ", ")
+ markDirtyAndScheduleSave()
+ }
+ .presentationDetents([.medium, .large])
+ }
.sheet(isPresented: $showTemplatePicker) {
TemplatePickerSheet { seed in
requestApplyTemplate(seed)
@@ -438,18 +446,25 @@ struct MemoEditView: View {
.accessibilityLabel(env.preferences.t("所在笔记本", en: "Notebook"))
.accessibilityIdentifier(CreateMemoChrome.notebook)
- TextField(
- env.preferences.t("添加标签,用逗号分隔", en: "Add tags, comma separated"),
- text: Binding(
- get: { viewModel.tagsText },
- set: { viewModel.tagsText = $0 }
- )
- )
- .font(.system(size: 15))
- .foregroundStyle(AppTheme.secondary)
- .textFieldStyle(.plain)
- .frame(minHeight: 36)
- .onChange(of: tagsText) { _, _ in markDirtyAndScheduleSave() }
+ Button {
+ showTagPicker = true
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: "tag")
+ .font(.system(size: 13, weight: .semibold))
+ Text(viewModel.tags.isEmpty
+ ? env.preferences.t("添加标签", en: "Add tags")
+ : viewModel.tags.map { "#\($0)" }.joined(separator: ", "))
+ .lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Image(systemName: "chevron.down")
+ .font(.system(size: 11, weight: .semibold))
+ }
+ .font(.system(size: 15))
+ .foregroundStyle(viewModel.tags.isEmpty ? AppTheme.muted : AppTheme.secondary)
+ .frame(minHeight: 36)
+ }
+ .buttonStyle(.plain)
.accessibilityLabel(env.preferences.t("笔记标签", en: "Tags"))
.accessibilityIdentifier(CreateMemoChrome.tags)
@@ -1192,6 +1207,155 @@ struct MemoEditView: View {
}
}
+private struct MemoTagPickerSheet: View {
+ @Environment(AppEnvironment.self) private var env
+ @Environment(\.dismiss) private var dismiss
+ @State private var selection: [String]
+ @State private var query = ""
+ @State private var availableTags: [TagSummary] = []
+ @State private var error: String?
+ let onChange: ([String]) -> Void
+
+ init(selectedTags: [String], onChange: @escaping ([String]) -> Void) {
+ _selection = State(initialValue: selectedTags)
+ self.onChange = onChange
+ }
+
+ private var normalizedQuery: String {
+ query.trimmingCharacters(in: .whitespacesAndNewlines)
+ .replacingOccurrences(of: "^#", with: "", options: .regularExpression)
+ }
+
+ private var visibleTags: [TagSummary] {
+ guard !normalizedQuery.isEmpty else { return availableTags }
+ return availableTags.filter { $0.name.localizedCaseInsensitiveContains(normalizedQuery) }
+ }
+
+ private var hasExactMatch: Bool {
+ availableTags.contains { $0.name.caseInsensitiveCompare(normalizedQuery) == .orderedSame }
+ }
+
+ var body: some View {
+ NavigationStack {
+ VStack(spacing: 12) {
+ if !selection.isEmpty {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 8) {
+ ForEach(selection, id: \.self) { tag in
+ Button {
+ toggle(tag)
+ } label: {
+ HStack(spacing: 4) {
+ Text("#\(tag)")
+ Image(systemName: "xmark")
+ }
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(AppTheme.accent)
+ .padding(.horizontal, 11)
+ .frame(minHeight: 32)
+ .background(AppTheme.accentSoft)
+ .clipShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(env.preferences.t("移除标签 \(tag)", en: "Remove tag \(tag)"))
+ }
+ }
+ .padding(.horizontal, 16)
+ }
+ }
+
+ HStack(spacing: 8) {
+ Image(systemName: "magnifyingglass").foregroundStyle(AppTheme.muted)
+ TextField(env.preferences.t("搜索或输入新标签", en: "Search or enter a new tag"), text: $query)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .onSubmit(createTag)
+ if !normalizedQuery.isEmpty && !hasExactMatch && selection.count < 24 {
+ Button(env.preferences.t("新建", en: "Create"), action: createTag)
+ .font(.system(size: 13, weight: .bold))
+ }
+ }
+ .padding(.horizontal, 12)
+ .frame(minHeight: 42)
+ .background(AppTheme.card)
+ .clipShape(RoundedRectangle(cornerRadius: 9))
+ .overlay(RoundedRectangle(cornerRadius: 9).stroke(AppTheme.border, lineWidth: 1))
+ .padding(.horizontal, 16)
+
+ if let error {
+ Text(error).font(.system(size: 13)).foregroundStyle(AppTheme.danger)
+ }
+
+ List(visibleTags, id: \.name) { tag in
+ Button {
+ toggle(tag.name)
+ } label: {
+ HStack {
+ Image(systemName: selection.contains(tag.name) ? "checkmark.square.fill" : "square")
+ .foregroundStyle(selection.contains(tag.name) ? AppTheme.accent : AppTheme.muted)
+ Text("#\(tag.name)").foregroundStyle(AppTheme.title)
+ Spacer()
+ Text(env.preferences.t("\(tag.memoCount) 条笔记", en: "\(tag.memoCount) notes"))
+ .font(.system(size: 12))
+ .foregroundStyle(AppTheme.muted)
+ }
+ }
+ .buttonStyle(.plain)
+ }
+ .listStyle(.plain)
+ .overlay {
+ if visibleTags.isEmpty {
+ ContentUnavailableView(
+ env.preferences.t("暂无匹配标签", en: "No matching tags"),
+ systemImage: "tag",
+ description: Text(env.preferences.t("可以输入名称创建新标签。", en: "Enter a name to create a new tag."))
+ )
+ }
+ }
+ }
+ .padding(.top, 12)
+ .navigationTitle(env.preferences.t("选择标签", en: "Choose tags"))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ Button(env.preferences.t("完成", en: "Done")) { dismiss() }
+ }
+ }
+ .task { loadTags() }
+ }
+ }
+
+ private func loadTags() {
+ guard let scope = env.session.dataScope else { return }
+ do {
+ availableTags = try env.mirror.listTags(scope: scope)
+ } catch {
+ self.error = error.localizedDescription
+ }
+ }
+
+ private func toggle(_ tag: String) {
+ if let index = selection.firstIndex(of: tag) {
+ selection.remove(at: index)
+ } else if selection.count < 24 {
+ selection.append(tag)
+ }
+ onChange(selection)
+ }
+
+ private func createTag() {
+ let additions = normalizedQuery
+ .split(whereSeparator: { $0 == "," || $0 == "," || $0.isNewline })
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ for tag in additions where selection.count < 24 && !selection.contains(tag) {
+ selection.append(tag)
+ }
+ query = ""
+ onChange(selection)
+ }
+}
+
// MARK: - Compact notebook picker for create/edit
diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift b/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift
index 1f84f9ba..52546774 100644
--- a/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift
@@ -28,10 +28,13 @@ final class MemoEditViewModel {
@ObservationIgnored private var saveTask: Task<Void, Never>?
var tags: [String] {
- tagsText
- .split(whereSeparator: { ",, ".contains($0) })
- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
- .filter { !$0.isEmpty }
+ var seen = Set<String>()
+ return tagsText
+ .split(whereSeparator: { $0 == "," || $0 == "," || $0.isNewline })
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "^#", with: "", options: .regularExpression) }
+ .filter { !$0.isEmpty && seen.insert($0).inserted }
+ .prefix(24)
+ .map { $0 }
}
func markDirty() {
diff --git a/apps/ios/Tests/EdgeEverTests/LocalMirrorTests.swift b/apps/ios/Tests/EdgeEverTests/LocalMirrorTests.swift
index 7b8659b7..28c61c8a 100644
--- a/apps/ios/Tests/EdgeEverTests/LocalMirrorTests.swift
+++ b/apps/ios/Tests/EdgeEverTests/LocalMirrorTests.swift
@@ -41,6 +41,9 @@ final class LocalMirrorTests: XCTestCase {
let listed = try mirror.listMemos(scope: scope, params: .init(q: "world"))
XCTAssertEqual(listed.totalCount, 1)
XCTAssertEqual(listed.memos.first?.title, "Hello")
+
+ let tags = try mirror.listTags(scope: scope)
+ XCTAssertEqual(tags, [TagSummary(name: "a", memoCount: 1, updatedAt: now)])
}
func testOutboxCreateAbsorbsUpdate() throws {
diff --git a/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift b/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift
index 2d111396..2219bc5d 100644
--- a/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift
+++ b/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift
@@ -5,8 +5,8 @@ import XCTest
final class MemoEditViewModelTests: XCTestCase {
func testTagsAreNormalized() {
let model = MemoEditViewModel()
- model.tagsText = " one, two,three one "
- XCTAssertEqual(model.tags, ["one", "two", "three", "one"])
+ model.tagsText = " one, two,three one, one, #four "
+ XCTAssertEqual(model.tags, ["one", "two", "three one", "four"])
}
func testRejectsEmptyBodyOverNonEmptyBaseline() {
diff --git a/apps/mobile/src/lib/local-mirror.ts b/apps/mobile/src/lib/local-mirror.ts
index 3de6d1f4..cb005805 100644
--- a/apps/mobile/src/lib/local-mirror.ts
+++ b/apps/mobile/src/lib/local-mirror.ts
@@ -1,7 +1,8 @@
import type { createEdgeEverClient, ListMemosResponse, MemoFilterMode, MemoSortMode } from "@edgeever/client";
-import type { MemoDetail, MemoSummary, Notebook } from "@edgeever/shared";
+import type { MemoDetail, MemoSummary, Notebook, TagSummary } from "@edgeever/shared";
import * as SQLite from "expo-sqlite";
import { hasMobileSyncCursorRewound, hasMobileSyncIdentityChanged, isMobileSyncMetadataInitialized, splitMobileBootstrapWriteBatches } from "./mobile-sync-protocol";
+import { summarizeMobileTags } from "./mobile-tags";
const DATABASE_NAME = "edgeever-mobile.db";
const BOOTSTRAP_PAGE_SIZE = 200;
@@ -75,6 +76,22 @@ export const listLocalNotebooks = async (scope: string): Promise<{ notebooks: No
};
};
+export const listLocalTags = async (scope: string): Promise<{ tags: TagSummary[] }> => {
+ const db = await getDatabase();
+ const rows = await db.getAllAsync<StoredMemoRow>(
+ "SELECT data_json FROM mobile_memos WHERE scope = ? AND is_deleted = 0",
+ scope
+ );
+ const memos = rows.flatMap((row) => {
+ try {
+ return [JSON.parse(row.data_json) as MemoDetail];
+ } catch {
+ return [];
+ }
+ });
+ return { tags: summarizeMobileTags(memos) };
+};
+
export const listLocalMemos = async (scope: string, params: LocalMemoListParams): Promise<ListMemosResponse> => {
const db = await getDatabase();
const conditions = ["scope = ?", "is_deleted = ?"];
diff --git a/apps/mobile/src/lib/mobile-locale.tsx b/apps/mobile/src/lib/mobile-locale.tsx
index 43b2812b..a5cae552 100644
--- a/apps/mobile/src/lib/mobile-locale.tsx
+++ b/apps/mobile/src/lib/mobile-locale.tsx
@@ -107,6 +107,11 @@ const mobileOnlyTranslations = new Map<string, string>([
["笔记标题", "Note title"],
["笔记标签", "Note tags"],
["选择笔记本", "Choose notebook"],
+ ["点选已有标签,或输入名称创建新标签", "Select existing tags or enter a name to create a new one"],
+ ["搜索或输入新标签", "Search or enter a new tag"],
+ ["没有匹配的现有标签,可直接新建", "No matching tags. You can create a new one."],
+ ["新建", "Create"],
+ ["{{count}} 条笔记", "{{count}} notes"],
["刷新 Token", "Refresh tokens"],
["Token 名称", "Token name"],
["没有正文预览", "No content preview"],
diff --git a/apps/mobile/src/lib/mobile-tags.test.ts b/apps/mobile/src/lib/mobile-tags.test.ts
new file mode 100644
index 00000000..abed5056
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-tags.test.ts
@@ -0,0 +1,22 @@
+import { expect, test } from "bun:test";
+import type { MemoDetail } from "@edgeever/shared";
+import { summarizeMobileTags } from "./mobile-tags";
+
+const memo = (id: string, tags: string[], updatedAt: string, isDeleted = false) => ({
+ id,
+ tags,
+ updatedAt,
+ isDeleted,
+} as MemoDetail);
+
+test("summarizes active memo tags for the offline picker", () => {
+ expect(summarizeMobileTags([
+ memo("1", ["work", "shared", "work"], "2026-08-13T00:00:00.000Z"),
+ memo("2", ["shared", "ideas"], "2026-08-14T00:00:00.000Z"),
+ memo("3", ["hidden"], "2026-08-15T00:00:00.000Z", true),
+ ])).toEqual([
+ { name: "ideas", memoCount: 1, updatedAt: "2026-08-14T00:00:00.000Z" },
+ { name: "shared", memoCount: 2, updatedAt: "2026-08-14T00:00:00.000Z" },
+ { name: "work", memoCount: 1, updatedAt: "2026-08-13T00:00:00.000Z" },
+ ]);
+});
diff --git a/apps/mobile/src/lib/mobile-tags.ts b/apps/mobile/src/lib/mobile-tags.ts
new file mode 100644
index 00000000..18801664
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-tags.ts
@@ -0,0 +1,19 @@
+import type { MemoDetail, TagSummary } from "@edgeever/shared";
+
+export const summarizeMobileTags = (memos: MemoDetail[]): TagSummary[] => {
+ const tags = new Map<string, { memoCount: number; updatedAt: string | null }>();
+
+ for (const memo of memos) {
+ if (memo.isDeleted) continue;
+ for (const name of new Set(memo.tags.map((tag) => tag.trim()).filter(Boolean))) {
+ const current = tags.get(name) ?? { memoCount: 0, updatedAt: null };
+ current.memoCount += 1;
+ if (!current.updatedAt || memo.updatedAt > current.updatedAt) current.updatedAt = memo.updatedAt;
+ tags.set(name, current);
+ }
+ }
+
+ return [...tags.entries()]
+ .sort(([left], [right]) => left.localeCompare(right, undefined, { sensitivity: "base" }))
+ .map(([name, summary]) => ({ name, ...summary }));
+};
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 5bef37dc..b2c29d42 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -104,6 +104,7 @@ import {
getLocalMemo,
listLocalMemos,
listLocalNotebooks,
+ listLocalTags,
resolveLocalMemo,
syncMobileLocalMirror,
upsertLocalMemo,
@@ -1742,6 +1743,130 @@ const NotebookPickerModal = ({
);
};
+const TagPickerModal = ({
+ dataScope,
+ onChange,
+ onClose,
+ selectedTags,
+ visible,
+}: {
+ dataScope: string;
+ onChange: (tags: string[]) => void;
+ onClose: () => void;
+ selectedTags: string[];
+ visible: boolean;
+}) => {
+ const { translate } = useMobileLocale();
+ const safeAreaInsets = useSafeAreaInsets();
+ const [searchText, setSearchText] = useState("");
+ const tagsQuery = useQuery({
+ queryKey: ["mobile-tags", dataScope],
+ queryFn: () => listLocalTags(dataScope),
+ enabled: visible && Boolean(dataScope),
+ });
+ const normalizedSearch = searchText.trim().replace(/^#/, "");
+ const tags = tagsQuery.data?.tags ?? [];
+ const visibleTags = tags.filter((tag) => tag.name.toLocaleLowerCase().includes(normalizedSearch.toLocaleLowerCase()));
+ const exactMatch = tags.some((tag) => tag.name.toLocaleLowerCase() === normalizedSearch.toLocaleLowerCase());
+
+ useEffect(() => {
+ if (visible) {
+ setSearchText("");
+ }
+ }, [visible]);
+
+ const commit = (nextTags: string[]) => onChange(Array.from(new Set(nextTags)).slice(0, 24));
+ const toggleTag = (name: string) => commit(
+ selectedTags.includes(name) ? selectedTags.filter((tag) => tag !== name) : [...selectedTags, name]
+ );
+ const createTag = () => {
+ const additions = parseTags(normalizedSearch);
+ if (additions.length === 0) return;
+ commit([...selectedTags, ...additions]);
+ setSearchText("");
+ };
+
+ return (
+ <Modal animationType="fade" onRequestClose={onClose} transparent visible={visible}>
+ <Pressable onPress={onClose} style={styles.actionSheetBackdrop}>
+ <Pressable style={[styles.actionSheet, styles.notebookPickerSheet, { paddingBottom: Math.max(8, safeAreaInsets.bottom) }]}>
+ <View style={styles.actionSheetHandle} />
+ <View style={styles.notebookPickerHeader}>
+ <View style={styles.notebookPickerHeaderText}>
+ <Text style={styles.actionSheetTitle}>{translate("选择标签")}</Text>
+ <Text style={styles.panelLabel}>{translate("点选已有标签,或输入名称创建新标签")}</Text>
+ </View>
+ <Pressable accessibilityLabel="关闭" accessibilityRole="button" onPress={onClose} style={styles.notebookPickerCloseButton}>
+ <X color="#0f172a" size={20} />
+ </Pressable>
+ </View>
+
+ <ScrollView contentContainerStyle={styles.notebookPickerContent} keyboardShouldPersistTaps="handled" style={styles.notebookPickerScroll}>
+ {selectedTags.length > 0 ? (
+ <View accessibilityLabel="已选标签" style={styles.tagPickerSelectedList}>
+ {selectedTags.map((tag) => (
+ <Pressable key={tag} accessibilityLabel={`移除标签 ${tag}`} accessibilityRole="button" onPress={() => toggleTag(tag)} style={styles.tagPickerChip}>
+ <Text style={styles.tagPickerChipText}>#{tag}</Text>
+ <X color="#047857" size={14} />
+ </Pressable>
+ ))}
+ </View>
+ ) : null}
+
+ <View style={styles.notebookPickerSearchBox}>
+ <Search color="#64748b" size={18} />
+ <TextInput
+ accessibilityLabel="搜索或输入新标签"
+ autoCapitalize="none"
+ autoCorrect={false}
+ onChangeText={setSearchText}
+ onSubmitEditing={createTag}
+ placeholder="搜索或输入新标签"
+ placeholderTextColor="#94a3b8"
+ returnKeyType="done"
+ style={styles.notebookPickerSearchInput}
+ value={searchText}
+ />
+ {normalizedSearch && !exactMatch && selectedTags.length < 24 ? (
+ <Pressable accessibilityLabel={`新建标签 ${normalizedSearch}`} accessibilityRole="button" onPress={createTag}>
+ <Text style={styles.tagPickerCreateText}>{translate("新建")}</Text>
+ </Pressable>
+ ) : null}
+ </View>
+
+ {tagsQuery.isLoading ? (
+ <ActivityIndicator color="#16a06e" style={styles.tagPickerLoading} />
+ ) : visibleTags.length === 0 ? (
+ <View style={styles.emptyInlinePanel}>
+ <Tag color="#94a3b8" size={28} />
+ <Text style={styles.mutedText}>{translate("没有匹配的现有标签,可直接新建")}</Text>
+ </View>
+ ) : visibleTags.map((tag) => {
+ const selected = selectedTags.includes(tag.name);
+ return (
+ <Pressable
+ key={tag.name}
+ accessibilityLabel={`标签 ${tag.name}`}
+ accessibilityRole="button"
+ accessibilityState={{ selected }}
+ onPress={() => toggleTag(tag.name)}
+ style={[styles.notebookPickerRow, selected && styles.notebookPickerRowActive]}
+ >
+ <View style={[styles.tagPickerCheckbox, selected && styles.tagPickerCheckboxSelected]}>
+ {selected ? <Check color="#ffffff" size={14} /> : null}
+ </View>
+ <Text numberOfLines={1} style={styles.tagPickerRowText}>#{tag.name}</Text>
+ <Text style={styles.panelLabel}>{translate(`${tag.memoCount} 条笔记`)}</Text>
+ </Pressable>
+ );
+ })}
+ </ScrollView>
+ </Pressable>
+ </Pressable>
+ </Modal>
+ );
+};
+
const CreateMemoModal = ({
baseUrl,
client: clientProp,
@@ -1796,6 +1921,7 @@ const CreateMemoModal = ({
const [tagsText, setTagsText] = useState("");
const [contentMarkdown, setContentMarkdown] = useState("");
const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);
+ const [tagPickerOpen, setTagPickerOpen] = useState(false);
const [templatePickerOpen, setTemplatePickerOpen] = useState(false);
const [draftLoaded, setDraftLoaded] = useState(false);
const [dirty, setDirty] = useState(false);
@@ -2329,18 +2455,13 @@ const CreateMemoModal = ({
<Text numberOfLines={1} style={styles.createMemoNotebookText}>{selectedNotebookName}</Text>
<ChevronDown color="#64748b" size={14} />
</Pressable>
- <TextInput
- accessibilityLabel="笔记标签"
- autoCorrect
- onChangeText={(value) => {
- setTagsText(value);
- markDirty();
- }}
- placeholder="添加标签,用逗号分隔"
- placeholderTextColor="#94a3b8"
- style={styles.createMemoTagsInput}
- value={tagsText}
- />
+ <Pressable accessibilityLabel="选择笔记标签" accessibilityRole="button" onPress={() => setTagPickerOpen(true)} style={styles.createMemoTagsButton}>
+ <Tag color="#64748b" size={15} />
+ <Text numberOfLines={1} style={[styles.createMemoTagsInput, !tagsText && styles.createMemoTagsPlaceholder]}>
+ {tagsText || "添加标签"}
+ </Text>
+ <ChevronDown color="#94a3b8" size={14} />
+ </Pressable>
</View>
<View style={styles.createMemoEditorFrame}>
@@ -2362,6 +2483,16 @@ const CreateMemoModal = ({
}}
visible={notebookPickerOpen}
/>
+ <TagPickerModal
+ dataScope={dataScope}
+ onChange={(nextTags) => {
+ setTagsText(nextTags.join(", "));
+ markDirty();
+ }}
+ onClose={() => setTagPickerOpen(false)}
+ selectedTags={parseTags(tagsText)}
+ visible={tagPickerOpen}
+ />
<MobileResourceActions
canMutate={Boolean(materializedMemoRef.current)}
onClose={() => setResourceTarget(null)}
@@ -2586,6 +2717,7 @@ const RichEditorModal = ({
const [tagsText, setTagsText] = useState(restoredDraft?.tagsText ?? memo?.tags.join(", ") ?? "");
const [notebookId, setNotebookId] = useState(restoredDraft?.notebookId ?? memo?.notebookId ?? "");
const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);
+ const [tagPickerOpen, setTagPickerOpen] = useState(false);
const [draftRestored, setDraftRestored] = useState(Boolean(restoredDraft));
const [ready, setReady] = useState(false);
const [dirty, setDirty] = useState(Boolean(restoredDraft));
@@ -2896,18 +3028,13 @@ const RichEditorModal = ({
<Text numberOfLines={1} style={styles.createMemoNotebookText}>{notebookLabel}</Text>
<ChevronDown color="#64748b" size={14} />
</Pressable>
- <TextInput
- autoCorrect
- onChangeText={(value) => {
- setTagsText(value);
- dirtyRef.current = true;
- setDirty(true);
- }}
- placeholder="添加标签,用逗号分隔"
- placeholderTextColor="#94a3b8"
- style={[styles.createMemoTagsInput, styles.richStandaloneTagsInput]}
- value={tagsText}
- />
+ <Pressable accessibilityLabel="选择笔记标签" accessibilityRole="button" onPress={() => setTagPickerOpen(true)} style={[styles.createMemoTagsButton, styles.richStandaloneTagsInput]}>
+ <Tag color="#64748b" size={15} />
+ <Text numberOfLines={1} style={[styles.createMemoTagsInput, !tagsText && styles.createMemoTagsPlaceholder]}>
+ {tagsText || "添加标签"}
+ </Text>
+ <ChevronDown color="#94a3b8" size={14} />
+ </Pressable>
</View>
{draftRestored ? <Text style={styles.richEditorDraftNotice}>已恢复上次未完成的本地草稿</Text> : null}
<View style={styles.richEditorFrame}>
@@ -2933,6 +3060,17 @@ const RichEditorModal = ({
}}
visible={notebookPickerOpen}
/>
+ <TagPickerModal
+ dataScope={createMobileDataScope(session?.baseUrl ?? baseUrl, session?.user?.id)}
+ onChange={(nextTags) => {
+ setTagsText(nextTags.join(", "));
+ dirtyRef.current = true;
+ setDirty(true);
+ }}
+ onClose={() => setTagPickerOpen(false)}
+ selectedTags={parseTags(tagsText)}
+ visible={tagPickerOpen}
+ />
<MobileResourceActions
canMutate={Boolean(memo && !memo.id.startsWith("local:"))}
onClose={() => setResourceTarget(null)}
diff --git a/apps/mobile/src/screens/workspace-styles.ts b/apps/mobile/src/screens/workspace-styles.ts
index 23da381b..505f3fc0 100644
--- a/apps/mobile/src/screens/workspace-styles.ts
+++ b/apps/mobile/src/screens/workspace-styles.ts
@@ -1240,6 +1240,17 @@ const baseWorkspaceStyles = StyleSheet.create({
minWidth: 0,
padding: 0,
},
+ createMemoTagsButton: {
+ alignItems: "center",
+ flex: 1,
+ flexDirection: "row",
+ gap: 6,
+ minHeight: 36,
+ minWidth: 0,
+ },
+ createMemoTagsPlaceholder: {
+ color: "#94a3b8",
+ },
createMemoToolButton: {
alignItems: "center",
borderColor: "transparent",
@@ -1551,6 +1562,53 @@ const baseWorkspaceStyles = StyleSheet.create({
notebookPickerRowActive: {
backgroundColor: "#f1f5f9",
},
+ tagPickerSelectedList: {
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 8,
+ marginBottom: 10,
+ },
+ tagPickerChip: {
+ alignItems: "center",
+ backgroundColor: "#ecfdf5",
+ borderRadius: 999,
+ flexDirection: "row",
+ gap: 4,
+ minHeight: 32,
+ paddingHorizontal: 11,
+ },
+ tagPickerChipText: {
+ color: "#047857",
+ fontSize: 13,
+ fontWeight: "700",
+ },
+ tagPickerCreateText: {
+ color: "#047857",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ tagPickerLoading: {
+ paddingVertical: 28,
+ },
+ tagPickerCheckbox: {
+ alignItems: "center",
+ borderColor: "#cbd5e1",
+ borderRadius: 5,
+ borderWidth: 1,
+ height: 22,
+ justifyContent: "center",
+ width: 22,
+ },
+ tagPickerCheckboxSelected: {
+ backgroundColor: "#16a06e",
+ borderColor: "#16a06e",
+ },
+ tagPickerRowText: {
+ color: "#0f172a",
+ flex: 1,
+ fontSize: 14,
+ fontWeight: "700",
+ },
actionSheetHandle: {
alignSelf: "center",
backgroundColor: "#cbd5e1",
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index eac4cca1..a41ebed7 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -76,6 +76,7 @@ import {
} from "@/components/ui/dialog";
import { EditorToolbar } from "./EditorToolbar";
import { EditorOutline } from "./EditorOutline";
+import { EditorTagPicker } from "./EditorTagPicker";
import { useAiBubbleMenu } from "./editor/useAiBubbleMenu";
import { WeChatIcon } from "./WeChatIcon";
import { ThemeToggle } from "./ThemeToggle";
@@ -3821,20 +3822,16 @@ const RichEditorPane = ({
</SelectContent>
</Select>
</div>
- <label className="flex h-8 min-w-[12rem] flex-1 items-center gap-2 rounded-md border border-transparent px-2 text-sm text-slate-500 transition focus-within:border-slate-200 focus-within:bg-slate-50 focus-within:ring-2 focus-within:ring-emerald-500/15">
- <Tags className="h-4 w-4" />
- <input
- value={tagsText}
- readOnly={effectiveReadOnly}
- onChange={(event) => {
- setTagsText(event.target.value);
- persistCurrentDraft(title, event.target.value, getMobilePlainTextValue());
- markDirty();
- }}
- className="min-w-0 flex-1 bg-transparent outline-none placeholder:text-slate-400"
- placeholder={t("editor.tagPlaceholder")}
- />
- </label>
+ <EditorTagPicker
+ disabled={effectiveReadOnly}
+ loadTags={() => repository.listTags()}
+ value={tagsText}
+ onChange={(nextTagsText) => {
+ setTagsText(nextTagsText);
+ persistCurrentDraft(title, nextTagsText, getMobilePlainTextValue());
+ markDirty();
+ }}
+ />
</div>
</div>
{noteSearchOpen && (
diff --git a/apps/web/src/components/EditorTagPicker.tsx b/apps/web/src/components/EditorTagPicker.tsx
new file mode 100644
index 00000000..d5a2918f
--- /dev/null
+++ b/apps/web/src/components/EditorTagPicker.tsx
@@ -0,0 +1,137 @@
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Check, ChevronDown, Tags, X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { normalizeTags, type TagSummary } from "@edgeever/shared";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { parseTagsText } from "@/lib/utils";
+
+type EditorTagPickerProps = {
+ disabled: boolean;
+ loadTags: () => Promise<{ tags: TagSummary[] }>;
+ value: string;
+ onChange: (value: string) => void;
+};
+
+export const EditorTagPicker = ({ disabled, loadTags, value, onChange }: EditorTagPickerProps) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const selectedTags = useMemo(() => normalizeTags(parseTagsText(value)), [value]);
+ const tagsQuery = useQuery({
+ queryKey: ["tags"],
+ queryFn: loadTags,
+ enabled: open,
+ });
+ const normalizedQuery = query.trim().replace(/^#/, "");
+ const visibleTags = (tagsQuery.data?.tags ?? []).filter((tag) =>
+ tag.name.toLocaleLowerCase().includes(normalizedQuery.toLocaleLowerCase())
+ );
+ const exactMatch = (tagsQuery.data?.tags ?? []).some(
+ (tag) => tag.name.toLocaleLowerCase() === normalizedQuery.toLocaleLowerCase()
+ );
+
+ const commit = (tags: string[]) => onChange(normalizeTags(tags).join(", "));
+ const toggleTag = (name: string) => {
+ commit(selectedTags.includes(name)
+ ? selectedTags.filter((tag) => tag !== name)
+ : [...selectedTags, name]);
+ };
+ const createTag = () => {
+ const additions = parseTagsText(normalizedQuery);
+ if (additions.length === 0) return;
+ commit([...selectedTags, ...additions]);
+ setQuery("");
+ };
+
+ return (
+ <>
+ <button
+ type="button"
+ disabled={disabled}
+ className="flex h-8 min-w-[12rem] flex-1 items-center gap-2 rounded-md border border-transparent px-2 text-left text-sm text-slate-500 outline-none transition hover:border-slate-200 hover:bg-slate-50 focus-visible:border-emerald-300 focus-visible:ring-2 focus-visible:ring-emerald-500/15 disabled:opacity-50"
+ aria-label={t("editor.tagPicker.open")}
+ onClick={() => setOpen(true)}
+ >
+ <Tags className="h-4 w-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">
+ {selectedTags.length > 0 ? selectedTags.map((tag) => `#${tag}`).join(", ") : t("editor.tagPlaceholder")}
+ </span>
+ <ChevronDown className="h-3.5 w-3.5 shrink-0 text-slate-400" />
+ </button>
+
+ <Dialog open={open} onOpenChange={(nextOpen) => { setOpen(nextOpen); if (!nextOpen) setQuery(""); }}>
+ <DialogContent className="flex max-h-[min(42rem,calc(100dvh-2rem))] max-w-lg flex-col overflow-hidden">
+ <DialogHeader>
+ <DialogTitle>{t("editor.tagPicker.title")}</DialogTitle>
+ <DialogDescription>{t("editor.tagPicker.description")}</DialogDescription>
+ </DialogHeader>
+
+ {selectedTags.length > 0 && (
+ <div className="flex flex-wrap gap-2" aria-label={t("editor.tagPicker.selected")}>
+ {selectedTags.map((tag) => (
+ <button
+ key={tag}
+ type="button"
+ className="inline-flex h-8 items-center gap-1 rounded-full bg-emerald-50 px-3 text-sm font-medium text-emerald-800 outline-none hover:bg-emerald-100 focus-visible:ring-2 focus-visible:ring-emerald-500/30"
+ onClick={() => toggleTag(tag)}
+ aria-label={t("editor.tagPicker.remove", { name: tag })}
+ >
+ #{tag}<X className="h-3.5 w-3.5" />
+ </button>
+ ))}
+ </div>
+ )}
+
+ <form className="flex gap-2" onSubmit={(event) => { event.preventDefault(); createTag(); }}>
+ <Input
+ autoFocus
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t("editor.tagPicker.searchPlaceholder")}
+ aria-label={t("editor.tagPicker.searchPlaceholder")}
+ />
+ <Button type="submit" variant="outline" disabled={!normalizedQuery || exactMatch || selectedTags.length >= 24}>
+ {t("editor.tagPicker.create")}
+ </Button>
+ </form>
+
+ <div className="min-h-0 flex-1 overflow-y-auto rounded-md border border-slate-200">
+ {tagsQuery.isLoading ? (
+ <p className="px-4 py-8 text-center text-sm text-slate-500">{t("editor.tagPicker.loading")}</p>
+ ) : visibleTags.length === 0 ? (
+ <p className="px-4 py-8 text-center text-sm text-slate-500">{t("editor.tagPicker.empty")}</p>
+ ) : (
+ visibleTags.map((tag) => {
+ const selected = selectedTags.includes(tag.name);
+ return (
+ <button
+ key={tag.name}
+ type="button"
+ className="flex min-h-11 w-full items-center gap-3 border-b border-slate-100 px-3 text-left text-sm outline-none last:border-b-0 hover:bg-slate-50 focus-visible:bg-emerald-50"
+ onClick={() => toggleTag(tag.name)}
+ aria-pressed={selected}
+ >
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded border border-slate-300 text-emerald-700">
+ {selected && <Check className="h-4 w-4" />}
+ </span>
+ <span className="min-w-0 flex-1 truncate font-medium">#{tag.name}</span>
+ <span className="text-xs text-slate-400">{t("editor.tagPicker.memoCount", { count: tag.memoCount })}</span>
+ </button>
+ );
+ })
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
diff --git a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
index 602bbec0..e1ecbc94 100644
--- a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
+++ b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
@@ -8,7 +8,7 @@ import { TaskItem, TaskList } from "@tiptap/extension-list";
import { mergeAttributes } from "@tiptap/core";
import Placeholder from "@tiptap/extension-placeholder";
import { TableKit } from "@tiptap/extension-table";
-import { createExcerpt, docToMarkdown, docToText, emptyDoc, getImageReferrerPolicy, MergeDivider, type MemoDetail, type MemoEditSession, type Notebook, type TiptapDoc } from "@edgeever/shared";
+import { createExcerpt, docToMarkdown, docToText, emptyDoc, getImageReferrerPolicy, MergeDivider, type MemoDetail, type MemoEditSession, type Notebook, type TagSummary, type TiptapDoc } from "@edgeever/shared";
import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
import { getMobileEditorInputAttributes, getMobileEditorPlaceholder } from "@edgeever/shared/mobile-editor";
import {
@@ -45,6 +45,8 @@ import { getMemoUpdateQueueId, isMemoUpdateAlreadyApplied, queueMemoUpdate, shou
import { EdgeEverCodeBlock, codeBlockLowlight } from "@/lib/code-block";
import { createMarkdownImagePasteRule } from "@/lib/markdown-image-paste";
import { ThemeBlock } from "./ThemeBlock";
+import { EditorTagPicker } from "./EditorTagPicker";
+import { listLocalTags } from "@/lib/local-mirror";
const ProtectedExternalImage = Image.extend({
addPasteRules() {
@@ -544,6 +546,14 @@ export const MobileStandaloneTiptapEditor = ({
scheduleMetadataSave();
};
+ const loadTags = useCallback(async () => {
+ if (memoId) {
+ const localMemo = await localDb.memos.filter((candidate) => candidate.id === memoId).first();
+ if (localMemo) return listLocalTags(localMemo.scope);
+ }
+ return requestMobileEditorJson<{ tags: TagSummary[] }>("/api/v1/tags");
+ }, [memoId]);
+
const handleNotebookChange = async (nextNotebookId: string) => {
const currentMemo = memoRef.current;
if (!currentMemo || !nextNotebookId || nextNotebookId === currentMemo.notebookId || notebookUpdatePending) {
@@ -919,14 +929,11 @@ export const MobileStandaloneTiptapEditor = ({
disabled={!memo || notebookUpdatePending || saveState === "loading" || notebookOptions.length === 0}
onOpen={() => setNotebookSheetOpen(true)}
/>
- <input
- className="mobile-editor-tags"
+ <EditorTagPicker
+ disabled={!memo || saveState === "loading"}
+ loadTags={loadTags}
value={tagsText}
- autoComplete="on"
- autoCorrect="on"
- inputMode="text"
- placeholder={t("editor.tagPlaceholder")}
- onChange={(event) => handleTagsChange(event.target.value)}
+ onChange={handleTagsChange}
/>
</div>
diff --git a/apps/web/src/lib/utils.test.mjs b/apps/web/src/lib/utils.test.mjs
index bea81c7e..64272aaa 100644
--- a/apps/web/src/lib/utils.test.mjs
+++ b/apps/web/src/lib/utils.test.mjs
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { buildNotebookTree } from "./utils.ts";
+import { buildNotebookTree, parseTagsText } from "./utils.ts";
const notebook = (id, parentId, memoCount, lastMemoUpdatedAt = null) => ({
id,
@@ -54,3 +54,14 @@ describe("buildNotebookTree", () => {
expect(root).not.toHaveProperty("children");
});
});
+
+describe("tag text parsing", () => {
+ test("supports multi-word tags and normalizes separators", () => {
+ expect(parseTagsText(" #product design, work,ideas\nwork ")).toEqual([
+ "product design",
+ "work",
+ "ideas",
+ "work",
+ ]);
+ });
+});
diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts
index c5eb8d9d..70117d46 100644
--- a/apps/web/src/lib/utils.ts
+++ b/apps/web/src/lib/utils.ts
@@ -59,6 +59,6 @@ export const formatDateTime = (value: string) =>
export const parseTagsText = (value: string) =>
value
- .split(/[,,\s]+/)
+ .split(/[,,\n]+/)
.map((tag) => tag.trim().replace(/^#/, ""))
.filter(Boolean);
diff --git a/apps/web/src/mobile-edit.tsx b/apps/web/src/mobile-edit.tsx
index b8dac38c..618c236c 100644
--- a/apps/web/src/mobile-edit.tsx
+++ b/apps/web/src/mobile-edit.tsx
@@ -1,4 +1,5 @@
import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRoot } from "react-dom/client";
import { MobileStandaloneTiptapEditor } from "@/components/MobileStandaloneTiptapEditor";
import { initializeTheme } from "@/components/ThemeProvider";
@@ -13,8 +14,14 @@ if (!root) {
initializeTheme();
+const queryClient = new QueryClient({
+ defaultOptions: { queries: { refetchOnWindowFocus: false, retry: 1, staleTime: 15_000 } },
+});
+
createRoot(root).render(
<React.StrictMode>
- <MobileStandaloneTiptapEditor />
+ <QueryClientProvider client={queryClient}>
+ <MobileStandaloneTiptapEditor />
+ </QueryClientProvider>
</React.StrictMode>
);
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 4ac24cc2..6322da56 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -911,6 +911,18 @@ export const enUS = {
deleteMemo: "Delete note",
notebookPlaceholder: "Current notebook",
tagPlaceholder: "Add tags, separated by commas",
+ tagPicker: {
+ open: "Choose note tags",
+ title: "Choose tags",
+ description: "Select existing tags or enter a name to create a new one.",
+ selected: "Selected tags",
+ remove: "Remove tag {{name}}",
+ searchPlaceholder: "Search or enter a new tag",
+ create: "Create",
+ loading: "Loading tags…",
+ empty: "No matching tags. You can create a new one.",
+ memoCount: "{{count}} notes",
+ },
searchPlaceholder: "Search in current note",
replacePlaceholder: "Replace with",
previousSearchResult: "Previous search result",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index b57b4045..ed55e4ae 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -911,6 +911,18 @@ export const zhCN = {
deleteMemo: "删除笔记",
notebookPlaceholder: "所在笔记本",
tagPlaceholder: "添加标签,用逗号分隔",
+ tagPicker: {
+ open: "选择笔记标签",
+ title: "选择标签",
+ description: "点选已有标签,或输入名称创建新标签。",
+ selected: "已选标签",
+ remove: "移除标签 {{name}}",
+ searchPlaceholder: "搜索或输入新标签",
+ create: "新建",
+ loading: "正在加载标签…",
+ empty: "没有匹配的现有标签,可直接新建。",
+ memoCount: "{{count}} 条笔记",
+ },
searchPlaceholder: "在当前笔记内搜索",
replacePlaceholder: "替换为",
previousSearchResult: "上一个搜索结果",