Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat: notes sharing for spaces
Chadpiha62541eb63ec5
diff --git a/preload.js b/preload.jsindex 317ab4d83..d6e655303 100644--- a/preload.js+++ b/preload.js@@ -575,6 +575,7 @@ contextBridge.exposeInMainWorld("electronAPI", {openSoundInputSettings: () => ipcRenderer.invoke("open-sound-input-settings"),openAccessibilitySettings: () => ipcRenderer.invoke("open-accessibility-settings"),openSystemAudioSettings: () => ipcRenderer.invoke("open-system-audio-settings"),+ showEmojiPanel: () => ipcRenderer.invoke("show-emoji-panel"),toggleMediaPlayback: () => ipcRenderer.invoke("toggle-media-playback"),pauseMediaPlayback: () => ipcRenderer.invoke("pause-media-playback"),resumeMediaPlayback: () => ipcRenderer.invoke("resume-media-playback"),diff --git a/src/components/notes/CreateSpaceDialog.tsx b/src/components/notes/CreateSpaceDialog.tsxindex 596be477e..c0416801b 100644--- a/src/components/notes/CreateSpaceDialog.tsx+++ b/src/components/notes/CreateSpaceDialog.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useShallow } from "zustand/react/shallow";import { useTranslation } from "react-i18next";import { Loader2 } from "lucide-react";@@ -12,6 +12,7 @@ import {} from "../ui/dialog";import { Button } from "../ui/button";import { Input } from "../ui/input";+import { Popover, PopoverAnchor, PopoverContent } from "../ui/popover";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";import { useToast } from "../ui/useToast";import CreateWorkspaceDialog from "../CreateWorkspaceDialog";@@ -22,13 +23,42 @@ import { useWorkspace } from "../../hooks/useWorkspace";import { useWorkspaceStore } from "../../stores/workspaceStore";import { useAuth } from "../../hooks/useAuth";import { useDelayedFlag } from "../../hooks/useDelayedFlag";+import { clampEmojiInput } from "../../lib/emojiInput";import {manageableWorkspaces as findManageableWorkspaces,selectWorkspaceForSpaceCreation,} from "../../lib/workspaceSelection";import { revealContainer, setActiveContext } from "../../stores/noteStore";+import { cn } from "../lib/utils";import type { WorkspaceMember } from "../../types/electron";+const EMOJI_CHOICES = [+ "📝",+ "📋",+ "💡",+ "🚀",+ "🎯",+ "📣",+ "🛠️",+ "🎨",+ "📊",+ "💼",+ "🤝",+ "🌱",+ "🔬",+ "🧪",+ "📚",+ "✨",+ "🔥",+ "⭐",+ "💬",+ "🗂️",+ "🧭",+ "🌍",+ "🔒",+ "🏆",+];+interface CreateSpaceDialogProps {open: boolean;onOpenChange: (open: boolean) => void;@@ -54,6 +84,8 @@ export default function CreateSpaceDialog({ open, onOpenChange }: CreateSpaceDia);const [name, setName] = useState("");const [emoji, setEmoji] = useState("");+ const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);+ const emojiInputRef = useRef<HTMLInputElement>(null);const [memberSearch, setMemberSearch] = useState("");const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());const [membersError, setMembersError] = useState(false);@@ -116,6 +148,7 @@ export default function CreateSpaceDialog({ open, onOpenChange }: CreateSpaceDiaif (!nextOpen) {setName("");setEmoji("");+ setEmojiPickerOpen(false);setMemberSearch("");setSelectedIds(new Set());setRosterWorkspaceId(null);@@ -142,6 +175,12 @@ export default function CreateSpaceDialog({ open, onOpenChange }: CreateSpaceDia});};+ // Linux has no OS emoji panel; the in-app grid is the fallback.+ const openEmojiPicker = async (): Promise<void> => {+ const nativeShown = await window.electronAPI?.showEmojiPanel?.().catch(() => false);+ if (!nativeShown) setEmojiPickerOpen(true);+ };+const handleWorkspaceChange = (workspaceId: string) => {setSelectedWorkspaceId(workspaceId);setSelectedIds(new Set());@@ -249,12 +288,46 @@ export default function CreateSpaceDialog({ open, onOpenChange }: CreateSpaceDia<label className="text-xs font-medium text-foreground/50">{t("notes.spaces.emojiLabel")}</label>- <Input- value={emoji}- onChange={(e) => setEmoji(e.target.value)}- maxLength={4}- className="text-center"- />+ <Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}>+ <PopoverAnchor asChild>+ <Input+ ref={emojiInputRef}+ value={emoji}+ onChange={(e) => setEmoji(clampEmojiInput(e.target.value))}+ onClick={() => void openEmojiPicker()}+ aria-label={t("notes.spaces.changeEmoji")}+ className="text-center"+ />+ </PopoverAnchor>+ <PopoverContent+ className="w-auto min-w-0 p-1.5"+ onOpenAutoFocus={(e) => e.preventDefault()}+ onCloseAutoFocus={(e) => e.preventDefault()}+ onInteractOutside={(e) => {+ if (e.target === emojiInputRef.current) e.preventDefault();+ }}+ >+ <div className="grid grid-cols-8 gap-0.5">+ {EMOJI_CHOICES.map((choice) => (+ <button+ key={choice}+ type="button"+ onClick={() => {+ setEmoji(choice === emoji ? "" : choice);+ setEmojiPickerOpen(false);+ emojiInputRef.current?.focus();+ }}+ className={cn(+ "flex h-7 w-7 items-center justify-center rounded-md text-base outline-none transition-colors hover:bg-accent focus-visible:bg-accent",+ choice === emoji && "bg-accent"+ )}+ >+ {choice}+ </button>+ ))}+ </div>+ </PopoverContent>+ </Popover></div><div className="space-y-1.5 flex-1"><label className="text-xs font-medium text-foreground/50">diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex 38ad38726..55c0c457c 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -25,6 +25,7 @@ import {Users,} from "lucide-react";import ShareNoteDialog from "./ShareNoteDialog";+import { noteCapabilities } from "../../lib/notePermissions";import SpaceMembersDialog from "./SpaceMembersDialog";import {useShareCacheEntry,@@ -250,9 +251,17 @@ export default function NoteEditor({const isShared = shareCache ? shareCache.share.visibility !== "private" : Boolean(note.is_shared);// Same gate as SyncService.canSyncSharedNotes: sharing needs a subscription.// An already-shared note stays manageable (unshare/revoke) after a lapse.- // Team notes never get a public web link — their audience is the space (D8).const isSubscribed = useSyncExternalStore(subscribeIsSubscribed, readIsSubscribed);- const canShare = isSignedIn && !isTeamNote && (isSubscribed || Boolean(note.is_shared));+ // Legacy servers do not return note ACLs. Their existing model gives every+ // team member edit access and personal notes to their owner, so those are+ // the safe compatibility defaults until `access.my_permission` is present.+ const shareCapabilities = noteCapabilities(+ shareCache?.access?.my_permission ?? (isTeamNote ? "editor" : "owner")+ );+ const canShare =+ isSignedIn && shareCapabilities.canShare && (isSubscribed || Boolean(note.is_shared));+ // Sync doesn't carry permissions, so a viewer is only known once share state loads.+ const canEditNote = shareCapabilities.canEdit;// A newer cloud copy arrived while this note had unpushed edits (plan §7.3).const conflict = useNoteConflict(note.client_note_id);const [conflictEditorName, setConflictEditorName] = useState<string | null>(null);@@ -723,7 +732,7 @@ export default function NoteEditor({<div className="px-5 pt-4 pb-0"><divref={titleRef}- contentEditable+ contentEditable={canEditNote}suppressContentEditableWarningonInput={handleTitleInput}onKeyDown={handleTitleKeyDown}@@ -1126,14 +1135,18 @@ export default function NoteEditor({) : viewMode === "transcript" && hasMeetingTranscript ? (<RichTextEditor value={note.transcript || ""} disabled />) : viewMode === "enhanced" && enhancement ? (- <RichTextEditor value={enhancement.content} onChange={handleEnhancedChange} />+ <RichTextEditor+ value={enhancement.content}+ onChange={handleEnhancedChange}+ disabled={!canEditNote}+ />) : (<RichTextEditorvalue={note.content}onChange={handleContentChange}editorRef={editorRef}placeholder={t("notes.editor.startWriting")}- disabled={actionProcessingState === "processing"}+ disabled={!canEditNote || actionProcessingState === "processing"}/>)}</div>diff --git a/src/components/notes/ShareNoteDialog.tsx b/src/components/notes/ShareNoteDialog.tsxindex a5ad5867e..ad8a39486 100644--- a/src/components/notes/ShareNoteDialog.tsx+++ b/src/components/notes/ShareNoteDialog.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { Check, Copy, Link2, Loader2, MoreHorizontal } from "lucide-react";+import { Check, Copy, Link2, Loader2, MoreHorizontal, Users } from "lucide-react";import { Dialog, DialogContent, DialogDescription, DialogTitle } from "../ui/dialog";import { Button } from "../ui/button";import {@@ -15,6 +15,7 @@ import { notesInputClass } from "./shared";import { useAuth } from "../../hooks/useAuth";import {NoteSharingService,+ type AccessPrincipalSuggestion,type ShareMutationResponse,} from "../../services/NoteSharingService.js";import { syncService } from "../../services/SyncService.js";@@ -23,11 +24,18 @@ import {getShareCacheEntry,persistNoteShareState,updateShareCache,+ useSpaces,useShareCacheEntry,} from "../../stores/noteStore";import { useToast } from "../ui/useToast";+import MemberAvatar from "../MemberAvatar";import { emailDomain, isPersonalEmailDomain } from "../../utils/personalEmailDomains";-import type { NoteItem, NoteShareInvitation, ShareVisibility } from "../../types/electron";+import type {+ NoteAccessGrant,+ NoteItem,+ NoteShareInvitation,+ ShareVisibility,+} from "../../types/electron";const SHARE_VIEWER_BASE_URL = "https://notes.openwhispr.com";const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;@@ -44,6 +52,12 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst ownerEmail: string = user?.email ?? "";const { t } = useTranslation();const { toast } = useToast();+ const spaces = useSpaces();+ const space = useMemo(+ () => spaces.find((candidate) => candidate.id === note.space_id) ?? null,+ [spaces, note.space_id]+ );+ const isTeamNote = space?.kind === "team";// A note synced from this dialog: markNoteSynced doesn't broadcast, so the// note prop can lag behind the local DB until the next note-updated event.@@ -60,8 +74,11 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst [emailInput, setEmailInput] = useState("");const [inputError, setInputError] = useState<string | null>(null);const [submitting, setSubmitting] = useState(false);+ const [suggestions, setSuggestions] = useState<AccessPrincipalSuggestion[]>([]);+ const [searchingSuggestions, setSearchingSuggestions] = useState(false);const [copied, setCopied] = useState(false);const [resendingId, setResendingId] = useState<string | null>(null);+ const [busyGrantId, setBusyGrantId] = useState<string | null>(null);const emailInputRef = useRef<HTMLInputElement>(null);const copyTimeoutRef = useRef<number | null>(null);const localIsSharedRef = useRef(Boolean(note.is_shared));@@ -74,7 +91,27 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst showDomainOption = Boolean(ownerDomain && !isPersonalEmailDomain(ownerDomain));const share = cached?.share ?? null;+ const access = cached?.access;+ const canManageSharing = access?.can_manage_access ?? true;+ // Principal search needs the ACL API; legacy servers only take raw emails.+ const canSearchPrincipals = Boolean(access?.can_manage_access);const invitations = useMemo(() => cached?.invitations ?? [], [cached?.invitations]);+ const accessInvitationEmails = useMemo(+ () =>+ new Set(+ (access?.grants ?? [])+ .map((grant) => grant.principal.email?.toLowerCase())+ .filter((email): email is string => Boolean(email))+ ),+ [access?.grants]+ );+ const visibleInvitations = useMemo(+ () =>+ invitations.filter(+ (invitation) => !accessInvitationEmails.has(invitation.email.toLowerCase())+ ),+ [invitations, accessInvitationEmails]+ );// While server state loads, the persisted flag keeps the footer honest.const isPrivate = share ? share.visibility === "private" : !note.is_shared;@@ -108,6 +145,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDupdateShareCache(cloudId, (entry) => ({share: res.share,invitations: res.invitations,+ access: res.access ?? entry?.access,rawToken: entry?.rawToken ?? null,}));const serverShared = res.share.visibility !== "private";@@ -141,6 +179,33 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD}}, [open]);+ useEffect(() => {+ const query = emailInput.trim();+ if (!open || !cloudId || !canSearchPrincipals || !query) {+ setSuggestions([]);+ setSearchingSuggestions(false);+ return;+ }+ let cancelled = false;+ setSearchingSuggestions(true);+ const timer = window.setTimeout(() => {+ NoteSharingService.searchAccessPrincipals(cloudId, query)+ .then((res) => {+ if (!cancelled) setSuggestions(res.suggestions.filter((item) => !item.existing_grant_id));+ })+ .catch(() => {+ if (!cancelled) setSuggestions([]);+ })+ .finally(() => {+ if (!cancelled) setSearchingSuggestions(false);+ });+ }, 200);+ return () => {+ cancelled = true;+ window.clearTimeout(timer);+ };+ }, [open, cloudId, canSearchPrincipals, emailInput]);+useEffect(() => {return () => {if (copyTimeoutRef.current) window.clearTimeout(copyTimeoutRef.current);@@ -149,7 +214,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst applyVisibility = useCallback(async (next: ShareVisibility): Promise<ShareMutationResponse | null> => {- if (!cloudId) return null;+ if (!cloudId || !canManageSharing) return null;const previous = getShareCacheEntry(cloudId);if (!previous || previous.share.visibility === next) return null;setSavingVisibility(true);@@ -217,7 +282,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDsetSavingVisibility(false);}},- [cloudId, ownerDomain, note.id, t, toast]+ [cloudId, canManageSharing, ownerDomain, note.id, t, toast]);const copyLink = useCallback(@@ -259,7 +324,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD}, [cloudId, note.id, copyLink, t, toast]);const handleLinkButton = useCallback(async () => {- if (!cloudId || !share) return;+ if (!cloudId || !share || !canManageSharing) return;setLinkBusy(true);try {if (share.visibility === "private") {@@ -277,10 +342,18 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD} finally {setLinkBusy(false);}- }, [cloudId, share, note.share_token, applyVisibility, copyLink, rotateAndCopy]);+ }, [+ cloudId,+ share,+ canManageSharing,+ note.share_token,+ applyVisibility,+ copyLink,+ rotateAndCopy,+ ]);const handleInvite = useCallback(async () => {- if (!cloudId) return;+ if (!cloudId || !canManageSharing) return;const trimmed = emailInput.trim();if (!trimmed) return;if (!EMAIL_REGEX.test(trimmed)) {@@ -320,11 +393,82 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD} finally {setSubmitting(false);}- }, [cloudId, emailInput, applyVisibility, t]);+ }, [cloudId, canManageSharing, emailInput, applyVisibility, t]);++ const handlePrincipalGrant = useCallback(+ async (principal: AccessPrincipalSuggestion) => {+ if (!cloudId || !cached?.access?.can_manage_access) return;+ setSubmitting(true);+ setInputError(null);+ try {+ const grant = await NoteSharingService.createAccessGrant(cloudId, {+ principal_type: principal.type,+ ...(principal.id ? { principal_id: principal.id } : {}),+ ...(principal.email ? { email: principal.email } : {}),+ permission: "viewer",+ });+ const refreshed = await NoteSharingService.getShareSettings(cloudId);+ updateShareCache(cloudId, (entry) => ({+ share: refreshed.share,+ invitations: refreshed.invitations,+ access:+ refreshed.access ??+ (entry?.access+ ? { ...entry.access, grants: [...entry.access.grants, grant] }+ : cached.access),+ rawToken: entry?.rawToken ?? cached.rawToken,+ }));+ if (refreshed.share.visibility !== "private") {+ void persistNoteShareState(note.id, { is_shared: 1 }).catch((err) =>+ console.error("Share flag persist failed:", err)+ );+ }+ setEmailInput("");+ setSuggestions([]);+ } catch (err) {+ console.error("Access grant creation failed:", err);+ setInputError(t("noteEditor.share.dialog.error.inviteFailed"));+ } finally {+ setSubmitting(false);+ }+ },+ [cloudId, cached, note.id, t]+ );++ const handleShareInput = useCallback(async () => {+ const trimmed = emailInput.trim();+ if (!trimmed || !canManageSharing) return;++ if (access) {+ const matchingSuggestion = suggestions.find(+ (principal) =>+ principal.email?.toLowerCase() === trimmed.toLowerCase() ||+ principal.name?.toLowerCase() === trimmed.toLowerCase()+ );+ if (matchingSuggestion) {+ await handlePrincipalGrant(matchingSuggestion);+ return;+ }+ if (EMAIL_REGEX.test(trimmed)) {+ await handlePrincipalGrant({+ type: "email",+ id: null,+ email: trimmed,+ name: null,+ image: null,+ member_count: null,+ existing_grant_id: null,+ });+ return;+ }+ }++ await handleInvite();+ }, [access, canManageSharing, emailInput, suggestions, handlePrincipalGrant, handleInvite]);const handleRevoke = useCallback(async (invitation: NoteShareInvitation) => {- if (!cloudId) return;+ if (!cloudId || !canManageSharing) return;const previous = getShareCacheEntry(cloudId);if (!previous) return;updateShareCache(cloudId, (entry) => ({@@ -346,12 +490,12 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDtoast({ title: t("noteEditor.share.dialog.error.revokeFailed"), variant: "destructive" });}},- [cloudId, t, toast]+ [cloudId, canManageSharing, t, toast]);const handleResend = useCallback(async (invitation: NoteShareInvitation) => {- if (!cloudId) return;+ if (!cloudId || !canManageSharing) return;setResendingId(invitation.id);try {const res = await NoteSharingService.resendInvite(cloudId, invitation.id);@@ -367,7 +511,76 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDsetResendingId(null);}},- [cloudId, t, toast]+ [cloudId, canManageSharing, t, toast]+ );++ const replaceAccessGrant = useCallback(+ (grantId: string, replacement: NoteAccessGrant | null) => {+ if (!cloudId || !cached) return;+ updateShareCache(cloudId, (entry) => ({+ share: entry?.share ?? cached.share,+ invitations: entry?.invitations ?? cached.invitations,+ access: entry?.access+ ? {+ ...entry.access,+ grants: replacement+ ? entry.access.grants.map((grant) => (grant.id === grantId ? replacement : grant))+ : entry.access.grants.filter((grant) => grant.id !== grantId),+ }+ : undefined,+ rawToken: entry?.rawToken ?? cached.rawToken,+ }));+ },+ [cloudId, cached]+ );++ const handleGrantPermission = useCallback(+ async (grant: NoteAccessGrant, permission: NoteAccessGrant["permission"]) => {+ if (!cloudId || grant.permission === permission) return;+ setBusyGrantId(grant.id);+ replaceAccessGrant(grant.id, { ...grant, permission });+ try {+ replaceAccessGrant(+ grant.id,+ await NoteSharingService.updateAccessGrant(cloudId, grant.id, permission)+ );+ } catch (err) {+ console.error("Access grant update failed:", err);+ replaceAccessGrant(grant.id, grant);+ toast({+ title: t("noteEditor.share.dialog.error.visibilityFailed"),+ variant: "destructive",+ });+ } finally {+ setBusyGrantId(null);+ }+ },+ [cloudId, replaceAccessGrant, t, toast]+ );++ const handleRemoveGrant = useCallback(+ async (grant: NoteAccessGrant) => {+ if (!cloudId) return;+ setBusyGrantId(grant.id);+ replaceAccessGrant(grant.id, null);+ try {+ await NoteSharingService.removeAccessGrant(cloudId, grant.id);+ const refreshed = await NoteSharingService.getShareSettings(cloudId);+ updateShareCache(cloudId, (entry) => ({+ share: refreshed.share,+ invitations: refreshed.invitations,+ access: refreshed.access ?? entry?.access,+ rawToken: entry?.rawToken ?? null,+ }));+ } catch (err) {+ console.error("Access grant removal failed:", err);+ replaceAccessGrant(grant.id, grant);+ toast({ title: t("noteEditor.share.dialog.error.revokeFailed"), variant: "destructive" });+ } finally {+ setBusyGrantId(null);+ }+ },+ [cloudId, replaceAccessGrant, t, toast]);const handleSyncAndShare = useCallback(async () => {@@ -387,7 +600,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDconst onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {if (e.key === "Enter" || (e.metaKey && e.key === "Enter")) {e.preventDefault();- void handleInvite();+ void handleShareInput();}};@@ -432,35 +645,78 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD</DialogDescription>{/* Invite row */}- <div className="flex items-center gap-2">- <input- ref={emailInputRef}- type="email"- value={emailInput}- onChange={(e) => {- setEmailInput(e.target.value);- if (inputError) setInputError(null);- }}- onKeyDown={onKeyDown}- placeholder={t("noteEditor.share.dialog.searchPlaceholder")}- disabled={submitting}- className={cn(- notesInputClass,- "flex-1 disabled:opacity-50 disabled:cursor-not-allowed"- )}- aria-label={t("noteEditor.share.dialog.emailLabel")}- aria-invalid={inputError ? true : undefined}- aria-describedby={inputError ? "share-invite-error" : undefined}- />- <Button- size="sm"- onClick={() => void handleInvite()}- disabled={submitting || !emailInput.trim()}- className="h-8 px-3 text-xs gap-1.5"- >- {submitting && <Loader2 size={12} className="animate-spin" />}- {t("noteEditor.share.dialog.shareButton")}- </Button>+ <div className="relative">+ <div className="flex items-center gap-2">+ <input+ ref={emailInputRef}+ type="text"+ value={emailInput}+ onChange={(e) => {+ setEmailInput(e.target.value);+ if (inputError) setInputError(null);+ }}+ onKeyDown={onKeyDown}+ placeholder={t("noteEditor.share.dialog.searchPlaceholder")}+ disabled={loading || submitting || !canManageSharing}+ className={cn(+ notesInputClass,+ "flex-1 disabled:opacity-50 disabled:cursor-not-allowed"+ )}+ aria-label={t("noteEditor.share.dialog.emailLabel")}+ aria-invalid={inputError ? true : undefined}+ aria-describedby={inputError ? "share-invite-error" : undefined}+ />+ <Button+ size="sm"+ onClick={() => void handleShareInput()}+ disabled={loading || submitting || !canManageSharing || !emailInput.trim()}+ className="h-8 px-3 text-xs gap-1.5"+ >+ {submitting && <Loader2 size={12} className="animate-spin" />}+ {t("noteEditor.share.dialog.shareButton")}+ </Button>+ </div>++ {access && emailInput.trim() && (searchingSuggestions || suggestions.length > 0) && (+ <div className="absolute z-20 top-9 left-0 right-[72px] max-h-44 overflow-y-auto rounded-lg border border-border bg-popover p-1 shadow-lg">+ {searchingSuggestions && suggestions.length === 0 ? (+ <div className="h-8 flex items-center justify-center">+ <Loader2 size={12} className="animate-spin text-foreground/40" />+ </div>+ ) : (+ suggestions.map((principal) => (+ <button+ key={`${principal.type}:${principal.id ?? principal.email}`}+ type="button"+ onClick={() => void handlePrincipalGrant(principal)}+ className="flex items-center gap-2 w-full min-w-0 px-2 h-9 rounded-md text-left hover:bg-foreground/5 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ {principal.type === "team" ||+ principal.type === "folder" ||+ principal.type === "workspace" ? (+ <AudienceIcon />+ ) : (+ <MemberAvatar+ name={principal.name}+ email={principal.email ?? principal.name ?? ""}+ image={principal.image}+ />+ )}+ <span className="min-w-0 flex-1">+ <span className="block text-xs text-foreground truncate">+ {principal.name || principal.email}+ </span>+ {principal.name && principal.email && (+ <span className="block text-[11px] text-foreground/40 truncate">+ {principal.email}+ </span>+ )}+ </span>+ </button>+ ))+ )}+ </div>+ )}</div><p@@ -473,19 +729,63 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD{/* Members list */}<div className="flex flex-col gap-1.5 mt-1">- <MemberRow- primary={ownerName || ownerEmail}- secondary={ownerName ? ownerEmail : null}- trailing={- <span className="text-[11px] text-foreground/40">- {t("noteEditor.share.dialog.owner")}- </span>- }- />+ {(access?.owner || !isTeamNote) && (+ <MemberRow+ leading={+ <MemberAvatar+ name={access?.owner.name ?? ownerName}+ email={access?.owner.email ?? ownerEmail}+ image={access?.owner.image}+ />+ }+ primary={access?.owner.name || access?.owner.email || ownerName || ownerEmail}+ secondary={+ access?.owner.name ? access.owner.email : ownerName ? ownerEmail : null+ }+ trailing={+ <span className="text-[11px] text-foreground/40">+ {t("noteEditor.share.dialog.owner")}+ </span>+ }+ />+ )}++ {(access?.grants ?? []).map((grant) => (+ <AccessGrantRow+ key={grant.id}+ grant={grant}+ canManage={Boolean(+ access?.can_manage_access &&+ (!grant.inherited || access.can_manage_inherited_access)+ )}+ busy={busyGrantId === grant.id}+ onPermissionChange={(permission) => void handleGrantPermission(grant, permission)}+ onRemove={() => void handleRemoveGrant(grant)}+ />+ ))}- {invitations.map((invitation) => (+ {isTeamNote &&+ space &&+ !(access?.grants ?? []).some(+ (grant) =>+ grant.principal.type === "team" && grant.principal.id === space.cloud_team_id+ ) && (+ <MemberRow+ leading={<AudienceIcon />}+ primary={space.name}+ secondary={t("noteEditor.share.dialog.teamAudience")}+ trailing={+ <span className="text-[11px] text-foreground/40">+ {t("noteEditor.share.dialog.editor")}+ </span>+ }+ />+ )}++ {visibleInvitations.map((invitation) => (<MemberRowkey={invitation.id}+ leading={<MemberAvatar name={null} email={invitation.email} size="md" />}primary={invitation.email}secondary={invitation.accepted_at@@ -493,37 +793,43 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD: t("noteEditor.share.dialog.pending")}trailing={- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- className={cn(- "h-6 w-6 flex items-center justify-center rounded-md",- "hover:bg-foreground/8 dark:hover:bg-white/8",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",- "transition-colors"- )}- aria-label={t("noteEditor.share.dialog.invitationActions")}- >- <MoreHorizontal size={13} className="text-foreground/50" />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" sideOffset={4}>- <DropdownMenuItem- className="text-xs"- disabled={resendingId === invitation.id}- onClick={() => void handleResend(invitation)}- >- {t("noteEditor.share.dialog.resend")}- </DropdownMenuItem>- <DropdownMenuItem- className="text-xs text-red-500"- onClick={() => void handleRevoke(invitation)}- >- {t("noteEditor.share.dialog.revoke")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ canManageSharing ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ className={cn(+ "h-6 w-6 flex items-center justify-center rounded-md",+ "hover:bg-foreground/8 dark:hover:bg-white/8",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",+ "transition-colors"+ )}+ aria-label={t("noteEditor.share.dialog.invitationActions")}+ >+ <MoreHorizontal size={13} className="text-foreground/50" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4}>+ <DropdownMenuItem+ className="text-xs"+ disabled={resendingId === invitation.id}+ onClick={() => void handleResend(invitation)}+ >+ {t("noteEditor.share.dialog.resend")}+ </DropdownMenuItem>+ <DropdownMenuItem+ className="text-xs text-red-500"+ onClick={() => void handleRevoke(invitation)}+ >+ {t("noteEditor.share.dialog.revoke")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <span className="text-[11px] text-foreground/40">+ {t("noteEditor.share.dialog.viewer")}+ </span>+ )}/>))}@@ -535,7 +841,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDvalue={share?.visibility ?? "private"}ownerDomain={ownerDomain}showDomainOption={showDomainOption}- disabled={loading || !share || savingVisibility || linkBusy}+ disabled={loading || !share || !canManageSharing || savingVisibility || linkBusy}onChange={(v) => void applyVisibility(v)}/><div className="flex-1" />@@ -543,7 +849,7 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteDvariant={isPrivate ? "default" : "outline"}size="sm"className="h-8 px-3 text-xs gap-1.5"- disabled={loading || !share || savingVisibility || linkBusy}+ disabled={loading || !share || !canManageSharing || savingVisibility || linkBusy}onClick={() => void handleLinkButton()}>{linkBusy ? (@@ -579,14 +885,16 @@ export default function ShareNoteDialog({ open, onOpenChange, note }: ShareNoteD}interface MemberRowProps {+ leading?: React.ReactNode;primary: string;secondary: string | null;trailing: React.ReactNode;}-function MemberRow({ primary, secondary, trailing }: MemberRowProps) {+function MemberRow({ leading, primary, secondary, trailing }: MemberRowProps) {return (<div className="flex items-center gap-2 py-1.5 px-1">+ {leading}<div className="flex-1 min-w-0"><p className="text-xs text-foreground truncate">{primary}</p>{secondary && <p className="text-[11px] text-foreground/40 truncate">{secondary}</p>}@@ -595,3 +903,105 @@ function MemberRow({ primary, secondary, trailing }: MemberRowProps) {</div>);}++function AudienceIcon() {+ return (+ <span className="w-7 h-7 rounded-md bg-primary/10 text-primary flex items-center justify-center shrink-0">+ <Users size={14} />+ </span>+ );+}++function AccessGrantRow({+ grant,+ canManage,+ busy,+ onPermissionChange,+ onRemove,+}: {+ grant: NoteAccessGrant;+ canManage: boolean;+ busy: boolean;+ onPermissionChange: (permission: NoteAccessGrant["permission"]) => void;+ onRemove: () => void;+}) {+ const { t } = useTranslation();+ const principal = grant.principal;+ const isGroup =+ principal.type === "team" || principal.type === "folder" || principal.type === "workspace";+ const primary = principal.name || principal.email || "";+ const secondary = grant.pending+ ? t("noteEditor.share.dialog.pending")+ : principal.type === "team"+ ? t("noteEditor.share.dialog.teamAudience")+ : principal.name+ ? principal.email+ : null;++ const permissionLabel = t(+ grant.permission === "editor"+ ? "noteEditor.share.dialog.editor"+ : "noteEditor.share.dialog.viewer"+ );++ return (+ <MemberRow+ leading={+ isGroup ? (+ <AudienceIcon />+ ) : (+ <MemberAvatar+ name={principal.name}+ email={principal.email ?? primary}+ image={principal.image}+ />+ )+ }+ primary={primary}+ secondary={secondary}+ trailing={+ canManage ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ disabled={busy}+ aria-label={t("noteEditor.share.dialog.invitationActions")}+ className={cn(+ "h-7 px-2 flex items-center gap-1 rounded-md text-[11px] text-foreground/50",+ "hover:bg-foreground/8 dark:hover:bg-white/8",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",+ "disabled:opacity-50 transition-colors"+ )}+ >+ {busy && <Loader2 size={11} className="animate-spin" />}+ {permissionLabel}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4}>+ <DropdownMenuItem+ className="text-xs gap-2"+ onClick={() => onPermissionChange("viewer")}+ >+ {grant.permission === "viewer" && <Check size={11} />}+ {t("noteEditor.share.dialog.viewer")}+ </DropdownMenuItem>+ <DropdownMenuItem+ className="text-xs gap-2"+ onClick={() => onPermissionChange("editor")}+ >+ {grant.permission === "editor" && <Check size={11} />}+ {t("noteEditor.share.dialog.editor")}+ </DropdownMenuItem>+ <DropdownMenuItem className="text-xs text-red-500" onClick={onRemove}>+ {t("noteEditor.share.dialog.revoke")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <span className="text-[11px] text-foreground/40">{permissionLabel}</span>+ )+ }+ />+ );+}diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsxindex 1995be91a..2c773725f 100644--- a/src/components/notes/SpacesTree.tsx+++ b/src/components/notes/SpacesTree.tsx@@ -42,9 +42,9 @@ import {import { useTeamSpacesCapability } from "../../hooks/useTeamSpacesCapability";import { useAuth } from "../../hooks/useAuth";import { useWorkspace } from "../../hooks/useWorkspace";+import { clampEmojiInput } from "../../lib/emojiInput";import { canManageSpace } from "../../lib/spacePermissions";import { readIsSubscribed, subscribeIsSubscribed } from "../../lib/subscriptionFlag";-import { NoteSharingService } from "../../services/NoteSharingService";import { deleteTeamSpace, leaveTeamSpace, renameTeamSpace } from "../../services/teamSpaceActions";import { useSettingsStore } from "../../stores/settingsStore";import { cn } from "../lib/utils";@@ -77,8 +77,6 @@ import {getNoteFromStore,getFoldersValue,getSpacesValue,- updateShareCache,- persistNoteShareState,} from "../../stores/noteStore";const FOLDER_INPUT_CLASS =@@ -1211,8 +1209,7 @@ export default function SpacesTree({fromSpaceId: number,toSpaceId: number,isFolder: boolean,- onConfirm: () => void,- willDisableShare = false+ onConfirm: () => void) => {const intoSpace = spaces.find((s) => s.id === toSpaceId);const fromSpace = spaces.find((s) => s.id === fromSpaceId);@@ -1227,9 +1224,7 @@ export default function SpacesTree({? t("notes.spaces.confirmMoveInTitle", { space: intoSpace.name }): t("notes.spaces.confirmMoveOutTitle", { space: fromSpace.name }),description: movingIntoTeam- ? willDisableShare- ? `${moveInDescription} ${t("notes.spaces.confirmMoveInShared")}`- : moveInDescription+ ? moveInDescription: t(isFolder ? "notes.spaces.confirmMoveOutFolder" : "notes.spaces.confirmMoveOut", {space: fromSpace.name,}),@@ -1238,33 +1233,6 @@ export default function SpacesTree({});};- // D8: team notes never carry a public web link — moving a web-shared note- // into a team space revokes its share (the confirm dialog announces it).- const willRevokeShare = (note: NoteItem, toSpaceId: number): boolean =>- Boolean(note.is_shared && note.cloud_id) &&- note.space_id !== toSpaceId &&- spaces.find((s) => s.id === toSpaceId)?.kind === "team";-- const revokePublicShare = async (note: NoteItem) => {- const cloudId = note.cloud_id;- if (!cloudId) return;- try {- const res = await NoteSharingService.clearShare(cloudId);- updateShareCache(cloudId, (entry) => ({- share: res.share,- invitations: entry?.invitations ?? [],- rawToken: null,- }));- void persistNoteShareState(note.id, { is_shared: 0, share_token: null }).catch(- (err: unknown) => console.error("Share flag persist failed:", err)- );- } catch {- // Best effort — the move proceeds; the link stays revocable by moving- // the note back to Personal.- toast({ title: t("notes.spaces.shareRevokeFailed"), variant: "destructive" });- }- };-const moveNoteSafely = async (noteId: number, target: NoteMoveTarget): Promise<boolean> => {try {await onMoveNote(noteId, target);@@ -1298,9 +1266,6 @@ export default function SpacesTree({const prev: NoteMoveTarget | null = note? { spaceId: note.space_id, folderId: note.folder_id }: null;- if (note && willRevokeShare(note, target.spaceId)) {- await revokePublicShare(note);- }const moved = await moveNoteSafely(noteId, target);if (moved && prev) {const title = note?.title || t("notes.list.untitled");@@ -1317,8 +1282,7 @@ export default function SpacesTree({note.space_id,target.spaceId,false,- () => void commitMoveNote(noteId, target),- willRevokeShare(note, target.spaceId)+ () => void commitMoveNote(noteId, target));} else {void commitMoveNote(noteId, target);@@ -1368,14 +1332,7 @@ export default function SpacesTree({const { dragState, noteDragHandlers, dropTargetHandlers } = useNoteDragAndDrop({onMoveToTarget: commitMoveNote,onCrossSpaceDrop: (note: DraggedNoteInfo, target, commit) => {- const full = getNoteFromStore(note.id);- confirmCrossSpaceMove(- note.spaceId,- target.spaceId,- false,- commit,- full ? willRevokeShare(full, target.spaceId) : false- );+ confirmCrossSpaceMove(note.spaceId, target.spaceId, false, commit);},onHoverTarget: (key) => setContainerExpanded(key, true),});@@ -1894,8 +1851,7 @@ export default function SpacesTree({<inputautoFocus={spaceRenameFocus === "emoji"}value={renameSpaceEmoji}- onChange={(e) => setRenameSpaceEmoji(e.target.value)}- maxLength={4}+ onChange={(e) => setRenameSpaceEmoji(clampEmojiInput(e.target.value))}aria-label={t("notes.spaces.changeEmoji")}className={cn(FOLDER_INPUT_CLASS, "w-8 shrink-0 px-0 text-center")}/>diff --git a/src/components/ui/popover.tsx b/src/components/ui/popover.tsxindex b9b469a32..3ea072f39 100644--- a/src/components/ui/popover.tsx+++ b/src/components/ui/popover.tsx@@ -7,6 +7,8 @@ const Popover = PopoverPrimitive.Root;const PopoverTrigger = PopoverPrimitive.Trigger;+const PopoverAnchor = PopoverPrimitive.Anchor;+const PopoverContent = React.forwardRef<React.ElementRef<typeof PopoverPrimitive.Content>,React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>@@ -26,4 +28,4 @@ const PopoverContent = React.forwardRef<));PopoverContent.displayName = PopoverPrimitive.Content.displayName;-export { Popover, PopoverTrigger, PopoverContent };+export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent };diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 03caeb0bb..a6bea5661 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -4050,6 +4050,18 @@ class IPCHandlers {ipcMain.handle("open-accessibility-settings", () => openSystemSettings("accessibility"));ipcMain.handle("open-system-audio-settings", () => openSystemSettings("systemAudio"));+ ipcMain.handle("show-emoji-panel", () => {+ try {+ if (app.isEmojiPanelSupported()) {+ app.showEmojiPanel();+ return true;+ }+ } catch (error) {+ debugLogger.error("Failed to show native emoji panel:", error);+ }+ return false;+ });+ipcMain.handle("toggle-media-playback", () => {const mediaPlayer = require("./mediaPlayer");return mediaPlayer.toggleMedia();diff --git a/src/lib/emojiInput.ts b/src/lib/emojiInput.tsnew file mode 100644index 000000000..2eb8470f0--- /dev/null+++ b/src/lib/emojiInput.ts@@ -0,0 +1,13 @@+const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });++// Clamps free-typed emoji-field input to a single emoji. A plain `maxLength`+// counts UTF-16 code units, which silently rejects ZWJ sequences like 🧑💻 (5+// units) — segmenting by grapheme keeps every emoji intact. The last grapheme+// wins so typing into a filled field replaces the current emoji.+export function clampEmojiInput(value: string): string {+ let last = "";+ for (const { segment } of graphemeSegmenter.segment(value.trim())) {+ last = segment;+ }+ return last;+}diff --git a/src/lib/notePermissions.ts b/src/lib/notePermissions.tsnew file mode 100644index 000000000..db1ff5ce1--- /dev/null+++ b/src/lib/notePermissions.ts@@ -0,0 +1,54 @@+import type { NotePermission } from "../types/electron";++export interface NoteCapabilities {+ canView: boolean;+ canEdit: boolean;+ canShare: boolean;+ canDelete: boolean;+ canManageInheritedAccess: boolean;+ canTransferOwnership: boolean;+}++const NO_ACCESS: NoteCapabilities = {+ canView: false,+ canEdit: false,+ canShare: false,+ canDelete: false,+ canManageInheritedAccess: false,+ canTransferOwnership: false,+};++/**+ * Client-side presentation capabilities. The server remains authoritative.+ * Editors may manage direct grants and links, but ownership and inherited+ * team/folder audiences remain owner/admin controls.+ */+export function noteCapabilities(+ permission: NotePermission | null | undefined,+ hasAdminOverride = false+): NoteCapabilities {+ if (hasAdminOverride || permission === "owner") {+ return {+ canView: true,+ canEdit: true,+ canShare: true,+ canDelete: true,+ canManageInheritedAccess: true,+ canTransferOwnership: true,+ };+ }+ if (permission === "editor") {+ return {+ canView: true,+ canEdit: true,+ canShare: true,+ canDelete: false,+ canManageInheritedAccess: false,+ canTransferOwnership: false,+ };+ }+ if (permission === "viewer") {+ return { ...NO_ACCESS, canView: true };+ }+ return { ...NO_ACCESS };+}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 4622b265a..5df00d8ca 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2416,14 +2416,12 @@"confirmMoveInTitle": "Nach {{space}} verschieben?","confirmMoveIn": "Alle in {{space}} können diese Notiz sehen und bearbeiten.","confirmMoveInFolder": "Alle in {{space}} können diesen Ordner und seine Notizen sehen und bearbeiten.",- "confirmMoveInShared": "Der öffentliche Link wird deaktiviert.","confirmMoveOutTitle": "Aus {{space}} verschieben?","confirmMoveOut": "Mitglieder von {{space}} verlieren den Zugriff auf diese Notiz.","confirmMoveOutFolder": "Mitglieder von {{space}} verlieren den Zugriff auf diesen Ordner und seine Notizen.","moved": "„{{title}}“ nach {{target}} verschoben","couldNotMove": "Ordner konnte nicht verschoben werden","couldNotMoveNote": "Notiz konnte nicht verschoben werden",- "shareRevokeFailed": "Öffentlicher Link konnte nicht deaktiviert werden","folderNameTaken": "„{{name}}“ konnte nicht verschoben werden – dort existiert bereits ein Ordner mit diesem Namen","undo": "Rückgängig","emptySpace": "Noch keine Notizen. Notizen hier sind für alle in {{space}} sichtbar.",@@ -3119,13 +3117,16 @@"dialog": {"title": "Notiz teilen","description": "Lade Personen per E-Mail ein oder teile einen Link zu dieser Notiz.",- "searchPlaceholder": "Personen per E-Mail hinzufügen",- "emailLabel": "E-Mail des Empfängers",+ "searchPlaceholder": "Personen, Ordner oder E-Mails suchen",+ "emailLabel": "Personen, Ordner oder E-Mail","shareButton": "Teilen","createLink": "Link erstellen","copyLink": "Link kopieren","copied": "Kopiert","owner": "Eigentümer",+ "editor": "Kann bearbeiten",+ "viewer": "Kann ansehen",+ "teamAudience": "Alle in diesem Team-Bereich","pending": "Ausstehend","accepted": "Hat Zugriff","resend": "Einladung erneut senden",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 36def036d..792f9ffa5 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2416,14 +2416,12 @@"confirmMoveInTitle": "Move to {{space}}?","confirmMoveIn": "Everyone in {{space}} will be able to view and edit this note.","confirmMoveInFolder": "Everyone in {{space}} will be able to view and edit this folder and its notes.",- "confirmMoveInShared": "Its public link will be disabled.","confirmMoveOutTitle": "Move out of {{space}}?","confirmMoveOut": "Members of {{space}} will lose access to this note.","confirmMoveOutFolder": "Members of {{space}} will lose access to this folder and its notes.","moved": "Moved “{{title}}” to {{target}}","couldNotMove": "Couldn't move folder","couldNotMoveNote": "Couldn't move note",- "shareRevokeFailed": "Couldn't disable the public link","folderNameTaken": "Couldn't move “{{name}}” — a folder with that name already exists there","undo": "Undo","emptySpace": "No notes yet. Notes here are visible to everyone in {{space}}.",@@ -3119,13 +3117,16 @@"dialog": {"title": "Share note","description": "Invite people by email or share a link to this note.",- "searchPlaceholder": "Add people by email",- "emailLabel": "Recipient email",+ "searchPlaceholder": "Search people, folders, or emails",+ "emailLabel": "People, folders, or email","shareButton": "Share","createLink": "Create link","copyLink": "Copy link","copied": "Copied","owner": "Owner",+ "editor": "Can edit",+ "viewer": "Can view",+ "teamAudience": "Everyone in this team space","pending": "Pending","accepted": "Has access","resend": "Resend invite",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex e75c998cf..721af5d2a 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2256,14 +2256,12 @@"confirmMoveInTitle": "¿Mover a {{space}}?","confirmMoveIn": "Todos en {{space}} podrán ver y editar esta nota.","confirmMoveInFolder": "Todos en {{space}} podrán ver y editar esta carpeta y sus notas.",- "confirmMoveInShared": "Su enlace público se desactivará.","confirmMoveOutTitle": "¿Sacar de {{space}}?","confirmMoveOut": "Los miembros de {{space}} perderán el acceso a esta nota.","confirmMoveOutFolder": "Los miembros de {{space}} perderán el acceso a esta carpeta y sus notas.","moved": "«{{title}}» se movió a {{target}}","couldNotMove": "No se pudo mover la carpeta","couldNotMoveNote": "No se pudo mover la nota",- "shareRevokeFailed": "No se pudo desactivar el enlace público","folderNameTaken": "No se pudo mover «{{name}}»: ya existe una carpeta con ese nombre allí","undo": "Deshacer","emptySpace": "Aún no hay notas. Las notas aquí son visibles para todos en {{space}}.",@@ -3062,13 +3060,16 @@"dialog": {"title": "Compartir nota","description": "Invita a personas por correo o comparte un enlace a esta nota.",- "searchPlaceholder": "Añade personas por correo",- "emailLabel": "Correo del destinatario",+ "searchPlaceholder": "Buscar personas, carpetas o correos",+ "emailLabel": "Personas, carpetas o correo","shareButton": "Compartir","createLink": "Crear enlace","copyLink": "Copiar enlace","copied": "Copiado","owner": "Propietario",+ "editor": "Puede editar",+ "viewer": "Puede ver",+ "teamAudience": "Todos en este espacio de equipo","pending": "Pendiente","accepted": "Tiene acceso","resend": "Reenviar invitación",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 4b48df9bd..6fb7ab5eb 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2416,14 +2416,12 @@"confirmMoveInTitle": "Déplacer vers {{space}} ?","confirmMoveIn": "Tous les membres de {{space}} pourront voir et modifier cette note.","confirmMoveInFolder": "Tous les membres de {{space}} pourront voir et modifier ce dossier et ses notes.",- "confirmMoveInShared": "Son lien public sera désactivé.","confirmMoveOutTitle": "Retirer de {{space}} ?","confirmMoveOut": "Les membres de {{space}} perdront l'accès à cette note.","confirmMoveOutFolder": "Les membres de {{space}} perdront l'accès à ce dossier et à ses notes.","moved": "« {{title}} » déplacée vers {{target}}","couldNotMove": "Impossible de déplacer le dossier","couldNotMoveNote": "Impossible de déplacer la note",- "shareRevokeFailed": "Impossible de désactiver le lien public","folderNameTaken": "Impossible de déplacer « {{name}} » : un dossier portant ce nom existe déjà à cet emplacement","undo": "Annuler","emptySpace": "Aucune note pour le moment. Les notes ici sont visibles par tous les membres de {{space}}.",@@ -3119,13 +3117,16 @@"dialog": {"title": "Partager la note","description": "Invitez des personnes par e-mail ou partagez un lien vers cette note.",- "searchPlaceholder": "Ajoutez des personnes par e-mail",- "emailLabel": "E-mail du destinataire",+ "searchPlaceholder": "Rechercher des personnes, dossiers ou e-mails",+ "emailLabel": "Personnes, dossiers ou e-mail","shareButton": "Partager","createLink": "Créer un lien","copyLink": "Copier le lien","copied": "Copié","owner": "Propriétaire",+ "editor": "Peut modifier",+ "viewer": "Peut consulter",+ "teamAudience": "Tous les membres de cet espace d'équipe","pending": "En attente","accepted": "A accès","resend": "Renvoyer l'invitation",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 22772f07b..115eee815 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2208,14 +2208,12 @@"confirmMoveInTitle": "Spostare in {{space}}?","confirmMoveIn": "Tutti in {{space}} potranno vedere e modificare questa nota.","confirmMoveInFolder": "Tutti in {{space}} potranno vedere e modificare questa cartella e le sue note.",- "confirmMoveInShared": "Il suo link pubblico verrà disattivato.","confirmMoveOutTitle": "Spostare fuori da {{space}}?","confirmMoveOut": "I membri di {{space}} perderanno l'accesso a questa nota.","confirmMoveOutFolder": "I membri di {{space}} perderanno l'accesso a questa cartella e alle sue note.","moved": "“{{title}}” spostata in {{target}}","couldNotMove": "Impossibile spostare la cartella","couldNotMoveNote": "Impossibile spostare la nota",- "shareRevokeFailed": "Impossibile disattivare il link pubblico","folderNameTaken": "Impossibile spostare “{{name}}”: esiste già una cartella con questo nome in quella posizione","undo": "Annulla","emptySpace": "Ancora nessuna nota. Le note qui sono visibili a tutti in {{space}}.",@@ -3014,13 +3012,16 @@"dialog": {"title": "Condividi nota","description": "Invita persone tramite email o condividi un link a questa nota.",- "searchPlaceholder": "Aggiungi persone tramite email",- "emailLabel": "Email del destinatario",+ "searchPlaceholder": "Cerca persone, cartelle o email",+ "emailLabel": "Persone, cartelle o email","shareButton": "Condividi","createLink": "Crea link","copyLink": "Copia link","copied": "Copiato","owner": "Proprietario",+ "editor": "Può modificare",+ "viewer": "Può visualizzare",+ "teamAudience": "Tutti in questo spazio del team","pending": "In attesa","accepted": "Ha accesso","resend": "Reinvia invito",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex aef065164..a86cecab3 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2136,14 +2136,12 @@"confirmMoveInTitle": "{{space}}に移動しますか?","confirmMoveIn": "{{space}}の全員がこのノートを表示・編集できるようになります。","confirmMoveInFolder": "{{space}}の全員がこのフォルダとそのノートを表示・編集できるようになります。",- "confirmMoveInShared": "公開リンクは無効になります。","confirmMoveOutTitle": "{{space}}から移動しますか?","confirmMoveOut": "{{space}}のメンバーはこのノートにアクセスできなくなります。","confirmMoveOutFolder": "{{space}}のメンバーはこのフォルダとそのノートにアクセスできなくなります。","moved": "「{{title}}」を{{target}}に移動しました","couldNotMove": "フォルダを移動できませんでした","couldNotMoveNote": "ノートを移動できませんでした",- "shareRevokeFailed": "公開リンクを無効にできませんでした","folderNameTaken": "「{{name}}」を移動できませんでした。同じ名前のフォルダが既に存在します","undo": "元に戻す","emptySpace": "まだノートがありません。ここのノートは{{space}}の全員に表示されます。",@@ -3014,13 +3012,16 @@"dialog": {"title": "ノートを共有","description": "メールで招待するか、このノートへのリンクを共有します。",- "searchPlaceholder": "メールアドレスでメンバーを追加",- "emailLabel": "受信者のメールアドレス",+ "searchPlaceholder": "ユーザー、フォルダー、メールを検索",+ "emailLabel": "ユーザー、フォルダー、メール","shareButton": "共有","createLink": "リンクを作成","copyLink": "リンクをコピー","copied": "コピーしました","owner": "オーナー",+ "editor": "編集可能",+ "viewer": "閲覧可能",+ "teamAudience": "このチームスペースの全員","pending": "保留中","accepted": "アクセス権あり","resend": "招待を再送信",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex f99dcff9b..fa29bb0e5 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2208,14 +2208,12 @@"confirmMoveInTitle": "Mover para {{space}}?","confirmMoveIn": "Todos em {{space}} poderão ver e editar esta nota.","confirmMoveInFolder": "Todos em {{space}} poderão ver e editar esta pasta e suas notas.",- "confirmMoveInShared": "O link público será desativado.","confirmMoveOutTitle": "Mover para fora de {{space}}?","confirmMoveOut": "Os membros de {{space}} perderão o acesso a esta nota.","confirmMoveOutFolder": "Os membros de {{space}} perderão o acesso a esta pasta e suas notas.","moved": "“{{title}}” movida para {{target}}","couldNotMove": "Não foi possível mover a pasta","couldNotMoveNote": "Não foi possível mover a nota",- "shareRevokeFailed": "Não foi possível desativar o link público","folderNameTaken": "Não foi possível mover “{{name}}”: já existe uma pasta com esse nome nesse local","undo": "Desfazer","emptySpace": "Nenhuma nota ainda. As notas aqui são visíveis para todos em {{space}}.",@@ -3014,13 +3012,16 @@"dialog": {"title": "Compartilhar nota","description": "Convide pessoas por e-mail ou compartilhe um link para esta nota.",- "searchPlaceholder": "Adicione pessoas por e-mail",- "emailLabel": "E-mail do destinatário",+ "searchPlaceholder": "Buscar pessoas, pastas ou emails",+ "emailLabel": "Pessoas, pastas ou email","shareButton": "Compartilhar","createLink": "Criar link","copyLink": "Copiar link","copied": "Copiado","owner": "Proprietário",+ "editor": "Pode editar",+ "viewer": "Pode visualizar",+ "teamAudience": "Todos neste espaço de equipe","pending": "Pendente","accepted": "Com acesso","resend": "Reenviar convite",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 03495fa84..be7726628 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2212,14 +2212,12 @@"confirmMoveInTitle": "Переместить в {{space}}?","confirmMoveIn": "Все в {{space}} смогут просматривать и редактировать эту заметку.","confirmMoveInFolder": "Все в {{space}} смогут просматривать и редактировать эту папку и её заметки.",- "confirmMoveInShared": "Публичная ссылка будет отключена.","confirmMoveOutTitle": "Переместить из {{space}}?","confirmMoveOut": "Участники {{space}} потеряют доступ к этой заметке.","confirmMoveOutFolder": "Участники {{space}} потеряют доступ к этой папке и её заметкам.","moved": "«{{title}}» перемещено в {{target}}","couldNotMove": "Не удалось переместить папку","couldNotMoveNote": "Не удалось переместить заметку",- "shareRevokeFailed": "Не удалось отключить публичную ссылку","folderNameTaken": "Не удалось переместить «{{name}}» — там уже есть папка с таким именем","undo": "Отменить","emptySpace": "Пока нет заметок. Заметки здесь видны всем в {{space}}.",@@ -3030,13 +3028,16 @@"dialog": {"title": "Поделиться заметкой","description": "Приглашайте людей по эл. почте или поделитесь ссылкой на эту заметку.",- "searchPlaceholder": "Добавьте людей по эл. почте",- "emailLabel": "Эл. почта получателя",+ "searchPlaceholder": "Поиск людей, папок или адресов",+ "emailLabel": "Люди, папки или адрес эл. почты","shareButton": "Поделиться","createLink": "Создать ссылку","copyLink": "Скопировать ссылку","copied": "Скопировано","owner": "Владелец",+ "editor": "Может редактировать",+ "viewer": "Может просматривать",+ "teamAudience": "Все в этом командном пространстве","pending": "Ожидает","accepted": "Имеет доступ","resend": "Отправить приглашение снова",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 53ceeab18..6413d0096 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2208,14 +2208,12 @@"confirmMoveInTitle": "移动到 {{space}}?","confirmMoveIn": "{{space}} 中的所有人都将能查看和编辑此笔记。","confirmMoveInFolder": "{{space}} 中的所有人都将能查看和编辑此文件夹及其笔记。",- "confirmMoveInShared": "其公开链接将被停用。","confirmMoveOutTitle": "移出 {{space}}?","confirmMoveOut": "{{space}} 的成员将无法再访问此笔记。","confirmMoveOutFolder": "{{space}} 的成员将无法再访问此文件夹及其笔记。","moved": "已将“{{title}}”移动到 {{target}}","couldNotMove": "无法移动文件夹","couldNotMoveNote": "无法移动笔记",- "shareRevokeFailed": "无法停用公开链接","folderNameTaken": "无法移动“{{name}}”:该位置已存在同名文件夹","undo": "撤销","emptySpace": "还没有笔记。这里的笔记对 {{space}} 中的所有人可见。",@@ -3014,13 +3012,16 @@"dialog": {"title": "分享笔记","description": "通过电子邮件邀请他人,或分享此笔记的链接。",- "searchPlaceholder": "通过电子邮件添加成员",- "emailLabel": "收件人邮箱",+ "searchPlaceholder": "搜索人员、文件夹或邮箱",+ "emailLabel": "人员、文件夹或邮箱","shareButton": "分享","createLink": "创建链接","copyLink": "复制链接","copied": "已复制","owner": "所有者",+ "editor": "可编辑",+ "viewer": "可查看",+ "teamAudience": "此团队空间中的所有人","pending": "待处理","accepted": "已获得访问权限","resend": "重新发送邀请",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 6599b0808..d0f76fd74 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2208,14 +2208,12 @@"confirmMoveInTitle": "移動到 {{space}}?","confirmMoveIn": "{{space}} 中的所有人都將能檢視和編輯這則筆記。","confirmMoveInFolder": "{{space}} 中的所有人都將能檢視和編輯這個資料夾及其筆記。",- "confirmMoveInShared": "其公開連結將被停用。","confirmMoveOutTitle": "移出 {{space}}?","confirmMoveOut": "{{space}} 的成員將無法再存取這則筆記。","confirmMoveOutFolder": "{{space}} 的成員將無法再存取這個資料夾及其筆記。","moved": "已將「{{title}}」移動到 {{target}}","couldNotMove": "無法移動資料夾","couldNotMoveNote": "無法移動筆記",- "shareRevokeFailed": "無法停用公開連結","folderNameTaken": "無法移動「{{name}}」:該位置已存在同名資料夾","undo": "復原","emptySpace": "還沒有筆記。這裡的筆記對 {{space}} 中的所有人可見。",@@ -3014,13 +3012,16 @@"dialog": {"title": "分享筆記","description": "透過電子郵件邀請成員,或分享此筆記的連結。",- "searchPlaceholder": "透過電子郵件新增成員",- "emailLabel": "收件人電子郵件",+ "searchPlaceholder": "搜尋人員、資料夾或電子郵件",+ "emailLabel": "人員、資料夾或電子郵件","shareButton": "分享","createLink": "建立連結","copyLink": "複製連結","copied": "已複製","owner": "擁有者",+ "editor": "可編輯",+ "viewer": "可檢視",+ "teamAudience": "此團隊空間中的所有人","pending": "待處理","accepted": "已取得存取權","resend": "重新傳送邀請",diff --git a/src/services/NoteSharingService.ts b/src/services/NoteSharingService.tsindex 850b3bc41..8d908cbdf 100644--- a/src/services/NoteSharingService.ts+++ b/src/services/NoteSharingService.ts@@ -1,9 +1,19 @@-import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";-import type { NoteShareInvitation, ShareSettings, ShareVisibility } from "../types/electron";+import { CloudApiError, cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";+import type {+ NoteAccessGrant,+ NoteAccessPrincipal,+ NoteAccessState,+ NotePermission,+ NoteShareInvitation,+ ShareSettings,+ ShareVisibility,+} from "../types/electron";export interface ShareStateResponse {share: ShareSettings;invitations: NoteShareInvitation[];+ // Optional so the desktop can roll out against the legacy sharing service.+ access?: NoteAccessState;}export interface ShareMutationResponse {@@ -26,8 +36,24 @@ function sharePath(cloudId: string, suffix: string = ""): string {return `/api/notes/${encodeURIComponent(cloudId)}/share${suffix}`;}+function accessPath(cloudId: string, suffix: string = ""): string {+ return `/api/notes/${encodeURIComponent(cloudId)}/access${suffix}`;+}+async function getShareSettings(cloudNoteId: string): Promise<ShareStateResponse> {- return cloudGet<ShareStateResponse>(sharePath(cloudNoteId));+ const state = await cloudGet<ShareStateResponse>(sharePath(cloudNoteId));+ if (state.access) return state;++ // The ACL API is deployed independently from legacy link sharing. A 404 is+ // the expected compatibility response until that rollout reaches a server.+ try {+ return { ...state, access: await getAccessSettings(cloudNoteId) };+ } catch (error) {+ if (error instanceof CloudApiError && (error.status === 404 || error.code === "not_found")) {+ return state;+ }+ throw error;+ }}async function updateShareSettings(@@ -71,6 +97,49 @@ async function resendInvite();}+export interface AccessPrincipalSuggestion extends NoteAccessPrincipal {+ existing_grant_id: string | null;+}++async function getAccessSettings(cloudNoteId: string): Promise<NoteAccessState> {+ return cloudGet<NoteAccessState>(accessPath(cloudNoteId));+}++async function searchAccessPrincipals(+ cloudNoteId: string,+ query: string+): Promise<{ suggestions: AccessPrincipalSuggestion[] }> {+ const suffix = `/suggestions?q=${encodeURIComponent(query)}`;+ return cloudGet<{ suggestions: AccessPrincipalSuggestion[] }>(accessPath(cloudNoteId, suffix));+}++async function createAccessGrant(+ cloudNoteId: string,+ input: {+ principal_type: NoteAccessPrincipal["type"];+ principal_id?: string;+ email?: string;+ permission: Exclude<NotePermission, "owner">;+ }+): Promise<NoteAccessGrant> {+ return cloudPost<NoteAccessGrant>(accessPath(cloudNoteId, "/grants"), input);+}++async function updateAccessGrant(+ cloudNoteId: string,+ grantId: string,+ permission: Exclude<NotePermission, "owner">+): Promise<NoteAccessGrant> {+ return cloudPatch<NoteAccessGrant>(+ accessPath(cloudNoteId, `/grants/${encodeURIComponent(grantId)}`),+ { permission }+ );+}++async function removeAccessGrant(cloudNoteId: string, grantId: string): Promise<void> {+ await cloudDelete(accessPath(cloudNoteId, `/grants/${encodeURIComponent(grantId)}`));+}+export const NoteSharingService = {getShareSettings,updateShareSettings,@@ -79,4 +148,9 @@ export const NoteSharingService = {inviteEmails,revokeInvite,resendInvite,+ getAccessSettings,+ searchAccessPrincipals,+ createAccessGrant,+ updateAccessGrant,+ removeAccessGrant,};diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex 8a4faa4bc..f025cdbe3 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -5,6 +5,7 @@ import { findDefaultFolder } from "../components/notes/shared";import type { CloudNote } from "../services/NotesService.js";import type {FolderItem,+ NoteAccessState,NoteItem,NoteShareInvitation,ShareSettings,@@ -14,6 +15,7 @@ import type {export interface NoteShareCacheEntry {share: ShareSettings;invitations: NoteShareInvitation[];+ access?: NoteAccessState;// Raw token is returned by the API exactly once (on generate or rotate)// and is only kept in memory for the active dialog session.rawToken: string | null;@@ -917,7 +919,8 @@ export function updateShareCache(): void {const { shareByCloudId } = useNoteStore.getState();const next = new Map(shareByCloudId);- next.set(cloudId, updater(next.get(cloudId)));+ const current = next.get(cloudId);+ next.set(cloudId, { ...current, ...updater(current) });useNoteStore.setState({ shareByCloudId: next });}diff --git a/src/types/electron.ts b/src/types/electron.tsindex 960a9a649..2b2cca1f8 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -78,6 +78,38 @@ export interface NoteItem {export type ShareVisibility = "private" | "link" | "domain" | "invited";+export type NotePermission = "owner" | "editor" | "viewer";++export type NoteAccessPrincipalType = "user" | "email" | "team" | "folder" | "workspace";++export interface NoteAccessPrincipal {+ type: NoteAccessPrincipalType;+ id: string | null;+ email: string | null;+ name: string | null;+ image: string | null;+ member_count: number | null;+}++export interface NoteAccessGrant {+ id: string;+ principal: NoteAccessPrincipal;+ permission: Exclude<NotePermission, "owner">;+ source: "direct" | "team" | "folder" | "workspace";+ inherited: boolean;+ pending: boolean;+ created_at: string;+ updated_at: string;+}++export interface NoteAccessState {+ owner: NoteAccessPrincipal;+ grants: NoteAccessGrant[];+ my_permission: NotePermission;+ can_manage_access: boolean;+ can_manage_inherited_access: boolean;+}+export interface ShareSettings {visibility: ShareVisibility;token_prefix: string | null;@@ -1299,6 +1331,7 @@ declare global {openSoundInputSettings?: () => Promise<{ success: boolean; error?: string }>;openAccessibilitySettings?: () => Promise<{ success: boolean; error?: string }>;openSystemAudioSettings?: () => Promise<{ success: boolean; error?: string }>;+ showEmojiPanel?: () => Promise<boolean>;toggleMediaPlayback?: () => Promise<boolean>;pauseMediaPlayback?: () => Promise<boolean>;resumeMediaPlayback?: () => Promise<boolean>;diff --git a/test/helpers/emojiInput.test.js b/test/helpers/emojiInput.test.jsnew file mode 100644index 000000000..112f7e8c8--- /dev/null+++ b/test/helpers/emojiInput.test.js@@ -0,0 +1,57 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const ts = require("typescript");++let loaded;+const load = () => {+ if (!loaded) {+ const filename = path.join(__dirname, "../../src/lib/emojiInput.ts");+ const source = fs.readFileSync(filename, "utf8");+ const output = ts.transpileModule(source, {+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },+ }).outputText;+ loaded = import(`data:text/javascript;base64,${Buffer.from(output).toString("base64")}`);+ }+ return loaded;+};++test("empty and whitespace-only input clamps to empty", async () => {+ const { clampEmojiInput } = await load();+ assert.equal(clampEmojiInput(""), "");+ assert.equal(clampEmojiInput(" "), "");+});++test("keeps a single simple emoji", async () => {+ const { clampEmojiInput } = await load();+ assert.equal(clampEmojiInput("😀"), "😀");+});++test("preserves multi-code-unit emoji that maxLength=4 used to reject", async () => {+ const { clampEmojiInput } = await load();+ // ZWJ sequence: 5 UTF-16 code units+ assert.equal(clampEmojiInput("🧑💻"), "🧑💻");+ // Family ZWJ sequence: 8 UTF-16 code units+ assert.equal(clampEmojiInput("👨👩👧"), "👨👩👧");+ // Skin-tone modifier: 4 UTF-16 code units+ assert.equal(clampEmojiInput("👍🏽"), "👍🏽");+ // Regional indicator flag+ assert.equal(clampEmojiInput("🇩🇪"), "🇩🇪");+});++test("typing after an existing emoji replaces it with the new one", async () => {+ const { clampEmojiInput } = await load();+ assert.equal(clampEmojiInput("😀🚀"), "🚀");+ assert.equal(clampEmojiInput("🚀👨👩👧"), "👨👩👧");+});++test("plain text clamps to its last character", async () => {+ const { clampEmojiInput } = await load();+ assert.equal(clampEmojiInput("ab"), "b");+});++test("surrounding whitespace is ignored", async () => {+ const { clampEmojiInput } = await load();+ assert.equal(clampEmojiInput(" 🚀 "), "🚀");+});diff --git a/test/helpers/notePermissions.test.js b/test/helpers/notePermissions.test.jsnew file mode 100644index 000000000..4cf83d94c--- /dev/null+++ b/test/helpers/notePermissions.test.js@@ -0,0 +1,53 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const ts = require("typescript");++let loaded;+const load = () => {+ if (!loaded) {+ const filename = path.join(__dirname, "../../src/lib/notePermissions.ts");+ const source = fs.readFileSync(filename, "utf8");+ const output = ts.transpileModule(source, {+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },+ }).outputText;+ loaded = import(`data:text/javascript;base64,${Buffer.from(output).toString("base64")}`);+ }+ return loaded;+};++test("editors can edit and share without owner-only capabilities", async () => {+ const { noteCapabilities } = await load();++ assert.deepEqual(noteCapabilities("editor"), {+ canView: true,+ canEdit: true,+ canShare: true,+ canDelete: false,+ canManageInheritedAccess: false,+ canTransferOwnership: false,+ });+});++test("viewers cannot edit or share", async () => {+ const { noteCapabilities } = await load();+ const capabilities = noteCapabilities("viewer");++ assert.equal(capabilities.canView, true);+ assert.equal(capabilities.canEdit, false);+ assert.equal(capabilities.canShare, false);+});++test("owners and administrators retain all capabilities", async () => {+ const { noteCapabilities } = await load();++ for (const capabilities of [noteCapabilities("owner"), noteCapabilities("viewer", true)]) {+ assert.equal(capabilities.canView, true);+ assert.equal(capabilities.canEdit, true);+ assert.equal(capabilities.canShare, true);+ assert.equal(capabilities.canDelete, true);+ assert.equal(capabilities.canManageInheritedAccess, true);+ assert.equal(capabilities.canTransferOwnership, true);+ }+});