Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/__tests__/unit/export-to-docx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,17 @@ describe("buildDocxParagraphs", () => {
const allText = JSON.stringify(paragraphs);
expect(allText).not.toContain("image");
});

it("默认包含题目配图且不包含拍照原图", async () => {
const { buildQuestionsDocx } = await import("@/lib/question-format/to-docx");
const withFigureOnly: StructuredQuestion[] = [
{ text: "如图计算。", figureImage: pngDataUrl(), images: [{ dataUrl: pngDataUrl() }] },
];
const blob = await buildQuestionsDocx(withFigureOnly, { includeImages: false });
const entries = unzipSync(new Uint8Array(await blob.arrayBuffer()));
const mediaFiles = Object.keys(entries).filter((n) => n.startsWith("word/media/"));
expect(mediaFiles).toHaveLength(1);
}, 20000);
});

describe("导出→导入往返", () => {
Expand Down
15 changes: 15 additions & 0 deletions src/__tests__/unit/from-error-item.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,21 @@ describe('fromErrorItem', () => {
expect(result!.images).toBeUndefined();
});

it('includeImages=false 且 includeFigures=true 时导出题目配图且不导出拍照原图', () => {
const result = fromErrorItem(
makeSource({
originalImageUrl: TINY_PNG_DATA_URL,
figureImage: TINY_PNG_DATA_URL,
figureSource: 'image',
}),
false,
true,
);
expect(result!.images).toBeUndefined();
expect(result!.figureImage).toBe(TINY_PNG_DATA_URL);
expect(result!.figureSource).toBe('image');
});

it('includeImages=true 且 originalImageUrl 是 data:image/png 时放入 images', () => {
const result = fromErrorItem(makeSource({ originalImageUrl: TINY_PNG_DATA_URL }), true);
expect(result!.images).toEqual([{ dataUrl: TINY_PNG_DATA_URL }]);
Expand Down
3 changes: 1 addition & 2 deletions src/__tests__/unit/question-figure.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ describe('题目配图', () => {
/>
</LanguageProvider>,
);
expect(textWithoutFigure).toContain('src="/photo.png"');
expect(textWithoutFigure).toContain('max-width:70%');
expect(textWithoutFigure).not.toContain('/photo.png');

const fillMarkup = renderToStaticMarkup(
<LanguageProvider>
Expand Down
9 changes: 7 additions & 2 deletions src/app/api/error-items/export-questions/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const logger = createLogger("api:error-items/export-questions");
const exportQuestionsSchema = z.object({
ids: z.array(z.string().min(1)).min(1).max(2000),
includeImages: z.boolean().optional(),
includeFigures: z.boolean().optional(),
});

export const POST = withUser(async (req: Request, { user }: AuthenticatedContext) => {
Expand All @@ -23,7 +24,7 @@ export const POST = withUser(async (req: Request, { user }: AuthenticatedContext
if (!parsed.success) {
return validationError("EXPORT_QUESTIONS_INVALID_INPUT", parsed.error.issues);
}
const { ids, includeImages } = parsed.data;
const { ids, includeImages, includeFigures } = parsed.data;

// 只查询属于当前用户的错题,不存在的 id 静默忽略
const items = await prisma.errorItem.findMany({
Expand All @@ -39,6 +40,8 @@ export const POST = withUser(async (req: Request, { user }: AuthenticatedContext
gradeSemester: true,
source: true,
figureSvg: true,
figureImage: true,
figureSource: true,
originalImageUrl: true,
subject: { select: { name: true } },
tags: { select: { name: true } },
Expand Down Expand Up @@ -67,10 +70,12 @@ export const POST = withUser(async (req: Request, { user }: AuthenticatedContext
gradeSemester: item.gradeSemester,
source: item.source,
figureSvg: item.figureSvg,
figureImage: item.figureImage,
figureSource: item.figureSource,
originalImageUrl: item.originalImageUrl,
subjectName: item.subject?.name ?? null,
tags: item.tags,
}, includeImages);
}, includeImages, includeFigures);
if (mapped === null) {
skipped += 1;
} else {
Expand Down
37 changes: 36 additions & 1 deletion src/components/error-list/export-questions-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,25 @@ export type ExportFormat = "json" | "excel" | "word";
const FORMAT_STORAGE_KEY = "error-list-export-format";

const ANSWERS_STORAGE_KEY = "error-list-export-include-answers";
const FIGURES_STORAGE_KEY = "error-list-export-include-figures";

/** 记住上次是否勾选「包含题目配图」(默认开启) */
function loadSavedFigures(): boolean {
try {
const saved = window.localStorage.getItem(FIGURES_STORAGE_KEY);
return saved === null ? true : saved === "1";
} catch {
return true;
}
}

function saveFigures(include: boolean): void {
try {
window.localStorage.setItem(FIGURES_STORAGE_KEY, include ? "1" : "0");
} catch {
// localStorage 不可用时忽略
}
}

/** 记住上次选择的导出格式(失败时静默回退默认值) */
function saveFormat(format: ExportFormat): void {
Expand Down Expand Up @@ -72,6 +91,7 @@ interface ExportQuestionsDialogProps {
export function ExportQuestionsDialog({ open, onOpenChange, selectedIds }: ExportQuestionsDialogProps) {
const { t } = useLanguage();
const [format, setFormat] = useState<ExportFormat>(loadSavedFormat);
const [includeFigures, setIncludeFigures] = useState<boolean>(loadSavedFigures);
const [includeImages, setIncludeImages] = useState(false);
const [includeAnswers, setIncludeAnswers] = useState<boolean>(loadSavedAnswers);
const [docxTitle, setDocxTitle] = useState("");
Expand All @@ -86,7 +106,11 @@ export function ExportQuestionsDialog({ open, onOpenChange, selectedIds }: Expor
const res = await fetch("/api/error-items/export-questions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: selectedIds, includeImages }),
body: JSON.stringify({
ids: selectedIds,
includeImages,
includeFigures: format === "word" ? includeFigures : false,
}),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
Expand Down Expand Up @@ -117,6 +141,7 @@ export function ExportQuestionsDialog({ open, onOpenChange, selectedIds }: Expor
const blob = await buildQuestionsDocx(questions, {
title,
includeAnswers,
includeFigures,
includeImages,
});
saved = await downloadBlobFile(blob, `wrong-notebook-questions-${dateStr}.docx`);
Expand Down Expand Up @@ -197,6 +222,16 @@ export function ExportQuestionsDialog({ open, onOpenChange, selectedIds }: Expor
{t.notebook.exportJsonDialog.includeAnswers}
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="include-figures"
checked={includeFigures}
onCheckedChange={(checked) => { setIncludeFigures(checked === true); saveFigures(checked === true); }}
/>
<label htmlFor="include-figures" className="text-sm cursor-pointer">
{t.notebook.exportJsonDialog.includeFigures}
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="include-images"
Expand Down
6 changes: 3 additions & 3 deletions src/components/print-preview/printable-question.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@ export const PrintableQuestion = memo(function PrintableQuestion({
{options.showQuestionText && item.questionText ? (
<div className="mb-4">
<PrintQuestionText content={item.questionText} />
{hasQuestionFigure
? <QuestionFigure svg={item.figureSvg} image={item.figureImage} source={item.figureSource} scale={item.figureScale} align={item.figureAlign} />
: originalImage}
{hasQuestionFigure && (
<QuestionFigure svg={item.figureSvg} image={item.figureImage} source={item.figureSource} scale={item.figureScale} align={item.figureAlign} />
)}
</div>
) : (
originalImage
Expand Down
5 changes: 3 additions & 2 deletions src/lib/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,11 +453,12 @@ export const en = {
formatExcel: "Excel",
formatWord: "Word",
excelNote: "Excel columns match the question bank import template, so the file can be re-imported via Question Bank Import; images are not written to Excel.",
wordNote: "Formulas are exported as LaTeX text; figureSvg is not exported.",
wordNote: "Formulas are exported as LaTeX text; question figures are embedded by default without original photos.",
docxTitleLabel: "Document title",
defaultDocxTitle: "Wrong Questions Export",
includeAnswers: "Include answers and analysis (in an \"Answer Key\" section at the end)",
includeImages: "Include original images (larger file)",
includeFigures: "Include question figures (without original photos)",
includeImages: "Include original photos (larger file)",
export: "Export",
exporting: "Exporting...",
cancel: "Cancel",
Expand Down
5 changes: 3 additions & 2 deletions src/lib/i18n/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,11 +453,12 @@ export const zh = {
formatExcel: "Excel",
formatWord: "Word",
excelNote: "Excel 列与题库导入模板一致,可直接通过「题库导入」再导入;图片不会写入 Excel。",
wordNote: "公式以 LaTeX 文本导出;figureSvg 不导出。",
wordNote: "公式以 LaTeX 文本导出;默认仅嵌入题目配图,不含拍照原图。",
docxTitleLabel: "文档标题",
defaultDocxTitle: "错题导出",
includeAnswers: "包含答案与解析(放在文末「参考答案」部分)",
includeImages: "包含原图(文件会变大)",
includeFigures: "包含题目配图(仅题图,不含拍照原图)",
includeImages: "包含拍照原图(整题照片,文件会变大)",
export: "导出",
exporting: "导出中...",
cancel: "取消",
Expand Down
2 changes: 1 addition & 1 deletion src/lib/print/print-preview-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { PrintDisplayOptions } from "@/components/print-preview/print-optio
export const PRINT_OPTIONS_STORAGE_KEY = "print-preview-options";

export const DEFAULT_PRINT_OPTIONS: PrintDisplayOptions = {
showQuestionText: false,
showQuestionText: true,
showAnswers: false,
showAnalysis: false,
showTags: false,
Expand Down
16 changes: 15 additions & 1 deletion src/lib/question-format/from-error-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export interface ErrorItemExportSource {
gradeSemester: string | null;
source: string | null;
figureSvg: string | null;
figureImage?: string | null;
figureSource?: string | null;
originalImageUrl: string;
subjectName: string | null;
tags: { name: string }[];
Expand All @@ -30,7 +32,11 @@ const IMAGE_DATA_URL_PATTERN = /^data:image\/(png|jpeg|webp);base64,/;
* 题干为空(null、undefined 或去空白后无内容)时返回 null,由调用方计数到 warnings。
* includeImages 为 true 且 originalImageUrl 是合法 data URL 且不超上限时写入 images。
*/
export function fromErrorItem(item: ErrorItemExportSource, includeImages?: boolean): StructuredQuestion | null {
export function fromErrorItem(
item: ErrorItemExportSource,
includeImages?: boolean,
includeFigures?: boolean,
): StructuredQuestion | null {
const text = item.questionText;
if (text === null || text === undefined || text.trim().length === 0) return null;

Expand All @@ -47,6 +53,14 @@ export function fromErrorItem(item: ErrorItemExportSource, includeImages?: boole
if (item.figureSvg) question.figureSvg = item.figureSvg;
if (item.tags.length > 0) question.knowledgePoints = item.tags.map((t) => t.name);

if (includeFigures && item.figureImage && IMAGE_DATA_URL_PATTERN.test(item.figureImage)
&& item.figureImage.length <= MAX_IMAGE_DATA_URL_LENGTH) {
question.figureImage = item.figureImage;
}
if (includeFigures && (item.figureSource === "svg" || item.figureSource === "image")) {
question.figureSource = item.figureSource;
}

if (includeImages && IMAGE_DATA_URL_PATTERN.test(item.originalImageUrl)
&& item.originalImageUrl.length <= MAX_IMAGE_DATA_URL_LENGTH) {
question.images = [{ dataUrl: item.originalImageUrl }];
Expand Down
11 changes: 11 additions & 0 deletions src/lib/question-format/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@ function normalizeQuestion(raw: unknown): { question: StructuredQuestion } | { e
const figureSvgError = checkMax(figureSvg, MAX_FIGURE_SVG_LENGTH_EXCHANGE, "FIGURE_SVG_TOO_LONG");
if (figureSvgError) return { error: figureSvgError };

const figureImage = normalizeOptionalString(record.figureImage);
if (figureImage !== undefined) {
if (!/^data:image\/(png|jpeg|webp);base64,/.test(figureImage)) return { error: INVALID_IMAGE_DATA_URL };
if (figureImage.length > MAX_IMAGE_DATA_URL_LENGTH) return { error: IMAGE_TOO_LARGE };
}
const figureSource = record.figureSource === "svg" || record.figureSource === "image"
? record.figureSource
: undefined;

const knowledgePointsResult = normalizeKnowledgePoints(record.knowledgePoints);
if ("error" in knowledgePointsResult) return { error: knowledgePointsResult.error };

Expand Down Expand Up @@ -214,6 +223,8 @@ function normalizeQuestion(raw: unknown): { question: StructuredQuestion } | { e
if (source !== undefined) question.source = source;
if (questionType !== undefined) question.questionType = questionType;
if (figureSvg !== undefined) question.figureSvg = figureSvg;
if (figureImage !== undefined) question.figureImage = figureImage;
if (figureSource !== undefined) question.figureSource = figureSource;
if (imagesResult.images.length > 0) question.images = imagesResult.images;
if (extensions !== undefined) question.extensions = extensions;
return { question };
Expand Down
2 changes: 2 additions & 0 deletions src/lib/question-format/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ export const structuredQuestionSchema = z.object({
source: z.string().max(MAX_SOURCE_LENGTH).optional(),
questionType: z.string().max(MAX_QUESTION_TYPE_LENGTH).optional(),
figureSvg: z.string().max(MAX_FIGURE_SVG_LENGTH_EXCHANGE).optional(),
figureImage: z.string().regex(IMAGE_DATA_URL_PATTERN, "INVALID_IMAGE_DATA_URL").max(MAX_IMAGE_DATA_URL_LENGTH, "IMAGE_TOO_LARGE").optional(),
figureSource: z.enum(["svg", "image"]).optional(),
images: z.array(questionImageSchema).max(MAX_IMAGES_PER_QUESTION).optional(),
extensions: z.record(z.string(), z.unknown()).optional(),
});
Expand Down
Loading