Страница импорта и звуковые эффекты из файлов
- метаданные пака (название, id, финал) читаются из самого CSV - страница /import/<токен>: перетащить таблицу, проверить, сохранить - пак применяется без перезапуска сервера, если партия не начата - звуки берутся из content/sfx/, иначе используется синтез - заголовок таблицы ищется по содержимому, а не по позиции
This commit is contained in:
1 parent
2f0263e59b
commit
ea2d5d905c
21 files changed
+1529
-88
No files matched your search
+130
-11
@@ -27,8 +27,9 @@ export interface ImportError {
|
||||
}
|
||||
|
||||
export interface ImportOptions {
|
||||
id: string
|
||||
title: string
|
||||
/** Необязателен: берётся из блока метаданных или из названия. */
|
||||
id?: string
|
||||
title?: string
|
||||
settings?: Partial<PackSettings>
|
||||
final?: { question: string; answer: string; comment?: string }
|
||||
}
|
||||
@@ -47,9 +48,98 @@ export interface TableRow {
|
||||
|
||||
export interface Table {
|
||||
header: string[]
|
||||
/** Строки над заголовком: название игры, id, финальный вопрос. */
|
||||
meta: TableRow[]
|
||||
rows: TableRow[]
|
||||
}
|
||||
|
||||
// ─── Метаданные пака ───────────────────────────────────────────────────────
|
||||
|
||||
export interface PackMeta {
|
||||
id?: string
|
||||
title?: string
|
||||
final?: { question: string; answer: string; comment?: string }
|
||||
}
|
||||
|
||||
const META_KEYS: Record<string, 'title' | 'id' | 'finalQuestion' | 'finalAnswer' | 'finalComment'> = {
|
||||
название: 'title',
|
||||
игра: 'title',
|
||||
title: 'title',
|
||||
id: 'id',
|
||||
код: 'id',
|
||||
'финальный вопрос': 'finalQuestion',
|
||||
финал: 'finalQuestion',
|
||||
'финальный ответ': 'finalAnswer',
|
||||
'комментарий к финалу': 'finalComment',
|
||||
}
|
||||
|
||||
/** Собирает метаданные из строк над заголовком таблицы. */
|
||||
export function readMeta(rows: TableRow[]): PackMeta {
|
||||
const meta: PackMeta = {}
|
||||
const final: NonNullable<PackMeta['final']> = { question: '', answer: '' }
|
||||
let hasFinal = false
|
||||
|
||||
for (const row of rows) {
|
||||
const key = META_KEYS[normalizeHeader(row.cells[0] ?? '')]
|
||||
if (!key) continue
|
||||
const value = (row.cells[1] ?? '').trim()
|
||||
if (!value) continue
|
||||
|
||||
if (key === 'title') meta.title = value
|
||||
else if (key === 'id') meta.id = value
|
||||
else if (key === 'finalQuestion') {
|
||||
final.question = value
|
||||
hasFinal = true
|
||||
} else if (key === 'finalAnswer') {
|
||||
final.answer = value
|
||||
hasFinal = true
|
||||
} else if (key === 'finalComment') {
|
||||
final.comment = value
|
||||
hasFinal = true
|
||||
}
|
||||
}
|
||||
|
||||
if (hasFinal && final.question && final.answer) {
|
||||
meta.final = final.comment
|
||||
? { question: final.question, answer: final.answer, comment: final.comment }
|
||||
: { question: final.question, answer: final.answer }
|
||||
}
|
||||
|
||||
return meta
|
||||
}
|
||||
|
||||
// ─── Кодировка и идентификатор ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Русский Excel сохраняет CSV в Windows-1251, а не в UTF-8.
|
||||
* Пробуем UTF-8 строго: если байты не складываются — это ANSI.
|
||||
*/
|
||||
export function decodeTable(bytes: Uint8Array): { text: string; encoding: 'utf-8' | 'windows-1251' } {
|
||||
try {
|
||||
return { text: new TextDecoder('utf-8', { fatal: true }).decode(bytes), encoding: 'utf-8' }
|
||||
} catch {
|
||||
return { text: new TextDecoder('windows-1251').decode(bytes), encoding: 'windows-1251' }
|
||||
}
|
||||
}
|
||||
|
||||
const TRANSLIT: Record<string, string> = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z',
|
||||
и: 'i', й: 'y', к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r',
|
||||
с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'c', ч: 'ch', ш: 'sh', щ: 'sch',
|
||||
ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
}
|
||||
|
||||
/** «Новогодний квиз 2027» → «novogodniy-kviz-2027». */
|
||||
export function slugify(input: string): string {
|
||||
const latin = Array.from(input.toLowerCase())
|
||||
.map((char) => TRANSLIT[char] ?? char)
|
||||
.join('')
|
||||
const slug = latin
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
return slug || 'quiz'
|
||||
}
|
||||
|
||||
const DELIMITERS = [',', ';', '\t'] as const
|
||||
|
||||
function firstLine(text: string): string {
|
||||
@@ -156,8 +246,31 @@ export function parseTable(text: string): Table {
|
||||
|
||||
if (touched || field.length > 0 || record.length > 0) pushRecord()
|
||||
|
||||
const header = rows.shift()
|
||||
return { header: header?.cells ?? [], rows }
|
||||
// Заголовок ищем по содержимому, а не по позиции: над ним может стоять
|
||||
// блок «Название игры; …». Без этого любая строка метаданных ломала импорт.
|
||||
const headerIndex = rows.findIndex((row) => looksLikeHeader(row.cells))
|
||||
if (headerIndex < 0) {
|
||||
const first = rows.shift()
|
||||
return { header: first?.cells ?? [], meta: [], rows }
|
||||
}
|
||||
|
||||
const meta = rows.slice(0, headerIndex)
|
||||
const header = rows[headerIndex]
|
||||
return {
|
||||
header: header?.cells ?? [],
|
||||
meta,
|
||||
rows: rows.slice(headerIndex + 1),
|
||||
}
|
||||
}
|
||||
|
||||
function looksLikeHeader(cells: string[]): boolean {
|
||||
const found = new Set<Column>()
|
||||
for (const raw of cells) {
|
||||
const column = HEADER_ALIASES[normalizeHeader(raw)]
|
||||
if (column) found.add(column)
|
||||
}
|
||||
// «Тема» плюс хоть что-то из содержимого клетки — это заголовок таблицы.
|
||||
return found.has('theme') && (found.has('value') || found.has('question') || found.has('answer'))
|
||||
}
|
||||
|
||||
// ─── Заголовки ─────────────────────────────────────────────────────────────
|
||||
@@ -289,9 +402,11 @@ interface Entry { line: number
|
||||
|
||||
// ─── Сборка пака ───────────────────────────────────────────────────────────
|
||||
|
||||
export function tableToPack(text: string, options: ImportOptions): ImportResult {
|
||||
export function tableToPack(text: string, options: ImportOptions = {}): ImportResult {
|
||||
const table = parseTable(text)
|
||||
const meta = readMeta(table.meta)
|
||||
const errors: ImportError[] = []
|
||||
const packId = options.id ?? meta.id ?? slugify(options.title ?? meta.title ?? 'quiz')
|
||||
|
||||
const columns = new Map<Column, number>()
|
||||
table.header.forEach((raw, index) => {
|
||||
@@ -358,7 +473,7 @@ export function tableToPack(text: string, options: ImportOptions): ImportResult
|
||||
|
||||
let media: string | undefined
|
||||
if (mediaRaw) {
|
||||
media = normalizeMediaSource(mediaRaw, options.id)
|
||||
media = normalizeMediaSource(mediaRaw, packId)
|
||||
if (!mediaKindOf(media)) {
|
||||
errors.push({
|
||||
line: row.line,
|
||||
@@ -464,16 +579,20 @@ export function tableToPack(text: string, options: ImportOptions): ImportResult
|
||||
return { id: `r${roundIndex + 1}`, title: roundTitle, themes }
|
||||
})
|
||||
|
||||
const title = options.title ?? meta.title ?? 'Новогодний квиз'
|
||||
const pack: Pack = {
|
||||
id: options.id,
|
||||
title: options.title,
|
||||
id: packId,
|
||||
title,
|
||||
settings: { ...DEFAULT_SETTINGS, ...options.settings },
|
||||
rounds,
|
||||
}
|
||||
if (options.final) {
|
||||
|
||||
// Финальный вопрос: приоритет у явного аргумента, иначе — из метаданных.
|
||||
const final = options.final ?? meta.final
|
||||
if (final) {
|
||||
// В паке финал — это Question, а не строка: у него есть text и answer.
|
||||
const question: Question = { text: options.final.question, answer: options.final.answer }
|
||||
if (options.final.comment) question.comment = options.final.comment
|
||||
const question: Question = { text: final.question, answer: final.answer }
|
||||
if (final.comment) question.comment = final.comment
|
||||
pack.final = { question }
|
||||
}
|
||||
|
||||
|
||||
@@ -13,11 +13,20 @@ export {
|
||||
} from './pack'
|
||||
export type { CellKeyParts, FoundCell, ParsePackResult, ParsedPack } from './pack'
|
||||
|
||||
export { detectDelimiter, parseTable, tableToPack, parseFinal } from './importer'
|
||||
export {
|
||||
detectDelimiter,
|
||||
parseTable,
|
||||
tableToPack,
|
||||
parseFinal,
|
||||
readMeta,
|
||||
decodeTable,
|
||||
slugify,
|
||||
} from './importer'
|
||||
export type {
|
||||
ImportError,
|
||||
ImportOptions,
|
||||
ImportResult,
|
||||
PackMeta,
|
||||
Table,
|
||||
TableRow,
|
||||
} from './importer'
|
||||
|
||||
@@ -47,6 +47,82 @@ describe('разбор таблицы', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('кодировка', () => {
|
||||
it('узнаёт Windows-1251, где байты не складываются в UTF-8', async () => {
|
||||
const { decodeTable } = await import('../src/index')
|
||||
// «Тема» в Windows-1251: D2 E5 EC E0.
|
||||
const bytes = Uint8Array.from([0xd2, 0xe5, 0xec, 0xe0])
|
||||
const decoded = decodeTable(bytes)
|
||||
expect(decoded.encoding).toBe('windows-1251')
|
||||
expect(decoded.text).toBe('Тема')
|
||||
})
|
||||
|
||||
it('читает UTF-8 как UTF-8', async () => {
|
||||
const { decodeTable } = await import('../src/index')
|
||||
const decoded = decodeTable(new TextEncoder().encode('Тема'))
|
||||
expect(decoded.encoding).toBe('utf-8')
|
||||
expect(decoded.text).toBe('Тема')
|
||||
})
|
||||
})
|
||||
|
||||
describe('метаданные над заголовком', () => {
|
||||
const csv = [
|
||||
'Название;Новогодний квиз 2027',
|
||||
'ID;novy-god-2027',
|
||||
'Финальный вопрос;Что делают с запиской?',
|
||||
'Финальный ответ;Сжигают',
|
||||
'Комментарий к финалу;До последнего удара',
|
||||
'',
|
||||
'Тема;Стоимость;Вопрос;Ответ',
|
||||
'Стол;100;Вопрос;Ответ',
|
||||
'Ёлка;100;Вопрос;Ответ',
|
||||
].join('\n')
|
||||
|
||||
it('берёт название, id и финал из самого файла', () => {
|
||||
const result = tableToPack(csv)
|
||||
if (!result.ok) throw new Error(result.errors.map((e) => e.message).join(', '))
|
||||
|
||||
expect(result.pack.title).toBe('Новогодний квиз 2027')
|
||||
expect(result.pack.id).toBe('novy-god-2027')
|
||||
expect(result.pack.final?.question.text).toBe('Что делают с запиской?')
|
||||
expect(result.pack.final?.question.answer).toBe('Сжигают')
|
||||
expect(result.pack.final?.question.comment).toBe('До последнего удара')
|
||||
expect(result.stats.cells).toBe(2)
|
||||
})
|
||||
|
||||
it('явные аргументы важнее метаданных', () => {
|
||||
const result = tableToPack(csv, { id: 'forced', title: 'Своё название' })
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
expect(result.pack.id).toBe('forced')
|
||||
expect(result.pack.title).toBe('Своё название')
|
||||
})
|
||||
|
||||
it('выводит id из названия транслитом', () => {
|
||||
const result = tableToPack(['Название;Ёлки-палки 2027', 'Тема;Стоимость;Вопрос;Ответ', 'Стол;100;В;О'].join('\n'))
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
expect(result.pack.id).toBe('elki-palki-2027')
|
||||
})
|
||||
|
||||
it('без метаданных не падает и даёт осмысленный id', () => {
|
||||
const result = tableToPack('Тема,Стоимость,Вопрос,Ответ\nСтол,100,В,О')
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
expect(result.pack.id).toBe('quiz')
|
||||
expect(result.pack.title).toBe('Новогодний квиз')
|
||||
})
|
||||
|
||||
it('финал без вопроса или без ответа не попадает в пак', () => {
|
||||
const text = [
|
||||
'Название;Тест',
|
||||
'Финальный вопрос;Вопрос без ответа',
|
||||
'Тема;Стоимость;Вопрос;Ответ',
|
||||
'Стол;100;В;О',
|
||||
].join('\n')
|
||||
const result = tableToPack(text)
|
||||
if (!result.ok) throw new Error('пак не собрался')
|
||||
expect(result.pack.final).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('сборка пака', () => {
|
||||
const csv = [
|
||||
'Раунд,Тема,Стоимость,Вопрос,Ответ,Комментарий,Тип,Медиа',
|
||||
|
||||
Reference in new issue
Block a user