@inshapardaz/likhari-react 0.1.8 → 0.1.9-dev.94

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 (35) hide show
  1. package/dist/EditorRoot.d.ts +60 -0
  2. package/dist/EditorRoot.d.ts.map +1 -1
  3. package/dist/EditorRoot.js +183 -10
  4. package/dist/components/DraftRestore.d.ts +24 -0
  5. package/dist/components/DraftRestore.d.ts.map +1 -0
  6. package/dist/components/DraftRestore.js +61 -0
  7. package/dist/components/DraftsDialog.d.ts +25 -0
  8. package/dist/components/DraftsDialog.d.ts.map +1 -0
  9. package/dist/components/DraftsDialog.js +66 -0
  10. package/dist/components/LeaveDialog.d.ts +22 -0
  11. package/dist/components/LeaveDialog.d.ts.map +1 -0
  12. package/dist/components/LeaveDialog.js +15 -0
  13. package/dist/components/TableDialog.d.ts +17 -0
  14. package/dist/components/TableDialog.d.ts.map +1 -0
  15. package/dist/components/TableDialog.js +33 -0
  16. package/dist/components/Toolbar.d.ts +4 -1
  17. package/dist/components/Toolbar.d.ts.map +1 -1
  18. package/dist/components/Toolbar.js +31 -5
  19. package/dist/i18n/strings.d.ts +45 -2
  20. package/dist/i18n/strings.d.ts.map +1 -1
  21. package/dist/i18n/strings.js +117 -3
  22. package/dist/index.d.ts +2 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/nodes.d.ts.map +1 -1
  25. package/dist/nodes.js +4 -0
  26. package/dist/persistence/draftStorage.d.ts +55 -0
  27. package/dist/persistence/draftStorage.d.ts.map +1 -0
  28. package/dist/persistence/draftStorage.js +198 -0
  29. package/dist/persistence/draftUi.d.ts +9 -0
  30. package/dist/persistence/draftUi.d.ts.map +1 -0
  31. package/dist/persistence/draftUi.js +23 -0
  32. package/dist/theme/editor.css +105 -0
  33. package/dist/theme/editorTheme.d.ts.map +1 -1
  34. package/dist/theme/editorTheme.js +5 -0
  35. package/package.json +2 -1
@@ -3,7 +3,10 @@ import type { SerializedEditorState } from 'lexical';
3
3
  import { type FormatId } from '@inshapardaz/likhari-converters';
4
4
  import { type EditorFeatureConfig, type FeatureConfigPresetName } from '@inshapardaz/likhari-core';
5
5
  import { type FontOption } from './fonts/index.js';
6
+ import { type DraftRestoreMode } from './components/DraftRestore.js';
6
7
  import { type Locale } from './i18n/index.js';
8
+ /** What happens when the user is about to leave with unsaved changes. */
9
+ export type NavigationGuardMode = 'confirm' | 'save-draft' | 'off';
7
10
  export interface EditorInitialContent {
8
11
  format: Extract<FormatId, 'lexical-json' | 'plain-text'>;
9
12
  value: string;
@@ -70,6 +73,63 @@ export interface EditorRootProps {
70
73
  * `[...DEFAULT_FONT_OPTIONS, { name: 'Mine', family: '"Mine", serif' }]`.
71
74
  */
72
75
  fontOptions?: FontOption[];
76
+ /**
77
+ * Saves drafts: a debounced autosave of the current content to
78
+ * `localStorage` (lexical-editor-spec.md §6.2), a resilience net against an
79
+ * accidental tab close that is independent of `onSave`/the Save button. The
80
+ * draft is stored under `documentId` when you give one (§6.1); without one, a
81
+ * unique id is generated for this editor, so editors never overwrite each
82
+ * other's drafts. The toolbar's Drafts button lists every draft in the browser
83
+ * to restore or delete. A draft is cleared on a successful explicit save.
84
+ * Defaults to `true`.
85
+ */
86
+ autosave?: boolean;
87
+ /**
88
+ * What to do on mount when a draft of this `documentId` newer than the initial
89
+ * content exists (needs `documentId`):
90
+ * - `'prompt'` (default): a banner with Restore / Ignore / Remove draft;
91
+ * - `'auto'`: load the draft straight away, no questions (see `onDraftRestored`);
92
+ * - `'off'`: keep the initial content; the draft is moved aside into the drafts
93
+ * list so new edits don't overwrite it unseen.
94
+ */
95
+ restoreDraft?: DraftRestoreMode;
96
+ /**
97
+ * What happens when the user is about to leave with unsaved changes, for both
98
+ * `EditorRef.confirmDiscard()` (in-app navigation, which your router guard
99
+ * calls) and for closing or refreshing the tab:
100
+ * - `'confirm'` (default): `confirmDiscard()` opens an in-editor popup (Save /
101
+ * Discard / Save draft / Cancel). On closing or refreshing the tab no
102
+ * popup is possible, and a draft is saved instead when `autosave` is on, so the
103
+ * browser's own "leave this page?" prompt is skipped; it only appears as a last
104
+ * resort, when no draft could be stored (autosave off, document over
105
+ * `autosaveMaxBytes`, storage unavailable);
106
+ * - `'save-draft'`: silently saves a draft and lets the user go — no popup, no
107
+ * browser prompt. Works even with `autosave={false}`. If the draft can't be
108
+ * stored (e.g. the document is over `autosaveMaxBytes`) `confirmDiscard()` falls
109
+ * back to the popup, so work is never lost silently;
110
+ * - `'off'`: no guard; the user is never asked.
111
+ */
112
+ navigationGuard?: NavigationGuardMode;
113
+ /** Called when a saved draft was loaded into the editor (banner Restore, or `restoreDraft="auto"`). */
114
+ onDraftRestored?: (draft: {
115
+ documentId: string;
116
+ savedAt: number;
117
+ }) => void;
118
+ /** Debounce delay before writing an autosave draft, in ms. Default `750`. */
119
+ autosaveDelayMs?: number;
120
+ /**
121
+ * Skips (rather than throwing) an autosave write whose JSON would exceed
122
+ * this size — `localStorage` has a shared ~5-10MB per-origin ceiling, so a
123
+ * single document with embedded base64 images must not be allowed to
124
+ * autosave past a sane limit. Default `2_000_000` (~2MB).
125
+ */
126
+ autosaveMaxBytes?: number;
127
+ /**
128
+ * How many drafts to keep in the browser, across all documents; the oldest
129
+ * beyond this are deleted as new ones are written (this editor's own draft
130
+ * is never pruned). Default `20`.
131
+ */
132
+ autosaveMaxDrafts?: number;
73
133
  }
74
134
  export interface EditorRef {
75
135
  getContent(format: FormatId): string;
@@ -1 +1 @@
1
- {"version":3,"file":"EditorRoot.d.ts","sourceRoot":"","sources":["../src/EditorRoot.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAU1D,OAAO,KAAK,EAAe,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAyB,KAAK,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AACvF,OAAO,EAAwB,KAAK,mBAAmB,EAAE,KAAK,uBAAuB,EAAE,MAAM,2B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MAAM,WAAW,SAAS;IACxB,UAAU,CAAC,MAAM,EAAE,QAAQ,GAAG,MAAM,CAAC;IACrC,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,GAAG,IAAI,CAAC;IAClD,iBAAiB,IAAI,OAAO,CAAC;IAC7B,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IACnC,KAAK,IAAI,IAAI,CAAC;CACf;AAQD,eAAO,MAAM,UAAU,uGA8WrB,CAAC"}
@@ -7,6 +7,8 @@ import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
7
7
  import { ListPlugin } from '@lexical/react/LexicalListPlugin';
8
8
  import { CheckListPlugin } from '@lexical/react/LexicalCheckListPlugin';
9
9
  import { LinkPlugin } from '@lexical/react/LexicalLinkPlugin';
10
+ import { TablePlugin } from '@lexical/react/LexicalTablePlugin';
11
+ import { HorizontalRulePlugin } from '@lexical/react/LexicalHorizontalRulePlugin';
10
12
  import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
11
13
  import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
12
14
  import { defaultFormatRegistry } from '@inshapardaz/likhari-converters';
@@ -17,19 +19,31 @@ import { EditorThemeProvider } from './theme/EditorThemeProvider.js';
17
19
  import { Toolbar } from './components/Toolbar.js';
18
20
  import { injectUrduWebFontsCss } from './fonts/index.js';
19
21
  import { LinkPastePlugin } from './plugins/LinkPastePlugin.js';
22
+ import { DraftRestore } from './components/DraftRestore.js';
23
+ import { LeaveDialog } from './components/LeaveDialog.js';
24
+ import { clearDraft, createDraftId, hasDraftContent, pruneDrafts, writeDraft, } from './persistence/draftStorage.js';
20
25
  import { ImageOptionsContext } from './image/ImageOptionsContext.js';
21
26
  import { PortalTargetContext } from './PortalTargetContext.js';
22
27
  import { UiStringsContext, getStrings } from './i18n/index.js';
28
+ const DEFAULT_AUTOSAVE_DELAY_MS = 750;
29
+ const DEFAULT_AUTOSAVE_MAX_BYTES = 2000000;
30
+ const DEFAULT_AUTOSAVE_MAX_DRAFTS = 20;
23
31
  function initialEditorStateJson(initialContent) {
24
32
  if (!initialContent)
25
33
  return undefined;
26
34
  const state = defaultFormatRegistry.parse(initialContent.format, initialContent.value);
27
35
  return JSON.stringify(state);
28
36
  }
29
- export const EditorRoot = forwardRef(function EditorRoot({ documentId, initialContent, featureConfig, featurePreset, theme, colorScheme, accentColor, locale = 'en', placeholder, height = '480px', onChange, onSave, showSave = Boolean(onSave), onImageUpload, fetchImage, fontOptions, }, ref) {
37
+ export const EditorRoot = forwardRef(function EditorRoot({ documentId, initialContent, featureConfig, featurePreset, theme, colorScheme, accentColor, locale = 'en', placeholder, height = '480px', onChange, onSave, showSave = Boolean(onSave), onImageUpload, fetchImage, fontOptions, autosave = true, restoreDraft = 'prompt', navigationGuard = 'confirm', onDraftRestored, autosaveDelayMs = DEFAULT_AUTOSAVE_DELAY_MS, autosaveMaxBytes = DEFAULT_AUTOSAVE_MAX_BYTES, autosaveMaxDrafts = DEFAULT_AUTOSAVE_MAX_DRAFTS, }, ref) {
30
38
  const config = useMemo(() => resolveFeatureConfig(featureConfig, featurePreset), [featureConfig, featurePreset]);
31
39
  const strings = useMemo(() => getStrings(locale), [locale]);
32
40
  const resolvedPlaceholder = placeholder ?? strings.editor.placeholder;
41
+ // The draft's storage key: the host's documentId, else — so editors without
42
+ // one never overwrite each other — a unique id generated for this editor (or
43
+ // the id of an anonymous draft the user restored into it).
44
+ const [generatedDraftId] = useState(createDraftId);
45
+ const [adoptedDraftId, setAdoptedDraftId] = useState(null);
46
+ const draftId = documentId ?? adoptedDraftId ?? generatedDraftId;
33
47
  // The urdu-web-fonts stylesheets are needed for the font dropdown and for
34
48
  // RTL content, whose canvas font (editor.css) is one of those families.
35
49
  useEffect(() => {
@@ -47,17 +61,136 @@ export const EditorRoot = forwardRef(function EditorRoot({ documentId, initialCo
47
61
  const editorStateRef = useRef(null);
48
62
  const lastSavedJsonRef = useRef(null);
49
63
  const [isDirty, setIsDirty] = useState(false);
64
+ const isDirtyRef = useRef(isDirty);
65
+ isDirtyRef.current = isDirty;
66
+ const autosaveTimerRef = useRef(null);
67
+ // The latest change not yet written, so unload / unmount can flush it.
68
+ const pendingDraftRef = useRef(null);
69
+ const flushDraft = () => {
70
+ if (autosaveTimerRef.current) {
71
+ clearTimeout(autosaveTimerRef.current);
72
+ autosaveTimerRef.current = null;
73
+ }
74
+ const pending = pendingDraftRef.current;
75
+ pendingDraftRef.current = null;
76
+ if (!pending)
77
+ return;
78
+ // A document that is blank again isn't worth a draft.
79
+ if (hasDraftContent(pending.json)) {
80
+ writeDraft(pending.id, pending.json, autosaveMaxBytes);
81
+ pruneDrafts(autosaveMaxDrafts, [pending.id]);
82
+ }
83
+ else {
84
+ clearDraft(pending.id);
85
+ }
86
+ };
87
+ const flushDraftRef = useRef(flushDraft);
88
+ flushDraftRef.current = flushDraft;
89
+ /** Writes the latest content as a draft now, without waiting out the debounce.
90
+ * Returns whether it is safely stored (or there was nothing worth storing). */
91
+ const saveDraftNow = () => {
92
+ if (autosaveTimerRef.current) {
93
+ clearTimeout(autosaveTimerRef.current);
94
+ autosaveTimerRef.current = null;
95
+ }
96
+ const latest = editorStateRef.current ? JSON.stringify(editorStateRef.current.toJSON()) : pendingDraftRef.current?.json;
97
+ pendingDraftRef.current = null;
98
+ if (!latest)
99
+ return true;
100
+ // A blank document isn't worth a draft.
101
+ if (!hasDraftContent(latest)) {
102
+ clearDraft(draftId);
103
+ return true;
104
+ }
105
+ const stored = writeDraft(draftId, latest, autosaveMaxBytes);
106
+ if (stored)
107
+ pruneDrafts(autosaveMaxDrafts, [draftId]);
108
+ return stored;
109
+ };
110
+ const saveDraftNowRef = useRef(saveDraftNow);
111
+ saveDraftNowRef.current = saveDraftNow;
112
+ const navigationGuardRef = useRef(navigationGuard);
113
+ navigationGuardRef.current = navigationGuard;
114
+ const autosaveRef = useRef(autosave);
115
+ autosaveRef.current = autosave;
116
+ // The in-editor "leave?" popup behind confirmDiscard().
117
+ const [leavePrompt, setLeavePrompt] = useState(null);
118
+ const leaveResolveRef = useRef(null);
119
+ const settleLeave = (canLeave) => {
120
+ const resolve = leaveResolveRef.current;
121
+ leaveResolveRef.current = null;
122
+ setLeavePrompt(null);
123
+ resolve?.(canLeave);
124
+ };
125
+ const askToLeave = (draftFailed = false) => new Promise((resolve) => {
126
+ leaveResolveRef.current?.(false); // a second call supersedes an unanswered one
127
+ leaveResolveRef.current = resolve;
128
+ setLeavePrompt({ draftFailed });
129
+ });
130
+ const confirmDiscardImpl = async () => {
131
+ if (!isDirtyRef.current || navigationGuard === 'off')
132
+ return true;
133
+ if (navigationGuard === 'save-draft') {
134
+ if (saveDraftNow())
135
+ return true;
136
+ return askToLeave(true);
137
+ }
138
+ return askToLeave();
139
+ };
140
+ const confirmDiscardRef = useRef(confirmDiscardImpl);
141
+ confirmDiscardRef.current = confirmDiscardImpl;
142
+ // An unanswered popup must not leave a caller's promise hanging if the editor goes away.
143
+ useEffect(() => () => leaveResolveRef.current?.(false), []);
144
+ // Computed once, before the first autosave write could possibly run, so
145
+ // the restore-prompt plugin below can tell a stored draft that's merely
146
+ // identical to the initial content apart (no prompt needed) from one that
147
+ // actually represents newer, unsaved work.
148
+ const initialContentJsonRef = useRef(undefined);
149
+ if (initialContentJsonRef.current === undefined) {
150
+ initialContentJsonRef.current = initialEditorStateJson(initialContent);
151
+ }
50
152
  const initialConfig = useMemo(() => ({
51
153
  namespace: `likhari-editor-${documentId ?? 'anonymous'}`,
52
154
  nodes: EDITOR_NODES,
53
155
  theme: editorTheme,
54
- editorState: initialEditorStateJson(initialContent),
156
+ editorState: initialContentJsonRef.current,
55
157
  onError(error) {
56
158
  throw error;
57
159
  },
58
160
  }),
59
161
  // eslint-disable-next-line react-hooks/exhaustive-deps
60
162
  []);
163
+ // beforeunload (lexical-editor-spec.md §6.4): the automatic half of the
164
+ // navigation guard — hasUnsavedChanges()/confirmDiscard() below are the
165
+ // imperative half a host's own router guard calls for in-app navigation,
166
+ // which the editor can't intercept on its own.
167
+ useEffect(() => {
168
+ if (typeof window === 'undefined')
169
+ return;
170
+ const handleBeforeUnload = (event) => {
171
+ // Write any edit still waiting out the debounce before the page goes.
172
+ flushDraftRef.current();
173
+ if (!isDirtyRef.current)
174
+ return;
175
+ const guard = navigationGuardRef.current;
176
+ if (guard === 'off')
177
+ return;
178
+ // The work is saved as a draft (restorable from the banner / drafts list
179
+ // when the page is opened again), so there is nothing to warn about and
180
+ // the browser's prompt is skipped. It only appears as a last resort, when
181
+ // no draft could be stored (autosave off, document too large, storage
182
+ // unavailable) — a page can't customise or replace it, and it is the only
183
+ // thing between the user and silently losing their work.
184
+ if ((guard === 'save-draft' || autosaveRef.current) && saveDraftNowRef.current())
185
+ return;
186
+ event.preventDefault();
187
+ event.returnValue = '';
188
+ };
189
+ window.addEventListener('beforeunload', handleBeforeUnload);
190
+ return () => window.removeEventListener('beforeunload', handleBeforeUnload);
191
+ }, []);
192
+ // Unmounting (e.g. in-app navigation) also writes what is still pending.
193
+ useEffect(() => () => flushDraftRef.current(), []);
61
194
  useImperativeHandle(ref, () => ({
62
195
  getContent(format) {
63
196
  if (!editorStateRef.current)
@@ -77,23 +210,35 @@ export const EditorRoot = forwardRef(function EditorRoot({ documentId, initialCo
77
210
  hasUnsavedChanges() {
78
211
  return isDirty;
79
212
  },
80
- async confirmDiscard() {
81
- if (!isDirty)
82
- return true;
83
- if (typeof window === 'undefined')
84
- return true;
85
- return window.confirm(strings.editor.confirmDiscard);
213
+ confirmDiscard() {
214
+ return confirmDiscardRef.current();
86
215
  },
87
216
  focus() {
88
217
  rootElementRef.current?.focus();
89
218
  },
90
- }), [isDirty, strings]);
219
+ }), [isDirty]);
91
220
  const rootElementRef = useRef(null);
92
221
  const handleChange = (state) => {
93
222
  editorStateRef.current = state;
94
223
  const json = JSON.stringify(state.toJSON());
95
224
  setIsDirty(json !== lastSavedJsonRef.current);
96
225
  onChange?.(state.toJSON());
226
+ if (autosave) {
227
+ pendingDraftRef.current = { id: draftId, json };
228
+ if (autosaveTimerRef.current)
229
+ clearTimeout(autosaveTimerRef.current);
230
+ autosaveTimerRef.current = setTimeout(flushDraft, autosaveDelayMs);
231
+ }
232
+ };
233
+ /** A draft was restored into the editor: that content is unsaved work. */
234
+ const handleDraftRestored = (entry) => {
235
+ setIsDirty(true);
236
+ if (documentId && entry.id === documentId)
237
+ onDraftRestored?.({ documentId, savedAt: entry.draft.savedAt });
238
+ // Without a documentId the restored draft becomes this editor's own, so
239
+ // later edits update it instead of piling up copies.
240
+ if (!documentId)
241
+ setAdoptedDraftId(entry.id);
97
242
  };
98
243
  const handleSave = () => {
99
244
  if (!editorStateRef.current)
@@ -103,6 +248,15 @@ export const EditorRoot = forwardRef(function EditorRoot({ documentId, initialCo
103
248
  const content = defaultFormatRegistry.serialize(format, json);
104
249
  lastSavedJsonRef.current = JSON.stringify(json);
105
250
  setIsDirty(false);
251
+ // A successful explicit save supersedes any in-progress/queued autosave
252
+ // draft — don't let a stale one linger and falsely prompt to "restore"
253
+ // older content next time this document is opened (§6.2).
254
+ if (autosaveTimerRef.current) {
255
+ clearTimeout(autosaveTimerRef.current);
256
+ autosaveTimerRef.current = null;
257
+ }
258
+ pendingDraftRef.current = null;
259
+ clearDraft(draftId);
106
260
  onSave?.(content, format);
107
261
  };
108
262
  const dir = locale === 'en' ? 'ltr' : 'rtl';
@@ -111,5 +265,24 @@ export const EditorRoot = forwardRef(function EditorRoot({ documentId, initialCo
111
265
  // rather than colliding on a shared one.
112
266
  const portalTargetId = useId();
113
267
  const portalTargetSelector = `#${CSS.escape(portalTargetId)}`;
114
- return (_jsx(EditorThemeProvider, { theme: theme, colorScheme: colorScheme, accentColor: accentColor, scopeElementId: portalTargetId, children: _jsxs("div", { className: "likhari-root", dir: dir, ref: rootElementRef, "data-document-id": documentId, style: { height: typeof height === 'number' ? `${height}px` : height }, children: [_jsx("div", { id: portalTargetId, className: "likhari-portal-target" }), _jsx(PortalTargetContext.Provider, { value: portalTargetSelector, children: _jsx(UiStringsContext.Provider, { value: strings, children: _jsx(ImageOptionsContext.Provider, { value: imageOptions, children: _jsxs(LexicalComposer, { initialConfig: initialConfig, children: [_jsx(Toolbar, { config: config, onSave: handleSave, isDirty: isDirty, showSave: showSave, fontOptions: fontOptions, direction: dir, locale: locale }), _jsx("div", { className: "likhari-canvas", children: _jsx(RichTextPlugin, { contentEditable: _jsx(ContentEditable, { className: "likhari-content-editable", dir: dir, "aria-label": strings.editor.contentLabel }), placeholder: _jsx("div", { className: "likhari-placeholder", children: resolvedPlaceholder }), ErrorBoundary: LexicalErrorBoundary }) }), config.history && _jsx(HistoryPlugin, {}), (config.lists.bullet || config.lists.numbered || config.lists.check) && _jsx(ListPlugin, {}), config.lists.check && _jsx(CheckListPlugin, {}), config.links && _jsx(LinkPlugin, {}), config.links && _jsx(LinkPastePlugin, {}), _jsx(OnChangePlugin, { onChange: handleChange })] }) }) }) })] }) }));
268
+ return (_jsx(EditorThemeProvider, { theme: theme, colorScheme: colorScheme, accentColor: accentColor, scopeElementId: portalTargetId, children: _jsxs("div", { className: "likhari-root", dir: dir, ref: rootElementRef, "data-document-id": documentId, style: { height: typeof height === 'number' ? `${height}px` : height }, children: [_jsx("div", { id: portalTargetId, className: "likhari-portal-target" }), _jsx(PortalTargetContext.Provider, { value: portalTargetSelector, children: _jsxs(UiStringsContext.Provider, { value: strings, children: [_jsx(ImageOptionsContext.Provider, { value: imageOptions, children: _jsxs(LexicalComposer, { initialConfig: initialConfig, children: [_jsx(Toolbar, { config: config, onSave: handleSave, isDirty: isDirty, showSave: showSave, fontOptions: fontOptions, direction: dir, locale: locale, drafts: autosave
269
+ ? { currentId: draftId, maxBytes: autosaveMaxBytes, adoptOnRestore: !documentId, onRestored: handleDraftRestored }
270
+ : undefined }), documentId && (_jsx(DraftRestore, { draftId: documentId, mode: restoreDraft, initialJson: initialContentJsonRef.current, locale: locale, onRestored: handleDraftRestored })), _jsx("div", { className: "likhari-canvas", children: _jsx(RichTextPlugin, { contentEditable: _jsx(ContentEditable, { className: "likhari-content-editable", dir: dir, "aria-label": strings.editor.contentLabel }), placeholder: _jsx("div", { className: "likhari-placeholder", children: resolvedPlaceholder }), ErrorBoundary: LexicalErrorBoundary }) }), config.history && _jsx(HistoryPlugin, {}), (config.lists.bullet || config.lists.numbered || config.lists.check) && _jsx(ListPlugin, {}), config.lists.check && _jsx(CheckListPlugin, {}), config.links && _jsx(LinkPlugin, {}), config.links && _jsx(LinkPastePlugin, {}), config.tables && _jsx(TablePlugin, { hasCellMerge: false, hasTabHandler: true }), config.blocks.horizontalRule && _jsx(HorizontalRulePlugin, {}), _jsx(OnChangePlugin, { onChange: handleChange })] }) }), _jsx(LeaveDialog, { opened: leavePrompt !== null, canSave: Boolean(onSave), canSaveDraft: autosave || navigationGuard === 'save-draft', draftFailed: leavePrompt?.draftFailed ?? false, onSave: () => {
271
+ handleSave();
272
+ settleLeave(true);
273
+ }, onSaveDraft: () => {
274
+ if (saveDraftNow())
275
+ settleLeave(true);
276
+ else
277
+ setLeavePrompt({ draftFailed: true });
278
+ }, onDiscard: () => {
279
+ // The user chose to drop this work, so no draft of it should linger either.
280
+ if (autosaveTimerRef.current) {
281
+ clearTimeout(autosaveTimerRef.current);
282
+ autosaveTimerRef.current = null;
283
+ }
284
+ pendingDraftRef.current = null;
285
+ clearDraft(draftId);
286
+ settleLeave(true);
287
+ }, onCancel: () => settleLeave(false) })] }) })] }) }));
115
288
  });
@@ -0,0 +1,24 @@
1
+ import { type DraftEntry } from '../persistence/draftStorage.js';
2
+ import type { Locale } from '../i18n/index.js';
3
+ /** What to do on mount with a stored draft of this document that is newer than the initial content. */
4
+ export type DraftRestoreMode = 'prompt' | 'auto' | 'off';
5
+ export interface DraftRestoreProps {
6
+ /** The host's `documentId` — the key the draft is stored under. */
7
+ draftId: string;
8
+ mode: DraftRestoreMode;
9
+ /** The Lexical JSON the editor started with; a draft identical to it isn't offered. */
10
+ initialJson?: string;
11
+ locale: Locale;
12
+ onRestored: (entry: DraftEntry) => void;
13
+ }
14
+ /**
15
+ * On mount, handles a draft of this document newer than the initial content
16
+ * (lexical-editor-spec.md §6.2), per `mode`:
17
+ * - `prompt` (default): a banner — Restore, Ignore (kept in the drafts list,
18
+ * since new edits would otherwise overwrite it) or Remove. Never picks silently.
19
+ * - `auto`: loads the draft straight away, no banner.
20
+ * - `off`: leaves the editor on its initial content, but moves the draft aside
21
+ * as an earlier version so new edits can't overwrite it unseen.
22
+ */
23
+ export declare function DraftRestore({ draftId, mode, initialJson, locale, onRestored }: DraftRestoreProps): import("react").JSX.Element | null;
24
+ //# sourceMappingURL=DraftRestore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DraftRestore.d.ts","sourceRoot":"","sources":["../../src/components/DraftRestore.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAwD,KAAK,UAAU,EAAoB,MAAM,6BAA6B,CAAC;AAGtI,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEtC,uGAAuG;AACvG,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,CAAC;AAEzD,MAAM,WAAW,iBAAiB;IAChC,mEAAmE;IACnE,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,gBAAgB,CAAC;IACvB,uFAAuF;IACvF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;CACzC;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,iBAAiB,sCA8DjG"}
@@ -0,0 +1,61 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import { IconHistory } from '@tabler/icons-react';
4
+ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
5
+ import { archiveDraft, clearDraft, hasDraftContent, readDraft } from '../persistence/draftStorage.js';
6
+ import { applyDraftToEditor, formatDraftTime } from '../persistence/draftUi.js';
7
+ import { useUiStrings } from '../i18n/useStrings.js';
8
+ /**
9
+ * On mount, handles a draft of this document newer than the initial content
10
+ * (lexical-editor-spec.md §6.2), per `mode`:
11
+ * - `prompt` (default): a banner — Restore, Ignore (kept in the drafts list,
12
+ * since new edits would otherwise overwrite it) or Remove. Never picks silently.
13
+ * - `auto`: loads the draft straight away, no banner.
14
+ * - `off`: leaves the editor on its initial content, but moves the draft aside
15
+ * as an earlier version so new edits can't overwrite it unseen.
16
+ */
17
+ export function DraftRestore({ draftId, mode, initialJson, locale, onRestored }) {
18
+ const [editor] = useLexicalComposerContext();
19
+ const strings = useUiStrings();
20
+ const [draft, setDraft] = useState(() => {
21
+ const stored = readDraft(draftId);
22
+ return stored && hasDraftContent(stored.json) && stored.json !== initialJson ? stored : null;
23
+ });
24
+ const handled = useRef(false);
25
+ const restore = () => {
26
+ if (!draft)
27
+ return;
28
+ if (applyDraftToEditor(editor, draft.json))
29
+ onRestored({ id: draftId, draft });
30
+ // A corrupt or incompatible draft can't be restored: drop the banner and keep the initial content.
31
+ setDraft(null);
32
+ };
33
+ const ignore = () => {
34
+ // Move it aside, so edits from here on can't overwrite it unseen.
35
+ if (archiveDraft(draftId))
36
+ clearDraft(draftId);
37
+ setDraft(null);
38
+ };
39
+ // Non-interactive modes act once, on mount.
40
+ useEffect(() => {
41
+ if (handled.current || !draft)
42
+ return;
43
+ handled.current = true;
44
+ if (mode === 'auto')
45
+ restore();
46
+ else if (mode === 'off')
47
+ ignore();
48
+ // Deliberately runs once on mount only.
49
+ // eslint-disable-next-line react-hooks/exhaustive-deps
50
+ }, []);
51
+ const remove = () => {
52
+ clearDraft(draftId);
53
+ setDraft(null);
54
+ };
55
+ if (!draft || mode !== 'prompt')
56
+ return null;
57
+ // Plain elements styled with the editor's own tokens (editor.css): Mantine's
58
+ // theme variables are scoped to the portal target, so an in-flow Mantine
59
+ // button here would fall back to Mantine's default blue.
60
+ return (_jsxs("div", { className: "likhari-draft-banner", role: "status", "aria-live": "polite", children: [_jsxs("div", { className: "likhari-draft-banner-message", children: [_jsx(IconHistory, { size: 18, stroke: 1.75, "aria-hidden": "true" }), _jsx("span", { children: strings.drafts.bannerMessage(formatDraftTime(draft.savedAt, locale)) })] }), _jsxs("div", { className: "likhari-draft-banner-actions", children: [_jsx("button", { type: "button", className: "likhari-draft-banner-button", "data-variant": "primary", onClick: restore, children: strings.drafts.restore }), _jsx("button", { type: "button", className: "likhari-draft-banner-button", onClick: ignore, children: strings.drafts.ignore }), _jsx("button", { type: "button", className: "likhari-draft-banner-button", "data-variant": "danger", onClick: remove, children: strings.drafts.remove })] })] }));
61
+ }
@@ -0,0 +1,25 @@
1
+ import { type DraftEntry } from '../persistence/draftStorage.js';
2
+ import type { Locale } from '../i18n/index.js';
3
+ /** What the toolbar needs to offer the drafts list. */
4
+ export interface DraftsToolbarOptions {
5
+ /** The key this editor's own autosave writes to. */
6
+ currentId: string;
7
+ /** Size cap for archiving the content a restore replaces. */
8
+ maxBytes: number;
9
+ /** Without a `documentId`, a restored draft becomes this editor's draft, so later edits update it instead of duplicating it. */
10
+ adoptOnRestore: boolean;
11
+ onRestored: (entry: DraftEntry) => void;
12
+ }
13
+ export interface DraftsDialogProps extends DraftsToolbarOptions {
14
+ opened: boolean;
15
+ locale: Locale;
16
+ onClose: () => void;
17
+ }
18
+ /**
19
+ * Every autosaved draft in this browser (all documents, and the earlier
20
+ * versions kept when a restore prompt was ignored), newest first, each with
21
+ * Restore and Delete. Restoring over content that differs asks first, and keeps
22
+ * the replaced content as a draft of its own, so nothing is lost either way.
23
+ */
24
+ export declare function DraftsDialog({ opened, locale, currentId, maxBytes, adoptOnRestore, onRestored, onClose }: DraftsDialogProps): import("react").JSX.Element;
25
+ //# sourceMappingURL=DraftsDialog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DraftsDialog.d.ts","sourceRoot":"","sources":["../../src/components/DraftsDialog.tsx"],"names":[],"mappings":"AAGA,OAAO,EAOL,KAAK,UAAU,EAChB,MAAM,6BAA6B,CAAC;AAIrC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEtC,uDAAuD;AACvD,MAAM,WAAW,oBAAoB;IACnC,oDAAoD;IACpD,SAAS,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,QAAQ,EAAE,MAAM,CAAC;IACjB,gIAAgI;IAChI,cAAc,EAAE,OAAO,CAAC;IACxB,UAAU,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;CACzC;AAED,MAAM,WAAW,iBAAkB,SAAQ,oBAAoB;IAC7D,MAAM,EAAE,OAAO,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAID;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,EAAE,UAAU,EAAE,OAAO,EAAE,EAAE,iBAAiB,+BAmH3H"}
@@ -0,0 +1,66 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useState } from 'react';
3
+ import { Badge, Button, Group, Modal, Paper, Stack, Text } from '@mantine/core';
4
+ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
5
+ import { clearDraft, createDraftId, hasDraftContent, isGeneratedDraftId, listDrafts, writeDraft, } from '../persistence/draftStorage.js';
6
+ import { applyDraftToEditor, formatDraftTime } from '../persistence/draftUi.js';
7
+ import { useUiStrings } from '../i18n/useStrings.js';
8
+ import { usePortalTarget } from '../PortalTargetContext.js';
9
+ /**
10
+ * Every autosaved draft in this browser (all documents, and the earlier
11
+ * versions kept when a restore prompt was ignored), newest first, each with
12
+ * Restore and Delete. Restoring over content that differs asks first, and keeps
13
+ * the replaced content as a draft of its own, so nothing is lost either way.
14
+ */
15
+ export function DraftsDialog({ opened, locale, currentId, maxBytes, adoptOnRestore, onRestored, onClose }) {
16
+ const [editor] = useLexicalComposerContext();
17
+ const strings = useUiStrings();
18
+ const portalTarget = usePortalTarget();
19
+ const [entries, setEntries] = useState([]);
20
+ const [pending, setPending] = useState(null);
21
+ useEffect(() => {
22
+ if (opened) {
23
+ setEntries(listDrafts());
24
+ setPending(null);
25
+ }
26
+ }, [opened]);
27
+ const currentJson = () => JSON.stringify(editor.getEditorState().toJSON());
28
+ const restore = (entry) => {
29
+ const before = currentJson();
30
+ // Keep what is being replaced, as a draft of its own.
31
+ if (before !== entry.draft.json && hasDraftContent(before)) {
32
+ writeDraft(createDraftId(), before, maxBytes, currentId);
33
+ if (adoptOnRestore)
34
+ clearDraft(currentId);
35
+ }
36
+ if (applyDraftToEditor(editor, entry.draft.json)) {
37
+ onRestored(entry);
38
+ onClose();
39
+ }
40
+ };
41
+ const requestRestore = (entry) => {
42
+ const before = currentJson();
43
+ // Replacing real, different content is confirmed first (inline, not a window.confirm).
44
+ if (before !== entry.draft.json && hasDraftContent(before))
45
+ setPending({ id: entry.id, action: 'restore' });
46
+ else
47
+ restore(entry);
48
+ };
49
+ const remove = (entry) => {
50
+ clearDraft(entry.id);
51
+ setEntries(listDrafts());
52
+ setPending(null);
53
+ };
54
+ const label = (entry) => {
55
+ const source = entry.draft.sourceId;
56
+ if (source)
57
+ return isGeneratedDraftId(source) ? strings.drafts.earlierUntitled : strings.drafts.earlierVersionOf(source);
58
+ return isGeneratedDraftId(entry.id) ? strings.drafts.untitled : strings.drafts.documentLabel(entry.id);
59
+ };
60
+ return (_jsx(Modal, { opened: opened, onClose: onClose, title: strings.drafts.dialogTitle, centered: true, size: "lg", portalProps: portalTarget ? { target: portalTarget } : undefined, children: _jsxs(Stack, { gap: "sm", children: [_jsx(Text, { size: "sm", c: "dimmed", children: strings.drafts.intro }), entries.length === 0 && _jsx(Text, { size: "sm", children: strings.drafts.empty }), entries.map((entry) => {
61
+ const isCurrent = entry.id === currentId;
62
+ const isPending = pending?.id === entry.id;
63
+ return (_jsx(Paper, { withBorder: true, p: "sm", radius: "sm", "data-draft-id": entry.id, children: _jsxs(Stack, { gap: 6, children: [_jsxs(Group, { justify: "space-between", wrap: "nowrap", align: "flex-start", children: [_jsx(Text, { size: "sm", lineClamp: 2, style: { flex: 1, wordBreak: 'break-word' }, children: entry.draft.preview || strings.drafts.noText }), isCurrent && _jsx(Badge, { variant: "light", children: strings.drafts.thisDocument })] }), _jsxs(Text, { size: "xs", c: "dimmed", children: [label(entry), " \u00B7 ", strings.drafts.savedAt(formatDraftTime(entry.draft.savedAt, locale)), " \u00B7", ' ', strings.drafts.size(Math.max(1, Math.round(entry.draft.json.length / 1024)))] }), !isCurrent &&
64
+ (isPending ? (_jsxs(Group, { gap: "xs", align: "center", children: [_jsx(Text, { size: "sm", children: pending.action === 'restore' ? strings.drafts.replacePrompt : strings.drafts.deletePrompt }), _jsx(Button, { size: "compact-sm", color: pending.action === 'delete' ? 'red' : undefined, onClick: () => (pending.action === 'restore' ? restore(entry) : remove(entry)), children: pending.action === 'restore' ? strings.drafts.replace : strings.drafts.delete }), _jsx(Button, { size: "compact-sm", variant: "default", onClick: () => setPending(null), children: strings.common.cancel })] })) : (_jsxs(Group, { gap: "xs", children: [_jsx(Button, { size: "compact-sm", onClick: () => requestRestore(entry), children: strings.drafts.restore }), _jsx(Button, { size: "compact-sm", variant: "subtle", color: "red", onClick: () => setPending({ id: entry.id, action: 'delete' }), children: strings.drafts.delete })] })))] }) }, entry.id));
65
+ }), _jsx(Group, { justify: "flex-end", children: _jsx(Button, { variant: "default", onClick: onClose, children: strings.drafts.close }) })] }) }));
66
+ }
@@ -0,0 +1,22 @@
1
+ export interface LeaveDialogProps {
2
+ opened: boolean;
3
+ /** Offer "Save" (calls the host's `onSave`, then lets the user leave). */
4
+ canSave: boolean;
5
+ /** Offer "Save draft" (keeps the work in this browser, then lets the user leave). */
6
+ canSaveDraft: boolean;
7
+ /** A "Save draft" attempt failed; explains why the dialog is still open. */
8
+ draftFailed: boolean;
9
+ onSave: () => void;
10
+ onSaveDraft: () => void;
11
+ onDiscard: () => void;
12
+ /** Cancel: stay on the page. Escape, the close button and clicking outside do the same. */
13
+ onCancel: () => void;
14
+ }
15
+ /**
16
+ * The in-editor popup behind `EditorRef.confirmDiscard()`: what to do with
17
+ * unsaved changes before leaving. It replaces `window.confirm()`, which can't
18
+ * be styled, translated per editor, or offer more than OK/Cancel. (The browser's
19
+ * own tab-close prompt can't be replaced — see `navigationGuard`.)
20
+ */
21
+ export declare function LeaveDialog({ opened, canSave, canSaveDraft, draftFailed, onSave, onSaveDraft, onDiscard, onCancel }: LeaveDialogProps): import("react").JSX.Element;
22
+ //# sourceMappingURL=LeaveDialog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LeaveDialog.d.ts","sourceRoot":"","sources":["../../src/components/LeaveDialog.tsx"],"names":[],"mappings":"AAIA,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,OAAO,CAAC;IAChB,0EAA0E;IAC1E,OAAO,EAAE,OAAO,CAAC;IACjB,qFAAqF;IACrF,YAAY,EAAE,OAAO,CAAC;IACtB,4EAA4E;IAC5E,WAAW,EAAE,OAAO,CAAC;IACrB,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB,WAAW,EAAE,MAAM,IAAI,CAAC;IACxB,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,2FAA2F;IAC3F,QAAQ,EAAE,MAAM,IAAI,CAAC;CACtB;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,gBAAgB,+BAyCrI"}
@@ -0,0 +1,15 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Alert, Button, Group, Modal, Stack, Text } from '@mantine/core';
3
+ import { useUiStrings } from '../i18n/useStrings.js';
4
+ import { usePortalTarget } from '../PortalTargetContext.js';
5
+ /**
6
+ * The in-editor popup behind `EditorRef.confirmDiscard()`: what to do with
7
+ * unsaved changes before leaving. It replaces `window.confirm()`, which can't
8
+ * be styled, translated per editor, or offer more than OK/Cancel. (The browser's
9
+ * own tab-close prompt can't be replaced — see `navigationGuard`.)
10
+ */
11
+ export function LeaveDialog({ opened, canSave, canSaveDraft, draftFailed, onSave, onSaveDraft, onDiscard, onCancel }) {
12
+ const strings = useUiStrings();
13
+ const portalTarget = usePortalTarget();
14
+ return (_jsx(Modal, { opened: opened, onClose: onCancel, title: strings.leaveDialog.title, centered: true, size: "lg", portalProps: portalTarget ? { target: portalTarget } : undefined, children: _jsxs(Stack, { gap: "md", children: [_jsx(Text, { size: "sm", children: strings.leaveDialog.message }), draftFailed && (_jsx(Alert, { color: "red", variant: "light", p: "xs", children: strings.leaveDialog.saveDraftFailed })), _jsxs(Group, { justify: "flex-end", gap: "xs", wrap: "nowrap", children: [canSave && (_jsx(Button, { size: "sm", onClick: onSave, children: strings.leaveDialog.save })), _jsx(Button, { size: "sm", variant: "outline", color: "red", onClick: onDiscard, children: strings.leaveDialog.discard }), canSaveDraft && (_jsx(Button, { size: "sm", variant: "default", onClick: onSaveDraft, children: strings.leaveDialog.saveDraft })), _jsx(Button, { size: "sm", variant: "default", onClick: onCancel, "data-autofocus": true, children: strings.common.cancel })] })] }) }));
15
+ }
@@ -0,0 +1,17 @@
1
+ export interface TableDialogValue {
2
+ rows: number;
3
+ columns: number;
4
+ headerRow: boolean;
5
+ }
6
+ export interface TableDialogProps {
7
+ opened: boolean;
8
+ onSubmit: (value: TableDialogValue) => void;
9
+ onClose: () => void;
10
+ }
11
+ /**
12
+ * Insert-table dialog: rows x columns and an optional header row. Cell
13
+ * merge/split is intentionally not offered anywhere in this dialog or the
14
+ * table it creates — see the comment on `TablePlugin` in `EditorRoot.tsx`.
15
+ */
16
+ export declare function TableDialog({ opened, onSubmit, onClose }: TableDialogProps): import("react").JSX.Element;
17
+ //# sourceMappingURL=TableDialog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TableDialog.d.ts","sourceRoot":"","sources":["../../src/components/TableDialog.tsx"],"names":[],"mappings":"AAKA,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC5C,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAOD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,gBAAgB,+BAiD1E"}