feat(spaces): add space-aware UI and filtering (#6230)

This commit is contained in:
ABird 2026-08-24 23:13:55 +08:00 committed by GitHub
parent 6da8461e1d
commit 66b9cb49c1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
79 changed files with 2320 additions and 345 deletions

View file

@ -74,6 +74,33 @@ func TestCompileRejectsStartsWithOnUnsupportedField(t *testing.T) {
require.Contains(t, err.Error(), "does not support text matching")
}
func TestRenderSpaceFilters(t *testing.T) {
t.Parallel()
for _, schema := range []Schema{NewSchema(), NewAttachmentSchema()} {
engine, err := NewEngine(schema)
require.NoError(t, err)
for _, dialect := range []DialectName{DialectSQLite, DialectMySQL, DialectPostgres} {
assigned, err := engine.CompileToStatement(
context.Background(),
`space == "spaces/team"`,
RenderOptions{Dialect: dialect},
)
require.NoError(t, err, schema.Name, dialect)
require.Contains(t, assigned.SQL, "spaces/", schema.Name, dialect)
require.Equal(t, []any{"spaces/team"}, assigned.Args, schema.Name, dialect)
unassigned, err := engine.CompileToStatement(context.Background(), `space == null`, RenderOptions{Dialect: dialect})
require.NoError(t, err, schema.Name, dialect)
require.Contains(t, unassigned.SQL, "IS NULL", schema.Name, dialect)
require.Empty(t, unassigned.Args, schema.Name, dialect)
}
_, err = engine.Compile(context.Background(), `space != null`)
require.ErrorContains(t, err, `operator != not allowed for field "space"`)
}
}
func TestCompileContainsEscapesLikeWildcards(t *testing.T) {
t.Parallel()

View file

@ -172,6 +172,20 @@ func NewSchema() Schema {
CompareNeq: true,
},
},
"space": {
Name: "space",
Kind: FieldKindScalar,
Type: FieldTypeString,
Column: Column{Table: "memo_space", Name: "uid"},
Expressions: map[DialectName]string{
DialectSQLite: "CASE WHEN `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END",
DialectMySQL: "CASE WHEN `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE CONCAT('spaces/', %[1]s) END",
DialectPostgres: "CASE WHEN memo.space_id IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END",
},
AllowedComparisonOps: map[ComparisonOperator]bool{
CompareEq: true,
},
},
"tags": {
Name: "tags",
Kind: FieldKindJSONList,
@ -252,6 +266,8 @@ func NewSchema() Schema {
cel.Variable("tag", cel.StringType),
cel.Variable("tags", cel.ListType(cel.StringType)),
cel.Variable("visibility", cel.StringType),
// Dyn permits the explicit null comparison used for memos without a space.
cel.Variable("space", cel.DynType),
cel.Variable("has_task_list", cel.BoolType),
cel.Variable("has_link", cel.BoolType),
cel.Variable("has_code", cel.BoolType),
@ -312,6 +328,20 @@ func NewAttachmentSchema() Schema {
CompareNeq: true,
},
},
"space": {
Name: "space",
Kind: FieldKindScalar,
Type: FieldTypeString,
Column: Column{Table: "attachment_space", Name: "uid"},
Expressions: map[DialectName]string{
DialectSQLite: "CASE WHEN `attachment`.`memo_id` IS NULL OR `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END",
DialectMySQL: "CASE WHEN `attachment`.`memo_id` IS NULL OR `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE CONCAT('spaces/', %[1]s) END",
DialectPostgres: "CASE WHEN attachment.memo_id IS NULL OR memo.space_id IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END",
},
AllowedComparisonOps: map[ComparisonOperator]bool{
CompareEq: true,
},
},
}
envOptions := []cel.EnvOption{
@ -319,6 +349,7 @@ func NewAttachmentSchema() Schema {
cel.Variable("mime_type", cel.StringType),
cel.Variable("create_time", cel.TimestampType),
cel.Variable("memo_id", cel.AnyType),
cel.Variable("space", cel.DynType),
cel.Variable("now", cel.TimestampType),
cel.ASTValidators(cel.ValidateRegexLiterals()),
}

View file

@ -193,12 +193,19 @@ message ListAttachmentsRequest {
// Optional. Filter to apply to the list results.
// Example: "mime_type==\"image/png\"" or "filename.contains(\"test\")"
// Supported operators: =, !=, <, <=, >, >=, : (contains), in
// Supported fields: filename, mime_type, create_time, memo
// Supported fields: filename, mime_type, create_time, memo_id, space.
// `space` only supports a non-negated `==` comparison with a Space resource
// name or null.
// `space` is the linked memo's space resource name, or null when the
// attachment is unlinked or its linked memo has no space.
string filter = 3 [(google.api.field_behavior) = OPTIONAL];
// Optional. The order to sort results by.
// Example: "create_time desc" or "filename asc"
string order_by = 4 [(google.api.field_behavior) = OPTIONAL];
reserved 5, 6;
reserved "space", "unassigned";
}
message ListAttachmentsResponse {

View file

@ -340,6 +340,7 @@ message ListMemosRequest {
// content (string), creator (string, e.g. "users/1"),
// created_ts / updated_ts (timestamp), pinned (bool),
// visibility (string: PRIVATE | PROTECTED | PUBLIC | SPACE),
// space (string resource name or null when the memo has no space),
// tags (list<string>; match with `"work" in tags`, not `tag == "work"`),
// has_task_list / has_link / has_code / has_incomplete_tasks (bool),
// has_location (bool; true when the memo has a location attached).
@ -347,6 +348,7 @@ message ListMemosRequest {
// the create_time / update_time names used by order_by.
// Examples:
// pinned == true && visibility == "PUBLIC"
// space == "spaces/team" or space == null
// tags.exists(t, t == "urgent")
// content.contains("roadmap") && created_ts > now - duration("168h")
string filter = 5 [(google.api.field_behavior) = OPTIONAL];
@ -354,14 +356,8 @@ message ListMemosRequest {
// Optional. If true, show deleted memos in the response.
bool show_deleted = 6 [(google.api.field_behavior) = OPTIONAL];
oneof scope {
// Optional. Limit results to readable non-comment memos in a space of
// which the caller is an active member.
string space = 7 [(google.api.resource_reference) = {type: "memos.api.v1/Space"}];
// Optional. Limit results to memos with no space. Must be true when set.
bool unassigned = 8;
}
reserved 7, 8;
reserved "space", "unassigned";
}
message ListMemosResponse {

View file

@ -399,6 +399,13 @@ message GetUserStatsRequest {
(google.api.field_behavior) = REQUIRED,
(google.api.resource_reference) = {type: "memos.api.v1/User"}
];
// Optional. CEL expression selecting the readable non-comment memos to
// include. Supports the same fields as ListMemos, including `space`.
string filter = 2 [(google.api.field_behavior) = OPTIONAL];
reserved 3;
reserved "space", "unassigned";
}
message ListAllUserStatsRequest {
@ -408,6 +415,9 @@ message ListAllUserStatsRequest {
// Optional. Filter to apply to memo stats.
// Uses the same filter syntax as ListMemos.
string filter = 2 [(google.api.field_behavior) = OPTIONAL];
reserved 3, 4;
reserved "space", "unassigned";
}
message ListAllUserStatsResponse {

View file

@ -783,7 +783,11 @@ type ListAttachmentsRequest struct {
// Optional. Filter to apply to the list results.
// Example: "mime_type==\"image/png\"" or "filename.contains(\"test\")"
// Supported operators: =, !=, <, <=, >, >=, : (contains), in
// Supported fields: filename, mime_type, create_time, memo
// Supported fields: filename, mime_type, create_time, memo_id, space.
// `space` only supports a non-negated `==` comparison with a Space resource
// name or null.
// `space` is the linked memo's space resource name, or null when the
// attachment is unlinked or its linked memo has no space.
Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"`
// Optional. The order to sort results by.
// Example: "create_time desc" or "filename asc"
@ -1170,13 +1174,14 @@ const file_api_v1_attachment_service_proto_rawDesc = "" +
"\n" +
"attachment\x18\x01 \x01(\v2\x18.memos.api.v1.AttachmentB\x03\xe0A\x02R\n" +
"attachment\x12(\n" +
"\rattachment_id\x18\x02 \x01(\tB\x03\xe0A\x01R\fattachmentId\"\x9b\x01\n" +
"\rattachment_id\x18\x02 \x01(\tB\x03\xe0A\x01R\fattachmentId\"\xba\x01\n" +
"\x16ListAttachmentsRequest\x12 \n" +
"\tpage_size\x18\x01 \x01(\x05B\x03\xe0A\x01R\bpageSize\x12\"\n" +
"\n" +
"page_token\x18\x02 \x01(\tB\x03\xe0A\x01R\tpageToken\x12\x1b\n" +
"\x06filter\x18\x03 \x01(\tB\x03\xe0A\x01R\x06filter\x12\x1e\n" +
"\border_by\x18\x04 \x01(\tB\x03\xe0A\x01R\aorderBy\"}\n" +
"\border_by\x18\x04 \x01(\tB\x03\xe0A\x01R\aorderByJ\x04\b\x05\x10\x06J\x04\b\x06\x10\aR\x05spaceR\n" +
"unassigned\"}\n" +
"\x17ListAttachmentsResponse\x12:\n" +
"\vattachments\x18\x01 \x03(\v2\x18.memos.api.v1.AttachmentR\vattachments\x12&\n" +
"\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"K\n" +

View file

@ -556,6 +556,7 @@ type ListMemosRequest struct {
// content (string), creator (string, e.g. "users/1"),
// created_ts / updated_ts (timestamp), pinned (bool),
// visibility (string: PRIVATE | PROTECTED | PUBLIC | SPACE),
// space (string resource name or null when the memo has no space),
// tags (list<string>; match with `"work" in tags`, not `tag == "work"`),
// has_task_list / has_link / has_code / has_incomplete_tasks (bool),
// has_location (bool; true when the memo has a location attached).
@ -565,16 +566,12 @@ type ListMemosRequest struct {
// Examples:
//
// pinned == true && visibility == "PUBLIC"
// space == "spaces/team" or space == null
// tags.exists(t, t == "urgent")
// content.contains("roadmap") && created_ts > now - duration("168h")
Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"`
// Optional. If true, show deleted memos in the response.
ShowDeleted bool `protobuf:"varint,6,opt,name=show_deleted,json=showDeleted,proto3" json:"show_deleted,omitempty"`
// Types that are valid to be assigned to Scope:
//
// *ListMemosRequest_Space
// *ListMemosRequest_Unassigned
Scope isListMemosRequest_Scope `protobuf_oneof:"scope"`
ShowDeleted bool `protobuf:"varint,6,opt,name=show_deleted,json=showDeleted,proto3" json:"show_deleted,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -651,50 +648,6 @@ func (x *ListMemosRequest) GetShowDeleted() bool {
return false
}
func (x *ListMemosRequest) GetScope() isListMemosRequest_Scope {
if x != nil {
return x.Scope
}
return nil
}
func (x *ListMemosRequest) GetSpace() string {
if x != nil {
if x, ok := x.Scope.(*ListMemosRequest_Space); ok {
return x.Space
}
}
return ""
}
func (x *ListMemosRequest) GetUnassigned() bool {
if x != nil {
if x, ok := x.Scope.(*ListMemosRequest_Unassigned); ok {
return x.Unassigned
}
}
return false
}
type isListMemosRequest_Scope interface {
isListMemosRequest_Scope()
}
type ListMemosRequest_Space struct {
// Optional. Limit results to readable non-comment memos in a space of
// which the caller is an active member.
Space string `protobuf:"bytes,7,opt,name=space,proto3,oneof"`
}
type ListMemosRequest_Unassigned struct {
// Optional. Limit results to memos with no space. Must be true when set.
Unassigned bool `protobuf:"varint,8,opt,name=unassigned,proto3,oneof"`
}
func (*ListMemosRequest_Space) isListMemosRequest_Scope() {}
func (*ListMemosRequest_Unassigned) isListMemosRequest_Scope() {}
type ListMemosResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The list of memos.
@ -2424,7 +2377,7 @@ const file_api_v1_memo_service_proto_rawDesc = "" +
"\tlongitude\x18\x03 \x01(\x01B\x03\xe0A\x01R\tlongitude\"^\n" +
"\x11CreateMemoRequest\x12+\n" +
"\x04memo\x18\x01 \x01(\v2\x12.memos.api.v1.MemoB\x03\xe0A\x02R\x04memo\x12\x1c\n" +
"\amemo_id\x18\x02 \x01(\tB\x03\xe0A\x01R\x06memoId\"\xc9\x02\n" +
"\amemo_id\x18\x02 \x01(\tB\x03\xe0A\x01R\x06memoId\"\x8c\x02\n" +
"\x10ListMemosRequest\x12 \n" +
"\tpage_size\x18\x01 \x01(\x05B\x03\xe0A\x01R\bpageSize\x12\"\n" +
"\n" +
@ -2432,13 +2385,8 @@ const file_api_v1_memo_service_proto_rawDesc = "" +
"\x05state\x18\x03 \x01(\x0e2\x13.memos.api.v1.StateB\x03\xe0A\x01R\x05state\x12\x1e\n" +
"\border_by\x18\x04 \x01(\tB\x03\xe0A\x01R\aorderBy\x12\x1b\n" +
"\x06filter\x18\x05 \x01(\tB\x03\xe0A\x01R\x06filter\x12&\n" +
"\fshow_deleted\x18\x06 \x01(\bB\x03\xe0A\x01R\vshowDeleted\x12/\n" +
"\x05space\x18\a \x01(\tB\x17\xfaA\x14\n" +
"\x12memos.api.v1/SpaceH\x00R\x05space\x12 \n" +
"\n" +
"unassigned\x18\b \x01(\bH\x00R\n" +
"unassignedB\a\n" +
"\x05scope\"e\n" +
"\fshow_deleted\x18\x06 \x01(\bB\x03\xe0A\x01R\vshowDeletedJ\x04\b\a\x10\bJ\x04\b\b\x10\tR\x05spaceR\n" +
"unassigned\"e\n" +
"\x11ListMemosResponse\x12(\n" +
"\x05memos\x18\x01 \x03(\v2\x12.memos.api.v1.MemoR\x05memos\x12&\n" +
"\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"?\n" +
@ -2739,10 +2687,6 @@ func file_api_v1_memo_service_proto_init() {
file_api_v1_attachment_service_proto_init()
file_api_v1_common_proto_init()
file_api_v1_memo_service_proto_msgTypes[1].OneofWrappers = []any{}
file_api_v1_memo_service_proto_msgTypes[4].OneofWrappers = []any{
(*ListMemosRequest_Space)(nil),
(*ListMemosRequest_Unassigned)(nil),
}
file_api_v1_memo_service_proto_msgTypes[23].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{

View file

@ -946,7 +946,10 @@ type GetUserStatsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Required. The resource name of the user.
// Format: users/{user}
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// Optional. CEL expression selecting the readable non-comment memos to
// include. Supports the same fields as ListMemos, including `space`.
Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -988,6 +991,13 @@ func (x *GetUserStatsRequest) GetName() string {
return ""
}
func (x *GetUserStatsRequest) GetFilter() string {
if x != nil {
return x.Filter
}
return ""
}
type ListAllUserStatsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Optional. The state of memos to include. Defaults to NORMAL.
@ -3438,13 +3448,16 @@ const file_api_v1_user_service_proto_rawDesc = "" +
"todo_count\x18\x03 \x01(\x05R\ttodoCount\x12\x1d\n" +
"\n" +
"undo_count\x18\x04 \x01(\x05R\tundoCount:E\xeaAB\n" +
"\x16memos.api.v1/UserStats\x12\x12users/{user}/stats*\tuserStats2\tuserStatsJ\x04\b\x02\x10\x03R\x17memo_display_timestamps\"D\n" +
"\x16memos.api.v1/UserStats\x12\x12users/{user}/stats*\tuserStats2\tuserStatsJ\x04\b\x02\x10\x03R\x17memo_display_timestamps\"z\n" +
"\x13GetUserStatsRequest\x12-\n" +
"\x04name\x18\x01 \x01(\tB\x19\xe0A\x02\xfaA\x13\n" +
"\x11memos.api.v1/UserR\x04name\"f\n" +
"\x11memos.api.v1/UserR\x04name\x12\x1b\n" +
"\x06filter\x18\x02 \x01(\tB\x03\xe0A\x01R\x06filterJ\x04\b\x03\x10\x04R\x05spaceR\n" +
"unassigned\"\x85\x01\n" +
"\x17ListAllUserStatsRequest\x12.\n" +
"\x05state\x18\x01 \x01(\x0e2\x13.memos.api.v1.StateB\x03\xe0A\x01R\x05state\x12\x1b\n" +
"\x06filter\x18\x02 \x01(\tB\x03\xe0A\x01R\x06filter\"I\n" +
"\x06filter\x18\x02 \x01(\tB\x03\xe0A\x01R\x06filterJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\x05spaceR\n" +
"unassigned\"I\n" +
"\x18ListAllUserStatsResponse\x12-\n" +
"\x05stats\x18\x01 \x03(\v2\x17.memos.api.v1.UserStatsR\x05stats\"\xf1\a\n" +
"\vUserSetting\x12\x17\n" +

View file

@ -360,6 +360,8 @@ func local_request_UserService_ListAllUserStats_0(ctx context.Context, marshaler
return msg, metadata, err
}
var filter_UserService_GetUserStats_0 = &utilities.DoubleArray{Encoding: map[string]int{"name": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}}
func request_UserService_GetUserStats_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var (
protoReq GetUserStatsRequest
@ -374,6 +376,12 @@ func request_UserService_GetUserStats_0(ctx context.Context, marshaler runtime.M
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
}
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UserService_GetUserStats_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if req.Body != nil {
_, _ = io.Copy(io.Discard, req.Body)
}
@ -395,6 +403,12 @@ func local_request_UserService_GetUserStats_0(ctx context.Context, marshaler run
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err)
}
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UserService_GetUserStats_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.GetUserStats(ctx, &protoReq)
return msg, metadata, err
}

View file

@ -61,7 +61,11 @@ paths:
Optional. Filter to apply to the list results.
Example: "mime_type==\"image/png\"" or "filename.contains(\"test\")"
Supported operators: =, !=, <, <=, >, >=, : (contains), in
Supported fields: filename, mime_type, create_time, memo
Supported fields: filename, mime_type, create_time, memo_id, space.
`space` only supports a non-negated `==` comparison with a Space resource
name or null.
`space` is the linked memo's space resource name, or null when the
attachment is unlinked or its linked memo has no space.
schema:
type: string
- name: orderBy
@ -663,6 +667,7 @@ paths:
content (string), creator (string, e.g. "users/1"),
created_ts / updated_ts (timestamp), pinned (bool),
visibility (string: PRIVATE | PROTECTED | PUBLIC | SPACE),
space (string resource name or null when the memo has no space),
tags (list<string>; match with `"work" in tags`, not `tag == "work"`),
has_task_list / has_link / has_code / has_incomplete_tasks (bool),
has_location (bool; true when the memo has a location attached).
@ -670,6 +675,7 @@ paths:
the create_time / update_time names used by order_by.
Examples:
pinned == true && visibility == "PUBLIC"
space == "spaces/team" or space == null
tags.exists(t, t == "urgent")
content.contains("roadmap") && created_ts > now - duration("168h")
schema:
@ -679,18 +685,6 @@ paths:
description: Optional. If true, show deleted memos in the response.
schema:
type: boolean
- name: space
in: query
description: |-
Optional. Limit results to readable non-comment memos in a space of
which the caller is an active member.
schema:
type: string
- name: unassigned
in: query
description: Optional. Limit results to memos with no space. Must be true when set.
schema:
type: boolean
responses:
"200":
description: OK
@ -2626,6 +2620,13 @@ paths:
required: true
schema:
type: string
- name: filter
in: query
description: |-
Optional. CEL expression selecting the readable non-comment memos to
include. Supports the same fields as ListMemos, including `space`.
schema:
type: string
responses:
"200":
description: OK

View file

@ -10,12 +10,10 @@ import (
"path/filepath"
"time"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/usememos/memos/internal/filter"
v1pb "github.com/usememos/memos/proto/gen/api/v1"
"github.com/usememos/memos/store"
)
@ -234,11 +232,10 @@ func (s *APIV1Service) ListAttachments(ctx context.Context, request *v1pb.ListAt
Limit: &pageSize,
Offset: &offset,
}
// Parse filter if provided
if request.Filter != "" {
if err := s.validateAttachmentFilter(ctx, request.Filter); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
if err := s.validateAttachmentFilterForUser(ctx, request.Filter, user); err != nil {
return nil, err
}
findAttachment.Filters = append(findAttachment.Filters, request.Filter)
}
@ -545,22 +542,6 @@ func attachmentsIncludeMemo(attachments []*store.Attachment) bool {
return false
}
func (s *APIV1Service) validateAttachmentFilter(ctx context.Context, filterStr string) error {
if filterStr == "" {
return errors.New("filter cannot be empty")
}
engine, err := filter.DefaultAttachmentEngine()
if err != nil {
return err
}
if _, err := engine.CompileToStatement(ctx, filterStr, filter.RenderOptions{Dialect: s.filterDialect()}); err != nil {
return errors.Wrap(err, "failed to compile filter")
}
return nil
}
// checkAttachmentAccess verifies the user has permission to access the attachment.
// For unlinked attachments (no memo), only the creator can access.
// For linked attachments, access follows the memo's visibility rules.

View file

@ -0,0 +1,145 @@
package v1
import (
"context"
"slices"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
filterpkg "github.com/usememos/memos/internal/filter"
"github.com/usememos/memos/store"
)
func (s *APIV1Service) validateMemoFilterForUser(ctx context.Context, filterText string, user *store.User) error {
engine, err := filterpkg.DefaultEngine()
if err != nil {
return status.Errorf(codes.Internal, "failed to initialize filter: %v", err)
}
return s.validateFilterSpaceAccess(ctx, filterText, engine, user)
}
func (s *APIV1Service) validateAttachmentFilterForUser(ctx context.Context, filterText string, user *store.User) error {
engine, err := filterpkg.DefaultAttachmentEngine()
if err != nil {
return status.Errorf(codes.Internal, "failed to initialize filter: %v", err)
}
return s.validateFilterSpaceAccess(ctx, filterText, engine, user)
}
func (s *APIV1Service) validateFilterSpaceAccess(ctx context.Context, filterText string, engine *filterpkg.Engine, user *store.User) error {
program, err := engine.Compile(ctx, filterText)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
}
if _, err := program.Render(filterpkg.RenderOptions{Dialect: s.filterDialect()}); err != nil {
return status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
}
spaceNames := map[string]struct{}{}
if err := collectSpaceFilterNames(program.ConditionTree(), false, spaceNames); err != nil {
return status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
}
if len(spaceNames) == 0 {
return nil
}
if user == nil {
return status.Error(codes.Unauthenticated, "user not authenticated")
}
names := make([]string, 0, len(spaceNames))
for name := range spaceNames {
names = append(names, name)
}
slices.Sort(names)
for _, name := range names {
if _, err := s.resolveWritableSpaceByName(ctx, name, user.ID); err != nil {
return err
}
}
return nil
}
func collectSpaceFilterNames(condition filterpkg.Condition, negated bool, names map[string]struct{}) error {
switch condition := condition.(type) {
case *filterpkg.LogicalCondition:
if err := collectSpaceFilterNames(condition.Left, negated, names); err != nil {
return err
}
return collectSpaceFilterNames(condition.Right, negated, names)
case *filterpkg.NotCondition:
return collectSpaceFilterNames(condition.Expr, true, names)
case *filterpkg.ComparisonCondition:
if !valueReferencesSpace(condition.Left) && !valueReferencesSpace(condition.Right) {
return nil
}
field, ok := condition.Left.(*filterpkg.FieldRef)
if !ok || field.Name != "space" || negated || condition.Operator != filterpkg.CompareEq {
return errors.New("space only supports a non-negated equality comparison")
}
literal, ok := condition.Right.(*filterpkg.LiteralValue)
if !ok {
return errors.New("space must be compared with a resource name or null")
}
if literal.Value == nil {
return nil
}
name, ok := literal.Value.(string)
if !ok {
return errors.New("space must be compared with a resource name or null")
}
names[name] = struct{}{}
return nil
case *filterpkg.InCondition:
if valueReferencesSpace(condition.Left) {
return errors.New("space does not support the in operator")
}
for _, value := range condition.Values {
if valueReferencesSpace(value) {
return errors.New("space does not support the in operator")
}
}
case *filterpkg.ElementInCondition:
if condition.Field == "space" || valueReferencesSpace(condition.Element) {
return errors.New("space does not support the in operator")
}
case *filterpkg.FieldPredicateCondition:
if condition.Field == "space" {
return errors.New("space must be compared with a resource name or null")
}
case *filterpkg.TextMatchCondition:
if condition.Field == "space" {
return errors.New("space does not support text matching")
}
case *filterpkg.RegexCondition:
if condition.Field == "space" {
return errors.New("space does not support regular expressions")
}
case *filterpkg.ListComprehensionCondition:
if condition.Field == "space" {
return errors.New("space does not support list operations")
}
default:
// Other condition types cannot reference a space.
}
return nil
}
func valueReferencesSpace(value filterpkg.ValueExpr) bool {
switch value := value.(type) {
case *filterpkg.FieldRef:
return value.Name == "space"
case *filterpkg.FunctionValue:
for _, argument := range value.Args {
if valueReferencesSpace(argument) {
return true
}
}
case *filterpkg.FieldAccessorValue:
return value.Field == "space"
default:
// Other value expressions cannot reference a space.
}
return false
}

View file

@ -89,27 +89,6 @@ func (s *APIV1Service) ListMemos(ctx context.Context, request *v1pb.ListMemosReq
}
memoFind.Access = accessScope
if request.Scope != nil {
switch scope := request.Scope.(type) {
case *v1pb.ListMemosRequest_Space:
if currentUser == nil {
return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
}
space, err := s.resolveWritableSpaceByName(ctx, scope.Space, currentUser.ID)
if err != nil {
return nil, err
}
memoFind.SpaceID = &space.ID
case *v1pb.ListMemosRequest_Unassigned:
if !scope.Unassigned {
return nil, status.Errorf(codes.InvalidArgument, "unassigned scope must be true")
}
memoFind.Unassigned = true
default:
return nil, status.Errorf(codes.InvalidArgument, "unsupported memo scope")
}
}
if request.State == v1pb.State_ARCHIVED {
state := store.Archived
memoFind.RowStatus = &state
@ -134,8 +113,8 @@ func (s *APIV1Service) ListMemos(ctx context.Context, request *v1pb.ListMemosReq
}
if request.Filter != "" {
if err := s.validateFilter(ctx, request.Filter); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
if err := s.validateMemoFilterForUser(ctx, request.Filter, currentUser); err != nil {
return nil, err
}
memoFind.Filters = append(memoFind.Filters, request.Filter)
}

View file

@ -480,6 +480,109 @@ func TestLinkedAttachmentMutationsRevalidateMemoSpaceMembership(t *testing.T) {
require.NoError(t, err)
}
func TestListAttachmentsSpaceFilter(t *testing.T) {
ctx := context.Background()
ts := NewTestService(t)
defer ts.Cleanup()
owner, err := ts.CreateRegularUser(ctx, "attachment-scope-owner")
require.NoError(t, err)
member, err := ts.CreateRegularUser(ctx, "attachment-scope-member")
require.NoError(t, err)
outsider, err := ts.CreateRegularUser(ctx, "attachment-scope-outsider")
require.NoError(t, err)
spaceA, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "attachment-api-scope-a", Title: "A"}, owner.ID)
require.NoError(t, err)
_, err = ts.Store.CreateSpaceMember(ctx, &store.SpaceMember{
SpaceID: spaceA.ID, UserID: member.ID, Role: store.SpaceMemberRoleUser,
}, owner.ID)
require.NoError(t, err)
spaceB, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "attachment-api-scope-b", Title: "B"}, owner.ID)
require.NoError(t, err)
unassignedMemo, err := ts.Store.CreateMemo(ctx, &store.Memo{
UID: "attachment-api-unassigned", CreatorID: owner.ID, Content: "unassigned", Visibility: store.Private,
})
require.NoError(t, err)
spaceAMemo, err := ts.Store.CreateMemo(ctx, &store.Memo{
UID: "attachment-api-space-a", CreatorID: owner.ID, Content: "a", Visibility: store.Private, SpaceID: &spaceA.ID,
})
require.NoError(t, err)
spaceBMemo, err := ts.Store.CreateMemo(ctx, &store.Memo{
UID: "attachment-api-space-b", CreatorID: owner.ID, Content: "b", Visibility: store.Public, SpaceID: &spaceB.ID,
})
require.NoError(t, err)
createAttachment := func(uid string, memoID *int32) {
t.Helper()
_, createErr := ts.Store.CreateAttachment(ctx, &store.Attachment{
UID: uid, CreatorID: owner.ID, Filename: uid + ".txt", Type: "text/plain", MemoID: memoID,
})
require.NoError(t, createErr)
}
createAttachment("attachment-api-unlinked", nil)
createAttachment("attachment-api-unassigned-file", &unassignedMemo.ID)
createAttachment("attachment-api-space-a-file", &spaceAMemo.ID)
createAttachment("attachment-api-space-b-file", &spaceBMemo.ID)
attachmentFilenames := func(response *v1pb.ListAttachmentsResponse) []string {
t.Helper()
filenames := make([]string, 0, len(response.Attachments))
for _, attachment := range response.Attachments {
filenames = append(filenames, attachment.Filename)
}
return filenames
}
ownerCtx := ts.CreateUserContext(ctx, owner.ID)
allResponse, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{PageSize: 100})
require.NoError(t, err)
require.Len(t, allResponse.Attachments, 4, "omitting the filter must preserve the creator's full readable library")
spaceResponse, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{
PageSize: 100,
Filter: `space == "spaces/` + spaceA.UID + `"`,
})
require.NoError(t, err)
require.Equal(t, []string{"attachment-api-space-a-file.txt"}, attachmentFilenames(spaceResponse))
unassignedResponse, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{
PageSize: 100,
Filter: `space == null`,
})
require.NoError(t, err)
require.ElementsMatch(t, []string{"attachment-api-unlinked.txt", "attachment-api-unassigned-file.txt"}, attachmentFilenames(unassignedResponse))
unusedInMemos, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{
PageSize: 100,
Filter: "memo_id == null && space == null",
})
require.NoError(t, err)
require.Equal(t, []string{"attachment-api-unlinked.txt"}, attachmentFilenames(unusedInMemos))
unusedInSpace, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{
PageSize: 100,
Filter: `memo_id == null && space == "spaces/` + spaceA.UID + `"`,
})
require.NoError(t, err)
require.Empty(t, unusedInSpace.Attachments)
memberResponse, err := ts.Service.ListAttachments(ts.CreateUserContext(ctx, member.ID), &v1pb.ListAttachmentsRequest{
PageSize: 100,
Filter: `space == "spaces/` + spaceA.UID + `"`,
})
require.NoError(t, err)
require.Empty(t, memberResponse.Attachments, "the attachment library remains creator-owned")
_, err = ts.Service.ListAttachments(ts.CreateUserContext(ctx, outsider.ID), &v1pb.ListAttachmentsRequest{
Filter: `space == "spaces/` + spaceA.UID + `"`,
})
require.Equal(t, codes.NotFound, status.Code(err))
_, err = ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{
Filter: `space != null`,
})
require.Equal(t, codes.InvalidArgument, status.Code(err))
}
func memoIDFromName(ctx context.Context, t *testing.T, ts *TestService, name string) int32 {
t.Helper()
memoUID, err := apiv1.ExtractMemoUIDFromName(name)

View file

@ -6,6 +6,8 @@ import (
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
v1pb "github.com/usememos/memos/proto/gen/api/v1"
storepb "github.com/usememos/memos/proto/gen/store"
@ -362,3 +364,103 @@ func TestUserStatsUseMemoLocalAccess(t *testing.T) {
require.Contains(t, memberStats.Stats[0].TagCount, "space")
require.NotContains(t, memberStats.Stats[0].TagCount, "private")
}
func TestUserStatsSpaceFilter(t *testing.T) {
ctx := context.Background()
ts := NewTestService(t)
defer ts.Cleanup()
owner, err := ts.CreateRegularUser(ctx, "stats-scope-owner")
require.NoError(t, err)
member, err := ts.CreateRegularUser(ctx, "stats-scope-member")
require.NoError(t, err)
outsider, err := ts.CreateRegularUser(ctx, "stats-scope-outsider")
require.NoError(t, err)
spaceA, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "stats-scope-a", Title: "A"}, owner.ID)
require.NoError(t, err)
_, err = ts.Store.CreateSpaceMember(ctx, &store.SpaceMember{
SpaceID: spaceA.ID,
UserID: member.ID,
Role: store.SpaceMemberRoleUser,
}, owner.ID)
require.NoError(t, err)
spaceB, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "stats-scope-b", Title: "B"}, owner.ID)
require.NoError(t, err)
spaceAName := "spaces/" + spaceA.UID
fixtures := []struct {
uid string
creatorID int32
visibility store.Visibility
spaceID *int32
tag string
}{
{uid: "stats-scope-unassigned", creatorID: owner.ID, visibility: store.Public, tag: "unassigned"},
{uid: "stats-scope-a-members", creatorID: owner.ID, visibility: store.SpaceAudience, spaceID: &spaceA.ID, tag: "a-members"},
{uid: "stats-scope-a-private", creatorID: owner.ID, visibility: store.Private, spaceID: &spaceA.ID, tag: "a-private"},
{uid: "stats-scope-a-member-private", creatorID: member.ID, visibility: store.Private, spaceID: &spaceA.ID, tag: "member-private"},
{uid: "stats-scope-b-public", creatorID: owner.ID, visibility: store.Public, spaceID: &spaceB.ID, tag: "b-public"},
}
for _, fixture := range fixtures {
_, err := ts.Store.CreateMemo(ctx, &store.Memo{
UID: fixture.uid,
CreatorID: fixture.creatorID,
Content: fixture.tag,
Visibility: fixture.visibility,
SpaceID: fixture.spaceID,
Payload: &storepb.MemoPayload{Tags: []string{fixture.tag}},
})
require.NoError(t, err)
}
ownerName := fmt.Sprintf("users/%s", owner.Username)
ownerCtx := ts.CreateUserContext(ctx, owner.ID)
ownerSpaceStats, err := ts.Service.GetUserStats(ownerCtx, &v1pb.GetUserStatsRequest{
Name: ownerName,
Filter: fmt.Sprintf(`space == %q`, spaceAName),
})
require.NoError(t, err)
require.Equal(t, int32(2), ownerSpaceStats.TotalMemoCount)
require.Contains(t, ownerSpaceStats.TagCount, "a-members")
require.Contains(t, ownerSpaceStats.TagCount, "a-private")
require.NotContains(t, ownerSpaceStats.TagCount, "unassigned")
require.NotContains(t, ownerSpaceStats.TagCount, "b-public")
ownerUnassignedStats, err := ts.Service.GetUserStats(ownerCtx, &v1pb.GetUserStatsRequest{
Name: ownerName,
Filter: `space == null`,
})
require.NoError(t, err)
require.Equal(t, int32(1), ownerUnassignedStats.TotalMemoCount)
require.Contains(t, ownerUnassignedStats.TagCount, "unassigned")
memberSpaceStats, err := ts.Service.ListAllUserStats(ts.CreateUserContext(ctx, member.ID), &v1pb.ListAllUserStatsRequest{
Filter: fmt.Sprintf(`space == %q`, spaceAName),
})
require.NoError(t, err)
require.Len(t, memberSpaceStats.Stats, 2)
visibleTags := map[string]int32{}
for _, stats := range memberSpaceStats.Stats {
for tag, count := range stats.TagCount {
visibleTags[tag] += count
}
}
require.Equal(t, map[string]int32{"a-members": 1, "member-private": 1}, visibleTags)
_, err = ts.Service.ListAllUserStats(ts.CreateUserContext(ctx, outsider.ID), &v1pb.ListAllUserStatsRequest{
Filter: fmt.Sprintf(`space == %q`, spaceAName),
})
require.Equal(t, codes.NotFound, status.Code(err))
_, err = ts.Service.ListAllUserStats(ctx, &v1pb.ListAllUserStatsRequest{
Filter: fmt.Sprintf(`space == %q`, spaceAName),
})
require.Equal(t, codes.Unauthenticated, status.Code(err))
_, err = ts.Service.GetUserStats(ownerCtx, &v1pb.GetUserStatsRequest{
Name: ownerName,
Filter: `space != null`,
})
require.Equal(t, codes.InvalidArgument, status.Code(err))
}

View file

@ -68,8 +68,8 @@ func (s *APIV1Service) ListAllUserStats(ctx context.Context, request *v1pb.ListA
}
if request.Filter != "" {
if err := s.validateFilter(ctx, request.Filter); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
if err := s.validateMemoFilterForUser(ctx, request.Filter, currentUser); err != nil {
return nil, err
}
memoFind.Filters = append(memoFind.Filters, request.Filter)
}
@ -190,7 +190,7 @@ func (s *APIV1Service) GetUserStats(ctx context.Context, request *v1pb.GetUserSt
}
userID := user.ID
accessScope, _, err := s.resolveMemoAccessScope(ctx)
accessScope, currentUser, err := s.resolveMemoAccessScope(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "%v", err)
}
@ -204,6 +204,13 @@ func (s *APIV1Service) GetUserStats(ctx context.Context, request *v1pb.GetUserSt
RowStatus: &normalStatus,
}
if request.Filter != "" {
if err := s.validateMemoFilterForUser(ctx, request.Filter, currentUser); err != nil {
return nil, err
}
memoFind.Filters = append(memoFind.Filters, request.Filter)
}
memoFind.Access = accessScope
createdTimestamps := []*timestamppb.Timestamp{}

View file

@ -151,6 +151,7 @@ func (d *DB) ListAttachments(ctx context.Context, find *store.FindAttachment) ([
query := "SELECT " + strings.Join(fields, ", ") + " FROM `attachment`" + " " +
"LEFT JOIN `memo` ON `attachment`.`memo_id` = `memo`.`id`" + " " +
"LEFT JOIN `space` AS `attachment_space` ON `memo`.`space_id` = `attachment_space`.`id`" + " " +
"WHERE " + strings.Join(where, " AND ") + " " +
"ORDER BY `updated_ts` DESC"
if find.Limit != nil {

View file

@ -169,9 +169,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
}
where = append(where, fmt.Sprintf("`memo`.`visibility` in (%s)", strings.Join(placeholder, ",")))
}
if v := find.SpaceID; v != nil {
where, args = append(where, "`memo`.`space_id` = ?"), append(args, *v)
}
if v := find.CommentContextMemoID; v != nil {
where, args = append(where, `EXISTS (
SELECT 1 FROM memo_relation AS comment_context
@ -180,9 +177,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
AND comment_context.type = 'COMMENT'
)`), append(args, *v)
}
if find.Unassigned {
where = append(where, "`memo`.`space_id` IS NULL")
}
if access := find.Access; access != nil {
where = append(where, mysqlMemoAccessPredicate(access, "`memo`", "`access_member`", &args))
}
@ -231,6 +225,7 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
query := "SELECT " + strings.Join(fields, ", ") + " FROM `memo`" + " " +
"LEFT JOIN `user` AS `memo_creator` ON `memo`.`creator_id` = `memo_creator`.`id`" + " " +
"LEFT JOIN `space` AS `memo_space` ON `memo`.`space_id` = `memo_space`.`id`" + " " +
"WHERE " + strings.Join(where, " AND ") + " " +
"HAVING " + strings.Join(having, " AND ") + " " +
"ORDER BY " + strings.Join(orderBy, ", ")

View file

@ -148,6 +148,7 @@ func (d *DB) ListAttachments(ctx context.Context, find *store.FindAttachment) ([
%s
FROM attachment
LEFT JOIN memo ON attachment.memo_id = memo.id
LEFT JOIN space AS attachment_space ON memo.space_id = attachment_space.id
WHERE %s
ORDER BY attachment.updated_ts DESC
`, strings.Join(fields, ", "), strings.Join(where, " AND "))

View file

@ -146,9 +146,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
}
where = append(where, fmt.Sprintf("memo.visibility in (%s)", strings.Join(holders, ", ")))
}
if v := find.SpaceID; v != nil {
where, args = append(where, "memo.space_id = "+placeholder(len(args)+1)), append(args, *v)
}
if v := find.CommentContextMemoID; v != nil {
contextHolder := placeholder(len(args) + 1)
args = append(args, *v)
@ -159,9 +156,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
AND comment_context.type = 'COMMENT'
)`)
}
if find.Unassigned {
where = append(where, "memo.space_id IS NULL")
}
if access := find.Access; access != nil {
where = append(where, postgresMemoAccessPredicate(access, "memo", "access_member", &args))
}
@ -211,6 +205,7 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
query := `SELECT ` + strings.Join(fields, ", ") + `
FROM memo
LEFT JOIN "user" AS memo_creator ON memo.creator_id = memo_creator.id
LEFT JOIN space AS memo_space ON memo.space_id = memo_space.id
WHERE ` + strings.Join(where, " AND ") + `
ORDER BY ` + strings.Join(orderBy, ", ")
if find.Limit != nil {

View file

@ -142,6 +142,7 @@ func (d *DB) ListAttachments(ctx context.Context, find *store.FindAttachment) ([
query := "SELECT " + strings.Join(fields, ", ") + " FROM `attachment`" + " " +
"LEFT JOIN `memo` ON `attachment`.`memo_id` = `memo`.`id`" + " " +
"LEFT JOIN `space` AS `attachment_space` ON `memo`.`space_id` = `attachment_space`.`id`" + " " +
"WHERE " + strings.Join(where, " AND ") + " " +
"ORDER BY `attachment`.`updated_ts` DESC"
if find.Limit != nil {

View file

@ -154,9 +154,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
}
where = append(where, fmt.Sprintf("`memo`.`visibility` IN (%s)", strings.Join(placeholder, ",")))
}
if v := find.SpaceID; v != nil {
where, args = append(where, "`memo`.`space_id` = ?"), append(args, *v)
}
if v := find.CommentContextMemoID; v != nil {
where, args = append(where, `EXISTS (
SELECT 1 FROM memo_relation AS comment_context
@ -165,9 +162,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
AND comment_context.type = 'COMMENT'
)`), append(args, *v)
}
if find.Unassigned {
where = append(where, "`memo`.`space_id` IS NULL")
}
if access := find.Access; access != nil {
where = append(where, sqliteMemoAccessPredicate(access, "`memo`", "`access_member`", &args))
}
@ -216,6 +210,7 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo
query := "SELECT " + strings.Join(fields, ", ") + " FROM `memo` " +
"LEFT JOIN `user` AS `memo_creator` ON `memo`.`creator_id` = `memo_creator`.`id` " +
"LEFT JOIN `space` AS `memo_space` ON `memo`.`space_id` = `memo_space`.`id` " +
"WHERE " + strings.Join(where, " AND ") + " " +
"ORDER BY " + strings.Join(orderBy, ", ")
if find.Limit != nil {

View file

@ -80,9 +80,7 @@ type FindMemo struct {
// Domain specific fields
VisibilityList []Visibility
SpaceID *int32
CommentContextMemoID *int32
Unassigned bool
Access *MemoAccessScope
ExcludeContent bool
ExcludeComments bool

View file

@ -56,6 +56,77 @@ func TestAttachmentAccessScopeFiltersBeforePagination(t *testing.T) {
require.Equal(t, unlinked.ID, attachments[0].ID, "the inaccessible newer row must be removed before LIMIT is applied")
}
func TestAttachmentSpaceFilterFiltersByMemoPlacement(t *testing.T) {
ctx := context.Background()
ts := NewTestingStore(ctx, t)
defer ts.Close()
owner, err := ts.CreateUser(ctx, &store.User{Username: "attachment-scope-owner", Role: store.RoleUser, PasswordHash: "hash"})
require.NoError(t, err)
spaceA, err := ts.CreateSpace(ctx, &store.Space{UID: "attachment-scope-a", Title: "A"}, owner.ID)
require.NoError(t, err)
spaceB, err := ts.CreateSpace(ctx, &store.Space{UID: "attachment-scope-b", Title: "B"}, owner.ID)
require.NoError(t, err)
unassignedMemo, err := ts.CreateMemo(ctx, &store.Memo{
UID: "attachment-scope-unassigned", CreatorID: owner.ID, Content: "unassigned", Visibility: store.Private,
})
require.NoError(t, err)
spaceAMemo, err := ts.CreateMemo(ctx, &store.Memo{
UID: "attachment-scope-a-memo", CreatorID: owner.ID, Content: "a", Visibility: store.Private, SpaceID: &spaceA.ID,
})
require.NoError(t, err)
spaceBMemo, err := ts.CreateMemo(ctx, &store.Memo{
UID: "attachment-scope-b-memo", CreatorID: owner.ID, Content: "b", Visibility: store.Public, SpaceID: &spaceB.ID,
})
require.NoError(t, err)
createAttachment := func(uid string, memoID *int32) *store.Attachment {
t.Helper()
attachment, createErr := ts.CreateAttachment(ctx, &store.Attachment{
UID: uid, CreatorID: owner.ID, Filename: uid + ".txt", Type: "text/plain", MemoID: memoID,
})
require.NoError(t, createErr)
return attachment
}
unlinked := createAttachment("attachment-scope-unlinked", nil)
unassigned := createAttachment("attachment-scope-unassigned-file", &unassignedMemo.ID)
inSpaceANewer := createAttachment("attachment-scope-a-newer", &spaceAMemo.ID)
inSpaceAOlder := createAttachment("attachment-scope-a-older", &spaceAMemo.ID)
inSpaceB := createAttachment("attachment-scope-b-file", &spaceBMemo.ID)
baseTime := time.Now().Unix() - 100
for attachment, updatedTs := range map[*store.Attachment]int64{
inSpaceB: baseTime + 50,
inSpaceANewer: baseTime + 40,
unlinked: baseTime + 30,
inSpaceAOlder: baseTime + 20,
unassigned: baseTime + 10,
} {
require.NoError(t, ts.UpdateAttachment(ctx, &store.UpdateAttachment{ID: attachment.ID, UpdatedTs: &updatedTs}))
}
access := &store.MemoAccessScope{UserID: &owner.ID, AllowPublic: true, AllowProtected: true}
limit, firstOffset := 1, 0
spaceAttachments, err := ts.ListAttachments(ctx, &store.FindAttachment{
CreatorID: &owner.ID, Access: access, Filters: []string{`space == "spaces/attachment-scope-a"`}, Limit: &limit, Offset: &firstOffset,
})
require.NoError(t, err)
require.Equal(t, []int32{inSpaceANewer.ID}, attachmentIDs(spaceAttachments), "filter must be applied before the first page")
secondOffset := 1
spaceAttachments, err = ts.ListAttachments(ctx, &store.FindAttachment{
CreatorID: &owner.ID, Access: access, Filters: []string{`space == "spaces/attachment-scope-a"`}, Limit: &limit, Offset: &secondOffset,
})
require.NoError(t, err)
require.Equal(t, []int32{inSpaceAOlder.ID}, attachmentIDs(spaceAttachments), "filter must be applied before the second page")
unassignedAttachments, err := ts.ListAttachments(ctx, &store.FindAttachment{
CreatorID: &owner.ID, Access: access, Filters: []string{`space == null`}, SkipDefaultLimit: true,
})
require.NoError(t, err)
require.ElementsMatch(t, []int32{unlinked.ID, unassigned.ID}, attachmentIDs(unassignedAttachments))
}
func TestAttachmentAccessScopeUsesDirectMemoAudience(t *testing.T) {
ctx := context.Background()
ts := NewTestingStore(ctx, t)

View file

@ -43,6 +43,7 @@ import { useAuth } from "@/contexts/AuthContext";
import { useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext";
import { useInstance } from "@/contexts/InstanceContext";
import { stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useAttachmentLibraryStats } from "@/hooks/useAttachmentLibrary";
import useCurrentUser from "@/hooks/useCurrentUser";
import { type MemoStatsContext, useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
@ -71,6 +72,7 @@ import SidebarSection, {
SIDEBAR_SECTION_ACTION_ICON_CLASSES,
SIDEBAR_SECTION_STACK_CLASSES,
} from "./SidebarSection";
import SpaceSwitcher from "./SpaceSwitcher";
import TagsSection from "./TagsSection";
const SIDEBAR_HORIZONTAL_PADDING = "px-3";
@ -245,6 +247,7 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) =>
const t = useTranslate();
const location = useLocation();
const currentUser = useCurrentUser();
const { memoFilter, selectedSpaceName } = useSpaceContext();
const md = useMediaQuery("md");
const { mobileOpen, setMobileOpen } = useAppSidebar();
const { isInitialized: authInitialized } = useAuth();
@ -254,9 +257,13 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) =>
enabled: context === "profile" && !!profileMatch?.params.username,
});
const statsUserName = context === "home" ? currentUser?.name : context === "profile" ? profileUser?.name : undefined;
// Profile remains instance-level, so its calendar must stay aligned with the unscoped profile feed.
const statsFilter = context === "profile" ? undefined : memoFilter;
const { statistics, tags } = useFilteredMemoStats({
context,
userName: statsUserName,
filter: statsFilter,
includeSpaceVisibility: !!selectedSpaceName,
enabled: authInitialized && instanceInitialized && (md || mobileOpen),
});
@ -266,6 +273,7 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) =>
// clicks must land somewhere that renders the filtered feed.
const onCollectionRoute = isMemoScopeRoute(location.pathname) || !!profileMatch;
const filterTarget = onCollectionRoute ? undefined : context === "explore" ? ROUTES.EXPLORE : ROUTES.HOME;
const tagStateScope = `${statsUserName ?? context}${selectedSpaceName ? `:${selectedSpaceName}` : ""}`;
return (
<div className={SIDEBAR_SECTION_STACK_CLASSES}>
@ -274,15 +282,16 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) =>
<StatisticsView statisticsData={statistics} navigationTarget={filterTarget} onDateSelect={() => setMobileOpen(false)} />
</SidebarSection>
{showViews && <ViewsSection />}
<TagsSection tagCount={tags} navigationTarget={filterTarget} scope={statsUserName ?? context} onSelect={() => setMobileOpen(false)} />
<TagsSection tagCount={tags} navigationTarget={filterTarget} scope={tagStateScope} onSelect={() => setMobileOpen(false)} />
</div>
);
};
const AttachmentsSidebarContent = () => {
const t = useTranslate();
const { memoFilter, selectedSpaceName } = useSpaceContext();
const { attachmentSection, setAttachmentSection, setMobileOpen } = useAppSidebar();
const { isComplete, stats } = useAttachmentLibraryStats();
const { isComplete, stats } = useAttachmentLibraryStats(memoFilter);
const total = stats.media + stats.documents + stats.audio;
const rows: Array<{ value: AttachmentSection; icon: LucideIcon; label: string; count?: number }> = [
{ value: "all", icon: ListIcon, label: t("common.all"), count: isComplete ? total : undefined },
@ -294,8 +303,16 @@ const AttachmentsSidebarContent = () => {
label: t("attachment-library.tabs.documents"),
count: isComplete ? stats.documents : undefined,
},
{ value: "unused", icon: Trash2Icon, label: t("attachment-library.labels.unused"), count: isComplete ? stats.unused : undefined },
];
// Unlinked uploads do not belong to any Space, so "Unused" is only a Memos-level collection.
if (!selectedSpaceName) {
rows.push({
value: "unused",
icon: Trash2Icon,
label: t("attachment-library.labels.unused"),
count: isComplete ? stats.unused : undefined,
});
}
return (
<SidebarSection label={t("common.attachments")}>
{rows.map((row) => (
@ -628,6 +645,21 @@ const GlobalNavigation = () => {
);
};
/** The sidebar/header brand slot: the Space switcher when signed in, the plain logo otherwise. */
const SidebarBrand = ({ className }: { className?: string }) => {
const currentUser = useCurrentUser();
if (currentUser) {
return <SpaceSwitcher className={className} />;
}
return (
<Link to={ROUTES.EXPLORE} className={cn("min-w-0 rounded-md focus-visible:outline-none", className)}>
<MemosLogo compact />
</Link>
);
};
const AppSidebar = ({ className }: { className?: string }) => {
const t = useTranslate();
const currentUser = useCurrentUser();
@ -636,12 +668,7 @@ const AppSidebar = ({ className }: { className?: string }) => {
return (
<aside className={cn("flex h-full w-full select-none flex-col bg-sidebar text-sidebar-foreground", className)}>
<div className={cn("flex h-13 shrink-0 items-center justify-between gap-2", SIDEBAR_HORIZONTAL_PADDING)}>
<Link
to={currentUser ? ROUTES.HOME : ROUTES.EXPLORE}
className="min-w-0 flex-1 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
>
<MemosLogo compact />
</Link>
<SidebarBrand className="w-full flex-1" />
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
@ -688,7 +715,6 @@ const AppSidebar = ({ className }: { className?: string }) => {
};
export const MobileAppHeader = () => {
const currentUser = useCurrentUser();
const { setMobileOpen } = useAppSidebar();
return (
<header className="sticky top-0 z-20 flex h-12 w-full items-center justify-start gap-1 border-b border-border/70 bg-background/90 px-2 backdrop-blur-md md:hidden">
@ -702,12 +728,7 @@ export const MobileAppHeader = () => {
>
<MenuIcon className="size-[18px]" />
</Button>
<Link
to={currentUser ? ROUTES.HOME : ROUTES.EXPLORE}
className="min-w-0 max-w-[12rem] rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
>
<MemosLogo compact />
</Link>
<SidebarBrand className="max-w-[12rem]" />
</header>
);
};

View file

@ -0,0 +1,136 @@
import { CheckIcon, ChevronsUpDownIcon, LoaderCircleIcon, type LucideIcon, PlusIcon } from "lucide-react";
import { type ReactNode, useState } from "react";
import CreateSpaceDialog from "@/components/CreateSpaceDialog";
import MemosLogo from "@/components/MemosLogo";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { cn } from "@/lib/utils";
import type { Space } from "@/types/proto/api/v1/space_service_pb";
import { useTranslate } from "@/utils/i18n";
// Mirrors MemosLogo's compact scale so the brand and a Space read as peers in the menu.
const MARK_SCALE = {
md: "size-7 rounded-[7px] text-[13px]",
sm: "size-5 rounded-[5px] text-[11px]",
} as const;
const SpaceMark = ({ space, size = "md" }: { space?: Space; size?: "sm" | "md" }) => {
const label = space?.title.trim() || "S";
const initial = Array.from(label)[0]?.toLocaleUpperCase() ?? "S";
return (
<span
aria-hidden
className={cn(
"flex shrink-0 items-center justify-center bg-sidebar-accent font-semibold text-sidebar-accent-foreground",
MARK_SCALE[size],
)}
>
{initial}
</span>
);
};
// Icons in action and status rows sit in a glyph-width slot so every label in the menu
// starts on the same text rail as the context rows.
const RowIcon = ({ icon: Icon, className }: { icon: LucideIcon; className?: string }) => (
<span className="flex size-5 shrink-0 items-center justify-center">
<Icon className={cn("size-3.5", className)} />
</span>
);
const ContextItem = ({ selected, onSelect, children }: { selected: boolean; onSelect: () => void; children: ReactNode }) => (
<DropdownMenuItem role="menuitemradio" aria-checked={selected} closeOnClick onClick={onSelect} className={cn(selected && "bg-accent/60")}>
{children}
{selected && <CheckIcon className="ms-auto size-3.5 shrink-0 text-primary" />}
</DropdownMenuItem>
);
function SpaceSwitcher({ className }: { className?: string }) {
const t = useTranslate();
const { spaces, selectedSpace, selectedSpaceName, isLoadingSpaces, isSpacesError, selectMemos, selectSpace } = useSpaceContext();
const [createOpen, setCreateOpen] = useState(false);
const currentContextLabel = selectedSpaceName ? selectedSpace?.title || t("space.current") : t("common.memos");
return (
<>
<DropdownMenu>
<DropdownMenuTrigger
render={
<button
type="button"
aria-label={`${t("space.switch")}: ${currentContextLabel}`}
className={cn(
"group flex h-9 min-w-0 max-w-full items-center gap-1 rounded-md px-0.5 text-start focus-visible:outline-none",
className,
)}
/>
}
>
<span className="flex min-w-0 flex-1 items-center">
{selectedSpaceName ? (
<>
<SpaceMark space={selectedSpace} />
<span className="ms-1.5 min-w-0 truncate text-[14px] font-medium tracking-[-0.01em] text-foreground">
{selectedSpace?.title || t("space.current")}
</span>
</>
) : (
<MemosLogo compact />
)}
</span>
<ChevronsUpDownIcon className="size-3.5 shrink-0 text-muted-foreground/70" strokeWidth={1.8} />
</DropdownMenuTrigger>
<DropdownMenuContent size="sm" align="start" sideOffset={4} className="w-[min(15rem,calc(100vw-1rem))]">
<DropdownMenuGroup>
<ContextItem selected={!selectedSpaceName} onSelect={selectMemos}>
<span className="min-w-0 flex-1">
<MemosLogo compact size="sm" />
</span>
</ContextItem>
{spaces.length > 0 && (
<>
<DropdownMenuLabel className="pb-0.5 pt-1.5 font-normal text-muted-foreground">{t("space.spaces")}</DropdownMenuLabel>
{spaces.map((space) => (
<ContextItem key={space.name} selected={space.name === selectedSpaceName} onSelect={() => selectSpace(space)}>
<SpaceMark space={space} size="sm" />
<span className="min-w-0 flex-1 truncate font-medium">{space.title}</span>
</ContextItem>
))}
</>
)}
</DropdownMenuGroup>
{/* isLoadingSpaces implies no data yet, so these only ever show on an empty list. */}
{isLoadingSpaces && (
<DropdownMenuItem disabled>
<RowIcon icon={LoaderCircleIcon} className="animate-spin" />
{t("space.loading")}
</DropdownMenuItem>
)}
{isSpacesError && spaces.length === 0 && (
<DropdownMenuItem disabled>
<span className="size-5 shrink-0" />
{t("space.load-error")}
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setCreateOpen(true)}>
<RowIcon icon={PlusIcon} />
{t("space.create")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<CreateSpaceDialog open={createOpen} onOpenChange={setCreateOpen} />
</>
);
}
export default SpaceSwitcher;

View file

@ -0,0 +1,105 @@
import { type FormEvent, useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useCreateSpace } from "@/hooks/useSpaceQueries";
import { handleError } from "@/lib/error";
import { useTranslate } from "@/utils/i18n";
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
}
function CreateSpaceDialog({ open, onOpenChange }: Props) {
const t = useTranslate();
const currentUserName = useCurrentUser()?.name ?? "";
const { selectSpace } = useSpaceContext();
const createSpace = useCreateSpace(currentUserName);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
useEffect(() => {
if (!open) {
setTitle("");
setDescription("");
}
}, [open]);
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const trimmedTitle = title.trim();
if (!trimmedTitle || createSpace.isPending) {
return;
}
try {
const space = await createSpace.mutateAsync({
title: trimmedTitle,
description: description.trim() || undefined,
});
selectSpace(space);
toast.success(t("space.create-success"));
onOpenChange(false);
} catch (error) {
handleError(error, toast.error, { context: "Create space" });
}
};
const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen && createSpace.isPending) {
return;
}
onOpenChange(nextOpen);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent size="sm">
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<DialogHeader>
<DialogTitle>{t("space.create")}</DialogTitle>
<DialogDescription>{t("space.create-description")}</DialogDescription>
</DialogHeader>
<div className="grid gap-2">
<Label htmlFor="space-title">{t("common.name")}</Label>
<Input
id="space-title"
value={title}
onChange={(event) => setTitle(event.target.value)}
placeholder={t("space.name-placeholder")}
autoComplete="off"
autoFocus
/>
</div>
<div className="grid gap-2">
<Label htmlFor="space-description">{t("common.description")}</Label>
<Textarea
id="space-description"
value={description}
onChange={(event) => setDescription(event.target.value)}
placeholder={t("space.description-placeholder")}
className="min-h-20 resize-none"
/>
</div>
<p className="text-xs text-muted-foreground">{t("space.creator-admin-note")}</p>
<DialogFooter>
<Button type="button" variant="ghost" disabled={createSpace.isPending} onClick={() => onOpenChange(false)}>
{t("common.cancel")}
</Button>
<Button type="submit" disabled={!title.trim() || createSpace.isPending}>
{t("common.create")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
export default CreateSpaceDialog;

View file

@ -1,23 +1,22 @@
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import VisibilityIcon from "@/components/VisibilityIcon";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { cn } from "@/lib/utils";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { getAssignableVisibilityOptions, getVisibilityOption } from "@/utils/memo";
import type { VisibilitySelectorProps } from "../types";
const VisibilitySelector = (props: VisibilitySelectorProps) => {
const { value, onChange } = props;
const compact = props.size === "compact";
const t = useTranslate();
const { selectedSpaceName } = useSpaceContext();
const visibilityOptions = [
{ value: Visibility.PRIVATE, label: t("memo.visibility.private"), description: t("memo.visibility.private-description") },
{ value: Visibility.PROTECTED, label: t("memo.visibility.protected"), description: t("memo.visibility.protected-description") },
{ value: Visibility.PUBLIC, label: t("memo.visibility.public"), description: t("memo.visibility.public-description") },
] as const;
const currentLabel = visibilityOptions.find((option) => option.value === value)?.label || "";
const visibilityOptions = getAssignableVisibilityOptions({ spaceSelected: Boolean(selectedSpaceName), current: value });
// Resolved from the full catalog, so the trigger names the memo's audience even
// when that audience is not currently on offer.
const currentOption = getVisibilityOption(value);
return (
<DropdownMenu onOpenChange={props.onOpenChange}>
@ -32,7 +31,7 @@ const VisibilitySelector = (props: VisibilitySelectorProps) => {
}
>
<VisibilityIcon visibility={value} className={cn("opacity-60 mr-1.5", compact && "w-[13px]")} />
<span className="truncate">{currentLabel}</span>
<span className="truncate">{currentOption ? t(currentOption.labelKey) : ""}</span>
<ChevronDownIcon className={cn("ml-0.5 opacity-60", compact ? "size-3.5 text-muted-foreground/70" : "w-4 h-4")} />
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
@ -40,8 +39,8 @@ const VisibilitySelector = (props: VisibilitySelectorProps) => {
<DropdownMenuItem key={option.value} onClick={() => onChange(option.value)}>
<VisibilityIcon visibility={option.value} />
<div className="flex flex-col">
<span>{option.label}</span>
<span className="text-xs text-muted-foreground">{option.description}</span>
<span>{t(option.labelKey)}</span>
<span className="text-xs text-muted-foreground">{t(option.descriptionKey)}</span>
</div>
{value === option.value && <CheckIcon className="ml-auto w-4 h-4 text-primary" />}
</DropdownMenuItem>

View file

@ -2,6 +2,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import { toast } from "react-hot-toast";
import { useNewMemo } from "@/contexts/NewMemoContext";
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
import { memoKeys } from "@/hooks/useMemoQueries";
import { userKeys } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
@ -13,6 +14,7 @@ import { useEditorContext } from "../state";
interface UseMemoSaveOptions {
memoName?: string;
parentMemoName?: string;
defaultSpace?: string;
defaultVisibility?: Visibility;
defaultCreateTime?: Date;
discardDraft: () => void;
@ -28,6 +30,7 @@ interface UseMemoSaveOptions {
export function useMemoSave({
memoName,
parentMemoName,
defaultSpace,
defaultVisibility,
defaultCreateTime,
discardDraft,
@ -50,7 +53,7 @@ export function useMemoSave({
dispatch(actions.setLoading("saving", true));
try {
const result = await memoService.save(state, { memoName, parentMemoName });
const result = await memoService.save(state, { memoName, parentMemoName, space: defaultSpace });
if (!result.hasChanges) {
toast.error(t("editor.no-changes-detected"));
@ -64,6 +67,7 @@ export function useMemoSave({
const invalidationPromises = [
queryClient.invalidateQueries({ queryKey: memoKeys.lists() }),
queryClient.invalidateQueries({ queryKey: userKeys.stats() }),
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() }),
];
if (memoName) {
invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.detail(memoName) }));
@ -98,6 +102,7 @@ export function useMemoSave({
}, [
actions,
defaultCreateTime,
defaultSpace,
defaultVisibility,
discardDraft,
dispatch,

View file

@ -41,6 +41,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
cacheKey,
memo,
parentMemoName,
defaultSpace,
autoFocus,
onFocusModeExit,
placeholder,
@ -286,6 +287,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
const handleSave = useMemoSave({
memoName,
parentMemoName,
defaultSpace,
defaultVisibility,
defaultCreateTime,
discardDraft,

View file

@ -82,6 +82,7 @@ export const memoService = {
options: {
memoName?: string;
parentMemoName?: string;
space?: string;
},
): Promise<{ memoName: string; hasChanges: boolean }> {
// 1. Upload local files first
@ -113,6 +114,7 @@ export const memoService = {
location: state.metadata.location,
createTime: state.timestamps.createTime ? timestampFromDate(state.timestamps.createTime) : undefined,
updateTime: state.timestamps.updateTime ? timestampFromDate(state.timestamps.updateTime) : undefined,
space: options.parentMemoName ? undefined : options.space,
});
const memo = options.parentMemoName

View file

@ -10,6 +10,8 @@ export interface MemoEditorProps {
/** Existing memo to edit. When provided, the editor initializes from it without fetching. */
memo?: Memo;
parentMemoName?: string;
/** Assigns a newly created top-level memo to this Space. Ignored for edits and comments. */
defaultSpace?: string;
autoFocus?: boolean;
/**
* Marks the instance as *hosted*: a host (the global composer dialog) presents

View file

@ -10,7 +10,7 @@ import { cn } from "@/lib/utils";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
import type { User } from "@/types/proto/api/v1/user_service_pb";
import { useTranslate } from "@/utils/i18n";
import { convertVisibilityToString } from "@/utils/memo";
import { getVisibilityOption } from "@/utils/memo";
import MemoActionMenu from "../../MemoActionMenu";
import { ReactionSelector } from "../../MemoReactionListView";
import UserAvatar from "../../UserAvatar";
@ -26,6 +26,7 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ showCreator, showVisibility, sh
const { memo, creator, currentUser, parentPage, isArchived, readonly, openEditor } = useMemoViewContext();
const { createTime, updateTime, displayTime: memoDisplayTime, isDisplayingUpdatedTime, relativeTimeFormat } = useMemoViewDerived();
const { newMemoName } = useNewMemo();
const visibilityOption = getVisibilityOption(memo.visibility);
const navigateTo = useNavigateTo();
const handleGotoMemoDetailPage = useCallback(() => {
@ -85,9 +86,7 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ showCreator, showVisibility, sh
<VisibilityIcon visibility={memo.visibility} />
</span>
</TooltipTrigger>
<TooltipContent>
{t(`memo.visibility.${convertVisibilityToString(memo.visibility).toLowerCase()}` as Parameters<typeof t>[0])}
</TooltipContent>
<TooltipContent>{visibilityOption && t(visibilityOption.labelKey)}</TooltipContent>
</Tooltip>
)}

View file

@ -6,10 +6,20 @@ interface Props {
className?: string;
collapsed?: boolean;
compact?: boolean;
/** Scale of the compact lockup: "md" for headers, "sm" for dense menu rows. */
size?: "sm" | "md";
}
// Kept in step with SpaceMark in SpaceSwitcher, so the brand and a Space read as peers
// wherever the two are listed together.
const COMPACT_SCALE = {
md: { mark: "size-7 rounded-[7px]", title: "ml-1.5 text-[14px]" },
sm: { mark: "size-5 rounded-[5px]", title: "ml-1.5 text-ui" },
} as const;
function MemosLogo(props: Props) {
const { collapsed, compact } = props;
const { collapsed, compact, size = "md" } = props;
const scale = COMPACT_SCALE[size];
const { generalSetting: instanceGeneralSetting } = useInstance();
const title = instanceGeneralSetting.customProfile?.title || "Memos";
const avatarUrl = instanceGeneralSetting.customProfile?.logoUrl || "/full-logo.webp";
@ -19,13 +29,10 @@ function MemosLogo(props: Props) {
<div
className={cn("w-auto flex flex-row justify-start items-center text-foreground", compact ? "px-0" : collapsed ? "px-1" : "px-3")}
>
<UserAvatar className={cn("shrink-0", compact && "size-7 rounded-[7px]")} avatarUrl={avatarUrl} />
<UserAvatar className={cn("shrink-0", compact && scale.mark)} avatarUrl={avatarUrl} />
{!collapsed && (
<span
className={cn(
"font-medium text-foreground shrink truncate",
compact ? "ml-1.5 text-[14px] tracking-[-0.01em]" : "ml-2 text-lg",
)}
className={cn("font-medium text-foreground shrink truncate", compact ? cn(scale.title, "tracking-[-0.01em]") : "ml-2 text-lg")}
>
{title}
</span>

View file

@ -9,6 +9,7 @@ import { useView } from "@/contexts/ViewContext";
import { useDelayedFlag } from "@/hooks/useDelayedFlag";
import { useInfiniteMemos } from "@/hooks/useMemoQueries";
import { hoistMemoToFront } from "@/hooks/useMemoSorting";
import { combineCELFilters } from "@/lib/cel-filter";
import { DEFAULT_LIST_MEMOS_PAGE_SIZE, LOADING_INDICATOR_DELAY_MS } from "@/lib/constants";
import { cn } from "@/lib/utils";
import { State } from "@/types/proto/api/v1/common_pb";
@ -40,6 +41,7 @@ interface Props {
state?: State;
orderBy?: string;
filter?: string;
contextFilter?: string;
pageSize?: number;
showCreator?: boolean;
enabled?: boolean;
@ -146,7 +148,7 @@ const PagedMemoList = (props: Props) => {
{
state: props.state || State.NORMAL,
orderBy: props.orderBy || "create_time desc",
filter: props.filter,
filter: combineCELFilters(props.contextFilter, props.filter),
pageSize: props.pageSize || DEFAULT_LIST_MEMOS_PAGE_SIZE,
},
{ enabled: props.enabled ?? true },

View file

@ -4,10 +4,9 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Switch } from "@/components/ui/switch";
import { useAuth } from "@/contexts/AuthContext";
import { useUpdateUserGeneralSetting } from "@/hooks/useUserQueries";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { UserSetting_GeneralSetting, UserSetting_GeneralSettingSchema } from "@/types/proto/api/v1/user_service_pb";
import { loadLocale, useTranslate } from "@/utils/i18n";
import { convertVisibilityFromString, convertVisibilityToString } from "@/utils/memo";
import { convertVisibilityFromString, DEFAULT_VISIBILITY_OPTIONS } from "@/utils/memo";
import { loadTheme } from "@/utils/theme";
import LocaleSelect from "../LocaleSelect";
import ThemeSelect from "../ThemeSelect";
@ -36,11 +35,7 @@ const PreferencesSection = () => {
};
const visibilityOptions = useMemo(
() =>
[Visibility.PRIVATE, Visibility.PROTECTED, Visibility.PUBLIC].map((v) => {
const value = convertVisibilityToString(v);
return { value, label: t(`memo.visibility.${value.toLowerCase() as Lowercase<typeof value>}`) };
}),
() => DEFAULT_VISIBILITY_OPTIONS.map((option) => ({ value: option.name, label: t(option.labelKey) })),
[t],
);

View file

@ -1,6 +1,6 @@
import { Globe2Icon, LockIcon, UsersIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
import type { Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { getVisibilityOption } from "@/utils/memo";
interface Props {
visibility: Visibility;
@ -9,15 +9,8 @@ interface Props {
const VisibilityIcon = (props: Props) => {
const { className, visibility } = props;
const VIcon = getVisibilityOption(visibility)?.icon;
let VIcon = null;
if (visibility === Visibility.PRIVATE) {
VIcon = LockIcon;
} else if (visibility === Visibility.PROTECTED) {
VIcon = UsersIcon;
} else if (visibility === Visibility.PUBLIC) {
VIcon = Globe2Icon;
}
if (!VIcon) {
return null;
}

View file

@ -9,6 +9,7 @@ import { IdentityProviderService } from "./types/proto/api/v1/idp_service_pb";
import { InstanceService } from "./types/proto/api/v1/instance_service_pb";
import { MemoService } from "./types/proto/api/v1/memo_service_pb";
import { MemoViewService } from "./types/proto/api/v1/memo_view_service_pb";
import { SpaceService } from "./types/proto/api/v1/space_service_pb";
import { UserService } from "./types/proto/api/v1/user_service_pb";
import { redirectOnAuthFailure } from "./utils/auth-redirect";
@ -198,6 +199,7 @@ export const memoServiceClient = createClient(MemoService, transport);
export const attachmentServiceClient = createClient(AttachmentService, transport);
export const aiServiceClient = createClient(AIService, transport);
export const memoViewServiceClient = createClient(MemoViewService, transport);
export const spaceServiceClient = createClient(SpaceService, transport);
// Configuration service clients
export const identityProviderServiceClient = createClient(IdentityProviderService, transport);

View file

@ -5,7 +5,9 @@ import type { MemoEditorProps } from "@/components/MemoEditor/types";
import { VisuallyHidden } from "@/components/ui/visually-hidden";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { spaceScopedCacheKey } from "@/lib/resource-names";
import { useTranslate } from "@/utils/i18n";
interface GlobalMemoEditorContextValue {
@ -35,11 +37,13 @@ const findVisibleFocusTarget = (selector: string): HTMLElement | null =>
export function GlobalMemoEditorProvider({ children }: { children: ReactNode }) {
const t = useTranslate();
const currentUserName = useCurrentUser()?.name;
const { selectedSpaceName } = useSpaceContext();
const { isUserSettingsInitialized } = useAuth();
const { setMobileOpen, setQuickFindOpen } = useAppSidebar();
// Keyed by the user who opened it, so signing out closes the composer in the
// same render and a different user signing in cannot resurrect it.
const [openedFor, setOpenedFor] = useState<string>();
// One snapshot taken when the composer opens: keyed by the user who opened it, so
// signing out closes the composer in the same render and a different user signing
// in cannot resurrect it, and pinned to the Space that was selected at that moment.
const [opened, setOpened] = useState<{ user: string; space?: string }>();
const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
// Only ever read from event handlers, so a ref keeps each save from
// re-rendering the provider and the whole editor tree it hosts.
@ -50,7 +54,7 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
const closeEditor = useCallback(() => {
openRequestVersionRef.current += 1;
isSavingRef.current = false;
setOpenedFor(undefined);
setOpened(undefined);
}, []);
const requestCloseEditor = useCallback(() => {
if (!isSavingRef.current) closeEditor();
@ -79,10 +83,10 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
.then(({ default: MemoEditor }) => {
if (openRequestVersionRef.current !== requestVersion) return;
setEditorComponent(() => MemoEditor);
setOpenedFor(currentUserName);
setOpened({ user: currentUserName, space: selectedSpaceName });
})
.catch(() => undefined);
}, [canOpen, currentUserName, setMobileOpen, setQuickFindOpen]);
}, [canOpen, currentUserName, selectedSpaceName, setMobileOpen, setQuickFindOpen]);
useEffect(() => {
// RootLayout remains mounted when a public instance moves from Home to
@ -102,7 +106,7 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
return remembered ?? findVisibleFocusTarget("[data-new-memo-trigger]") ?? findVisibleFocusTarget("[data-mobile-navigation-trigger]");
}, []);
const editorIsOpen = openedFor !== undefined && openedFor === currentUserName;
const editorIsOpen = opened !== undefined && opened.user === currentUserName;
const value = useMemo(() => ({ canOpen, openEditor }), [canOpen, openEditor]);
return (
@ -116,7 +120,7 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
return;
}
if (open) {
setOpenedFor(currentUserName);
setOpened((previous) => (currentUserName ? { user: currentUserName, space: previous?.space } : undefined));
} else {
closeEditor();
}
@ -136,7 +140,8 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
</VisuallyHidden>
<EditorComponent
autoFocus
cacheKey="global-memo-editor"
cacheKey={spaceScopedCacheKey("global-memo-editor", opened?.space)}
defaultSpace={opened?.space}
placeholder={t("editor.any-thoughts")}
onConfirm={closeEditor}
onCancel={closeEditor}

View file

@ -0,0 +1,144 @@
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useSpaces } from "@/hooks/useSpaceQueries";
import { buildSpaceFilter } from "@/lib/cel-filter";
import { ROUTES } from "@/router/routes";
import type { Space } from "@/types/proto/api/v1/space_service_pb";
const SELECTED_SPACE_STORAGE_PREFIX = "memos-selected-space:";
export const getSelectedSpaceStorageKey = (userName: string) => `${SELECTED_SPACE_STORAGE_PREFIX}${userName}`;
const readSelectedSpaceName = (userName: string): string | undefined => {
try {
return sessionStorage.getItem(getSelectedSpaceStorageKey(userName)) || undefined;
} catch {
return undefined;
}
};
const writeSelectedSpaceName = (userName: string, spaceName: string | undefined) => {
try {
const key = getSelectedSpaceStorageKey(userName);
if (spaceName) {
sessionStorage.setItem(key, spaceName);
} else {
sessionStorage.removeItem(key);
}
} catch {
// sessionStorage can be unavailable in restricted browser contexts.
}
};
interface SpaceContextValue {
spaces: Space[];
selectedSpace?: Space;
selectedSpaceName?: string;
memoFilter?: string;
isLoadingSpaces: boolean;
isSpacesError: boolean;
selectSpace: (space: Space) => void;
selectMemos: () => void;
}
const SpaceContext = createContext<SpaceContextValue | null>(null);
// Stable identity for the pre-load and error states, so the memoized context value
// below does not rebuild — and re-render every consumer — on each provider render.
const NO_SPACES: Space[] = [];
function UserSpaceSession({ userName, children }: { userName: string; children: ReactNode }) {
// Switching context lands on that context's feed, so the switcher doubles as the
// brand slot's way home. Held in a ref because `navigate` changes identity on every
// route change, which would otherwise rebuild the context value — and re-render the
// global composer and the editor tree it hosts — on each navigation.
const navigate = useNavigate();
const navigateRef = useRef(navigate);
navigateRef.current = navigate;
const [selectedSpaceName, setSelectedSpaceName] = useState(() => readSelectedSpaceName(userName));
const [optimisticSpace, setOptimisticSpace] = useState<Space>();
const spacesQuery = useSpaces(userName);
const spaces = spacesQuery.data ?? NO_SPACES;
const listedSelectedSpace = spaces.find((space) => space.name === selectedSpaceName);
const selectedSpace = listedSelectedSpace ?? (optimisticSpace?.name === selectedSpaceName ? optimisticSpace : undefined);
useEffect(() => {
if (listedSelectedSpace && optimisticSpace?.name === listedSelectedSpace.name) {
setOptimisticSpace(undefined);
}
}, [listedSelectedSpace, optimisticSpace]);
useEffect(() => {
if (!selectedSpaceName || !spacesQuery.isSuccess || selectedSpace) {
return;
}
writeSelectedSpaceName(userName, undefined);
setSelectedSpaceName(undefined);
}, [selectedSpace, selectedSpaceName, spacesQuery.isSuccess, userName]);
const selectSpace = useCallback(
(space: Space) => {
writeSelectedSpaceName(userName, space.name);
setOptimisticSpace(space);
setSelectedSpaceName(space.name);
navigateRef.current(ROUTES.HOME);
},
[userName],
);
const selectMemos = useCallback(() => {
writeSelectedSpaceName(userName, undefined);
setOptimisticSpace(undefined);
setSelectedSpaceName(undefined);
navigateRef.current(ROUTES.HOME);
}, [userName]);
const value = useMemo<SpaceContextValue>(
() => ({
spaces,
selectedSpace,
selectedSpaceName,
memoFilter: buildSpaceFilter(selectedSpaceName),
isLoadingSpaces: spacesQuery.isPending,
isSpacesError: spacesQuery.isError,
selectSpace,
selectMemos,
}),
[selectMemos, selectSpace, selectedSpace, selectedSpaceName, spaces, spacesQuery.isError, spacesQuery.isPending],
);
return <SpaceContext.Provider value={value}>{children}</SpaceContext.Provider>;
}
const anonymousValue: SpaceContextValue = {
spaces: [],
isLoadingSpaces: false,
isSpacesError: false,
selectSpace: () => undefined,
selectMemos: () => undefined,
};
export function SpaceProvider({ children }: { children: ReactNode }) {
const currentUserName = useCurrentUser()?.name;
if (!currentUserName) {
return <SpaceContext.Provider value={anonymousValue}>{children}</SpaceContext.Provider>;
}
return (
<UserSpaceSession key={currentUserName} userName={currentUserName}>
{children}
</UserSpaceSession>
);
}
export function useSpaceContext() {
const context = useContext(SpaceContext);
if (!context) {
throw new Error("useSpaceContext must be used within SpaceProvider");
}
return context;
}

View file

@ -8,6 +8,7 @@ import {
isVideoAttachment,
} from "@/components/MemoMetadata/Attachment/attachmentHelpers";
import { useInfiniteAttachments } from "@/hooks/useAttachmentQueries";
import { combineCELFilters } from "@/lib/cel-filter";
import type { Attachment, ListAttachmentsRequest } from "@/types/proto/api/v1/attachment_service_pb";
import { isMotionAttachment } from "@/utils/attachment";
import { useTranslate } from "@/utils/i18n";
@ -170,9 +171,9 @@ const groupMediaByMonth = (
}));
};
export function useAttachmentLibrary(locale: string) {
export function useAttachmentLibrary(locale: string, filter?: string) {
const t = useTranslate();
const query = useInfiniteAttachments(ATTACHMENT_LIBRARY_REQUEST);
const query = useInfiniteAttachments({ ...ATTACHMENT_LIBRARY_REQUEST, filter });
const attachments = useMemo(() => (query.data?.pages ?? []).flatMap((page) => page.attachments), [query.data?.pages]);
@ -241,16 +242,19 @@ export function useAttachmentLibrary(locale: string) {
};
}
export function useAttachmentLibraryStats() {
const query = useCompleteAttachments(COMPLETE_ATTACHMENT_LIBRARY_REQUEST);
export function useAttachmentLibraryStats(filter?: string) {
const query = useCompleteAttachments({ ...COMPLETE_ATTACHMENT_LIBRARY_REQUEST, filter });
const attachments = useMemo(() => (query.data?.pages ?? []).flatMap((page) => page.attachments), [query.data?.pages]);
const stats = useMemo(() => buildAttachmentLibraryStats(attachments), [attachments]);
return { ...query, stats };
}
export function useUnusedAttachmentLibrary(locale: string, enabled = true) {
const query = useCompleteAttachments(UNUSED_ATTACHMENT_LIBRARY_REQUEST, enabled);
export function useUnusedAttachmentLibrary(locale: string, filter?: string, enabled = true) {
const query = useCompleteAttachments(
{ ...UNUSED_ATTACHMENT_LIBRARY_REQUEST, filter: combineCELFilters(UNUSED_ATTACHMENT_LIBRARY_REQUEST.filter, filter) },
enabled,
);
const attachments = useMemo(() => (query.data?.pages ?? []).flatMap((page) => page.attachments), [query.data?.pages]);
const unusedItems = useMemo(
() => attachments.map((attachment) => toLibraryListItem(attachment, locale)).sort((a, b) => sortByNewest(a.createdAt, b.createdAt)),

View file

@ -5,6 +5,7 @@ import { useMemo } from "react";
import { type MemoTimeBasis, useView } from "@/contexts/ViewContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useAllUserStats, useUserStats } from "@/hooks/useUserQueries";
import { combineCELFilters } from "@/lib/cel-filter";
import { mergeTagCounts } from "@/lib/tag";
import { State } from "@/types/proto/api/v1/common_pb";
import type { UserStats } from "@/types/proto/api/v1/user_service_pb";
@ -22,6 +23,8 @@ export interface UseFilteredMemoStatsOptions {
userName?: string;
context?: MemoStatsContext;
enabled?: boolean;
filter?: string;
includeSpaceVisibility?: boolean;
}
const toDateString = (date: Date) => dayjs(date).format("YYYY-MM-DD");
@ -38,21 +41,26 @@ const timestampsForBasis = (stats: UserStats, basis: MemoTimeBasis) => {
};
export const useFilteredMemoStats = (options: UseFilteredMemoStatsOptions = {}): FilteredMemoStats => {
const { userName, context, enabled = true } = options;
const { userName, context, enabled = true, filter, includeSpaceVisibility = false } = options;
const currentUser = useCurrentUser();
const { timeBasis } = useView();
// home/profile: use backend per-user stats (full tag set, not page-limited)
const { data: userStats, isLoading: isLoadingUserStats } = useUserStats(userName, { enabled });
const { data: userStats, isLoading: isLoadingUserStats } = useUserStats(userName, { enabled, filter });
// explore/archived: fetch backend grouped stats and aggregate them locally.
// ListAllUserStats AND's the request filter with the server's auth filter, so
// private memos are not included unless explicitly visible to the current user.
const exploreVisibilityFilter = currentUser != null ? 'visibility in ["PUBLIC", "PROTECTED"]' : 'visibility in ["PUBLIC"]';
const exploreVisibilityFilter =
currentUser != null
? includeSpaceVisibility
? 'visibility in ["PUBLIC", "PROTECTED", "SPACE"]'
: 'visibility in ["PUBLIC", "PROTECTED"]'
: 'visibility in ["PUBLIC"]';
const allUserStatsRequest =
context === "explore"
? { state: State.NORMAL, filter: exploreVisibilityFilter }
? { state: State.NORMAL, filter: combineCELFilters(filter, exploreVisibilityFilter) }
: context === "archived"
? { state: State.ARCHIVED }
? { state: State.ARCHIVED, filter }
: {};
const shouldFetchAllUserStats = context === "explore" || (context === "archived" && !!currentUser?.name);
const { data: allUserStats = [], isLoading: isLoadingAllUserStats } = useAllUserStats(allUserStatsRequest, {

View file

@ -2,6 +2,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
import { getRequestToken, refreshAccessToken } from "@/connect";
import { useAuth } from "@/contexts/AuthContext";
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
import { memoKeys } from "@/hooks/useMemoQueries";
import { userKeys } from "@/hooks/useUserQueries";
@ -466,4 +467,5 @@ function handleSSEEvent(event: SSEChangeEvent, queryClient: ReturnType<typeof us
function invalidateLiveMemoQueries(queryClient: ReturnType<typeof useQueryClient>) {
queryClient.invalidateQueries({ queryKey: memoKeys.all, refetchType: "active" });
queryClient.invalidateQueries({ queryKey: userKeys.stats(), refetchType: "active" });
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists(), refetchType: "active" });
}

View file

@ -3,22 +3,9 @@ import { type MemoFilter, useMemoFilterContext } from "@/contexts/MemoFilterCont
import useCurrentUser from "@/hooks/useCurrentUser";
import { useMemoViews } from "@/hooks/useUserQueries";
import { BUILTIN_TASKS_VIEW_FILTER, BUILTIN_TASKS_VIEW_ID, getMemoViewId } from "@/lib/memo-views";
import { buildMemoCreatorFilter } from "@/lib/resource-names";
import { buildMemoCreatorFilter, getVisibilityName } from "@/lib/resource-names";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
const getVisibilityName = (visibility: Visibility): string => {
switch (visibility) {
case Visibility.PUBLIC:
return "PUBLIC";
case Visibility.PROTECTED:
return "PROTECTED";
case Visibility.PRIVATE:
return "PRIVATE";
default:
return "PRIVATE";
}
};
const escapeFilterValue = (value: string): string => JSON.stringify(value);
const getLocalDayTimestampRange = (value: string): { startTimestamp: number; endTimestamp: number } | undefined => {

View file

@ -10,6 +10,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import { memoServiceClient } from "@/connect";
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
import { userKeys } from "@/hooks/useUserQueries";
import { DEFAULT_LIST_MEMOS_PAGE_SIZE } from "@/lib/constants";
import type { ListMemosRequest, ListMemosResponse, Memo } from "@/types/proto/api/v1/memo_service_pb";
@ -199,6 +200,8 @@ export function useCreateMemo() {
queryClient.setQueryData(memoKeys.detail(newMemo.name), newMemo);
// Invalidate user stats
queryClient.invalidateQueries({ queryKey: userKeys.stats() });
// Creating a memo can bind previously unlinked attachments.
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() });
},
});
}
@ -255,6 +258,8 @@ export function useUpdateMemo() {
}
// Invalidate user stats
queryClient.invalidateQueries({ queryKey: userKeys.stats() });
// Placement changes move linked attachments between scoped libraries.
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() });
},
});
}
@ -274,6 +279,8 @@ export function useDeleteMemo() {
queryClient.invalidateQueries({ queryKey: memoKeys.lists() });
// Invalidate user stats
queryClient.invalidateQueries({ queryKey: userKeys.stats() });
// Memo deletion can remove or unlink associated attachments.
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() });
},
});
}

View file

@ -0,0 +1,52 @@
import { create } from "@bufbuild/protobuf";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { spaceServiceClient } from "@/connect";
import { type Space, SpaceSchema } from "@/types/proto/api/v1/space_service_pb";
const SPACE_LIST_PAGE_SIZE = 1000;
export const spaceKeys = {
all: ["spaces"] as const,
lists: () => [...spaceKeys.all, "list"] as const,
list: (userName: string) => [...spaceKeys.lists(), userName] as const,
};
export function useSpaces(userName: string | undefined) {
return useQuery({
queryKey: spaceKeys.list(userName ?? ""),
queryFn: async () => {
const spaces: Space[] = [];
let pageToken = "";
do {
const response = await spaceServiceClient.listSpaces({
pageSize: SPACE_LIST_PAGE_SIZE,
pageToken,
});
spaces.push(...response.spaces);
pageToken = response.nextPageToken;
} while (pageToken);
return spaces;
},
enabled: Boolean(userName),
// SpaceProvider wraps the whole route tree, so this drains every page on boot.
// Space membership is near-static, so don't re-run that loop on each tab return.
staleTime: 1000 * 60 * 5,
refetchOnWindowFocus: false,
});
}
export function useCreateSpace(userName: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ title, description }: { title: string; description?: string }) =>
spaceServiceClient.createSpace({
space: create(SpaceSchema, { title, description }),
}),
onSuccess: (space) => {
queryClient.setQueryData<Space[]>(spaceKeys.list(userName), (spaces = []) => [...spaces, space]);
},
});
}

View file

@ -26,7 +26,8 @@ export const userKeys = {
details: () => [...userKeys.all, "detail"] as const,
detail: (name: string) => [...userKeys.details(), name] as const,
stats: () => [...userKeys.all, "stats"] as const,
userStats: (name: string) => [...userKeys.stats(), name] as const,
userStats: (name: string, filter?: string) =>
filter ? ([...userKeys.stats(), name, filter] as const) : ([...userKeys.stats(), name] as const),
allUserStats: (request: Partial<ListAllUserStatsQuery>) => [...userKeys.stats(), "all", request] as const,
currentUser: () => [...userKeys.all, "current"] as const,
memoViews: (parent?: string) => [...userKeys.all, "memoViews", parent] as const,
@ -49,14 +50,14 @@ export function useUser(name: string, options?: { enabled?: boolean }) {
});
}
export function useUserStats(username?: string, options?: { enabled?: boolean }) {
export function useUserStats(username?: string, options?: { enabled?: boolean; filter?: string }) {
return useQuery({
queryKey: username ? userKeys.userStats(username) : userKeys.stats(),
queryKey: username ? userKeys.userStats(username, options?.filter) : userKeys.stats(),
queryFn: async () => {
if (!username) {
throw new Error("Username is required");
}
const stats = await userServiceClient.getUserStats({ name: username });
const stats = await userServiceClient.getUserStats({ name: username, filter: options?.filter });
return stats;
},
enabled: !!username && (options?.enabled ?? true),

View file

@ -13,6 +13,7 @@ import { AppSidebarProvider } from "@/contexts/AppSidebarContext";
import { GlobalMemoEditorProvider } from "@/contexts/GlobalMemoEditorContext";
import { useInstance } from "@/contexts/InstanceContext";
import { MemoFilterProvider, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { SpaceProvider } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useMediaQuery from "@/hooks/useMediaQuery";
import { InstanceAccessMode } from "@/types/proto/api/v1/instance_service_pb";
@ -99,13 +100,15 @@ const RootLayoutContent = () => {
};
const RootLayout = () => (
<MemoFilterProvider>
<AppSidebarProvider>
<GlobalMemoEditorProvider>
<RootLayoutContent />
</GlobalMemoEditorProvider>
</AppSidebarProvider>
</MemoFilterProvider>
<SpaceProvider>
<MemoFilterProvider>
<AppSidebarProvider>
<GlobalMemoEditorProvider>
<RootLayoutContent />
</GlobalMemoEditorProvider>
</AppSidebarProvider>
</MemoFilterProvider>
</SpaceProvider>
);
export default RootLayout;

View file

@ -0,0 +1,6 @@
export const combineCELFilters = (...filters: Array<string | undefined>): string | undefined => {
const conditions = filters.filter((filter): filter is string => Boolean(filter));
return conditions.length === 0 ? undefined : conditions.map((filter) => `(${filter})`).join(" && ");
};
export const buildSpaceFilter = (spaceName?: string): string => (spaceName ? `space == ${JSON.stringify(spaceName)}` : "space == null");

View file

@ -62,3 +62,7 @@ export const getVisibilityName = (visibility: Visibility): string => {
}
return name;
};
// Namespaces an editor draft cache key by Space, so drafts never bleed across contexts.
// Memos (no Space selected) keeps the bare key it has always used.
export const spaceScopedCacheKey = (baseKey: string, spaceName?: string): string => (spaceName ? `${baseKey}:${spaceName}` : baseKey);

View file

@ -434,7 +434,9 @@
"protected": "Protected",
"protected-description": "Visible to signed-in users",
"public": "Public",
"public-description": "Visible to everyone"
"public-description": "Visible to everyone",
"space": "Space",
"space-description": "Visible to members of this space"
}
},
"message": {
@ -947,6 +949,19 @@
"load-error": "Failed to load statistics"
}
},
"space": {
"create": "Create space",
"create-description": "Create a shared place for memos and members.",
"create-success": "Space created",
"creator-admin-note": "You'll become the first admin.",
"current": "Space",
"description-placeholder": "What is this space for?",
"load-error": "Couldn't load spaces",
"loading": "Loading spaces…",
"name-placeholder": "e.g. Product",
"spaces": "Spaces",
"switch": "Switch space"
},
"tag": {
"all-tags": "All Tags",
"create-tag": "Create Tag",

View file

@ -1,5 +1,6 @@
import MemoView from "@/components/MemoView";
import PagedMemoList, { getMemoKey } from "@/components/PagedMemoList";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useMemoFilters, useMemoSorting } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
import { State } from "@/types/proto/api/v1/common_pb";
@ -7,6 +8,7 @@ import { Memo } from "@/types/proto/api/v1/memo_service_pb";
const Archived = () => {
const user = useCurrentUser();
const { memoFilter: contextFilter } = useSpaceContext();
const memoFilter = useMemoFilters({
creatorName: user?.name,
@ -27,6 +29,7 @@ const Archived = () => {
state={State.ARCHIVED}
orderBy={orderBy}
filter={memoFilter}
contextFilter={contextFilter}
/>
);
};

View file

@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
import { LoaderCircleIcon, Trash2Icon } from "lucide-react";
import { useState } from "react";
import { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import {
AttachmentAudioRows,
@ -16,10 +16,12 @@ import PreviewImageDialog from "@/components/PreviewImageDialog";
import { Button } from "@/components/ui/button";
import { attachmentServiceClient } from "@/connect";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useAttachmentLibrary, useUnusedAttachmentLibrary } from "@/hooks/useAttachmentLibrary";
import { useBatchDeleteAttachments } from "@/hooks/useAttachmentQueries";
import useDialog from "@/hooks/useDialog";
import i18n from "@/i18n";
import { combineCELFilters } from "@/lib/cel-filter";
import { handleError } from "@/lib/error";
import { ListAttachmentsRequestSchema } from "@/types/proto/api/v1/attachment_service_pb";
import { useTranslate } from "@/utils/i18n";
@ -37,14 +39,18 @@ const chunkNames = (names: string[], size: number) => {
return chunks;
};
const listUnusedAttachmentNames = async () => {
const listUnusedAttachmentNames = async (filter: string | undefined, selectedSpaceName: string | undefined) => {
if (selectedSpaceName) {
return [];
}
const names: string[] = [];
let pageToken = "";
do {
const response = await attachmentServiceClient.listAttachments(
create(ListAttachmentsRequestSchema, {
filter: "memo_id == null",
filter: combineCELFilters("memo_id == null", filter),
pageSize: UNUSED_PAGE_SIZE,
pageToken,
}),
@ -60,7 +66,8 @@ const listUnusedAttachmentNames = async () => {
const Attachments = () => {
const t = useTranslate();
const deleteUnusedAttachmentsDialog = useDialog();
const { attachmentSection } = useAppSidebar();
const { attachmentSection, setAttachmentSection } = useAppSidebar();
const { memoFilter, selectedSpaceName } = useSpaceContext();
const [previewState, setPreviewState] = useState({ open: false, initialIndex: 0 });
const { mutateAsync: batchDeleteAttachments, isPending: isDeletingUnused } = useBatchDeleteAttachments();
const {
@ -77,7 +84,7 @@ const Attachments = () => {
mediaPreviewItems,
refetch,
stats,
} = useAttachmentLibrary(i18n.language);
} = useAttachmentLibrary(i18n.language, memoFilter);
const {
error: unusedError,
isComplete: unusedIsComplete,
@ -85,7 +92,13 @@ const Attachments = () => {
isLoading: unusedIsLoading,
refetch: refetchUnused,
unusedItems: completeUnusedItems,
} = useUnusedAttachmentLibrary(i18n.language, attachmentSection === "unused");
} = useUnusedAttachmentLibrary(i18n.language, memoFilter, attachmentSection === "unused" && !selectedSpaceName);
useEffect(() => {
if (selectedSpaceName && attachmentSection === "unused") {
setAttachmentSection("all");
}
}, [attachmentSection, selectedSpaceName, setAttachmentSection]);
const handlePreview = (itemId: string) => {
const initialIndex = mediaPreviewItems.findIndex((item) => item.id === itemId);
@ -94,7 +107,7 @@ const Attachments = () => {
const handleDeleteUnusedAttachments = async () => {
try {
const names = await listUnusedAttachmentNames();
const names = await listUnusedAttachmentNames(memoFilter, selectedSpaceName);
if (names.length === 0) {
await Promise.all([refetch(), refetchUnused()]);

View file

@ -1,5 +1,6 @@
import MemoView from "@/components/MemoView";
import PagedMemoList, { getMemoKey } from "@/components/PagedMemoList";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useMemoFilters, useMemoSorting } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
import { State } from "@/types/proto/api/v1/common_pb";
@ -7,12 +8,15 @@ import { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
const Explore = () => {
const currentUser = useCurrentUser();
const { memoFilter: contextFilter, selectedSpaceName } = useSpaceContext();
// Determine visibility filter based on authentication status
// - Logged-in users: Can see PUBLIC and PROTECTED memos
// - Logged-in users: Can see PUBLIC and PROTECTED memos, plus SPACE memos while a Space is selected
// - Visitors: Can only see PUBLIC memos
// Note: The backend is responsible for filtering stats based on visibility permissions.
const visibilities = currentUser ? [Visibility.PUBLIC, Visibility.PROTECTED] : [Visibility.PUBLIC];
const visibilities = currentUser
? [Visibility.PUBLIC, Visibility.PROTECTED, ...(selectedSpaceName ? [Visibility.SPACE] : [])]
: [Visibility.PUBLIC];
const memoFilter = useMemoFilters({
includeMemoViews: true,
@ -32,6 +36,7 @@ const Explore = () => {
listSort={listSort}
orderBy={orderBy}
filter={memoFilter}
contextFilter={contextFilter}
showCreator
/>
);

View file

@ -6,8 +6,10 @@ import PagedMemoList, { getMemoKey } from "@/components/PagedMemoList";
import { useAuth } from "@/contexts/AuthContext";
import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { NewMemoProvider } from "@/contexts/NewMemoContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useMemoFilters, useMemoSorting } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
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";
import { useTranslate } from "@/utils/i18n";
@ -17,7 +19,11 @@ const Home = () => {
const t = useTranslate();
const { isUserSettingsInitialized } = useAuth();
const { filters } = useMemoFilterContext();
const { memoFilter: contextFilter, selectedSpaceName } = useSpaceContext();
const defaultCreateTime = useMemo(() => deriveDefaultCreateTimeFromFilters(filters), [filters]);
// Doubles as the remount key: the draft cache only reloads on mount, so the editor
// has to be rebuilt for the new Space rather than just re-pointed at another cache.
const editorCacheKey = spaceScopedCacheKey("home-memo-editor", selectedSpaceName);
const memoFilter = useMemoFilters({
creatorName: user?.name,
@ -40,15 +46,18 @@ const Home = () => {
listSort={listSort}
orderBy={orderBy}
filter={memoFilter}
contextFilter={contextFilter}
renderLeading={({ useGrid }) => {
if (!isUserSettingsInitialized) return null;
return (
<MemoEditor
key={editorCacheKey}
className={useGrid ? undefined : "mb-2"}
cacheKey="home-memo-editor"
cacheKey={editorCacheKey}
placeholder={t("editor.any-thoughts")}
defaultCreateTime={defaultCreateTime}
defaultSpace={selectedSpaceName}
/>
);
}}

View file

@ -16,7 +16,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file api/v1/attachment_service.proto.
*/
export const file_api_v1_attachment_service: GenFile = /*@__PURE__*/
fileDesc("Ch9hcGkvdjEvYXR0YWNobWVudF9zZXJ2aWNlLnByb3RvEgxtZW1vcy5hcGkudjEivAEKC01vdGlvbk1lZGlhEi8KBmZhbWlseRgBIAEoDjIfLm1lbW9zLmFwaS52MS5Nb3Rpb25NZWRpYUZhbWlseRIrCgRyb2xlGAIgASgOMh0ubWVtb3MuYXBpLnYxLk1vdGlvbk1lZGlhUm9sZRIQCghncm91cF9pZBgDIAEoCRIhChlwcmVzZW50YXRpb25fdGltZXN0YW1wX3VzGAQgASgDEhoKEmhhc19lbWJlZGRlZF92aWRlbxgFIAEoCCK0AQoNTWVkaWFNZXRhZGF0YRISCgV3aWR0aBgBIAEoBUgBiAEBEhMKBmhlaWdodBgCIAEoBUgCiAEBEiwKBXBob3RvGAMgASgLMhsubWVtb3MuYXBpLnYxLlBob3RvTWV0YWRhdGFIABIsCgV2aWRlbxgEIAEoCzIbLm1lbW9zLmFwaS52MS5WaWRlb01ldGFkYXRhSABCCQoHZGV0YWlsc0IICgZfd2lkdGhCCQoHX2hlaWdodCKjAwoNUGhvdG9NZXRhZGF0YRI0CgxjYXB0dXJlX3RpbWUYASABKAsyHi5tZW1vcy5hcGkudjEuTWVkaWFDYXB0dXJlVGltZRItCghsb2NhdGlvbhgCIAEoCzIbLm1lbW9zLmFwaS52MS5NZWRpYUxvY2F0aW9uEiQKF3NvdXJjZV9leGlmX29yaWVudGF0aW9uGAMgASgFSACIAQESEwoLY2FtZXJhX21ha2UYBCABKAkSFAoMY2FtZXJhX21vZGVsGAUgASgJEhIKCmxlbnNfbW9kZWwYBiABKAkSFQoIZl9udW1iZXIYByABKAFIAYgBARIiChVleHBvc3VyZV90aW1lX3NlY29uZHMYCCABKAFIAogBARIQCgNpc28YCSABKAVIA4gBARIcCg9mb2NhbF9sZW5ndGhfbW0YCiABKAFIBIgBAUIaChhfc291cmNlX2V4aWZfb3JpZW50YXRpb25CCwoJX2ZfbnVtYmVyQhgKFl9leHBvc3VyZV90aW1lX3NlY29uZHNCBgoEX2lzb0ISChBfZm9jYWxfbGVuZ3RoX21tIlMKEE1lZGlhQ2FwdHVyZVRpbWUSFwoPbG9jYWxfZGF0ZV90aW1lGAEgASgJEhcKCnV0Y19vZmZzZXQYAiABKAlIAIgBAUINCgtfdXRjX29mZnNldCKLAQoNTWVkaWFMb2NhdGlvbhIVCghsYXRpdHVkZRgBIAEoAUgAiAEBEhYKCWxvbmdpdHVkZRgCIAEoAUgBiAEBEhwKD2FsdGl0dWRlX21ldGVycxgDIAEoAUgCiAEBQgsKCV9sYXRpdHVkZUIMCgpfbG9uZ2l0dWRlQhIKEF9hbHRpdHVkZV9tZXRlcnMiQwoNVmlkZW9NZXRhZGF0YRIdChBkdXJhdGlvbl9zZWNvbmRzGAEgASgBSACIAQFCEwoRX2R1cmF0aW9uX3NlY29uZHMiqQMKCkF0dGFjaG1lbnQSEQoEbmFtZRgBIAEoCUID4EEIEjQKC2NyZWF0ZV90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhUKCGZpbGVuYW1lGAMgASgJQgPgQQISFAoHY29udGVudBgEIAEoDEID4EEEEhoKDWV4dGVybmFsX2xpbmsYBSABKAlCA+BBARIRCgR0eXBlGAYgASgJQgPgQQISEQoEc2l6ZRgHIAEoA0ID4EEDEhYKBG1lbW8YCCABKAlCA+BBAUgAiAEBEjQKDG1vdGlvbl9tZWRpYRgJIAEoCzIZLm1lbW9zLmFwaS52MS5Nb3Rpb25NZWRpYUID4EEBEjsKDm1lZGlhX21ldGFkYXRhGAogASgLMhsubWVtb3MuYXBpLnYxLk1lZGlhTWV0YWRhdGFCBuBBAeBBBTpP6kFMChdtZW1vcy5hcGkudjEvQXR0YWNobWVudBIYYXR0YWNobWVudHMve2F0dGFjaG1lbnR9KgthdHRhY2htZW50czIKYXR0YWNobWVudEIHCgVfbWVtbyJoChdDcmVhdGVBdHRhY2htZW50UmVxdWVzdBIxCgphdHRhY2htZW50GAEgASgLMhgubWVtb3MuYXBpLnYxLkF0dGFjaG1lbnRCA+BBAhIaCg1hdHRhY2htZW50X2lkGAIgASgJQgPgQQEidQoWTGlzdEF0dGFjaG1lbnRzUmVxdWVzdBIWCglwYWdlX3NpemUYASABKAVCA+BBARIXCgpwYWdlX3Rva2VuGAIgASgJQgPgQQESEwoGZmlsdGVyGAMgASgJQgPgQQESFQoIb3JkZXJfYnkYBCABKAlCA+BBASJhChdMaXN0QXR0YWNobWVudHNSZXNwb25zZRItCgthdHRhY2htZW50cxgBIAMoCzIYLm1lbW9zLmFwaS52MS5BdHRhY2htZW50EhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSJFChRHZXRBdHRhY2htZW50UmVxdWVzdBItCgRuYW1lGAEgASgJQh/gQQL6QRkKF21lbW9zLmFwaS52MS9BdHRhY2htZW50IoIBChdVcGRhdGVBdHRhY2htZW50UmVxdWVzdBIxCgphdHRhY2htZW50GAEgASgLMhgubWVtb3MuYXBpLnYxLkF0dGFjaG1lbnRCA+BBAhI0Cgt1cGRhdGVfbWFzaxgCIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE1hc2tCA+BBAiJIChdEZWxldGVBdHRhY2htZW50UmVxdWVzdBItCgRuYW1lGAEgASgJQh/gQQL6QRkKF21lbW9zLmFwaS52MS9BdHRhY2htZW50IjMKHUJhdGNoRGVsZXRlQXR0YWNobWVudHNSZXF1ZXN0EhIKBW5hbWVzGAEgAygJQgPgQQIqaAoRTW90aW9uTWVkaWFGYW1pbHkSIwofTU9USU9OX01FRElBX0ZBTUlMWV9VTlNQRUNJRklFRBAAEhQKEEFQUExFX0xJVkVfUEhPVE8QARIYChRBTkRST0lEX01PVElPTl9QSE9UTxACKlkKD01vdGlvbk1lZGlhUm9sZRIhCh1NT1RJT05fTUVESUFfUk9MRV9VTlNQRUNJRklFRBAAEgkKBVNUSUxMEAESCQoFVklERU8QAhINCglDT05UQUlORVIQAzLQBgoRQXR0YWNobWVudFNlcnZpY2USiQEKEENyZWF0ZUF0dGFjaG1lbnQSJS5tZW1vcy5hcGkudjEuQ3JlYXRlQXR0YWNobWVudFJlcXVlc3QaGC5tZW1vcy5hcGkudjEuQXR0YWNobWVudCI02kEKYXR0YWNobWVudILT5JMCIToKYXR0YWNobWVudCITL2FwaS92MS9hdHRhY2htZW50cxJ7Cg9MaXN0QXR0YWNobWVudHMSJC5tZW1vcy5hcGkudjEuTGlzdEF0dGFjaG1lbnRzUmVxdWVzdBolLm1lbW9zLmFwaS52MS5MaXN0QXR0YWNobWVudHNSZXNwb25zZSIbgtPkkwIVEhMvYXBpL3YxL2F0dGFjaG1lbnRzEnoKDUdldEF0dGFjaG1lbnQSIi5tZW1vcy5hcGkudjEuR2V0QXR0YWNobWVudFJlcXVlc3QaGC5tZW1vcy5hcGkudjEuQXR0YWNobWVudCIr2kEEbmFtZYLT5JMCHhIcL2FwaS92MS97bmFtZT1hdHRhY2htZW50cy8qfRKpAQoQVXBkYXRlQXR0YWNobWVudBIlLm1lbW9zLmFwaS52MS5VcGRhdGVBdHRhY2htZW50UmVxdWVzdBoYLm1lbW9zLmFwaS52MS5BdHRhY2htZW50IlTaQRZhdHRhY2htZW50LHVwZGF0ZV9tYXNrgtPkkwI1OgphdHRhY2htZW50MicvYXBpL3YxL3thdHRhY2htZW50Lm5hbWU9YXR0YWNobWVudHMvKn0SfgoQRGVsZXRlQXR0YWNobWVudBIlLm1lbW9zLmFwaS52MS5EZWxldGVBdHRhY2htZW50UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSIr2kEEbmFtZYLT5JMCHiocL2FwaS92MS97bmFtZT1hdHRhY2htZW50cy8qfRKJAQoWQmF0Y2hEZWxldGVBdHRhY2htZW50cxIrLm1lbW9zLmFwaS52MS5CYXRjaERlbGV0ZUF0dGFjaG1lbnRzUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSIqgtPkkwIkOgEqIh8vYXBpL3YxL2F0dGFjaG1lbnRzOmJhdGNoRGVsZXRlQq4BChBjb20ubWVtb3MuYXBpLnYxQhZBdHRhY2htZW50U2VydmljZVByb3RvUAFaMGdpdGh1Yi5jb20vdXNlbWVtb3MvbWVtb3MvcHJvdG8vZ2VuL2FwaS92MTthcGl2MaICA01BWKoCDE1lbW9zLkFwaS5WMcoCDE1lbW9zXEFwaVxWMeICGE1lbW9zXEFwaVxWMVxHUEJNZXRhZGF0YeoCDk1lbW9zOjpBcGk6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp]);
fileDesc("Ch9hcGkvdjEvYXR0YWNobWVudF9zZXJ2aWNlLnByb3RvEgxtZW1vcy5hcGkudjEivAEKC01vdGlvbk1lZGlhEi8KBmZhbWlseRgBIAEoDjIfLm1lbW9zLmFwaS52MS5Nb3Rpb25NZWRpYUZhbWlseRIrCgRyb2xlGAIgASgOMh0ubWVtb3MuYXBpLnYxLk1vdGlvbk1lZGlhUm9sZRIQCghncm91cF9pZBgDIAEoCRIhChlwcmVzZW50YXRpb25fdGltZXN0YW1wX3VzGAQgASgDEhoKEmhhc19lbWJlZGRlZF92aWRlbxgFIAEoCCK0AQoNTWVkaWFNZXRhZGF0YRISCgV3aWR0aBgBIAEoBUgBiAEBEhMKBmhlaWdodBgCIAEoBUgCiAEBEiwKBXBob3RvGAMgASgLMhsubWVtb3MuYXBpLnYxLlBob3RvTWV0YWRhdGFIABIsCgV2aWRlbxgEIAEoCzIbLm1lbW9zLmFwaS52MS5WaWRlb01ldGFkYXRhSABCCQoHZGV0YWlsc0IICgZfd2lkdGhCCQoHX2hlaWdodCKjAwoNUGhvdG9NZXRhZGF0YRI0CgxjYXB0dXJlX3RpbWUYASABKAsyHi5tZW1vcy5hcGkudjEuTWVkaWFDYXB0dXJlVGltZRItCghsb2NhdGlvbhgCIAEoCzIbLm1lbW9zLmFwaS52MS5NZWRpYUxvY2F0aW9uEiQKF3NvdXJjZV9leGlmX29yaWVudGF0aW9uGAMgASgFSACIAQESEwoLY2FtZXJhX21ha2UYBCABKAkSFAoMY2FtZXJhX21vZGVsGAUgASgJEhIKCmxlbnNfbW9kZWwYBiABKAkSFQoIZl9udW1iZXIYByABKAFIAYgBARIiChVleHBvc3VyZV90aW1lX3NlY29uZHMYCCABKAFIAogBARIQCgNpc28YCSABKAVIA4gBARIcCg9mb2NhbF9sZW5ndGhfbW0YCiABKAFIBIgBAUIaChhfc291cmNlX2V4aWZfb3JpZW50YXRpb25CCwoJX2ZfbnVtYmVyQhgKFl9leHBvc3VyZV90aW1lX3NlY29uZHNCBgoEX2lzb0ISChBfZm9jYWxfbGVuZ3RoX21tIlMKEE1lZGlhQ2FwdHVyZVRpbWUSFwoPbG9jYWxfZGF0ZV90aW1lGAEgASgJEhcKCnV0Y19vZmZzZXQYAiABKAlIAIgBAUINCgtfdXRjX29mZnNldCKLAQoNTWVkaWFMb2NhdGlvbhIVCghsYXRpdHVkZRgBIAEoAUgAiAEBEhYKCWxvbmdpdHVkZRgCIAEoAUgBiAEBEhwKD2FsdGl0dWRlX21ldGVycxgDIAEoAUgCiAEBQgsKCV9sYXRpdHVkZUIMCgpfbG9uZ2l0dWRlQhIKEF9hbHRpdHVkZV9tZXRlcnMiQwoNVmlkZW9NZXRhZGF0YRIdChBkdXJhdGlvbl9zZWNvbmRzGAEgASgBSACIAQFCEwoRX2R1cmF0aW9uX3NlY29uZHMiqQMKCkF0dGFjaG1lbnQSEQoEbmFtZRgBIAEoCUID4EEIEjQKC2NyZWF0ZV90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhUKCGZpbGVuYW1lGAMgASgJQgPgQQISFAoHY29udGVudBgEIAEoDEID4EEEEhoKDWV4dGVybmFsX2xpbmsYBSABKAlCA+BBARIRCgR0eXBlGAYgASgJQgPgQQISEQoEc2l6ZRgHIAEoA0ID4EEDEhYKBG1lbW8YCCABKAlCA+BBAUgAiAEBEjQKDG1vdGlvbl9tZWRpYRgJIAEoCzIZLm1lbW9zLmFwaS52MS5Nb3Rpb25NZWRpYUID4EEBEjsKDm1lZGlhX21ldGFkYXRhGAogASgLMhsubWVtb3MuYXBpLnYxLk1lZGlhTWV0YWRhdGFCBuBBAeBBBTpP6kFMChdtZW1vcy5hcGkudjEvQXR0YWNobWVudBIYYXR0YWNobWVudHMve2F0dGFjaG1lbnR9KgthdHRhY2htZW50czIKYXR0YWNobWVudEIHCgVfbWVtbyJoChdDcmVhdGVBdHRhY2htZW50UmVxdWVzdBIxCgphdHRhY2htZW50GAEgASgLMhgubWVtb3MuYXBpLnYxLkF0dGFjaG1lbnRCA+BBAhIaCg1hdHRhY2htZW50X2lkGAIgASgJQgPgQQEilAEKFkxpc3RBdHRhY2htZW50c1JlcXVlc3QSFgoJcGFnZV9zaXplGAEgASgFQgPgQQESFwoKcGFnZV90b2tlbhgCIAEoCUID4EEBEhMKBmZpbHRlchgDIAEoCUID4EEBEhUKCG9yZGVyX2J5GAQgASgJQgPgQQFKBAgFEAZKBAgGEAdSBXNwYWNlUgp1bmFzc2lnbmVkImEKF0xpc3RBdHRhY2htZW50c1Jlc3BvbnNlEi0KC2F0dGFjaG1lbnRzGAEgAygLMhgubWVtb3MuYXBpLnYxLkF0dGFjaG1lbnQSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJIkUKFEdldEF0dGFjaG1lbnRSZXF1ZXN0Ei0KBG5hbWUYASABKAlCH+BBAvpBGQoXbWVtb3MuYXBpLnYxL0F0dGFjaG1lbnQiggEKF1VwZGF0ZUF0dGFjaG1lbnRSZXF1ZXN0EjEKCmF0dGFjaG1lbnQYASABKAsyGC5tZW1vcy5hcGkudjEuQXR0YWNobWVudEID4EECEjQKC3VwZGF0ZV9tYXNrGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFza0ID4EECIkgKF0RlbGV0ZUF0dGFjaG1lbnRSZXF1ZXN0Ei0KBG5hbWUYASABKAlCH+BBAvpBGQoXbWVtb3MuYXBpLnYxL0F0dGFjaG1lbnQiMwodQmF0Y2hEZWxldGVBdHRhY2htZW50c1JlcXVlc3QSEgoFbmFtZXMYASADKAlCA+BBAipoChFNb3Rpb25NZWRpYUZhbWlseRIjCh9NT1RJT05fTUVESUFfRkFNSUxZX1VOU1BFQ0lGSUVEEAASFAoQQVBQTEVfTElWRV9QSE9UTxABEhgKFEFORFJPSURfTU9USU9OX1BIT1RPEAIqWQoPTW90aW9uTWVkaWFSb2xlEiEKHU1PVElPTl9NRURJQV9ST0xFX1VOU1BFQ0lGSUVEEAASCQoFU1RJTEwQARIJCgVWSURFTxACEg0KCUNPTlRBSU5FUhADMtAGChFBdHRhY2htZW50U2VydmljZRKJAQoQQ3JlYXRlQXR0YWNobWVudBIlLm1lbW9zLmFwaS52MS5DcmVhdGVBdHRhY2htZW50UmVxdWVzdBoYLm1lbW9zLmFwaS52MS5BdHRhY2htZW50IjTaQQphdHRhY2htZW50gtPkkwIhOgphdHRhY2htZW50IhMvYXBpL3YxL2F0dGFjaG1lbnRzEnsKD0xpc3RBdHRhY2htZW50cxIkLm1lbW9zLmFwaS52MS5MaXN0QXR0YWNobWVudHNSZXF1ZXN0GiUubWVtb3MuYXBpLnYxLkxpc3RBdHRhY2htZW50c1Jlc3BvbnNlIhuC0+STAhUSEy9hcGkvdjEvYXR0YWNobWVudHMSegoNR2V0QXR0YWNobWVudBIiLm1lbW9zLmFwaS52MS5HZXRBdHRhY2htZW50UmVxdWVzdBoYLm1lbW9zLmFwaS52MS5BdHRhY2htZW50IivaQQRuYW1lgtPkkwIeEhwvYXBpL3YxL3tuYW1lPWF0dGFjaG1lbnRzLyp9EqkBChBVcGRhdGVBdHRhY2htZW50EiUubWVtb3MuYXBpLnYxLlVwZGF0ZUF0dGFjaG1lbnRSZXF1ZXN0GhgubWVtb3MuYXBpLnYxLkF0dGFjaG1lbnQiVNpBFmF0dGFjaG1lbnQsdXBkYXRlX21hc2uC0+STAjU6CmF0dGFjaG1lbnQyJy9hcGkvdjEve2F0dGFjaG1lbnQubmFtZT1hdHRhY2htZW50cy8qfRJ+ChBEZWxldGVBdHRhY2htZW50EiUubWVtb3MuYXBpLnYxLkRlbGV0ZUF0dGFjaG1lbnRSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IivaQQRuYW1lgtPkkwIeKhwvYXBpL3YxL3tuYW1lPWF0dGFjaG1lbnRzLyp9EokBChZCYXRjaERlbGV0ZUF0dGFjaG1lbnRzEisubWVtb3MuYXBpLnYxLkJhdGNoRGVsZXRlQXR0YWNobWVudHNSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IiqC0+STAiQ6ASoiHy9hcGkvdjEvYXR0YWNobWVudHM6YmF0Y2hEZWxldGVCrgEKEGNvbS5tZW1vcy5hcGkudjFCFkF0dGFjaG1lbnRTZXJ2aWNlUHJvdG9QAVowZ2l0aHViLmNvbS91c2VtZW1vcy9tZW1vcy9wcm90by9nZW4vYXBpL3YxO2FwaXYxogIDTUFYqgIMTWVtb3MuQXBpLlYxygIMTWVtb3NcQXBpXFYx4gIYTWVtb3NcQXBpXFYxXEdQQk1ldGFkYXRh6gIOTWVtb3M6OkFwaTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp]);
/**
* @generated from message memos.api.v1.MotionMedia
@ -385,7 +385,11 @@ export type ListAttachmentsRequest = Message<"memos.api.v1.ListAttachmentsReques
* Optional. Filter to apply to the list results.
* Example: "mime_type==\"image/png\"" or "filename.contains(\"test\")"
* Supported operators: =, !=, <, <=, >, >=, : (contains), in
* Supported fields: filename, mime_type, create_time, memo
* Supported fields: filename, mime_type, create_time, memo_id, space.
* `space` only supports a non-negated `==` comparison with a Space resource
* name or null.
* `space` is the linked memo's space resource name, or null when the
* attachment is unlinked or its linked memo has no space.
*
* @generated from field: string filter = 3;
*/

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,27 +1,76 @@
import { BoxesIcon, Globe2Icon, LockIcon, type LucideIcon, UsersIcon } from "lucide-react";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
export const convertVisibilityFromString = (visibility: string) => {
switch (visibility) {
case "PUBLIC":
return Visibility.PUBLIC;
case "PROTECTED":
return Visibility.PROTECTED;
case "PRIVATE":
return Visibility.PRIVATE;
default:
return Visibility.PUBLIC;
}
};
export interface VisibilityOption {
value: Visibility;
/** Proto enum name, as stored in user settings and sent in filter expressions. */
name: "PRIVATE" | "SPACE" | "PROTECTED" | "PUBLIC";
labelKey: "memo.visibility.private" | "memo.visibility.space" | "memo.visibility.protected" | "memo.visibility.public";
descriptionKey:
| "memo.visibility.private-description"
| "memo.visibility.space-description"
| "memo.visibility.protected-description"
| "memo.visibility.public-description";
icon: LucideIcon;
/** SPACE only means anything inside a Space, so it is offered contextually rather than as a standing choice. */
requiresSpace: boolean;
}
export const convertVisibilityToString = (visibility: Visibility) => {
switch (visibility) {
case Visibility.PUBLIC:
return "PUBLIC";
case Visibility.PROTECTED:
return "PROTECTED";
case Visibility.PRIVATE:
return "PRIVATE";
default:
return "PRIVATE";
}
};
/**
* The single source of truth for how each audience is named, described and drawn.
* Ordered by widening audience. Every visibility surface derives from this, so a new
* enum value is added here once instead of in each picker, icon map and converter.
*/
export const VISIBILITY_OPTIONS: readonly VisibilityOption[] = [
{
value: Visibility.PRIVATE,
name: "PRIVATE",
labelKey: "memo.visibility.private",
descriptionKey: "memo.visibility.private-description",
icon: LockIcon,
requiresSpace: false,
},
{
value: Visibility.SPACE,
name: "SPACE",
labelKey: "memo.visibility.space",
descriptionKey: "memo.visibility.space-description",
icon: BoxesIcon,
requiresSpace: true,
},
{
value: Visibility.PROTECTED,
name: "PROTECTED",
labelKey: "memo.visibility.protected",
descriptionKey: "memo.visibility.protected-description",
icon: UsersIcon,
requiresSpace: false,
},
{
value: Visibility.PUBLIC,
name: "PUBLIC",
labelKey: "memo.visibility.public",
descriptionKey: "memo.visibility.public-description",
icon: Globe2Icon,
requiresSpace: false,
},
];
export const getVisibilityOption = (visibility: Visibility): VisibilityOption | undefined =>
VISIBILITY_OPTIONS.find((option) => option.value === visibility);
/**
* Audiences a memo can be set to. SPACE is offered while a Space is selected, and also
* for a memo that already uses it — so opening one outside its Space shows its real
* audience instead of a blank control that quietly downgrades on the next pick.
*/
export const getAssignableVisibilityOptions = (options: { spaceSelected: boolean; current?: Visibility }): VisibilityOption[] =>
VISIBILITY_OPTIONS.filter((option) => !option.requiresSpace || options.spaceSelected || option.value === options.current);
/** Audiences offered as a persistent default. A Space-scoped default has no meaning outside a Space. */
export const DEFAULT_VISIBILITY_OPTIONS: readonly VisibilityOption[] = VISIBILITY_OPTIONS.filter((option) => !option.requiresSpace);
export const convertVisibilityFromString = (visibility: string) =>
VISIBILITY_OPTIONS.find((option) => option.name === visibility)?.value ?? Visibility.PUBLIC;
export const convertVisibilityToString = (visibility: Visibility) => getVisibilityOption(visibility)?.name ?? "PRIVATE";

View file

@ -17,6 +17,15 @@ const globalEditorState = vi.hoisted(() => ({
canOpen: true,
openEditor: vi.fn(),
}));
const spaceState = vi.hoisted(() => ({
spaces: [] as Array<{ name: string; title: string; description: string }>,
selectedSpace: undefined as { name: string; title: string; description: string } | undefined,
selectedSpaceName: undefined as string | undefined,
memoFilter: "space == null" as string | undefined,
selectMemos: vi.fn(),
selectSpace: vi.fn(),
}));
const filteredStatsHook = vi.hoisted(() => vi.fn());
vi.mock("@/components/MemosLogo", () => ({
default: () => <span>Memos logo</span>,
@ -30,6 +39,10 @@ vi.mock("@/components/UserMenu", () => ({
default: () => <div>User menu</div>,
}));
vi.mock("@/components/CreateSpaceDialog", () => ({
default: () => null,
}));
vi.mock("@/components/StatisticsView", () => ({
default: () => <div>Calendar</div>,
}));
@ -76,12 +89,23 @@ vi.mock("@/contexts/MemoFilterContext", () => ({
}),
}));
vi.mock("@/contexts/SpaceContext", () => ({
useSpaceContext: () => ({
...spaceState,
isLoadingSpaces: false,
isSpacesError: false,
}),
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => authState.currentUser,
}));
vi.mock("@/hooks/useFilteredMemoStats", () => ({
useFilteredMemoStats: () => ({ statistics: { activityStats: {}, timeBasis: "create_time" }, tags: {} }),
useFilteredMemoStats: (options: unknown) => {
filteredStatsHook(options);
return { statistics: { activityStats: {}, timeBasis: "create_time" }, tags: {} };
},
}));
vi.mock("@/hooks/useAttachmentLibrary", () => ({
@ -135,22 +159,57 @@ describe("App sidebar logo", () => {
sidebarState.mobileOpen = false;
globalEditorState.canOpen = true;
globalEditorState.openEditor.mockClear();
spaceState.spaces = [];
spaceState.selectedSpace = undefined;
spaceState.selectedSpaceName = undefined;
spaceState.memoFilter = "space == null";
spaceState.selectMemos.mockClear();
spaceState.selectSpace.mockClear();
filteredStatsHook.mockClear();
});
it("keeps logo navigation unchanged and opens the global memo editor", () => {
it("shows the context switcher and opens the global memo editor", () => {
render(
<MemoryRouter initialEntries={["/attachments"]}>
<AppSidebar />
</MemoryRouter>,
);
const logo = screen.getByRole("link", { name: "Memos logo" });
expect(logo).toHaveAttribute("href", "/");
expect(screen.getByRole("button", { name: "space.switch: common.memos" })).toHaveTextContent("Memos logo");
fireEvent.click(screen.getByRole("button", { name: "editor.new-memo" }));
expect(globalEditorState.openEditor).toHaveBeenCalledOnce();
expect(screen.queryByText("common.calendar")).not.toBeInTheDocument();
});
it("scopes collection statistics to the selected Space", () => {
spaceState.selectedSpaceName = "spaces/product";
spaceState.memoFilter = 'space == "spaces/product"';
render(
<MemoryRouter initialEntries={["/explore"]}>
<AppSidebar />
</MemoryRouter>,
);
expect(filteredStatsHook).toHaveBeenCalledWith(
expect.objectContaining({ context: "explore", filter: 'space == "spaces/product"', includeSpaceVisibility: true }),
);
});
it("hides the instance-level unused attachment collection in a Space", () => {
spaceState.selectedSpaceName = "spaces/product";
spaceState.memoFilter = 'space == "spaces/product"';
render(
<MemoryRouter initialEntries={["/attachments"]}>
<AppSidebar />
</MemoryRouter>,
);
expect(screen.queryByRole("button", { name: "attachment-library.labels.unused" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "attachment-library.tabs.media" })).toBeInTheDocument();
});
it("hides Compose when the composer reports it is not available", () => {
globalEditorState.canOpen = false;
render(
@ -172,6 +231,8 @@ describe("App sidebar logo", () => {
</MemoryRouter>,
);
expect(screen.getByRole("link", { name: "Memos logo" })).toHaveAttribute("href", "/explore");
expect(screen.queryByRole("button", { name: /^space\.switch:/ })).not.toBeInTheDocument();
expect(screen.getByRole("link", { name: "common.explore" })).toBeInTheDocument();
expect(screen.getByRole("link", { name: "common.about" })).toHaveAttribute("href", "/about");
expect(screen.getByRole("link", { name: "common.sign-in-to-memos" }).closest("footer")).not.toBeNull();
@ -330,7 +391,7 @@ describe("App sidebar logo", () => {
expectActiveNavPill(await screen.findByRole("button", { name: label, current: "page" }), label);
});
it("keeps the mobile header limited to navigation and brand", () => {
it("keeps the mobile header limited to navigation and context", () => {
render(
<MemoryRouter initialEntries={["/about"]}>
<MobileAppHeader />
@ -338,7 +399,7 @@ describe("App sidebar logo", () => {
);
expect(screen.getByRole("button", { name: "Open navigation" })).toHaveAttribute("data-mobile-navigation-trigger");
expect(screen.getByRole("link", { name: "Memos logo" })).toHaveAttribute("href", "/");
expect(screen.getByRole("button", { name: "space.switch: common.memos" })).toHaveTextContent("Memos logo");
expect(screen.queryByRole("button", { name: "common.search" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "editor.new-memo" })).not.toBeInTheDocument();
});

View file

@ -3,7 +3,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { createElement, type PropsWithChildren } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { buildAttachmentLibraryStats, useAttachmentLibraryStats } from "@/hooks/useAttachmentLibrary";
import { buildAttachmentLibraryStats, useAttachmentLibraryStats, useUnusedAttachmentLibrary } from "@/hooks/useAttachmentLibrary";
import {
type Attachment,
AttachmentSchema,
@ -67,10 +67,27 @@ describe("buildAttachmentLibraryStats", () => {
});
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: queryClient }, children);
const { result } = renderHook(() => useAttachmentLibraryStats(), { wrapper });
const filter = 'space == "spaces/team"';
const { result } = renderHook(() => useAttachmentLibraryStats(filter), { wrapper });
await waitFor(() => expect(result.current.isComplete).toBe(true));
expect(result.current.stats).toEqual({ media: 1, documents: 0, audio: 0, unused: 1 });
expect(clients.listAttachments).toHaveBeenCalledTimes(2);
expect(clients.listAttachments.mock.calls.map(([request]) => request.filter)).toEqual([filter, filter]);
});
it("combines the current context with the unused attachment filter", async () => {
clients.listAttachments.mockResolvedValue({ attachments: [], nextPageToken: "" });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: queryClient }, children);
const filter = "space == null";
const { result } = renderHook(() => useUnusedAttachmentLibrary("en", filter), { wrapper });
await waitFor(() => expect(result.current.isComplete).toBe(true));
expect(clients.listAttachments).toHaveBeenCalledWith(
expect.objectContaining({
filter: "(memo_id == null) && (space == null)",
}),
);
});
});

View file

@ -0,0 +1,77 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import CreateSpaceDialog from "@/components/CreateSpaceDialog";
const mocks = vi.hoisted(() => ({
mutateAsync: vi.fn(),
onOpenChange: vi.fn(),
selectSpace: vi.fn(),
toastSuccess: vi.fn(),
isPending: false,
}));
vi.mock("react-hot-toast", () => ({
toast: { error: vi.fn(), success: mocks.toastSuccess },
}));
vi.mock("@/contexts/SpaceContext", () => ({
useSpaceContext: () => ({ selectSpace: mocks.selectSpace }),
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => ({ name: "users/test" }),
}));
vi.mock("@/hooks/useSpaceQueries", () => ({
useCreateSpace: () => ({ mutateAsync: mocks.mutateAsync, isPending: mocks.isPending }),
}));
vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => key,
}));
describe("CreateSpaceDialog", () => {
beforeEach(() => {
mocks.mutateAsync.mockReset().mockResolvedValue({ name: "spaces/product", title: "Product", description: "Plans" });
mocks.onOpenChange.mockClear();
mocks.selectSpace.mockClear();
mocks.toastSuccess.mockClear();
mocks.isPending = false;
});
it("creates and immediately selects the new Space", async () => {
render(<CreateSpaceDialog open onOpenChange={mocks.onOpenChange} />);
fireEvent.change(screen.getByLabelText("common.name"), { target: { value: " Product " } });
fireEvent.change(screen.getByLabelText("common.description"), { target: { value: " Plans " } });
fireEvent.click(screen.getByRole("button", { name: "common.create" }));
await waitFor(() => expect(mocks.mutateAsync).toHaveBeenCalledWith({ title: "Product", description: "Plans" }));
expect(mocks.selectSpace).toHaveBeenCalledWith({ name: "spaces/product", title: "Product", description: "Plans" });
expect(mocks.onOpenChange).toHaveBeenCalledWith(false);
});
it("prevents dismissal while creation is pending", async () => {
let resolveCreate!: (space: { name: string; title: string; description: string }) => void;
mocks.mutateAsync.mockReturnValue(
new Promise((resolve) => {
resolveCreate = resolve;
}),
);
const view = render(<CreateSpaceDialog open onOpenChange={mocks.onOpenChange} />);
fireEvent.change(screen.getByLabelText("common.name"), { target: { value: "Product" } });
fireEvent.click(screen.getByRole("button", { name: "common.create" }));
mocks.isPending = true;
view.rerender(<CreateSpaceDialog open onOpenChange={mocks.onOpenChange} />);
fireEvent.click(screen.getByRole("button", { name: "Close" }));
expect(mocks.onOpenChange).not.toHaveBeenCalled();
expect(screen.getByRole("dialog")).toBeInTheDocument();
await act(async () => {
resolveCreate({ name: "spaces/product", title: "Product", description: "" });
});
expect(mocks.selectSpace).toHaveBeenCalledWith({ name: "spaces/product", title: "Product", description: "" });
expect(mocks.onOpenChange).toHaveBeenCalledWith(false);
});
});

View file

@ -25,6 +25,7 @@ vi.mock("@/contexts/ViewContext", async () => {
import { useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
import { useAllUserStats, useUserStats } from "@/hooks/useUserQueries";
import { State } from "@/types/proto/api/v1/common_pb";
const wrapper = ({ children }: { children: ReactNode }) => children as never;
@ -117,7 +118,55 @@ describe("useFilteredMemoStats", () => {
renderHook(() => useFilteredMemoStats({ userName: "users/test", context: "explore", enabled: false }), { wrapper });
expect(useUserStats).toHaveBeenCalledWith("users/test", { enabled: false });
expect(useUserStats).toHaveBeenCalledWith("users/test", { enabled: false, filter: undefined });
expect(useAllUserStats).toHaveBeenCalledWith(expect.anything(), { enabled: false });
});
it("passes the selected Space filter to Home statistics", () => {
mockUseView.mockReturnValue({
timeBasis: "create_time",
orderByTimeAsc: false,
setOrderByTimeAsc: vi.fn(),
setTimeBasis: vi.fn(),
});
const filter = 'space == "spaces/product"';
renderHook(() => useFilteredMemoStats({ userName: "users/test", context: "home", filter }), { wrapper });
expect(useUserStats).toHaveBeenCalledWith("users/test", { enabled: true, filter });
});
it("scopes Explore statistics and includes the Space audience", () => {
mockUseView.mockReturnValue({
timeBasis: "create_time",
orderByTimeAsc: false,
setOrderByTimeAsc: vi.fn(),
setTimeBasis: vi.fn(),
});
const filter = 'space == "spaces/product"';
renderHook(() => useFilteredMemoStats({ context: "explore", filter, includeSpaceVisibility: true }), { wrapper });
expect(useAllUserStats).toHaveBeenCalledWith(
{
state: State.NORMAL,
filter: '(space == "spaces/product") && (visibility in ["PUBLIC", "PROTECTED", "SPACE"])',
},
{ enabled: true },
);
});
it("uses the no-Space filter for Memos statistics", () => {
mockUseView.mockReturnValue({
timeBasis: "create_time",
orderByTimeAsc: false,
setOrderByTimeAsc: vi.fn(),
setTimeBasis: vi.fn(),
});
const filter = "space == null";
renderHook(() => useFilteredMemoStats({ context: "archived", filter }), { wrapper });
expect(useAllUserStats).toHaveBeenCalledWith({ state: State.ARCHIVED, filter }, { enabled: true });
});
});

View file

@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
loadMemoEditor: vi.fn(),
setMobileOpen: vi.fn(),
setQuickFindOpen: vi.fn(),
selectedSpaceName: undefined as string | undefined,
}));
vi.mock("@/components/MemoEditor/loader", () => ({
@ -27,6 +28,10 @@ vi.mock("@/contexts/AuthContext", () => ({
useAuth: () => ({ isUserSettingsInitialized: mocks.isUserSettingsInitialized }),
}));
vi.mock("@/contexts/SpaceContext", () => ({
useSpaceContext: () => ({ selectedSpaceName: mocks.selectedSpaceName }),
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => mocks.currentUser,
}));
@ -111,6 +116,7 @@ describe("GlobalMemoEditorProvider", () => {
mocks.loadMemoEditor.mockResolvedValue({ default: MockMemoEditor });
mocks.setMobileOpen.mockClear();
mocks.setQuickFindOpen.mockClear();
mocks.selectedSpaceName = undefined;
});
it("opens a modal focus-mode editor, closes the sidebar surfaces, and restores focus after Escape", async () => {
@ -254,4 +260,20 @@ describe("GlobalMemoEditorProvider", () => {
expect(mocks.loadMemoEditor).not.toHaveBeenCalled();
});
it("snapshots the selected Space when opening the composer", async () => {
mocks.selectedSpaceName = "spaces/product";
await openViaTrigger();
expect(mocks.editorProps).toMatchObject({
cacheKey: "global-memo-editor:spaces/product",
defaultSpace: "spaces/product",
});
mocks.selectedSpaceName = "spaces/other";
expect(mocks.editorProps).toMatchObject({
cacheKey: "global-memo-editor:spaces/product",
defaultSpace: "spaces/product",
});
});
});

View file

@ -2,8 +2,17 @@ import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import Home from "@/pages/Home";
const state = vi.hoisted(() => ({
selectedSpaceName: undefined as string | undefined,
editorProps: undefined as Record<string, unknown> | undefined,
listProps: undefined as Record<string, unknown> | undefined,
}));
vi.mock("@/components/MemoEditor", () => ({
default: () => <div data-testid="memo-editor" />,
default: (props: Record<string, unknown>) => {
state.editorProps = props;
return <div data-testid="memo-editor" />;
},
}));
vi.mock("@/components/MemoView", () => ({
@ -14,15 +23,19 @@ vi.mock("@/components/PagedMemoList", () => ({
default: ({
renderer,
renderLeading,
...props
}: {
renderer: (memo: { name: string }, options: { compact: boolean }) => React.ReactNode;
renderLeading: (options: { useGrid: boolean }) => React.ReactNode;
}) => (
<>
{renderLeading({ useGrid: false })}
{renderer({ name: "memos/1" }, { compact: false })}
</>
),
} & Record<string, unknown>) => {
state.listProps = props;
return (
<>
{renderLeading({ useGrid: false })}
{renderer({ name: "memos/1" }, { compact: false })}
</>
);
},
getMemoKey: (memo: { name: string }) => memo.name,
}));
@ -38,6 +51,13 @@ vi.mock("@/contexts/NewMemoContext", () => ({
NewMemoProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
vi.mock("@/contexts/SpaceContext", () => ({
useSpaceContext: () => ({
selectedSpaceName: state.selectedSpaceName,
memoFilter: state.selectedSpaceName ? `space == "${state.selectedSpaceName}"` : "space == null",
}),
}));
vi.mock("@/hooks", () => ({
useMemoFilters: () => "",
useMemoSorting: () => ({ listSort: undefined, orderBy: "create_time desc" }),
@ -53,9 +73,22 @@ vi.mock("@/utils/i18n", () => ({
describe("<Home>", () => {
it("renders the editor and memo cards synchronously without blank placeholders", () => {
state.selectedSpaceName = undefined;
render(<Home />);
expect(screen.getByTestId("memo-editor")).toBeInTheDocument();
expect(screen.getByTestId("memo-view")).toBeInTheDocument();
expect(state.listProps).toMatchObject({ contextFilter: "space == null" });
});
it("filters the feed and sets new memo placement to the selected Space", () => {
state.selectedSpaceName = "spaces/product";
render(<Home />);
expect(state.listProps).toMatchObject({ contextFilter: 'space == "spaces/product"' });
expect(state.editorProps).toMatchObject({
cacheKey: "home-memo-editor:spaces/product",
defaultSpace: "spaces/product",
});
});
});

View file

@ -10,6 +10,7 @@ vi.mock("@/utils/i18n", async (importOriginal) => ({
}));
vi.mock("@/hooks/useCurrentUser", () => ({ default: () => undefined }));
vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userGeneralSetting: undefined }) }));
vi.mock("@/contexts/SpaceContext", () => ({ useSpaceContext: () => ({ selectedSpaceName: undefined }) }));
vi.mock("@/components/map/useReverseGeocoding", () => ({ useReverseGeocoding: () => ({ data: undefined }) }));
beforeAll(() => {

View file

@ -17,6 +17,12 @@ vi.mock("@/contexts/AuthContext", () => ({
useAuth: () => ({ currentUser: { name: "users/test" } }),
}));
vi.mock("@/hooks/useAttachmentQueries", () => ({
attachmentKeys: {
lists: () => ["attachments", "list"],
},
}));
vi.mock("@/hooks/useMemoQueries", () => ({
memoKeys: {
all: ["memos"],
@ -230,6 +236,8 @@ describe("useLiveMemoRefresh", () => {
expect(secondInvalidate).toHaveBeenCalledWith({ queryKey: ["memos"], refetchType: "active" });
expect(firstInvalidate).toHaveBeenCalledWith({ queryKey: ["users", "stats"], refetchType: "active" });
expect(secondInvalidate).toHaveBeenCalledWith({ queryKey: ["users", "stats"], refetchType: "active" });
expect(firstInvalidate).toHaveBeenCalledWith({ queryKey: ["attachments", "list"], refetchType: "active" });
expect(secondInvalidate).toHaveBeenCalledWith({ queryKey: ["attachments", "list"], refetchType: "active" });
});
first.unmount();

View file

@ -11,6 +11,8 @@ import {
} from "@/types/proto/api/v1/memo_service_pb";
const clients = vi.hoisted(() => ({
createMemo: vi.fn(),
createMemoComment: vi.fn(),
getMemo: vi.fn(),
updateMemo: vi.fn(),
}));
@ -20,8 +22,8 @@ vi.mock("@/connect", () => ({
createAttachment: vi.fn(),
},
memoServiceClient: {
createMemo: vi.fn(),
createMemoComment: vi.fn(),
createMemo: clients.createMemo,
createMemoComment: clients.createMemoComment,
getMemo: clients.getMemo,
updateMemo: clients.updateMemo,
},
@ -47,9 +49,39 @@ const createEditorState = (memo: Memo): EditorState => ({
describe("memo editor relation updates", () => {
beforeEach(() => {
clients.createMemo.mockReset().mockImplementation(async ({ memo }: { memo: Memo }) => ({ ...memo, name: "memos/created" }));
clients.createMemoComment
.mockReset()
.mockImplementation(async ({ comment }: { comment: Memo }) => ({ ...comment, name: "memos/comment" }));
clients.getMemo.mockReset();
clients.updateMemo.mockReset();
clients.updateMemo.mockImplementation(async ({ memo }: { memo: Memo }) => memo);
});
it("assigns a new top-level memo to the selected Space", async () => {
const state = createInitialState();
state.content = "Roadmap";
await memoService.save(state, { space: "spaces/product" });
expect(clients.createMemo).toHaveBeenCalledWith({
memo: expect.objectContaining({ content: "Roadmap", space: "spaces/product" }),
});
});
it("does not inherit the selected Space when creating a comment", async () => {
const state = createInitialState();
state.content = "Reply";
await memoService.save(state, { parentMemoName: "memos/parent", space: "spaces/product" });
expect(clients.createMemoComment).toHaveBeenCalledOnce();
const request = clients.createMemoComment.mock.calls[0][0];
expect(request.name).toBe("memos/parent");
expect(request.comment.content).toBe("Reply");
expect(request.comment.space).toBeUndefined();
});
it("sends only mutable references when editing a comment", async () => {
const commentName = "memos/comment";
const parentRelation = createRelation(MemoRelation_Type.COMMENT, commentName, "memos/parent");

View file

@ -56,6 +56,16 @@ describe("memo views", () => {
);
});
it("maps the Space audience without falling back to Private", () => {
expect(
buildMemoFilter({
filters: [],
includePinned: false,
visibilities: [Visibility.PUBLIC, Visibility.PROTECTED, Visibility.SPACE],
}),
).toBe('visibility in ["PUBLIC", "PROTECTED", "SPACE"]');
});
it("maps property filter factors to their CEL flags", () => {
expect(
buildMemoFilter({

View file

@ -12,15 +12,19 @@ const feed = vi.hoisted(() => ({
fetchNextPage: vi.fn(async () => undefined),
}));
const readiness = vi.hoisted(() => ({ userSettings: true }));
const memoQuery = vi.hoisted(() => ({ request: undefined as Record<string, unknown> | undefined }));
vi.mock("@/hooks/useMemoQueries", () => ({
useInfiniteMemos: () => ({
data: { pages: [{ memos: feed.memos, nextPageToken: "" }] },
fetchNextPage: feed.fetchNextPage,
hasNextPage: feed.hasNextPage,
isFetchingNextPage: false,
isLoading: feed.isLoading,
}),
useInfiniteMemos: (request: Record<string, unknown>) => {
memoQuery.request = request;
return {
data: { pages: [{ memos: feed.memos, nextPageToken: "" }] },
fetchNextPage: feed.fetchNextPage,
hasNextPage: feed.hasNextPage,
isFetchingNextPage: false,
isLoading: feed.isLoading,
};
},
}));
vi.mock("@/contexts/MemoFilterContext", () => ({
@ -68,6 +72,7 @@ describe("<PagedMemoList>", () => {
feed.isLoading = false;
feed.fetchNextPage.mockClear();
readiness.userSettings = true;
memoQuery.request = undefined;
});
it("keeps fetched memo content hidden until privacy settings settle", () => {
@ -153,6 +158,18 @@ describe("<PagedMemoList>", () => {
expect(screen.getByTestId("placeholder-sprite")).toBeInTheDocument();
});
it("combines the selected Space filter with the memo list filter", () => {
render(
<QueryClientProvider client={new QueryClient()}>
<PagedMemoList renderer={() => <div />} contextFilter={'space == "spaces/product"'} filter="pinned == true" />
</QueryClientProvider>,
);
expect(memoQuery.request).toMatchObject({
filter: '(space == "spaces/product") && (pinned == true)',
});
});
it("shows the empty state below route-owned leading content", () => {
renderList(undefined, { leading: <div data-testid="leading-content" /> });

View file

@ -27,6 +27,11 @@ vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => ({ profile: instanceState }),
}));
vi.mock("@/contexts/SpaceContext", () => ({
SpaceProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
useSpaceContext: () => ({ selectedSpaceName: undefined }),
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => authState.currentUser,
}));

View file

@ -0,0 +1,167 @@
import { create } from "@bufbuild/protobuf";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getSelectedSpaceStorageKey, SpaceProvider, useSpaceContext } from "@/contexts/SpaceContext";
import { SpaceSchema } from "@/types/proto/api/v1/space_service_pb";
const newlyCreatedSpace = create(SpaceSchema, { name: "spaces/new", title: "New", description: "" });
const state = vi.hoisted(() => ({
currentUser: { name: "users/alice" } as { name: string } | undefined,
query: {
data: [] as Array<{ name: string; title: string; description: string }>,
isSuccess: true,
isPending: false,
isError: false,
},
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => state.currentUser,
}));
vi.mock("@/hooks/useSpaceQueries", () => ({
useSpaces: () => state.query,
}));
const Probe = () => {
const { memoFilter, spaces, selectedSpace, selectedSpaceName, selectMemos, selectSpace } = useSpaceContext();
return (
<div>
<output data-testid="selected-name">{selectedSpaceName ?? "Memos"}</output>
<output data-testid="selected-title">{selectedSpace?.title ?? ""}</output>
<output data-testid="memo-filter">{memoFilter ?? "all"}</output>
<button type="button" onClick={selectMemos}>
Select Memos
</button>
<button type="button" onClick={() => spaces[0] && selectSpace(spaces[0])}>
Select first Space
</button>
<button type="button" onClick={() => selectSpace(newlyCreatedSpace)}>
Select new Space
</button>
<CurrentPath />
</div>
);
};
const CurrentPath = () => <output data-testid="path">{useLocation().pathname}</output>;
const renderProvider = (initialPath = "/explore") =>
render(
<MemoryRouter initialEntries={[initialPath]}>
<SpaceProvider>
<Probe />
</SpaceProvider>
</MemoryRouter>,
);
describe("SpaceProvider", () => {
beforeEach(() => {
sessionStorage.clear();
state.currentUser = { name: "users/alice" };
state.query = { data: [], isSuccess: true, isPending: false, isError: false };
});
it("uses Memos when the user has no stored Space selection", () => {
renderProvider();
expect(screen.getByTestId("selected-name")).toHaveTextContent("Memos");
expect(screen.getByTestId("memo-filter")).toHaveTextContent("space == null");
});
it("restores a valid Space and stores changes only for the current user", () => {
const product = { name: "spaces/product", title: "Product", description: "" };
state.query.data = [product];
sessionStorage.setItem(getSelectedSpaceStorageKey("users/alice"), product.name);
renderProvider();
expect(screen.getByTestId("selected-name")).toHaveTextContent(product.name);
expect(screen.getByTestId("selected-title")).toHaveTextContent("Product");
expect(screen.getByTestId("memo-filter")).toHaveTextContent('space == "spaces/product"');
fireEvent.click(screen.getByRole("button", { name: "Select Memos" }));
expect(sessionStorage.getItem(getSelectedSpaceStorageKey("users/alice"))).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Select first Space" }));
expect(sessionStorage.getItem(getSelectedSpaceStorageKey("users/alice"))).toBe(product.name);
});
it("clears a stored selection only after a successful list proves it unavailable", async () => {
const key = getSelectedSpaceStorageKey("users/alice");
sessionStorage.setItem(key, "spaces/removed");
renderProvider();
await waitFor(() => expect(screen.getByTestId("selected-name")).toHaveTextContent("Memos"));
expect(sessionStorage.getItem(key)).toBeNull();
});
it("preserves a stored selection when the Space list fails transiently", () => {
const key = getSelectedSpaceStorageKey("users/alice");
sessionStorage.setItem(key, "spaces/product");
state.query = { data: [], isSuccess: false, isPending: false, isError: true };
renderProvider();
expect(screen.getByTestId("selected-name")).toHaveTextContent("spaces/product");
expect(sessionStorage.getItem(key)).toBe("spaces/product");
});
it("keeps a newly created Space selected until the refreshed list includes it", () => {
renderProvider();
fireEvent.click(screen.getByRole("button", { name: "Select new Space" }));
expect(screen.getByTestId("selected-name")).toHaveTextContent(newlyCreatedSpace.name);
expect(screen.getByTestId("selected-title")).toHaveTextContent(newlyCreatedSpace.title);
expect(screen.getByTestId("memo-filter")).toHaveTextContent('space == "spaces/new"');
expect(sessionStorage.getItem(getSelectedSpaceStorageKey("users/alice"))).toBe(newlyCreatedSpace.name);
});
it("lands on the context's feed when switching to a Space", () => {
const product = { name: "spaces/product", title: "Product", description: "" };
state.query.data = [product];
renderProvider("/archived");
expect(screen.getByTestId("path")).toHaveTextContent("/archived");
fireEvent.click(screen.getByRole("button", { name: "Select first Space" }));
expect(screen.getByTestId("selected-name")).toHaveTextContent(product.name);
expect(screen.getByTestId("path")).toHaveTextContent("/");
});
it("returns to the Memos feed when leaving a Space, even from another route", () => {
const product = { name: "spaces/product", title: "Product", description: "" };
state.query.data = [product];
sessionStorage.setItem(getSelectedSpaceStorageKey("users/alice"), product.name);
renderProvider("/explore");
fireEvent.click(screen.getByRole("button", { name: "Select Memos" }));
expect(screen.getByTestId("selected-name")).toHaveTextContent("Memos");
expect(screen.getByTestId("path")).toHaveTextContent("/");
});
it("isolates the active selection across account changes", () => {
const product = { name: "spaces/product", title: "Product", description: "" };
const personal = { name: "spaces/personal", title: "Personal", description: "" };
state.query.data = [product, personal];
sessionStorage.setItem(getSelectedSpaceStorageKey("users/alice"), product.name);
sessionStorage.setItem(getSelectedSpaceStorageKey("users/bob"), personal.name);
const view = renderProvider();
expect(screen.getByTestId("selected-name")).toHaveTextContent(product.name);
state.currentUser = { name: "users/bob" };
view.rerender(
<MemoryRouter initialEntries={["/explore"]}>
<SpaceProvider>
<Probe />
</SpaceProvider>
</MemoryRouter>,
);
expect(screen.getByTestId("selected-name")).toHaveTextContent(personal.name);
});
});

View file

@ -0,0 +1,73 @@
import { render } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import Archived from "@/pages/Archived";
import Explore from "@/pages/Explore";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
const state = vi.hoisted(() => ({
selectedSpaceName: undefined as string | undefined,
memoFilter: "space == null" as string | undefined,
listProps: [] as Array<Record<string, unknown>>,
filterOptions: [] as Array<Record<string, unknown>>,
}));
vi.mock("@/components/MemoView", () => ({
default: () => <div />,
}));
vi.mock("@/components/PagedMemoList", () => ({
default: (props: Record<string, unknown>) => {
state.listProps.push(props);
return <div />;
},
getMemoKey: (memo: { name: string }) => memo.name,
}));
vi.mock("@/contexts/SpaceContext", () => ({
useSpaceContext: () => ({ selectedSpaceName: state.selectedSpaceName, memoFilter: state.memoFilter }),
}));
vi.mock("@/hooks", () => ({
useMemoFilters: (options: Record<string, unknown>) => {
state.filterOptions.push(options);
return "filter";
},
useMemoSorting: () => ({ listSort: undefined, orderBy: "create_time desc" }),
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => ({ name: "users/test" }),
}));
describe("Space-scoped feed pages", () => {
beforeEach(() => {
state.selectedSpaceName = undefined;
state.memoFilter = "space == null";
state.listProps = [];
state.filterOptions = [];
});
it("uses the no-Space filter for Memos Explore and Archived", () => {
render(
<>
<Explore />
<Archived />
</>,
);
expect(state.listProps).toHaveLength(2);
expect(state.listProps[0]).toMatchObject({ contextFilter: "space == null" });
expect(state.listProps[1]).toMatchObject({ contextFilter: "space == null" });
});
it("uses the selected Space filter and includes its member audience in Explore", () => {
state.selectedSpaceName = "spaces/product";
state.memoFilter = 'space == "spaces/product"';
render(<Explore />);
expect(state.listProps[0]).toMatchObject({ contextFilter: 'space == "spaces/product"' });
expect(state.filterOptions[0]).toMatchObject({
visibilities: [Visibility.PUBLIC, Visibility.PROTECTED, Visibility.SPACE],
});
});
});

View file

@ -0,0 +1,71 @@
import { create } from "@bufbuild/protobuf";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { spaceKeys, useCreateSpace, useSpaces } from "@/hooks/useSpaceQueries";
import { SpaceSchema } from "@/types/proto/api/v1/space_service_pb";
const clients = vi.hoisted(() => ({
createSpace: vi.fn(),
listSpaces: vi.fn(),
}));
vi.mock("@/connect", () => ({
spaceServiceClient: clients,
}));
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
const createWrapper = (queryClient: QueryClient) =>
function QueryWrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
};
describe("Space queries", () => {
beforeEach(() => {
clients.createSpace.mockReset();
clients.listSpaces.mockReset();
});
it("loads every page so the switcher can show all available Spaces", async () => {
clients.listSpaces
.mockResolvedValueOnce({
spaces: [create(SpaceSchema, { name: "spaces/one", title: "One" })],
nextPageToken: "next",
})
.mockResolvedValueOnce({
spaces: [create(SpaceSchema, { name: "spaces/two", title: "Two" })],
nextPageToken: "",
});
const queryClient = createQueryClient();
const { result } = renderHook(() => useSpaces("users/test"), { wrapper: createWrapper(queryClient) });
await waitFor(() => expect(result.current.data?.map((space) => space.name)).toEqual(["spaces/one", "spaces/two"]));
expect(clients.listSpaces).toHaveBeenNthCalledWith(1, { pageSize: 1000, pageToken: "" });
expect(clients.listSpaces).toHaveBeenNthCalledWith(2, { pageSize: 1000, pageToken: "next" });
});
it("adds a created Space to the current user's cache", async () => {
const createdSpace = create(SpaceSchema, { name: "spaces/product", title: "Product", description: "Plans" });
clients.createSpace.mockResolvedValue(createdSpace);
const queryClient = createQueryClient();
const { result } = renderHook(() => useCreateSpace("users/test"), { wrapper: createWrapper(queryClient) });
await act(async () => {
await result.current.mutateAsync({ title: "Product", description: "Plans" });
});
expect(clients.createSpace).toHaveBeenCalledWith({
space: expect.objectContaining({ title: "Product", description: "Plans" }),
});
expect(queryClient.getQueryData(spaceKeys.list("users/test"))).toEqual([createdSpace]);
});
});

View file

@ -0,0 +1,90 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import SpaceSwitcher from "@/components/AppSidebar/SpaceSwitcher";
const spaceState = vi.hoisted(() => ({
spaces: [
{ name: "spaces/product", title: "Product", description: "" },
{ name: "spaces/research", title: "Research", description: "" },
],
selectedSpace: undefined as { name: string; title: string; description: string } | undefined,
selectedSpaceName: undefined as string | undefined,
selectMemos: vi.fn(),
selectSpace: vi.fn(),
}));
vi.mock("@/components/MemosLogo", () => ({
default: () => <span>Memos</span>,
}));
vi.mock("@/components/CreateSpaceDialog", () => ({
default: ({ open }: { open: boolean }) => (open ? <div role="dialog">Create Space dialog</div> : null),
}));
vi.mock("@/contexts/SpaceContext", () => ({
useSpaceContext: () => ({
...spaceState,
isLoadingSpaces: false,
isSpacesError: false,
}),
}));
vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => key,
}));
describe("SpaceSwitcher", () => {
beforeEach(() => {
spaceState.selectedSpace = undefined;
spaceState.selectedSpaceName = undefined;
spaceState.selectMemos.mockClear();
spaceState.selectSpace.mockClear();
});
it("lists Memos, every available Space, and the create entry", async () => {
render(<SpaceSwitcher />);
fireEvent.click(screen.getByRole("button", { name: "space.switch: common.memos" }));
expect(await screen.findByRole("menuitemradio", { name: "Memos" })).toHaveAttribute("aria-checked", "true");
expect(screen.getByRole("menuitemradio", { name: "Product" })).toHaveAttribute("aria-checked", "false");
expect(screen.getByRole("menuitemradio", { name: "Research" })).toBeInTheDocument();
expect(screen.getByRole("menuitem", { name: "space.create" })).toBeInTheDocument();
});
it("marks exactly one context as active", async () => {
spaceState.selectedSpaceName = "spaces/product";
spaceState.selectedSpace = spaceState.spaces[0];
render(<SpaceSwitcher />);
fireEvent.click(screen.getByRole("button", { name: "space.switch: Product" }));
const rows = await screen.findAllByRole("menuitemradio");
expect(rows.map((row) => row.getAttribute("aria-checked"))).toEqual(["false", "true", "false"]);
// The active row carries the fill; the check is its only indicator.
const active = screen.getByRole("menuitemradio", { name: "Product" });
expect(active.className).toContain("bg-accent/60");
expect(active.querySelector("svg")).not.toBeNull();
expect(screen.getByRole("menuitemradio", { name: "Research" }).querySelector("svg")).toBeNull();
});
it("switches context without navigation and opens Space creation", async () => {
render(<SpaceSwitcher />);
fireEvent.click(screen.getByRole("button", { name: "space.switch: common.memos" }));
fireEvent.click(await screen.findByRole("menuitemradio", { name: "Product" }));
expect(spaceState.selectSpace).toHaveBeenCalledWith(spaceState.spaces[0]);
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
// Selecting Memos is how a signed-in user gets back to the home feed.
fireEvent.click(screen.getByRole("button", { name: "space.switch: common.memos" }));
fireEvent.click(await screen.findByRole("menuitemradio", { name: "Memos" }));
expect(spaceState.selectMemos).toHaveBeenCalledOnce();
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "space.switch: common.memos" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "space.create" }));
expect(screen.getByRole("dialog", { name: "" })).toHaveTextContent("Create Space dialog");
});
});

View file

@ -0,0 +1,61 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, renderHook } from "@testing-library/react";
import type { PropsWithChildren } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useMemoSave } from "@/components/MemoEditor/hooks/useMemoSave";
const mocks = vi.hoisted(() => ({
dispatch: vi.fn(),
markNewMemo: vi.fn(),
memoSave: vi.fn(),
}));
vi.mock("@/components/MemoEditor/services", () => ({
errorService: { getErrorMessage: () => "save failed" },
memoService: { save: mocks.memoSave },
validationService: { canSave: () => ({ valid: true }) },
}));
vi.mock("@/components/MemoEditor/state", () => ({
useEditorContext: () => ({
actions: {
reset: () => ({ type: "reset" }),
setLoading: (key: string, value: boolean) => ({ type: "set-loading", key, value }),
setMetadata: () => ({ type: "set-metadata" }),
setTimestamps: () => ({ type: "set-timestamps" }),
},
dispatch: mocks.dispatch,
getState: () => ({}),
}),
}));
vi.mock("@/contexts/NewMemoContext", () => ({
useNewMemo: () => ({ markNewMemo: mocks.markNewMemo }),
}));
vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => key,
}));
describe("useMemoSave", () => {
beforeEach(() => {
mocks.dispatch.mockReset();
mocks.markNewMemo.mockReset();
mocks.memoSave.mockReset();
});
it("invalidates scoped attachment libraries after a memo save", async () => {
mocks.memoSave.mockResolvedValue({ hasChanges: true, memoName: "memos/new" });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");
const wrapper = ({ children }: PropsWithChildren) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
const discardDraft = vi.fn();
const { result } = renderHook(() => useMemoSave({ discardDraft }), { wrapper });
await act(async () => result.current());
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["attachments", "list"] });
expect(discardDraft).toHaveBeenCalledOnce();
expect(mocks.markNewMemo).toHaveBeenCalledWith("memos/new");
});
});

View file

@ -0,0 +1,46 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useAllUserStats, useUserStats } from "@/hooks/useUserQueries";
import { State } from "@/types/proto/api/v1/common_pb";
const clients = vi.hoisted(() => ({
getUserStats: vi.fn(),
listAllUserStats: vi.fn(),
}));
vi.mock("@/connect", () => ({
memoViewServiceClient: {},
userServiceClient: clients,
}));
const createWrapper = () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return function QueryWrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
};
};
describe("User statistics filter queries", () => {
beforeEach(() => {
clients.getUserStats.mockReset().mockResolvedValue({ name: "users/test/stats" });
clients.listAllUserStats.mockReset().mockResolvedValue({ stats: [] });
});
it("sends a Space filter with per-user statistics", async () => {
const filter = 'space == "spaces/product"';
const { result } = renderHook(() => useUserStats("users/test", { filter }), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(clients.getUserStats).toHaveBeenCalledWith({ name: "users/test", filter });
});
it("sends the no-Space filter with grouped statistics", async () => {
const filter = "space == null";
const { result } = renderHook(() => useAllUserStats({ state: State.ARCHIVED, filter }), { wrapper: createWrapper() });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(clients.listAllUserStats).toHaveBeenCalledWith(expect.objectContaining({ state: State.ARCHIVED, filter }));
});
});

View file

@ -0,0 +1,71 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import VisibilitySelector from "@/components/MemoEditor/Toolbar/VisibilitySelector";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
const space = vi.hoisted(() => ({ selectedSpaceName: undefined as string | undefined }));
vi.mock("@/contexts/SpaceContext", () => ({
useSpaceContext: () => ({ selectedSpaceName: space.selectedSpaceName }),
}));
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
// Base UI menus reach for layout/pointer APIs jsdom doesn't implement.
beforeAll(() => {
Element.prototype.scrollIntoView = vi.fn();
Element.prototype.hasPointerCapture = vi.fn(() => false);
Element.prototype.setPointerCapture = vi.fn();
Element.prototype.releasePointerCapture = vi.fn();
});
const openMenu = async (value: Visibility, onChange = vi.fn()) => {
render(<VisibilitySelector value={value} onChange={onChange} />);
fireEvent.click(screen.getByRole("button"));
await screen.findByRole("menu");
return onChange;
};
describe("VisibilitySelector", () => {
beforeEach(() => {
space.selectedSpaceName = undefined;
});
it("omits the Space audience outside a Space", async () => {
await openMenu(Visibility.PRIVATE);
expect(screen.getAllByRole("menuitem").map((item) => item.textContent)).toEqual([
"memo.visibility.privatememo.visibility.private-description",
"memo.visibility.protectedmemo.visibility.protected-description",
"memo.visibility.publicmemo.visibility.public-description",
]);
});
it("offers the Space audience with its own description while a Space is selected", async () => {
space.selectedSpaceName = "spaces/product";
await openMenu(Visibility.PRIVATE);
const spaceItem = screen.getByRole("menuitem", { name: /memo\.visibility\.space/ });
expect(spaceItem).toHaveTextContent("memo.visibility.space-description");
});
it("names a Space memo's audience on the trigger even outside its Space", () => {
render(<VisibilitySelector value={Visibility.SPACE} onChange={vi.fn()} />);
expect(screen.getByRole("button")).toHaveTextContent("memo.visibility.space");
});
it("keeps a Space memo's own audience selectable outside its Space", async () => {
await openMenu(Visibility.SPACE);
expect(screen.getByRole("menuitem", { name: /memo\.visibility\.space/ })).toBeInTheDocument();
});
it("reports the picked audience", async () => {
const onChange = await openMenu(Visibility.PRIVATE);
fireEvent.click(screen.getByRole("menuitem", { name: /memo\.visibility\.public/ }));
expect(onChange).toHaveBeenCalledWith(Visibility.PUBLIC);
});
});

View file

@ -0,0 +1,63 @@
import { render } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import VisibilityIcon from "@/components/VisibilityIcon";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
import {
convertVisibilityFromString,
convertVisibilityToString,
DEFAULT_VISIBILITY_OPTIONS,
getAssignableVisibilityOptions,
VISIBILITY_OPTIONS,
} from "@/utils/memo";
const values = (options: readonly { value: Visibility }[]) => options.map((option) => option.value);
describe("Space visibility presentation", () => {
it("round-trips the Space audience name", () => {
expect(convertVisibilityFromString("SPACE")).toBe(Visibility.SPACE);
expect(convertVisibilityToString(Visibility.SPACE)).toBe("SPACE");
});
it("renders a distinct icon per audience", () => {
const rendered = VISIBILITY_OPTIONS.map((option) => {
const { container } = render(<VisibilityIcon visibility={option.value} />);
return container.querySelector("svg")?.innerHTML;
});
expect(rendered.every(Boolean)).toBe(true);
expect(new Set(rendered).size).toBe(VISIBILITY_OPTIONS.length);
});
it("renders nothing for an unspecified audience", () => {
const { container } = render(<VisibilityIcon visibility={Visibility.VISIBILITY_UNSPECIFIED} />);
expect(container.querySelector("svg")).toBeNull();
});
});
describe("assignable visibility options", () => {
it("withholds the Space audience outside a Space", () => {
expect(values(getAssignableVisibilityOptions({ spaceSelected: false }))).toEqual([
Visibility.PRIVATE,
Visibility.PROTECTED,
Visibility.PUBLIC,
]);
});
it("offers the Space audience while a Space is selected", () => {
expect(values(getAssignableVisibilityOptions({ spaceSelected: true }))).toEqual([
Visibility.PRIVATE,
Visibility.SPACE,
Visibility.PROTECTED,
Visibility.PUBLIC,
]);
});
it("keeps a memo's own Space audience on offer outside its Space, so picking cannot silently downgrade it", () => {
expect(values(getAssignableVisibilityOptions({ spaceSelected: false, current: Visibility.SPACE }))).toContain(Visibility.SPACE);
});
it("never offers the Space audience as a persistent default", () => {
expect(values(DEFAULT_VISIBILITY_OPTIONS)).not.toContain(Visibility.SPACE);
});
});