Repository navigation
Expand file tree
/
Copy pathmodel.ts
More file actions
612 lines (606 loc) · 20.5 KB
/
Copy pathmodel.ts
File metadata and controls
612 lines (606 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import { msg, LocalizedError } from '../i18n'
import { z } from 'zod'
import { createEmptyCard, type Card as FsrsCard } from 'ts-fsrs'
import { scheduleSchema, librarySchema as legacySchema } from './legacy'
import { pluginDataSchema, assessmentSchema } from '../plugins/data'
import { sourceSchema, excerptSchema, MAX_SOURCE_BYTES } from './source-data'
import { validateSourceHierarchy } from './source-tree'
import { practiceSchema, attemptSchema, attemptSummarySchema } from './practice-data'
export { scheduleSchema } from './legacy'
const date = z.iso.datetime()
const id = z.string().min(1).max(150)
const tags = z.array(z.string().trim().min(1).max(40)).max(20)
const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/)
const autoBurialSchema = z.object({ day, reviewId: id })
export const filterStates = [
'all',
'新卡片',
'待复习',
'学习中',
'复习中',
'已暂停',
'今日暂缓',
'顽固卡',
] as const
export const savedSearchSchema = z.object({
id,
name: z.string().trim().min(1).max(80),
query: z.string().max(1000),
deckId: z.string().max(150),
state: z.enum(filterStates),
})
export type SavedSearch = z.infer<typeof savedSearchSchema>
export type SearchFilter = Pick<SavedSearch, 'query' | 'deckId' | 'state'>
export interface StudySession {
ids: string[]
reschedule: boolean
}
export const colors = ['sage', 'sand', 'lavender', 'blue', 'rose'] as const
export const noteTypes = {
basic: '正反面',
reversed: '双向卡',
cloze: '挖空卡',
plugin: '插件题目',
} as const
export const mediaTypes = [
'image/png',
'image/jpeg',
'image/webp',
'image/gif',
'audio/mpeg',
'audio/wav',
'audio/x-wav',
'audio/ogg',
'audio/mp4',
'audio/webm',
'audio/flac',
'audio/aac',
] as const
export const MAX_MEDIA_BYTES = 10 * 1024 * 1024
export const MAX_BACKUP_BYTES = 100 * 1024 * 1024
export function clozes(text: string) {
const result: { raw: string; number: number; answer: string; hint: string }[] = []
const fail = () =>
new LocalizedError(
msg('挖空格式应为 {{c1::答案}} 或 {{c1::答案::提示}},编号为 1–99,不支持嵌套挖空。'),
)
const starts = /\{\{c/gi
let match: RegExpExecArray | null
while ((match = starts.exec(text))) {
const header = text.slice(match.index).match(/^\{\{c([1-9]\d?)::/)
if (!header) throw fail()
const start = match.index + header[0].length
let end = start,
depth = 0
for (; end < text.length; end++) {
if (/^\{\{c/i.test(text.slice(end))) throw fail()
if (text.startsWith('}}', end) && depth === 0) break
if (text[end] === '\\' && !(depth === 0 && text.startsWith('}}', end + 1))) {
end++
continue
}
if (text[end] === '{') depth++
if (text[end] === '}' && --depth < 0) throw fail()
}
if (end >= text.length) throw fail()
const [answer, ...hints] = text.slice(start, end).split('::')
if (!answer?.trim()) throw new LocalizedError(msg('挖空答案不能为空。'))
result.push({
raw: text.slice(match.index, end + 2),
number: Number(header[1]),
answer,
hint: hints.join('::'),
})
starts.lastIndex = end + 2
}
if (!result.length) throw fail()
return result
}
export const deckSchema = z.object({
id,
name: z.string().trim().min(1).max(80),
description: z.string().max(300),
color: z.enum(colors),
createdAt: date,
newLimit: z.number().int().min(0).max(9999).default(20),
reviewLimit: z.number().int().min(0).max(9999).default(200),
burySiblings: z.boolean().default(true),
leechThreshold: z.number().int().min(0).max(100).default(8),
desiredRetention: z.number().min(0.7).max(0.97).default(0.9),
})
export const noteSchema = z
.object({
id,
deckId: id,
type: z.enum(['basic', 'reversed', 'cloze', 'plugin']),
plugin: pluginDataSchema.optional(),
excerpt: excerptSchema.optional(),
format: z.enum(['plain', 'markdown']).default('plain'),
front: z.string().trim().min(1).max(10_000),
back: z.string().trim().max(10_000),
tags,
frontMedia: z.array(id).max(8),
backMedia: z.array(id).max(8),
createdAt: date,
updatedAt: date,
})
.superRefine((note, ctx) => {
if (note.type !== 'cloze' && note.type !== 'plugin' && !note.back)
ctx.addIssue({ code: 'custom', message: '答案不能为空' })
if (note.type === 'plugin' && !note.plugin)
ctx.addIssue({ code: 'custom', message: '请选择题目插件。' })
if (note.type !== 'plugin' && note.plugin)
ctx.addIssue({ code: 'custom', message: '普通卡片不能包含插件数据。' })
if (note.type === 'cloze') {
try {
clozes(note.front)
} catch (error) {
ctx.addIssue({
code: 'custom',
message: (error as Error).message,
params: error instanceof LocalizedError ? { i18n: error.detail } : undefined,
})
}
}
})
export const cardSchema = z.object({
id,
noteId: id,
variant: z.string().regex(/^(forward|reverse|cloze:[1-9]\d?)$/),
schedule: scheduleSchema,
createdAt: date,
updatedAt: date,
suspended: z.boolean(),
leech: z.boolean().default(false),
autoBurial: autoBurialSchema.optional(),
buriedOn: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.optional(),
})
export const mediaSchema = z.object({
id,
name: z.string().min(1).max(255),
type: z.enum([...mediaTypes, 'text/plain', 'text/markdown']),
size: z.number().int().positive().max(MAX_MEDIA_BYTES),
createdAt: date,
})
export const reviewSchema = z.object({
id,
cardId: id,
rating: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]),
reviewedAt: date,
nextDue: date,
studyDay: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
kind: z.enum(['new', 'review', 'learning', 'legacy']),
source: z.enum(['normal', 'filtered']).default('normal'),
assessment: assessmentSchema.optional(),
practiceId: id.optional(),
effects: z
.object({
siblings: z.array(z.object({ cardId: id, previous: autoBurialSchema.optional() })).max(99),
markedLeech: z.boolean(),
})
.optional(),
previous: z.object({ schedule: scheduleSchema, updatedAt: date }).optional(),
})
export type Schedule = z.infer<typeof scheduleSchema>
export type Deck = z.infer<typeof deckSchema>
export type Note = z.infer<typeof noteSchema>
export type Card = z.infer<typeof cardSchema>
export type Media = z.infer<typeof mediaSchema>
export type Review = z.infer<typeof reviewSchema>
export type Grade = Review['rating']
export type DeckInput = Pick<
Deck,
| 'name'
| 'description'
| 'color'
| 'newLimit'
| 'reviewLimit'
| 'burySiblings'
| 'leechThreshold'
| 'desiredRetention'
>
export type NoteInput = Pick<
Note,
'deckId' | 'type' | 'front' | 'back' | 'tags' | 'frontMedia' | 'backMedia' | 'plugin' | 'excerpt'
> & { format?: Note['format'] }
export type CardView = Card &
Pick<
Note,
| 'deckId'
| 'front'
| 'back'
| 'tags'
| 'type'
| 'format'
| 'frontMedia'
| 'backMedia'
| 'plugin'
| 'excerpt'
> & { cloze?: { answers: string[]; context: string; extra: string } }
export interface MediaUpload {
meta: Media
blob: Blob
}
export function variants(note: Pick<Note, 'type' | 'front'>): string[] {
if (note.type === 'basic' || note.type === 'plugin') return ['forward']
if (note.type === 'reversed') return ['forward', 'reverse']
return [...new Set(clozes(note.front).map((cloze) => cloze.number))]
.sort((a, b) => a - b)
.map((number) => `cloze:${number}`)
}
const libraryContents = z.object({
version: z.literal(13),
sources: z.array(sourceSchema).max(10_000),
practices: z.array(practiceSchema).max(100_000),
attempts: z.array(attemptSchema).max(500_000),
savedSearches: z.array(savedSearchSchema).max(100).default([]),
decks: z.array(deckSchema).max(1000),
notes: z.array(noteSchema).max(100_000),
cards: z.array(cardSchema).max(200_000),
reviews: z.array(reviewSchema).max(500_000),
media: z.array(mediaSchema).max(100_000),
})
export function validateLibraryReferences(
library: Omit<z.infer<typeof libraryContents>, 'attempts'> & {
attempts: { id: string; practiceId: string }[]
},
problem: (message: string) => void,
) {
for (const key of [
'decks',
'notes',
'cards',
'reviews',
'media',
'savedSearches',
'practices',
'attempts',
'sources',
] as const) {
if (new Set(library[key].map((entry) => entry.id)).size !== library[key].length)
problem(`${key} 中存在重复 ID`)
}
const decks = new Set(library.decks.map((deck) => deck.id))
const notes = new Map(library.notes.map((note) => [note.id, note]))
const cards = new Set(library.cards.map((card) => card.id))
const media = new Map(library.media.map((item) => [item.id, item]))
const sources = new Map(library.sources.map((source) => [source.id, source]))
for (const source of library.sources) {
const asset = media.get(source.mediaId)
if (
!asset ||
asset.type !== (source.format === 'markdown' ? 'text/markdown' : 'text/plain') ||
asset.size > MAX_SOURCE_BYTES
)
problem('来源正文缺失或格式不正确')
if (source.origin) {
const parent = sources.get(source.origin.sourceId)
if (!parent || source.format !== parent.format || source.origin.end > parent.characters)
problem('摘录与来源不匹配')
}
}
validateSourceHierarchy(library.sources, problem)
const cardVariants = new Map<string, string[]>()
for (const card of library.cards) {
if (!notes.has(card.noteId)) problem('卡片所属笔记不存在')
cardVariants.set(card.noteId, [...(cardVariants.get(card.noteId) ?? []), card.variant])
}
for (const note of library.notes) {
if (!decks.has(note.deckId)) problem('笔记所属卡组不存在')
if ([...note.frontMedia, ...note.backMedia].some((mediaId) => !media.has(mediaId)))
problem('笔记引用的媒体不存在')
if (
[...note.frontMedia, ...note.backMedia].some((id) => media.get(id)?.type.startsWith('text/'))
)
problem('正文快照不能用作图片或音频')
if (note.excerpt) {
const source = sources.get(note.excerpt.sourceId)
if (
!source ||
note.excerpt.end > source.characters ||
note.excerpt.end - note.excerpt.start !== note.excerpt.quote.length
)
problem('摘录与来源不匹配')
}
try {
if (variants(note).sort().join(',') !== (cardVariants.get(note.id) ?? []).sort().join(','))
problem('卡片与笔记生成规则不匹配')
} catch {
problem('挖空格式不正确')
}
}
if (library.reviews.some((review) => !cards.has(review.cardId)))
problem('复习记录对应的卡片不存在')
const practices = new Map(library.practices.map((entry) => [entry.id, entry]))
if (library.practices.some((entry) => !cards.has(entry.cardId))) problem('练习对应的卡片不存在')
if (library.attempts.some((entry) => !practices.has(entry.practiceId)))
problem('提交对应的练习不存在')
for (const review of library.reviews) {
if (review.practiceId && practices.get(review.practiceId)?.cardId !== review.cardId)
problem('评分与练习不匹配')
}
const reviews = new Map(library.reviews.map((entry) => [entry.id, entry]))
for (const practice of library.practices) {
const review = practice.reviewId ? reviews.get(practice.reviewId) : undefined
if (
practice.reviewId &&
(!review ||
review.practiceId !== practice.id ||
review.cardId !== practice.cardId ||
review.rating !== practice.rating)
)
problem('练习关联的评分不存在')
}
}
export const librarySchema = libraryContents.superRefine((library, ctx) =>
validateLibraryReferences(library, (message) => ctx.addIssue({ code: 'custom', message })),
)
export const workspaceLibrarySchema = libraryContents
.extend({ attempts: z.array(z.union([attemptSchema, attemptSummarySchema])).max(500_000) })
.superRefine((library, ctx) =>
validateLibraryReferences(library, (message) => ctx.addIssue({ code: 'custom', message })),
)
export type Library = z.infer<typeof workspaceLibrarySchema>
export const recordSchemas = {
sources: sourceSchema,
decks: deckSchema,
notes: noteSchema,
cards: cardSchema,
reviews: reviewSchema,
media: mediaSchema,
savedSearches: savedSearchSchema,
practices: practiceSchema,
attempts: attemptSchema,
}
export function emptyLibrary(): Library {
return {
version: 13,
sources: [],
decks: [],
notes: [],
cards: [],
reviews: [],
media: [],
savedSearches: [],
practices: [],
attempts: [],
}
}
export function localDay(date = new Date()): string {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
export function serializeSchedule(card: FsrsCard): Schedule {
return { ...card, due: card.due.toISOString(), last_review: card.last_review?.toISOString() }
}
export function hydrateSchedule(card: Schedule): FsrsCard {
return {
...card,
due: new Date(card.due),
last_review: card.last_review ? new Date(card.last_review) : undefined,
}
}
export function newCard(noteId: string, variant: string, now = new Date()): Card {
return {
id: crypto.randomUUID(),
noteId,
variant,
schedule: serializeSchedule(createEmptyCard(now)),
createdAt: now.toISOString(),
updatedAt: now.toISOString(),
suspended: false,
leech: false,
}
}
export function renderCard(card: Card, note: Note): CardView {
let front = note.front,
back = note.back,
frontMedia = note.frontMedia,
backMedia = note.backMedia
if (card.variant === 'reverse')
[front, back, frontMedia, backMedia] = [back, front, backMedia, frontMedia]
let cloze: CardView['cloze']
if (note.type === 'cloze') {
const target = Number(card.variant.split(':')[1])
let answer = front
const deletions = clozes(note.front)
for (const item of deletions) {
front = front.replace(item.raw, () =>
item.number === target ? `[${item.hint || '…'}]` : item.answer,
)
answer = answer.replace(item.raw, () => item.answer)
}
cloze = {
answers: deletions.filter((item) => item.number === target).map((item) => item.answer),
context: answer,
extra: note.back,
}
back = answer + (note.back ? `\n\n${note.back}` : '')
}
return {
...card,
cloze,
deckId: note.deckId,
type: note.type,
plugin: note.plugin,
excerpt: note.excerpt,
format: note.format,
tags: note.tags,
front,
back,
frontMedia,
backMedia,
}
}
export function cardViews(library: Library): CardView[] {
const notes = new Map(library.notes.map((note) => [note.id, note]))
return library.cards.map((card) => renderCard(card, notes.get(card.noteId)!))
}
/** For UI consumers of immutable snapshots: reuse unchanged rendered cards. */
export function createCardViewReader() {
const cache = new WeakMap<Card, { note: Note; view: CardView }>()
let previousNotes: Library['notes'] | undefined,
notes = new Map<string, Note>()
return (library: Library) => {
if (previousNotes !== library.notes) {
previousNotes = library.notes
notes = new Map(library.notes.map((note) => [note.id, note]))
}
return library.cards.map((card) => {
const note = notes.get(card.noteId)!,
prior = cache.get(card)
if (prior?.note === note) return prior.view
const view = renderCard(card, note)
cache.set(card, { note, view })
return view
})
}
}
export function pruneMedia(library: Library): Library {
const used = new Set([
...library.notes.flatMap((note) => [...note.frontMedia, ...note.backMedia]),
...library.sources.map((source) => source.mediaId),
])
return { ...library, media: library.media.filter((item) => used.has(item.id)) }
}
export function saveNote(
library: Library,
input: NoteInput,
noteId?: string,
allowRemove = false,
now = new Date(),
): Library {
const previous = library.notes.find((note) => note.id === noteId)
if (noteId && !previous) throw new LocalizedError(msg('笔记已不存在,请刷新页面。'))
const note = noteSchema.parse({
...input,
excerpt: input.excerpt ?? previous?.excerpt,
id: noteId ?? crypto.randomUUID(),
createdAt: previous?.createdAt ?? now.toISOString(),
updatedAt: now.toISOString(),
})
const keys = variants(note)
const oldCards = library.cards.filter((card) => card.noteId === note.id)
const removed = new Set(
oldCards.filter((card) => !keys.includes(card.variant)).map((card) => card.id),
)
if (removed.size && !allowRemove)
throw new LocalizedError(msg('修改后部分卡片将不再生成,请确认移除这些卡片及其复习记录。'))
const removedPractices = new Set(
library.practices.filter((entry) => removed.has(entry.cardId)).map((entry) => entry.id),
)
// Existing cards keep their index; only new variants append. Editing a note must not
// shift every later card, which would rewrite the whole library on each save.
const existing = new Set(oldCards.map((card) => card.variant))
const added = keys.filter((key) => !existing.has(key)).map((key) => newCard(note.id, key, now))
return pruneMedia({
...library,
notes: previous
? library.notes.map((entry) => (entry.id === note.id ? note : entry))
: [...library.notes, note],
cards:
added.length || removed.size
? [...library.cards.filter((card) => !removed.has(card.id)), ...added]
: library.cards,
reviews: library.reviews.filter((review) => !removed.has(review.cardId)),
practices: library.practices.filter((entry) => !removed.has(entry.cardId)),
attempts: library.attempts.filter((entry) => !removedPractices.has(entry.practiceId)),
})
}
export function removeNotes(library: Library, ids: Set<string>): Library {
const removed = new Set(
library.cards.filter((card) => ids.has(card.noteId)).map((card) => card.id),
)
const removedPractices = new Set(
library.practices.filter((entry) => removed.has(entry.cardId)).map((entry) => entry.id),
)
return pruneMedia({
...library,
notes: library.notes.filter((note) => !ids.has(note.id)),
cards: library.cards.filter((card) => !removed.has(card.id)),
reviews: library.reviews.filter((review) => !removed.has(review.cardId)),
practices: library.practices.filter((entry) => !removed.has(entry.cardId)),
attempts: library.attempts.filter((entry) => !removedPractices.has(entry.practiceId)),
})
}
export function migrateLibrary(value: unknown): Library {
if (
typeof value === 'object' &&
value !== null &&
'version' in value &&
(value.version === 2 ||
value.version === 3 ||
value.version === 4 ||
value.version === 5 ||
value.version === 6 ||
value.version === 7 ||
value.version === 8 ||
value.version === 9 ||
value.version === 10 ||
value.version === 11 ||
value.version === 12 ||
value.version === 13)
)
return librarySchema.parse(
value.version === 13
? value
: value.version === 6 ||
value.version === 7 ||
value.version === 8 ||
value.version === 9 ||
value.version === 10 ||
value.version === 11 ||
value.version === 12
? { ...value, version: 13 }
: value.version === 5
? { sources: [], ...value, version: 13 }
: {
sources: [],
practices: [],
attempts: [],
...value,
version: 13,
},
)
const old = legacySchema.parse(value)
const seen = new Set<string>()
return librarySchema.parse({
version: 13,
sources: [],
practices: [],
attempts: [],
decks: old.decks,
media: [],
notes: old.cards.map((card) => ({
id: `note-${card.id}`,
deckId: card.deckId,
type: 'basic',
front: card.front,
back: card.back,
tags: card.tags,
frontMedia: [],
backMedia: [],
createdAt: card.createdAt,
updatedAt: card.updatedAt,
})),
cards: old.cards.map((card) => ({
id: card.id,
noteId: `note-${card.id}`,
variant: 'forward',
schedule: card.schedule,
createdAt: card.createdAt,
updatedAt: card.updatedAt,
suspended: false,
})),
reviews: [...old.reviews]
.sort((a, b) => a.reviewedAt.localeCompare(b.reviewedAt))
.map((review) => {
// V1 did not record the pre-review state: don't invent a review/learning classification.
const kind = seen.has(review.cardId) ? 'legacy' : 'new'
seen.add(review.cardId)
return { ...review, kind, studyDay: localDay(new Date(review.reviewedAt)) }
}),
})
}