Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

feat(editor): add contextual tag, checklist, and visibility suggestions (#6367)

Johnny80bab62c723d
diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/Editor/controller.ts
index c50ec05fc..ed3dabfcf 100644
--- a/web/src/components/MemoEditor/Editor/controller.ts
+++ b/web/src/components/MemoEditor/Editor/controller.ts
@@ -1,6 +1,10 @@
+import { isolateHistory } from "@codemirror/commands";
+import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
import { EditorSelection, type EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
+import { isCompleteTagValue } from "@/utils/tag-grammar";
import type { EditorController, FormattingController } from "../types/editorController";
+import { findMarkdownTagMatches } from "./markdownTagRanges";
import {
cancelUploadAnchor,
createUploadAnchor,
@@ -19,11 +23,44 @@ function blockPad(before: string, after: string): { prefix: string; suffix: stri
}
export function createController(view: EditorView, formatting: FormattingController): EditorController {
+ const currentTags = () => findMarkdownTagMatches(view.state, 0, view.state.doc.length).map((match) => match.value);
return {
focus: () => view.focus(),
hasFocus: () => view.hasFocus,
isEmpty: () => isEmptyDoc(view.state),
getMarkdown: () => view.state.doc.toString(),
+ getTags: currentTags,
+ hasChecklist: () => {
+ let found = false;
+ const tree = ensureSyntaxTree(view.state, view.state.doc.length) ?? syntaxTree(view.state);
+ tree.iterate({
+ enter: (node) => {
+ if (node.name === "Task") found = true;
+ if (found) return false;
+ },
+ });
+ return found;
+ },
+ insertTag: (tag) => {
+ if (!isCompleteTagValue(tag) || view.compositionStarted || currentTags().includes(tag)) return false;
+ const { doc, selection } = view.state;
+ const { head } = selection.main;
+ // Like insertMarkdown, keep highlighted text and insert at the active end.
+ // Honor the chosen Markdown context, including code, instead of relocating it.
+ const prefix = head > 0 && !/\s/.test(doc.sliceString(head - 1, head)) ? " " : "";
+ const hasFollowingSpace = /^[ \t]$/.test(doc.sliceString(head, head + 1));
+ const insert = `${prefix}#${tag}${hasFollowingSpace ? "" : " "}`;
+ view.dispatch({
+ changes: { from: head, insert },
+ // Exactly one space follows the tag, inserted or reused; the caret lands after it.
+ selection: { anchor: head + prefix.length + tag.length + 2 },
+ annotations: isolateHistory.of("full"),
+ userEvent: "input",
+ scrollIntoView: true,
+ });
+ view.focus();
+ return true;
+ },
setMarkdown: (markdown) => {
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: markdown } });
},
diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md
index b4a1f35b8..3d79aedc4 100644
--- a/web/src/components/MemoEditor/README.md
+++ b/web/src/components/MemoEditor/README.md
@@ -105,6 +105,30 @@ The app formatting keymap sits ahead of CodeMirror's generic `defaultKeymap`: `M
Pure TypeScript functions containing business logic. No React hooks, easy to test.
+### Suggestions
+
+Hosts of a new top-level memo (Home, the global composer) pass `useMemoSuggestions()`
+into the `suggestions` prop; edits and comments omit the bar. `lib/memo-suggestions.ts`
+merges typed candidates from providers and keeps the strongest source per id
+(selection, then search, then the selected View). `lib/suggestion-expression.ts` is a
+small Boolean CEL reader shared by the providers; unsupported syntax never falls back
+to scanning free text.
+
+- Tags: explicit tag conditions and selected tags. `insertTag()` is one isolated undo
+ step at the caret that keeps selected text and honors the current Markdown context.
+- Checklist: task-list conditions, including the built-in Tasks View; a negative
+ task-list or incomplete-task condition suppresses it.
+- Visibility: exactly one explicit audience across filters and View, otherwise nothing.
+ Space visibility also requires actual Space placement.
+
+`EditorSuggestions` hides until the draft has text, drops suggestions already satisfied
+(via the Markdown-aware `getTags()` / `hasChecklist()`, so code examples do not count)
+or already accepted, and shows at most three across kinds. Acceptance history lives in
+the editor store so Undo or reverting a choice does not immediately resuggest it, and it
+clears with the draft on reset; nothing is persisted with the memo. `SuggestionsBar` is
+payload-agnostic; a new kind extends the `MemoSuggestion` union and its
+eligibility/application in `EditorSuggestions`.
+
### Presentation: inline vs hosted
Every instance is one of two things, and `onFocusModeExit` is the switch:
diff --git a/web/src/components/MemoEditor/components/EditorSuggestions.tsx b/web/src/components/MemoEditor/components/EditorSuggestions.tsx
new file mode 100644
index 000000000..fb54b744c
--- /dev/null
+++ b/web/src/components/MemoEditor/components/EditorSuggestions.tsx
@@ -0,0 +1,142 @@
+import { isEqual } from "lodash-es";
+import { ListTodoIcon, ZapIcon } from "lucide-react";
+import { type RefObject, useId, useLayoutEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { MAX_MEMO_SUGGESTIONS, type MemoSuggestion, type SuggestionItem } from "@/lib/memo-suggestions";
+import { cn } from "@/lib/utils";
+import { useTranslate } from "@/utils/i18n";
+import { getAssignableVisibilityOptions, getVisibilityOption } from "@/utils/memo";
+import { useEditorContext, useEditorSelector } from "../state";
+import type { EditorController } from "../types/editorController";
+
+/** Shared UI for all suggestion kinds. Payloads and application belong to the caller. */
+export function SuggestionsBar({
+ suggestions,
+ disabled,
+ onAccept,
+}: {
+ suggestions: readonly SuggestionItem[];
+ disabled: boolean;
+ onAccept: (id: string) => void;
+}) {
+ const t = useTranslate();
+ const labelId = useId();
+ if (!suggestions.length) return null;
+ return (
+ <div role="group" aria-labelledby={labelId} className="flex w-full items-start gap-2 text-ui">
+ <span id={labelId} className="inline-flex h-6 shrink-0 items-center gap-1.5 text-muted-foreground/70">
+ <ZapIcon className="size-3.5" aria-hidden />
+ {t("editor.suggestions")}
+ </span>
+ <div className="flex min-w-0 flex-1 flex-wrap gap-1.5">
+ {suggestions.map((suggestion) => (
+ <button
+ key={suggestion.id}
+ type="button"
+ disabled={disabled}
+ aria-label={suggestion.accessibleLabel ?? suggestion.label}
+ className={cn(
+ buttonVariants({ variant: "quiet", size: "sm" }),
+ "h-6 max-w-full gap-1 border border-dashed border-muted-foreground/30 px-1.5 text-muted-foreground hover:border-muted-foreground/50 has-[>svg]:px-1.5",
+ )}
+ onClick={() => onAccept(suggestion.id)}
+ >
+ {suggestion.icon && <suggestion.icon className="size-3" aria-hidden />}
+ <span className="truncate">{suggestion.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** Coordinates draft eligibility and acceptance; each kind owns its application. */
+export function EditorSuggestions({
+ suggestions,
+ controllerRef,
+ space,
+}: {
+ suggestions: readonly MemoSuggestion[];
+ controllerRef: RefObject<EditorController | null>;
+ space?: string;
+}) {
+ const t = useTranslate();
+ const { actions, dispatch } = useEditorContext();
+ const content = useEditorSelector((state) => state.content);
+ const acceptedIds = useEditorSelector((state) => state.acceptedSuggestionIds);
+ const isSaving = useEditorSelector((state) => state.ui.isLoading.saving);
+ const visibility = useEditorSelector((state) => state.metadata.visibility);
+ const [tags, setTags] = useState<string[]>([]);
+ const [hasChecklist, setHasChecklist] = useState(false);
+ const needsTags = suggestions.some((suggestion) => suggestion.kind === "tag");
+ const needsChecklist = suggestions.some((suggestion) => suggestion.kind === "checklist");
+ // Read after the editor has applied restored/external content in its layout effect.
+ // The document scans only pay off when a tag or checklist suggestion exists.
+ useLayoutEffect(() => {
+ const controller = controllerRef.current;
+ if ((!needsTags && !needsChecklist) || !controller || controller.getMarkdown() !== content) return;
+ if (needsTags) {
+ const next = controller.getTags();
+ setTags((prev) => (isEqual(prev, next) ? prev : next));
+ }
+ if (needsChecklist) setHasChecklist(controller.hasChecklist());
+ }, [content, controllerRef, needsTags, needsChecklist]);
+
+ if (!content.trim()) return null;
+
+ const visibilityOptions = getAssignableVisibilityOptions({ hasSpacePlacement: Boolean(space), current: visibility });
+ const visible = suggestions
+ .filter((suggestion) => {
+ if (acceptedIds.includes(suggestion.id)) return false;
+ switch (suggestion.kind) {
+ case "tag":
+ return !tags.includes(suggestion.tag);
+ case "checklist":
+ return !hasChecklist;
+ case "visibility":
+ return suggestion.visibility !== visibility && visibilityOptions.some((option) => option.value === suggestion.visibility);
+ }
+ })
+ .slice(0, MAX_MEMO_SUGGESTIONS)
+ .map((suggestion): MemoSuggestion & SuggestionItem => {
+ switch (suggestion.kind) {
+ case "tag":
+ return { ...suggestion, label: `#${suggestion.tag}`, accessibleLabel: `${t("common.add")} #${suggestion.tag}` };
+ case "checklist":
+ return { ...suggestion, label: t("editor.format.task-list"), icon: ListTodoIcon };
+ case "visibility": {
+ const option = getVisibilityOption(suggestion.visibility)!;
+ return { ...suggestion, label: t(option.labelKey), icon: option.icon };
+ }
+ }
+ });
+
+ const accept = (id: string) => {
+ const suggestion = visible.find((item) => item.id === id);
+ const controller = controllerRef.current;
+ if (!suggestion || !controller) return;
+ let applied = false;
+ switch (suggestion.kind) {
+ case "tag":
+ applied = controller.insertTag(suggestion.tag);
+ break;
+ case "checklist": {
+ if (controller.hasChecklist() || !controller.formatting) return;
+ const before = controller.getMarkdown();
+ controller.formatting.run("taskList");
+ applied = before !== controller.getMarkdown();
+ controller.focus();
+ break;
+ }
+ case "visibility":
+ // Assignability was checked when the chip was rendered from the same state.
+ dispatch(actions.setMetadata({ visibility: suggestion.visibility }));
+ controller.focus();
+ applied = true;
+ break;
+ }
+ if (applied) dispatch(actions.acceptSuggestion(suggestion.id));
+ };
+
+ return <SuggestionsBar suggestions={visible} disabled={isSaving} onAccept={accept} />;
+}
diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsx
index 0fd3b4d02..8a8ede251 100644
--- a/web/src/components/MemoEditor/index.tsx
+++ b/web/src/components/MemoEditor/index.tsx
@@ -9,6 +9,7 @@ import { InstanceSetting_Key } from "@/types/proto/api/v1/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
import { convertVisibilityFromString } from "@/utils/memo";
import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeOverlay, TimestampPopover } from "./components";
+import { EditorSuggestions } from "./components/EditorSuggestions";
import { FOCUS_MODE_STYLES, FORMATTING_TOOLBAR_STORAGE_KEY } from "./constants";
import type { EditorFileOrigin } from "./Editor/extensions";
import {
@@ -42,6 +43,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
cacheKey,
memo,
parentMemoName,
+ suggestions = [],
defaultSpace,
defaultLocation,
autoFocus,
@@ -388,6 +390,9 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
onInsertAttachments={inlineImageUpload.insertRemoteImages}
onInsertLocalFiles={inlineImageUpload.insertLocalImages}
/>
+ {!memo && !parentMemoName && isInitialized && suggestions.length > 0 && (
+ <EditorSuggestions suggestions={suggestions} controllerRef={editorRef} space={editorSpace} />
+ )}
<EditorToolbar
onSave={handleSave}
onCancel={onCancel ? handleCancel : undefined}
diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.ts
index a941eed88..f106a939c 100644
--- a/web/src/components/MemoEditor/state/actions.ts
+++ b/web/src/components/MemoEditor/state/actions.ts
@@ -66,6 +66,11 @@ export const editorActions = {
payload: value,
}),
+ acceptSuggestion: (id: string): EditorAction => ({
+ type: "ACCEPT_SUGGESTION",
+ payload: id,
+ }),
+
reset: (): EditorAction => ({
type: "RESET",
}),
diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts
index 2536370d6..ab94cf24b 100644
--- a/web/src/components/MemoEditor/state/reducer.ts
+++ b/web/src/components/MemoEditor/state/reducer.ts
@@ -107,6 +107,11 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
case "RESET":
return createInitialState();
+ case "ACCEPT_SUGGESTION":
+ return state.acceptedSuggestionIds.includes(action.payload)
+ ? state
+ : { ...state, acceptedSuggestionIds: [...state.acceptedSuggestionIds, action.payload] };
+
default:
return state;
}
diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.ts
index 7d8aae7dc..e5cb7811e 100644
--- a/web/src/components/MemoEditor/state/types.ts
+++ b/web/src/components/MemoEditor/state/types.ts
@@ -36,6 +36,8 @@ export interface EditorState {
/** Whether an audio recording is in flight; gates save. The recorder's full
* state lives in useAudioRecorder — only this shared bit reaches the store. */
recorderBusy: boolean;
+ /** Draft-local acceptance history, retained across Undo but cleared on reset. */
+ acceptedSuggestionIds: string[];
}
export type EditorAction =
@@ -51,6 +53,7 @@ export type EditorAction =
| { type: "SET_TIMESTAMPS"; payload: Partial<EditorState["timestamps"]> }
| { type: "SET_RECORDER_BUSY"; payload: boolean }
| { type: "SET_JUST_SAVED"; payload: boolean }
+ | { type: "ACCEPT_SUGGESTION"; payload: string }
| { type: "RESET" };
// Module-private template for createInitialState.
@@ -79,6 +82,7 @@ const defaultState: EditorState = {
},
localFiles: [],
recorderBusy: false,
+ acceptedSuggestionIds: [],
};
/** Fresh initial state for a mounting editor. */
diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.ts
index 8dba2eda8..36da5dc23 100644
--- a/web/src/components/MemoEditor/types/components.ts
+++ b/web/src/components/MemoEditor/types/components.ts
@@ -1,3 +1,4 @@
+import type { MemoSuggestion } from "@/lib/memo-suggestions";
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import type { Location, Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
import type { EditorFileOrigin } from "../Editor/extensions";
@@ -11,6 +12,8 @@ export interface MemoEditorProps {
/** Existing memo to edit. When provided, the editor initializes from it without fetching. */
memo?: Memo;
parentMemoName?: string;
+ /** Context-derived suggestions for a new top-level memo. */
+ suggestions?: readonly MemoSuggestion[];
/** Assigns a newly created top-level memo to this Space. Ignored for edits and comments. */
defaultSpace?: string;
/** Seeds a new memo once; restored draft metadata takes precedence. */
diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.ts
index 00f9f4131..032ce21ea 100644
--- a/web/src/components/MemoEditor/types/editorController.ts
+++ b/web/src/components/MemoEditor/types/editorController.ts
@@ -17,6 +17,12 @@ export interface EditorController {
setMarkdown(markdown: string): void;
/** Insert markdown at the cursor as its own block. */
insertMarkdown(markdown: string): void;
+ /** Actual Markdown tags, excluding code, URLs, and other literal contexts. */
+ getTags(): string[];
+ /** Whether the document contains a parsed Markdown checklist, checked or unchecked. */
+ hasChecklist(): boolean;
+ /** Insert a tag at the caret without replacing selected text, then advance the caret. Returns whether it was inserted. */
+ insertTag(tag: string): boolean;
createUploadAnchor(descriptor: UploadAnchorDescriptor, position?: number): void;
updateUploadAnchor(descriptor: UploadAnchorDescriptor): void;
resolveUploadAnchor(id: string, markdown: string): void;
diff --git a/web/src/contexts/GlobalMemoEditorContext.tsx b/web/src/contexts/GlobalMemoEditorContext.tsx
index 0bfae71bb..27f9fcb50 100644
--- a/web/src/contexts/GlobalMemoEditorContext.tsx
+++ b/web/src/contexts/GlobalMemoEditorContext.tsx
@@ -10,6 +10,7 @@ import { useAuth } from "@/contexts/AuthContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useMediaQuery from "@/hooks/useMediaQuery";
+import { useMemoSuggestions } from "@/hooks/useMemoSuggestions";
import { spaceScopedCacheKey } from "@/lib/resource-names";
import { useTranslate } from "@/utils/i18n";
@@ -43,6 +44,7 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
const t = useTranslate();
const location = useLocation();
const currentUserName = useCurrentUser()?.name;
+ const suggestions = useMemoSuggestions();
const { selectedSpaceName, isSpaceReady } = useSpaceContext();
const { isUserSettingsInitialized } = useAuth();
const desktop = useMediaQuery("md");
@@ -172,6 +174,7 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
autoFocus
cacheKey={spaceScopedCacheKey("global-memo-editor", opened?.space)}
defaultSpace={opened?.space}
+ suggestions={suggestions}
placeholder={t("editor.any-thoughts")}
onConfirm={closeEditor}
onCancel={closeEditor}
diff --git a/web/src/hooks/useMemoFilters.ts b/web/src/hooks/useMemoFilters.ts
index 3a3f531f0..889d1ffe9 100644
--- a/web/src/hooks/useMemoFilters.ts
+++ b/web/src/hooks/useMemoFilters.ts
@@ -88,21 +88,25 @@ export const buildMemoFilter = ({
return combineCELFilters(...conditions);
};
+/** CEL filter of the View selected in the sidebar: the built-in Tasks filter or the saved View's stored filter. */
+export const useSelectedMemoViewFilter = (): string | undefined => {
+ const currentUser = useCurrentUser();
+ const { memoView } = useMemoFilterContext();
+ const { data: memoViews = [] } = useMemoViews(currentUser?.name);
+ return useMemo(() => {
+ if (memoView === BUILTIN_TASKS_VIEW_ID) return BUILTIN_TASKS_VIEW_FILTER;
+ return memoViews.find((view) => getMemoViewId(view.name) === memoView)?.filter;
+ }, [memoView, memoViews]);
+};
+
export const useMemoFilters = (options: UseMemoFiltersOptions = {}): string | undefined => {
const { creatorName, includeMemoViews = false, includePinned = false, visibilities } = options;
- const currentUser = useCurrentUser();
- const { data: memoViews = [] } = useMemoViews(includeMemoViews ? currentUser?.name : undefined);
const { filters, memoView: currentMemoView } = useMemoFilterContext();
+ const selectedMemoViewFilter = useSelectedMemoViewFilter();
// The sidebar calendar buckets days by this basis, so a picked day must select on it too.
const { timeBasis } = useView();
- // Get the selected memo view if needed.
- const selectedMemoViewFilter = useMemo(() => {
- if (!includeMemoViews || currentMemoView === BUILTIN_TASKS_VIEW_ID) return undefined;
- return memoViews.find((memoView) => getMemoViewId(memoView.name) === currentMemoView)?.filter;
- }, [includeMemoViews, currentMemoView, memoViews]);
-
return useMemo(
() =>
buildMemoFilter({
@@ -110,7 +114,7 @@ export const useMemoFilters = (options: UseMemoFiltersOptions = {}): string | un
currentMemoView: includeMemoViews ? currentMemoView : undefined,
filters,
includePinned,
- selectedMemoViewFilter,
+ selectedMemoViewFilter: includeMemoViews ? selectedMemoViewFilter : undefined,
visibilities,
timeBasis,
}),
diff --git a/web/src/hooks/useMemoSuggestions.ts b/web/src/hooks/useMemoSuggestions.ts
new file mode 100644
index 000000000..2d6c20771
--- /dev/null
+++ b/web/src/hooks/useMemoSuggestions.ts
@@ -0,0 +1,11 @@
+import { useMemo } from "react";
+import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { getMemoSuggestions, type MemoSuggestion } from "@/lib/memo-suggestions";
+import { useSelectedMemoViewFilter } from "./useMemoFilters";
+
+/** The same browsing context supplies both inline and full-screen composers. */
+export function useMemoSuggestions(): MemoSuggestion[] {
+ const { filters } = useMemoFilterContext();
+ const viewFilter = useSelectedMemoViewFilter();
+ return useMemo(() => getMemoSuggestions(filters, viewFilter), [filters, viewFilter]);
+}
diff --git a/web/src/lib/context-suggestions.ts b/web/src/lib/context-suggestions.ts
new file mode 100644
index 000000000..5941b1e41
--- /dev/null
+++ b/web/src/lib/context-suggestions.ts
@@ -0,0 +1,110 @@
+import type { MemoFilter } from "@/contexts/MemoFilterContext";
+import type { Visibility } from "@/types/proto/api/v1/memo_service_pb";
+import { VISIBILITY_OPTIONS } from "@/utils/memo";
+import type { MemoSuggestion, SuggestionSource } from "./memo-suggestions";
+import { parseSuggestionExpression, readStringList, type SuggestionExpression, type SuggestionToken } from "./suggestion-expression";
+
+interface ContextConditions {
+ checklist: boolean;
+ excludesChecklist: boolean;
+ audiences: Set<Visibility>;
+ explicitAudiences: Set<Visibility>;
+}
+
+const emptyConditions = (): ContextConditions => ({
+ checklist: false,
+ excludesChecklist: false,
+ audiences: new Set(VISIBILITY_OPTIONS.map((option) => option.value)),
+ explicitAudiences: new Set(),
+});
+
+function readAtom(tokens: SuggestionToken[], negated: boolean): ContextConditions {
+ const result = emptyConditions();
+ const [left, operator, right] = tokens;
+ if (!left) return result;
+ if (["has_task_list", "has_incomplete_tasks"].includes(left.text)) {
+ let positive: boolean;
+ if (tokens.length === 1) positive = true;
+ else if (tokens.length === 3 && ["==", "!="].includes(operator.text) && ["true", "false"].includes(right.text)) {
+ positive = (right.text === "true") === (operator.text === "==");
+ } else return result;
+ result.checklist = positive !== negated;
+ // A new checklist starts unchecked, so a ban on incomplete tasks also excludes it.
+ result.excludesChecklist = !result.checklist;
+ return result;
+ }
+
+ let names: string[] | undefined;
+ let excludes = negated;
+ if (tokens.length === 3 && ["==", "!="].includes(operator.text)) {
+ const name = left.text === "visibility" ? right.value : right.text === "visibility" ? left.value : undefined;
+ if (name === undefined) return result;
+ names = [name];
+ excludes = (operator.text === "!=") !== negated;
+ } else if (left.text === "visibility" && operator?.text === "in") {
+ names = readStringList(tokens.slice(2));
+ }
+ if (!names) return result;
+ const values = new Set(VISIBILITY_OPTIONS.filter((option) => names.includes(option.name)).map((option) => option.value));
+ result.audiences = excludes ? new Set([...result.audiences].filter((value) => !values.has(value))) : values;
+ result.explicitAudiences = excludes ? new Set() : values;
+ return result;
+}
+
+function analyze(expression: SuggestionExpression, negated = false): ContextConditions {
+ if (expression.kind === "not") return analyze(expression.child, !negated);
+ if (expression.kind === "atom") return readAtom(expression.tokens, negated);
+ const left = analyze(expression.left, negated);
+ const right = analyze(expression.right, negated);
+ const conjunction = (expression.kind === "and") !== negated;
+ const excludesChecklist = conjunction
+ ? left.excludesChecklist || right.excludesChecklist
+ : left.excludesChecklist && right.excludesChecklist;
+ return {
+ checklist: (left.checklist || right.checklist) && !excludesChecklist,
+ excludesChecklist,
+ audiences: conjunction
+ ? new Set([...left.audiences].filter((value) => right.audiences.has(value)))
+ : new Set([...left.audiences, ...right.audiences]),
+ explicitAudiences: new Set([...left.explicitAudiences, ...right.explicitAudiences]),
+ };
+}
+
+function readConditions(source: string): ContextConditions {
+ try {
+ const expression = parseSuggestionExpression(source);
+ return expression ? analyze(expression) : emptyConditions();
+ } catch {
+ return emptyConditions();
+ }
+}
+
+/** Checklist and audience providers share the same Boolean reader as tags. */
+export function getContextSuggestionCandidates(filters: MemoFilter[], viewFilter?: string): MemoSuggestion[] {
+ const conditions = filters.flatMap<ContextConditions & { source: SuggestionSource }>((filter) => {
+ if (filter.factor === "celSearch") return [{ ...readConditions(filter.value), source: "search" as const }];
+ if (filter.factor === "visibility") {
+ return [{ ...readConditions(`visibility == ${JSON.stringify(filter.value)}`), source: "selection" as const }];
+ }
+ if (filter.factor === "property.hasTaskList") return [{ ...readConditions("has_task_list"), source: "selection" as const }];
+ return [];
+ });
+ if (viewFilter) conditions.push({ ...readConditions(viewFilter), source: "view" });
+ const candidates: MemoSuggestion[] = [];
+ if (!conditions.some((condition) => condition.excludesChecklist)) {
+ for (const condition of conditions) {
+ if (condition.checklist) candidates.push({ id: "checklist", kind: "checklist", source: condition.source });
+ }
+ }
+ // An audience is one value: alternatives, exclusions alone, and conflicts don't guess.
+ const audiences = VISIBILITY_OPTIONS.filter((option) => conditions.every((condition) => condition.audiences.has(option.value)));
+ if (audiences.length === 1) {
+ const audience = audiences[0];
+ for (const condition of conditions) {
+ if (condition.explicitAudiences.has(audience.value)) {
+ candidates.push({ id: `visibility:${audience.name}`, kind: "visibility", source: condition.source, visibility: audience.value });
+ }
+ }
+ }
+ return candidates;
+}
diff --git a/web/src/lib/memo-suggestions.ts b/web/src/lib/memo-suggestions.ts
new file mode 100644
index 000000000..f2b269348
--- /dev/null
+++ b/web/src/lib/memo-suggestions.ts
@@ -0,0 +1,39 @@
+import { uniqBy } from "lodash-es";
+import type { LucideIcon } from "lucide-react";
+import type { MemoFilter } from "@/contexts/MemoFilterContext";
+import type { Visibility } from "@/types/proto/api/v1/memo_service_pb";
+import { getContextSuggestionCandidates } from "./context-suggestions";
+import { getTagSuggestionCandidates } from "./tag-suggestions";
+
+export type SuggestionSource = "selection" | "search" | "view";
+
+/** Shared presentation contract; the bar does not interpret suggestion payloads. */
+export interface SuggestionItem {
+ id: string;
+ label: string;
+ accessibleLabel?: string;
+ icon?: LucideIcon;
+}
+
+/** Add future suggestion kinds to this discriminated union, with their own payloads. */
+export type MemoSuggestion = {
+ id: string;
+ source: SuggestionSource;
+} & ({ kind: "tag"; tag: string } | { kind: "checklist" } | { kind: "visibility"; visibility: Visibility });
+
+export const MAX_MEMO_SUGGESTIONS = 3;
+
+const sourcePriority: Record<SuggestionSource, number> = { selection: 0, search: 1, view: 2 };
+
+/** Merge providers by context priority and retain the strongest source for each id. */
+export function getMemoSuggestions(filters: MemoFilter[], viewFilter?: string): MemoSuggestion[] {
+ const candidates: MemoSuggestion[] = getTagSuggestionCandidates(filters, viewFilter).map(({ tag, source }) => ({
+ id: `tag:${tag}`,
+ kind: "tag",
+ source,
+ tag,
+ }));
+ candidates.push(...getContextSuggestionCandidates(filters, viewFilter));
+ candidates.sort((left, right) => sourcePriority[left.source] - sourcePriority[right.source]);
+ return uniqBy(candidates, "id");
+}
diff --git a/web/src/lib/suggestion-expression.ts b/web/src/lib/suggestion-expression.ts
new file mode 100644
index 000000000..a83df86ec
--- /dev/null
+++ b/web/src/lib/suggestion-expression.ts
@@ -0,0 +1,109 @@
+export interface SuggestionToken {
+ text: string;
+ value?: string;
+}
+
+export type SuggestionExpression =
+ | { kind: "atom"; tokens: SuggestionToken[] }
+ | { kind: "not"; child: SuggestionExpression }
+ | {
+ kind: "and" | "or";
+ left: SuggestionExpression;
+ right: SuggestionExpression;
+ };
+
+const STRING_ESCAPES: Record<string, string> = { a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v" };
+const BRACKET_PAIRS: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
+// Sticky: lastIndex is set before every exec.
+const LEXER =
+ /\s+|\/\/[^\n]*|"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[a-zA-Z_]\w*|\d+(?:\.\d+)?|&&|\|\||==|!=|<=|>=|[()[\]{},.!<>+*/%?:-]/gy;
+
+function decodeString(text: string): string {
+ return text.slice(1, -1).replace(/\\(u[\da-fA-F]{4}|U[\da-fA-F]{8}|x[\da-fA-F]{2}|[0-7]{3}|.)/g, (_, escaped: string) => {
+ if (/^[uUx]/.test(escaped)) return String.fromCodePoint(Number.parseInt(escaped.slice(1), 16));
+ if (/^[0-7]{3}$/.test(escaped)) return String.fromCodePoint(Number.parseInt(escaped, 8));
+ if (escaped in STRING_ESCAPES) return STRING_ESCAPES[escaped];
+ if (["\\", '"', "'", "?"].includes(escaped)) return escaped;
+ throw new Error("Unsupported string escape");
+ });
+}
+
+/**
+ * A deliberately small CEL reader, not a filter evaluator. Boolean structure is
+ * parsed; calls and other atoms stay opaque for each suggestion provider to interpret.
+ * Unsupported syntax never falls back to searching strings for tag-like text.
+ */
+function parseExpression(source: string): SuggestionExpression {
+ const tokens: SuggestionToken[] = [];
+ let end = 0;
+ while (end < source.length) {
+ LEXER.lastIndex = end;
+ const match = LEXER.exec(source);
+ if (!match) throw new Error("Unsupported token");
+ const text = match[0];
+ end = LEXER.lastIndex;
+ if (/^\s|^\/\//.test(text)) continue;
+ tokens.push({ text, value: /^["']/.test(text) ? decodeString(text) : undefined });
+ }
+ let position = 0;
+ const take = (text: string) => {
+ if (tokens[position]?.text !== text) return false;
+ position++;
+ return true;
+ };
+ const unary = (): SuggestionExpression => {
+ if (take("!")) return { kind: "not", child: unary() };
+ if (take("(")) {
+ const expression = binary("||");
+ if (!take(")")) throw new Error("Unbalanced expression");
+ return expression;
+ }
+ const start = position;
+ const closers: string[] = [];
+ while (position < tokens.length) {
+ const token = tokens[position];
+ if (token.value === undefined) {
+ const text = token.text;
+ if (!closers.length && ["&&", "||", ")"].includes(text)) break;
+ // Ternaries can change the meaning of the surrounding Boolean clauses.
+ if (!closers.length && ["?", ":", ","].includes(text)) throw new Error("Unsupported expression");
+ if (text in BRACKET_PAIRS) closers.push(BRACKET_PAIRS[text]);
+ else if ([")", "]", "}"].includes(text) && closers.pop() !== text) throw new Error("Unbalanced atom");
+ }
+ position++;
+ }
+ if (position === start || closers.length) throw new Error("Incomplete expression");
+ const atom = tokens.slice(start, position);
+ if (/^(?:in|[.!<>=+*/%-]|==|!=|<=|>=)$/.test(atom.at(-1)?.text ?? "")) throw new Error("Incomplete atom");
+ return { kind: "atom", tokens: atom };
+ };
+ const binary = (operator: "&&" | "||"): SuggestionExpression => {
+ const next = () => (operator === "&&" ? unary() : binary("&&"));
+ let expression = next();
+ while (take(operator)) expression = { kind: operator === "&&" ? "and" : "or", left: expression, right: next() };
+ return expression;
+ };
+ const expression = binary("||");
+ if (position !== tokens.length) throw new Error("Unsupported expression suffix");
+ return expression;
+}
+
+/** Invalid or unsupported syntax contributes no inferred conditions. */
+export function parseSuggestionExpression(source: string): SuggestionExpression | undefined {
+ try {
+ return parseExpression(source);
+ } catch {
+ return undefined;
+ }
+}
+
+/** Read a complete list of string literals, allowing CEL's trailing comma. */
+export function readStringList(tokens: SuggestionToken[]): string[] | undefined {
+ if (tokens[0]?.text !== "[" || tokens.at(-1)?.text !== "]") return undefined;
+ const values = tokens.slice(1, -1);
+ if (values.at(-1)?.text === ",") values.pop();
+ if (!values.length) return [];
+ if (values.length % 2 === 0) return undefined;
+ if (values.some((token, index) => (index % 2 === 0 ? token.value === undefined : token.text !== ","))) return undefined;
+ return values.filter((_, index) => index % 2 === 0).map((token) => token.value as string);
+}
diff --git a/web/src/lib/tag-suggestions.ts b/web/src/lib/tag-suggestions.ts
new file mode 100644
index 000000000..3cec1da48
--- /dev/null
+++ b/web/src/lib/tag-suggestions.ts
@@ -0,0 +1,59 @@
+import type { MemoFilter } from "@/contexts/MemoFilterContext";
+import type { SuggestionSource } from "@/lib/memo-suggestions";
+import { isCompleteTagValue } from "@/utils/tag-grammar";
+import { parseSuggestionExpression, readStringList, type SuggestionExpression, type SuggestionToken } from "./suggestion-expression";
+
+interface TagConditions {
+ candidates: string[];
+ excluded: Set<string>;
+}
+
+function literalTags(tokens: SuggestionToken[]): string[] {
+ if (tokens.length === 3 && tokens[0].value !== undefined && tokens[1].text === "in" && tokens[2].text === "tags") {
+ return [tokens[0].value];
+ }
+ if (tokens[0]?.text !== "tag" || tokens[1]?.text !== "in") return [];
+ return readStringList(tokens.slice(2)) ?? [];
+}
+
+function analyze(expression: SuggestionExpression, negated = false): TagConditions {
+ if (expression.kind === "not") return analyze(expression.child, !negated);
+ if (expression.kind === "atom") {
+ const tags = literalTags(expression.tokens);
+ return negated ? { candidates: [], excluded: new Set(tags) } : { candidates: tags, excluded: new Set() };
+ }
+ const left = analyze(expression.left, negated);
+ const right = analyze(expression.right, negated);
+ const conjunction = (expression.kind === "and") !== negated;
+ const excluded = conjunction
+ ? new Set([...left.excluded, ...right.excluded])
+ : new Set([...left.excluded].filter((tag) => right.excluded.has(tag)));
+ return { candidates: [...left.candidates, ...right.candidates].filter((tag) => !excluded.has(tag)), excluded };
+}
+
+export function extractTagConditions(source: string): TagConditions {
+ try {
+ const expression = parseSuggestionExpression(source);
+ if (expression) return analyze(expression);
+ } catch {
+ // Excessively deep Boolean expressions are not useful suggestions.
+ }
+ return { candidates: [], excluded: new Set() };
+}
+
+/** Tag provider: extraction and tag-specific exclusions, without presentation policy. */
+export function getTagSuggestionCandidates(filters: MemoFilter[], viewFilter?: string): { tag: string; source: SuggestionSource }[] {
+ const conditions = [
+ ...filters
+ .filter((filter) => filter.factor === "celSearch")
+ .map((filter) => ({ source: "search" as const, ...extractTagConditions(filter.value) })),
+ ...(viewFilter ? [{ source: "view" as const, ...extractTagConditions(viewFilter) }] : []),
+ ];
+ const excluded = new Set(conditions.flatMap((condition) => [...condition.excluded]));
+ // Emission order is priority order: explicit selection, then search, then the saved View.
+ const candidates = [
+ ...filters.filter((filter) => filter.factor === "tagSearch").map((filter) => ({ tag: filter.value, source: "selection" as const })),
+ ...conditions.flatMap((condition) => condition.candidates.map((tag) => ({ tag, source: condition.source }))),
+ ];
+ return candidates.filter(({ tag }) => !excluded.has(tag) && isCompleteTagValue(tag));
+}
diff --git a/web/src/locales/ar.json b/web/src/locales/ar.json
index 9d6564392..ae605348c 100644
--- a/web/src/locales/ar.json
+++ b/web/src/locales/ar.json
@@ -141,6 +141,7 @@
"no-language-feedback": "لم يتم العثور على اللغة؟ إرسال ردود الفعل"
},
"editor": {
+ "suggestions": "اقتراحات",
"add-your-comment-here": "أضف تعليقك هنا...",
"any-thoughts": "أية أفكار...",
"exit-focus-mode": "الخروج من وضع التركيز",
diff --git a/web/src/locales/az.json b/web/src/locales/az.json
index a0780ff72..ee6073bbf 100644
--- a/web/src/locales/az.json
+++ b/web/src/locales/az.json
@@ -237,6 +237,7 @@
"no-language-feedback": "Dil tapılmadı? Rəy göndərin"
},
"editor": {
+ "suggestions": "Təkliflər",
"add-your-comment-here": "Şərhinizi bura yazın...",
"any-thoughts": "Ağlınıza nə gəlir...",
"exit-focus-mode": "Fokus rejimindən çıx",
diff --git a/web/src/locales/bg.json b/web/src/locales/bg.json
index d731784e2..0deac9629 100644
--- a/web/src/locales/bg.json
+++ b/web/src/locales/bg.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Езикът не е намерен? Изпратете обратна връзка"
},
"editor": {
+ "suggestions": "Предложения",
"add-your-comment-here": "Добавете своя коментар тук...",
"any-thoughts": "Някакви мисли...",
"exit-focus-mode": "Излезте от режима на фокусиране",
diff --git a/web/src/locales/ca.json b/web/src/locales/ca.json
index 72a325ce3..34479b256 100644
--- a/web/src/locales/ca.json
+++ b/web/src/locales/ca.json
@@ -141,6 +141,7 @@
"no-language-feedback": "No s'ha trobat l'idioma? Envieu comentaris"
},
"editor": {
+ "suggestions": "Suggeriments",
"add-your-comment-here": "Afegeix el teu comentari aquí...",
"any-thoughts": "Alguna idea...",
"exit-focus-mode": "Surt del mode focus",
diff --git a/web/src/locales/cs.json b/web/src/locales/cs.json
index d747efa04..515e25874 100644
--- a/web/src/locales/cs.json
+++ b/web/src/locales/cs.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Jazyk nenalezen? Odeslat zpětnou vazbu"
},
"editor": {
+ "suggestions": "Návrhy",
"add-your-comment-here": "Přidejte sem svůj komentář...",
"any-thoughts": "Jakékoli myšlenky...",
"exit-focus-mode": "Ukončit režim soustředění",
diff --git a/web/src/locales/da.json b/web/src/locales/da.json
index c9495c68d..92647cb18 100644
--- a/web/src/locales/da.json
+++ b/web/src/locales/da.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Sprog ikke fundet? Send feedback"
},
"editor": {
+ "suggestions": "Forslag",
"add-your-comment-here": "Tilføj din kommentar her...",
"any-thoughts": "Nogen tanker...",
"exit-focus-mode": "Afslut fokustilstand",
diff --git a/web/src/locales/de.json b/web/src/locales/de.json
index b92a46bfc..b508d576c 100644
--- a/web/src/locales/de.json
+++ b/web/src/locales/de.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Sprache nicht gefunden? Geben Sie Feedback ab"
},
"editor": {
+ "suggestions": "Vorschläge",
"add-your-comment-here": "Füge deinen Kommentar hinzu...",
"any-thoughts": "Ein Gedanke...",
"exit-focus-mode": "Fokus Modus verlassen",
diff --git a/web/src/locales/el.json b/web/src/locales/el.json
index 2ac847284..cf7b97142 100644
--- a/web/src/locales/el.json
+++ b/web/src/locales/el.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Δεν βρέθηκε η γλώσσα; Υποβολή σχολίων"
},
"editor": {
+ "suggestions": "Προτάσεις",
"add-your-comment-here": "Προσθέστε το σχόλιό σας εδώ...",
"any-thoughts": "Οποιαδήποτε σκέψη...",
"exit-focus-mode": "Έξοδος από τη λειτουργία εστίασης",
diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.json
index 84c14e299..e88cee72d 100644
--- a/web/src/locales/en-GB.json
+++ b/web/src/locales/en-GB.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Language not found? Submit feedback"
},
"editor": {
+ "suggestions": "Suggestions",
"add-your-comment-here": "Add your comment here...",
"any-thoughts": "Any thoughts...",
"exit-focus-mode": "Exit Focus Mode",
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index 449257321..6086045bc 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -237,6 +237,7 @@
"no-language-feedback": "Language not found? Submit feedback"
},
"editor": {
+ "suggestions": "Suggestions",
"add-your-comment-here": "Add your comment here...",
"any-thoughts": "Any thoughts...",
"exit-focus-mode": "Exit Focus Mode",
diff --git a/web/src/locales/es.json b/web/src/locales/es.json
index b1b35c18b..32807db2a 100644
--- a/web/src/locales/es.json
+++ b/web/src/locales/es.json
@@ -141,6 +141,7 @@
"no-language-feedback": "¿Idioma no encontrado? Enviar comentarios"
},
"editor": {
+ "suggestions": "Sugerencias",
"add-your-comment-here": "Agrega tu comentario aquí...",
"any-thoughts": "Alguna idea...",
"exit-focus-mode": "Salir del modo enfoque",
diff --git a/web/src/locales/et.json b/web/src/locales/et.json
index 12fadc6ba..de3eae78a 100644
--- a/web/src/locales/et.json
+++ b/web/src/locales/et.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Keelt ei leitud? Esitage tagasisidet"
},
"editor": {
+ "suggestions": "Soovitused",
"add-your-comment-here": "Lisa oma kommentaar siia...",
"any-thoughts": "Mingid mõtted...",
"exit-focus-mode": "Välju teravustamisrežiimist",
diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json
index 01659f453..2c487de8c 100644
--- a/web/src/locales/fa.json
+++ b/web/src/locales/fa.json
@@ -141,6 +141,7 @@
"no-language-feedback": "زبان پیدا نشد؟ ارسال بازخورد"
},
"editor": {
+ "suggestions": "پیشنهادها",
"add-your-comment-here": "نظر خود را اینجا اضافه کنید...",
"any-thoughts": "فکر شما...",
"exit-focus-mode": "خروج از حالت تمرکز",
diff --git a/web/src/locales/fi.json b/web/src/locales/fi.json
index a1efe4a42..8a91235c2 100644
--- a/web/src/locales/fi.json
+++ b/web/src/locales/fi.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Eikö kieltä löydy? Lähetä palautetta"
},
"editor": {
+ "suggestions": "Ehdotukset",
"add-your-comment-here": "Lisää kommenttisi tähän...",
"any-thoughts": "Mitään ajatuksia...",
"exit-focus-mode": "Poistu tarkennustilasta",
diff --git a/web/src/locales/fr.json b/web/src/locales/fr.json
index 1e7b356e7..08c7305d9 100644
--- a/web/src/locales/fr.json
+++ b/web/src/locales/fr.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Langue introuvable ? Soumettre des commentaires"
},
"editor": {
+ "suggestions": "Suggestions",
"add-your-comment-here": "Ajoutez votre commentaire ici...",
"any-thoughts": "Des idées...",
"exit-focus-mode": "Quitter le mode concentration",
diff --git a/web/src/locales/gl.json b/web/src/locales/gl.json
index 3b6cc8d56..bb4968017 100644
--- a/web/src/locales/gl.json
+++ b/web/src/locales/gl.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Non se atopou o idioma? Enviar comentarios"
},
"editor": {
+ "suggestions": "Suxestións",
"add-your-comment-here": "Engade aquí o comentario...",
"any-thoughts": "O que pensas...",
"exit-focus-mode": "Saír do modo sen distraccións",
diff --git a/web/src/locales/he.json b/web/src/locales/he.json
index 4e0624cac..576554787 100644
--- a/web/src/locales/he.json
+++ b/web/src/locales/he.json
@@ -212,6 +212,7 @@
"no-language-feedback": "לא מצאתם את השפה? שלחו משוב"
},
"editor": {
+ "suggestions": "הצעות",
"add-your-comment-here": "הוסיפו את התגובה שלכם כאן...",
"any-thoughts": "יש מחשבות...",
"exit-focus-mode": "יציאה ממצב מיקוד",
diff --git a/web/src/locales/hi.json b/web/src/locales/hi.json
index 2366c60a0..2d6a951c3 100644
--- a/web/src/locales/hi.json
+++ b/web/src/locales/hi.json
@@ -141,6 +141,7 @@
"no-language-feedback": "भाषा नहीं मिली? प्रतिक्रिया सबमिट करें"
},
"editor": {
+ "suggestions": "सुझाव",
"add-your-comment-here": "अपनी टिप्पणी यहाँ जोड़ें...",
"any-thoughts": "कोई विचार...",
"exit-focus-mode": "फोकस मोड से बाहर निकलें",
diff --git a/web/src/locales/hr.json b/web/src/locales/hr.json
index 973d7bb3c..7d36c76e1 100644
--- a/web/src/locales/hr.json
+++ b/web/src/locales/hr.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Jezik nije pronađen? Pošaljite povratne informacije"
},
"editor": {
+ "suggestions": "Prijedlozi",
"add-your-comment-here": "Dodaj svoj komentar ovdje...",
"any-thoughts": "Imaš li misli...",
"exit-focus-mode": "Izlazi iz načina rada za fokus",
diff --git a/web/src/locales/hu.json b/web/src/locales/hu.json
index 2e69cc930..f62ac3102 100644
--- a/web/src/locales/hu.json
+++ b/web/src/locales/hu.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Nem található a nyelv? Visszajelzés küldése"
},
"editor": {
+ "suggestions": "Javaslatok",
"add-your-comment-here": "Írd ide a megjegyzésed...",
"any-thoughts": "Bármi ami a fejedben jár...",
"exit-focus-mode": "Kilépés a fókusz módból",
diff --git a/web/src/locales/id.json b/web/src/locales/id.json
index c48c5f5eb..2f04e1f9e 100644
--- a/web/src/locales/id.json
+++ b/web/src/locales/id.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Bahasa tidak ditemukan? Kirim masukan"
},
"editor": {
+ "suggestions": "Saran",
"add-your-comment-here": "Tambahkan komentar Anda di sini...",
"any-thoughts": "Punya pemikiran...",
"exit-focus-mode": "Keluar dari Mode Fokus",
diff --git a/web/src/locales/it.json b/web/src/locales/it.json
index 667478777..24cde662b 100644
--- a/web/src/locales/it.json
+++ b/web/src/locales/it.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Lingua non trovata? Invia feedback"
},
"editor": {
+ "suggestions": "Suggerimenti",
"add-your-comment-here": "Aggiungi qui il tuo commento...",
"any-thoughts": "Qualsiasi cosa pensi...",
"exit-focus-mode": "Esci Modalità Focus",
diff --git a/web/src/locales/ja.json b/web/src/locales/ja.json
index bd1d8243d..609e18800 100644
--- a/web/src/locales/ja.json
+++ b/web/src/locales/ja.json
@@ -141,6 +141,7 @@
"no-language-feedback": "言語が見つかりませんか? フィードバックを送信する"
},
"editor": {
+ "suggestions": "候補",
"add-your-comment-here": "ここにコメントを追加...",
"any-thoughts": "今思ったことは...",
"exit-focus-mode": "フォーカスを終了",
diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.json
index f4411c870..d9e3f3fcb 100644
--- a/web/src/locales/ka-GE.json
+++ b/web/src/locales/ka-GE.json
@@ -141,6 +141,7 @@
"no-language-feedback": "ენა ვერ მოიძებნა? გამოხმაურება"
},
"editor": {
+ "suggestions": "შემოთავაზებები",
"add-your-comment-here": "დაამატეთ თქვენი კომენტარი აქ...",
"any-thoughts": "რამე იდეები...",
"exit-focus-mode": "ფოკუსის რეჟიმიდან გასვლა",
diff --git a/web/src/locales/ko.json b/web/src/locales/ko.json
index a8cd5a2c5..120a9d6fa 100644
--- a/web/src/locales/ko.json
+++ b/web/src/locales/ko.json
@@ -141,6 +141,7 @@
"no-language-feedback": "언어를 찾을 수 없나요? 피드백 제출"
},
"editor": {
+ "suggestions": "제안",
"add-your-comment-here": "여기에 댓글을 추가하세요...",
"any-thoughts": "떠오르는 게 있나요...",
"exit-focus-mode": "집중 모드 종료",
diff --git a/web/src/locales/lt.json b/web/src/locales/lt.json
index aad84b237..262a28d45 100644
--- a/web/src/locales/lt.json
+++ b/web/src/locales/lt.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Kalba nerasta? Pateikite atsiliepimą"
},
"editor": {
+ "suggestions": "Pasiūlymai",
"add-your-comment-here": "Pridėkite savo komentarą čia...",
"any-thoughts": "Bet kokios mintys...",
"exit-focus-mode": "Išeikite iš fokusavimo režimo",
diff --git a/web/src/locales/lv.json b/web/src/locales/lv.json
index ce808841c..e1ea84b50 100644
--- a/web/src/locales/lv.json
+++ b/web/src/locales/lv.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Valoda nav atrasta? Iesniedziet atsauksmes"
},
"editor": {
+ "suggestions": "Ieteikumi",
"add-your-comment-here": "Pievienojiet savu komentāru šeit...",
"any-thoughts": "Jebkuras domas...",
"exit-focus-mode": "Iziet no fokusa režīma",
diff --git a/web/src/locales/mr.json b/web/src/locales/mr.json
index 9eb3083e2..5eeb9f75b 100644
--- a/web/src/locales/mr.json
+++ b/web/src/locales/mr.json
@@ -141,6 +141,7 @@
"no-language-feedback": "भाषा सापडली नाही? अभिप्राय सबमिट करा"
},
"editor": {
+ "suggestions": "सूचना",
"add-your-comment-here": "तुमची टिप्पणी येथे जो़डा",
"any-thoughts": "आपले विचार...",
"exit-focus-mode": "फोकस मोड सोडा",
diff --git a/web/src/locales/nb.json b/web/src/locales/nb.json
index 6e35ba430..205a8fdb6 100644
--- a/web/src/locales/nb.json
+++ b/web/src/locales/nb.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Finner du ikke språket? Send tilbakemelding"
},
"editor": {
+ "suggestions": "Forslag",
"add-your-comment-here": "Legg til din kommentar her...",
"any-thoughts": "Noen tanker...",
"exit-focus-mode": "Avslutt fokusmodus",
diff --git a/web/src/locales/nl.json b/web/src/locales/nl.json
index d3efa6145..9c065f0c8 100644
--- a/web/src/locales/nl.json
+++ b/web/src/locales/nl.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Taal niet gevonden? Geef feedback"
},
"editor": {
+ "suggestions": "Suggesties",
"add-your-comment-here": "Voeg hier je opmerking toe…",
"any-thoughts": "Enkele gedachten…",
"exit-focus-mode": "Focusmodus afsluiten",
diff --git a/web/src/locales/pl.json b/web/src/locales/pl.json
index 63e031576..4494b6eb3 100644
--- a/web/src/locales/pl.json
+++ b/web/src/locales/pl.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Nie znaleziono języka? Prześlij opinię"
},
"editor": {
+ "suggestions": "Sugestie",
"add-your-comment-here": "Dodaj swój komentarz tutaj...",
"any-thoughts": "Jakieś przemyślenia...",
"exit-focus-mode": "Wyjdź z Trybu Skupienia",
diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.json
index 35eed2c32..0b9aa9c24 100644
--- a/web/src/locales/pt-BR.json
+++ b/web/src/locales/pt-BR.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Idioma não encontrado? Enviar comentários"
},
"editor": {
+ "suggestions": "Sugestões",
"add-your-comment-here": "Adicione seu comentário aqui…",
"any-thoughts": "Alguma ideia…",
"exit-focus-mode": "Sair do Modo Foco",
diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.json
index 8fc7bb937..a072df795 100644
--- a/web/src/locales/pt-PT.json
+++ b/web/src/locales/pt-PT.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Idioma não encontrado? Enviar comentários"
},
"editor": {
+ "suggestions": "Sugestões",
"add-your-comment-here": "Adicione o seu comentário aqui...",
"any-thoughts": "Alguma ideia…",
"exit-focus-mode": "Sair do Modo Foco",
diff --git a/web/src/locales/ro.json b/web/src/locales/ro.json
index 94c94f0f6..a19990d46 100644
--- a/web/src/locales/ro.json
+++ b/web/src/locales/ro.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Limba nu a fost găsită? Trimiteți feedback"
},
"editor": {
+ "suggestions": "Sugestii",
"add-your-comment-here": "Adauga comentariul tau aici...",
"any-thoughts": "Orice gânduri...",
"exit-focus-mode": "Ieșiți din modul de focalizare",
diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json
index 59d305b9e..e21bce837 100644
--- a/web/src/locales/ru.json
+++ b/web/src/locales/ru.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Язык не найден? Отправить отзыв"
},
"editor": {
+ "suggestions": "Предложения",
"add-your-comment-here": "Напишите свой комментарий...",
"any-thoughts": "Напишите что-нибудь...",
"exit-focus-mode": "Выйти из режима фокуса",
diff --git a/web/src/locales/sk.json b/web/src/locales/sk.json
index 5c4922075..966d1f7a3 100644
--- a/web/src/locales/sk.json
+++ b/web/src/locales/sk.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Jazyk sa nenašiel? Odoslať spätnú väzbu"
},
"editor": {
+ "suggestions": "Návrhy",
"add-your-comment-here": "Tu pridajte svoj komentár...",
"any-thoughts": "Akékoľvek myšlienky...",
"exit-focus-mode": "Ukončite režim zaostrenia",
diff --git a/web/src/locales/sl.json b/web/src/locales/sl.json
index 71694b18b..3d7e31aad 100644
--- a/web/src/locales/sl.json
+++ b/web/src/locales/sl.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Jezik ni bil najden? Pošlji povratne informacije"
},
"editor": {
+ "suggestions": "Predlogi",
"add-your-comment-here": "Tu dodaj svoj komentar...",
"any-thoughts": "Kakšne misli...",
"exit-focus-mode": "Izhod iz načina osredotočanja",
diff --git a/web/src/locales/sr.json b/web/src/locales/sr.json
index 32f6488bf..2555be3c0 100644
--- a/web/src/locales/sr.json
+++ b/web/src/locales/sr.json
@@ -179,6 +179,7 @@
"no-language-feedback": "Језик није пронађен? Пошаљите повратне информације"
},
"editor": {
+ "suggestions": "Предлози",
"add-your-comment-here": "Додајте свој коментар овде...",
"any-thoughts": "Било каква размишљања...",
"exit-focus-mode": "Изађите из режима фокуса",
diff --git a/web/src/locales/sv.json b/web/src/locales/sv.json
index fde20e4b9..6b68209e8 100644
--- a/web/src/locales/sv.json
+++ b/web/src/locales/sv.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Språket hittades inte? Skicka feedback"
},
"editor": {
+ "suggestions": "Förslag",
"add-your-comment-here": "Lägg till din kommentar här...",
"any-thoughts": "Några tankar...",
"exit-focus-mode": "Avsluta fokusläge",
diff --git a/web/src/locales/th.json b/web/src/locales/th.json
index 0ab77d0f8..608c280a4 100644
--- a/web/src/locales/th.json
+++ b/web/src/locales/th.json
@@ -141,6 +141,7 @@
"no-language-feedback": "ไม่พบภาษา? ส่งข้อเสนอแนะ"
},
"editor": {
+ "suggestions": "คำแนะนำ",
"add-your-comment-here": "เพิ่มความคิดเห็นของคุณที่นี่...",
"any-thoughts": "ความคิดใดๆ...",
"exit-focus-mode": "ออกจากโหมดโฟกัส",
diff --git a/web/src/locales/tr.json b/web/src/locales/tr.json
index 17ed687ee..24488b503 100644
--- a/web/src/locales/tr.json
+++ b/web/src/locales/tr.json
@@ -166,6 +166,7 @@
"no-language-feedback": "Dil bulunamadı mı? Geri bildirim gönder"
},
"editor": {
+ "suggestions": "Öneriler",
"add-your-comment-here": "Yorumunuzu buraya ekleyin...",
"any-thoughts": "Düşünceleriniz...",
"exit-focus-mode": "Odak modundan çık",
diff --git a/web/src/locales/uk.json b/web/src/locales/uk.json
index 211d3c992..33f01a540 100644
--- a/web/src/locales/uk.json
+++ b/web/src/locales/uk.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Мова не знайдена? Надіслати відгук"
},
"editor": {
+ "suggestions": "Пропозиції",
"add-your-comment-here": "Додайте свій коментар тут...",
"any-thoughts": "Якісь думки...",
"exit-focus-mode": "Вийти з режиму фокусування",
diff --git a/web/src/locales/vi.json b/web/src/locales/vi.json
index 2e32aac35..eb992b0fe 100644
--- a/web/src/locales/vi.json
+++ b/web/src/locales/vi.json
@@ -141,6 +141,7 @@
"no-language-feedback": "Không tìm thấy ngôn ngữ? Gửi phản hồi"
},
"editor": {
+ "suggestions": "Gợi ý",
"add-your-comment-here": "Thêm bình luận của bạn tại đây...",
"any-thoughts": "Có suy nghĩ gì...",
"exit-focus-mode": "Thoát chế độ tập trung",
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index 3dfa3390e..2a60892f3 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -171,6 +171,7 @@
"no-language-feedback": "未找到语言? 提交反馈"
},
"editor": {
+ "suggestions": "建议",
"add-your-comment-here": "请输入您的评论...",
"any-thoughts": "此刻的想法...",
"exit-focus-mode": "退出聚焦模式",
diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.json
index 450a2454e..0e5d267a4 100644
--- a/web/src/locales/zh-Hant.json
+++ b/web/src/locales/zh-Hant.json
@@ -219,6 +219,7 @@
"no-language-feedback": "未找到語言? 提交回饋"
},
"editor": {
+ "suggestions": "建議",
"add-your-comment-here": "在這裡添加您的評論...",
"any-thoughts": "任何想法...",
"exit-focus-mode": "退出專注模式",
diff --git a/web/src/pages/Home.tsx b/web/src/pages/Home.tsx
index 4a0d4b7e2..4d4abade9 100644
--- a/web/src/pages/Home.tsx
+++ b/web/src/pages/Home.tsx
@@ -10,6 +10,7 @@ import { NewMemoProvider } from "@/contexts/NewMemoContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useMemoFilters, useMemoSorting } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
+import { useMemoSuggestions } from "@/hooks/useMemoSuggestions";
import { spaceScopedCacheKey } from "@/lib/resource-names";
import { State } from "@/types/proto/api/v1/common_pb";
import { Memo } from "@/types/proto/api/v1/memo_service_pb";
@@ -17,6 +18,7 @@ import { useTranslate } from "@/utils/i18n";
const Home = () => {
const user = useCurrentUser();
+ const suggestions = useMemoSuggestions();
const t = useTranslate();
const { isUserSettingsInitialized } = useAuth();
const { claimHomeAutoFocus } = useGlobalMemoEditor();
@@ -61,6 +63,7 @@ const Home = () => {
placeholder={t("editor.any-thoughts")}
defaultCreateTime={defaultCreateTime}
defaultSpace={selectedSpaceName}
+ suggestions={suggestions}
/>
);
}}
diff --git a/web/src/utils/tag-grammar.ts b/web/src/utils/tag-grammar.ts
index 651663967..e1ff19471 100644
--- a/web/src/utils/tag-grammar.ts
+++ b/web/src/utils/tag-grammar.ts
@@ -224,3 +224,9 @@ export function findTagMatches(source: string, from = 0, limit = source.length):
return matches;
}
+
+/** Whether `value` written as `#value` scans as exactly one complete tag with nothing left over. */
+export function isCompleteTagValue(value: string): boolean {
+ const match = scanTagAt(`#${value}`, 0);
+ return match?.value === value && match.to === value.length + 1;
+}
diff --git a/web/tests/editor-controller.test.ts b/web/tests/editor-controller.test.ts
index da2db5707..1a4eea61c 100644
--- a/web/tests/editor-controller.test.ts
+++ b/web/tests/editor-controller.test.ts
@@ -1,7 +1,10 @@
+import { history, redo, undo } from "@codemirror/commands";
+import { markdown } from "@codemirror/lang-markdown";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { describe, expect, it } from "vitest";
import { createController } from "@/components/MemoEditor/Editor/controller";
+import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
function view(doc = "") {
return new EditorView({ state: EditorState.create({ doc }) });
@@ -41,3 +44,95 @@ describe("source editor controller", () => {
expect(c.getCursor()).toBe(10);
});
});
+
+function setup(doc: string) {
+ const v = new EditorView({
+ state: EditorState.create({ doc, extensions: [markdown({ extensions: memoMarkdownExtensions }), history()] }),
+ });
+ return { v, c: createController(v, {} as never) };
+}
+
+describe("suggested tag insertion", () => {
+ it("inserts an undoable tag at the selection head without replacing highlighted text", () => {
+ const { v, c } = setup("alpha beta");
+ v.dispatch({ selection: { anchor: 1, head: 5 } });
+ expect(c.insertTag("work")).toBe(true);
+ expect(c.getMarkdown()).toBe("alpha #work beta");
+ expect(v.state.selection.main).toMatchObject({ anchor: 12, head: 12 });
+ expect(c.getTags()).toEqual(["work"]);
+ expect(undo(v)).toBe(true);
+ expect(c.getMarkdown()).toBe("alpha beta");
+ expect(redo(v)).toBe(true);
+ expect(c.getTags()).toEqual(["work"]);
+ v.destroy();
+ });
+
+ it("inserts successive tags at the caret and isolates each click in history", () => {
+ const { v, c } = setup("A note\n\n#work");
+ c.setCursor(c.getMarkdown().length);
+ c.insertTag("release");
+ c.insertTag("planning");
+ expect(c.getMarkdown()).toBe("A note\n\n#work #release #planning ");
+ undo(v);
+ expect(c.getMarkdown()).toBe("A note\n\n#work #release ");
+ v.destroy();
+ });
+
+ it.each([
+ ["", 0, "#work ", 6],
+ ["alpha beta", 0, "#work alpha beta", 6],
+ ["alpha beta", 6, "alpha #work beta", 12],
+ ["alphabeta", 5, "alpha #work beta", 12],
+ ["alpha\nnext", 5, "alpha #work \nnext", 12],
+ ["alpha beta", 10, "alpha beta #work ", 17],
+ ])("inserts inline at position %s / %i with natural spacing", (doc, cursor, expected, nextCursor) => {
+ const { v, c } = setup(doc);
+ c.setCursor(cursor);
+ c.insertTag("work");
+ expect(c.getMarkdown()).toBe(expected);
+ expect(c.getCursor()).toBe(nextCursor);
+ v.destroy();
+ });
+
+ it("honors a cursor inside an unfinished code block instead of moving the tag elsewhere", () => {
+ const doc = "```js\nconst x = 1";
+ const { v, c } = setup(doc);
+ c.setCursor(doc.length);
+ expect(c.insertTag("work")).toBe(true);
+ expect(c.getMarkdown()).toBe(`${doc} #work `);
+ expect(c.getTags()).toEqual([]);
+ undo(v);
+ expect(c.getMarkdown()).toBe(doc);
+ v.destroy();
+ });
+
+ it("recognizes actual tags, excluding code, links, URLs, escapes, and nested parent names", () => {
+ const { v, c } = setup("`#work` [#work](/url) https://example.com/#work \\#work\n\n#work/project");
+ expect(c.getTags()).toEqual(["work/project"]);
+ c.setCursor(c.getMarkdown().length);
+ expect(c.insertTag("work")).toBe(true);
+ expect(c.insertTag("work")).toBe(false);
+ expect(c.insertTag("two words")).toBe(false);
+ expect(c.getTags()).toEqual(["work/project", "work"]);
+ v.destroy();
+ });
+});
+
+describe("checklist detection", () => {
+ it.each([
+ ["- [ ] Task", true],
+ ["- [X] Done", true],
+ ["- Parent\n - [ ] Nested", true],
+ ["Note\n\n- [x] Done", true],
+ ["```\n- [ ] Example\n```", false],
+ ["`- [ ] Example`", false],
+ [" - [ ] Indented code", false],
+ ["\\- [ ] Escaped", false],
+ ["<pre>\n- [ ] HTML\n</pre>", false],
+ ["- Plain list", false],
+ ])("recognizes rendered tasks in %s", (doc, expected) => {
+ const { v, c } = setup(doc);
+ expect(c.hasChecklist()).toBe(expected);
+ v.destroy();
+ });
+});
diff --git a/web/tests/editor-suggestions.test.tsx b/web/tests/editor-suggestions.test.tsx
new file mode 100644
index 000000000..c6645bba6
--- /dev/null
+++ b/web/tests/editor-suggestions.test.tsx
@@ -0,0 +1,211 @@
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { useRef } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { EditorContent } from "@/components/MemoEditor/components/EditorContent";
+import { EditorSuggestions, SuggestionsBar } from "@/components/MemoEditor/components/EditorSuggestions";
+import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import type { EditorController } from "@/components/MemoEditor/types/editorController";
+import { getMemoSuggestions, type MemoSuggestion } from "@/lib/memo-suggestions";
+import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
+
+vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
+vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }) }));
+
+let editor: ReturnType<typeof useEditorContext>;
+let controller: React.RefObject<EditorController | null>;
+const candidates = getMemoSuggestions(["work", "release", "planning", "later"].map((value) => ({ factor: "tagSearch", value })));
+
+function Harness({ suggestions, space }: { suggestions: MemoSuggestion[]; space?: string }) {
+ editor = useEditorContext();
+ controller = useRef<EditorController>(null);
+ return (
+ <>
+ <EditorContent ref={controller} onSubmit={vi.fn()} onFiles={vi.fn()} />
+ <EditorSuggestions suggestions={suggestions} controllerRef={controller} space={space} />
+ </>
+ );
+}
+
+function composer(suggestions = candidates, content = "A note", space?: string) {
+ return (
+ <EditorProvider initialEditorState={{ ...createInitialState(), content }}>
+ <Harness suggestions={suggestions} space={space} />
+ </EditorProvider>
+ );
+}
+
+describe("editor suggestions", () => {
+ it.each(["", " \n\t "])("shows suggestions only after writing content, and hides them when cleared: %j", (content) => {
+ render(composer(candidates, content));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => controller.current?.setMarkdown("A thought"));
+ expect(screen.getByRole("group", { name: "editor.suggestions" })).toBeInTheDocument();
+ act(() => controller.current?.setMarkdown(content));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ });
+
+ it("uses a payload-agnostic bar with dashed buttons", () => {
+ const onAccept = vi.fn();
+ render(<SuggestionsBar suggestions={[{ id: "future:example", label: "Example" }]} disabled={false} onAccept={onAccept} />);
+ const chip = screen.getByRole("button", { name: "Example" });
+ expect(chip).toHaveClass("border-dashed");
+ fireEvent.click(chip);
+ expect(onAccept).toHaveBeenCalledWith("future:example");
+ });
+
+ it("shows at most three and fills the vacated slot after acceptance", () => {
+ render(composer());
+ expect(screen.getAllByRole("button")).toHaveLength(3);
+ expect(screen.queryByRole("button", { name: "common.add #later" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "common.add #work" }));
+ expect(editor.getState().content).toBe("#work A note");
+ expect(screen.queryByRole("button", { name: "common.add #work" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "common.add #later" })).toBeInTheDocument();
+ expect(controller.current?.hasFocus()).toBe(true);
+ });
+
+ it("inserts at the remembered caret when a chip takes focus", () => {
+ render(composer(candidates, "Before after"));
+ act(() => controller.current?.setCursor(7));
+ const chip = screen.getByRole("button", { name: "common.add #work" });
+ act(() => chip.focus());
+ fireEvent.click(chip);
+ expect(editor.getState().content).toBe("Before #work after");
+ expect(controller.current?.getCursor()).toBe(13);
+ expect(controller.current?.hasFocus()).toBe(true);
+ });
+
+ it("hides tags in restored and manually edited content, but not inside code", () => {
+ render(composer(candidates, "#work\n\n`#release`"));
+ expect(screen.queryByRole("button", { name: "common.add #work" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "common.add #release" })).toBeInTheDocument();
+ act(() => controller.current?.setMarkdown("#work #release"));
+ expect(screen.queryByRole("button", { name: "common.add #release" })).not.toBeInTheDocument();
+ });
+
+ it("retains acceptance across removal and context changes, then clears it for a fresh draft", () => {
+ const result = render(composer());
+ fireEvent.click(screen.getByRole("button", { name: "common.add #work" }));
+ act(() => controller.current?.setMarkdown("A note"));
+ result.rerender(composer([candidates[0]]));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ expect(controller.current?.getMarkdown()).toBe("A note");
+ act(() => editor.dispatch(editor.actions.reset()));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => controller.current?.setMarkdown("A fresh thought"));
+ expect(screen.getByRole("button", { name: "common.add #work" })).toBeInTheDocument();
+ });
+
+ it("leaves accepted text intact when context changes and prevents insertion during save", () => {
+ const result = render(composer());
+ fireEvent.click(screen.getByRole("button", { name: "common.add #work" }));
+ result.rerender(composer([candidates[1]]));
+ expect(controller.current?.getMarkdown()).toBe("#work A note");
+ act(() => editor.dispatch(editor.actions.setLoading("saving", true)));
+ const chip = screen.getByRole("button", { name: "common.add #release" });
+ expect(chip).toBeDisabled();
+ fireEvent.click(chip);
+ expect(controller.current?.getMarkdown()).toBe("#work A note");
+ });
+
+ it("hides the whole row when nothing applies", () => {
+ render(composer([], "A note"));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ });
+});
+
+const checklist: MemoSuggestion = { id: "checklist", kind: "checklist", source: "view" };
+const publicAudience: MemoSuggestion = { id: "visibility:PUBLIC", kind: "visibility", visibility: Visibility.PUBLIC, source: "view" };
+const spaceAudience: MemoSuggestion = { id: "visibility:SPACE", kind: "visibility", visibility: Visibility.SPACE, source: "view" };
+
+describe("checklist and visibility acceptance", () => {
+ it("formats the remembered cursor line and retains acceptance after removal", () => {
+ render(composer([checklist], "First\nSecond"));
+ act(() => controller.current?.setCursor(8));
+ const chip = screen.getByRole("button", { name: "editor.format.task-list" });
+ act(() => chip.focus());
+ fireEvent.click(chip);
+ expect(editor.getState().content).toBe("First\n- [ ] Second");
+ expect(controller.current?.hasFocus()).toBe(true);
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => controller.current?.setMarkdown("First\nSecond"));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => editor.dispatch(editor.actions.reset()));
+ act(() => controller.current?.setMarkdown("Fresh thought"));
+ expect(screen.getByRole("button", { name: "editor.format.task-list" })).toBeInTheDocument();
+ });
+
+ it("converts selected lines while preserving their text", () => {
+ render(composer([checklist], "First\n- Second"));
+ act(() => controller.current?.selectAll());
+ fireEvent.click(screen.getByRole("button", { name: "editor.format.task-list" }));
+ expect(editor.getState().content).toBe("- [ ] First\n- [ ] Second");
+ });
+
+ it.each(["- [ ] Task", "- [x] Done", "- Parent\n - [ ] Nested"])("hides an existing checklist: %s", (content) => {
+ render(composer([checklist], content));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => controller.current?.setMarkdown("A note"));
+ expect(screen.getByRole("button", { name: "editor.format.task-list" })).toBeInTheDocument();
+ });
+
+ it("ignores checklist syntax inside code and reacts to manual insertion", () => {
+ render(composer([checklist], "```\n- [ ] Example\n```"));
+ expect(screen.getByRole("button", { name: "editor.format.task-list" })).toBeInTheDocument();
+ act(() => controller.current?.setMarkdown("- [ ] Real task"));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ });
+
+ it("changes visibility only on acceptance, keeps text intact, and remembers the choice", () => {
+ render(composer([publicAudience]));
+ expect(editor.getState().metadata.visibility).toBe(Visibility.PRIVATE);
+ fireEvent.click(screen.getByRole("button", { name: "memo.visibility.public" }));
+ expect(editor.getState().metadata.visibility).toBe(Visibility.PUBLIC);
+ expect(editor.getState().content).toBe("A note");
+ expect(controller.current?.hasFocus()).toBe(true);
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => editor.dispatch(editor.actions.setMetadata({ visibility: Visibility.PRIVATE })));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ });
+
+ it("hides an already selected audience and reacts to manual changes", () => {
+ render(composer([publicAudience]));
+ act(() => editor.dispatch(editor.actions.setMetadata({ visibility: Visibility.PUBLIC })));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => editor.dispatch(editor.actions.setMetadata({ visibility: Visibility.PRIVATE })));
+ expect(screen.getByRole("button", { name: "memo.visibility.public" })).toBeInTheDocument();
+ });
+
+ it("requires actual Space placement to offer Space visibility", () => {
+ const result = render(composer([spaceAudience]));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ result.rerender(composer([spaceAudience], "A note", "spaces/team"));
+ expect(screen.getByRole("button", { name: "memo.visibility.space" })).toBeInTheDocument();
+ result.rerender(composer([spaceAudience]));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ result.rerender(composer([spaceAudience], "A note", "spaces/team"));
+ fireEvent.click(screen.getByRole("button", { name: "memo.visibility.space" }));
+ expect(editor.getState().metadata.visibility).toBe(Visibility.SPACE);
+ });
+
+ it("shares the three-chip limit across kinds after filtering fulfilled suggestions", () => {
+ render(composer([...candidates.slice(0, 2), checklist, publicAudience], "#work A note"));
+ expect(screen.getAllByRole("button")).toHaveLength(3);
+ expect(screen.getByRole("button", { name: "common.add #release" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "editor.format.task-list" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "memo.visibility.public" })).toBeInTheDocument();
+ });
+
+ it("hides all kinds in an empty draft and prevents acceptance while saving", () => {
+ render(composer([checklist, publicAudience], ""));
+ expect(screen.queryByRole("group")).not.toBeInTheDocument();
+ act(() => controller.current?.setMarkdown("A note"));
+ act(() => editor.dispatch(editor.actions.setLoading("saving", true)));
+ for (const chip of screen.getAllByRole("button")) {
+ expect(chip).toBeDisabled();
+ fireEvent.click(chip);
+ }
+ expect(editor.getState().content).toBe("A note");
+ expect(editor.getState().metadata.visibility).toBe(Visibility.PRIVATE);
+ });
+});
diff --git a/web/tests/formatting-toolbar.test.tsx b/web/tests/formatting-toolbar.test.tsx
index cdc164c38..7786f265f 100644
--- a/web/tests/formatting-toolbar.test.tsx
+++ b/web/tests/formatting-toolbar.test.tsx
@@ -21,6 +21,9 @@ function makeController(opts: { active?: Partial<ActiveFormatState> } = {}) {
const run = vi.fn();
const activeFormats: ActiveFormatState = { ...EMPTY_ACTIVE_FORMATS, ...opts.active };
const controller: EditorController = {
+ getTags: () => [],
+ hasChecklist: () => false,
+ insertTag: vi.fn(() => true),
focus: () => {},
hasFocus: () => false,
isEmpty: () => true,
diff --git a/web/tests/global-memo-editor.test.tsx b/web/tests/global-memo-editor.test.tsx
index 63d47e29b..c5d69c38e 100644
--- a/web/tests/global-memo-editor.test.tsx
+++ b/web/tests/global-memo-editor.test.tsx
@@ -6,6 +6,10 @@ import { GlobalMemoEditorProvider, useGlobalMemoEditor } from "@/contexts/Global
const DIALOG = { name: "editor.new-memo" };
+vi.mock("@/hooks/useMemoSuggestions", () => ({
+ useMemoSuggestions: () => [{ id: "tag:work" }],
+}));
+
const mocks = vi.hoisted(() => ({
currentUser: { name: "users/test" } as { name: string } | undefined,
isUserSettingsInitialized: true,
@@ -197,6 +201,7 @@ describe("GlobalMemoEditorProvider", () => {
expect(mocks.editorProps).toMatchObject({
autoFocus: true,
cacheKey: "global-memo-editor",
+ suggestions: [{ id: "tag:work" }],
onFocusModeExit: expect.any(Function),
});
await waitFor(() => expect(dialog).toContainElement(document.activeElement as HTMLElement | null));
diff --git a/web/tests/home-loading-boundary.test.tsx b/web/tests/home-loading-boundary.test.tsx
index 19d5c3680..107041e24 100644
--- a/web/tests/home-loading-boundary.test.tsx
+++ b/web/tests/home-loading-boundary.test.tsx
@@ -2,6 +2,10 @@ import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import Home from "@/pages/Home";
+vi.mock("@/hooks/useMemoSuggestions", () => ({
+ useMemoSuggestions: () => [{ id: "tag:work" }],
+}));
+
const state = vi.hoisted(() => ({
selectedSpaceName: undefined as string | undefined,
editorProps: undefined as Record<string, unknown> | undefined,
@@ -85,6 +89,7 @@ describe("<Home>", () => {
expect(state.listProps).toMatchObject({ contextFilter: undefined });
expect(state.editorProps).toMatchObject({ cacheKey: "home-memo-editor", defaultSpace: undefined });
expect(state.editorProps?.autoFocus).toEqual(expect.any(Function));
+ expect(state.editorProps?.suggestions).toEqual([{ id: "tag:work" }]);
});
it("filters the feed and sets new memo placement to the selected Space", () => {
diff --git a/web/tests/memo-suggestions.test.ts b/web/tests/memo-suggestions.test.ts
new file mode 100644
index 000000000..b900e2230
--- /dev/null
+++ b/web/tests/memo-suggestions.test.ts
@@ -0,0 +1,166 @@
+import { describe, expect, it } from "vitest";
+import { getMemoSuggestions } from "@/lib/memo-suggestions";
+import { extractTagConditions } from "@/lib/tag-suggestions";
+
+describe("tag suggestion extraction", () => {
+ it.each([
+ ['"work" in tags', ["work"]],
+ ["'work/project' in tags", ["work/project"]],
+ ['tag in ["work", "release",]', ["work", "release"]],
+ ['("work" in tags && "release" in tags) || "personal" in tags', ["work", "release", "personal"]],
+ ['has_task_list && "work" in tags && content.contains("release")', ["work"]],
+ ['"work" in tags // ignore this: && !("work" in tags)', ["work"]],
+ ['"\\u5de5\\u4f5c" in tags', ["工作"]],
+ ["'it\\'s' in tags", ["it's"]],
+ ['!("archived" in tags)', []],
+ ['!("archived" in tags || "private" in tags)', []],
+ ['!("archived" in tags && !("work" in tags))', ["work"]],
+ ['content.contains("work")', []],
+ ["content.contains('\"work\" in tags')", []],
+ ['tags.exists(t, t.startsWith("work/"))', []],
+ ['("work" in tags) == false', []],
+ ['true ? "work" in tags : "personal" in tags', []],
+ ['"work" in tags &&', []],
+ ['"work" in tags && visibility ==', []],
+ ['("work" in tags', []],
+ ['"work" in tags || content.contains("x"', []],
+ ['"work" in tags && x[)', []],
+ ['"work" in tags && @', []],
+ ['tag in ["work", variable]', []],
+ ["tag in []", []],
+ ])("extracts explicit tags conservatively: %s", (source, expected) => {
+ expect(extractTagConditions(source).candidates).toEqual(expected);
+ });
+
+ it("combines unconditional exclusions without treating an OR branch as a global exclusion", () => {
+ expect([...extractTagConditions('!("work" in tags) && !("personal" in tags)').excluded]).toEqual(["work", "personal"]);
+ expect([...extractTagConditions('!("work" in tags) || "personal" in tags').excluded]).toEqual([]);
+ expect([...extractTagConditions('!("work" in tags) || (!("work" in tags) && has_task_list)').excluded]).toEqual(["work"]);
+ expect([...extractTagConditions('!(tag in ["work", "personal"])').excluded]).toEqual(["work", "personal"]);
+ expect([...extractTagConditions('!("work" in tags && "personal" in tags)').excluded]).toEqual([]);
+ });
+});
+
+describe("memo suggestions", () => {
+ it("ranks selection before search before View, deduplicates, and leaves the visible limit to the editor", () => {
+ const suggestions = getMemoSuggestions(
+ [
+ { factor: "celSearch", value: 'tag in ["search", "selected"]' },
+ { factor: "tagSearch", value: "selected" },
+ { factor: "tagSearch", value: "second" },
+ ],
+ 'tag in ["view", "search", "selected"]',
+ );
+ expect(suggestions.map(({ id, source }) => [id, source])).toEqual([
+ ["tag:selected", "selection"],
+ ["tag:second", "selection"],
+ ["tag:search", "search"],
+ ["tag:view", "view"],
+ ]);
+ expect(suggestions[0]).toMatchObject({ kind: "tag", tag: "selected" });
+ });
+
+ it("applies exclusions across sources and ignores plain-text searches", () => {
+ expect(
+ getMemoSuggestions(
+ [
+ { factor: "tagSearch", value: "archived" },
+ { factor: "celSearch", value: '!("work" in tags)' },
+ { factor: "contentSearch", value: "#personal" },
+ ],
+ '!("archived" in tags) && tag in ["work", "release"]',
+ ).map((suggestion) => suggestion.id),
+ ).toEqual(["tag:release"]);
+ });
+
+ it("does not exclude a selected tag merely because one alternative negates it", () => {
+ expect(
+ getMemoSuggestions([{ factor: "tagSearch", value: "work" }], '!("work" in tags) || "personal" in tags').map(
+ (suggestion) => suggestion.id,
+ ),
+ ).toEqual(["tag:work", "tag:personal"]);
+ });
+
+ it("validates complete tag identities and preserves case, Unicode, punctuation, and paths", () => {
+ const tags = ["work/project", "工作", "🎉", "C++", "R&D", "Work", "work", "", "two words", "#work", "work/", "x\ny", "wo\u200brk"];
+ expect(getMemoSuggestions(tags.map((value) => ({ factor: "tagSearch", value }))).map((suggestion) => suggestion.id)).toEqual(
+ tags.slice(0, 7).map((tag) => `tag:${tag}`),
+ );
+ });
+});
+
+describe("checklist suggestions", () => {
+ it.each([
+ ["has_task_list", true],
+ ["has_incomplete_tasks", true],
+ ["has_task_list == true", true],
+ ["has_task_list != false", true],
+ ["!(has_task_list == false)", true],
+ ["has_task_list || content.contains('todo')", true],
+ ["!has_task_list", false],
+ ["has_task_list == false", false],
+ ["has_task_list && !has_incomplete_tasks", false],
+ ["has_task_list && !has_task_list", false],
+ ["content.contains('has_task_list')", false],
+ ["has_task_list &&", false],
+ ])("reads task conditions: %s", (value, expected) => {
+ expect(getMemoSuggestions([{ factor: "celSearch", value }]).some((item) => item.kind === "checklist")).toBe(expected);
+ });
+
+ it("ranks and deduplicates across kinds and applies exclusions across contexts", () => {
+ expect(
+ getMemoSuggestions(
+ [
+ { factor: "property.hasTaskList", value: "true" },
+ { factor: "celSearch", value: 'has_task_list && "work" in tags' },
+ ],
+ 'has_task_list && "view" in tags',
+ ).map(({ id, source }) => [id, source]),
+ ).toEqual([
+ ["checklist", "selection"],
+ ["tag:work", "search"],
+ ["tag:view", "view"],
+ ]);
+ expect(getMemoSuggestions([{ factor: "property.hasTaskList", value: "true" }], "!has_task_list")).toEqual([]);
+ });
+});
+
+describe("visibility suggestions", () => {
+ it.each([
+ ['visibility == "PRIVATE"', "PRIVATE"],
+ ['"PUBLIC" == visibility', "PUBLIC"],
+ ['visibility == "PROTECTED"', "PROTECTED"],
+ ['visibility in ["SPACE",]', "SPACE"],
+ ['!(visibility != "PRIVATE")', "PRIVATE"],
+ ['visibility == "PRIVATE" || (visibility == "PRIVATE" && has_task_list)', "PRIVATE"],
+ ['visibility in ["PRIVATE", "PUBLIC"] && visibility != "PUBLIC"', "PRIVATE"],
+ ['visibility == "PRIVATE" || visibility == "PUBLIC"', undefined],
+ ['visibility == "PUBLIC" || content.contains("x")', undefined],
+ ['visibility != "PRIVATE"', undefined],
+ ['visibility == "private"', undefined],
+ ['visibility == "UNKNOWN"', undefined],
+ ['visibility == "PRIVATE" && visibility == "PUBLIC"', undefined],
+ ["content.contains('visibility == \"PUBLIC\"')", undefined],
+ ['visibility == "PUBLIC" &&', undefined],
+ ['visibility != "PRIVATE" && visibility != "SPACE" && visibility != "PROTECTED"', undefined],
+ ])("requires a single explicit audience: %s", (value, expected) => {
+ expect(
+ getMemoSuggestions([{ factor: "celSearch", value }])
+ .filter((item) => item.kind === "visibility")
+ .map((item) => item.id),
+ ).toEqual(expected ? [`visibility:${expected}`] : []);
+ });
+
+ it("respects conflicts and chooses the strongest agreeing source", () => {
+ expect(getMemoSuggestions([{ factor: "visibility", value: "PRIVATE" }], 'visibility == "PUBLIC"')).toEqual([]);
+ expect(
+ getMemoSuggestions(
+ [
+ { factor: "visibility", value: "PRIVATE" },
+ { factor: "celSearch", value: 'visibility == "PRIVATE"' },
+ ],
+ 'visibility == "PRIVATE"',
+ ),
+ ).toMatchObject([{ id: "visibility:PRIVATE", source: "selection" }]);
+ });
+});
diff --git a/web/tests/root-layout-global-editor.test.tsx b/web/tests/root-layout-global-editor.test.tsx
index 909cda3c1..193c2344d 100644
--- a/web/tests/root-layout-global-editor.test.tsx
+++ b/web/tests/root-layout-global-editor.test.tsx
@@ -3,6 +3,8 @@ import { MemoryRouter, Route, Routes, useLocation, useNavigate } from "react-rou
import { beforeEach, describe, expect, it, vi } from "vitest";
import RootLayout from "@/layouts/RootLayout";
+vi.mock("@/hooks/useMemoSuggestions", () => ({ useMemoSuggestions: () => [] }));
+
const authState = vi.hoisted(() => ({ currentUser: { name: "users/test" } as { name: string } | undefined }));
const instanceState = vi.hoisted(() => ({ accessMode: 2, instanceUrl: "https://example.com", demo: true }));
diff --git a/web/tests/use-memo-suggestions.test.tsx b/web/tests/use-memo-suggestions.test.tsx
new file mode 100644
index 000000000..428d2f372
--- /dev/null
+++ b/web/tests/use-memo-suggestions.test.tsx
@@ -0,0 +1,46 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { MemoFilter } from "@/contexts/MemoFilterContext";
+import { useMemoSuggestions } from "@/hooks/useMemoSuggestions";
+import { BUILTIN_TASKS_VIEW_ID } from "@/lib/memo-views";
+
+const mocks = vi.hoisted(() => ({
+ filters: [] as MemoFilter[],
+ memoView: undefined as string | undefined,
+ views: [] as { name: string; filter: string }[],
+}));
+vi.mock("@/contexts/MemoFilterContext", () => ({ useMemoFilterContext: () => mocks }));
+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/me" }) }));
+vi.mock("@/hooks/useUserQueries", () => ({ useMemoViews: () => ({ data: mocks.views }) }));
+
+describe("useMemoSuggestions", () => {
+ beforeEach(() => {
+ mocks.filters = [];
+ mocks.memoView = undefined;
+ mocks.views = [];
+ });
+
+ it("suggests a checklist in the built-in Tasks View", () => {
+ mocks.memoView = BUILTIN_TASKS_VIEW_ID;
+ const { result } = renderHook(() => useMemoSuggestions());
+ expect(result.current).toEqual([{ id: "checklist", kind: "checklist", source: "view" }]);
+ });
+
+ it("resolves the selected View and reacts to filters, selection, and query loading", () => {
+ mocks.memoView = "work";
+ const { result, rerender } = renderHook(() => useMemoSuggestions());
+ expect(result.current).toEqual([]);
+ mocks.views = [{ name: "users/me/views/work", filter: '"work" in tags' }];
+ rerender();
+ expect(result.current.map((suggestion) => suggestion.id)).toEqual(["tag:work"]);
+ mocks.filters = [
+ { factor: "tagSearch", value: "release" },
+ { factor: "celSearch", value: '"planning" in tags' },
+ ];
+ rerender();
+ expect(result.current.map((suggestion) => suggestion.id)).toEqual(["tag:release", "tag:planning", "tag:work"]);
+ mocks.memoView = undefined;
+ rerender();
+ expect(result.current.map((suggestion) => suggestion.id)).toEqual(["tag:release", "tag:planning"]);
+ });
+});