@fiduswriter/books 0.0.0-stage → 0.2.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 (188) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +87 -2
  3. package/css/book.css +219 -0
  4. package/dist/exporter/bits/index.d.ts +42 -0
  5. package/dist/exporter/bits/index.d.ts.map +1 -0
  6. package/dist/exporter/bits/index.js +113 -0
  7. package/dist/exporter/bits/index.js.map +1 -0
  8. package/dist/exporter/bits/templates.d.ts +7 -0
  9. package/dist/exporter/bits/templates.d.ts.map +1 -0
  10. package/dist/exporter/bits/templates.js +78 -0
  11. package/dist/exporter/bits/templates.js.map +1 -0
  12. package/dist/exporter/docx/index.d.ts +33 -0
  13. package/dist/exporter/docx/index.d.ts.map +1 -0
  14. package/dist/exporter/docx/index.js +139 -0
  15. package/dist/exporter/docx/index.js.map +1 -0
  16. package/dist/exporter/docx/render.d.ts +19 -0
  17. package/dist/exporter/docx/render.d.ts.map +1 -0
  18. package/dist/exporter/docx/render.js +123 -0
  19. package/dist/exporter/docx/render.js.map +1 -0
  20. package/dist/exporter/epub/index.d.ts +70 -0
  21. package/dist/exporter/epub/index.d.ts.map +1 -0
  22. package/dist/exporter/epub/index.js +310 -0
  23. package/dist/exporter/epub/index.js.map +1 -0
  24. package/dist/exporter/epub/templates.d.ts +65 -0
  25. package/dist/exporter/epub/templates.d.ts.map +1 -0
  26. package/dist/exporter/epub/templates.js +224 -0
  27. package/dist/exporter/epub/templates.js.map +1 -0
  28. package/dist/exporter/epub/tools.d.ts +5 -0
  29. package/dist/exporter/epub/tools.d.ts.map +1 -0
  30. package/dist/exporter/epub/tools.js +59 -0
  31. package/dist/exporter/epub/tools.js.map +1 -0
  32. package/dist/exporter/html/index.d.ts +70 -0
  33. package/dist/exporter/html/index.d.ts.map +1 -0
  34. package/dist/exporter/html/index.js +320 -0
  35. package/dist/exporter/html/index.js.map +1 -0
  36. package/dist/exporter/html/templates.d.ts +40 -0
  37. package/dist/exporter/html/templates.d.ts.map +1 -0
  38. package/dist/exporter/html/templates.js +225 -0
  39. package/dist/exporter/html/templates.js.map +1 -0
  40. package/dist/exporter/html/tools.d.ts +2 -0
  41. package/dist/exporter/html/tools.d.ts.map +1 -0
  42. package/dist/exporter/html/tools.js +23 -0
  43. package/dist/exporter/html/tools.js.map +1 -0
  44. package/dist/exporter/latex/index.d.ts +36 -0
  45. package/dist/exporter/latex/index.d.ts.map +1 -0
  46. package/dist/exporter/latex/index.js +116 -0
  47. package/dist/exporter/latex/index.js.map +1 -0
  48. package/dist/exporter/latex/templates.d.ts +4 -0
  49. package/dist/exporter/latex/templates.d.ts.map +1 -0
  50. package/dist/exporter/latex/templates.js +26 -0
  51. package/dist/exporter/latex/templates.js.map +1 -0
  52. package/dist/exporter/native/index.d.ts +22 -0
  53. package/dist/exporter/native/index.d.ts.map +1 -0
  54. package/dist/exporter/native/index.js +141 -0
  55. package/dist/exporter/native/index.js.map +1 -0
  56. package/dist/exporter/odt/index.d.ts +33 -0
  57. package/dist/exporter/odt/index.d.ts.map +1 -0
  58. package/dist/exporter/odt/index.js +133 -0
  59. package/dist/exporter/odt/index.js.map +1 -0
  60. package/dist/exporter/odt/render.d.ts +21 -0
  61. package/dist/exporter/odt/render.d.ts.map +1 -0
  62. package/dist/exporter/odt/render.js +126 -0
  63. package/dist/exporter/odt/render.js.map +1 -0
  64. package/dist/exporter/pretty.d.ts +17 -0
  65. package/dist/exporter/pretty.d.ts.map +1 -0
  66. package/dist/exporter/pretty.js +55 -0
  67. package/dist/exporter/pretty.js.map +1 -0
  68. package/dist/exporter/print/index.d.ts +25 -0
  69. package/dist/exporter/print/index.d.ts.map +1 -0
  70. package/dist/exporter/print/index.js +46 -0
  71. package/dist/exporter/print/index.js.map +1 -0
  72. package/dist/exporter/print/templates.d.ts +2 -0
  73. package/dist/exporter/print/templates.d.ts.map +1 -0
  74. package/dist/exporter/print/templates.js +5 -0
  75. package/dist/exporter/print/templates.js.map +1 -0
  76. package/dist/exporter/tools.d.ts +31 -0
  77. package/dist/exporter/tools.d.ts.map +1 -0
  78. package/dist/exporter/tools.js +177 -0
  79. package/dist/exporter/tools.js.map +1 -0
  80. package/dist/i18n.d.ts +7 -0
  81. package/dist/i18n.d.ts.map +1 -0
  82. package/dist/i18n.js +918 -0
  83. package/dist/i18n.js.map +1 -0
  84. package/dist/ids.d.ts +19 -0
  85. package/dist/ids.d.ts.map +1 -0
  86. package/dist/ids.js +27 -0
  87. package/dist/ids.js.map +1 -0
  88. package/dist/importer/native/index.d.ts +45 -0
  89. package/dist/importer/native/index.d.ts.map +1 -0
  90. package/dist/importer/native/index.js +166 -0
  91. package/dist/importer/native/index.js.map +1 -0
  92. package/dist/importer/native/reader.d.ts +32 -0
  93. package/dist/importer/native/reader.d.ts.map +1 -0
  94. package/dist/importer/native/reader.js +170 -0
  95. package/dist/importer/native/reader.js.map +1 -0
  96. package/dist/index.d.ts +4 -0
  97. package/dist/index.d.ts.map +1 -0
  98. package/dist/index.js +3 -0
  99. package/dist/index.js.map +1 -0
  100. package/dist/schema/index.d.ts +7 -0
  101. package/dist/schema/index.d.ts.map +1 -0
  102. package/dist/schema/index.js +8 -0
  103. package/dist/schema/index.js.map +1 -0
  104. package/dist/types.d.ts +171 -0
  105. package/dist/types.d.ts.map +1 -0
  106. package/dist/types.js +5 -0
  107. package/dist/types.js.map +1 -0
  108. package/dist/ui/book_dialog/dialog.d.ts +161 -0
  109. package/dist/ui/book_dialog/dialog.d.ts.map +1 -0
  110. package/dist/ui/book_dialog/dialog.js +750 -0
  111. package/dist/ui/book_dialog/dialog.js.map +1 -0
  112. package/dist/ui/book_dialog/export.d.ts +95 -0
  113. package/dist/ui/book_dialog/export.d.ts.map +1 -0
  114. package/dist/ui/book_dialog/export.js +217 -0
  115. package/dist/ui/book_dialog/export.js.map +1 -0
  116. package/dist/ui/book_dialog/index.d.ts +38 -0
  117. package/dist/ui/book_dialog/index.d.ts.map +1 -0
  118. package/dist/ui/book_dialog/index.js +36 -0
  119. package/dist/ui/book_dialog/index.js.map +1 -0
  120. package/dist/ui/book_dialog/sanity_check.d.ts +22 -0
  121. package/dist/ui/book_dialog/sanity_check.d.ts.map +1 -0
  122. package/dist/ui/book_dialog/sanity_check.js +109 -0
  123. package/dist/ui/book_dialog/sanity_check.js.map +1 -0
  124. package/dist/ui/book_dialog/templates.d.ts +76 -0
  125. package/dist/ui/book_dialog/templates.d.ts.map +1 -0
  126. package/dist/ui/book_dialog/templates.js +542 -0
  127. package/dist/ui/book_dialog/templates.js.map +1 -0
  128. package/dist/ui/book_dialog/types.d.ts +258 -0
  129. package/dist/ui/book_dialog/types.d.ts.map +1 -0
  130. package/dist/ui/book_dialog/types.js +15 -0
  131. package/dist/ui/book_dialog/types.js.map +1 -0
  132. package/locale/ar/messages.json +49 -0
  133. package/locale/bg/messages.json +49 -0
  134. package/locale/cs/messages.json +49 -0
  135. package/locale/da/messages.json +49 -0
  136. package/locale/de/messages.json +49 -0
  137. package/locale/en/messages.json +49 -0
  138. package/locale/en_US/messages.json +49 -0
  139. package/locale/es/messages.json +49 -0
  140. package/locale/fr/messages.json +49 -0
  141. package/locale/it/messages.json +49 -0
  142. package/locale/ja/messages.json +49 -0
  143. package/locale/ko/messages.json +49 -0
  144. package/locale/nb/messages.json +49 -0
  145. package/locale/nl/messages.json +49 -0
  146. package/locale/pl/messages.json +49 -0
  147. package/locale/pt_BR/messages.json +49 -0
  148. package/locale/pt_PT/messages.json +49 -0
  149. package/locale/ru/messages.json +49 -0
  150. package/locale/sv/messages.json +49 -0
  151. package/locale/tr/messages.json +49 -0
  152. package/locale/zh_Hans/messages.json +49 -0
  153. package/logo.svg +10 -0
  154. package/package.json +150 -5
  155. package/src/exporter/bits/index.ts +184 -0
  156. package/src/exporter/bits/templates.ts +107 -0
  157. package/src/exporter/docx/index.ts +258 -0
  158. package/src/exporter/docx/render.ts +177 -0
  159. package/src/exporter/epub/index.ts +496 -0
  160. package/src/exporter/epub/templates.ts +403 -0
  161. package/src/exporter/epub/tools.ts +68 -0
  162. package/src/exporter/html/index.ts +479 -0
  163. package/src/exporter/html/templates.ts +362 -0
  164. package/src/exporter/html/tools.ts +26 -0
  165. package/src/exporter/latex/index.ts +190 -0
  166. package/src/exporter/latex/templates.ts +35 -0
  167. package/src/exporter/native/index.ts +238 -0
  168. package/src/exporter/odt/index.ts +230 -0
  169. package/src/exporter/odt/render.ts +181 -0
  170. package/src/exporter/pretty.ts +75 -0
  171. package/src/exporter/print/index.ts +76 -0
  172. package/src/exporter/print/templates.ts +8 -0
  173. package/src/exporter/tools.ts +270 -0
  174. package/src/global.d.ts +2 -0
  175. package/src/i18n.ts +936 -0
  176. package/src/ids.ts +27 -0
  177. package/src/importer/native/index.ts +269 -0
  178. package/src/importer/native/reader.ts +247 -0
  179. package/src/index.ts +20 -0
  180. package/src/modules.d.ts +7 -0
  181. package/src/schema/index.ts +8 -0
  182. package/src/types.ts +208 -0
  183. package/src/ui/book_dialog/dialog.ts +940 -0
  184. package/src/ui/book_dialog/export.ts +449 -0
  185. package/src/ui/book_dialog/index.ts +84 -0
  186. package/src/ui/book_dialog/sanity_check.ts +208 -0
  187. package/src/ui/book_dialog/templates.ts +736 -0
  188. package/src/ui/book_dialog/types.ts +283 -0
@@ -0,0 +1,940 @@
1
+ /**
2
+ * The book edit dialog.
3
+ *
4
+ * A tabbed dialog that edits a book's metadata and settings, manages its
5
+ * chapter list (add/remove/reorder, part grouping and per-chapter part
6
+ * titles), picks the cover image, triggers a sanity check and starts an
7
+ * export.
8
+ *
9
+ * Everything host-specific is injected: see `./types.js`. The book *overview*
10
+ * page -- its datatable, bulk actions, sharing, copy and delete -- is not
11
+ * part of this component and stays with the host.
12
+ */
13
+
14
+ import type {Book, BookMetadata, Chapter, DocumentListEntry} from "../../types.js"
15
+ import {
16
+ ContentMenu,
17
+ Dialog,
18
+ FileSelector,
19
+ addAlert,
20
+ findTarget,
21
+ gettext
22
+ } from "fwtoolkit"
23
+ import type {DialogButtonSpec} from "fwtoolkit"
24
+ import {bookExportMenuModel} from "./export.js"
25
+ import type {BookExportMenu} from "./export.js"
26
+ import {bookSanityCheck} from "./sanity_check.js"
27
+ import {
28
+ bookBasicInfoTemplate,
29
+ bookBibliographyDataTemplate,
30
+ bookChapterDialogTemplate,
31
+ bookChapterListTemplate,
32
+ bookDOCXDataRowTemplate,
33
+ bookDOCXDataTemplate,
34
+ bookDialogChaptersTemplate,
35
+ bookDialogTemplate,
36
+ bookEpubDataCoverTemplate,
37
+ bookEpubDataTemplate,
38
+ bookODTDataRowTemplate,
39
+ bookODTDataTemplate,
40
+ bookPrintDataTemplate,
41
+ bookSanityCheckTemplate
42
+ } from "./templates.js"
43
+ import type {
44
+ BookDialogButton,
45
+ BookDialogImageDB,
46
+ BookDialogInfo,
47
+ BookDialogOptions,
48
+ BookDialogPart
49
+ } from "./types.js"
50
+
51
+ /** The file records fwtoolkit's file selector accepts. */
52
+ type FileSelectorFiles = ConstructorParameters<typeof FileSelector>[0]["files"]
53
+
54
+ /** The metadata a freshly created book starts out with. */
55
+ function emptyMetadata(): BookMetadata {
56
+ return {
57
+ author: "",
58
+ subtitle: "",
59
+ version: "",
60
+ publisher: "",
61
+ copyright: "",
62
+ keywords: "",
63
+ description: "",
64
+ isbn: "",
65
+ publication_date: "",
66
+ series_title: "",
67
+ series_position: ""
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Read a value out of one of the book dialog's form fields. The dialog markup
73
+ * comes from ./templates.js, so the ids are fixed.
74
+ */
75
+ function fieldValue(root: ParentNode, id: string): string {
76
+ return (root.querySelector(`#${id}`) as HTMLInputElement).value
77
+ }
78
+
79
+ /** The tabbed book editor. */
80
+ export class BookDialog {
81
+ options: BookDialogOptions
82
+ /** Whether this dialog creates a new book or edits an existing one. */
83
+ isNew: boolean
84
+ /** The book being edited. A working copy, not the host's own record. */
85
+ book: Book
86
+ documentList: BookDialogOptions["documentList"]
87
+ exportMenu: BookExportMenu
88
+ /** Callbacks invoked after the book has been saved. */
89
+ onSave: Array<(book: Book) => Promise<unknown> | unknown>
90
+ dialogParts: BookDialogPart[]
91
+ /** Cover images that are not part of the host's image database. */
92
+ bookImageDB: BookDialogImageDB
93
+ dialog: Dialog | null
94
+ /** The chapters tab's file selector, once the dialog is open. */
95
+ fileSelector: FileSelector | null
96
+
97
+ constructor(options: BookDialogOptions) {
98
+ this.options = options
99
+ this.documentList = options.documentList
100
+ this.exportMenu = bookExportMenuModel()
101
+ this.onSave = options.onSave ? [...options.onSave] : []
102
+ this.dialog = null
103
+ this.fileSelector = null
104
+ this.isNew = !options.book
105
+ this.book = this.isNew
106
+ ? this.createEmptyBook()
107
+ : this.workingCopy(options.book as Book)
108
+ this.bookImageDB = {db: {}}
109
+
110
+ if (this.book.cover_image && !this.imageDB().db[this.book.cover_image]) {
111
+ // The cover image is not in the current user's image DB -- it was
112
+ // either deleted or another user originally added it. As we don't
113
+ // do anything fancy with it, we simply add the current cover image
114
+ // to the DB locally so that image selection works as expected.
115
+ this.bookImageDB.db[this.book.cover_image] =
116
+ this.book.cover_image_data ?? {}
117
+ }
118
+
119
+ this.dialogParts = [
120
+ {
121
+ title: gettext("Basic info"),
122
+ description: gettext("Basic book information"),
123
+ template: bookBasicInfoTemplate
124
+ },
125
+ {
126
+ title: gettext("Chapters"),
127
+ description: gettext("Documents assigned as chapters"),
128
+ template: bookDialogChaptersTemplate
129
+ },
130
+ {
131
+ title: gettext("Bibliography"),
132
+ description: gettext("Bibliography related settings"),
133
+ template: bookBibliographyDataTemplate
134
+ },
135
+ {
136
+ title: gettext("Epub"),
137
+ description: gettext("Epub related settings"),
138
+ template: bookEpubDataTemplate
139
+ },
140
+ ...(this.options.backend.saveDocxTemplate
141
+ ? [
142
+ {
143
+ title: gettext("DOCX"),
144
+ description: gettext("DOCX related settings"),
145
+ template: bookDOCXDataTemplate
146
+ }
147
+ ]
148
+ : []),
149
+ ...(this.options.backend.saveOdtTemplate
150
+ ? [
151
+ {
152
+ title: gettext("ODT"),
153
+ description: gettext("ODT related settings"),
154
+ template: bookODTDataTemplate
155
+ }
156
+ ]
157
+ : []),
158
+ {
159
+ title: gettext("Print/PDF"),
160
+ description: gettext("Print related settings"),
161
+ template: bookPrintDataTemplate
162
+ },
163
+ {
164
+ title: gettext("Sanity check"),
165
+ description: gettext("Perform sanity check on book"),
166
+ template: bookSanityCheckTemplate
167
+ }
168
+ ]
169
+ }
170
+
171
+ /** The image database the dialog renders cover previews from. */
172
+ imageDB(): BookDialogImageDB {
173
+ return {
174
+ db: Object.assign(
175
+ {},
176
+ this.options.imageDB?.db ?? {},
177
+ this.bookImageDB.db
178
+ )
179
+ }
180
+ }
181
+
182
+ /** The dialog's root element, or the document before it is opened. */
183
+ root(): ParentNode {
184
+ return this.dialog?.dialogEl ?? document
185
+ }
186
+
187
+ /** The bundle the tab templates are rendered from. */
188
+ bookInfo(): BookDialogInfo {
189
+ return {
190
+ book: this.book,
191
+ documentList: this.documentList,
192
+ citationStyles: this.options.citationStyles ?? {},
193
+ bookStyleList: this.options.exportContext?.bookStyles ?? [],
194
+ imageDB: this.imageDB(),
195
+ canPickChapters: Boolean(this.options.backend.pickChapters),
196
+ canOpenChapters: Boolean(this.options.backend.openChapter),
197
+ chapterCatalog: this.options.chapterCatalog !== false
198
+ }
199
+ }
200
+
201
+ /** A brand new book with the dialog's default metadata and settings. */
202
+ createEmptyBook(): Book {
203
+ const {path = "/", exportContext} = this.options
204
+ return {
205
+ title: "",
206
+ id: 0,
207
+ chapters: [],
208
+ added: 0,
209
+ updated: 0,
210
+ path,
211
+ metadata: emptyMetadata(),
212
+ settings: {
213
+ bibliography_header: gettext("Bibliography"),
214
+ citationstyle: "apa",
215
+ book_style: exportContext?.bookStyles[0]
216
+ ? exportContext.bookStyles[0].slug
217
+ : ("" as string),
218
+ papersize: "octavo",
219
+ language: "en-US"
220
+ }
221
+ } as Book
222
+ }
223
+
224
+ /**
225
+ * The dialog's working copy of an existing book.
226
+ *
227
+ * The record is copied shallowly -- the `chapters` array stays shared with
228
+ * the host's record, exactly as the Django backend's dialog behaved -- and
229
+ * the metadata block is merged onto a complete one so every form field
230
+ * has something to read back.
231
+ */
232
+ workingCopy(book: Book): Book {
233
+ return Object.assign({}, book, {
234
+ metadata: Object.assign(emptyMetadata(), book.metadata)
235
+ })
236
+ }
237
+
238
+ /**
239
+ * The dialog's buttons, from the host's `buttons` option or the classic
240
+ * default row (Export dropdown, Save, Cancel -- or Close for a read-only
241
+ * book).
242
+ */
243
+ buildButtons(): DialogButtonSpec[] {
244
+ const specs = this.options.buttons ?? this.defaultButtons()
245
+ return specs.map(spec => {
246
+ if (spec.type) {
247
+ return {type: spec.type}
248
+ }
249
+ return {
250
+ text: spec.text,
251
+ classes: spec.classes ?? "fw-dark",
252
+ icon: spec.icon,
253
+ dropdown: spec.dropdown,
254
+ click: (event?: Event) => this.runButton(spec, event)
255
+ }
256
+ })
257
+ }
258
+
259
+ /** The classic button row, used when the host supplies none. */
260
+ defaultButtons(): BookDialogButton[] {
261
+ if (this.readOnly()) {
262
+ return [{type: "close"}]
263
+ }
264
+ const specs: BookDialogButton[] = []
265
+ if (this.options.exportContext) {
266
+ specs.push({
267
+ text: gettext("Export"),
268
+ dropdown: true,
269
+ keepOpen: true,
270
+ click: (dialog, event) => dialog.openExportMenu(event)
271
+ })
272
+ }
273
+ specs.push({text: gettext("Save"), click: dialog => dialog.saveBook()})
274
+ specs.push({type: "cancel"})
275
+ return specs
276
+ }
277
+
278
+ /** Run a button's action, closing the dialog unless it wants to stay. */
279
+ runButton(spec: BookDialogButton, event?: Event): unknown {
280
+ const result = spec.click?.(this, event)
281
+ const close = () => {
282
+ if (!spec.keepOpen) {
283
+ this.dialog?.close()
284
+ }
285
+ }
286
+ if (result instanceof Promise) {
287
+ return result.then(close)
288
+ }
289
+ close()
290
+ return result
291
+ }
292
+
293
+ /**
294
+ * Open the export dropdown menu at the position of the triggering event.
295
+ *
296
+ * Exposed for hosts that build their own button row: the Export button
297
+ * is just a dropdown-styled button whose click calls this. Does nothing
298
+ * when no export context was given.
299
+ */
300
+ openExportMenu(event?: Event): unknown {
301
+ if (!this.options.exportContext) {
302
+ return undefined
303
+ }
304
+ const mouseEvent = event as MouseEvent
305
+ const contentMenu = new ContentMenu({
306
+ page: {
307
+ saveBook: (exportId?: string) => this.saveBook(exportId),
308
+ book: this.book,
309
+ documentList: this.documentList,
310
+ context: this.options.exportContext
311
+ },
312
+ menu: this.exportMenu,
313
+ menuPos: {X: mouseEvent.pageX, Y: mouseEvent.pageY},
314
+ width: 250
315
+ })
316
+ return contentMenu.open()
317
+ }
318
+
319
+ /** Render and open the dialog. */
320
+ open(): void {
321
+ const title = this.isNew ? gettext("Create Book") : gettext("Edit Book")
322
+ const body = bookDialogTemplate({
323
+ title,
324
+ dialogParts: this.dialogParts,
325
+ bookInfo: this.bookInfo()
326
+ })
327
+
328
+ const dialog = new Dialog({
329
+ width: 840,
330
+ height: 520,
331
+ title,
332
+ body,
333
+ buttons: this.buildButtons(),
334
+ fullScreen: this.options.fullScreen,
335
+ canClose: this.options.canClose,
336
+ canEscape: this.options.canEscape,
337
+ ...(this.options.onClose ? {onClose: this.options.onClose} : {})
338
+ })
339
+ dialog.open()
340
+ this.dialog = dialog
341
+
342
+ dialog.dialogEl
343
+ .querySelectorAll<HTMLElement>("#bookoptions-tab .tab-content")
344
+ .forEach((el, index) => {
345
+ if (index) {
346
+ el.style.display = "none"
347
+ }
348
+ })
349
+
350
+ if (!this.readOnly()) {
351
+ this.refreshFileSelector()
352
+ this.bindTemplateInput(
353
+ dialog,
354
+ "input-docx-template",
355
+ "docx-template-row",
356
+ (book, template) => {
357
+ book.docx_template = template
358
+ },
359
+ this.options.backend.saveDocxTemplate?.bind(this.options.backend)
360
+ )
361
+ this.bindTemplateInput(
362
+ dialog,
363
+ "input-odt-template",
364
+ "odt-template-row",
365
+ (book, template) => {
366
+ book.odt_template = template
367
+ },
368
+ this.options.backend.saveOdtTemplate?.bind(this.options.backend)
369
+ )
370
+ }
371
+
372
+ // Handle tab link clicking
373
+ dialog.dialogEl
374
+ .querySelectorAll<HTMLAnchorElement>(
375
+ "#bookoptions-tab .fw-tab-link a"
376
+ )
377
+ .forEach(el => {
378
+ const tab = el.parentElement as HTMLElement
379
+ const tabList = tab.parentElement as HTMLElement
380
+ el.addEventListener("click", event => {
381
+ event.preventDefault()
382
+
383
+ tabList
384
+ .querySelectorAll<HTMLElement>(
385
+ ".fw-tab-link.fw-current-tab"
386
+ )
387
+ .forEach(other =>
388
+ other.classList.remove("fw-current-tab")
389
+ )
390
+ tab.classList.add("fw-current-tab")
391
+
392
+ const link = el.getAttribute("href") as string
393
+ dialog.dialogEl
394
+ .querySelectorAll<HTMLElement>(
395
+ "#bookoptions-tab .tab-content"
396
+ )
397
+ .forEach(panel => {
398
+ if (panel.matches(link)) {
399
+ panel.style.display = ""
400
+ } else {
401
+ panel.style.display = "none"
402
+ }
403
+ })
404
+ })
405
+ })
406
+
407
+ dialog.dialogEl.addEventListener("click", event =>
408
+ this.handleDialogClick(event)
409
+ )
410
+
411
+ const citationStyleSelect = dialog.dialogEl.querySelector<HTMLSelectElement>(
412
+ "#book-settings-citationstyle"
413
+ )
414
+ if (citationStyleSelect) {
415
+ citationStyleSelect.addEventListener("change", event => {
416
+ this.book.settings.citationstyle = (
417
+ event.target as HTMLSelectElement
418
+ ).value
419
+ })
420
+ }
421
+
422
+ const bookStyleSelect =
423
+ dialog.dialogEl.querySelector<HTMLSelectElement>(
424
+ "#book-settings-bookstyle"
425
+ )
426
+ if (bookStyleSelect) {
427
+ bookStyleSelect.addEventListener("change", event => {
428
+ this.book.settings.book_style = (
429
+ event.target as HTMLSelectElement
430
+ ).value
431
+ })
432
+ }
433
+
434
+ const paperSizeSelect =
435
+ dialog.dialogEl.querySelector<HTMLSelectElement>(
436
+ "#book-settings-papersize"
437
+ )
438
+ if (paperSizeSelect) {
439
+ paperSizeSelect.addEventListener("change", event => {
440
+ this.book.settings.papersize = (
441
+ event.target as HTMLSelectElement
442
+ ).value
443
+ })
444
+ }
445
+ }
446
+
447
+ /** Whether the book is only readable, i.e. not editable. */
448
+ readOnly(): boolean {
449
+ return this.book.rights === "read"
450
+ }
451
+
452
+ /**
453
+ * Let the user pick a DOCX/ODT template file and hand it to the host.
454
+ *
455
+ * The book is saved first, because a freshly created book has no id the
456
+ * host could attach a template to.
457
+ */
458
+ bindTemplateInput(
459
+ dialog: Dialog,
460
+ inputId: string,
461
+ rowId: string,
462
+ applyTemplate: (book: Book, template: string) => void,
463
+ saveTemplate?: (book: Book, file: File) => Promise<string | null>
464
+ ): void {
465
+ const input =
466
+ dialog.dialogEl.querySelector<HTMLInputElement>(`#${inputId}`)
467
+ if (!input || !saveTemplate) {
468
+ return
469
+ }
470
+ input.addEventListener("change", event => {
471
+ const file = (event.target as HTMLInputElement).files![0]
472
+ return this.saveBook()
473
+ .then(() => saveTemplate(this.book, file))
474
+ .then(template => {
475
+ if (!template) {
476
+ return
477
+ }
478
+ applyTemplate(this.book, template)
479
+ this.refreshRow(
480
+ rowId,
481
+ rowId === "docx-template-row"
482
+ ? bookDOCXDataRowTemplate({book: this.book})
483
+ : bookODTDataRowTemplate({book: this.book})
484
+ )
485
+ })
486
+ })
487
+ }
488
+
489
+ /** Replace the markup of one of the dialog's rows. */
490
+ refreshRow(rowId: string, html: string): void {
491
+ const row = this.root().querySelector(`#${rowId}`)
492
+ if (row) {
493
+ row.innerHTML = html
494
+ }
495
+ }
496
+
497
+ /**
498
+ * (Re-)build the chapters tab's file selector from the document list.
499
+ *
500
+ * Hosts can extend the list after the dialog opened -- the desktop adds
501
+ * the files the user picked through its native file dialog -- so the
502
+ * selector is rebuilt rather than created only in `open()`.
503
+ */
504
+ refreshFileSelector(): void {
505
+ if (this.readOnly() || !this.dialog) {
506
+ return
507
+ }
508
+ const dom = this.dialog.dialogEl.querySelector<HTMLElement>(
509
+ "#book-document-list"
510
+ )
511
+ if (!dom) {
512
+ return
513
+ }
514
+ this.fileSelector = new FileSelector({
515
+ dom,
516
+ files: this.documentList as unknown as FileSelectorFiles,
517
+ multiSelect: true,
518
+ selectFolders: false
519
+ })
520
+ this.fileSelector.init()
521
+ }
522
+
523
+ /**
524
+ * Replace the document list the dialog's catalog and chapter rows read
525
+ * from, and refresh the affected parts of the dialog.
526
+ */
527
+ setDocumentList(documentList: BookDialogOptions["documentList"]): void {
528
+ this.documentList = documentList
529
+ this.refreshFileSelector()
530
+ this.refreshChapterList()
531
+ this.updateChapterNotice()
532
+ }
533
+
534
+ /** Re-render the chapter list. */
535
+ refreshChapterList(): void {
536
+ this.refreshRow(
537
+ "book-chapter-list",
538
+ bookChapterListTemplate({
539
+ book: this.book,
540
+ documentList: this.documentList
541
+ })
542
+ )
543
+ }
544
+
545
+ /**
546
+ * Add or remove the encrypted-chapters notice that lives alongside the
547
+ * chapter list. Called after any operation that changes book.chapters so
548
+ * the notice stays in sync.
549
+ */
550
+ updateChapterNotice(): void {
551
+ const chapterListEl = this.root().querySelector("#book-chapter-list")
552
+ if (!chapterListEl) {
553
+ return
554
+ }
555
+ const container = chapterListEl.closest(".fw-ar-container")
556
+ if (!container) {
557
+ return
558
+ }
559
+ const existingNotice = container.querySelector(".e2ee-chapter-notice")
560
+ const hasEncrypted = this.book.chapters.some(ch =>
561
+ this.documentList.find(doc => doc.id === ch.text)?.e2ee
562
+ )
563
+ if (hasEncrypted && !existingNotice) {
564
+ container.insertAdjacentHTML(
565
+ "beforeend",
566
+ `<p class="fw-note e2ee-chapter-notice">
567
+ <i class="fas fa-lock"></i>
568
+ ${gettext("This book contains encrypted chapters. A personal passphrase is required to export or run a sanity check on this book.")}
569
+ </p>`
570
+ )
571
+ } else if (!hasEncrypted && existingNotice) {
572
+ existingNotice.remove()
573
+ }
574
+ }
575
+
576
+ /** Open a sub-dialog to edit a chapter's part title. */
577
+ editChapterDialog(chapter: Chapter): void {
578
+ const doc = this.documentList.find(doc => doc.id === chapter.text)
579
+ let docTitle = doc?.title ?? ""
580
+ if (!docTitle.length) {
581
+ docTitle = gettext("Untitled")
582
+ }
583
+
584
+ const buttons: DialogButtonSpec[] = [
585
+ {
586
+ type: "cancel"
587
+ },
588
+ {
589
+ text: gettext("Submit"),
590
+ classes: "fw-dark",
591
+ click: () => {
592
+ // The part-title field lives in this sub-dialog, not in
593
+ // the book dialog's own root.
594
+ chapter.part = fieldValue(
595
+ dialog.dialogEl,
596
+ "book-chapter-part"
597
+ )
598
+ this.refreshChapterList()
599
+ dialog.close()
600
+ }
601
+ }
602
+ ]
603
+
604
+ const dialog = new Dialog({
605
+ title: `${gettext("Edit Chapter")}: ${chapter.number}. ${docTitle}`,
606
+ body: bookChapterDialogTemplate({chapter}),
607
+ width: 300,
608
+ height: 100,
609
+ buttons
610
+ })
611
+ dialog.open()
612
+ }
613
+
614
+ /** Let the user pick the cover image through the host's image picker. */
615
+ selectCoverImage(): Promise<void> {
616
+ return Promise.resolve(
617
+ this.options.backend.selectCoverImage?.(this.book.cover_image ?? false)
618
+ ).then(selected => {
619
+ if (!selected) {
620
+ delete this.book.cover_image
621
+ } else {
622
+ this.book.cover_image = selected.id
623
+ this.book.cover_image_data = selected.data
624
+ this.bookImageDB.db[selected.id] = selected.data
625
+ }
626
+ this.refreshRow(
627
+ "cover-preview-row",
628
+ bookEpubDataCoverTemplate({
629
+ book: this.book,
630
+ imageDB: this.imageDB()
631
+ })
632
+ )
633
+ })
634
+ }
635
+
636
+ /**
637
+ * Read the form fields into the book record without persisting.
638
+ *
639
+ * Chapter and part edits live in `this.book` directly, but the metadata
640
+ * and settings fields are only read back on save. Hosts that write the
641
+ * book from outside the dialog -- a window-close flush, a Save-as in the
642
+ * host UI -- call this first so the edited state is complete. A no-op
643
+ * when the dialog is closed or the book is read-only.
644
+ *
645
+ * @returns The dialog's book record with the form fields applied.
646
+ */
647
+ syncEdits(): Book {
648
+ const book = this.book
649
+ if (this.readOnly() || !this.dialog) {
650
+ return book
651
+ }
652
+ const root = this.root()
653
+ book.title = fieldValue(root, "book-title")
654
+ book.metadata.author = fieldValue(root, "book-metadata-author")
655
+ book.metadata.subtitle = fieldValue(root, "book-metadata-subtitle")
656
+ book.metadata.version = fieldValue(root, "book-metadata-version")
657
+ book.metadata.copyright = fieldValue(root, "book-metadata-copyright")
658
+ book.metadata.publisher = fieldValue(root, "book-metadata-publisher")
659
+ book.metadata.keywords = fieldValue(root, "book-metadata-keywords")
660
+ book.metadata.description = fieldValue(root, "book-metadata-description")
661
+ book.metadata.isbn = fieldValue(root, "book-metadata-isbn")
662
+ book.metadata.publication_date = fieldValue(
663
+ root,
664
+ "book-metadata-publication-date"
665
+ )
666
+ book.metadata.series_title = fieldValue(root, "book-metadata-series-title")
667
+ book.metadata.series_position = fieldValue(
668
+ root,
669
+ "book-metadata-series-position"
670
+ )
671
+ book.settings.language = fieldValue(root, "book-settings-language")
672
+ book.path = (this.isNew ? "" : (book.path ?? "")) || this.options.path || ""
673
+ return book
674
+ }
675
+
676
+ /**
677
+ * Persist the edited book through the host and notify the save callbacks.
678
+ *
679
+ * Must only be called while the dialog is open.
680
+ */
681
+ saveBook(exportId?: string): Promise<unknown> {
682
+ const book = this.book
683
+ if (this.readOnly()) {
684
+ return Promise.resolve()
685
+ }
686
+ this.syncEdits()
687
+
688
+ return this.options.backend
689
+ .saveBook(book, exportId)
690
+ .catch((error: unknown) => {
691
+ // Include the cause: a bare "could not be saved" leaves hosts
692
+ // (and users) with no way to tell a cancelled picker from a
693
+ // failed write.
694
+ addAlert(
695
+ "error",
696
+ `${gettext("The book could not be saved")}: ${
697
+ error instanceof Error ? error.message : String(error)
698
+ }`
699
+ )
700
+ throw error
701
+ })
702
+ .then(async saved => {
703
+ if (!saved) {
704
+ // The host handed the session to a new window (an
705
+ // untitled book promoted to its real path) and resumes
706
+ // the triggering export there; nothing to update here.
707
+ return false
708
+ }
709
+ this.book = Object.assign(book, {
710
+ id: saved.id ?? book.id,
711
+ added: saved.added ?? book.added,
712
+ updated: saved.updated ?? book.updated
713
+ })
714
+ await Promise.all(this.onSave.map(method => method(this.book)))
715
+ return true
716
+ })
717
+ }
718
+
719
+ /**
720
+ * Move a chapter one position up or down the list.
721
+ *
722
+ * @param docId - Id of the chapter document to move.
723
+ * @param offset - `-1` to move up, `1` to move down.
724
+ */
725
+ moveChapter(docId: number, offset: number): void {
726
+ const chapter = this.book.chapters.find(
727
+ chapter => chapter.text === docId
728
+ ) as Chapter
729
+ const neighbour = this.book.chapters.find(
730
+ other => other.number === chapter.number + offset
731
+ ) as Chapter
732
+ if (!neighbour) {
733
+ return
734
+ }
735
+ chapter.number += offset
736
+ neighbour.number -= offset
737
+ this.refreshChapterList()
738
+ this.updateChapterNotice()
739
+ }
740
+
741
+ /** Remove a chapter from the book and close the numbering gap. */
742
+ removeChapter(docId: number): void {
743
+ const chapter = this.book.chapters.find(
744
+ chapter => chapter.text === docId
745
+ ) as Chapter
746
+ if (!chapter) {
747
+ return
748
+ }
749
+ this.book.chapters.forEach(other => {
750
+ if (other.number > chapter.number) {
751
+ other.number--
752
+ }
753
+ })
754
+ this.book.chapters = this.book.chapters.filter(
755
+ other => other !== chapter
756
+ )
757
+ this.refreshChapterList()
758
+ this.updateChapterNotice()
759
+ }
760
+
761
+ /**
762
+ * Add a document as the book's next chapter.
763
+ *
764
+ * External documents (standalone files the host picked) carry their file
765
+ * location onto the chapter, so file-based hosts can re-resolve the live
766
+ * document on the next load.
767
+ */
768
+ addChapter(doc: DocumentListEntry): void {
769
+ if (this.book.chapters.some(chapter => chapter.text === doc.id)) {
770
+ return
771
+ }
772
+ const chapNums = this.book.chapters.map(chapter => chapter.number)
773
+ const number = chapNums.length ? Math.max(...chapNums) + 1 : 1
774
+ this.book.chapters.push({
775
+ text: doc.id as number,
776
+ number,
777
+ part: "",
778
+ ...(doc.external && doc.path ? {path: doc.path} : {})
779
+ })
780
+ }
781
+
782
+ /** Append the documents selected in the file selector as new chapters. */
783
+ addChapters(fileSelector: FileSelector): void {
784
+ fileSelector.selected.forEach(entry => {
785
+ if (entry.type !== "file") {
786
+ return
787
+ }
788
+ this.addChapter(entry.file as unknown as DocumentListEntry)
789
+ })
790
+ fileSelector.deselectAll()
791
+
792
+ this.refreshChapterList()
793
+ this.updateChapterNotice()
794
+ }
795
+
796
+ /**
797
+ * Let the user pick standalone documents through the host and add them as
798
+ * chapters.
799
+ *
800
+ * The host returns stub entries for the picked files; the dialog merges
801
+ * them into the catalog so they show up in the file selector, and adds
802
+ * each as a chapter. The chapter content itself is resolved by the host
803
+ * when the book is saved or exported.
804
+ */
805
+ addPickedChapters(): Promise<void> {
806
+ if (!this.options.backend.pickChapters) {
807
+ return Promise.resolve()
808
+ }
809
+ return this.options.backend.pickChapters().then(picked => {
810
+ if (!picked.length) {
811
+ return
812
+ }
813
+ picked.forEach(doc => {
814
+ if (!this.documentList.some(existing => existing.id === doc.id)) {
815
+ this.documentList.push(doc)
816
+ }
817
+ this.addChapter(doc)
818
+ })
819
+ this.refreshFileSelector()
820
+ this.refreshChapterList()
821
+ this.updateChapterNotice()
822
+ })
823
+ }
824
+
825
+ /** Handle a click anywhere inside the dialog. */
826
+ handleDialogClick(event: Event): void {
827
+ const el: {target?: HTMLElement} = {}
828
+ // `findTarget` fills `el.target` with the matching ancestor; all the
829
+ // chapter/template rows carry their document id in a data attribute.
830
+ const clickedId = (): number =>
831
+ Number.parseInt(el.target!.dataset.id as string)
832
+
833
+ switch (true) {
834
+ case findTarget(event, ".book-sort-up", el):
835
+ this.moveChapter(clickedId(), -1)
836
+ break
837
+ case findTarget(event, ".book-sort-down", el):
838
+ this.moveChapter(clickedId(), 1)
839
+ break
840
+ case findTarget(event, ".delete-chapter", el):
841
+ this.removeChapter(clickedId())
842
+ break
843
+ case findTarget(event, "#add-chapter", el):
844
+ if (this.fileSelector) {
845
+ this.addChapters(this.fileSelector)
846
+ }
847
+ break
848
+ case findTarget(event, "#add-chapter-file", el):
849
+ void this.addPickedChapters()
850
+ break
851
+ case findTarget(event, ".open-chapter", el): {
852
+ const chapter = this.book.chapters.find(
853
+ candidate => candidate.text === clickedId()
854
+ )
855
+ if (chapter) {
856
+ this.options.backend.openChapter?.(chapter)
857
+ }
858
+ break
859
+ }
860
+ case findTarget(event, ".edit-chapter", el):
861
+ this.editChapterDialog(
862
+ this.book.chapters.find(
863
+ chapter => chapter.text === clickedId()
864
+ ) as Chapter
865
+ )
866
+ break
867
+ case findTarget(event, "#select-cover-image-button", el):
868
+ this.selectCoverImage()
869
+ break
870
+ case findTarget(event, "#select-docx-template", el): {
871
+ const input = this.root().querySelector<HTMLElement>(
872
+ "#input-docx-template"
873
+ )
874
+ input!.click()
875
+ break
876
+ }
877
+ case findTarget(event, "#select-odt-template", el): {
878
+ const input = this.root().querySelector<HTMLElement>(
879
+ "#input-odt-template"
880
+ )
881
+ input!.click()
882
+ break
883
+ }
884
+ case findTarget(event, "#remove-cover-image-button", el): {
885
+ delete this.book.cover_image
886
+ this.refreshRow(
887
+ "cover-preview-row",
888
+ bookEpubDataCoverTemplate({
889
+ book: this.book,
890
+ // We just deleted the cover image, so we don't need a
891
+ // full DB.
892
+ imageDB: {db: {}}
893
+ })
894
+ )
895
+ break
896
+ }
897
+ case findTarget(event, "#remove-docx-template-button", el): {
898
+ delete this.book.docx_template
899
+ this.refreshRow(
900
+ "docx-template-row",
901
+ bookDOCXDataRowTemplate({book: this.book})
902
+ )
903
+ break
904
+ }
905
+ case findTarget(event, "#remove-odt-template-button", el): {
906
+ delete this.book.odt_template
907
+ this.refreshRow(
908
+ "odt-template-row",
909
+ bookODTDataRowTemplate({book: this.book})
910
+ )
911
+ break
912
+ }
913
+ case findTarget(event, "#perform-sanity-check-button", el): {
914
+ this.performSanityCheck()
915
+ break
916
+ }
917
+ default:
918
+ break
919
+ }
920
+ }
921
+
922
+ /** Save the book and render its sanity check report in place. */
923
+ performSanityCheck(): Promise<void> {
924
+ const {schema, chapterLoader, e2ee} = this.options
925
+ return this.saveBook()
926
+ .then(() =>
927
+ bookSanityCheck(this.book, this.documentList, {
928
+ schema,
929
+ chapterLoader,
930
+ e2ee
931
+ })
932
+ )
933
+ .then(sanityCheckOutputHTML => {
934
+ const sanityCheckOutput = this.root().querySelector("#sanity-check-output")
935
+ if (sanityCheckOutput) {
936
+ sanityCheckOutput.innerHTML = sanityCheckOutputHTML
937
+ }
938
+ })
939
+ }
940
+ }