ocean-brain 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/mcp.js +58 -32
  2. package/package.json +2 -2
  3. package/server/client/dist/assets/{ArrowRight.es-Bm-ZXpEC.js → ArrowRight.es-BEhnlwfe.js} +1 -1
  4. package/server/client/dist/assets/AuxiliaryPanelHeader-B1k7pZpn.js +1 -0
  5. package/server/client/dist/assets/Calendar-D7QJsAlg.js +25 -0
  6. package/server/client/dist/assets/{Callout-CviyPHKO.js → Callout-BTd1BYtV.js} +1 -1
  7. package/server/client/dist/assets/{Copy.es-BPreRnP9.js → Copy.es-BoLjilxv.js} +1 -1
  8. package/server/client/dist/assets/File.es-Ct7fscBg.js +1 -0
  9. package/server/client/dist/assets/{Graph-yPE3ljW0.js → Graph-DYUb7gQb.js} +1 -1
  10. package/server/client/dist/assets/{Graph-vXQQ0a-Q.js → Graph-LY_IgMYy.js} +1 -1
  11. package/server/client/dist/assets/{Image.es-DnR3qc_c.js → Image.es-OYyN3BYt.js} +1 -1
  12. package/server/client/dist/assets/Note-DsMhwrHw.js +25 -0
  13. package/server/client/dist/assets/NotePropertiesPanel-aCKXAe5F.js +2 -0
  14. package/server/client/dist/assets/{PencilLine.es-B9V6u64t.js → PencilLine.es-0JpEgxFY.js} +1 -1
  15. package/server/client/dist/assets/{Plus.es-CRRp2u5J.js → Plus.es-DRfLW_bI.js} +1 -1
  16. package/server/client/dist/assets/{Reminders-BOtfNeYD.js → Reminders-COr1OHvF.js} +1 -1
  17. package/server/client/dist/assets/Search-Ctkx0BQk.js +31 -0
  18. package/server/client/dist/assets/{SurfaceCard-GMt5xM7v.js → SurfaceCard-t7pdfhEe.js} +1 -1
  19. package/server/client/dist/assets/Tag-BjxtrIQW.js +1 -0
  20. package/server/client/dist/assets/TagNotes-DV_fdRbg.js +1 -0
  21. package/server/client/dist/assets/{Trash.es-svHOb5LN.js → Trash.es-Bo1VyK9Q.js} +1 -1
  22. package/server/client/dist/assets/ViewChip-DlCkL4z4.js +1 -0
  23. package/server/client/dist/assets/ViewNotes-wWWeFJyU.js +1 -0
  24. package/server/client/dist/assets/ViewSectionDialog-DhH8harC.js +102 -0
  25. package/server/client/dist/assets/Views-CWE99SnI.js +1 -0
  26. package/server/client/dist/assets/app-B9WZRrAH.css +1 -0
  27. package/server/client/dist/assets/app-BpSMjzET.js +26 -0
  28. package/server/client/dist/assets/{image.api-QmHYjp3z.js → image.api-CyQisInP.js} +1 -1
  29. package/server/client/dist/assets/index-B-E1Ilh9.js +1 -0
  30. package/server/client/dist/assets/manage-image-azmo5iVw.js +1 -0
  31. package/server/client/dist/assets/manage-image-detail-BF-uSqb_.js +1 -0
  32. package/server/client/dist/assets/{mcp-uFZkdhCi.js → mcp-CCaFd0zm.js} +1 -1
  33. package/server/client/dist/assets/mcp-admin-adapter-PMmgPupc.js +1 -0
  34. package/server/client/dist/assets/{note-ui-CxK8ymUc.js → note-ui-CtijppHK.js} +1 -1
  35. package/server/client/dist/assets/{note.api-BQovzEzd.js → note.api-D3oJmG3q.js} +2 -2
  36. package/server/client/dist/assets/{placeholder-D3b8lZGE.js → placeholder-AusSo8p9.js} +2 -2
  37. package/server/client/dist/assets/{properties-M-yWq1D7.js → properties-BrNJLkxR.js} +1 -1
  38. package/server/client/dist/assets/route-preload.js +2 -2
  39. package/server/client/dist/assets/search-D-xKTPdO.js +1 -0
  40. package/server/client/dist/assets/search-admin-adapter-CJnJmL6w.js +1 -0
  41. package/server/client/dist/assets/{tag.api-DUfjr8bg.js → tag.api-DNSQpqwk.js} +1 -1
  42. package/server/client/dist/assets/{time-CfAYZipR.js → time-D5LRMumI.js} +3 -3
  43. package/server/client/dist/assets/trash-D4-9sv8q.js +1 -0
  44. package/server/client/dist/assets/{useReminderMutate--omDLmBV.js → useReminderMutate-BrGO9M0o.js} +1 -1
  45. package/server/client/dist/index.html +5 -5
  46. package/server/dist/features/note/graphql/note.field.resolver.js +2 -0
  47. package/server/dist/features/note/graphql/note.mutation.resolver.js +19 -14
  48. package/server/dist/features/note/graphql/note.query.resolver.js +15 -5
  49. package/server/dist/features/note/graphql/note.type-defs.js +1 -0
  50. package/server/dist/features/note/services/authoring.js +15 -10
  51. package/server/dist/features/note/services/note-reference-index.js +98 -0
  52. package/server/dist/features/note/services/search.js +5 -0
  53. package/server/dist/features/note/services/snapshot.js +4 -0
  54. package/server/dist/features/note/services/trash.js +2 -0
  55. package/server/dist/features/note/services/write.js +10 -3
  56. package/server/dist/features/search/graphql/resolver.js +13 -1
  57. package/server/dist/features/search/graphql/type-defs.js +7 -0
  58. package/server/dist/features/search/hybrid-ranking.js +4 -2
  59. package/server/dist/features/search/hybrid-search.js +4 -2
  60. package/server/dist/features/search/related-notes.js +186 -0
  61. package/server/dist/main.js +10 -3
  62. package/server/prisma/migrations/20260728090000_0019_note_reference_index/migration.sql +15 -0
  63. package/server/prisma/schema.prisma +16 -0
  64. package/server/client/dist/assets/Calendar-BsNs3NzO.js +0 -25
  65. package/server/client/dist/assets/Note-CmreVzvQ.js +0 -25
  66. package/server/client/dist/assets/NotePropertiesPanel-DXYgE8h2.js +0 -2
  67. package/server/client/dist/assets/Search-C-FB3pKf.js +0 -1
  68. package/server/client/dist/assets/Tag-lBxDRE77.js +0 -1
  69. package/server/client/dist/assets/TagNotes-Bgorp_rC.js +0 -1
  70. package/server/client/dist/assets/ViewNotes-C7d10VFf.js +0 -1
  71. package/server/client/dist/assets/ViewSectionDialog-Bhw-ILop.js +0 -102
  72. package/server/client/dist/assets/Views-C7V3saUo.js +0 -1
  73. package/server/client/dist/assets/app-DQBV36r_.js +0 -50
  74. package/server/client/dist/assets/app-ZgwR5t_I.css +0 -1
  75. package/server/client/dist/assets/index-CaF9d-zG.js +0 -1
  76. package/server/client/dist/assets/manage-image-DCDF8AM9.js +0 -1
  77. package/server/client/dist/assets/manage-image-detail-e0ViRAj-.js +0 -1
  78. package/server/client/dist/assets/mcp-admin-adapter-D39G3udJ.js +0 -1
  79. package/server/client/dist/assets/search-DFnzZKLd.js +0 -1
  80. package/server/client/dist/assets/trash-CClKfP1x.js +0 -1
@@ -1,14 +1,20 @@
1
1
  import { createApp } from "./app.js";
2
+ import { ensureNoteReferenceIndex } from "./features/note/services/note-reference-index.js";
2
3
  import { getDefaultSemanticSearchManager } from "./features/search/search-manager.js";
3
4
  import { logAuthConfig, resolveAuthConfig } from "./modules/auth-mode.js";
4
5
  import { startDataMaintenanceScheduler } from "./modules/data-maintenance.js";
5
6
  const PORT = Number(process.env.PORT || 6683);
6
7
  const HOST = process.env.HOST || "0.0.0.0";
7
- try {
8
+ const startServer = async () => {
8
9
  const authConfig = resolveAuthConfig(process.env);
9
10
  logAuthConfig(authConfig);
10
11
  const app = createApp(authConfig);
11
12
  getDefaultSemanticSearchManager();
13
+ const rebuiltReferenceCount = await ensureNoteReferenceIndex();
14
+ if (rebuiltReferenceCount > 0) {
15
+ process.stdout.write(`[maintenance] Rebuilt ${rebuiltReferenceCount} note reference rows
16
+ `);
17
+ }
12
18
  app.listen(PORT, HOST, () => {
13
19
  process.stdout.write(`http server listen on ${HOST}:${PORT} (auth: ${authConfig.mode})
14
20
  `);
@@ -26,9 +32,10 @@ try {
26
32
  }
27
33
  });
28
34
  });
29
- } catch (error) {
35
+ };
36
+ startServer().catch((error) => {
30
37
  const message = error instanceof Error ? error.message : "Unknown auth configuration error";
31
38
  process.stderr.write(`[auth] Startup failed: ${message}
32
39
  `);
33
40
  process.exit(1);
34
- }
41
+ });
@@ -0,0 +1,15 @@
1
+ CREATE TABLE "NoteReference" (
2
+ "sourceNoteId" INTEGER NOT NULL,
3
+ "targetNoteId" INTEGER NOT NULL,
4
+
5
+ PRIMARY KEY ("sourceNoteId", "targetNoteId"),
6
+ CONSTRAINT "NoteReference_sourceNoteId_fkey" FOREIGN KEY ("sourceNoteId") REFERENCES "Note" ("id") ON DELETE CASCADE ON UPDATE CASCADE
7
+ );
8
+
9
+ CREATE INDEX "NoteReference_targetNoteId_sourceNoteId_idx" ON "NoteReference"("targetNoteId", "sourceNoteId");
10
+
11
+ CREATE TABLE "NoteReferenceIndexState" (
12
+ "id" INTEGER NOT NULL PRIMARY KEY,
13
+ "version" INTEGER NOT NULL,
14
+ "updatedAt" DATETIME NOT NULL
15
+ );
@@ -40,12 +40,28 @@ model Note {
40
40
  reminders Reminder[] @relation("NoteToReminder")
41
41
  snapshots NoteSnapshot[]
42
42
  properties NoteProperty[]
43
+ outgoingReferences NoteReference[] @relation("NoteReferenceSource")
43
44
 
44
45
  @@index([updatedAt, id])
45
46
  @@index([createdAt, id])
46
47
  @@index([pinned, updatedAt, id])
47
48
  }
48
49
 
50
+ model NoteReference {
51
+ sourceNoteId Int
52
+ targetNoteId Int
53
+ sourceNote Note @relation("NoteReferenceSource", fields: [sourceNoteId], references: [id], onDelete: Cascade)
54
+
55
+ @@id([sourceNoteId, targetNoteId])
56
+ @@index([targetNoteId, sourceNoteId])
57
+ }
58
+
59
+ model NoteReferenceIndexState {
60
+ id Int @id
61
+ version Int
62
+ updatedAt DateTime @updatedAt
63
+ }
64
+
49
65
  model PropertyDefinition {
50
66
  id Int @id @default(autoincrement())
51
67
  key String @unique
@@ -1,25 +0,0 @@
1
- import{j as e,r as d}from"./floating-ui.react-dom-BWTnA00G.js";import{T as b,C as te,H,M as w,w as se,x as q,B as O,N as ae,U as re,q as F,g as K,P as ne,k as oe,f as ie}from"./note.api-BQovzEzd.js";import{d as f,s as le,a as z}from"./time-CfAYZipR.js";import{N as ce,C as de}from"./url-9nrbQs7Z.js";import{x as ue,y as me}from"./app-DQBV36r_.js";import{C as he}from"./Callout-CviyPHKO.js";import"./preload-helper-BXl3LOEh.js";import"./Graph-vXQQ0a-Q.js";const ge=({day:a,cellClassName:t,dayNumberClassName:s,isCurrentMonth:i,items:o,overflowCount:l,onOpenOverflow:m})=>e.jsxs("div",{className:`min-h-[196px] rounded-[16px] border p-2.5 ${t}`.trim(),children:[e.jsx("div",{className:"mb-2.5 flex justify-end",children:e.jsx(b,{as:"span",variant:"label",className:`flex h-7 w-7 items-center justify-center rounded-[10px] ${s}`.trim(),children:a})}),i&&o.length>0?e.jsxs("div",{className:"flex flex-col gap-1.5",children:[o,l>0?e.jsxs("button",{type:"button",onClick:m,className:"focus-ring-soft w-full rounded-[10px] border border-dashed border-border-subtle/70 bg-subtle/70 py-1 text-center text-micro font-semibold text-fg-tertiary outline-none transition-colors hover:border-border-secondary/70 hover:bg-hover-subtle hover:text-fg-secondary",children:["+",l," more"]}):null]}):null]}),V=({params:a,toneClassName:t="",header:s,title:i,meta:o,titleClassName:l=""})=>e.jsx(te,{to:ce,params:a,className:"focus-ring-soft group block rounded-[8px] outline-none",children:e.jsxs("div",{className:H("flex items-start gap-1.5 rounded-[8px] px-1.5 py-1 transition-colors group-hover:bg-hover-subtle",t),children:[s?e.jsx("span",{className:"mt-[2px] flex h-4 w-4 shrink-0 items-center justify-center text-fg-tertiary",children:s}):e.jsx("span",{"aria-hidden":"true",className:"mt-[6px] h-1.5 w-1.5 shrink-0 rounded-full bg-fg-placeholder"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(b,{as:"div",variant:"label",weight:"medium",tone:"secondary",className:H("line-clamp-1",l),children:i}),o?e.jsx(b,{as:"div",variant:"micro",weight:"medium",tone:"tertiary",className:"mt-0.5",children:o}):null]})]})}),xe=({note:a,type:t})=>e.jsx(V,{params:{id:a.id},header:e.jsx(ue,{size:12}),title:a.title,meta:f(Number(t==="create"?a.createdAt:a.updatedAt)).format("HH:mm")}),pe=({reminder:a})=>e.jsx(V,{params:{id:String(a.note?.id??a.noteId)},header:e.jsx(le,{size:12}),title:a.content||a.note?.title||"No title",titleClassName:a.completed?"line-through":"",meta:f(Number(a.reminderDate)).format("HH:mm")}),A=3,Q=(a,t)=>a.map(s=>s.type==="note"?e.jsx(xe,{note:s.item,type:t},`note-${s.item.id}`):e.jsx(pe,{reminder:s.item},`reminder-${s.item.id}`)),ye=({year:a,month:t,day:s,isCurrentMonth:i,isSunday:o,isToday:l,isPast:m,notes:h,reminders:g,type:N})=>{const[M,v]=d.useState(!1),p=d.useMemo(()=>{const r=h.map(u=>({type:"note",item:u})),c=g.map(u=>({type:"reminder",item:u}));return m?[...r,...c]:[...c,...r]},[m,h,g]),D=p.length>A,S=d.useMemo(()=>Q(p.slice(0,A),N),[p,N]),$=d.useMemo(()=>Q(p,N),[p,N]),k=d.useCallback(()=>v(!0),[]),C=d.useCallback(()=>v(!1),[]),E=()=>i?l?"border-border-secondary/70 bg-[color:color-mix(in_srgb,var(--surface)_88%,var(--accent-soft-primary)_12%)]":"bg-surface border-border-subtle":"bg-muted/18 border-border-subtle/70",I=()=>l?"bg-cta text-fg-on-filled font-semibold":i?o?"text-fg-weekend font-bold":"text-fg-secondary font-bold":"text-fg-disabled opacity-55";return e.jsxs(e.Fragment,{children:[e.jsx(ge,{day:s,cellClassName:E(),dayNumberClassName:I(),isCurrentMonth:i,items:S,overflowCount:D?p.length-A:0,onOpenOverflow:k}),D&&e.jsxs(w,{isOpen:M,onClose:C,variant:"inspect",children:[e.jsx(w.Header,{title:`${a}/${String(t).padStart(2,"0")}/${String(s).padStart(2,"0")}`,onClose:C}),e.jsxs(w.Body,{children:[e.jsxs(w.Description,{className:"sr-only",children:["View all notes and reminders scheduled for day ",s,"."]}),e.jsx("div",{className:"flex max-h-[60vh] flex-col gap-2 overflow-y-auto",children:$})]})]})]})},fe=d.memo(ye),be=["January","February","March","April","May","June","July","August","September","October","November","December"],je=({month:a,year:t,type:s,onPrevMonth:i,onNextMonth:o,onToday:l,onTypeChange:m})=>e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-x-2.5 gap-y-1",children:[e.jsx(b,{as:"h1",variant:"display",weight:"bold",tracking:"tighter",className:"text-2xl leading-none sm:text-[2.15rem]",children:be[a-1]}),e.jsx(b,{as:"span",variant:"subheading",weight:"medium",tone:"secondary",tracking:"tight",className:"pb-0.5",children:t})]}),e.jsx(b,{as:"p",variant:"meta",weight:"medium",tone:"secondary",children:"Track note activity and reminders across the month"})]}),e.jsx("div",{className:"flex lg:justify-end",children:e.jsxs("div",{className:"surface-base inline-flex flex-wrap items-center gap-3 rounded-[16px] px-3.5 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(me,{className:"h-4 w-4 shrink-0 text-fg-tertiary"}),e.jsx(b,{id:"calendar-note-date-label",as:"span",variant:"label",weight:"medium",tone:"tertiary",children:"Note date"}),e.jsxs(se,{value:s,"aria-labelledby":"calendar-note-date-label",onValueChange:g=>m(g),variant:"ghost",size:"sm",children:[e.jsx(q,{value:"create",children:"Created"}),e.jsx(q,{value:"update",children:"Updated"})]})]}),e.jsx("div",{className:"h-5 w-px bg-divider"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(O,{variant:"ghost",size:"sm",onClick:l,children:"Today"}),e.jsx(O,{variant:"ghost",size:"icon-sm","aria-label":"Previous month",onClick:i,children:e.jsx(ae,{width:18,height:18})}),e.jsx(O,{variant:"ghost",size:"icon-sm","aria-label":"Next month",onClick:o,children:e.jsx(re,{width:18,height:18})})]})]})})]}),Ne=`
2
- query NotesInDateRange($dateRange: DateRangeInput) {
3
- notesInDateRange(dateRange: $dateRange) {
4
- id
5
- title
6
- createdAt
7
- updatedAt
8
- }
9
- }
10
- `,ve=`
11
- query RemindersInDateRange($dateRange: DateRangeInput) {
12
- remindersInDateRange(dateRange: $dateRange) {
13
- id
14
- noteId
15
- reminderDate
16
- completed
17
- priority
18
- content
19
- note {
20
- id
21
- title
22
- }
23
- }
24
- }
25
- `,Me=async a=>{const t=await K(Ne,{dateRange:a});if(t.type==="error")throw t;return t.notesInDateRange},De=async a=>{const t=await K(ve,{dateRange:a});if(t.type==="error")throw t;return t.remindersInDateRange},Ce=({year:a,month:t})=>{const s=`${a}-${String(t).padStart(2,"0")}-01`,i=t===12?1:t+1,l=`${t===12?a+1:a}-${String(i).padStart(2,"0")}-01`,m={start:s,end:l},h=z({queryKey:F.calendar.notesInDateRange(a,t),queryFn:()=>Me(m)}),g=z({queryKey:F.reminders.inDateRange(a,t),queryFn:()=>De(m)});return{notes:h.data??[],reminders:g.data??[],isLoading:h.isLoading||g.isLoading,isError:h.isError||g.isError}},Re=["SUN","MON","TUE","WED","THU","FRI","SAT"],we=[],Se=[],B=ie(de);function _e(){const a=B.useNavigate(),{year:t,month:s,type:i}=B.useSearch(),o=d.useRef(null),l=d.useRef(!1),m=d.useRef(0),h=d.useRef(0),g=d.useCallback(r=>{l.current=!0,m.current=r.pageX-(o.current?.offsetLeft??0),h.current=o.current?.scrollLeft??0,o.current&&(o.current.style.cursor="grabbing",o.current.style.userSelect="none")},[]),N=d.useCallback(r=>{if(!l.current||!o.current)return;r.preventDefault();const u=(r.pageX-o.current.offsetLeft-m.current)*1.2;o.current.scrollLeft=h.current-u},[]),M=d.useCallback(()=>{l.current=!1,o.current&&(o.current.style.cursor="grab",o.current.style.userSelect="")},[]),{notes:v,reminders:p,isLoading:D,isError:S}=Ce({year:t,month:s}),$=d.useMemo(()=>{const r=f(),c=`${r.year()}-${r.month()+1}-${r.date()}`,u=new Map;for(const n of v){const y=i==="create"?f(Number(n.createdAt)):f(Number(n.updatedAt)),x=`${y.year()}-${y.month()+1}-${y.date()}`,j=u.get(x)||[];j.push(n),u.set(x,j)}const T=new Map;for(const n of p){const y=f(Number(n.reminderDate)),x=`${y.year()}-${y.month()+1}-${y.date()}`,j=T.get(x)||[];j.push(n),T.set(x,j)}const W=new Date(t,s-1,1),X=new Date(t,s,0),L=W.getDay(),_=X.getDate(),R=[],U=s===1?12:s-1,Y=s===1?t-1:t,J=new Date(Y,U,0).getDate();for(let n=L-1;n>=0;n--)R.push({day:J-n,isCurrentMonth:!1,year:Y,month:U});for(let n=1;n<=_;n++)R.push({day:n,isCurrentMonth:!0,year:t,month:s});const P=(L+_)%7,G=P===0?0:7-P,Z=s===12?1:s+1,ee=s===12?t+1:t;for(let n=1;n<=G;n++)R.push({day:n,isCurrentMonth:!1,year:ee,month:Z});return R.map((n,y)=>{const x=`${n.year}-${n.month}-${n.day}`,j=f(`${n.year}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`);return{key:x,year:n.year,month:n.month,day:n.day,isCurrentMonth:n.isCurrentMonth,isSunday:y%7===0,isToday:x===c,isPast:j.isBefore(r,"day"),notes:u.get(x)||we,reminders:T.get(x)||Se}})},[t,s,v,p,i]),k=()=>{const r=s===1?12:s-1,c=s===1?t-1:t;a({search:u=>({...u,month:r,year:c})})},C=()=>{const r=s===12?1:s+1,c=s===12?t+1:t;a({search:u=>({...u,month:r,year:c})})},E=()=>{a({search:r=>({...r,month:f().month()+1,year:f().year()})})},I=r=>{r&&a({search:c=>({...c,type:r})})};return e.jsx(ne,{title:"Calendar",variant:"none",children:S?e.jsx(he,{children:"Failed to load calendar data. Please try again later."}):e.jsxs("div",{className:"surface-base",children:[e.jsx("div",{className:"border-b border-border-subtle/80 px-4 py-4 sm:px-5",children:e.jsx(je,{month:s,year:t,type:i,onPrevMonth:k,onNextMonth:C,onToday:E,onTypeChange:I})}),e.jsx("div",{ref:o,className:"cursor-grab overflow-x-auto px-4 pb-4 pt-3 sm:px-5",onMouseDown:g,onMouseMove:N,onMouseUp:M,onMouseLeave:M,children:e.jsxs("div",{className:"min-w-[1260px]",children:[e.jsx("div",{className:"mb-2.5 grid grid-cols-7 gap-1.5",children:Re.map((r,c)=>e.jsx(b,{as:"div",variant:"label",weight:"semibold",tracking:"wider",transform:"uppercase",className:`py-2 text-center ${c===0?"text-fg-weekend":"text-fg-tertiary"}`,children:r},r))}),D?e.jsx("div",{className:"grid grid-cols-7 gap-1.5",children:Array.from({length:35}).map((r,c)=>e.jsx(oe,{height:180},c))}):e.jsx("div",{className:"grid grid-cols-7 gap-1.5",children:$.map(r=>e.jsx(fe,{year:r.year,month:r.month,day:r.day,isCurrentMonth:r.isCurrentMonth,isSunday:r.isSunday,isToday:r.isToday,isPast:r.isPast,notes:r.notes,reminders:r.reminders,type:i},r.key))})]})})]})})}export{_e as default};
@@ -1,25 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-B14ZAmWA.js","assets/preload-helper-BXl3LOEh.js","assets/floating-ui.react-dom-BWTnA00G.js","assets/transform-BUB79_za.js","assets/katex-DywYRkvg.css"])))=>i.map(i=>d[i]);
2
- import{r as o,j as a}from"./floating-ui.react-dom-BWTnA00G.js";import{af as Sn,z as Ye,T as j,h as yt,l as An,q as H,M,B as k,H as Z,G as wt,F as Ct,R as En,d as Ae,u as qe,ag as Rn,ah as kn,ai as Tn,L as He,I as Mn,c as Dn,a as Pn,b as Be,U as _n,s as Ln,aj as On,V as Nt,ab as jt,ak as ze,al as Hn,W as Bn,ac as Fn,ad as $n,am as In,Q as Ge,P as Qe,an as Je,f as Un,k as ie,C as Vn}from"./note.api-BQovzEzd.js";import{M as xe,k as zn,r as Zn,f as St,m as Wn,a as Fe,b as Kn,d as G,s as Yn,l as At,o as qn,p as Et,q as Rt,v as Gn,w as rt,e as Qn}from"./time-CfAYZipR.js";import{m as Jn,c as Xn,C as at}from"./Callout-CviyPHKO.js";import{J as kt,A as Tt,a as er,N as tr,p as nr}from"./NotePropertiesPanel-DXYgE8h2.js";import{N as Ee,T as rr,S as ar}from"./url-9nrbQs7Z.js";import{S as sr}from"./SurfaceCard-GMt5xM7v.js";import{u as or,R as ir}from"./useReminderMutate--omDLmBV.js";import{n as cr}from"./Plus.es-CRRp2u5J.js";import{h as Xe,m as lr,L as Mt,Z as Dt,M as dr,K as ur,a as fr}from"./note-ui-CxK8ymUc.js";import{u as pr}from"./image.api-QmHYjp3z.js";import{L as mr,t as st,q as hr,B as he,G as gr,y as ot}from"./note-core-DUTqUh5N.js";import{_ as Ze}from"./preload-helper-BXl3LOEh.js";import{s as xr}from"./Copy.es-BPreRnP9.js";import{m as br}from"./PencilLine.es-B9V6u64t.js";import{f as vr,c as yr}from"./tag.api-DUfjr8bg.js";import{cn as it}from"./note-runtime-zN5ddTba.js";function wr(e,n){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const t=!!(e.condition??!0),s=e.blockerFn;return{shouldBlockFn:async()=>t&&s!==void 0?await s():t,enableBeforeUnload:t,withResolver:s===void 0}}function Cr(e,n){const{shouldBlockFn:t,enableBeforeUnload:s=!0,disabled:r=!1,withResolver:i=!1}=wr(e),l=Sn(),{history:c}=l,[f,u]=o.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return o.useEffect(()=>{const p=async g=>{function x(E){const w=l.parseLocation(E),m=l.getMatchedRoutes(w.pathname);return m.foundRoute===void 0?{routeId:"__notFound__",fullPath:w.pathname,pathname:w.pathname,params:m.routeParams,search:l.options.parseSearch(E.search)}:{routeId:m.foundRoute.id,fullPath:m.foundRoute.fullPath,pathname:w.pathname,params:m.routeParams,search:l.options.parseSearch(E.search)}}const d=x(g.currentLocation),h=x(g.nextLocation);if(d.routeId==="__notFound__"&&h.routeId!=="__notFound__")return!1;const y=await t({action:g.action,current:d,next:h});if(!i)return y;if(!y)return!1;const S=await new Promise(E=>{u({status:"blocked",current:d,next:h,action:g.action,proceed:()=>E(!1),reset:()=>E(!0)})});return u({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),S};return r?void 0:c.block({blockerFn:p,enableBeforeUnload:s})},[t,s,r,i,c,l]),f}const Nr=new Map([["bold",o.createElement(o.Fragment,null,o.createElement("path",{d:"M216.49,79.52l-56-56A12,12,0,0,0,152,20H56A20,20,0,0,0,36,40V216a20,20,0,0,0,20,20H200a20,20,0,0,0,20-20V88A12,12,0,0,0,216.49,79.52ZM160,57l23,23H160ZM60,212V44h76V92a12,12,0,0,0,12,12h48V212Z"}))],["duotone",o.createElement(o.Fragment,null,o.createElement("path",{d:"M208,88H152V32Z",opacity:"0.2"}),o.createElement("path",{d:"M213.66,82.34l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40V216a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V88A8,8,0,0,0,213.66,82.34ZM160,51.31,188.69,80H160ZM200,216H56V40h88V88a8,8,0,0,0,8,8h48V216Z"}))],["fill",o.createElement(o.Fragment,null,o.createElement("path",{d:"M213.66,82.34l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40V216a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V88A8,8,0,0,0,213.66,82.34ZM152,88V44l44,44Z"}))],["light",o.createElement(o.Fragment,null,o.createElement("path",{d:"M212.24,83.76l-56-56A6,6,0,0,0,152,26H56A14,14,0,0,0,42,40V216a14,14,0,0,0,14,14H200a14,14,0,0,0,14-14V88A6,6,0,0,0,212.24,83.76ZM158,46.48,193.52,82H158ZM200,218H56a2,2,0,0,1-2-2V40a2,2,0,0,1,2-2h90V88a6,6,0,0,0,6,6h50V216A2,2,0,0,1,200,218Z"}))],["regular",o.createElement(o.Fragment,null,o.createElement("path",{d:"M213.66,82.34l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40V216a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V88A8,8,0,0,0,213.66,82.34ZM160,51.31,188.69,80H160ZM200,216H56V40h88V88a8,8,0,0,0,8,8h48V216Z"}))],["thin",o.createElement(o.Fragment,null,o.createElement("path",{d:"M210.83,85.17l-56-56A4,4,0,0,0,152,28H56A12,12,0,0,0,44,40V216a12,12,0,0,0,12,12H200a12,12,0,0,0,12-12V88A4,4,0,0,0,210.83,85.17ZM156,41.65,198.34,84H156ZM200,220H56a4,4,0,0,1-4-4V40a4,4,0,0,1,4-4h92V88a4,4,0,0,0,4,4h52V216A4,4,0,0,1,200,220Z"}))]]),jr=new Map([["bold",o.createElement(o.Fragment,null,o.createElement("path",{d:"M248.49,71.51l-32-32a12,12,0,0,0-17,17L211,68h-3c-52,0-64.8,30.71-75.08,55.38-8.82,21.17-15.45,37.05-42.75,40.09a44,44,0,1,0,.28,24.08c43.34-3.87,55.07-32,64.63-54.93C164.9,109,172,92,208,92h3l-11.52,11.51a12,12,0,0,0,17,17l32-32A12,12,0,0,0,248.49,71.51ZM48,196a20,20,0,1,1,20-20A20,20,0,0,1,48,196Z"}))],["duotone",o.createElement(o.Fragment,null,o.createElement("path",{d:"M80,176a32,32,0,1,1-32-32A32,32,0,0,1,80,176Z",opacity:"0.2"}),o.createElement("path",{d:"M245.66,74.34l-32-32a8,8,0,0,0-11.32,11.32L220.69,72H208c-49.33,0-61.05,28.12-71.38,52.92-9.38,22.51-16.92,40.59-49.48,42.84a40,40,0,1,0,.1,16c43.26-2.65,54.34-29.15,64.14-52.69C161.41,107,169.33,88,208,88h12.69l-18.35,18.34a8,8,0,0,0,11.32,11.32l32-32A8,8,0,0,0,245.66,74.34ZM48,200a24,24,0,1,1,24-24A24,24,0,0,1,48,200Z"}))],["fill",o.createElement(o.Fragment,null,o.createElement("path",{d:"M245.66,85.66l-32,32a8,8,0,0,1-11.32-11.32L220.69,88H208c-38.67,0-46.59,19-56.62,43.08C141.05,155.88,129.33,184,80,184H79a32,32,0,1,1,0-16h1c38.67,0,46.59-19,56.62-43.08C147,100.12,158.67,72,208,72h12.69L202.34,53.66a8,8,0,0,1,11.32-11.32l32,32A8,8,0,0,1,245.66,85.66Z"}))],["light",o.createElement(o.Fragment,null,o.createElement("path",{d:"M244.24,75.76l-32-32a6,6,0,0,0-8.48,8.48L225.51,74H208c-48,0-59.44,27.46-69.54,51.69-9.43,22.64-17.66,42.33-53,44.16a38,38,0,1,0,.06,12c43.34-2.06,54.29-28.29,64-51.55C159.44,106.53,168,86,208,86h17.51l-21.75,21.76a6,6,0,1,0,8.48,8.48l32-32A6,6,0,0,0,244.24,75.76ZM48,202a26,26,0,1,1,26-26A26,26,0,0,1,48,202Z"}))],["regular",o.createElement(o.Fragment,null,o.createElement("path",{d:"M245.66,74.34l-32-32a8,8,0,0,0-11.32,11.32L220.69,72H208c-49.33,0-61.05,28.12-71.38,52.92-9.38,22.51-16.92,40.59-49.48,42.84a40,40,0,1,0,.1,16c43.26-2.65,54.34-29.15,64.14-52.69C161.41,107,169.33,88,208,88h12.69l-18.35,18.34a8,8,0,0,0,11.32,11.32l32-32A8,8,0,0,0,245.66,74.34ZM48,200a24,24,0,1,1,24-24A24,24,0,0,1,48,200Z"}))],["thin",o.createElement(o.Fragment,null,o.createElement("path",{d:"M242.83,77.17l-32-32a4,4,0,0,0-5.66,5.66L230.34,76H208c-46.67,0-57.84,26.81-67.69,50.46-9.46,22.69-18.4,44.16-56.55,45.48a36,36,0,1,0,0,8c43.49-1.42,54.33-27.39,63.91-50.39C157.45,106.12,166.67,84,208,84h22.34l-25.17,25.17a4,4,0,0,0,5.66,5.66l32-32A4,4,0,0,0,242.83,77.17ZM48,204a28,28,0,1,1,28-28A28,28,0,0,1,48,204Z"}))]]),Sr=new Map([["bold",o.createElement(o.Fragment,null,o.createElement("path",{d:"M212,40a12,12,0,0,1-12,12H170.71A20,20,0,0,0,151,68.42L142.38,116H184a12,12,0,0,1,0,24H138l-9.44,51.87A44,44,0,0,1,85.29,228H56a12,12,0,0,1,0-24H85.29A20,20,0,0,0,105,187.58L113.62,140H72a12,12,0,0,1,0-24h46l9.44-51.87A44,44,0,0,1,170.71,28H200A12,12,0,0,1,212,40Z"}))],["duotone",o.createElement(o.Fragment,null,o.createElement("path",{d:"M200,40V200a16,16,0,0,1-16,16H56V56A16,16,0,0,1,72,40Z",opacity:"0.2"}),o.createElement("path",{d:"M208,40a8,8,0,0,1-8,8H170.71a24,24,0,0,0-23.62,19.71L137.59,120H184a8,8,0,0,1,0,16H134.68l-10,55.16A40,40,0,0,1,85.29,224H56a8,8,0,0,1,0-16H85.29a24,24,0,0,0,23.62-19.71l9.5-52.29H72a8,8,0,0,1,0-16h49.32l10-55.16A40,40,0,0,1,170.71,32H200A8,8,0,0,1,208,40Z"}))],["fill",o.createElement(o.Fragment,null,o.createElement("path",{d:"M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32ZM176,72H159.92a16,16,0,0,0-15.73,13l-6.55,35H168a8,8,0,0,1,0,16H134.64l-7.11,37.9A32,32,0,0,1,96.08,200H80a8,8,0,0,1,0-16H96.08A16,16,0,0,0,111.81,171L118.36,136H88a8,8,0,0,1,0-16h33.36l7.11-37.9A32,32,0,0,1,159.92,56H176a8,8,0,0,1,0,16Z"}))],["light",o.createElement(o.Fragment,null,o.createElement("path",{d:"M206,40a6,6,0,0,1-6,6H170.71a26,26,0,0,0-25.58,21.35L135.19,122H184a6,6,0,0,1,0,12H133l-10.33,56.8A38,38,0,0,1,85.29,222H56a6,6,0,0,1,0-12H85.29a26,26,0,0,0,25.58-21.35L120.81,134H72a6,6,0,0,1,0-12h51l10.33-56.8A38,38,0,0,1,170.71,34H200A6,6,0,0,1,206,40Z"}))],["regular",o.createElement(o.Fragment,null,o.createElement("path",{d:"M208,40a8,8,0,0,1-8,8H170.71a24,24,0,0,0-23.62,19.71L137.59,120H184a8,8,0,0,1,0,16H134.68l-10,55.16A40,40,0,0,1,85.29,224H56a8,8,0,0,1,0-16H85.29a24,24,0,0,0,23.62-19.71l9.5-52.29H72a8,8,0,0,1,0-16h49.32l10-55.16A40,40,0,0,1,170.71,32H200A8,8,0,0,1,208,40Z"}))],["thin",o.createElement(o.Fragment,null,o.createElement("path",{d:"M204,40a4,4,0,0,1-4,4H170.71a28,28,0,0,0-27.55,23l-10.37,57H184a4,4,0,0,1,0,8H131.34l-10.63,58.44A36,36,0,0,1,85.29,220H56a4,4,0,0,1,0-8H85.29a28,28,0,0,0,27.55-23l10.37-57H72a4,4,0,0,1,0-8h52.66l10.63-58.44A36,36,0,0,1,170.71,36H200A4,4,0,0,1,204,40Z"}))]]),Pt=o.forwardRef((e,n)=>o.createElement(Ye,{ref:n,...e,weights:Nr}));Pt.displayName="FileIcon";const Ar=Pt,_t=o.forwardRef((e,n)=>o.createElement(Ye,{ref:n,...e,weights:jr}));_t.displayName="FlowArrowIcon";const Lt=_t,Ot=o.forwardRef((e,n)=>o.createElement(Ye,{ref:n,...e,weights:Sr}));Ot.displayName="FunctionIcon";const Ht=Ot;function Er({title:e,description:n,selected:t=!1,onClick:s,children:r}){return a.jsxs("button",{type:"button","aria-pressed":t,className:`focus-ring-soft flex w-full items-start justify-between gap-3 p-3 text-left transition-colors sm:p-4 ${t?"surface-floating bg-elevated":"rounded-[14px] border border-border-subtle bg-transparent hover:border-border-secondary hover:bg-hover-subtle"}`,onClick:s,children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx(j,{as:"div",variant:"body",weight:"semibold",tone:t?"default":"secondary",children:e}),a.jsx(j,{as:"div",variant:"meta",weight:"medium",tone:t?"secondary":"tertiary",className:"mt-1",children:n})]}),r?a.jsx("div",{className:"shrink-0",children:r}):null]})}const Rr=e=>{const{data:n}=yt({queryKey:H.notes.backReferences(e.noteId),async queryFn(){const t=await An(e.noteId);if(t.type==="error")throw t;return t.backReferences}});return e.render(n)},kr=[{value:"narrow",label:"Narrow",description:"Optimized for reading long-form content"},{value:"wide",label:"Wide",description:"Balanced width suitable for most content"},{value:"full",label:"Full Width",description:"Maximize screen space utilization"}];function Tr({isOpen:e,onClose:n,onSave:t,currentLayout:s="wide"}){const[r,i]=o.useState(s);o.useEffect(()=>{e&&i(s)},[e,s]);const l=()=>{t(r),n()};return a.jsxs(M,{isOpen:e,onClose:n,variant:"compact",children:[a.jsx(M.Header,{title:"Layout Settings",onClose:n}),a.jsx(M.Body,{children:a.jsx("div",{className:"flex flex-col gap-3 sm:gap-4",children:a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(j,{as:"div",variant:"body",weight:"semibold",tone:"secondary",children:"Note layout"}),a.jsx("div",{className:"flex flex-col gap-2",children:kr.map(c=>a.jsx(Er,{title:c.label,description:c.description,selected:r===c.value,onClick:()=>i(c.value)},c.value))})]})})}),a.jsx(M.Footer,{children:a.jsxs(xe,{children:[a.jsx(k,{variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),a.jsx(k,{variant:"primary",size:"sm",onClick:l,children:"Apply"})]})})]})}const ge=e=>{const n=/^\d+$/.test(e)?Number(e):Date.parse(e);return Number.isFinite(n)?n:null},je=(e,n)=>{const t=ge(e),s=ge(n);return t===null||s===null?e===n?0:null:t===s?0:t<s?-1:1},Mr=2200;function Dr({status:e,savedAt:n,savedVersion:t,confirmationRevision:s}){const[r,i]=o.useState(()=>Date.now()),[l,c]=o.useState(!1);o.useEffect(()=>{if(e!=="saved")return;const d=window.setTimeout(()=>i(Date.now()),zn(ge(t),r));return()=>window.clearTimeout(d)},[r,t,e]),o.useEffect(()=>{if(s===0)return;c(!0);const d=window.setTimeout(()=>c(!1),Mr);return()=>window.clearTimeout(d)},[s]);const f=e==="saved"&&l,u=e==="pending"?"Saving...":e==="saving"?"Saving now...":e==="error"?"Save failed. Try again.":e==="conflict"?"Save paused: changed elsewhere":`Saved ${Zn(ge(t),r)}`,p=Z("inline-flex items-center gap-2 transition-colors",e==="saved"&&!f&&"text-fg-secondary",f&&"text-accent-success",(e==="pending"||e==="saving")&&"text-fg-default",(e==="error"||e==="conflict")&&"text-fg-error"),g=Z("save-progress-ring flex h-4 w-4 shrink-0 items-center justify-center rounded-full",(e==="pending"||e==="saving")&&"save-progress-ring-active",e==="saved"&&f&&"save-progress-ring-complete",(e==="error"||e==="conflict")&&"save-progress-ring-error"),x=e==="error"||e==="conflict"?a.jsx(Jn,{className:"h-3.5 w-3.5",weight:"fill"}):a.jsx("span",{className:g,"aria-hidden":!0,children:a.jsx("span",{className:"h-2 w-2 rounded-full bg-elevated"})});return a.jsxs(j,{as:"span",variant:"label",weight:"medium",className:p,role:"status","aria-live":"polite",title:n,children:[x,u]})}function Pr({title:e,titleRef:n,isPinned:t,createdAt:s,saveStatus:r,savedAt:i,savedVersion:l,saveConfirmationRevision:c,onTitleChange:f,onCopyMarkdown:u,onDownloadDocument:p,onTogglePinned:g,onChangeLayout:x,onCloneNote:d,onRestoreVersion:h,onDelete:y,onSave:N}){return a.jsx("div",{className:"surface-floating sticky top-20 z-[1001] mb-7 px-5 pt-4 pb-3.5",children:a.jsxs("div",{className:"flex flex-col gap-3.5",children:[a.jsxs("div",{className:"flex items-start justify-between gap-5",children:[a.jsxs("div",{className:"min-w-0 flex-1 pt-0.5",children:[a.jsx(j,{as:"div",variant:"micro",weight:"semibold",tracking:"widest",transform:"uppercase",tone:"tertiary",className:"mb-1.5",children:"Thought in progress"}),a.jsx("input",{ref:n,"aria-label":"Note title",placeholder:"Title",className:"text-heading sm:text-display w-full bg-transparent font-semibold leading-[1.25] tracking-[-0.02em] outline-none",type:"text",value:e,onChange:S=>f(S.target.value)})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a.jsx(wt,{button:a.jsx(St,{label:"Note actions",size:"lg"}),items:[{name:"Copy Markdown",onClick:u},{name:"Download document",onClick:p},{type:"separator",key:"export-separator"},{name:t?"Unpin":"Pin",onClick:g},{name:"Change layout",onClick:x},{type:"separator"},{name:"Clone this note",onClick:d},{name:"Restore previous version",onClick:h},{type:"separator"},{name:"Delete",onClick:y}]}),a.jsx(k,{size:"sm",variant:"subtle",isLoading:r==="saving",disabled:r==="conflict",onClick:N,children:"Save"})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-x-2.5 gap-y-1.5 border-t border-border-subtle/80 pt-3",children:[t&&a.jsxs(j,{as:"span",variant:"label",weight:"medium",tone:"secondary",className:"inline-flex items-center gap-1.5",children:[a.jsx(Wn,{className:"h-3 w-3",weight:"fill"}),"Pinned"]}),t&&a.jsx("span",{className:"h-1 w-1 rounded-full bg-border-secondary"}),a.jsx(Dr,{status:r,savedAt:i,savedVersion:l,confirmationRevision:c}),a.jsx("span",{className:"h-1 w-1 rounded-full bg-border-secondary"}),a.jsxs(j,{as:"span",variant:"micro",weight:"medium",tone:"tertiary",children:["Created ",s]})]})]})})}const _r=/[:{}[\],&*#?|<>=!%@`-]/,Lr="/assets/images/",Or=e=>e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[\\/:*?"<>|]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"untitled-note",Ne=e=>e?_r.test(e)||/^\s|\s$/.test(e)?JSON.stringify(e):e:'""',Se=e=>{if(!e)return;const n=Number(e);return Number.isFinite(n)?new Date(n).toISOString():e},et=()=>typeof window>"u"||!window.location?.origin?"http://localhost":window.location.origin,Re=(e,n=et())=>{try{const t=new URL(e,n);return t.origin===n&&t.pathname.startsWith(Lr)}catch{return!1}},Bt=(e,n=et())=>{const t=new URL(e,n);return`${t.pathname}${t.search}`},Ft=e=>e.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()??"",Hr=e=>e.trim().replace(/[\\/:*?"<>|]/g,"-").split("").map(s=>s.charCodeAt(0)<32?"-":s).join("").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"image",Br=e=>{const n=e.lastIndexOf(".");return n<=0||n===e.length-1?{baseName:e,extension:""}:{baseName:e.slice(0,n),extension:e.slice(n)}},$t=(e,n,t)=>{const r=new URL(e,et()).pathname.split("/").filter(Boolean),i=decodeURIComponent(r[r.length-1]??""),l=`image-${n+1}`,{baseName:c,extension:f}=Br(Hr(i||l));let u=`${c}${f}`,p=2;for(;t.has(u);)u=`${c}-${p}${f}`,p+=1;return t.add(u),`assets/${u}`},Fr=(e,n)=>{let t=null;for(let s=n;s<e.length;s+=1){const r=e[s];if(t){r===t&&(t=null);continue}if(r==='"'||r==="'"){t=r;continue}if(r===">")return s}return-1},$r=(e,n)=>{let t=n;for(;t<e.length;){const s=e.toLowerCase().indexOf("<img",t);if(s===-1)return-1;const r=e[s+4],i=s===0?-1:e.lastIndexOf("<",s-1),l=s===0?-1:e.lastIndexOf(">",s-1);if(i<=l&&(!r||/[\s/>]/.test(r)))return s;t=s+4}return-1},Ir=(e,n,t,s)=>{let r=n;for(;r<t;){for(;r<t&&/[\s/]/.test(e[r]);)r+=1;const i=r;for(;r<t&&/[^\s=/>]/.test(e[r]);)r+=1;const l=e.slice(i,r).toLowerCase();for(;r<t&&/\s/.test(e[r]);)r+=1;if(e[r]!=="=")continue;for(r+=1;r<t&&/\s/.test(e[r]);)r+=1;const c=e[r];if(c==='"'||c==="'"){const u=r+1,p=e.indexOf(c,u);if(p===-1||p>t)return;if(r=p+1,l===s)return{end:p,start:u,value:e.slice(u,p)};continue}const f=r;for(;r<t&&/[^\s>]/.test(e[r]);)r+=1;if(l===s)return{end:r,start:f,value:e.slice(f,r)}}},It=e=>{const n=[];let t=0;for(;t<e.length;){const s=$r(e,t);if(s===-1)break;const r=Fr(e,s+4);if(r===-1)break;const i=Ir(e,s+4,r,"src");i&&n.push({end:r+1,source:i,start:s}),t=r+1}return n},Ut=(e,n)=>{let t=e;for(const s of[...n].sort((r,i)=>i.start-r.start))t=`${t.slice(0,s.start)}${s.value}${t.slice(s.end)}`;return t},Vt=(e,n)=>{let t=e;for(const s of[...n].sort((r,i)=>i.start-r.start))t=`${t.slice(0,s.start)}${s.value}${t.slice(s.end)}`;return t},zt=e=>{const n=[];let t=0;for(;t<e.length;){const s=e.indexOf("![",t);if(s===-1)break;let r=s+2,i=1;for(;r<e.length&&i>0&&e[r]!==`
3
- `;){if(e[r]==="\\"){r+=2;continue}e[r]==="["?i+=1:e[r]==="]"&&(i-=1),r+=1}if(i!==0||e[r]!=="("){t=s+2;continue}const l=r+1;let c=l;for(;c<e.length&&e[c]!==`
4
- `&&/\s/.test(e[c]);)c+=1;if(c>=e.length||e[c]===`
5
- `){t=s+2;continue}let f=c,u=c,p=c;if(e[c]==="<"){for(r=c+1;r<e.length&&e[r]!==">"&&e[r]!==`
6
- `;)r+=e[r]==="\\"?2:1;if(e[r]!==">"){t=s+2;continue}f=r+1,u=c+1,p=r}else{let g=0;for(r=c;r<e.length&&e[r]!==`
7
- `;){const x=e[r];if(x==="\\"){r+=2;continue}if(/\s/.test(x)&&g===0)break;if(x==="(")g+=1;else if(x===")"){if(g===0)break;g-=1}r+=1}f=r,u=c,p=f}if(p<=u){t=s+2;continue}for(r=f;r<e.length&&e[r]!==`
8
- `&&/\s/.test(e[r]);)r+=1;if(e[r]==='"'||e[r]==="'"){const g=e[r];for(r+=1;r<e.length&&e[r]!==`
9
- `;){if(e[r]==="\\"){r+=2;continue}if(e[r]===g){r+=1;break}r+=1}}for(;r<e.length&&e[r]!==`
10
- `&&/\s/.test(e[r]);)r+=1;if(e[r]!==")"){t=s+2;continue}n.push({end:r+1,source:{end:f,start:l,value:e.slice(u,p)},start:s}),t=r+1}return n},Ur=(e,n)=>`${Or(e)}.${n}`,Vr=({id:e,title:n,createdAt:t,updatedAt:s})=>{const r=["---",`title: ${Ne(n)}`,`note_id: ${Ne(e)}`],i=Se(t),l=Se(s);return i&&r.push(`created_at: ${Ne(i)}`),l&&r.push(`updated_at: ${Ne(l)}`),r.push("source: ocean-brain","---"),r.join(`
11
- `)},Zt=(e,n,t=!1)=>t?`${Vr(n)}
12
-
13
- ${e}`:e,Wt=(e,n,{includeMetadata:t=!1}={})=>{const s=Zt(e,n,t),r=zt(s).filter(i=>Re(i.source.value)).map(i=>({end:i.end,start:i.start,value:""}));return Vt(s,r)},Kt=(e,n,{includeMetadata:t=!1}={})=>`${t?`<!--
14
- source: ocean-brain
15
- note_id: ${n.id}
16
- title: ${n.title}
17
- created_at: ${Se(n.createdAt)??""}
18
- updated_at: ${Se(n.updatedAt)??""}
19
- -->
20
- `:""}${e}`,zr=(e,n,{includeMetadata:t=!1}={})=>{const s=Kt(e,n,{includeMetadata:t}),r=It(s).filter(i=>Re(i.source.value)).map(i=>({end:i.end,start:i.start,value:""}));return Ut(s,r)},Zr=async(e,n,{fetchImpl:t=fetch,includeMetadata:s=!1}={})=>{const r=new kt,i=Kt(e,n,{includeMetadata:s}),l=It(i),c=[],f=new Set,u=new Map;for(const{source:p}of l){if(!Re(p.value))continue;const g=Bt(p.value);let x=u.get(g);if(!x){x=$t(g,u.size,f),u.set(g,x);const d=await t(g,{credentials:"same-origin"});if(!d.ok)throw new Error(`Failed to fetch image asset: ${g}`);if(!Ft(d).startsWith("image/"))throw new Error(`Image asset did not return image content: ${g}`);r.file(x,new Uint8Array(await d.arrayBuffer()))}c.push({end:p.end,start:p.start,value:`./${x}`})}return r.file("note.html",Ut(i,c)),r.generateAsync({type:"blob"})},Wr=async(e,n,{fetchImpl:t=fetch,includeMetadata:s=!1}={})=>{const r=new kt,i=Zt(e,n,s),l=zt(i),c=[],f=new Set,u=new Map;for(const{source:p}of l){if(!Re(p.value))continue;const g=Bt(p.value);let x=u.get(g);if(!x){x=$t(g,u.size,f),u.set(g,x);const d=await t(g,{credentials:"same-origin"});if(!d.ok)throw new Error(`Failed to fetch image asset: ${g}`);if(!Ft(d).startsWith("image/"))throw new Error(`Image asset did not return image content: ${g}`);r.file(x,new Uint8Array(await d.arrayBuffer()))}c.push({end:p.end,start:p.start,value:`./${x}`})}return r.file("note.md",Vt(i,c)),r.generateAsync({type:"blob"})},Kr=(e,n)=>{const t=URL.createObjectURL(e),s=document.createElement("a");s.href=t,s.download=n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(t)},Yt={html:{extension:"html",getContent:e=>e.getHtml(),createDocumentBlob:(e,n)=>new Blob([zr(e,n.metadata,{includeMetadata:n.includeMetadata})],{type:"text/html;charset=utf-8"}),createZipBlob:(e,n)=>Zr(e,n.metadata,{fetchImpl:n.fetchImpl,includeMetadata:n.includeMetadata})},markdown:{extension:"md",getContent:e=>e.getMarkdown(),createDocumentBlob:(e,n)=>new Blob([Wt(e,n.metadata,{includeMetadata:n.includeMetadata})],{type:"text/markdown;charset=utf-8"}),createZipBlob:(e,n)=>Wr(e,n.metadata,{fetchImpl:n.fetchImpl,includeMetadata:n.includeMetadata})}},qt=(e,n)=>n?"zip":Yt[e].extension,Yr=async e=>{const n=Yt[e.format],t=n.getContent(e.source);if(t===void 0)return{type:"not-ready",format:e.format};const s=qt(e.format,e.includeAssets);return{type:"success",blob:e.includeAssets?await n.createZipBlob(t,e):n.createDocumentBlob(t,e),filename:Ur(e.metadata.title,s)}},qr=e=>e==="markdown"?"Markdown is not ready yet.":"HTML is not ready yet.",ct=({checked:e,description:n,id:t,label:s,onChange:r})=>{const i=`${t}-label`;return a.jsxs("div",{className:"flex min-h-6 items-center gap-2",children:[a.jsx(Ct,{id:t,size:"sm",checked:e,onChange:l=>r(l.target.checked),"aria-labelledby":i}),a.jsx("label",{id:i,htmlFor:t,className:"min-w-0 cursor-pointer",children:a.jsx(j,{as:"span",variant:"label",weight:"medium",tone:"secondary",className:"block",children:s})}),a.jsx(En,{content:a.jsx("span",{className:"block max-w-[240px] leading-4",children:n}),side:"top",children:a.jsx("button",{type:"button",className:"focus-ring-soft inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-fg-tertiary transition-colors hover:bg-hover-subtle hover:text-fg-secondary","aria-label":`${s} help`,children:a.jsx(Xn,{className:"h-3.5 w-3.5"})})})]})};function Gr({isOpen:e,metadata:n,getHtml:t,getMarkdown:s,onClose:r}){const i=Ae(),[l,c]=o.useState("html"),[f,u]=o.useState(!0),[p,g]=o.useState(!1),[x,d]=o.useState(!1),h=qt(l,f),y=async()=>{d(!0);try{const N=await Yr({format:l,includeAssets:f,includeMetadata:p,metadata:n,source:{getHtml:t,getMarkdown:s}});if(N.type==="not-ready"){i(qr(N.format));return}Kr(N.blob,N.filename),r(),i("Downloaded note.")}catch{i("Failed to download note.")}finally{d(!1)}};return a.jsxs(M,{isOpen:e,onClose:r,variant:"compact",children:[a.jsx(M.Header,{title:"Download document",onClose:r}),a.jsx(M.Body,{children:a.jsxs("div",{className:"flex flex-col gap-5",children:[a.jsxs("div",{className:"flex flex-col gap-3",role:"radiogroup","aria-label":"Format",children:[a.jsx(j,{as:"span",variant:"meta",weight:"bold",tone:"muted",children:"Format"}),a.jsxs("div",{className:"flex flex-wrap gap-4",children:[a.jsxs("label",{className:"flex cursor-pointer items-center gap-2",children:[a.jsx("input",{type:"radio",name:"note-export-format",value:"html",checked:l==="html",onChange:()=>c("html"),className:"h-4 w-4 accent-cta"}),a.jsx(j,{as:"span",variant:"label",weight:"medium",tone:"secondary",children:".html"})]}),a.jsxs("label",{className:"flex cursor-pointer items-center gap-2",children:[a.jsx("input",{type:"radio",name:"note-export-format",value:"markdown",checked:l==="markdown",onChange:()=>c("markdown"),className:"h-4 w-4 accent-cta"}),a.jsx(j,{as:"span",variant:"label",weight:"medium",tone:"secondary",children:".md"})]})]})]}),a.jsxs("div",{className:"flex flex-col gap-3",role:"group","aria-label":"Options",children:[a.jsx(j,{as:"span",variant:"meta",weight:"bold",tone:"muted",children:"Options"}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(ct,{id:"note-export-include-assets",label:"Include local image assets",checked:f,onChange:u,description:"Bundle uploaded Ocean Brain images with the document. Without assets, local images are omitted."}),a.jsx(ct,{id:"note-export-include-metadata",label:"Include metadata",checked:p,onChange:g,description:"Add the note title, note id, timestamps, and Ocean Brain source information."})]})]})]})}),a.jsx(M.Footer,{children:a.jsxs(xe,{children:[a.jsx(k,{variant:"ghost",size:"sm",onClick:r,children:"Cancel"}),a.jsx(k,{variant:"primary",size:"sm",onClick:y,disabled:x,children:x?"Downloading...":`Download .${h}`})]})})]})}const Gt=e=>e==="mcp"?{actor:"An MCP client",place:"through MCP",target:"the MCP update"}:e==="web"?{actor:"Another browser tab",place:"in another tab",target:"the tab update"}:{actor:"Another editor",place:"elsewhere",target:"the outside change"},Qr=({isDeleted:e,isConflict:n,source:t})=>{const s=Gt(t);return e?`This note was moved to trash ${s.place}`:n?`Save paused: note changed ${s.place}`:`This note changed ${s.place}`},Jr=({isDeleted:e,isConflict:n,hasDraft:t,source:s})=>{const r=Gt(s);return e?`${r.actor} moved this note to trash. Open trash to review or restore it.`:n&&t?`Your draft is saved locally. Reload the latest note, overwrite ${r.target}, or clone your draft into a new note.`:n?`The layout change is paused because the note changed ${r.place}. Reload the latest note or overwrite only the layout.`:`${r.actor} changed this note while it was open here. Reload the latest version before continuing.`};function Xr({isOpen:e,isDeleted:n,isConflict:t,hasDraft:s,source:r,isReloading:i,onReload:l,onOverwrite:c,onCloneDraft:f,onOpenTrash:u}){return a.jsxs(M,{isOpen:e,onClose:()=>{},variant:"inspect",children:[a.jsx(M.Header,{title:Qr({isDeleted:n,isConflict:t,source:r})}),a.jsx(M.Body,{children:a.jsx(j,{as:"p",variant:"body",tone:"secondary",className:"leading-6",children:Jr({isDeleted:n,isConflict:t,hasDraft:s,source:r})})}),a.jsx(M.Footer,{children:a.jsx(xe,{children:n?a.jsx(k,{type:"button",variant:"primary",size:"sm",onClick:u,children:"Open trash"}):t?a.jsxs(a.Fragment,{children:[a.jsx(k,{type:"button",variant:"subtle",size:"sm",isLoading:i,onClick:l,children:"Reload latest"}),s&&a.jsx(k,{type:"button",variant:"ghost",size:"sm",onClick:f,children:"Clone draft"}),a.jsx(k,{type:"button",variant:"danger",size:"sm",onClick:c,children:"Overwrite"})]}):a.jsx(k,{type:"button",variant:"primary",size:"sm",isLoading:i,onClick:l,children:"Reload latest"})})})]})}function ea({localDraftCreatedAt:e,hasSaveError:n,onRestoreDraft:t,onDiscardDraft:s,onRetrySave:r,onSaveAsNewNote:i}){return a.jsxs(a.Fragment,{children:[e&&a.jsx(at,{tone:"danger",className:"mb-6",children:a.jsxs("div",{className:"flex w-full flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[a.jsxs("span",{children:["A draft from ",e," is saved only in this browser."]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsx(k,{type:"button",size:"sm",variant:"subtle",className:"self-start",onClick:t,children:"Restore draft"}),a.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"self-start",onClick:s,children:"Discard"})]})]})}),n&&a.jsx(at,{tone:"danger",className:"mb-6",children:a.jsxs("div",{className:"flex w-full flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[a.jsx("span",{children:"Save failed. Your latest draft is still available here. Retry before leaving this note."}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsx(k,{type:"button",size:"sm",variant:"subtle",className:"self-start",onClick:r,children:"Retry save"}),a.jsx(k,{type:"button",size:"sm",variant:"ghost",className:"self-start",onClick:i,children:"Save as new note"})]})]})})]})}const lt=(e,n)=>e||(n==="mobile"?"Mobile browser":n==="mcp"?"MCP":"Web browser");function ta({isOpen:e,noteId:n,onClose:t,restoreSnapshot:s,onRestored:r}){const i=Ae(),l=qe(),[c,f]=o.useState(null),[u,p]=o.useState("diff"),g=o.useRef(null),x=Fe({queryKey:H.notes.snapshots(n),queryFn:async()=>{const m=await Rn(n);if(m.type==="error")throw m;return m.noteSnapshots},enabled:e}),d=Kn({mutationFn:s,onSuccess:async m=>{if(m){if(m.type==="error"){i(m.errors[0].message);return}await Promise.all([l.invalidateQueries({queryKey:H.notes.detail(n),exact:!0}),l.invalidateQueries({queryKey:H.notes.listAll(),exact:!1}),l.invalidateQueries({queryKey:H.notes.tagListAll(),exact:!1}),l.invalidateQueries({queryKey:H.notes.tagNameListAll(),exact:!1}),l.invalidateQueries({queryKey:H.notes.pinned(),exact:!0}),l.invalidateQueries({queryKey:H.notes.backReferencesAll(),exact:!1}),l.invalidateQueries({queryKey:H.notes.graph(),exact:!0}),l.invalidateQueries({queryKey:H.notes.snapshots(n),exact:!1}),l.invalidateQueries({queryKey:H.views.sectionNotesAll(),exact:!1}),l.invalidateQueries({queryKey:H.tags.all(),exact:!1})]),i("Previous version restored."),r?.(m.restoreNoteSnapshot),f(null),t()}}}),h=x.data?.find(m=>m.id===c)??null,y=Fe({queryKey:[...H.notes.snapshotDetail(c??"pending"),"diff"],queryFn:async()=>{if(!c)throw new Error("SNAPSHOT_NOT_SELECTED");const m=await kn(c,"current");if(m.type==="error")throw m;if(!m.noteSnapshotDiff)throw new Error("SNAPSHOT_DIFF_NOT_FOUND");return m.noteSnapshotDiff},enabled:!!c&&u==="diff"}),N=Fe({queryKey:H.notes.snapshotDetail(c??"pending"),queryFn:async()=>{if(!c)throw new Error("SNAPSHOT_NOT_SELECTED");const m=await Tn(c);if(m.type==="error")throw m;if(!m.noteSnapshot)throw new Error("SNAPSHOT_NOT_FOUND");return m.noteSnapshot},enabled:!!c&&u==="content"}),S=N.data?.contentAsMarkdown.trim()??"";o.useEffect(()=>{c&&g.current?.focus()},[c]);const E=(m,v)=>{p(v),f(m)},w=()=>{f(null),p("diff"),t()};return a.jsxs(M,{isOpen:e,onClose:w,variant:"inspect",children:[a.jsx(M.Header,{title:h?u==="diff"?"Snapshot Diff":"Snapshot Content":"Restore Previous Version",onClose:w}),a.jsx(M.Description,{className:"sr-only",children:h?u==="diff"?"Review the markdown diff between this snapshot and the current note.":"Read this snapshot content before restoring it.":"Choose a previous snapshot to restore."}),a.jsx(M.Body,{children:h?a.jsxs("div",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsx(j,{as:"p",variant:"body",weight:"semibold",truncate:!0,children:h.title}),a.jsxs(j,{as:"p",variant:"label",tone:"tertiary",children:["Before"," ",lt(h.meta.label,h.meta.entrypoint)," ","edit - ",G(h.createdAt).format("YYYY-MM-DD HH:mm:ss")]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.jsx(k,{variant:u==="diff"?"primary":"subtle",size:"sm",onClick:()=>p("diff"),children:"Show diff"}),a.jsx(k,{variant:u==="content"?"primary":"subtle",size:"sm",onClick:()=>p("content"),children:"View content"})]}),u==="diff"?y.isLoading?a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-4 py-3",children:"Loading snapshot diff..."}):y.isError?a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-4 py-3",children:"Snapshot diff could not be loaded."}):y.data?a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(j,{as:"p",variant:"meta",tone:"secondary",children:"Changes from this snapshot to the current note. Red lines were in the snapshot; green lines are in the current note."}),a.jsx("pre",{className:"max-h-[60vh] overflow-y-auto overflow-x-hidden whitespace-pre-wrap break-words rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-0 py-3 text-xs leading-5 text-fg-secondary",children:y.data.diff.markdown.split(`
21
- `).map((m,v)=>{const T=m.startsWith("+")&&!m.startsWith("+++")?"bg-emerald-500/12 text-emerald-700 dark:text-emerald-200":m.startsWith("-")&&!m.startsWith("---")?"bg-rose-500/12 text-rose-700 dark:text-rose-200":m.startsWith("@@")?"bg-sky-500/12 text-sky-700 dark:text-sky-200":"text-fg-secondary";return a.jsx("span",{className:`block min-w-full whitespace-pre-wrap break-words px-4 ${T}`,children:m||" "},`${v}-${m}`)})})]}):null:N.isLoading?a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-4 py-3",children:"Loading snapshot content..."}):N.isError?a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-4 py-3",children:"Snapshot content could not be loaded."}):S?a.jsx("pre",{className:"max-h-[60vh] overflow-auto whitespace-pre-wrap break-words rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-4 py-3 text-sm leading-6 text-fg-secondary",children:S}):a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-4 py-3",children:"No readable content was found for this snapshot."})]}):a.jsxs("div",{className:"flex flex-col gap-3",children:[a.jsx(j,{as:"p",variant:"meta",tone:"secondary",children:"Choose a previous snapshot to restore this note back to that state."}),x.isLoading&&a.jsx(j,{as:"div",variant:"meta",tone:"secondary",children:"Loading previous versions..."}),!x.isLoading&&x.data?.length===0&&a.jsx(j,{as:"div",variant:"meta",tone:"secondary",className:"rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-4 py-3",children:"A recovery snapshot appears before the first edit in a session. Up to 10 recent snapshots are kept for 7 days, and identical versions are skipped."}),!x.isLoading&&x.data&&x.data.length>0&&a.jsx("div",{className:"flex flex-col gap-2",children:x.data.map(m=>a.jsx(sr,{padding:"compact",children:a.jsxs("div",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs(j,{as:"p",variant:"body",weight:"semibold",children:["Before"," ",lt(m.meta.label,m.meta.entrypoint)," ","edit"]}),a.jsx(j,{as:"p",variant:"meta",truncate:!0,tone:"secondary",children:m.title}),a.jsx(j,{as:"p",variant:"label",tone:"tertiary",children:G(m.createdAt).format("YYYY-MM-DD HH:mm:ss")})]}),a.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2 sm:justify-end",children:[a.jsx(k,{variant:"subtle",size:"sm",onClick:()=>E(m.id,"diff"),children:"Compare"}),a.jsx(k,{size:"sm",isLoading:d.isPending,onClick:()=>d.mutate(m.id),children:"Restore"})]})]}),m.contentPreview&&a.jsx("div",{className:"rounded-[14px] border border-border-subtle bg-hover-subtle/50 px-3 py-2",children:a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"line-clamp-4 whitespace-pre-wrap break-words",children:m.contentPreview})})]})},m.id))})]})}),h&&a.jsx(M.Footer,{children:a.jsxs(xe,{children:[a.jsx(k,{ref:g,variant:"subtle",onClick:()=>{f(null),p("diff")},children:"Back"}),a.jsx(k,{isLoading:d.isPending,onClick:()=>d.mutate(h.id),children:"Restore this version"})]})})]})}const dt={low:{active:"border-border-secondary bg-elevated text-fg-default",inactive:"border-transparent bg-transparent text-fg-muted hover:bg-hover-subtle"},medium:{active:"border-border-secondary bg-elevated text-fg-default",inactive:"border-transparent bg-transparent text-fg-muted hover:bg-hover-subtle"},high:{active:"border-border-secondary bg-elevated text-fg-default",inactive:"border-transparent bg-transparent text-fg-muted hover:bg-hover-subtle"}};function na({isOpen:e,onClose:n,onSave:t,reminder:s,mode:r}){const[i,l]=o.useState(new Date),[c,f]=o.useState("medium"),[u,p]=o.useState("");o.useEffect(()=>{e&&r==="edit"&&s?(l(new Date(Number(s.reminderDate))),f(s.priority||"medium"),p(s.content||"")):e&&r==="create"&&(l(new Date),f("medium"),p(""))},[e,r,s]);const g=()=>{t(i,c,u||void 0),n()},x=d=>c===d?dt[d].active:dt[d].inactive;return a.jsxs(M,{isOpen:e,onClose:n,variant:"form",children:[a.jsx(M.Header,{title:r==="create"?"Create Reminder":"Edit Reminder",onClose:n}),a.jsx(M.Body,{children:a.jsxs("div",{className:"flex flex-col gap-3 sm:gap-4",children:[a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(He,{children:"Date & Time"}),a.jsx(Mn,{type:"datetime-local",size:"sm",value:G(i).format("YYYY-MM-DDTHH:mm"),onChange:d=>l(new Date(d.target.value))})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(He,{children:"Content"}),a.jsx(Dn,{size:"sm",placeholder:"Enter reminder content (optional)",value:u,onChange:d=>p(d.target.value)})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(He,{children:"Priority"}),a.jsxs(Pn,{type:"single",variant:"quiet",value:c,onValueChange:d=>d&&f(d),className:"gap-1.5 border-none rounded-[14px] bg-muted/70 p-1 sm:gap-2",children:[a.jsx(Be,{value:"low",className:`flex-1 rounded-[10px] border ${x("low")}`,children:a.jsx(j,{as:"span",weight:"medium",className:"text-current",children:"Low"})}),a.jsx(Be,{value:"medium",className:`flex-1 rounded-[10px] border ${x("medium")}`,children:a.jsx(j,{as:"span",weight:"medium",className:"text-current",children:"Medium"})}),a.jsx(Be,{value:"high",className:`flex-1 rounded-[10px] border ${x("high")}`,children:a.jsx(j,{as:"span",weight:"medium",className:"text-current",children:"High"})})]})]})]})}),a.jsx(M.Footer,{children:a.jsxs(xe,{children:[a.jsx(k,{variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),a.jsx(k,{variant:"primary",size:"sm",onClick:g,children:r==="create"?"Create":"Save"})]})})]})}function ra({noteId:e}){const[n,t]=o.useState(!1),[s,r]=o.useState(!1),[i,l]=o.useState("create"),[c,f]=o.useState(void 0),{onCreate:u,onUpdate:p,onDelete:g}=or(),x=()=>{l("create"),f(void 0),r(!0)},d=w=>{l("edit"),f(w),r(!0)},h=(w,m,v)=>{i==="create"?u(e,w,m,()=>{r(!1)},v):i==="edit"&&c&&p(c.id,e,{reminderDate:w,priority:m,content:v},()=>{r(!1)})},y=w=>{p(w.id,e,{completed:!w.completed})},N=w=>{const m=G(Number(w)),v=G();return m.isSame(v,"day")?`Today at ${m.format("HH:mm")}`:m.isSame(v.add(1,"day"),"day")?`Tomorrow at ${m.format("HH:mm")}`:m.format("YYYY-MM-DD HH:mm")},S=w=>{const m=G(Number(w)),v=G(),T=m.diff(v,"hour");return T<=6?"high":T<=24?"medium":"low"},E=w=>{const m=G(Number(w)),v=G(),T=m.diff(v,"hour"),F=m.diff(v,"minute")%60;return T<0||F<0?"Overdue":T===0?`${F}m remaining`:`${T}h ${F}m remaining`};return a.jsxs(a.Fragment,{children:[a.jsx(Tt,{title:"Reminders",icon:a.jsx(Yn,{className:"h-3.5 w-3.5"}),action:a.jsxs(a.Fragment,{children:[!n&&a.jsxs(k,{size:"sm",variant:"ghost",onClick:x,children:[a.jsx(cr,{className:"w-3 h-3"}),a.jsx(j,{as:"span",variant:"label",className:"hidden sm:inline",children:"Add"})]}),a.jsxs(k,{type:"button",size:"sm",variant:"ghost","aria-label":n?"Expand reminders":"Collapse reminders","aria-expanded":!n,onClick:()=>t(!n),children:[n?a.jsx(_n,{className:"h-3.5 w-3.5"}):a.jsx(Ln,{className:"h-3.5 w-3.5"}),n?"Expand":"Collapse"]})]}),children:!n&&a.jsx(ir,{noteId:e,searchParams:{offset:0,limit:9999},render:({reminders:w,totalCount:m})=>a.jsx("div",{className:"flex flex-col gap-2",children:w.length===0?a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"py-3 text-center",children:m===0?"No reminders yet":"All reminders complete"}):a.jsx("div",{className:"flex flex-col",children:w.map(v=>{const T=v.priority||S(v.reminderDate),F=E(v.reminderDate),D=F==="Overdue";return a.jsxs("div",{className:Z("flex items-center gap-2.5 px-2 py-1.5"),children:[a.jsx(Ct,{checked:v.completed,onChange:()=>y(v),size:"sm","aria-label":`Reminder: ${v.content||N(v.reminderDate)}`}),a.jsx(j,{as:"div",variant:"body",weight:"medium",className:Z("truncate flex-1 min-w-0",v.completed&&"line-through opacity-40"),children:v.content||N(v.reminderDate)}),a.jsxs("div",{className:Z("shrink-0 flex items-center gap-1",v.completed&&"opacity-40"),children:[v.content&&a.jsx(j,{as:"span",variant:"meta",tone:"secondary",children:N(v.reminderDate)}),!v.completed&&a.jsx(j,{as:"span",variant:"label",weight:"medium",tone:D||T==="high"?"error":"tertiary",className:Z(v.content&&'before:content-["·"] before:mr-1'),children:F})]}),a.jsx(wt,{button:a.jsx(St,{label:"Reminder actions"}),items:[{name:"Edit",onClick:()=>d(v)},{name:"Delete",onClick:()=>g(v.id,e)}]})]},v.id)})})})})}),a.jsx(na,{isOpen:s,onClose:()=>r(!1),onSave:h,reminder:c,mode:i})]})}const aa=e=>[{title:"Diagram",subtext:"Create a flowchart or diagram with Mermaid syntax",onItemClick:()=>{st(e,{type:"codeBlock",props:{language:"mermaid"}})},aliases:["mermaid","diagram","flowchart","sequence"],group:"Other",icon:a.jsx(Lt,{})},{title:"Math Formula",subtext:"Write a formula with KaTeX or LaTeX",onItemClick:()=>{st(e,{type:"codeBlock",props:{language:"math"}})},aliases:["math","formula","equation","katex","latex"],group:"Other",icon:a.jsx(Ht,{})}],sa=({editor:e})=>a.jsx(Xe,{triggerCharacter:"/",getItems:async n=>mr([...lr(e).filter(t=>t.title!=="Audio"&&t.title!=="Video"&&t.title!=="File"),...aa(e),{title:"Table of Contents",subtext:"Insert a table of contents based on headings",onItemClick:()=>{e.insertBlocks([{type:"tableOfContents"}],e.getTextCursorPosition().block,"after")},aliases:["toc","table of contents","contents","outline","index"],group:"Other",icon:a.jsx(At,{})}],n)}),oa=(e,n)=>n?e.filter(t=>t.id!==n):e,ia=({currentNoteId:e,onClick:n})=>a.jsx(Xe,{triggerCharacter:"[",getItems:async t=>{const s=await On({query:t,limit:5});return s.type==="error"?[]:oa(s.allNotes.notes,e).map(i=>({title:i.title,onItemClick:()=>n({type:"reference",props:{id:i.id,title:i.title}})}))}}),Qt=["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/avif"],ca=new Set(Qt),ut="Unsupported image type. Use PNG, JPEG, GIF, WebP, BMP, or AVIF.",la="Failed to upload image.",da=e=>ca.has(e);let ft,pt;const ua=()=>(ft??=Ze(async()=>{const{default:e}=await import("./mermaid.core-B14ZAmWA.js").then(n=>n.bc);return{default:e}},__vite__mapDeps([0,1,2,3])).then(({default:e})=>e),ft),fa=()=>(pt??=Promise.all([Ze(()=>import("./katex-x288kqHd.js"),[]),Ze(()=>Promise.resolve({}),__vite__mapDeps([4]))]).then(([{default:e}])=>e),pt),pa=e=>{const n=e?.trim().toLowerCase();return n==="mermaid"?"mermaid":n==="math"||n==="katex"||n==="latex"?"math":null},ma=e=>`ocean-brain-mermaid-${e.replace(/[^a-zA-Z0-9_-]/g,"")||"diagram"}`,ha=async(e,n,t,s="light")=>{if(e==="mermaid"){const i=await ua();i.initialize({securityLevel:"strict",startOnLoad:!1,suppressErrorRendering:!0,theme:s==="dark"?"dark":"default"});const l=await i.render(ma(t),n);return{html:l.svg,bindFunctions:l.bindFunctions}}return{html:(await fa()).renderToString(n,{displayMode:!0,output:"htmlAndMathml",strict:"warn",throwOnError:!0,trust:!1})}},ga={floating:"pointer-events-auto inline-flex h-7 cursor-pointer select-none items-center gap-1.5 rounded-[8px] border border-white/10 bg-white/10 px-2.5 text-xs font-medium text-white/60 opacity-75 shadow-[0_8px_18px_-14px_rgba(0,0,0,0.45)] backdrop-blur-sm transition-colors hover:bg-white/20 hover:text-white/90 hover:opacity-100 focus-ring-soft focus:text-white/90 focus:opacity-100",toolbar:"focus-ring-soft inline-flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-[8px] border border-transparent px-2.5 text-xs font-semibold text-fg-secondary outline-none transition-colors hover:border-border-subtle hover:bg-hover-subtle hover:text-fg-default"},xa={idle:"",copied:"text-accent-success hover:text-accent-success focus:text-accent-success",failed:"text-fg-error hover:text-fg-error focus:text-fg-error"},ba={idle:"Copy",copied:"Copied",failed:"Copy failed"},mt=({getText:e,resetDelayMs:n=2e3,variant:t="floating"})=>{const[s,r]=o.useState("idle"),i=o.useRef(null),l=o.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null)},[]),c=o.useCallback(()=>{l(),i.current=setTimeout(()=>{r("idle"),i.current=null},n)},[l,n]);o.useEffect(()=>l,[l]);const f=g=>{g.stopPropagation()},u=g=>{g.preventDefault(),g.stopPropagation()},p=async g=>{f(g);try{await navigator.clipboard.writeText(e()),r("copied")}catch{r("failed")}c()};return a.jsx("div",{className:Z(t==="floating"&&"pointer-events-none absolute right-3 top-2 z-[1]"),contentEditable:!1,onMouseDown:u,children:a.jsxs("button",{type:"button",className:Z(ga[t],xa[s]),contentEditable:!1,onClick:p,children:[a.jsx(xr,{className:"h-3.5 w-3.5"}),a.jsx("span",{"aria-live":"polite",children:ba[s]})]})})},va=({kind:e,source:n})=>{const t=o.useId(),s=o.useRef(null),r=Nt(u=>u.theme),[i,l]=o.useState(()=>typeof IntersectionObserver>"u"),[c,f]=o.useState({status:"idle"});return o.useEffect(()=>{const u=s.current;if(i||!u||typeof IntersectionObserver>"u"){l(!0);return}const p=new IntersectionObserver(([g])=>{g?.isIntersecting&&(l(!0),p.disconnect())},{rootMargin:"240px"});return p.observe(u),()=>p.disconnect()},[i]),o.useEffect(()=>{if(!i)return;let u=!1;return f({status:"loading"}),ha(e,n,t,r).then(p=>{u||f({status:"success",...p})}).catch(()=>{u||f({status:"error"})}),()=>{u=!0}},[e,t,i,n,r]),o.useEffect(()=>{c.status==="success"&&c.bindFunctions&&s.current&&c.bindFunctions(s.current)},[c]),a.jsxs("div",{ref:s,"data-rich-code-preview":!0,className:"min-h-24 w-full overflow-auto bg-surface px-4 py-5 text-fg-default sm:px-6 sm:py-6",contentEditable:!1,"aria-label":e==="mermaid"?"Mermaid diagram preview":"Math formula preview",children:[c.status==="success"&&a.jsx("div",{className:"[&_.katex-display]:m-0 [&_svg]:mx-auto [&_svg]:block [&_svg]:h-auto [&_svg]:max-h-[min(68vh,640px)] [&_svg]:max-w-full",dangerouslySetInnerHTML:{__html:c.html}}),(c.status==="idle"||c.status==="loading")&&a.jsx("div",{className:"flex min-h-8 items-center justify-center text-sm text-black/55",children:"Rendering preview…"}),c.status==="error"&&a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"mb-3 text-sm text-red-700",children:"Preview could not be rendered. The source is preserved."}),a.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap rounded-[6px] bg-black/5 p-4 text-sm text-black",children:a.jsx("code",{children:n})})]})]})},ht="focus-ring-soft inline-flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-[8px] border px-2.5 text-xs font-semibold outline-none transition-colors",We=e=>typeof e=="string"?e:!e||typeof e!="object"?"":"text"in e&&typeof e.text=="string"?e.text:"content"in e?Array.isArray(e.content)?e.content.map(We).join(""):We(e.content):"",ya=({block:e,contentRef:n})=>{const t=o.useRef(null),s=pa(e.props.language),r=e.content.map(We).join(""),[i,l]=o.useState(r),[c,f]=o.useState(r.length===0),u=s!==null&&!c,p=s==="mermaid"?"Diagram":"Math Formula",g=`${p} controls`,x=o.useCallback(h=>{t.current=h,n(h)},[n]);o.useEffect(()=>{const h=t.current;if(!h)return;const y=()=>l(h.textContent??""),N=new MutationObserver(y);return N.observe(h,{characterData:!0,childList:!0,subtree:!0}),()=>N.disconnect()},[]);const d=h=>{h.preventDefault(),h.stopPropagation()};return a.jsxs(a.Fragment,{children:[s&&a.jsxs("div",{role:"toolbar","aria-label":g,"data-rich-code-toolbar":!0,className:"flex min-h-11 w-full flex-wrap items-center justify-between gap-2 border-b border-border-subtle bg-elevated px-3 py-1.5 text-fg-secondary",contentEditable:!1,onMouseDown:d,children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2 px-1 text-xs font-semibold text-fg-secondary",children:[s==="mermaid"?a.jsx(Lt,{className:"h-4 w-4 shrink-0 text-fg-tertiary"}):a.jsx(Ht,{className:"h-4 w-4 shrink-0 text-fg-tertiary"}),a.jsx("span",{className:"truncate",children:p})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("div",{className:"flex items-center gap-0.5 rounded-[10px] border border-border-subtle bg-hover-subtle/55 p-0.5",children:[a.jsxs("button",{type:"button","aria-pressed":c,className:Z(ht,c?"border-border-secondary/70 bg-elevated text-fg-default shadow-[0_8px_18px_-16px_rgba(15,18,24,0.28)]":"border-transparent text-fg-secondary hover:bg-hover-subtle hover:text-fg-default"),contentEditable:!1,onClick:h=>{h.stopPropagation(),f(!0)},children:[a.jsx(br,{className:"h-3.5 w-3.5"}),"Edit"]}),a.jsxs("button",{type:"button","aria-pressed":u,className:Z(ht,u?"border-border-secondary/70 bg-elevated text-fg-default shadow-[0_8px_18px_-16px_rgba(15,18,24,0.28)]":"border-transparent text-fg-secondary hover:bg-hover-subtle hover:text-fg-default"),contentEditable:!1,onClick:h=>{h.stopPropagation(),f(!1)},children:[a.jsx(qn,{className:"h-3.5 w-3.5"}),"Preview"]})]}),a.jsx(mt,{variant:"toolbar",getText:()=>t.current?.textContent?.trimEnd()??""})]})]}),a.jsx("pre",{className:Z(u&&"hidden",s&&"bg-[#181b20]"),children:a.jsx("code",{ref:x})}),s&&u&&a.jsx(va,{kind:s,source:i}),!s&&a.jsx(mt,{getText:()=>t.current?.textContent?.trimEnd()??""})]})},wa="focus-ring-soft inline-flex cursor-pointer items-center rounded-[8px] border border-border-subtle bg-[color-mix(in_srgb,var(--elevated)_72%,var(--hover-subtle))] px-2 py-0.5 text-xs font-semibold text-fg-secondary transition-colors hover:border-border-secondary hover:bg-elevated hover:text-fg-default dark:bg-[color-mix(in_srgb,var(--elevated)_82%,var(--hover-subtle))]",Ca={type:"reference",propSchema:{id:{default:""},title:{default:"Unknown"}},content:"none"};function Na(e){const n=jt(),t=()=>{e.editor.blur(),n({to:Ee,params:{id:e.inlineContent.props.id}})},s=r=>{r.preventDefault(),r.stopPropagation()};return a.jsx("span",{role:"link",tabIndex:0,contentEditable:!1,className:wa,onMouseDown:s,onClick:r=>{s(r),t()},onKeyDown:r=>{r.key!=="Enter"&&r.key!==" "||(s(r),t())},children:a.jsxs("span",{children:["[",e.inlineContent.props.title,"]"]})})}const ja=Mt(Ca,{render:e=>a.jsx(Na,{...e})}),Sa=()=>{const e=dr(),[n,t]=o.useState([]),s={1:"pl-3",2:"pl-[26px]",3:"pl-[40px]",4:"pl-[54px]",5:"pl-[68px]",6:"pl-[82px]"};o.useEffect(()=>{const l=()=>{const f=e.document,u=[],p=g=>{for(const x of g){if(x.type==="heading"){const d=x,h=d.props.level||1,y=d.content?.map(N=>N.text||"").join("")||"";y.trim()&&u.push({id:x.id,level:h,text:y})}x.children&&Array.isArray(x.children)&&p(x.children)}};p(f),t(u)};l();const c=e.onChange?.(l);return()=>{c&&c()}},[e]);const r=l=>{e.setTextCursorPosition(l);const c=document.querySelector(`[data-id="${l}"]`);if(c){const f=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;c.scrollIntoView({behavior:f?"auto":"smooth",block:"center"})}},i=a.jsx(er,{icon:a.jsx(At,{className:"h-3.5 w-3.5"}),title:"Table of Contents",className:"text-fg-tertiary"});return n.length===0?a.jsxs("div",{className:"surface-base w-full p-4",children:[i,a.jsx(j,{as:"p",variant:"meta",tone:"secondary",className:"mt-2",children:"Add headings to your document to generate a table of contents"})]}):a.jsxs("div",{className:"surface-base w-full p-4",children:[a.jsx("div",{className:"mb-2",children:i}),a.jsx("nav",{className:"space-y-0.5",children:n.map(l=>{const c=l.level===1;return a.jsxs("button",{type:"button",onClick:()=>r(l.id),className:Z("focus-ring-soft","flex","w-full","items-center","gap-2","rounded-[10px]","px-2.5","py-1.5",s[l.level]??"pl-2.5","text-left","transition-colors","hover:bg-hover-subtle",c?"text-fg-default":"text-fg-secondary"),children:[a.jsxs(j,{as:"span",variant:"label",weight:"medium",tone:"tertiary",className:"min-w-[1.5rem]",children:["H",l.level]}),a.jsx(j,{as:"span",variant:"body",weight:c?"semibold":"medium",className:"line-clamp-2 text-current",children:l.text})]},l.id)})})]})},Aa=Dt({type:"tableOfContents",propSchema:{},content:"none"},{render:()=>a.jsx(Sa,{})})(),Ea="focus-ring-soft inline-flex cursor-pointer items-center rounded-[8px] border border-border-subtle bg-emphasis px-2 py-0.5 text-xs font-semibold text-fg-secondary transition-colors hover:border-border-secondary hover:bg-hover-subtle hover:text-fg-default dark:bg-emphasis",Ra={type:"tag",propSchema:{id:{default:""},tag:{default:"@Unknown"}},content:"none"};function ka(e){const n=jt(),t=()=>{e.editor.blur(),n({to:rr,params:{id:e.inlineContent.props.id},search:{page:1}})},s=r=>{r.preventDefault(),r.stopPropagation()};return a.jsx("span",{role:"link",tabIndex:0,contentEditable:!1,className:Ea,onMouseDown:s,onClick:r=>{s(r),t()},onKeyDown:r=>{r.key!=="Enter"&&r.key!==" "||(s(r),t())},children:a.jsx("span",{children:e.inlineContent.props.tag})})}const Ta=Mt(Ra,{render:e=>a.jsx(ka,{...e})}),Ma=e=>e,Da=e=>e,Pa=Ma({tag:Ta,reference:ja}),_a=Da({tableOfContents:Aa}),ce=he.codeBlock,gt=Dt(ce.config,{meta:ce.implementation.meta,parse:ce.implementation.parse,parseContent:ce.implementation.parseContent,runsBefore:ce.implementation.runsBefore,render:ya})(),La={...gt,extensions:ce.extensions,implementation:{...gt.implementation,toExternalHTML:ce.implementation.toExternalHTML}},Oa={...he.image,implementation:{...he.image.implementation,meta:{...he.image.implementation.meta,fileBlockAccept:[...Qt]}}},Ha=hr.create({inlineContentSpecs:{...gr,...Pa},blockSpecs:{...he,image:Oa,codeBlock:La,..._a}}),Ba=(e,n)=>n.some(t=>t.name===`@${e}`),Fa=({onClick:e})=>a.jsx(Xe,{triggerCharacter:"@",getItems:async n=>{const t=await vr({query:n,limit:5});if(t.type==="error")return[];const{tags:s}=t.allTags,r=Ba(n,s),i=[{title:"Add a new tag",onItemClick:async()=>{const l=await yr({name:"@"+n});if(l.type==="error")return;const{id:c,name:f}=l.createTag;e({type:"tag",props:{id:c,tag:f}})}}];return s.length===0?i:s.map(l=>({title:l.name,onItemClick:()=>e({type:"tag",props:{id:l.id,tag:l.name}})})).concat(n&&!r?i:[])}}),$a=/^ {0,3}(`{3,}|~{3,})/,Ia=/<[^<>\n]*>/g,Jt=/~+/g,Xt=/[\p{L}\p{M}\p{N}\p{Sc}%‰.,+\-/:°℃℉µμ·²³^]/u,Ke=new RegExp("^(?:[+-]?\\p{Sc}?|\\p{Sc}[+-]?)\\p{N}","u"),en=/&#(?:x[0-9a-f]+|\d+);/giu,Ua=new Set(["Files","blocknote/html","vscode-editor-data"]),xt="OBTILDE",bt="",Va=[/(^|\n) {0,3}#{1,6} {1,8}[^\n]{1,64}\r?\n\r?\n\s{0,32}\S/,/(_|__|\*|\*\*|~~|==|\+\+)(?!\s)(?:[^\s](?:.{0,62}[^\s])?|\S)(?=\1)/,/\[[^\]]{1,128}\]\(https?:\/\/\S{1,999}\)/,/(?:\s|^)`(?!\s)(?:[^\s`](?:[^`]{0,46}[^\s`])?|[^\s`])`([^\w]|$)/,/(?:^|\n)\s{0,5}-\s{1}[^\n]+\n\s{0,15}-\s/,/(?:^|\n)\s{0,5}\d+\.\s{1}[^\n]+\n\s{0,15}\d+\.\s/,/\n{2} {0,3}-{2,48}\n{2}/,/(?:\n|^)(```|~~~|\$\$)(?!`|~)[^\s]{0,64} {0,64}[^\n]{0,64}\n[\s\S]{0,9999}?\s*\1 {0,64}(?:\n+|$)/,/(?:\n|^)(?!\s)\w[^\n]{0,64}\n(-|=)\1{0,64}\n\n\s{0,64}(\w|$)/,/(?:^|(\r?\n\r?\n))( {0,3}>[^\n]{1,333}\n){1,999}($|(\r?\n))/],za=e=>e.split(`
22
- `).some(n=>{const t=n.trim();return t.length>2&&t.startsWith("|")&&t.endsWith("|")}),Za=e=>Va.some(n=>n.test(e))||za(e),Wa=e=>e.endsWith(`\r
23
- `)?{body:e.slice(0,-2),ending:`\r
24
- `}:e.endsWith(`
25
- `)||e.endsWith("\r")?{body:e.slice(0,-1),ending:e.slice(-1)}:{body:e,ending:""},tn=(e,n,t)=>{let s=n;for(;e[s]===t;)s+=1;return s-n},nn=e=>{const n=e.slice(2,-1),t=n[0]?.toLowerCase()==="x",s=Number.parseInt(t?n.slice(1):n,t?16:10);return!Number.isSafeInteger(s)||s<0||s>1114111?e:String.fromCodePoint(s)},Ka=e=>{const n=e.replace(en,nn),t=e.toLowerCase();let s=0,r=`${xt}${s}${bt}`;for(;e.includes(r)||t.includes(encodeURIComponent(r).toLowerCase())||n.includes(r);)s+=1,r=`${xt}${s}${bt}`;return r},Ya=(e,n,t)=>t-n>2?!1:rn(e,n)&&Ga(e,t),vt=(e,n)=>{let t=n;for(;t>0&&Xt.test(e[t-1]??"");)t-=1;return{start:t,token:e.slice(t,n)}},qa=(e,n)=>{let t=n;for(;t<e.length&&Xt.test(e[t]??"");)t+=1;return e.slice(n,t)},rn=(e,n)=>{const t=vt(e,n);if(Ke.test(t.token))return!0;if(!t.token)return!1;let s=t.start;for(;s>0&&(e[s-1]===" "||e[s-1]===" ");)s-=1;return s===t.start?!1:Ke.test(vt(e,s).token)},Ga=(e,n)=>Ke.test(qa(e,n)),an=e=>{const n=[],t=new Set;for(const s of e.matchAll(Jt)){const r=s.index,i=s[0].length,l=r+i;if(i>2)continue;const c=l<e.length&&!/\s/u.test(e[l]??""),f=r>0&&!/\s/u.test(e[r-1]??"");if(Ya(e,r,l)){if(f&&t.delete(i))continue;n.push({length:i,start:r});continue}f&&t.delete(i)||c&&rn(e,r)&&t.add(i)}return n},$e=(e,n)=>{let t="",s=0;const r=new Set(an(e).map(i=>i.start));for(const i of e.matchAll(Jt)){const l=i.index,c=l+i[0].length;t+=e.slice(s,l),t+=r.has(l)?n.repeat(i[0].length):i[0],s=c}return t+e.slice(s)},Qa=e=>{const n=e.slice(1,-1),t=/^[a-z][a-z0-9.+-]{1,31}:[^\s<>]*$/i.test(n)||/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(n),s=/^<\/?[a-z][\w:-]*(?:\s[^<>]*)?\/?\s*>$/i.test(e)||/^<![^<>]*>$/.test(e);return t||s},Ja=(e,n)=>{let t="",s=0;for(const r of e.matchAll(Ia)){const i=r.index;t+=$e(e.slice(s,i),n),t+=Qa(r[0])?r[0]:$e(r[0],n),s=i+r[0].length}return t+$e(e.slice(s),n)},sn=e=>an(e).length>0,Xa=e=>{if(!sn(e))return ot(e);const n=Ka(e),t=Ja(e,n),s=encodeURIComponent(n);return ot(t).split(n).join("~").split(s).join("~")},es=(e,n)=>{let t=0;for(let s=n-1;s>=0&&e[s]==="\\";s-=1)t+=1;return t%2===1},ts=(e,n,t)=>{let s=n+t;for(;s<e.length;){const r=e.indexOf("`",s);if(r===-1)return null;const i=tn(e,r,"`");if(i===t)return r+i;s=r+i}return null},ns=(e,n)=>{let t=e.indexOf("`",n);for(;t!==-1;){const s=tn(e,t,"`");if(!es(e,t)){const r=ts(e,t,s);if(r!==null)return{start:t,end:r}}t=e.indexOf("`",t+s)}return null},rs=(e,n)=>{let t="",s=0;for(;s<e.length;){const r=ns(e,s);if(!r){t+=n(e.slice(s));break}t+=n(e.slice(s,r.start)),t+=e.slice(r.start,r.end),s=r.end}return t},on=(e,n)=>{let t=null;return e.split(new RegExp("(?<=\\n)")).map(s=>{const{body:r,ending:i}=Wa(s);if(t)return new RegExp(`^ {0,3}${t.marker}{${t.length},} *$`).test(r)&&(t=null),s;const l=r.match($a)?.[1];return l?(t={marker:l[0],length:l.length},s):`${rs(r,n)}${i}`}).join("")},as=(e,n)=>{let t=0;for(let s=n;s<e.length;s+=1){const r=e[s];if(r==="\\"){s+=1;continue}if(r==="("){t+=1;continue}if(r===")"){if(t>0){t-=1;continue}return s}}return null},cn=e=>{let n="",t=0;for(;t<e.length;){const s=e.indexOf("](",t);if(s===-1){n+=e.slice(t);break}const r=s+2,i=as(e,r);if(i===null){n+=e.slice(t);break}n+=e.slice(t,r),n+=e.slice(r,i).split("\\&").join("&"),n+=")",t=i+1}return n},ss=(e,n)=>{const t=e[n-1];if(t!=="*"&&t!=="_")return!1;let s=n-1;for(;s>0&&e[s-1]===t;)s-=1;const r=e.slice(s,n),i=e.lastIndexOf(r,s-1);return i!==-1&&i+r.length<s},os=(e,n)=>{const t=e[n];if(t!=="*"&&t!=="_")return!1;let s=n+1;for(;s<e.length&&e[s]===t;)s+=1;const r=e.slice(n,s),i=e.indexOf(r,s);return i!==-1&&s<i},is=(e,n,t)=>ss(e,n)||os(e,n+t),cs=e=>on(e,n=>{const t=n.replace(en,(s,r,i)=>is(i,r,s.length)?nn(s):s);return cn(t)}),ls=e=>on(e,cn),ds=e=>{const n=e.getData("text/plain");n&&(e.setData("text/markdown",n),e.setData("text/plain",cs(n)))},us=({event:e,editor:n,defaultPasteHandler:t})=>{const s=e.clipboardData;if(!s||n.getTextCursorPosition().block.type==="codeBlock")return t();const r=Array.from(s.types);if(r.some(c=>Ua.has(c)))return t();const i=r.includes("text/markdown"),l=s.getData(i?"text/markdown":"text/plain");return!l||!sn(l)||!i&&r.includes("text/html")&&!Za(l)?t():(n.pasteHTML(Xa(l)),!0)},fs=new Set(["tableOfContents"]),ps="OCEAN_BRAIN_TAG_",ms="_TOKEN",hs=e=>`${ps}${e}${ms}`,gs=e=>!Array.isArray(e)&&e?.type==="tableContent",xs=(e,n)=>Array.isArray(e)?e.map(n):gs(e)?{...e,rows:e.rows?.map(t=>({...t,cells:t.cells?.map(s=>({...s,content:s.content?.map(n)}))}))}:e,ln=(e,n)=>e.filter(t=>!fs.has(t.type)).map(t=>({...t,content:n(t.content),children:t.children?.length?ln(t.children,n):[]}));function bs(e){const n=new Map;let t=0;return{blocks:ln(e,r=>xs(r,i=>{if(i.type==="reference"){const l=String(i.props?.id||""),c=String(i.props?.title||i.props?.id||"");return{type:"text",text:l?`[[${c}]](note:${l})`:`[[${c}]]`,styles:{}}}if(i.type==="tag"){const l=i.props?.tag||"",c=hs(t);return t+=1,n.set(c,l),{type:"text",text:c,styles:{}}}return i})),placeholderToTag:n}}function vs(e,n){let t=e;for(const[s,r]of n.entries())t=t.split(s).join(`[${r}]`);return t}async function ys(e){return new Promise((n,t)=>{const s=new FileReader;s.readAsDataURL(e),s.onload=()=>n(s.result),s.onerror=r=>t(r)})}const ws=o.forwardRef(({content:e,currentNoteId:n,editable:t,onChange:s},r)=>{const{theme:i}=Nt(u=>u),l=Ae(),c=ur({schema:Ha,initialContent:e&&JSON.parse(e)||void 0,pasteHandler:u=>us(u),uploadFile:async(u,p)=>{const g=()=>{p&&c.getBlock(p)&&c.removeBlocks([p])};if(!da(u.type))throw g(),l(ut),new Error(ut);try{return await pr({base64:await ys(u)})}catch(x){throw g(),l(la),x}}},[l]);o.useImperativeHandle(r,()=>({getContent:()=>JSON.stringify(c.document),getMarkdown:()=>{const u=bs(c.document),p=c.blocksToMarkdownLossy(u.blocks);return ls(vs(p,u.placeholderToTag))},getHtml:()=>c.blocksToHTMLLossy(c.document)}));const f=u=>{ds(u.clipboardData)};return a.jsxs(fr,{slashMenu:!1,theme:i,editor:c,editable:t,onChange:s,onCopy:f,onCut:f,children:[a.jsx(sa,{editor:c}),a.jsx(ia,{currentNoteId:n,onClick:u=>{c.insertInlineContent([u," "])}}),a.jsx(Fa,{onClick:u=>{c.insertInlineContent([u," "])}})]})}),Cs=({event:e,noteId:n,editSessionId:t,loadedUpdatedAt:s,acceptedUpdatedAt:r,hasUnsavedChanges:i})=>{if(e.noteId!==n||e.type==="mcp.note.created")return{type:"ignore"};if(e.source==="web"&&e.editSessionId===t)return{type:"ignore"};if(e.type==="mcp.note.deleted")return{type:"notify",change:{type:"deleted",source:e.source},shouldPauseSave:!1};const l=je(e.updatedAt,s),c=je(e.updatedAt,r);return l!==null&&l<=0||c!==null&&c<=0?{type:"ignore"}:{type:"notify",change:{type:"updated",updatedAt:e.updatedAt,source:e.source},shouldPauseSave:i}},Ns=({change:e,isConflict:n,loadedUpdatedAt:t})=>e?!(e.type==="updated"&&!n&&e.updatedAt===t):!1;function js({allowNextNavigationRef:e,hasExternalPendingChanges:n,saveStatus:t,flushPendingChanges:s,notify:r}){const i=o.useCallback(async()=>{if(e.current)return e.current=!1,!1;if(t==="conflict")return r("Resolve the note conflict before leaving."),!0;const l=await s();return l==="error"?(r("Save failed. Stay on this note and try again."),!0):l==="conflict"},[e,s,r,t]);Cr({disabled:t==="saved"&&!n,enableBeforeUnload:!1,shouldBlockFn:i})}const tt=e=>`ocean-brain.note-draft.${e}`,Ss=e=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(tt(e));if(!n)return null;const t=JSON.parse(n);return typeof t.title!="string"||typeof t.content!="string"||typeof t.baseUpdatedAt!="string"?null:{title:t.title,content:t.content,baseUpdatedAt:t.baseUpdatedAt,createdAt:typeof t.createdAt=="number"?t.createdAt:Date.now(),...t.layout==="narrow"||t.layout==="wide"||t.layout==="full"?{layout:t.layout}:{}}}catch{return null}},Ie=(e,n)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(tt(e),JSON.stringify(n))}catch{}},Ue=e=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(tt(e))}catch{}},As=1e3,Es="NOTE_UPDATE_CONFLICT";function Rs({noteId:e,initialContent:n,initialUpdatedAt:t,editSessionIdRef:s,getContent:r,beforeSave:i,hasExternalPendingChanges:l,serverVersionRef:c,executeWrite:f,onSaved:u,onConflict:p,onError:g}){const x=qe(),d=o.useRef(null),h=o.useRef(null),y=o.useRef(!1),N=o.useRef(null),S=o.useRef(!1),E=o.useRef(t),w=c??E,m=o.useRef(0),v=o.useRef(!1),T=o.useRef(!0),F=o.useRef(u),D=o.useRef(p),W=o.useRef(g),be=o.useRef(i),X=o.useRef(l),me=o.useRef(f),[re,ee]=o.useState("saved"),[ke,le]=o.useState(null),$=o.useCallback(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]),L=o.useCallback(R=>{T.current&&ee(R)},[]),Te=o.useCallback(R=>{w.current=R},[]),ve=o.useCallback((R,O={})=>({title:R,content:r()??n,createdAt:Date.now(),baseUpdatedAt:w.current,...O.layout?{layout:O.layout}:{}}),[r,n]),de=o.useCallback(()=>{h.current&&Ie(e,h.current)},[e]),ae=o.useCallback(R=>{v.current=!0,L("conflict"),D.current(R??w.current)},[L]),_=o.useCallback(async({ignoreConflict:R=!1,silent:O=!1}={})=>{if(y.current)return S.current=!0,N.current??"idle";const De=h.current!==null,se=X.current?.()??!1;if(!De&&!se)return S.current=!1,"idle";const I=m.current;S.current=!1,$(),y.current=!0,O||L("saving");const B=(async()=>{const ue=await be.current?.()??"idle";if(I!==m.current)return"idle";if(ue==="error")return y.current=!1,N.current=null,h.current?L("error"):L("saved"),"error";const P=h.current;if(!P)return y.current=!1,N.current=null,L("saved"),ue;h.current=null;const q=async()=>{if(I!==m.current)return"idle";let z;try{z=await ze({id:e,title:P.title,content:P.content,...P.layout?{layout:P.layout}:{},editSessionId:s.current,...R?{force:!0}:{expectedUpdatedAt:w.current}})}catch{z={type:"error",category:"network",errors:[{code:"NETWORK_ERROR",message:"Failed to save note."}]}}if(I!==m.current)return"idle";if(z.type==="error"){y.current=!1,N.current=null,h.current||(h.current=P),de();const U=z.errors[0];if(U.code===Es&&!R){const oe=U.details?.extensions?.currentUpdatedAt;return v.current=!0,!O&&T.current&&(L("conflict"),D.current(oe??w.current)),"conflict"}return!O&&T.current&&(L("error"),W.current(U.message)),"error"}const we=!O&&T.current,J=H.notes.detail(e);if(await x.cancelQueries({queryKey:J,exact:!0}),I!==m.current)return"idle";y.current=!1,N.current=null,v.current=!1,w.current=z.updateNote.updatedAt,we&&F.current(z.updateNote.updatedAt),x.setQueryData(J,U=>U&&{...U,title:z.updateNote.title,content:P.content,...P.layout?{layout:P.layout}:{},updatedAt:z.updateNote.updatedAt}),Et({noteId:e,updatedAt:z.updateNote.updatedAt,editSessionId:s.current});const fe=h.current;return fe?.baseUpdatedAt===P.baseUpdatedAt?(h.current={...fe,baseUpdatedAt:z.updateNote.updatedAt},de()):fe||Ue(e),h.current||Rt(x),we&&(h.current?ee("pending"):ee("saved")),"saved"},V=me.current?await me.current(q):await q();return V?V==="saved"&&(h.current||S.current)?_({silent:O}):V:(h.current||(h.current=P),de(),y.current=!1,N.current=null,L("pending"),"idle")})();return N.current=B,B},[$,s,e,de,x,w,L]),te=o.useCallback((R,O={})=>{if(h.current=R,Ie(e,R),v.current){L("conflict");return}if(L("pending"),$(),O.immediate){_();return}d.current=window.setTimeout(()=>{_()},As)},[$,_,e,L]),ne=o.useCallback(R=>{if(h.current=R,Ie(e,R),le(null),R.baseUpdatedAt!==w.current){ae(w.current);return}te(R)},[e,te,ae]),ye=o.useCallback(()=>{m.current+=1,$(),h.current=null,y.current=!1,N.current=null,S.current=!1,v.current=!1,Ue(e),le(null),ee("saved")},[$,e]),Me=o.useCallback(()=>{$(),N.current=null,S.current=!1,v.current=!1,L(h.current?"pending":"saved")},[$,L]),Q=o.useCallback(()=>{Ue(e),le(null)},[e]),Y=o.useCallback(()=>h.current,[]),K=o.useCallback(R=>{$(),ae(R)},[$,ae]);return o.useEffect(()=>{be.current=i,me.current=f,X.current=l,D.current=p,W.current=g,F.current=u},[i,f,l,p,g,u]),o.useEffect(()=>(T.current=!0,()=>{T.current=!1}),[]),o.useEffect(()=>{h.current||y.current||v.current||(w.current=t,ee("saved"))},[t]),o.useEffect(()=>{m.current+=1,h.current=null,y.current=!1,N.current=null,S.current=!1,v.current=!1,w.current=t,le(Ss(e)),ee("saved")},[e]),o.useEffect(()=>{const R=O=>{!h.current&&!y.current&&!v.current&&!X.current?.()||(O.preventDefault(),O.returnValue="")};return window.addEventListener("beforeunload",R),()=>{window.removeEventListener("beforeunload",R)}},[]),o.useEffect(()=>()=>{$(),h.current&&!v.current&&_({silent:!0})},[$,_]),{saveStatus:re,localDraft:ke,serverUpdatedAtRef:w,hasUnsavedChanges:re!=="saved",buildDraft:ve,queueSave:te,flushPendingSave:_,restoreLocalDraft:ne,discardLocalDraft:Q,clearDrafts:ye,resolveConflict:Me,pauseForConflict:K,getPendingDraft:Y,setServerUpdatedAt:Te}}function ks(){const e=o.useRef(Promise.resolve()),n=o.useRef(0),t=o.useRef(0),[s,r]=o.useState(!1),i=o.useCallback(u=>{t.current+=1,r(!0);const p=n.current,g=()=>p===n.current?u():void 0,x=e.current.then(g,g);e.current=x.then(()=>{},()=>{});const d=()=>{t.current-=1,t.current===0&&r(!1)};return x.then(d,d),x},[]),l=o.useCallback(()=>{n.current+=1},[]),c=o.useCallback(()=>e.current,[]),f=o.useCallback(()=>t.current>0,[]);return o.useMemo(()=>({execute:i,invalidatePending:l,drain:c,isBusy:s,hasPendingWrites:f}),[c,i,f,l,s])}const Ts="NOTE_UPDATE_CONFLICT",Ve=e=>{const n=ge(e);return G(n??Number(e)).format("YYYY-MM-DD HH:mm:ss")},Ms=e=>e?.extensions?.currentUpdatedAt;function Ds({noteId:e,navigateToNote:n,notify:t}){const s=qe(),r=o.useRef(null),i=o.useRef(null),[l]=o.useState(it),c=o.useRef(l),f=o.useRef(null),u=o.useRef(null),p=o.useRef(!1),g=o.useRef(0),x=yt({queryKey:H.notes.detail(e),queryFn:async()=>{const b=await Hn(e);if(b.type==="error")throw b;return b.note},gcTime:0}),d=x.data,h=x.refetch,y=o.useRef(d.updatedAt),N=o.useRef(d.updatedAt),[S,E]=o.useState(d.title),[w,m]=o.useState(d.pinned),[v,T]=o.useState(d.layout||"wide"),F=o.useRef(v),[D,W]=o.useState(null),[be,X]=o.useState(null),[me,re]=o.useState(0),[ee,ke]=o.useState(()=>Ve(d.updatedAt)),[le,$]=o.useState(d.updatedAt),[L,Te]=o.useState(0),[ve,de]=o.useState(!1),ae=o.useRef(!1),{execute:_,invalidatePending:te,drain:ne,isBusy:ye,hasPendingWrites:Me}=ks(),Q=o.useCallback(b=>{F.current=b,T(b)},[]),Y=o.useCallback((b,C={})=>{y.current=b,N.current=b,ke(Ve(b)),$(b),C.confirmSave&&Te(A=>A+1)},[]),K=o.useCallback(async({updatedAt:b,patch:C,confirmSave:A=!0})=>{const pe=H.notes.detail(e),Le=g.current;return await s.cancelQueries({queryKey:pe,exact:!0}),Le!==g.current?!1:(Y(b,{confirmSave:A}),s.setQueryData(pe,Oe=>Oe&&{...Oe,...C,updatedAt:b}),Et({noteId:e,updatedAt:b,editSessionId:c.current}),Rt(s),!0)},[Y,e,s]),R=o.useCallback(b=>{ae.current=b,de(b)},[]),O=o.useCallback(()=>f.current?.flushPendingSave({expectedUpdatedAt:y.current})??Promise.resolve("idle"),[]),De=Rs({noteId:e,initialContent:d.content,initialUpdatedAt:d.updatedAt,editSessionIdRef:c,serverVersionRef:y,executeWrite:_,getContent:()=>r.current?.getContent(),beforeSave:O,hasExternalPendingChanges:()=>ae.current||Me(),onSaved:b=>{u.current=null,Y(b,{confirmSave:!0})},onConflict:b=>{W({type:"updated",updatedAt:b,source:"unknown"}),t("This note changed elsewhere. Choose how to resolve the draft.")},onError:t}),{saveStatus:se,localDraft:I,serverUpdatedAtRef:B,hasUnsavedChanges:ue,buildDraft:P,queueSave:q,flushPendingSave:V,restoreLocalDraft:z,discardLocalDraft:we,clearDrafts:J,resolveConflict:fe,pauseForConflict:U,getPendingDraft:oe}=De,Ce=ue||ve||ye,nt=o.useCallback(async b=>{const C=await V(b);return C==="error"||C==="conflict"||await ne(),C},[ne,V]),un=o.useCallback(b=>_(async()=>{const C=await Bn({...b,expectedUpdatedAt:y.current});return C.type==="success"&&await K({updatedAt:C.updateNoteProperties.updatedAt,patch:{properties:C.updateNoteProperties.properties}}),C}),[K,_]);js({allowNextNavigationRef:p,hasExternalPendingChanges:ve||ye,saveStatus:se,flushPendingChanges:nt,notify:t}),o.useEffect(()=>{if(Ce){d.updatedAt!==B.current&&(je(d.updatedAt,B.current)??0)>0&&U(d.updatedAt);return}const b=N.current;if(!(b&&d.updatedAt!==b&&(je(d.updatedAt,b)??0)<0)&&(m(d.pinned),Q(d.layout||"wide"),E(d.title),b!==d.updatedAt)){const C=r.current?.getContent();Y(d.updatedAt),(C===void 0||C!==d.content)&&(X(null),re(A=>A+1))}},[Y,Ce,d.content,d.layout,d.pinned,d.title,d.updatedAt,U,B]),o.useEffect(()=>{D?.type!=="updated"||se==="conflict"||D.updatedAt!==d.updatedAt||(Y(d.updatedAt),W(null))},[Y,D,d.updatedAt,se]),o.useEffect(()=>Gn(b=>{const C=Cs({event:b,noteId:e,editSessionId:c.current,loadedUpdatedAt:d.updatedAt,acceptedUpdatedAt:B.current,hasUnsavedChanges:Ce});C.type!=="ignore"&&(C.shouldPauseSave&&C.change.type==="updated"&&U(C.change.updatedAt),W(C.change))}),[Ce,d.updatedAt,e,U,B]);const fn=o.useCallback(()=>{q(P(S))},[P,q,S]),pn=o.useCallback(b=>{E(b),q(P(b))},[P,q]),mn=o.useCallback(()=>{q(P(S),{immediate:!0})},[P,q,S]),hn=o.useCallback(async b=>{if(ue){Q(b),q(P(S,{layout:b}),{immediate:!0}),t("Layout will be saved with your draft.");return}const C=await V();C==="error"||C==="conflict"||await _(async()=>{const A=await ze({id:e,layout:b,editSessionId:c.current,expectedUpdatedAt:B.current});if(A.type==="error"){A.errors[0].code===Ts&&(u.current=b,Q(b),U(Ms(A.errors[0].details)??B.current)),t(A.errors[0].message);return}await K({updatedAt:A.updateNote.updatedAt,patch:{layout:b}})&&(u.current=null,Q(b),t("Layout has been updated."))})},[K,P,_,V,ue,e,t,U,q,B,S]),gn=o.useCallback(async()=>{const b=await V();if(b==="error"||b==="conflict")return;const C=!w;await _(async()=>{const A=await Fn(e,C);if(A.type==="error"){t(A.errors[0].message);return}await K({updatedAt:A.pinNote.updatedAt,patch:{pinned:C},confirmSave:!1})&&m(C)})},[K,_,V,w,e,t]),Pe=o.useCallback(()=>({id:e,title:S,createdAt:d.createdAt,updatedAt:B.current||d.updatedAt}),[d.createdAt,d.updatedAt,e,B,S]),xn=o.useCallback(async()=>{const b=r.current?.getMarkdown();if(b===void 0){t("Markdown is not ready yet.");return}try{await navigator.clipboard.writeText(Wt(b,Pe())),t("Copied note as Markdown.")}catch{t("Failed to copy Markdown.")}},[Pe,t]),bn=o.useCallback(async()=>{f.current?.invalidateInFlightSave(),te(),await ne(),g.current+=1;const b=await h();if(b.error||!b.data){t("Failed to reload the latest note state.");return}f.current?.discardPendingChanges(),J(),u.current=null,Y(b.data.updatedAt),E(b.data.title),Q(b.data.layout||"wide"),X(null),re(C=>C+1),W(null)},[J,Y,ne,te,t,h]),vn=o.useCallback(async()=>{if(oe()){u.current=null,W(null),await V({ignoreConflict:!0});return}const C=u.current;if(!C){W(null),await V({ignoreConflict:!0});return}await _(async()=>{const A=await ze({id:e,layout:C,editSessionId:c.current,force:!0});if(A.type==="error"){t(A.errors[0].message);return}await K({updatedAt:A.updateNote.updatedAt,patch:{layout:C}})&&(u.current=null,fe(),W(null),Q(C))})},[K,_,V,oe,e,t,fe]),yn=o.useCallback(async()=>{const b=oe();if(!b||await O()==="error")return;const A=await $n({title:rt(b.title||"untitled"),content:rt(b.content),layout:b.layout??v});if(A.type==="error"){t(A.errors[0].message);return}p.current=!0,u.current=null,W(null),J(),Promise.resolve(n(A.createNote.id)).finally(()=>{p.current=!1})},[J,O,oe,v,n,t]),wn=o.useCallback(()=>{I&&(E(I.title),I.layout&&Q(I.layout),X(I.content),re(b=>b+1),z(I))},[I,z]),Cn=o.useCallback(()=>{},[]),Nn=o.useCallback(async b=>(f.current?.invalidateInFlightSave(),te(),await ne(),g.current+=1,_(async()=>{const C=await In(b,B.current);if(C.type==="error")return C;const A=C.restoreNoteSnapshot;return await K({updatedAt:A.updatedAt,patch:{title:A.title,content:A.content,layout:A.layout,pinned:A.pinned}})&&(c.current=it(),f.current?.discardPendingChanges(),J(),u.current=null,W(null),E(A.title),Q(A.layout||"wide"),m(A.pinned),X(A.content),re(Le=>Le+1)),C})),[K,J,ne,_,te]),_e=se==="conflict"&&D?.type==="updated",jn=_e?oe():null;return{document:{title:S,titleRef:i,isPinned:w,layout:v,getLayout:()=>F.current,properties:d.properties,createdAt:Ve(d.createdAt),onTitleChange:pn,onLayoutSave:hn,onTogglePinned:gn},editor:{ref:r,key:`${e}:${me}`,content:be??d.content,getContent:()=>r.current?.getContent()??"",getHtml:()=>r.current?.getHtml(),getMarkdown:()=>r.current?.getMarkdown(),onChange:fn},save:{status:se,lastSavedAt:ee,lastSavedVersion:le,confirmationRevision:L,onManualSave:mn,flushPendingChanges:nt},recovery:{localDraftCreatedAt:I?G(I.createdAt).format("YYYY-MM-DD HH:mm:ss"):null,onRestoreLocalDraft:wn,onDiscardLocalDraft:we,onClonePendingDraft:yn},externalChange:{value:D,isConflict:_e,hasConflictDraft:jn!==null,isBlocking:Ns({change:D,isConflict:_e,loadedUpdatedAt:d.updatedAt}),isReloading:x.isRefetching,onReload:bn,onOverwrite:vn},properties:{ref:f,expectedUpdatedAt:B.current,editSessionId:c.current,saveProperties:un,onPendingChange:R,onSaved:Cn},exportDocument:{metadata:Pe(),onCopyMarkdown:xn},snapshots:{restore:Nn}}}const dn=Un(Ee),Ps={narrow:"max-w-[640px]",wide:"max-w-[896px]",full:"max-w-full px-4"},_s=a.jsx(Qe,{title:"Loading note",variant:"none",children:a.jsxs("main",{className:"mx-auto max-w-[896px]",children:[a.jsx(ie,{className:"mb-8",height:123}),a.jsxs("div",{className:"flex flex-col gap-5",children:[a.jsx(ie,{height:135}),a.jsx(ie,{className:"ml-12",height:320}),a.jsx(ie,{height:107}),a.jsx(ie,{height:100})]})]})});function Ls({noteId:e}){return a.jsx(Ge,{fallback:a.jsx(ie,{height:107}),errorTitle:"Failed to load reminders",errorDescription:"Retry loading reminder details for this note.",renderError:({error:n,retry:t})=>a.jsx(Je,{title:"Failed to load reminders",description:"Retry loading reminder details for this note.",error:n,onRetry:t,showBackAction:!1,showHomeAction:!1}),children:a.jsx(ra,{noteId:e})})}function Os({noteId:e}){return a.jsx(Ge,{fallback:a.jsx(ie,{height:100}),errorTitle:"Failed to load back references",errorDescription:"Retry loading notes that link back here.",renderError:({error:n,retry:t})=>a.jsx(Je,{title:"Failed to load back references",description:"Retry loading notes that link back here.",error:n,onRetry:t,showBackAction:!1,showHomeAction:!1}),children:a.jsx(Rr,{noteId:e,render:n=>n?.length?a.jsx(Tt,{icon:a.jsx(nr,{className:"h-3.5 w-3.5"}),title:"Back References",children:a.jsx("ul",{className:"flex flex-col",children:n.map(t=>a.jsx("li",{children:a.jsxs(Vn,{to:Ee,params:{id:t.id},className:"flex items-center gap-2 rounded-[10px] px-2.5 py-1.5 text-fg-secondary transition-colors hover:bg-hover-subtle hover:text-fg-default",children:[a.jsx(Ar,{className:"h-3.5 w-3.5 shrink-0 text-fg-tertiary"}),a.jsx(j,{as:"span",variant:"body",weight:"medium",className:"text-current",children:t.title})]})},t.id))})}):null})})}function Hs({id:e}){const n=Ae(),t=dn.useNavigate(),[s,r]=o.useState(!1),[i,l]=o.useState(!1),[c,f]=o.useState(!1),u=Ds({noteId:e,notify:n,navigateToNote:D=>t({to:Ee,params:{id:D}})}),{onCreate:p,onDelete:g,deleteWarningDialog:x}=Qn(),{document:d,editor:h,save:y,recovery:N,externalChange:S,properties:E,exportDocument:w,snapshots:m}=u,v=()=>t({to:ar,search:{page:1}}),T=async()=>{const D=await y.flushPendingChanges();D==="error"||D==="conflict"||await g(e,v)},F=async()=>{const D=await y.flushPendingChanges();D==="error"||D==="conflict"||await p(d.titleRef.current?.value||"untitled",h.getContent(),d.getLayout())};return a.jsx(Qe,{title:d.title,variant:"none",children:a.jsxs("main",{className:Z("mx-auto",Ps[d.layout]),children:[a.jsx(Pr,{title:d.title,titleRef:d.titleRef,isPinned:d.isPinned,createdAt:d.createdAt,saveStatus:y.status,savedAt:y.lastSavedAt,savedVersion:y.lastSavedVersion,saveConfirmationRevision:y.confirmationRevision,onTitleChange:d.onTitleChange,onCopyMarkdown:()=>{w.onCopyMarkdown()},onDownloadDocument:()=>f(!0),onTogglePinned:()=>{d.onTogglePinned()},onChangeLayout:()=>r(!0),onCloneNote:()=>{F()},onRestoreVersion:()=>l(!0),onDelete:()=>{T()},onSave:y.onManualSave}),a.jsx(ea,{localDraftCreatedAt:N.localDraftCreatedAt,hasSaveError:y.status==="error",onRestoreDraft:N.onRestoreLocalDraft,onDiscardDraft:N.onDiscardLocalDraft,onRetrySave:y.onManualSave,onSaveAsNewNote:()=>{N.onClonePendingDraft()}}),a.jsxs("div",{className:"flex flex-col gap-5",children:[a.jsx(tr,{ref:E.ref,noteId:e,properties:d.properties,expectedUpdatedAt:E.expectedUpdatedAt,editSessionId:E.editSessionId,disabled:y.status!=="saved",saveProperties:E.saveProperties,onPendingChange:E.onPendingChange,onSaved:E.onSaved}),a.jsx(ws,{ref:h.ref,content:h.content,currentNoteId:e,onChange:h.onChange},h.key),a.jsx(Ls,{noteId:e}),a.jsx(Os,{noteId:e})]}),a.jsx(Tr,{isOpen:s,onClose:()=>r(!1),onSave:d.onLayoutSave,currentLayout:d.layout}),a.jsx(Xr,{isOpen:S.isBlocking,isDeleted:S.value?.type==="deleted",isConflict:S.isConflict,hasDraft:S.hasConflictDraft,source:S.value?.source??"unknown",isReloading:S.isReloading,onReload:()=>{S.onReload()},onOverwrite:()=>{S.onOverwrite()},onCloneDraft:()=>{N.onClonePendingDraft()},onOpenTrash:()=>{v()}}),a.jsx(Gr,{isOpen:c,metadata:w.metadata,getHtml:h.getHtml,getMarkdown:h.getMarkdown,onClose:()=>f(!1)}),a.jsx(ta,{isOpen:i,noteId:e,onClose:()=>l(!1),restoreSnapshot:m.restore}),x]})})}function to(){const{id:e}=dn.useParams();if(!e)throw new Error("Note id is required.");return a.jsx(Ge,{fallback:_s,errorTitle:"Failed to load note",errorDescription:"Retry loading the note editor.",resetKeys:[e],renderError:({error:n,retry:t})=>a.jsx(Qe,{title:"Note",variant:"none",children:a.jsx(Je,{title:"Failed to load note",description:"Retry loading the note editor.",error:n,onRetry:t})}),children:a.jsx(Hs,{id:e},e)})}export{Hs as NoteContent,to as default};