feat:作业纸

This commit is contained in:
R524809
2026-10-23 16:53:22 +08:00
parent fe1074e3f0
commit 98dc338848
14 changed files with 757 additions and 247 deletions
@@ -1,53 +1,42 @@
import type { DebugPublishMeta } from '../../utils/debugPublish';
import { inferGradeFromAge } from '../../utils/debugPublish';
import { PAPER_SHEET_WORKSHEET_DEFINITIONS } from '../../config/worksheets/papers';
import {
PAPER_SHEET_WORKSHEET_DEFINITIONS,
PAPER_SHEET_WORKSHEET_ID,
PAPER_TYPES,
type PaperType,
} from '../../config/worksheets/papers';
type PaperSheetWorksheetRow =
(typeof PAPER_SHEET_WORKSHEET_DEFINITIONS)[number];
export { PAPER_SHEET_WORKSHEET_ID, type PaperType };
export const PAPER_TYPE_OPTIONS = PAPER_TYPES;
const WORKSHEET_BY_ID = Object.fromEntries(
PAPER_SHEET_WORKSHEET_DEFINITIONS.map((m) => [m.id, m]),
) as Record<string, PaperSheetWorksheetRow>;
const WORKSHEET_BY_ID = new Map(
PAPER_SHEET_WORKSHEET_DEFINITIONS.map((entry) => [entry.id, entry]),
);
export const PAPER_SHEET_WORKSHEET_ID = PAPER_SHEET_WORKSHEET_DEFINITIONS[0].id;
/** 纸张类型 id */
export type PaperType =
| 'tian'
| 'mi'
| 'square'
| 'four-line'
| 'letter'
| 'horizontal'
| 'vertical'
| 'dictation-hanzi'
| 'dictation-pinyin'
| 'homework-log';
export interface PaperTypeOption {
id: PaperType;
name: string;
/** 次要说明 */
desc: string;
/** 只接收已注册条目;旧综合入口继续支持 type,并兼容分享中的 mode。 */
export function resolvePaperEntry(options: {
id?: string;
type?: string;
mode?: string;
}) {
const id = options.id || PAPER_SHEET_WORKSHEET_ID;
const entry = WORKSHEET_BY_ID.get(id);
if (!entry) throw new Error('当前作业纸暂不可用,请更新小程序');
const legacyType = options.type || options.mode;
const paperType =
entry.renderConfig.paperType ||
(legacyType && isValidPaperType(legacyType)
? legacyType
: DEFAULT_PAPER_TYPE);
return { entry, paperType };
}
/** 纸张类型选项(展示顺序与用户需求一致) */
export const PAPER_TYPE_OPTIONS: PaperTypeOption[] = [
{ id: 'tian', name: '田字格', desc: '汉字练习' },
{ id: 'mi', name: '米字格', desc: '书法练习' },
{ id: 'square', name: '方格', desc: '书法练字纸' },
{ id: 'four-line', name: '四线三格', desc: '拼音 / 字母' },
{ id: 'letter', name: '信纸', desc: '横线信笺' },
{ id: 'horizontal', name: '横线', desc: '横线本' },
{ id: 'vertical', name: '竖线', desc: '竖排书写' },
{ id: 'dictation-hanzi', name: '汉字听写', desc: '田字格 + 订正栏' },
{
id: 'dictation-pinyin',
name: '拼音/英语听写',
desc: '四线三格 + 订正栏',
},
{ id: 'homework-log', name: '作业登记表', desc: '分科登记' },
];
export function getWorksheetIdForPaperType(paperType: PaperType): string {
return PAPER_SHEET_WORKSHEET_DEFINITIONS.find(
(entry) => entry.renderConfig.paperType === paperType,
)!.id;
}
export interface PaperColorOption {
id: string;
@@ -75,16 +64,16 @@ export function isValidPaperType(id: string): id is PaperType {
}
export function getModeInfo(id: string) {
const m = WORKSHEET_BY_ID[id];
const m = WORKSHEET_BY_ID.get(id);
return m ? { title: m.title, desc: m.subtitle } : undefined;
}
export function isValidMode(id: string): boolean {
return id in WORKSHEET_BY_ID;
return WORKSHEET_BY_ID.has(id);
}
export function getPublishMetaByMode(id: string): DebugPublishMeta | null {
const m = WORKSHEET_BY_ID[id];
const m = WORKSHEET_BY_ID.get(id);
if (!m) return null;
return {
id: m.id,
+158 -38
View File
@@ -8,9 +8,16 @@ import {
getModeInfo,
getPublishMetaByMode,
isValidPaperType,
resolvePaperEntry,
getWorksheetIdForPaperType,
type PaperType,
} from './paperSheet.config';
import { createPage, type CanvasDataState } from '../../base/pageMixin';
import {
createPage,
getPageCommonMethods,
type CanvasDataState,
} from '../../base/pageMixin';
import { getWorksheet } from '../../services/content-api';
import { defaultShareConfig } from '../../config/config';
import type { DebugPublishMeta } from '../../utils/debugPublish';
import {
@@ -20,6 +27,10 @@ import {
} from '../../utils/favorites';
const pageInfoLookup = getModeInfo;
const commonMethods = getPageCommonMethods({
pageInfoLookup,
shareConfig: defaultShareConfig,
});
type PageData = CanvasDataState & {
worksheetId: string;
@@ -28,6 +39,8 @@ type PageData = CanvasDataState & {
selectedPaperType: PaperType;
selectedColor: string;
isPreviewFavorite: boolean;
isWorksheetReady: boolean;
favoriteLoading: boolean;
isDevEnv: boolean;
debugPublishVisible: boolean;
debugPublishLoading: boolean;
@@ -42,6 +55,8 @@ createPage(
boxWidth: 0,
drawService: null as PaperDrawService | null,
_favoritedMap: {} as Record<string, boolean>,
_entryRequest: 0,
_favoriteVersions: {} as Record<string, number>,
data: {
pageTitle: '作业纸',
@@ -54,28 +69,77 @@ createPage(
selectedPaperType: DEFAULT_PAPER_TYPE,
selectedColor: DEFAULT_PAPER_COLOR,
isPreviewFavorite: false,
isWorksheetReady: false,
favoriteLoading: false,
isDevEnv: false,
debugPublishVisible: false,
debugPublishLoading: false,
debugPublishMeta: null,
} as unknown as PageData,
onLoad(options: { id?: string; type?: string }) {
async onLoad(options: { id?: string; type?: string; mode?: string }) {
this.syncDebugPublishEnv();
const initialType =
options.type && isValidPaperType(options.type)
? (options.type as PaperType)
: DEFAULT_PAPER_TYPE;
this.setData({
selectedPaperType: initialType,
});
this.initPageInfo(PAPER_SHEET_WORKSHEET_ID, '作业纸');
await this.openEntry(options);
this.loadFavoritedMap();
},
onUnload() {
this._entryRequest++;
},
/** 开发版直接预览已注册配置以制作封面;体验/正式版切换前校验公开状态。 */
async openEntry(options: {
id?: string;
type?: string;
mode?: string;
}) {
const request = ++this._entryRequest;
this.setData({
isWorksheetReady: false,
hasContent: false,
// 换纸张即丢弃旧发布表单,防止旧条目元数据配上新封面。
debugPublishVisible: false,
debugPublishMeta: null,
});
try {
const { entry, paperType } = resolvePaperEntry(options);
// 草稿在公开详情中固定为 404;开发版使用本地注册配置,不通过失败请求判断预览权限。
if (!this.data.isDevEnv) {
const remote = await getWorksheet(entry.id);
if (
entry.id !== PAPER_SHEET_WORKSHEET_ID &&
(remote.rendering?.rendererKey !== entry.rendererKey ||
remote.rendering?.paperType !== paperType)
) {
throw new Error('作业纸配置暂不可用,请更新小程序');
}
}
if (request !== this._entryRequest) return;
this.setData({
worksheetId: entry.id,
selectedPaperType: paperType,
// 综合入口分享保留所选纸张;独立条目由 ID 唯一确定纸张类型。
currentMode:
entry.id === PAPER_SHEET_WORKSHEET_ID
? paperType
: entry.id,
isPreviewFavorite: this._favoritedMap[entry.id] === true,
isWorksheetReady: true,
});
this.initPageInfo(entry.id, entry.title);
await this.drawCanvas();
} catch (error) {
if (request !== this._entryRequest) return;
wx.showToast({
title:
error instanceof Error
? error.message
: '作业纸加载失败',
icon: 'none',
});
}
},
onCanvasReady(e: WechatMiniprogram.CustomEvent) {
this.initCanvasFromComponent(e.detail, {
createDrawService: (
@@ -93,23 +157,35 @@ createPage(
},
async drawCanvas() {
if (!this.drawService) return;
if (!this.drawService || !this.data.isWorksheetReady) return;
const request = this._entryRequest;
try {
await (this.drawService as PaperDrawService).draw(
this.data.selectedPaperType,
this.data.selectedColor,
);
this.setData({ hasContent: true });
if (
request === this._entryRequest &&
this.data.isWorksheetReady
)
this.setData({ hasContent: true });
} catch (err) {
console.error('paperSheet draw failed', err);
this.setData({ hasContent: false });
if (request === this._entryRequest)
this.setData({ hasContent: false });
}
},
onSelectPaperType(e: WechatMiniprogram.TouchEvent) {
const id = e.currentTarget.dataset.id as PaperType | undefined;
if (!id || id === this.data.selectedPaperType) return;
this.setData({ selectedPaperType: id }, () => this.drawCanvas());
const id = e.currentTarget.dataset.id as string | undefined;
if (!id || !isValidPaperType(id)) return;
const worksheetId = getWorksheetIdForPaperType(id);
if (
worksheetId === this.data.worksheetId &&
this.data.isWorksheetReady
)
return;
return this.openEntry({ id: worksheetId });
},
onSelectColor(e: WechatMiniprogram.TouchEvent) {
@@ -124,33 +200,77 @@ createPage(
onShare() {},
async onPreviewFavorite() {
const next = !this.data.isPreviewFavorite;
this.setData({ isPreviewFavorite: next });
const id = this.data.worksheetId;
if (id) {
this._favoritedMap[id] = next;
if (next) {
addFavorite(id);
} else {
removeFavorite(id);
}
async exportToPrint() {
if (!this.data.isWorksheetReady || !this.data.hasContent) return;
return commonMethods.exportToPrint.call(this);
},
async onShareSuccess() {
if (!this.data.isWorksheetReady || !this.data.hasContent) {
this.setData({ showShareDialog: false });
return;
}
return commonMethods.onShareSuccess.call(this);
},
/** 请求失败不显示收藏成功,且响应只更新操作时的条目。 */
async onPreviewFavorite() {
if (!this.data.isWorksheetReady || this.data.favoriteLoading)
return;
const id = this.data.worksheetId;
const next = !this.data.isPreviewFavorite;
this._favoriteVersions[id] = (this._favoriteVersions[id] || 0) + 1;
this.setData({ favoriteLoading: true });
try {
const ok = await (next ? addFavorite(id) : removeFavorite(id));
if (ok) {
this._favoritedMap[id] = next;
if (this.data.worksheetId === id)
this.setData({ isPreviewFavorite: next });
}
wx.showToast({
title: ok
? next
? '收藏成功'
: '已取消收藏'
: '收藏操作失败,请重试',
icon: 'none',
});
} finally {
this.setData({ favoriteLoading: false });
}
wx.showToast({
title: next ? '收藏成功' : '已取消收藏',
icon: 'none',
});
},
async loadFavoritedMap() {
const ids = [PAPER_SHEET_WORKSHEET_ID];
this._favoritedMap = await batchCheckFavorited(ids);
if (this._favoritedMap[this.data.worksheetId]) {
this.setData({ isPreviewFavorite: true });
const ids = [
PAPER_SHEET_WORKSHEET_ID,
...PAPER_TYPE_OPTIONS.map((paper) =>
getWorksheetIdForPaperType(paper.id),
),
];
const versions = { ...this._favoriteVersions };
try {
const map = await batchCheckFavorited(ids);
// 慢速初次查询不能覆盖查询期间完成的收藏操作。
for (const id of ids) {
if (versions[id] === this._favoriteVersions[id])
this._favoritedMap[id] = map[id] === true;
}
this.setData({
isPreviewFavorite:
this._favoritedMap[this.data.worksheetId] === true,
});
} catch {
// 收藏加载失败不阻止预览;后续操作仍以服务端写入结果为准。
}
},
getWorksheetStatsId(): string {
return this.data.worksheetId;
},
getPublishMeta(): DebugPublishMeta {
if (!this.data.isWorksheetReady) throw new Error('请先加载作业纸');
const meta = getPublishMetaByMode(this.data.worksheetId);
if (!meta) {
throw new Error('当前题型配置不存在');
@@ -1,11 +1,11 @@
<nav-bar title="作业纸" />
<nav-bar title="{{pageTitle}}" />
<view class="ps-page">
<view class="ps-main">
<preview-card
id="previewCard"
showRefresh="{{true}}"
showFavorite="{{true}}"
showFavorite="{{isWorksheetReady && !favoriteLoading}}"
favorited="{{isPreviewFavorite}}"
bind:canvas-ready="onCanvasReady"
bind:refresh="onPreviewRefresh"
@@ -63,6 +63,7 @@
<debug-publish-tools
wx:if="{{isDevEnv && hasContent}}"
id="debugPublishTools"
defaultCropMode="none"
visible="{{debugPublishVisible}}"
loading="{{debugPublishLoading}}"
meta="{{debugPublishMeta}}"