texlite 0.14.0 → 0.16.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 (77) hide show
  1. package/DESIGN.md +94 -4
  2. package/README.md +5 -2
  3. package/README.zh-CN.md +5 -2
  4. package/dist/client/assets/AdminUsers-Dyapv-3c.js +1 -0
  5. package/dist/client/assets/CitationLibraryDialog-CU7Q7r0Z.js +1 -0
  6. package/dist/client/assets/Dashboard-DsdhFENx.js +2 -0
  7. package/dist/client/assets/GitDialog-CZpnKw-J.js +3 -0
  8. package/dist/client/assets/{GitHubAccountDialog-yUPMZj-e.js → GitHubAccountDialog-CZ8O_PjD.js} +1 -1
  9. package/dist/client/assets/{HistoryDialog-CZK-cFfU.js → HistoryDialog-DWYErBwj.js} +3 -3
  10. package/dist/client/assets/LatexEditor-CssVgypt.js +141 -0
  11. package/dist/client/assets/{PdfPreview-BqohZpfh.js → PdfPreview-BjghzUb1.js} +1 -1
  12. package/dist/client/assets/{ProjectIconPickerDialog-63_apW1i.js → ProjectIconPickerDialog-CqRmgFBM.js} +1 -1
  13. package/dist/client/assets/{ProjectNavigationDialogs-D8I4OJQB.js → ProjectNavigationDialogs-BZxI3PJO.js} +1 -1
  14. package/dist/client/assets/ProjectSettings-CZE_xDKn.js +1 -0
  15. package/dist/client/assets/ProjectWorkspace-CAX3qEYr.js +32 -0
  16. package/dist/client/assets/{SelectionHistoryDialog-DiYNdIe5.js → SelectionHistoryDialog-CR5c3I8k.js} +2 -2
  17. package/dist/client/assets/{SystemMetricsDialog-B9cIXfPM.js → SystemMetricsDialog-DDpFwgXh.js} +1 -1
  18. package/dist/client/assets/{TagManagementDialog-DqGTPckP.js → TagManagementDialog-CXLA9h_j.js} +1 -1
  19. package/dist/client/assets/WordCountDialog-DUyR24vv.js +1 -0
  20. package/dist/client/assets/check-CwBYzomT.js +1 -0
  21. package/dist/client/assets/chevron-up-D5lCNKlk.js +1 -0
  22. package/dist/client/assets/chktex-CRkLYKcV.js +3 -0
  23. package/dist/client/assets/{citationLibrary-ZeQPCv5O.js → citationLibrary-C9WnXB-1.js} +2 -2
  24. package/dist/client/assets/{external-link-DtHz2OWn.js → external-link-C9Td1CCj.js} +1 -1
  25. package/dist/client/assets/{github-B3ClW0wI.js → github-D-JDXb-w.js} +1 -1
  26. package/dist/client/assets/{hard-drive-A2DTDrXg.js → hard-drive-Ctj3K_zx.js} +1 -1
  27. package/dist/client/assets/{index-Bgr9VmTh.js → index-9hnQ8Q9x.js} +1 -1
  28. package/dist/client/assets/index-C0qg2Ylw.css +1 -0
  29. package/dist/client/assets/index-DkpU9Fgs.js +10 -0
  30. package/dist/client/assets/index-_eYe7K9T.js +1 -0
  31. package/dist/client/assets/{minimize-2-CjavrBs6.js → minimize-2-BiVyoWZA.js} +1 -1
  32. package/dist/client/assets/{minus-417bfmnF.js → minus-Bl8l4LXq.js} +1 -1
  33. package/dist/client/assets/{plus-CCRSrXDi.js → plus-CCxK-HNt.js} +1 -1
  34. package/dist/client/assets/react-CltQJflK.js +49 -0
  35. package/dist/client/assets/{refresh-cw-0bKWvgVy.js → refresh-cw-BE8IbaHI.js} +1 -1
  36. package/dist/client/assets/{search-DhHW3xg7.js → search-CPbhRWQE.js} +1 -1
  37. package/dist/client/assets/{sigma-ggAZwYZs.js → sigma-LxGD9tK2.js} +1 -1
  38. package/dist/client/assets/spellCheck-hpm8qZTr.js +1 -0
  39. package/dist/client/assets/{tags-jYRdvWMN.js → tags-DuN89PsZ.js} +1 -1
  40. package/dist/client/assets/{type-CZnTyitQ.js → type-BiettCiY.js} +1 -1
  41. package/dist/client/assets/{x-CUwbFgRb.js → x-C_3swJOC.js} +1 -1
  42. package/dist/client/index.html +4 -4
  43. package/dist/client/texlite-icon.svg +8 -0
  44. package/dist/server/anchors.js +57 -96
  45. package/dist/server/auth.js +0 -3
  46. package/dist/server/chktex.js +3 -4
  47. package/dist/server/collaboration.js +34 -1
  48. package/dist/server/db.js +9 -1
  49. package/dist/server/i18n.js +4 -0
  50. package/dist/server/latexCompletion.js +11 -88
  51. package/dist/server/projectOutline.js +4 -39
  52. package/dist/server/projectSearch.js +0 -4
  53. package/dist/server/routes/citations.js +22 -0
  54. package/dist/server/routes/comments.js +4 -4
  55. package/dist/server/routes/projectShared.js +11 -2
  56. package/dist/server/routes/users.js +21 -3
  57. package/dist/shared/bibtexReferences.js +5 -1
  58. package/dist/shared/latexCompletion.js +1 -0
  59. package/dist/shared/latexReferences.js +13 -3
  60. package/dist/shared/latexSymbols.js +77 -0
  61. package/dist/shared/sourceCommentAnchors.js +128 -0
  62. package/package.json +1 -1
  63. package/dist/client/assets/AdminUsers-BMwfVHyu.js +0 -1
  64. package/dist/client/assets/CitationLibraryDialog-D_GkXecF.js +0 -1
  65. package/dist/client/assets/Dashboard-DhKiB4Lp.js +0 -2
  66. package/dist/client/assets/GitDialog-DHwqaGWR.js +0 -3
  67. package/dist/client/assets/LatexEditor-BuLjoc1X.js +0 -141
  68. package/dist/client/assets/ProjectSettings-ChIKBc0N.js +0 -1
  69. package/dist/client/assets/ProjectWorkspace-D8vBa8aq.js +0 -32
  70. package/dist/client/assets/WordCountDialog-B0pBzLsg.js +0 -1
  71. package/dist/client/assets/check-6jrUH-ay.js +0 -1
  72. package/dist/client/assets/chktex-Cp2H8q1t.js +0 -3
  73. package/dist/client/assets/index-DNQd-LXW.css +0 -1
  74. package/dist/client/assets/index-DprUq41V.js +0 -10
  75. package/dist/client/assets/react-BVUjbTTn.js +0 -49
  76. package/dist/client/assets/spellCheck-JOkkBKD7.js +0 -1
  77. package/dist/client/assets/user-plus-DFkFh0mU.js +0 -1
@@ -3,7 +3,7 @@ import { maskLatexComments } from "../shared/latexLiterals.js";
3
3
  import { findLatexSourceIncludes } from "../shared/latexDependencies.js";
4
4
  import { forEachLatexCommand, readLatexMandatoryArguments } from "../shared/latexScanner.js";
5
5
  import { resolveLatexInclude, toLatexIncludeDirective } from "./latexDocumentGraph.js";
6
- import { listProjectFiles, listProjectFilesAsync, resolveSourcePath, safeRelativePath } from "./files.js";
6
+ import { listProjectFilesAsync, resolveSourcePath, safeRelativePath } from "./files.js";
7
7
  const levels = new Map([
8
8
  ["part", 0],
9
9
  ["chapter", 0],
@@ -12,40 +12,6 @@ const levels = new Map([
12
12
  ["subsubsection", 3],
13
13
  ["paragraph", 4]
14
14
  ]);
15
- export function buildProjectOutline(config, projectId, mainFileInput) {
16
- const mainFile = safeRelativePath(mainFileInput);
17
- return buildProjectOutlineFromFiles(config, projectId, mainFile, sourceFilePaths(listProjectFiles(config, projectId)));
18
- }
19
- function buildProjectOutlineFromFiles(config, projectId, mainFile, availableFiles) {
20
- const result = [];
21
- const visited = new Set();
22
- const visit = (filePath, importBase) => {
23
- if (visited.has(filePath) || visited.size >= 200)
24
- return;
25
- visited.add(filePath);
26
- const absolute = resolveSourcePath(config, projectId, filePath);
27
- if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile() || fs.statSync(absolute).size > 3 * 1024 * 1024)
28
- return;
29
- const content = fs.readFileSync(absolute, "utf8");
30
- for (const event of scanOutlineSource(content)) {
31
- if (event.type === "heading") {
32
- result.push({ path: filePath, line: event.line, level: event.level, title: event.title });
33
- continue;
34
- }
35
- const included = resolveLatexInclude(event.directive, importBase, availableFiles);
36
- if (included)
37
- visit(included.path, included.importBase);
38
- }
39
- };
40
- visit(mainFile, "");
41
- return result;
42
- }
43
- /** Async outline builder used by the HTTP path so large projects do not block the event loop. */
44
- export async function buildProjectOutlineAsync(config, projectId, mainFileInput) {
45
- const mainFile = safeRelativePath(mainFileInput);
46
- const availableFiles = sourceFilePaths(await listProjectFilesAsync(config, projectId));
47
- return buildProjectOutlineAsyncFromFiles(config, projectId, mainFile, availableFiles);
48
- }
49
15
  async function buildProjectOutlineAsyncFromFiles(config, projectId, mainFile, availableFiles) {
50
16
  const result = [];
51
17
  const visited = new Set();
@@ -137,10 +103,9 @@ function sourceFilePaths(entries) {
137
103
  return new Set(entries.filter((entry) => entry.type === "file").map((entry) => entry.path));
138
104
  }
139
105
  /**
140
- * Read one source file into ordered outline events. The shared scanner keeps
141
- * offsets from the original source while skipping comments and literal TeX
142
- * forms, so the synchronous and asynchronous builders cannot drift in their
143
- * interpretation of headings and arguments.
106
+ * Read one source file into ordered heading and include events. The shared
107
+ * scanner preserves original source offsets while skipping comments and
108
+ * literal TeX forms.
144
109
  */
145
110
  function scanOutlineSource(source) {
146
111
  const lineStarts = sourceLineStarts(source);
@@ -1,5 +1,4 @@
1
1
  import fs from "node:fs";
2
- import path from "node:path";
3
2
  import { listProjectFilesAsync, resolveSourcePath } from "./files.js";
4
3
  import { httpError } from "./http.js";
5
4
  const textExtension = /(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i;
@@ -112,6 +111,3 @@ function searchPattern(options) {
112
111
  const source = options.wholeWord ? `(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])` : escaped;
113
112
  return new RegExp(source, `${options.caseSensitive ? "" : "i"}gu`);
114
113
  }
115
- export function projectSearchTextFile(filePath) {
116
- return textExtension.test(path.basename(filePath));
117
- }
@@ -177,6 +177,28 @@ export function registerCitationRoutes(app, context) {
177
177
  .run(tag.id, user.id, tag.name, tag.color, now());
178
178
  return reply.code(201).send({ tag, created: true });
179
179
  });
180
+ app.patch("/api/citations/tags/:tagId", async (request, reply) => {
181
+ const user = requireUser(request, reply, db);
182
+ if (!user)
183
+ return;
184
+ const { tagId } = request.params;
185
+ const existing = db.prepare("SELECT id, name, color, user_id FROM citation_library_tags WHERE id = ? AND user_id = ?")
186
+ .get(tagId, user.id);
187
+ if (!existing)
188
+ return apiError(reply, 404, "CITATION_TAG_NOT_FOUND");
189
+ const body = request.body;
190
+ const name = body?.name === undefined ? existing.name : citationTagName(body.name);
191
+ const color = body?.color === undefined ? existing.color : body.color;
192
+ if (!tagColors.includes(color))
193
+ throw new ValidationError();
194
+ const duplicate = db.prepare("SELECT id FROM citation_library_tags WHERE user_id = ? AND name = ? COLLATE NOCASE AND id != ?")
195
+ .get(user.id, name, tagId);
196
+ if (duplicate)
197
+ return apiError(reply, 409, "CITATION_TAG_NAME_EXISTS");
198
+ db.prepare("UPDATE citation_library_tags SET name = ?, color = ? WHERE id = ? AND user_id = ?")
199
+ .run(name, color, tagId, user.id);
200
+ return { tag: { id: tagId, name, color, ownerId: user.id } };
201
+ });
180
202
  app.delete("/api/citations/tags/:tagId", async (request, reply) => {
181
203
  const user = requireUser(request, reply, db);
182
204
  if (!user)
@@ -207,10 +207,10 @@ export function registerCommentRoutes(app, context) {
207
207
  projectId: id, commentId, authorId: user.id, content, previousContent: comment.content, createdAt: changedAt
208
208
  });
209
209
  }
210
- if (typeof body.resolved === "boolean") {
211
- db.prepare("UPDATE comments SET resolved = ?, updated_at = ? WHERE id = ?")
212
- .run(body.resolved ? 1 : 0, changedAt, commentId);
213
- if (body.resolved && !comment.resolved)
210
+ if (typeof body.resolved === "boolean" && body.resolved !== Boolean(comment.resolved)) {
211
+ db.prepare("UPDATE comments SET resolved = ?, resolved_by = ?, resolved_at = ?, updated_at = ? WHERE id = ?")
212
+ .run(body.resolved ? 1 : 0, body.resolved ? user.id : null, body.resolved ? changedAt : null, changedAt, commentId);
213
+ if (body.resolved)
214
214
  markCommentMentionsResolved(db, commentId, changedAt);
215
215
  }
216
216
  })();
@@ -198,8 +198,11 @@ function commentsForScope(db, config, projectId, filePath) {
198
198
  const commentOrder = hasFileScope
199
199
  ? "c.created_at"
200
200
  : "c.file_path COLLATE NOCASE, c.start_line, c.created_at";
201
- const rows = db.prepare(`SELECT c.*, u.username AS author_username, u.display_name AS author_display_name FROM comments c
202
- LEFT JOIN users u ON u.id = c.author_id WHERE c.project_id = ?${fileClause} ORDER BY ${commentOrder}`)
201
+ const rows = db.prepare(`SELECT c.*, u.username AS author_username, u.display_name AS author_display_name,
202
+ resolver.username AS resolved_by_username, resolver.display_name AS resolved_by_display_name FROM comments c
203
+ LEFT JOIN users u ON u.id = c.author_id
204
+ LEFT JOIN users resolver ON resolver.id = c.resolved_by
205
+ WHERE c.project_id = ?${fileClause} ORDER BY ${commentOrder}`)
203
206
  .all(projectId, ...(hasFileScope ? [filePath] : []));
204
207
  if (!rows.length)
205
208
  return [];
@@ -239,12 +242,18 @@ function commentsForScope(db, config, projectId, filePath) {
239
242
  authorUsername: comment.author_username,
240
243
  authorDisplayName: comment.author_display_name,
241
244
  selectedText: comment.selected_text,
245
+ contextBefore: comment.context_before,
246
+ contextAfter: comment.context_after,
242
247
  startOffset: comment.start_offset,
243
248
  endOffset: comment.end_offset,
244
249
  startLine: offsetToLine(sourceByPath.get(comment.file_path) ?? "", comment.start_offset),
245
250
  endLine: offsetToLine(sourceByPath.get(comment.file_path) ?? "", comment.end_offset),
246
251
  content: comment.content,
247
252
  resolved: Boolean(comment.resolved),
253
+ resolvedById: comment.resolved_by,
254
+ resolvedByUsername: comment.resolved_by_username,
255
+ resolvedByDisplayName: comment.resolved_by_display_name,
256
+ resolvedAt: comment.resolved_at,
248
257
  orphaned: Boolean(comment.orphaned),
249
258
  createdAt: comment.created_at,
250
259
  updatedAt: comment.updated_at,
@@ -17,12 +17,27 @@ export function registerUserManagementRoutes(app, context) {
17
17
  app.get("/api/admin/users", async (request, reply) => {
18
18
  if (!requireAdmin(request, reply, db))
19
19
  return;
20
+ const query = request.query;
21
+ const search = typeof query.q === "string" ? query.q.trim() : "";
22
+ const requestedPage = Number(query.page ?? "1");
23
+ const pageSize = 20;
24
+ const where = search ? "WHERE (u.username LIKE ? ESCAPE '\\' OR u.display_name LIKE ? ESCAPE '\\')" : "";
25
+ const pattern = `%${search.replace(/[\\%_]/g, "\\$&")}%`;
26
+ const params = search ? [pattern, pattern] : [];
27
+ const total = db.prepare(`SELECT COUNT(*) AS count FROM users u ${where}`).get(...params).count;
28
+ const totalPages = Math.ceil(total / pageSize);
29
+ const page = Math.min(Number.isSafeInteger(requestedPage) && requestedPage > 0 ? requestedPage : 1, Math.max(1, totalPages));
20
30
  const users = db.prepare(`
21
31
  SELECT u.*,
22
32
  (SELECT COUNT(*) FROM projects p WHERE p.owner_id = u.id) AS owned_projects
23
- FROM users u ORDER BY u.created_at
24
- `).all();
25
- return { users: users.map((user) => ({ ...publicUser(user), ownedProjects: user.owned_projects })) };
33
+ FROM users u ${where}
34
+ ORDER BY u.created_at, u.username COLLATE NOCASE
35
+ LIMIT ? OFFSET ?
36
+ `).all(...params, pageSize, (page - 1) * pageSize);
37
+ return {
38
+ users: users.map((user) => ({ ...publicUser(user), ownedProjects: user.owned_projects })),
39
+ pagination: { page, pageSize, total, totalPages }
40
+ };
26
41
  });
27
42
  app.post("/api/admin/users", async (request, reply) => {
28
43
  if (!requireAdmin(request, reply, db))
@@ -56,6 +71,9 @@ export function registerUserManagementRoutes(app, context) {
56
71
  const body = request.body;
57
72
  const role = body.role === "admin" ? "admin" : body.role === "user" ? "user" : target.role;
58
73
  const disabled = typeof body.disabled === "boolean" ? Number(body.disabled) : target.disabled;
74
+ if (target.id === admin.id && (disabled || role !== "admin")) {
75
+ return apiError(reply, 400, "SELF_RESTRICT_FORBIDDEN");
76
+ }
59
77
  const canCreateProjects = typeof body.canCreateProjects === "boolean"
60
78
  ? Number(body.canCreateProjects) : target.can_create_projects;
61
79
  if (target.role === "admin" && (!role || role !== "admin" || disabled) && activeAdminCount(db) <= 1) {
@@ -36,7 +36,11 @@ function readBibtexBlock(source, start) {
36
36
  continue;
37
37
  }
38
38
  if (quoted) {
39
- if (character === "\"")
39
+ if (character === "{")
40
+ braceDepth += 1;
41
+ else if (character === "}" && braceDepth > 0)
42
+ braceDepth -= 1;
43
+ else if (character === "\"" && braceDepth === 0)
40
44
  quoted = false;
41
45
  continue;
42
46
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { findBibtexEntryKeys } from "./bibtexReferences.js";
8
8
  import { maskLatexComments } from "./latexLiterals.js";
9
- import { forEachLatexCommand, isLatexCommentStart, readLatexBalancedArgument, readLatexMandatoryArguments, readLatexOptionalArguments, skipLatexComment, skipLatexTrivia } from "./latexScanner.js";
9
+ import { forEachLatexCommand, isLatexCommentStart, isLatexEscaped, readLatexBalancedArgument, readLatexMandatoryArguments, readLatexOptionalArguments, skipLatexComment, skipLatexTrivia } from "./latexScanner.js";
10
10
  import { classifyLatexReferenceCommand } from "./latexReferenceCommands.js";
11
11
  export { findLatexBibliographyFiles, findLatexSourceIncludes } from "./latexDependencies.js";
12
12
  export { maskLatexComments } from "./latexLiterals.js";
@@ -127,8 +127,14 @@ export function findLatexReferences(source) {
127
127
  });
128
128
  return references.sort((left, right) => left.from - right.from || left.to - right.to);
129
129
  }
130
- export function latexReferenceAt(source, offset) {
131
- return findLatexReferences(source).find((reference) => offset >= reference.from && offset < reference.to) ?? null;
130
+ function hasMacroParameter(key) {
131
+ // Parameterized definitions such as \label{fig:#1} are templates, not
132
+ // concrete reference targets. Keep fixed keys in definitions discoverable.
133
+ for (let index = 0; index < key.length - 1; index += 1) {
134
+ if (key[index] === "#" && /[1-9]/.test(key[index + 1]) && !isLatexEscaped(key, index))
135
+ return true;
136
+ }
137
+ return false;
132
138
  }
133
139
  function definitionsFromLatex(source, kind) {
134
140
  const definitions = [];
@@ -138,6 +144,8 @@ function definitionsFromLatex(source, kind) {
138
144
  if (!argument)
139
145
  return;
140
146
  for (const range of keyRanges(source, argument)) {
147
+ if (hasMacroParameter(range.key))
148
+ continue;
141
149
  definitions.push({
142
150
  key: range.key,
143
151
  command: command.name,
@@ -153,6 +161,8 @@ function definitionsFromLatex(source, kind) {
153
161
  if (!argument)
154
162
  return;
155
163
  for (const range of keyRanges(source, argument)) {
164
+ if (hasMacroParameter(range.key))
165
+ continue;
156
166
  definitions.push({
157
167
  key: range.key,
158
168
  command: command.name,
@@ -0,0 +1,77 @@
1
+ import { commandSnippet, newCommandArguments, xparseCommandArguments, xparseCommandDefinitions } from "./latexCommandSnippets.js";
2
+ import { maskLatexComments, maskLatexLiteralContent } from "./latexLiterals.js";
3
+ import { findLatexReferenceDefinitions } from "./latexReferences.js";
4
+ /**
5
+ * Extract source-derived completion symbols without I/O, editor state, caches,
6
+ * built-ins, or project scope. Items have no source attribution: callers add
7
+ * a file path or the current-file marker. Citations here are local bibitems;
8
+ * the server separately indexes BibTeX databases and selects their root scope.
9
+ * This is lexical extraction, not TeX macro expansion.
10
+ */
11
+ export function extractLatexSymbols(original) {
12
+ const symbols = {
13
+ commands: new Map(),
14
+ environments: new Map(),
15
+ labels: new Map(),
16
+ citations: new Map(),
17
+ packages: new Map(),
18
+ classes: new Map(),
19
+ files: new Map()
20
+ };
21
+ const add = (group, label, detail, kind, apply) => {
22
+ if (label && !symbols[group].has(label)) {
23
+ symbols[group].set(label, { label, detail, kind, ...(apply ? { apply } : {}) });
24
+ }
25
+ };
26
+ const command = (name, detail, apply) => add("commands", `\\${name}`, detail, "function", apply);
27
+ const commandDetail = (count) => `Project command (${count} argument${count === 1 ? "" : "s"})`;
28
+ const environment = (name, detail) => {
29
+ // Match the editor grammar's EnvName alphabet, including package-defined
30
+ // names such as proof.custom or expl3-style names with a colon.
31
+ if (/^[A-Za-z@0-9:_*.+\-]+$/.test(name))
32
+ add("environments", name, detail, "keyword");
33
+ };
34
+ const content = maskLatexComments(maskLatexLiteralContent(original));
35
+ for (const match of content.matchAll(/\\(?:newcommand|renewcommand|providecommand|DeclareRobustCommand)\s*\*?\s*(?:\{\s*)?\\([A-Za-z@][A-Za-z@0-9:_]*)\s*(?:\})?\s*(?:\[(\d+)\])?(?:\s*(\[[^\]]*\]))?/g)) {
36
+ const arguments_ = newCommandArguments(Number.parseInt(match[2] ?? "0", 10), Boolean(match[3]));
37
+ command(match[1], commandDetail(arguments_.length), commandSnippet(`\\${match[1]}`, arguments_));
38
+ }
39
+ for (const definition of xparseCommandDefinitions(content)) {
40
+ const arguments_ = xparseCommandArguments(definition.specification);
41
+ command(definition.name, arguments_ ? commandDetail(arguments_.length) : "Project command", arguments_ ? commandSnippet(`\\${definition.name}`, arguments_) : undefined);
42
+ }
43
+ for (const match of content.matchAll(/\\(?:def|gdef|edef|xdef)\s*\\([A-Za-z@][A-Za-z@0-9:_]*)((?:\s*#\d+)*)/g)) {
44
+ const count = [...(match[2] ?? "").matchAll(/#\d+/g)].length;
45
+ command(match[1], "Project macro", commandSnippet(`\\${match[1]}`, newCommandArguments(count, false)));
46
+ }
47
+ for (const match of content.matchAll(/\\DeclareMathOperator\s*\*?\s*\{?\\([A-Za-z@][A-Za-z@0-9:_]*)\}?/g))
48
+ command(match[1], "Project math operator");
49
+ for (const match of content.matchAll(/\\DeclarePairedDelimiter\s*\{?\\([A-Za-z@][A-Za-z@0-9:_]*)\}?/g))
50
+ command(match[1], "Project math delimiter");
51
+ for (const match of content.matchAll(/\\cs_(?:new|set|gset|provide|generate)(?:_protected)?\:[A-Za-z]+\s+\\([A-Za-z@][A-Za-z@0-9:_]*)/g))
52
+ command(match[1], "Expl3 project command");
53
+ for (const match of content.matchAll(/\\(?:newenvironment|renewenvironment|NewDocumentEnvironment|RenewDocumentEnvironment|DeclareDocumentEnvironment)\s*\*?\s*\{([^}]+)\}/g))
54
+ environment(match[1].trim(), "Project environment");
55
+ for (const match of content.matchAll(/\\(?:newtheorem|declaretheorem)\s*\*?\s*\{([^}]+)\}/g))
56
+ environment(match[1].trim(), "Theorem environment");
57
+ for (const definition of findLatexReferenceDefinitions(original, "label")) {
58
+ add("labels", definition.key, "Label", "constant");
59
+ }
60
+ for (const definition of findLatexReferenceDefinitions(original, "citation")) {
61
+ add("citations", definition.key, "Bibliography key", "constant");
62
+ }
63
+ for (const match of content.matchAll(/\\(?:input|include|subfile|import)\s*(?:\{([^}]+)\}|\s+([^\s%]+))/g)) {
64
+ add("files", (match[1] ?? match[2] ?? "").trim(), "Project file", "text");
65
+ }
66
+ for (const match of content.matchAll(/\\(usepackage|RequirePackage|documentclass)\s*(?:\[[^\]]*\])?\s*\{([^}]+)\}/g)) {
67
+ const isClass = match[1] === "documentclass";
68
+ for (const name of match[2].split(",").map((value) => value.trim()).filter(Boolean)) {
69
+ add(isClass ? "classes" : "packages", name, isClass ? "Document class" : "Package", isClass ? "class" : "text");
70
+ }
71
+ }
72
+ return {
73
+ commands: [...symbols.commands.values()], environments: [...symbols.environments.values()],
74
+ labels: [...symbols.labels.values()], citations: [...symbols.citations.values()],
75
+ packages: [...symbols.packages.values()], classes: [...symbols.classes.values()], files: [...symbols.files.values()]
76
+ };
77
+ }
@@ -0,0 +1,128 @@
1
+ const CONTEXT_SIZE = 48;
2
+ export function anchorSource(source) {
3
+ return { length: source.length, sliceString: (from, to) => source.slice(from, to) };
4
+ }
5
+ export function sourceAnchorAt(source, start, end) {
6
+ const startOffset = clamp(Math.min(start, end), 0, source.length);
7
+ const endOffset = clamp(Math.max(start, end), startOffset, source.length);
8
+ return {
9
+ startOffset, endOffset,
10
+ selectedText: source.sliceString(startOffset, endOffset),
11
+ contextBefore: source.sliceString(Math.max(0, startOffset - CONTEXT_SIZE), startOffset),
12
+ contextAfter: source.sliceString(endOffset, Math.min(source.length, endOffset + CONTEXT_SIZE)),
13
+ orphaned: false
14
+ };
15
+ }
16
+ function mappedOffset(position, changes, side) {
17
+ let delta = 0;
18
+ for (const change of changes) {
19
+ if (position < change.from)
20
+ break;
21
+ if (position > change.to || position === change.to && change.to > change.from) {
22
+ delta += change.insertLength - (change.to - change.from);
23
+ }
24
+ else {
25
+ return change.from + delta + (side > 0 ? change.insertLength : 0);
26
+ }
27
+ }
28
+ return position + delta;
29
+ }
30
+ /**
31
+ * Follow partial edits, but keep the last attached quote and context when the
32
+ * selection is erased or no longer recognizable. They are required for undo
33
+ * recovery; the mapped range alone is just a positional hint while detached.
34
+ * A browser may bound recovery searches near the hint to avoid flattening the
35
+ * entire CodeMirror document on each keystroke. Saves search the whole file.
36
+ */
37
+ export function mapSourceAnchor(anchor, oldSource, newSource, changes, recoveryWindow, insertedRanges = []) {
38
+ const oldStart = clamp(anchor.startOffset, 0, oldSource.length);
39
+ const oldEnd = clamp(anchor.endOffset, oldStart, oldSource.length);
40
+ const deletions = changes.filter((change) => change.from < oldEnd && change.to > oldStart);
41
+ // Replacements touching the selection's boundaries belong to the range.
42
+ // Pure insertions just outside it do not (typing before/after a quote).
43
+ const startSide = deletions.some((change) => change.from <= oldStart) ? -1 : 1;
44
+ const endSide = deletions.some((change) => change.to >= oldEnd) ? 1 : -1;
45
+ const start = clamp(mappedOffset(oldStart, changes, startSide), 0, newSource.length);
46
+ const end = clamp(mappedOffset(oldEnd, changes, endSide), start, newSource.length);
47
+ const oldMatches = oldSource.sliceString(oldStart, oldEnd) === anchor.selectedText;
48
+ if (!anchor.orphaned && oldMatches) {
49
+ if (!anchor.selectedText && oldStart === oldEnd)
50
+ return sourceAnchorAt(newSource, start, start);
51
+ const deletedLength = deletions.reduce((sum, change) => sum + Math.min(oldEnd, change.to) - Math.max(oldStart, change.from), 0);
52
+ const retainedLength = oldEnd - oldStart - deletedLength;
53
+ // Exact editor operations can retain even one original character.
54
+ // A guessed text diff needs stronger evidence for word replacements.
55
+ const minimumRetained = changes.some((change) => change.inferred) ? Math.min(2, oldEnd - oldStart) : 1;
56
+ if (end > start && retainedLength >= minimumRetained) {
57
+ return sourceAnchorAt(newSource, start, end);
58
+ }
59
+ }
60
+ const detached = { ...anchor, startOffset: start, endOffset: end, orphaned: true };
61
+ // Do not silently legitimize a previously attached but stale DB row whose
62
+ // quote didn't match the old document in the first place.
63
+ if (!anchor.orphaned && !oldMatches)
64
+ return detached;
65
+ const restored = contextualMatch(newSource, anchor, start, recoveryWindow, insertedRanges);
66
+ return restored === null ? detached : sourceAnchorAt(newSource, restored, restored + anchor.selectedText.length);
67
+ }
68
+ function contextualMatch(source, anchor, start, window, insertedRanges = []) {
69
+ const selected = anchor.selectedText;
70
+ if (!selected)
71
+ return null;
72
+ const from = window === undefined ? 0 : Math.max(0, start - selected.length - window);
73
+ const to = window === undefined ? source.length : Math.min(source.length, start + selected.length + window);
74
+ // Whole-document undo/paste may restore a quote far from the collapsed
75
+ // hint. Inspect the inserted fragment in that case, not the whole file on
76
+ // each subsequent small edit while the comment remains detached.
77
+ const ranges = window === undefined ? [{ from, to }] : [{ from, to },
78
+ ...insertedRanges.filter((range) => range.to - range.from >= selected.length)];
79
+ const seen = new Set();
80
+ const availableContext = anchor.contextBefore.length + anchor.contextAfter.length;
81
+ let best = null;
82
+ let bestRank = Number.NEGATIVE_INFINITY;
83
+ let tied = false;
84
+ for (const range of ranges) {
85
+ const search = source.sliceString(range.from, range.to);
86
+ for (let cursor = 0; cursor <= search.length;) {
87
+ const index = search.indexOf(selected, cursor);
88
+ if (index < 0)
89
+ break;
90
+ const found = range.from + index;
91
+ cursor = index + Math.max(1, selected.length);
92
+ if (seen.has(found))
93
+ continue;
94
+ seen.add(found);
95
+ const before = source.sliceString(Math.max(0, found - anchor.contextBefore.length), found);
96
+ const after = source.sliceString(found + selected.length, Math.min(source.length, found + selected.length + anchor.contextAfter.length));
97
+ const contextScore = commonSuffixLength(before, anchor.contextBefore) + commonPrefixLength(after, anchor.contextAfter);
98
+ // A whole-file selection has no context. Only an exact whole-file undo
99
+ // is safe in that case; proximity or uniqueness alone is insufficient.
100
+ if (availableContext ? contextScore >= Math.min(4, availableContext) : found === 0 && selected.length === source.length) {
101
+ const rank = contextScore * 1000 - Math.abs(found - start);
102
+ if (rank > bestRank) {
103
+ best = found;
104
+ bestRank = rank;
105
+ tied = false;
106
+ }
107
+ else if (rank === bestRank)
108
+ tied = true;
109
+ }
110
+ }
111
+ }
112
+ return tied ? null : best;
113
+ }
114
+ function commonPrefixLength(left, right) {
115
+ let index = 0;
116
+ while (index < Math.min(left.length, right.length) && left[index] === right[index])
117
+ index++;
118
+ return index;
119
+ }
120
+ function commonSuffixLength(left, right) {
121
+ let count = 0;
122
+ while (count < Math.min(left.length, right.length) && left[left.length - count - 1] === right[right.length - count - 1])
123
+ count++;
124
+ return count;
125
+ }
126
+ function clamp(value, min, max) {
127
+ return Math.max(min, Math.min(max, Number.isFinite(value) ? Math.floor(value) : min));
128
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "texlite",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "A lightweight local-first collaborative LaTeX workspace",
5
5
  "license": "AGPL-3.0-only",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{u as Y,r as n,j as e}from"./react-BVUjbTTn.js";import{c as d,M as D,d as _,C as ee,g as h,h as m}from"./index-DprUq41V.js";import{U as se,T as H,X as O}from"./x-CUwbFgRb.js";import{U as $}from"./user-plus-DFkFh0mU.js";import{S as ae}from"./Dashboard-DhKiB4Lp.js";import"./hard-drive-A2DTDrXg.js";import"./github-B3ClW0wI.js";import"./sigma-ggAZwYZs.js";import"./tags-jYRdvWMN.js";const re=d("Dices",[["rect",{width:"12",height:"12",x:"2",y:"10",rx:"2",ry:"2",key:"6agr2n"}],["path",{d:"m17.92 14 3.5-3.5a2.24 2.24 0 0 0 0-3l-5-4.92a2.24 2.24 0 0 0-3 0L10 6",key:"1o487t"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 14h.01",key:"ssrbsk"}],["path",{d:"M15 6h.01",key:"cblpky"}],["path",{d:"M18 9h.01",key:"2061c0"}]]);const ne=d("FolderCheck",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9 13 2 2 4-4",key:"6343dt"}]]);const te=d("FolderX",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9.5 10.5 5 5",key:"ra9qjz"}],["path",{d:"m14.5 10.5-5 5",key:"l2rkpq"}]]);const V=d("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);const ie=d("ShieldOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]]);const oe=d("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);const le=d("UserX",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);function de(p=10){const t="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%",a=crypto.getRandomValues(new Uint8Array(p));return Array.from(a,S=>t[S%t.length]).join("")}function be({currentUser:p,minPasswordLength:t}){const{t:a}=Y(),[S,B]=n.useState([]),[A,c]=n.useState(""),[J,C]=n.useState(!1),[r,o]=n.useState({username:"",displayName:"",password:"",role:"user",canCreateProjects:!1}),[k,g]=n.useState(null),[j,P]=n.useState(""),[x,w]=n.useState(null),[z,N]=n.useState(!1),[i,E]=n.useState(!1),[F,y]=n.useState(""),[l,f]=n.useState(null),[U,R]=n.useState(!1),[X,u]=n.useState(""),b=()=>h("/api/admin/users").then(({users:s})=>B(s)).catch(s=>c(m(s)));n.useEffect(()=>{b()},[]);const q=async()=>{if(r.password.length<t)return c(a("auth.passwordMinimum",{count:t}));try{await h("/api/admin/users",{method:"POST",body:JSON.stringify({username:r.username,displayName:r.displayName||r.username,password:r.password,role:r.role,canCreateProjects:r.canCreateProjects})}),C(!1),o({username:"",displayName:"",password:"",role:"user",canCreateProjects:!1}),await b()}catch(s){c(m(s))}},M=async(s,v)=>{try{await h(`/api/admin/users/${s.id}`,{method:"PATCH",body:JSON.stringify(v)}),await b()}catch(T){c(m(T))}},K=async s=>{if(!s.disabled){f({target:s,setting:"disable"}),u("");return}await M(s,{disabled:!1})},Z=async s=>{if(s.role==="admin"){f({target:s,setting:"demote"}),u("");return}await M(s,{role:"admin"})},G=async s=>{if(s.canCreateProjects){f({target:s,setting:"denyProjectCreation"}),u("");return}await M(s,{canCreateProjects:!0})},I=async()=>{if(!l)return;const{target:s,setting:v}=l,T=v==="disable"?{disabled:!0}:v==="demote"?{role:"user"}:{canCreateProjects:!1};R(!0),u("");try{await h(`/api/admin/users/${s.id}`,{method:"PATCH",body:JSON.stringify(T)}),await b(),f(null)}catch(W){u(m(W))}finally{R(!1)}},L=async()=>{if(!(!k||!j)){if(j.length<t)return c(a("auth.passwordMinimum",{count:t}));try{await h(`/api/admin/users/${k.id}`,{method:"PATCH",body:JSON.stringify({password:j})}),g(null),P("")}catch(s){c(m(s))}}},Q=async()=>{if(!(!x||i)){E(!0),y("");try{await h(`/api/admin/users/${x.id}`,{method:"DELETE",body:JSON.stringify({deleteProjects:z})}),w(null),N(!1),await b()}catch(s){y(m(s))}finally{E(!1)}}};return e.jsxs("main",{className:"dashboard",children:[e.jsxs("div",{className:"section-title",children:[e.jsxs("div",{children:[e.jsxs("h1",{children:[e.jsx(se,{"aria-hidden":!0,size:25}),a("users.manage")]}),e.jsx("p",{className:"muted",children:a("users.onlyAdmin")})]}),e.jsxs("button",{className:"primary icon-button",onClick:()=>C(!0),children:[e.jsx($,{"aria-hidden":!0,size:15}),a("users.add")]})]}),A&&e.jsx("p",{className:"error",children:A}),e.jsx("div",{className:"table-card",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a("common.user")}),e.jsx("th",{children:a("users.role")}),e.jsx("th",{children:a("users.createProjects")}),e.jsx("th",{children:a("users.ownedProjects")}),e.jsx("th",{children:a("users.status")}),e.jsx("th",{children:a("users.actions")})]})}),e.jsx("tbody",{children:S.map(s=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:s.displayName}),e.jsxs("small",{children:["@",s.username]})]}),e.jsx("td",{children:s.role==="admin"?a("common.admin"):a("common.user")}),e.jsx("td",{children:s.canCreateProjects?a("users.allow"):a("users.deny")}),e.jsx("td",{children:s.ownedProjects}),e.jsx("td",{children:s.disabled?a("common.disabled"):a("common.normal")}),e.jsxs("td",{children:[e.jsxs("button",{className:"icon-button",disabled:s.id===p.id,onClick:()=>K(s),children:[s.disabled?e.jsx(oe,{"aria-hidden":!0,size:13}):e.jsx(le,{"aria-hidden":!0,size:13}),s.disabled?a("users.enable"):a("users.disable")]}),e.jsxs("button",{className:"icon-button",disabled:s.id===p.id,onClick:()=>Z(s),children:[s.role==="admin"?e.jsx(ie,{"aria-hidden":!0,size:13}):e.jsx(ae,{"aria-hidden":!0,size:13}),s.role==="admin"?a("users.demote"):a("users.promote")]}),e.jsxs("button",{className:"icon-button",disabled:s.role==="admin",onClick:()=>G(s),children:[s.canCreateProjects?e.jsx(te,{"aria-hidden":!0,size:13}):e.jsx(ne,{"aria-hidden":!0,size:13}),s.canCreateProjects?a("users.denyCreate"):a("users.allowCreate")]}),e.jsxs("button",{className:"icon-button",onClick:()=>{g(s),P("")},children:[e.jsx(V,{"aria-hidden":!0,size:13}),a("users.resetPassword")]}),e.jsxs("button",{className:"icon-button danger-text",disabled:s.id===p.id,onClick:()=>{w(s),N(!1),y("")},children:[e.jsx(H,{"aria-hidden":!0,size:13}),a("common.delete")]})]})]},s.id))})]})}),e.jsx(D,{open:J,title:a("users.add"),description:a("users.addDescription"),onOpenChange:C,footer:e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"icon-button",onClick:()=>C(!1),children:[e.jsx(O,{"aria-hidden":!0,size:14}),a("common.cancel")]}),e.jsxs("button",{className:"primary icon-button",disabled:r.password.length<t,onClick:()=>{q()},children:[e.jsx($,{"aria-hidden":!0,size:14}),a("users.createUser")]})]}),children:e.jsxs("div",{className:"form-stack",children:[e.jsxs("label",{className:"form-field",children:[a("auth.username"),e.jsx("input",{value:r.username,onChange:s=>o({...r,username:s.target.value})})]}),e.jsxs("label",{className:"form-field",children:[a("users.displayName"),e.jsx("input",{value:r.displayName,onChange:s=>o({...r,displayName:s.target.value})})]}),e.jsxs("label",{className:"form-field",children:[a("users.initialPassword"),e.jsxs("span",{className:"password-generator",children:[e.jsx("input",{minLength:t,autoComplete:"new-password",value:r.password,onChange:s=>o({...r,password:s.target.value})}),e.jsxs("button",{type:"button",title:a("users.generatePassword"),onClick:()=>o({...r,password:de()}),children:[e.jsx(re,{size:15}),a("users.randomPassword")]})]}),e.jsx("small",{className:"field-hint",children:a("auth.passwordMinimum",{count:t})})]}),e.jsxs("label",{className:"form-field",children:[a("users.role"),e.jsxs("select",{value:r.role,onChange:s=>o({...r,role:s.target.value}),children:[e.jsx("option",{value:"user",children:a("common.user")}),e.jsx("option",{value:"admin",children:a("common.admin")})]})]}),e.jsxs("label",{className:"checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:r.canCreateProjects||r.role==="admin",disabled:r.role==="admin",onChange:s=>o({...r,canCreateProjects:s.target.checked})})," ",a("users.allowCreate")]})]})}),e.jsx(D,{open:!!k,title:a("users.resetPassword"),description:a("users.resetDescription",{username:k?.username??""}),onOpenChange:s=>{s||g(null)},footer:e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"icon-button",onClick:()=>g(null),children:[e.jsx(O,{"aria-hidden":!0,size:14}),a("common.cancel")]}),e.jsxs("button",{className:"primary icon-button",disabled:j.length<t,onClick:()=>{L()},children:[e.jsx(V,{"aria-hidden":!0,size:14}),a("users.reset")]})]}),children:e.jsxs("label",{className:"form-field",children:[a("auth.newPassword"),e.jsx("input",{autoFocus:!0,type:"password",minLength:t,autoComplete:"new-password",value:j,onChange:s=>P(s.target.value)}),e.jsx("small",{className:"field-hint",children:a("auth.passwordMinimum",{count:t})})]})}),e.jsx(D,{open:!!x,title:a("users.deleteTitle"),description:a("users.deleteDescription",{username:x?.username??""}),onOpenChange:s=>{!s&&!i&&(w(null),y(""))},footer:e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"icon-button",disabled:i,onClick:()=>{w(null),y("")},children:[e.jsx(O,{"aria-hidden":!0,size:14}),a("common.cancel")]}),e.jsxs("button",{className:"danger icon-button",disabled:i,"aria-busy":i,onClick:()=>{Q()},children:[i?e.jsx(_,{className:"spin","aria-hidden":!0,size:14}):e.jsx(H,{"aria-hidden":!0,size:14}),a(i?"common.loading":"users.deleteTitle")]})]}),children:e.jsxs(e.Fragment,{children:[F&&e.jsx("p",{className:"error dialog-error",children:F}),e.jsxs("fieldset",{className:"choice-group",disabled:i,children:[e.jsx("legend",{children:a("users.ownedChoice",{count:x?.ownedProjects??0})}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!z,onChange:()=>N(!1)})," ",a("users.transferProjects")]}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:z,onChange:()=>N(!0)})," ",a("users.deleteProjects")]})]})]})}),e.jsx(ee,{open:!!l,title:a(`userConfirmations.${l?.setting??"disable"}Title`),description:a(`userConfirmations.${l?.setting??"disable"}Description`,{username:l?.target.username??""}),confirmLabel:a(`userConfirmations.${l?.setting??"disable"}Confirm`),danger:!0,busy:U,error:X,onCancel:()=>{U||(f(null),u(""))},onConfirm:()=>{I()}})]})}export{be as AdminUsers};
@@ -1 +0,0 @@
1
- import{u as Yt,r,j as t}from"./react-BVUjbTTn.js";import{c as At,g as S,h as k,d as H,C as Bt,M as ut}from"./index-DprUq41V.js";import{parseBibEntriesResult as Qt,citationBibtexLimitLabel as Xt,parseSingleBibEntry as Kt,citationVenue as Gt}from"./citationLibrary-ZeQPCv5O.js";import{B as tt,X as et,i as bt,C as Zt,k as zt,T as ti}from"./x-CUwbFgRb.js";import{P as it}from"./plus-CCRSrXDi.js";import{C as J}from"./check-6jrUH-ay.js";import{S as ii}from"./search-DhHW3xg7.js";import{T as ei}from"./tags-jYRdvWMN.js";const ai=At("Import",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m8 11 4 4 4-4",key:"1dohi6"}],["path",{d:"M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4",key:"1ywtjm"}]]);const ni=At("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]),si=[],ri={status:"empty",entries:si};function hi({open:o,onOpenChange:j,page:u=!1,onBack:b,currentFile:v="",currentSource:p="",readOnly:E=!1,currentUserId:m,maxBibtexBytes:l,onInsert:f}){const{t:e}=Yt(),[K,A]=r.useState("library"),[z,d]=r.useState(""),[L,P]=r.useState(""),[I,N]=r.useState([]),[at,C]=r.useState(1),[g,ht]=r.useState({page:1,pageSize:60,total:0,totalPages:0}),[Ft,U]=r.useState(0),[q,pt]=r.useState([]),[Y,gt]=r.useState(""),[xt,_t]=r.useState("green"),[h,x]=r.useState(null),[B,F]=r.useState([]),[nt,jt]=r.useState(!1),[Rt,vt]=r.useState(!1),[V,O]=r.useState(null),[y,T]=r.useState(null),[st,rt]=r.useState(""),[Dt,_]=r.useState(!1),[Q,ot]=r.useState(""),[ft,ct]=r.useState(null),[lt,X]=r.useState(null),[It,W]=r.useState(""),[$,c]=r.useState(""),[Lt,M]=r.useState(""),[Ct,w]=r.useState(new Map),[Ot,G]=r.useState(!1),[$t,Ht]=r.useState(0),R=!!(/\.bib$/i.test(v)&&f),dt=r.useMemo(()=>o&&R?Qt(p,l):ri,[o,p,R,l]),Nt=dt.status==="too-large",Tt=dt.status==="invalid",D=dt.entries,Jt=r.useMemo(()=>new Set(D.map(i=>i.citationKey.toLowerCase())),[D]);r.useEffect(()=>{if(!o)return;const i=new AbortController,a=window.setTimeout(()=>{vt(!0),c("");const n=new URLSearchParams;z.trim()&&n.set("q",z.trim()),L&&n.set("tag",L),n.set("page",String(at)),n.set("pageSize","60"),S(`/api/citations?${n.toString()}`,{signal:i.signal}).then(s=>{N(s.entries),ht(s.pagination),s.pagination.page!==at&&C(s.pagination.page)}).catch(s=>{s instanceof Error&&s.name==="AbortError"||c(k(s))}).finally(()=>{i.signal.aborted||vt(!1)})},z.trim()?180:0);return()=>{window.clearTimeout(a),i.abort()}},[o,z,L,at,Ft]),r.useEffect(()=>{if(!o)return;const i=new AbortController;return S("/api/citations/tags",{signal:i.signal}).then(a=>pt(a.tags)).catch(a=>{a instanceof Error&&a.name==="AbortError"||c(k(a))}),()=>i.abort()},[o]),r.useEffect(()=>{if(!o||!R){w(new Map),G(!1);return}const i=new AbortController,a=[...new Set(D.map(n=>n.citationKey))];return a.length?(G(!0),S("/api/citations/lookup",{method:"POST",body:JSON.stringify({keys:a}),signal:i.signal}).then(n=>{w(new Map(n.matches.map(s=>[s.citationKey.toLowerCase(),s])))}).catch(n=>{n instanceof Error&&n.name==="AbortError"||c(k(n))}).finally(()=>{i.signal.aborted||G(!1)}),()=>i.abort()):(w(new Map),G(!1),()=>i.abort())},[o,R,D,$t]),r.useEffect(()=>{o&&(A("library"),d(""),P(""),C(1),ht({page:1,pageSize:60,total:0,totalPages:0}),T(null),_(!1),ot(""),x(null),ct(null),X(null),W(""),c(""),M(""),w(new Map))},[o,R]);const Ut=async i=>{O(i.citationKey),c("");try{const a=Ct.get(i.citationKey.toLowerCase()),n=await S("/api/citations",{method:"POST",body:JSON.stringify({bibtex:i.bibtex,citationKey:i.citationKey,entryType:i.entryType,title:i.title,authors:i.authors,year:i.year,overwrite:!!a,expectedRevision:a?.revision})});N(s=>[n.entry,...s.filter(Z=>Z.id!==n.entry.id&&Z.citationKey.toLowerCase()!==n.entry.citationKey.toLowerCase())]),w(s=>new Map(s).set(n.entry.citationKey.toLowerCase(),{id:n.entry.id,citationKey:n.entry.citationKey,revision:n.entry.revision})),x(n.entry),F(n.entry.tags.map(s=>s.id)),M(n.updated?e("citationLibrary.updated"):e("citationLibrary.saved")),C(1),U(s=>s+1)}catch(a){c(k(a)),Ht(n=>n+1)}finally{O(null)}},wt=async()=>{if(y){O(y.citationKey),c("");try{const i=Kt(st,l);if(!i){c(e("citationErrors.invalid"));return}const a=await S(`/api/citations/${encodeURIComponent(y.id)}`,{method:"PATCH",body:JSON.stringify({bibtex:i.bibtex,citationKey:i.citationKey,entryType:i.entryType,title:i.title,authors:i.authors,year:i.year,expectedRevision:y.revision})});N(n=>[a.entry,...n.filter(s=>s.id!==a.entry.id)]),w(n=>{const s=new Map(n);return s.delete(y.citationKey.toLowerCase()),s.set(a.entry.citationKey.toLowerCase(),{id:a.entry.id,citationKey:a.entry.citationKey,revision:a.entry.revision}),s}),T(null),M(e("citationLibrary.updated")),C(1),U(n=>n+1)}catch(i){c(k(i))}finally{O(null)}}},qt=async()=>{if(Q.trim()){O("__new__"),c("");try{const i=Kt(Q,l);if(!i){c(e("citationErrors.invalid"));return}const a=await S("/api/citations",{method:"POST",body:JSON.stringify({bibtex:i.bibtex,citationKey:i.citationKey,entryType:i.entryType,title:i.title,authors:i.authors,year:i.year})});N(n=>[a.entry,...n.filter(s=>s.id!==a.entry.id&&s.citationKey.toLowerCase()!==a.entry.citationKey.toLowerCase())]),w(n=>new Map(n).set(a.entry.citationKey.toLowerCase(),{id:a.entry.id,citationKey:a.entry.citationKey,revision:a.entry.revision})),_(!1),ot(""),M(a.updated?e("citationLibrary.updated"):e("citationLibraryActions.added")),x(a.entry),F(a.entry.tags.map(n=>n.id)),C(1),U(n=>n+1)}catch(i){c(k(i))}finally{O(null)}}},St=async()=>{if(Y.trim()){c("");try{const i=await S("/api/citations/tags",{method:"POST",body:JSON.stringify({name:Y.trim(),color:xt})});pt(a=>[...a.filter(n=>n.id!==i.tag.id),i.tag].sort((n,s)=>n.name.localeCompare(s.name))),gt(""),M(e("citationLibrary.tagCreated"))}catch(i){c(k(i))}}},Vt=i=>{T(null),_(!1),x(i),F(i.tags.map(a=>a.id))},yt=async()=>{if(h){jt(!0),c("");try{const i=await S(`/api/citations/${encodeURIComponent(h.id)}/tags`,{method:"PATCH",body:JSON.stringify({tagIds:B,expectedRevision:h.revision})});N(a=>a.map(n=>n.id===i.entry.id?i.entry:n)),w(a=>new Map(a).set(i.entry.citationKey.toLowerCase(),{id:i.entry.id,citationKey:i.entry.citationKey,revision:i.entry.revision})),x(i.entry),F(i.entry.tags.map(a=>a.id)),M(e("citationLibrary.tagsUpdated")),U(a=>a+1)}catch(i){c(k(i))}finally{jt(!1)}}},Wt=async i=>{ct(i.id),W("");try{await S(`/api/citations/${encodeURIComponent(i.id)}`,{method:"DELETE"}),N(a=>a.filter(n=>n.id!==i.id)),w(a=>{const n=new Map(a);return n.delete(i.citationKey.toLowerCase()),n}),y?.id===i.id&&T(null),h?.id===i.id&&x(null),M(e("citationLibrary.deleted")),C(1),U(a=>a+1),X(null)}catch(a){W(k(a))}finally{ct(null)}},kt=t.jsxs("div",{className:"citation-library-dialog",children:[t.jsxs("div",{className:"citation-library-tabs",role:"tablist","aria-label":e("citationLibrary.title"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":K==="library",className:K==="library"?"active":"",onClick:()=>A("library"),children:[t.jsx(tt,{size:15}),e("citationLibrary.myLibrary"),t.jsx("span",{children:g.total})]}),R&&t.jsxs("button",{type:"button",role:"tab","aria-selected":K==="current",className:K==="current"?"active":"",onClick:()=>A("current"),children:[t.jsx(it,{size:15}),e("citationLibrary.currentFile"),t.jsx("span",{children:D.length})]})]}),$&&!(u&&(h||y))&&t.jsx("p",{className:"error dialog-error",children:$}),Lt&&t.jsxs("p",{className:"citation-library-notice",role:"status",children:[t.jsx(J,{size:14}),Lt,t.jsx("button",{type:"button","aria-label":e("common.close"),onClick:()=>M(""),children:t.jsx(et,{size:13})})]}),K==="library"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"citation-library-search-row",children:[t.jsxs("label",{className:"citation-library-search",children:[t.jsx(ii,{size:15}),t.jsx("input",{autoFocus:!0,placeholder:e("citationLibrary.searchPlaceholder"),value:z,onChange:i=>{d(i.target.value),C(1)}}),t.jsx("span",{children:e("citationLibrary.searchHint")})]}),t.jsxs("button",{type:"button",className:"citation-add-entry-button",onClick:()=>{_(!0),T(null),x(null)},children:[t.jsx(it,{size:14}),e("citationLibraryActions.addEntry")]})]}),t.jsxs("div",{className:"citation-tag-bar",children:[t.jsxs("div",{className:"citation-tag-filters",children:[t.jsx("button",{type:"button",className:L?"":"active",onClick:()=>{P(""),C(1)},children:e("citationLibrary.allTags")}),q.map(i=>t.jsxs("button",{type:"button",className:L===i.id?"active":"",onClick:()=>{P(L===i.id?"":i.id),C(1)},children:[t.jsx("span",{className:`citation-tag-dot tag-${i.color}`}),i.name]},i.id)),q.length===0&&t.jsx("span",{className:"muted",children:e("citationLibrary.noTags")})]}),t.jsxs("div",{className:"citation-tag-create",children:[t.jsx("input",{value:Y,placeholder:e("citationLibrary.newTagPlaceholder"),onChange:i=>gt(i.target.value),onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),St())}}),t.jsx("select",{"aria-label":e("citationLibrary.tagColor"),value:xt,onChange:i=>_t(i.target.value),children:["red","orange","yellow","green","blue","purple","gray"].map(i=>t.jsx("option",{value:i,children:e(`tags.${i}`)},i))}),t.jsxs("button",{type:"button",disabled:!Y.trim(),title:e("citationLibrary.createTag"),onClick:()=>{St()},children:[t.jsx(it,{size:13}),e("citationLibrary.createTag")]})]})]}),Dt&&t.jsxs("div",{className:"citation-edit-panel",children:[t.jsxs("div",{className:"citation-edit-header",children:[t.jsxs("div",{children:[t.jsx("strong",{children:e("citationLibraryActions.addEntryTitle")}),t.jsx("small",{children:e("citationLibraryActions.addEntryDescription")})]}),t.jsx("button",{type:"button","aria-label":e("common.close"),onClick:()=>_(!1),children:t.jsx(et,{size:15})})]}),t.jsx("textarea",{autoFocus:!0,value:Q,onChange:i=>ot(i.target.value),placeholder:e("citationLibraryActions.addEntryPlaceholder"),spellCheck:!1,rows:9}),t.jsxs("div",{className:"citation-edit-actions",children:[t.jsx("button",{type:"button",onClick:()=>_(!1),children:e("common.cancel")}),t.jsxs("button",{type:"button",className:"primary",disabled:!Q.trim()||V==="__new__",onClick:()=>{qt()},children:[V==="__new__"?t.jsx(H,{className:"spin",size:14}):t.jsx(J,{size:14}),e("citationLibraryActions.addEntry")]})]})]}),Rt?t.jsxs("div",{className:"citation-library-empty",children:[t.jsx(H,{className:"spin",size:22}),t.jsx("span",{children:e("common.loading")})]}):I.length===0?t.jsxs("div",{className:"citation-library-empty",children:[t.jsx(tt,{size:28}),t.jsx("strong",{children:e("citationLibrary.emptyTitle")}),t.jsx("span",{children:e(L?"citationLibrary.noTagMatches":"citationLibrary.emptyDescription")})]}):t.jsx("div",{className:"citation-entry-list",children:I.map(i=>t.jsxs("div",{className:"citation-entry-item",children:[t.jsx(Pt,{entry:i,currentUserId:m,selected:h?.id===i.id||y?.id===i.id,alreadyInFile:!u&&Jt.has(i.citationKey.toLowerCase()),importDisabled:E,deleting:ft===i.id,onImport:f?async()=>{await f(i)&&j(!1)}:void 0,onEdit:i.ownerId===m?()=>{x(null),_(!1),T(i),rt(i.bibtex)}:void 0,onTags:i.ownerId===m?()=>Vt(i):void 0,onDelete:i.ownerId===m?()=>{X(i),W("")}:void 0,t:e}),!u&&h?.id===i.id&&t.jsx(mt,{entry:h,tags:q,selectedIds:B,saving:nt,onClose:()=>x(null),onToggle:a=>F(n=>n.includes(a)?n.filter(s=>s!==a):[...n,a]),onSave:()=>{yt()},t:e}),!u&&y?.id===i.id&&t.jsx(Mt,{title:e("citationLibrary.editTitle",{key:y.citationKey}),value:st,saving:V===y.citationKey,onChange:rt,onClose:()=>T(null),onSave:()=>{wt()},t:e})]},i.id))}),g.totalPages>1&&t.jsxs("nav",{className:"citation-library-pagination","aria-label":e("citationLibraryPagination.pageOf",{page:g.page,totalPages:g.totalPages,count:g.total}),children:[t.jsxs("button",{type:"button",disabled:g.page<=1,onClick:()=>C(i=>Math.max(1,i-1)),children:[t.jsx(bt,{size:14}),e("citationLibraryPagination.previous")]}),t.jsx("span",{children:e("citationLibraryPagination.pageOf",{page:g.page,totalPages:g.totalPages,count:g.total})}),t.jsxs("button",{type:"button",disabled:g.page>=g.totalPages,onClick:()=>C(i=>Math.min(g.totalPages,i+1)),children:[e("citationLibraryPagination.next"),t.jsx(Zt,{size:14})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"citation-current-heading",children:[t.jsxs("div",{children:[t.jsx("strong",{children:e("citationLibrary.currentFileTitle")}),t.jsx("span",{children:e("citationLibrary.currentFileDescription")})]}),t.jsxs("button",{type:"button",onClick:()=>A("library"),children:[t.jsx(bt,{size:14}),e("citationLibrary.backToLibrary")]})]}),Nt&&t.jsxs("p",{className:"warning citation-library-warning",children:[t.jsx(zt,{size:15}),e("citationLibrary.fileTooLarge",{size:Xt(l)})]}),Tt&&t.jsxs("p",{className:"warning citation-library-warning",children:[t.jsx(zt,{size:15}),e("citationLibrary.fileInvalid")]}),D.length===0?t.jsxs("div",{className:"citation-library-empty",children:[t.jsx(tt,{size:28}),t.jsx("strong",{children:e("citationLibrary.noEntries")}),t.jsx("span",{children:e(Nt?"citationLibrary.fileTooLargeHint":Tt?"citationLibrary.fileInvalidHint":"citationLibrary.noEntriesDescription")})]}):t.jsx("div",{className:"citation-entry-list",children:D.map((i,a)=>t.jsxs("div",{className:"citation-entry-item",children:[t.jsx(Pt,{entry:i,saved:Ct.has(i.citationKey.toLowerCase()),saving:V===i.citationKey,saveDisabled:Ot,onSave:()=>{Ut(i)},t:e}),!u&&h?.citationKey.toLowerCase()===i.citationKey.toLowerCase()&&t.jsx(mt,{entry:h,tags:q,selectedIds:B,saving:nt,onClose:()=>x(null),onToggle:n=>F(s=>s.includes(n)?s.filter(Z=>Z!==n):[...s,n]),onSave:()=>{yt()},t:e})]},`${i.citationKey}-${a}`))})]})]}),Et=t.jsx(Bt,{open:!!lt,title:e("citationLibrary.deleteTitle"),description:e("citationLibrary.deleteDescription",{key:lt?.citationKey??""}),confirmLabel:e("common.delete"),danger:!0,error:It,busy:!!ft,onCancel:()=>{X(null),W("")},onConfirm:()=>{const i=lt;i&&Wt(i)}});return u?t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"citation-library-page",children:[t.jsxs("header",{className:"citation-library-page-header",children:[t.jsxs("div",{children:[t.jsxs("h1",{children:[t.jsx(tt,{"aria-hidden":!0,size:26}),e("citationLibrary.title")]}),t.jsx("p",{children:e("citationLibraryHomeDescription")})]}),b&&t.jsxs("button",{type:"button",onClick:b,children:[t.jsx(bt,{size:15}),e("projects.title")]})]}),kt]}),h&&t.jsx(ut,{open:!0,title:e("citationLibrary.tagsTitle",{key:h.citationKey}),description:e("citationLibrary.tags"),onOpenChange:i=>{i||(x(null),c(""))},children:t.jsxs(t.Fragment,{children:[$&&t.jsx("p",{className:"error dialog-error",children:$}),t.jsx(mt,{entry:h,tags:q,selectedIds:B,saving:nt,modal:!0,onClose:()=>{x(null),c("")},onToggle:i=>F(a=>a.includes(i)?a.filter(n=>n!==i):[...a,i]),onSave:()=>{yt()},t:e})]})}),y&&t.jsx(ut,{open:!0,extraWide:!0,title:e("citationLibrary.editTitle",{key:y.citationKey}),description:e("citationLibrary.title"),onOpenChange:i=>{i||(T(null),c(""))},children:t.jsxs(t.Fragment,{children:[$&&t.jsx("p",{className:"error dialog-error",children:$}),t.jsx(Mt,{title:e("citationLibrary.editTitle",{key:y.citationKey}),value:st,saving:V===y.citationKey,modal:!0,onChange:rt,onClose:()=>{T(null),c("")},onSave:()=>{wt()},t:e})]})}),Et]}):t.jsxs(t.Fragment,{children:[t.jsx(ut,{open:o,extraWide:!0,className:"citation-library-modal",title:e("citationLibrary.title"),description:e(R?"citationLibrary.description":"citationLibraryHomeDescription",{file:v}),onOpenChange:j,footer:t.jsx("button",{onClick:()=>j(!1),children:e("common.close")}),children:kt}),Et]})}function Pt({entry:o,currentUserId:j,selected:u,alreadyInFile:b,saved:v,saving:p,saveDisabled:E,importDisabled:m,deleting:l,onSave:f,onImport:e,onEdit:K,onTags:A,onDelete:z,t:d}){const L="id"in o,P=L?o:null,I=Gt(o);return t.jsxs("article",{className:`citation-entry-card${u?" selected":""}${b?" already-in-file":""}`,title:b?d("citationErrors.alreadyInFile",{key:o.citationKey}):void 0,children:[t.jsxs("div",{className:"citation-entry-main",children:[t.jsxs("div",{className:"citation-entry-heading",children:[t.jsx("code",{children:o.citationKey}),t.jsxs("span",{children:["@",o.entryType]}),I&&t.jsx("span",{className:"citation-entry-venue",title:I,children:I}),v&&t.jsxs("em",{children:[t.jsx(J,{size:11}),d("citationLibrary.savedLabel")]})]}),t.jsx("strong",{children:o.title||d("citationLibrary.untitled")}),t.jsxs("p",{children:[o.authors||d("citationLibrary.authorUnknown"),o.year&&t.jsxs("span",{children:[" · ",o.year]})]}),P&&P.tags.length>0&&t.jsx("div",{className:"citation-entry-tags",children:P.tags.map(N=>t.jsxs("span",{className:`citation-tag-pill tag-${N.color}`,children:[t.jsx("span",{className:"citation-tag-dot"}),N.name]},N.id))})]}),t.jsxs("div",{className:"citation-entry-actions",children:[f&&t.jsxs("button",{type:"button",className:v?"saved":"primary",disabled:p||E,onClick:f,children:[p||E?t.jsx(H,{className:"spin",size:13}):v?t.jsx(J,{size:13}):t.jsx(it,{size:13}),d(p?"citationLibrary.saving":v?"citationLibrary.update":"citationLibrary.save")]}),e&&t.jsxs("button",{type:"button",disabled:m||b,title:b?d("citationErrors.alreadyInFile",{key:o.citationKey}):d(m?"citationLibrary.importRequiresWrite":"citationLibrary.importToFile"),onClick:()=>{e()},children:[t.jsx(ai,{size:13}),d("citationLibrary.import")]}),P&&A&&t.jsxs("button",{type:"button",onClick:A,children:[t.jsx(ei,{size:13}),d("citationLibrary.tags")]}),L&&K&&t.jsxs("button",{type:"button",onClick:K,children:[t.jsx(ni,{size:13}),d("common.edit")]}),L&&z&&t.jsxs("button",{type:"button",className:"danger-text",disabled:l,onClick:z,children:[l?t.jsx(H,{className:"spin",size:13}):t.jsx(ti,{size:13}),d("common.delete")]})]})]})}function mt({entry:o,tags:j,selectedIds:u,saving:b,modal:v=!1,onClose:p,onToggle:E,onSave:m,t:l}){const f=t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"citation-tag-choice-list",children:j.length===0?t.jsx("span",{className:"muted",children:l("citationLibrary.noTagsToAssign")}):j.map(e=>t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:u.includes(e.id),onChange:()=>E(e.id)}),t.jsx("span",{className:`citation-tag-dot tag-${e.color}`}),e.name]},e.id))}),t.jsxs("div",{className:"citation-edit-actions",children:[t.jsx("button",{type:"button",onClick:p,children:l("common.cancel")}),t.jsxs("button",{type:"button",className:"primary",disabled:b||j.length===0,onClick:m,children:[b?t.jsx(H,{className:"spin",size:14}):t.jsx(J,{size:14}),l("citationLibrary.saveTags")]})]})]});return v?t.jsx("div",{className:"citation-modal-form",children:f}):t.jsxs("div",{className:"citation-tag-editor",children:[t.jsxs("div",{className:"citation-edit-header",children:[t.jsx("strong",{children:l("citationLibrary.tagsTitle",{key:o.citationKey})}),t.jsx("button",{type:"button","aria-label":l("common.close"),onClick:p,children:t.jsx(et,{size:15})})]}),f]})}function Mt({title:o,value:j,saving:u,modal:b=!1,onChange:v,onClose:p,onSave:E,t:m}){const l=t.jsxs(t.Fragment,{children:[t.jsx("textarea",{autoFocus:!b,value:j,onChange:f=>v(f.target.value),spellCheck:!1,rows:12}),t.jsxs("div",{className:"citation-edit-actions",children:[t.jsx("button",{type:"button",onClick:p,children:m("common.cancel")}),t.jsxs("button",{type:"button",className:"primary",disabled:!j.trim()||u,onClick:E,children:[u?t.jsx(H,{className:"spin",size:14}):t.jsx(J,{size:14}),m("common.save")]})]})]});return b?t.jsx("div",{className:"citation-modal-form citation-edit-panel",children:l}):t.jsxs("div",{className:"citation-edit-panel",children:[t.jsxs("div",{className:"citation-edit-header",children:[t.jsx("strong",{children:o}),t.jsx("button",{type:"button","aria-label":m("common.close"),onClick:p,children:t.jsx(et,{size:15})})]}),l]})}export{hi as CitationLibraryDialog};