dsh-game-material-master 0.3.0 → 0.6.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.
package/lib/client.js CHANGED
@@ -98,6 +98,7 @@ window.__ModuleLoader__.load({
98
98
  "已创建新项目": "New project created",
99
99
  "确定删除项目「{n0}」?项目目录会被整个移除,无法撤销。": "Delete project \"{n0}\"? The whole project directory is removed, and this cannot be undone.",
100
100
  "新的项目名": "New project name",
101
+ "新项目的名字": "Name for the new project",
101
102
  "读取文件失败": "Failed to read file",
102
103
  "已上传源图:{n0}": "Source image uploaded: {n0}",
103
104
  "提示词已保存": "Prompt saved",
@@ -373,6 +374,7 @@ window.__ModuleLoader__.load({
373
374
  "已取消通过": "Approval removed",
374
375
  "已标记通过": "Marked as approved",
375
376
  "下载 PNG": "Download PNG",
377
+ "下载原图": "Download original",
376
378
  "已重新生成": "Regenerated",
377
379
  "正在重新生成第 {n0} 张…": "Regenerating image {n0}…",
378
380
  "删除": "Delete",
@@ -497,6 +499,7 @@ window.__ModuleLoader__.load({
497
499
  "取消隐藏": "Unhide",
498
500
  "隐藏": "Hide",
499
501
  "已更新「{n0}」的语义": "Updated semantics for \"{n0}\"",
502
+ "语义校验失败": "Semantics validation failed",
500
503
  "{n0}{n1}": "{n0}{n1}",
501
504
  "近端": "proximal",
502
505
  "远端": "distal",
@@ -752,6 +755,9 @@ window.__ModuleLoader__.load({
752
755
  "已新建骨骼动画任务": "Skeletal animation job created",
753
756
  "删除任务「{n0}」?产物文件会一并删除。": "Delete job \"{n0}\"? Its output files will be deleted as well.",
754
757
  "新的任务名": "New job name",
758
+ "新图片任务的名字": "Name for the new image job",
759
+ "新序列帧任务的名字": "Name for the new sequence job",
760
+ "新骨骼动画任务的名字": "Name for the new skeletal animation job",
755
761
  "已重命名": "Renamed",
756
762
  "已上传参考图:{n0}": "Reference image uploaded: {n0}",
757
763
  "已上传 {n0} 个部件(文件名即部件名)": "Uploaded {n0} parts (the file name is used as the part name)",
@@ -1025,7 +1031,173 @@ window.__ModuleLoader__.load({
1025
1031
  "放弃修改": "Discard changes",
1026
1032
  "共 {n0} 行 × {n1} 列": "{n0} rows x {n1} cols",
1027
1033
  "正在编辑 {n0} · 当前是「{n1}」": "Editing {n0} · currently '{n1}'",
1028
- "涂改只改草稿,点「保存布局」才写回项目;之后再点「铺成地图」出图。手动改布局不会作废已生成的地块。": "Painting only changes a draft; click 'Save layout' to write it back, then 'Assemble map' to render. Editing the layout never discards generated tiles."
1034
+ "涂改只改草稿,点「保存布局」才写回项目;之后再点「铺成地图」出图。手动改布局不会作废已生成的地块。": "Painting only changes a draft; click 'Save layout' to write it back, then 'Assemble map' to render. Editing the layout never discards generated tiles.",
1035
+ // ── 功能管理 / 侧栏快捷菜单 ──
1036
+ "功能菜单": "Feature menu",
1037
+ "快捷进入功能": "Jump to a feature",
1038
+ "功能管理": "Feature management",
1039
+ "隐藏不用的功能。隐藏后界面里不再出现它的页签与侧栏菜单项,对话里的 AI 也无法调用它(工具会直接报错)。随时可以再打开,已有的项目数据不会被删除。": "Hide the features you do not use. A hidden feature disappears from the workbench tabs and the sidebar menu, and the agent cannot call it either (its tools fail loudly). You can turn it back on at any time, and existing project data is never deleted.",
1040
+ "已隐藏": "Hidden",
1041
+ "显示中": "Visible",
1042
+ "当前功能全部可见。": "All features are currently visible.",
1043
+ "已隐藏 {n0} 个功能:{n1}。隐藏的模块在对话里同样不可调用。": "{n0} feature(s) hidden: {n1}. Hidden modules cannot be called from chat either.",
1044
+ "已隐藏 {n0} 个功能(设置 → 游戏素材大师 → 功能管理)": "{n0} feature(s) hidden (Settings → Game Material Master → Feature management)",
1045
+ "所有功能都已被隐藏,请到「设置 → 游戏素材大师 → 功能管理」里打开至少一个。": "Every feature is hidden. Turn at least one back on in \"Settings → Game Material Master → Feature management\".",
1046
+ "所有功能都已被隐藏。请到「设置 → 游戏素材大师 → 功能管理」里打开至少一个。": "Every feature is hidden. Turn at least one back on in \"Settings → Game Material Master → Feature management\".",
1047
+ // ── 地图编辑器(模块六)────────────────────────────────────────────
1048
+ "地图编辑器": "Map editor",
1049
+ "画笔": "Brush",
1050
+ "橡皮": "Eraser",
1051
+ "吸管": "Picker",
1052
+ "我的地图": "My map",
1053
+ "读文件失败": "Failed to read the file",
1054
+ "已导入 {n0}": "Imported {n0}",
1055
+ "还没有地图项目。": "No map project yet.",
1056
+ "还没有导出过。": "Nothing exported yet.",
1057
+ "任务进行中…": "A job is running…",
1058
+ // ── 地图编辑器:实验性说明弹窗 ──────────────────────────────────────
1059
+ "界面上看到的地图与导出的 PNG 执行的是同一份绘制计划,所以不会有「预览好看、导出位移」这种事。": "The map you see and the exported PNG execute the same draw plan, so \"looks right in the preview but shifts on export\" cannot happen.",
1060
+ "地图编辑器仍在开发中": "The map editor is still in development",
1061
+ "地图编辑器(实验性)": "Map editor (experimental)",
1062
+ "已删除项目": "Project deleted",
1063
+ "已改地图尺寸": "Map resized",
1064
+ "换一组": "Roll again",
1065
+ // ── 地图编辑器(模块六):一屏零术语,AsLib RPG Map Maker 同款 ────────
1066
+ "这条路是全本地的:导入素材图、自动连接、画地图、导出 PNG 都在本机算,一次模型调用都没有,所以不花钱。": "This path is fully local: importing the image, auto-connecting, painting and exporting the PNG all run on this machine - not a single model call, so nothing is billed.",
1067
+ "与模块⑤不同:它不生成素材,只把你自己的素材图切成一块一块,铺图、接边和导出都由本地代码完成。": "Unlike module 5 it generates no artwork: it cuts your own tile image into pieces, and the placing, edge matching and export are all done by local code.",
1068
+ "导入自己的素材图 → 自动连接 → 直接画 → 导出 PNG": "Import your own tile image → auto-connect → paint → export PNG",
1069
+ "先在左边点一块图当笔刷。": "Pick a tile on the left first.",
1070
+ "图层 2": "Layer 2",
1071
+ "确定删除素材「{n0}」?它切出来的块会一起删掉,无法撤销。": "Delete the tile image \"{n0}\"? The pieces cut from it are removed too, and this cannot be undone.",
1072
+ "已删除素材": "Tile image deleted",
1073
+ "改小地图会丢掉范围外的格子(可以撤销)。继续?": "Shrinking the map discards the cells outside the new bounds (undoable). Continue?",
1074
+ "清掉这一层上已经画的格子?": "Clear every painted cell on this layer?",
1075
+ "已清空这一层": "Layer cleared",
1076
+ "先选至少一块图:在左边点一下,按住 Shift 或 Ctrl 可以多选。": "Pick at least one tile first: click one on the left, and hold Shift or Ctrl for several.",
1077
+ "选一张素材图开始,或者先用自带素材试试。建出来就是 32×32、两层,可以直接画。": "Choose a tile image to start, or try the built-in one. What you get is a 32 by 32 map with two layers, ready to paint.",
1078
+ "选一张素材图开始": "Choose a tile image to start",
1079
+ "会动 {n0} 帧": "Animates: {n0} frames",
1080
+ "新增素材": "Add image",
1081
+ "恢复默认素材": "Restore built-ins",
1082
+ "还没有素材。点「新增素材」加一张自己的,或者点「恢复默认素材」拿到自带的那套。": "No images yet. Click \"Add image\" to bring your own, or \"Restore built-ins\" to get the bundled set.",
1083
+ "{n0}×{n1} · {n2} 块": "{n0}×{n1} · {n2} tiles",
1084
+ "自带": "Built-in",
1085
+ "素材的属性在新增时就定下来了,之后不能改 —— 要换就删掉重新新增。": "An image's properties are fixed when you add it and cannot be changed afterwards -- delete it and add it again to use different settings.",
1086
+ "素材图": "Image file",
1087
+ "选择图片": "Choose file",
1088
+ "还没选": "Nothing chosen yet",
1089
+ "叫什么": "Name",
1090
+ "留空就用文件名": "Leave empty to use the file name",
1091
+ "格子大小(留空就自动认)": "Cell size (leave empty to detect)",
1092
+ "只影响会动的素材(水、翻页图这类)": "Only affects images that animate (water, flip-books and the like)",
1093
+ "先选一张素材图。": "Choose an image file first.",
1094
+ "已新增素材 {n0}": "Added image: {n0}",
1095
+ "已恢复 {n0} 张默认素材": "Restored {n0} built-in images",
1096
+ "默认素材都在。": "All built-in images are already here.",
1097
+ "会动吗": "Does it animate?",
1098
+ "不动": "No",
1099
+ "这张图当作一堆静止的图块。": "Treats this image as a set of still tiles.",
1100
+ "翻页图": "Flip-book",
1101
+ "像手翻书:每一行是一页,连着播就动起来了。同一列的几行算同一块,画的时候点哪一行都行,整片会一起动。": "Like a flip-book: each row is one page, and playing them in order makes it move. Rows in the same column count as one tile, so it does not matter which row you click when painting -- the whole patch animates together.",
1102
+ "地图大小要是 1 以上的整数。": "The map size must be a whole number of 1 or more.",
1103
+ "地图最大 512×512 格。": "A map can be at most 512×512 cells.",
1104
+ "单位是格。改大只是多出空地;改小会丢掉范围外的格子(可撤销)": "Units are cells. Making it bigger just adds empty space; making it smaller drops the cells outside the new bounds (undoable).",
1105
+ "按图片尺寸自己认格子与用法。想重新认一次,就再上传一遍这张图。": "Works out the cell size and usage from the image dimensions. To detect it again, just upload the image once more.",
1106
+ "一格贴一块图,不做任何拼接。": "One tile per cell, with no stitching.",
1107
+ "按上下左右有没有同样的格子,自动从 16 块里挑一块:边缘、拐角会自己接上。": "Picks one of 16 tiles from the cells above, below, left and right, so edges and corners join up on their own.",
1108
+ "一小格再拆成 2×2 小块,按邻居自动拼成一片。草地、水面这类连着画的地面用它。": "Splits each cell into 2×2 sub-tiles that stitch together with their neighbours. Use it for ground you paint in large areas, such as grass or water.",
1109
+ "普通": "Plain",
1110
+ "整格": "Auto 16",
1111
+ "拼块": "Auto 2×2",
1112
+ "重命名项目": "Rename project",
1113
+ "确定": "OK",
1114
+ "{n0}:{n1}": "{n0}: {n1}",
1115
+ "{n0}:{n1}({n2})": "{n0}: {n1} ({n2})",
1116
+ "撤回上一步": "Undo the last step",
1117
+ "把刚撤回的一步再做回来": "Redo the step you just undid",
1118
+ "按住左键涂抹,铺当前选中的那块图": "Hold the left button to paint the currently selected tile",
1119
+ "把这格擦成空;右键随时是橡皮": "Erase this cell; right-click is always the eraser",
1120
+ "同色的连通区一次填满": "Fill a connected run of the same tile in one go",
1121
+ "吸取这一格用的图块,变成当前笔刷": "Pick up the tile used in this cell and make it the current brush",
1122
+ "拖动平移画布;空格拖或中键拖也行": "Drag to pan the canvas; space-drag or middle-drag works too",
1123
+ "只显示当前这一层,底铺绿色": "Show only the current layer on a green backdrop",
1124
+ "上半换上一层、下半换下一层;中间的数字是当前层号": "Click the upper half for the layer above, the lower half for the one below; the number in the middle is the current layer",
1125
+ "显示或隐藏格线,方便数格子": "Show or hide the grid lines so cells are easier to count",
1126
+ "随机铺满 / 迷宫 / 大陆:用选中的图块一键铺满整层": "Random fill / maze / continent: fill the whole layer with the selected tiles in one click",
1127
+ "地图大小、图层、帮助": "Map size, layers and help",
1128
+ "图层": "Layer",
1129
+ "素材图加载失败:{n0}(试试重新上传这张图)": "Could not load the tile image: {n0} (try uploading it again)",
1130
+ "用自带素材试试": "Try the built-in image",
1131
+ "切换项目": "Switch project",
1132
+ "素材": "Image",
1133
+ "第 {n0} 块": "Tile {n0}",
1134
+ "还没有素材,点上面的「素材」上传一张。": "No tile image yet: click \"Image\" above to upload one.",
1135
+ "油漆桶": "Paint bucket",
1136
+ "抓手": "Hand",
1137
+ "单层预览": "Single layer",
1138
+ "上一层": "Layer up",
1139
+ "下一层": "Layer down",
1140
+ "网格线": "Grid lines",
1141
+ "一键生成": "Generate",
1142
+ "设置": "Settings",
1143
+ "素材调色板": "Tile palette",
1144
+ "自动": "Automatic",
1145
+ "普通图块": "Plain tiles",
1146
+ "整格自动连接": "Full-cell auto-connect",
1147
+ "拼块自动连接": "Block auto-connect",
1148
+ "慢": "Slow",
1149
+ "中": "Medium",
1150
+ "快": "Fast",
1151
+ "这块素材怎么用": "How this image is used",
1152
+ "动画速度": "Animation speed",
1153
+ "导出内容": "What to export",
1154
+ "地图图片 PNG": "Map image (PNG)",
1155
+ "地图长什么样,直接能放进游戏": "How the map looks - ready to drop into a game",
1156
+ "存档数据 JSON": "Save data (JSON)",
1157
+ "每一格是什么,给引擎和工具读": "Which tile sits in each cell, for engines and tools",
1158
+ "素材原图": "Source tilesets",
1159
+ "把素材图一起拷进包里,换台机器也能用": "Copy the tileset images in too, so the package works on another machine",
1160
+ "产出不止一个文件时自动打成一个 ZIP;只有一个文件时就直接给你那个文件。": "More than one file is packed into a single ZIP; a single file is handed to you as it is.",
1161
+ "至少勾一项要导出的内容。": "Choose at least one thing to export.",
1162
+ "最近一次导出:{n0} 个文件": "Last export: {n0} files",
1163
+ "下载 {n0}": "Download {n0}",
1164
+ "打包,含全部内容": "Bundle with everything",
1165
+ "另存为…": "Save as…",
1166
+ "下载走浏览器(默认进它的下载目录);想自己挑位置就点「另存为…」。": "Downloads go through the browser (its download folder by default); use \"Save as…\" to pick the location yourself.",
1167
+ "下载走浏览器:文件会进它的下载目录(想每次都自己挑位置,在浏览器里打开「下载前询问保存位置」)。": "Downloads go through the browser: files land in its download folder (turn on \"Ask where to save each file\" in the browser to choose every time).",
1168
+ "这个浏览器不支持「另存为」,请用下载(位置由浏览器的下载设置决定)。": "This browser does not support \"Save as\" - use the download link instead (the browser decides the location).",
1169
+ "已保存到 {n0}": "Saved to {n0}",
1170
+ "另存为失败:{n0}": "Save as failed: {n0}",
1171
+ "还没有导出过,先点「导出」。现在打开的是项目目录。": "Nothing has been exported yet - press \"Export\" first. The project folder is open for now.",
1172
+ "已打开 {n0}": "Opened {n0}",
1173
+ "文件都在 {n0}": "All files are in {n0}",
1174
+ "倍率": "Scale",
1175
+ "只影响 PNG 的尺寸,不影响存档数据": "Only affects the PNG size, not the saved data",
1176
+ "打开导出目录": "Open the export folder",
1177
+ "地图大小": "Map size",
1178
+ "图层 {n0}": "Layer {n0}",
1179
+ "已加一层": "Layer added",
1180
+ "加一层": "Add layer",
1181
+ "至少要留一层": "At least one layer must remain",
1182
+ "删掉当前这一层": "Delete the current layer",
1183
+ "已删掉这一层": "Layer deleted",
1184
+ "删一层": "Delete layer",
1185
+ "清空当前图层": "Clear current layer",
1186
+ "帮助": "Help",
1187
+ "左键拖动=用当前工具画;空格拖动或中键拖动=平移;滚轮=缩放;右键=橡皮。": "Left-drag paints with the current tool; space-drag or middle-drag pans; the wheel zooms; the right button erases.",
1188
+ "调色板里点一下选一块图当笔刷,按住 Shift 或 Ctrl 可以多选,「一键生成」会用这些图块。": "Click a tile in the palette to use it as the brush; hold Shift or Ctrl to select several, and \"Generate\" uses exactly those.",
1189
+ "地图四周是接上的:自动连接会把上下、左右两边接起来。画布拖不出地图 —— 拖到边就停,地图左上角对齐后不会再乱动;图外那片空白画不上。": "The map wraps all the way round: auto-tiling joins the top/bottom and left/right edges. The canvas cannot be dragged off the map -- it stops at the edge, and once the map's top-left lines up with the canvas it stays there. The blank area outside the map cannot be painted.",
1190
+ "整个模块看过了": "Seen the whole module",
1191
+ "随机铺满": "Random fill",
1192
+ "迷宫": "Maze",
1193
+ "大陆": "Continent",
1194
+ "用的图块:还没选。在左边点一下选一块,按住 Shift 或 Ctrl 可以多选。": "Tiles used: none yet. Click one on the left, and hold Shift or Ctrl for several.",
1195
+ "用的图块:{n0}": "Tiles used: {n0}",
1196
+ "迷宫:按顺序取两块,第一块当墙,第二块当路。": "Maze: takes two tiles in order - the first is the wall, the second the path.",
1197
+ "大陆:按顺序取最多四块当四种地貌(水下 / 海面 / 草地 / 雪地)。": "Continent: takes up to four tiles in order as four terrains (underwater / sea / grass / snow).",
1198
+ "随机铺满:在选中的图块里均匀随机。": "Random fill: uniformly random among the selected tiles.",
1199
+ "缩得太小,放大一点。": "Zoomed out too far - zoom in a bit.",
1200
+ "第 {n0} 层 / 共 {n1} 层": "Layer {n0} of {n1}"
1029
1201
  };
1030
1202
  /* i18n-ignore-end */
1031
1203
  /**
@@ -1047,6 +1219,9 @@ window.__ModuleLoader__.load({
1047
1219
  () => {
1048
1220
  TILE_STAGES = make_TILE_STAGES();
1049
1221
  },
1222
+ () => {
1223
+ MAP_EXPERIMENTAL_POINTS = make_MAP_EXPERIMENTAL_POINTS();
1224
+ },
1050
1225
  () => {
1051
1226
  STAGES = make_STAGES();
1052
1227
  },
@@ -1215,7 +1390,7 @@ window.__ModuleLoader__.load({
1215
1390
  ["resetFramePicks", true],
1216
1391
  ["rekey", true],
1217
1392
  ["compose", true],
1218
- // 模块②:图片生成
1393
+ // 模块②(图片生成)—— 这一段只是远程方法清单,和下面的组件区无关
1219
1394
  ["listImageJobs", false],
1220
1395
  ["createImageJob", true],
1221
1396
  ["getImageJob", true],
@@ -1299,7 +1474,28 @@ window.__ModuleLoader__.load({
1299
1474
  ["saveTileMapCells", true],
1300
1475
  ["runTileExport", true],
1301
1476
  ["cancelTileJob", true],
1302
- ["revealTileProject", true]
1477
+ ["revealTileProject", true],
1478
+ // 地图编辑器(模块六)。同样:第二个字段是「收不收 payload」。
1479
+ ["listMapProjects", false],
1480
+ ["createMapProject", true],
1481
+ ["getMapProject", true],
1482
+ ["saveMapProject", true],
1483
+ ["deleteMapProject", true],
1484
+ ["importMapTileset", true],
1485
+ ["importSampleTileset", true],
1486
+ ["saveMapTileset", true],
1487
+ ["removeMapTileset", true],
1488
+ ["saveMapDoc", true],
1489
+ ["applyMapOps", true],
1490
+ ["mapUndo", true],
1491
+ ["mapRedo", true],
1492
+ ["mapPlan", true],
1493
+ ["runMapGenerate", true],
1494
+ ["runMapPreview", true],
1495
+ ["runMapExport", true],
1496
+ ["cancelMapJob", true],
1497
+ ["setMapApproved", true],
1498
+ ["revealMapProject", true]
1303
1499
  ];
1304
1500
  const CONTRIBUTION = {
1305
1501
  package: PACKAGE,
@@ -1414,14 +1610,25 @@ window.__ModuleLoader__.load({
1414
1610
  ];
1415
1611
  }
1416
1612
  let TILE_EXPERIMENTAL_POINTS = make_TILE_EXPERIMENTAL_POINTS();
1417
- /** 五个功能模块。插件是「大师」,每个模块管一类素材。 */
1613
+ /** 进入模块⑥时的实验性说明要点(导入自己的素材图那条路)。 */
1614
+ function make_MAP_EXPERIMENTAL_POINTS() {
1615
+ return [
1616
+ T("这条路是全本地的:导入素材图、自动连接、画地图、导出 PNG 都在本机算,一次模型调用都没有,所以不花钱。"),
1617
+ T("与模块⑤不同:它不生成素材,只把你自己的素材图切成一块一块,铺图、接边和导出都由本地代码完成。"),
1618
+ T("界面上看到的地图与导出的 PNG 执行的是同一份绘制计划,所以不会有「预览好看、导出位移」这种事。"),
1619
+ T("发现问题或有改进想法,欢迎到 GitHub 仓库一起开发。")
1620
+ ];
1621
+ }
1622
+ let MAP_EXPERIMENTAL_POINTS = make_MAP_EXPERIMENTAL_POINTS();
1623
+ /** 六个功能模块。插件是「大师」,每个模块管一类素材。 */
1418
1624
  function make_MODULES() {
1419
1625
  return [
1420
1626
  { key: "sprite", title: T("八方向图生成"), hint: T("一张设定图 → 8 方向 × 8 帧精灵图") },
1421
1627
  { key: "image", title: T("图片生成"), hint: T("按提示词出图,可带参考图,支持抠绿幕导出 PNG") },
1422
1628
  { key: "sequence", title: T("序列帧生成"), hint: T("图/视频参考生成视频 → 抽帧 → 抠像 → 合成与播放预览") },
1423
1629
  { key: "rig", title: T("骨骼动画生成"), hint: T("拆件 → 装配定位 → 推骨骼与动画 → 打包 Spine 图集"), experimental: true },
1424
- { key: "tile", title: T("45°地图地块生成"), hint: T("45° 等距地块 → 拼成地图:几何交给代码,内容交给 AI"), experimental: true }
1630
+ { key: "tile", title: T("45°地图地块生成"), hint: T("45° 等距地块 → 拼成地图:几何交给代码,内容交给 AI"), experimental: true },
1631
+ { key: "map", title: T("地图编辑器"), hint: T("导入自己的素材图 → 自动连接 → 直接画 → 导出 PNG"), experimental: true }
1425
1632
  ];
1426
1633
  }
1427
1634
  let MODULES = make_MODULES();
@@ -1445,6 +1652,72 @@ window.__ModuleLoader__.load({
1445
1652
  ];
1446
1653
  }
1447
1654
  let STAGES = make_STAGES();
1655
+ // ── 功能管理(被隐藏的模块)──────────────────────────────────────────
1656
+ //
1657
+ // 设置页「功能管理」写、工作台页签与侧栏菜单读,所以状态放在工厂闭包里共享
1658
+ // 一份,而不是各自去 `getConfig()`。
1659
+ //
1660
+ // 「隐藏」是**双向**的:这里只管界面,对话工具面由宿主 `src/tools.ts` 再拦
1661
+ // 一次(`hiddenModules` 存在宿主配置里,两侧读的是同一份)。只藏界面不拦
1662
+ // 工具等于没藏——模型照样能调生成类方法,真实计费。
1663
+ const hiddenModulesState = { keys: [], listeners: new Set() };
1664
+ /** 收敛成合法且顺序固定的 key 数组(与宿主 `normalizeHiddenModules` 同口径)。 */
1665
+ function normalizeHiddenKeys(value) {
1666
+ if (!Array.isArray(value))
1667
+ return [];
1668
+ return MODULES.map((entry) => entry.key).filter((key) => value.includes(key));
1669
+ }
1670
+ /** 写入并通知订阅者;内容没变就不通知(避免无谓重渲染)。 */
1671
+ function publishHiddenModules(value) {
1672
+ const next = normalizeHiddenKeys(value);
1673
+ if (next.length === hiddenModulesState.keys.length && next.every((key, index) => key === hiddenModulesState.keys[index]))
1674
+ return;
1675
+ hiddenModulesState.keys = next;
1676
+ for (const listener of [...hiddenModulesState.listeners]) {
1677
+ try {
1678
+ listener(next);
1679
+ }
1680
+ catch {
1681
+ // 单个订阅者出错不该拖垮别的。
1682
+ }
1683
+ }
1684
+ }
1685
+ /** 从宿主读一次当前可见性。读失败就当作「全部可见」,不要因此白屏。 */
1686
+ async function refreshHiddenModules(api) {
1687
+ if (api === undefined)
1688
+ return;
1689
+ try {
1690
+ const config = await api.getConfig();
1691
+ publishHiddenModules(config?.hiddenModules);
1692
+ }
1693
+ catch {
1694
+ // 配置读不到不是致命错误:界面照常,工具面仍然会拦。
1695
+ }
1696
+ }
1697
+ /**
1698
+ * 组件里用:当前被隐藏的模块 key 数组。
1699
+ *
1700
+ * `api` 可省略(那时只订阅、不主动拉取)——设置页自己会 `load()` 并 publish。
1701
+ */
1702
+ function useHiddenModules(api) {
1703
+ const [hidden, setHidden] = React.useState(hiddenModulesState.keys);
1704
+ React.useEffect(() => {
1705
+ hiddenModulesState.listeners.add(setHidden);
1706
+ // 订阅之前可能已经有值了(设置页先加载完),补一次对齐。
1707
+ setHidden(hiddenModulesState.keys);
1708
+ return () => {
1709
+ hiddenModulesState.listeners.delete(setHidden);
1710
+ };
1711
+ }, []);
1712
+ React.useEffect(() => {
1713
+ void refreshHiddenModules(api);
1714
+ }, [api]);
1715
+ return hidden;
1716
+ }
1717
+ /** 可见的模块(页签、侧栏菜单都按它渲染)。 */
1718
+ function visibleModulesOf(hidden) {
1719
+ return MODULES.filter((entry) => !hidden.includes(entry.key));
1720
+ }
1448
1721
  // ── 深链接:从会话里点一下链接就切到插件对应页面 ─────────────────────
1449
1722
  //
1450
1723
  // 宿主 src/links.ts 是这套约定的唯一真源;这里只能复制常量(浏览器半区是
@@ -1455,7 +1728,7 @@ window.__ModuleLoader__.load({
1455
1728
  // http(s) 链接加 target="_blank",不拦就会真的新开一个标签页。
1456
1729
  // 只按 `dsh-gmm` 参数识别自己的链接,其它链接(含站外的)一律放行。
1457
1730
  const OPEN_QUERY_KEY = "dsh-gmm";
1458
- const OPEN_MODULES = new Set(["sprite", "image", "sequence", "rig", "tile"]);
1731
+ const OPEN_MODULES = new Set(["sprite", "image", "sequence", "rig", "tile", "map"]);
1459
1732
  /** 意图订阅者:各模块组件都挂着,谁在挂载谁就被通知。 */
1460
1733
  const intentListeners = new Set();
1461
1734
  /** 最近一次意图。晚挂载的组件(切模块后才渲染)订阅时立刻拿到它。 */
@@ -1618,6 +1891,13 @@ window.__ModuleLoader__.load({
1618
1891
  // 就被切了;而前四个模块恰好都在 686 以内,所以这个坑一直没暴露出来。
1619
1892
  const CSS = `
1620
1893
  .SPR_root{display:flex;flex-direction:column;height:100%;min-height:0;overflow-y:auto;overflow-x:hidden;color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px}
1894
+ /*
1895
+ * 六号模块(地图编辑器)自己的正文容器。
1896
+ *
1897
+ * ⚠️ 以前**一条 CSS 都没有**:卡片与文字紧贴面板左右边缘,看着像没做完(真机反馈
1898
+ * 「这个界面离左边没有 padding」)。这里对齐模块①②③用的 .SPR_main(16px 18px 40px)。
1899
+ */
1900
+ .SPR_moduleBody{display:block;padding:16px 18px 40px}
1621
1901
  .SPR_head{display:flex;align-items:center;gap:10px;padding:14px 18px;border-bottom:1px solid var(--dsw-alias-border-l2);flex:none}
1622
1902
  .SPR_head h2{margin:0;font-size:15px;font-weight:600}
1623
1903
  .SPR_headSub{color:var(--dsw-alias-label-tertiary);font-size:12px}
@@ -1706,6 +1986,126 @@ window.__ModuleLoader__.load({
1706
1986
  .SPR_mapCell-active{background:rgba(255,120,0,.6);outline:1px solid rgba(255,120,0,.9)}
1707
1987
  .SPR_mapCell-empty{background:rgba(150,150,150,.16)}
1708
1988
  .SPR_mapCellLabel{pointer-events:none;font-size:10px;color:var(--dsw-alias-label-secondary);opacity:0}
1989
+ /* ── 地图编辑器(模块六)· AsLib RPG Map Maker 同款一屏布局 ─────────────
1990
+ 外层仍然走 DSH 变量(浅色 / 深色都不吃亏),编辑器内部沿用 AsLib 配色:
1991
+ 深灰 #424242、木质按钮、红框选中、单层预览绿底 rgb(56,170,68)。 */
1992
+ .SPR_moduleBody[data-module="map"]{padding:0;height:100%;box-sizing:border-box;display:flex;flex-direction:column;min-height:0}
1993
+ .SPR_mapEdRoot{display:flex;flex-direction:column;flex:1;min-height:0;border-radius:12px;overflow:hidden;background:#424242;color:#f2efe9;border:1px solid var(--dsw-alias-border-l2)}
1994
+ .SPR_mapEdSpacer{flex:1;min-width:0}
1995
+ .SPR_mapEdHint{font-size:11px;line-height:1.7;color:#c9c4bb;margin:0}
1996
+ /* 顶栏:一行。没有步骤条,也没有长说明。 */
1997
+ .SPR_mapEdTop{display:flex;align-items:center;gap:8px;padding:6px 10px;background:#383838;border-bottom:1px solid #232323;flex:none}
1998
+ .SPR_mapEdProjWrap{position:relative;min-width:0}
1999
+ .SPR_mapEdProj{display:inline-flex;align-items:center;gap:6px;font:inherit;font-size:13px;font-weight:600;max-width:280px;cursor:pointer;color:#f7f3ec;background:transparent;border:1px solid transparent;border-radius:8px;padding:4px 8px}
2000
+ .SPR_mapEdProj:hover{background:#4a4a4a}
2001
+ .SPR_mapEdProj[data-open="true"]{background:#4a4a4a;border-color:#6d6d6d}
2002
+ .SPR_mapEdProjName{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2003
+ .SPR_mapEdCaret{font-size:10px;color:#c9c4bb}
2004
+ .SPR_mapEdMenu{position:absolute;top:calc(100% + 4px);left:0;z-index:30;min-width:200px;max-height:60vh;overflow:auto;display:flex;flex-direction:column;padding:4px;background:#2f2f2f;border:1px solid #1c1c1c;border-radius:10px;box-shadow:0 10px 26px rgba(0,0,0,.45)}
2005
+ .SPR_mapEdMenuItem{font:inherit;font-size:12px;text-align:left;cursor:pointer;color:#ece7df;background:transparent;border:none;border-radius:6px;padding:6px 9px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
2006
+ .SPR_mapEdMenuItem:hover{background:#454545}
2007
+ .SPR_mapEdMenuItem[data-on="true"]{background:#4d4d4d;color:var(--dsw-alias-state-business-primary, #8ab4f8)}
2008
+ .SPR_mapEdMenuItem[data-danger="true"]{color:var(--dsw-alias-state-error-primary, #ff8b7a)}
2009
+ .SPR_mapEdMenuLabel{font-size:10px;color:#9d968c;padding:8px 9px 2px}
2010
+ .SPR_mapEdTopBtn{font:inherit;font-size:12px;cursor:pointer;color:#f7f3ec;background:linear-gradient(#5d5d5d,#4b4b4b);border:1px solid #232323;border-radius:8px;padding:5px 14px}
2011
+ .SPR_mapEdTopBtn:hover{background:linear-gradient(#6a6a6a,#555)}
2012
+ .SPR_mapEdTopBtn[data-on="true"]{background:linear-gradient(#7d6a4a,#5f5038);border-color:#d9a95f}
2013
+ .SPR_mapEdSave{font-size:11px;color:#b9b3a8;white-space:nowrap;font-variant-numeric:tabular-nums}
2014
+ .SPR_mapEdSave[data-busy="true"]{color:var(--dsw-alias-state-warning-primary, #ffc400)}
2015
+ /* 两栏主体:左列 28.5%(240~340),右列画布。 */
2016
+ .SPR_mapEdBody{display:flex;flex:1;min-height:0}
2017
+ .SPR_mapEdSide{width:28.5%;min-width:240px;max-width:340px;flex:none;display:flex;flex-direction:column;gap:6px;padding:8px;box-sizing:border-box;background:#3b3b3b;border-right:1px solid #232323;min-height:0}
2018
+ .SPR_mapEdSideTitle{font-size:11px;color:#a9a29a;padding-left:2px}
2019
+ .SPR_mapEdPalette{flex:1;min-height:120px;overflow:auto;background:#2d2d2d;border:1px solid #232323;border-radius:6px;padding:4px}
2020
+ .SPR_mapEdPaletteGrid{display:grid;grid-template-columns:repeat(8,32px);gap:2px}
2021
+ .SPR_mapEdTile{width:32px;height:32px;padding:0;border:1px solid #262626;border-radius:3px;background-color:#1f1f1f;background-repeat:no-repeat;image-rendering:pixelated;cursor:pointer}
2022
+ .SPR_mapEdTile:hover{border-color:#d9a95f}
2023
+ /* 红框=当前笔刷(AsLib 同款) */
2024
+ .SPR_mapEdTile[data-on="true"]{outline:2px solid #e23b2b;outline-offset:-2px;border-color:#e23b2b}
2025
+ /* 工具格:6 列 × 2 行,木质方块按钮 */
2026
+ .SPR_mapEdTools{display:grid;grid-template-columns:repeat(6,1fr);gap:4px;flex:none}
2027
+ .SPR_mapEdTool{aspect-ratio:1/1;display:flex;align-items:center;justify-content:center;padding:0;cursor:pointer;color:#3a2a12;background:linear-gradient(#e6bd7d,#c9974f);border:1px solid #6b4a22;border-radius:4px}
2028
+ .SPR_mapEdTool:hover{background:linear-gradient(#f2d29a,#d6a761)}
2029
+ .SPR_mapEdTool[data-on="true"]{background:linear-gradient(#fbe3ad,#e0b268);box-shadow:inset 0 0 0 2px #d23b2c}
2030
+ .SPR_mapEdTool:disabled{opacity:.4;cursor:default}
2031
+ .SPR_mapEdLayerBtn{flex-direction:column;gap:0;padding:1px;background:linear-gradient(#e6bd7d,#c9974f)}
2032
+ /* 工具格上方的小标签(名称 + 快捷键 + 介绍)。
2033
+ position:fixed —— 祖先里有 overflow 容器,absolute 会被裁掉「按钮正上方」那一段。 */
2034
+ .SPR_mapEdTip{position:fixed;z-index:60;pointer-events:none;transform:translate(-50%,-100%);max-width:236px;padding:6px 8px;border-radius:6px;border:1px solid #6b4a22;background:#2b2b2b;color:#f3e7d3;box-shadow:0 6px 16px rgba(0,0,0,.4);font-size:11px;line-height:1.5;text-align:left}
2035
+ .SPR_mapEdTip::after{content:"";position:absolute;left:50%;bottom:-6px;margin-left:-5px;border-left:5px solid transparent;border-right:5px solid transparent;border-top:6px solid #2b2b2b}
2036
+ .SPR_mapEdTipName{display:flex;align-items:center;gap:6px;font-weight:600}
2037
+ .SPR_mapEdTipKey{padding:0 4px;border-radius:3px;background:#4a4a4a;font-size:10px;font-weight:400;color:#e8d7bb}
2038
+ .SPR_mapEdTipDesc{margin-top:2px;color:#c9bda8}
2039
+ /* 新建 / 重命名项目的名字对话框。fixed 居中:祖先里有 overflow 容器,
2040
+ absolute 会被裁掉(和工具小标签、侧栏菜单同一个坑)。 */
2041
+ .SPR_mapEdDlgMask{position:fixed;inset:0;z-index:70;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.42)}
2042
+ .SPR_mapEdDlg{width:300px;max-width:calc(100vw - 32px);padding:12px;border:1px solid #6b4a22;border-radius:8px;background:#2f2f2f;color:#f3e7d3;box-shadow:0 10px 30px rgba(0,0,0,.5)}
2043
+ .SPR_mapEdDlgTitle{font-size:13px;font-weight:600;margin-bottom:8px}
2044
+ .SPR_mapEdDlgLabel{display:block;font-size:11px;color:#c9bda8;margin-bottom:4px}
2045
+ .SPR_mapEdDlgInput{width:100%;box-sizing:border-box;padding:6px 8px;border:1px solid #6b4a22;border-radius:4px;background:#1f1f1f;color:#f3e7d3;font-size:12px;outline:none}
2046
+ .SPR_mapEdDlgInput:focus{border-color:#d9a95f}
2047
+ .SPR_mapEdDlgRow{display:flex;justify-content:flex-end;gap:8px;margin-top:12px}
2048
+ .SPR_mapEdLayerHalf{flex:1;width:100%;display:flex;align-items:center;justify-content:center;padding:0;cursor:pointer;color:#4a3416;background:transparent;border:none;border-radius:3px}
2049
+ .SPR_mapEdLayerHalf:hover:not(:disabled){background:rgba(255,255,255,.28)}
2050
+ .SPR_mapEdLayerHalf:disabled{opacity:.3;cursor:default}
2051
+ .SPR_mapEdLayerNum{font-size:10px;line-height:1;font-weight:700;color:#4a3416;font-variant-numeric:tabular-nums}
2052
+ /* 画布:铺满右列,像素画不糊 */
2053
+ .SPR_mapEdStage{position:relative;flex:1;min-width:0;min-height:360px;background:#3a3a3a;overflow:hidden}
2054
+ .SPR_mapEdCanvas{display:block;width:100%;height:100%;image-rendering:pixelated;touch-action:none;cursor:crosshair}
2055
+ .SPR_mapEdToast{position:absolute;left:10px;bottom:10px;font-size:11px;padding:4px 10px;border-radius:999px;background:rgba(0,0,0,.62);color:#ffe9a8}
2056
+ .SPR_mapEdToast[data-busy="true"]{color:var(--dsw-alias-state-warning-primary, #ffc400)}
2057
+ /* 卡片:从顶栏下面拉出来的小面板,盖在画布上(关掉就什么都不占) */
2058
+ .SPR_mapEdCardWrap{position:absolute;top:44px;right:12px;z-index:20;max-width:min(520px,92%)}
2059
+ .SPR_mapEdCard{display:flex;flex-direction:column;gap:8px;padding:10px 12px;border-radius:10px;background:#2f2f2f;border:1px solid #1c1c1c;box-shadow:0 12px 30px rgba(0,0,0,.5)}
2060
+ .SPR_mapEdCardHead{display:flex;align-items:center;gap:8px}
2061
+ .SPR_mapEdCardHead>h4{margin:0;font-size:13px;color:#f7f3ec}
2062
+ .SPR_mapEdCardClose{font:inherit;font-size:14px;line-height:1;cursor:pointer;color:#c9c4bb;background:transparent;border:none;border-radius:6px;padding:2px 6px}
2063
+ .SPR_mapEdCardClose:hover{background:#454545;color:#fff}
2064
+ .SPR_mapEdCardRow{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
2065
+ .SPR_mapEdRows{display:flex;flex-direction:column;gap:6px}
2066
+ .SPR_mapEdRow{display:flex;flex-direction:column;gap:3px}
2067
+ .SPR_mapEdLabel{font-size:11px;color:#bfb8ae}
2068
+ .SPR_mapEdRowHint{font-size:11px;line-height:1.6;color:#9d968c}
2069
+ .SPR_mapEdTsList{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:4px;max-height:220px;overflow:auto}
2070
+ .SPR_mapEdTsRow{display:flex;align-items:center;gap:6px;padding:3px 4px;border:1px solid transparent;border-radius:6px}
2071
+ .SPR_mapEdTsRow[data-on="true"]{border-color:#d9a95f;background:#3a2f1d}
2072
+ .SPR_mapEdTsPick{flex:1;display:flex;align-items:baseline;gap:8px;min-width:0;padding:2px 4px;font:inherit;font-size:12px;color:#f2efe9;text-align:left;background:none;border:0;cursor:pointer}
2073
+ .SPR_mapEdTsPick:hover{color:#ffd79a}
2074
+ .SPR_mapEdTsName{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2075
+ .SPR_mapEdTsMeta{flex:none;font-size:11px;color:#9a9a9a}
2076
+ .SPR_mapEdTsBadge{flex:none;padding:0 4px;border-radius:3px;background:#4a4a4a;font-size:10px;color:#e8d7bb}
2077
+ .SPR_mapEdTsBadge[data-anim="true"]{background:#2f4a2f;color:#bfe6bf}
2078
+ .SPR_mapEdPair{display:flex;align-items:center;gap:6px}
2079
+ .SPR_mapEdTimes{color:#9a9a9a;font-size:12px}
2080
+ .SPR_mapEdSeg{display:flex;gap:4px;flex-wrap:wrap}
2081
+ .SPR_mapEdSegBtn{font:inherit;font-size:12px;padding:4px 10px;border:1px solid #565656;border-radius:6px;background:#242424;color:#f2efe9;cursor:pointer}
2082
+ .SPR_mapEdSegBtn:hover{border-color:#d9a95f}
2083
+ .SPR_mapEdSegBtn[data-on="true"]{border-color:#d9a95f;background:#3a2f1d;color:#ffd79a;font-weight:600}
2084
+ .SPR_mapEdSelect{font:inherit;font-size:12px;color:#f2efe9;background:#242424;border:1px solid #565656;border-radius:6px;padding:4px 8px;max-width:100%}
2085
+ .SPR_mapEdChips{display:flex;gap:6px;flex-wrap:wrap}
2086
+ .SPR_mapEdChip{font:inherit;font-size:11px;cursor:pointer;color:#ded8cf;background:#3b3b3b;border:1px solid #565656;border-radius:999px;padding:3px 10px}
2087
+ .SPR_mapEdChip[data-on="true"]{border-color:#d9a95f;color:#ffd89a}
2088
+ .SPR_mapEdCheck{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:#e6e1d8}
2089
+ .SPR_mapEdHelp{display:flex;flex-direction:column;gap:4px;padding:8px 10px;border-radius:8px;background:#383838}
2090
+ .SPR_mapEdHelp>h5{margin:0;font-size:12px;color:#f7f3ec}
2091
+ .SPR_mapEdHelp>p{margin:0;font-size:11px;line-height:1.7;color:#c9c4bb}
2092
+ .SPR_mapEdRadios{display:flex;gap:12px;flex-wrap:wrap}
2093
+ .SPR_mapEdRadio{display:inline-flex;align-items:center;gap:5px;font-size:12px;color:#e6e1d8;cursor:pointer}
2094
+ .SPR_mapEdFiles{margin:0;padding-left:18px;font-size:12px;line-height:1.9;color:#c9c4bb}
2095
+ .SPR_mapEdFiles li{display:flex;align-items:center;gap:6px}
2096
+ .SPR_mapEdFiles a{color:var(--dsw-alias-state-business-primary, #8ab4f8)}
2097
+ /* 导出结果区:把「导完了、文件在哪、怎么拿走」圈在一起,与上面的选择区分开 */
2098
+ .SPR_mapEdExportResult{display:flex;flex-direction:column;gap:6px;padding:8px 10px;border:1px solid #4a4a4a;border-radius:8px;background:#383838}
2099
+ .SPR_mapEdMark{color:var(--dsw-alias-state-success-primary, #7ee08a);font-weight:700}
2100
+ .SPR_mapEdWarnings{margin:0;padding-left:18px;font-size:11px;line-height:1.7;color:#d8d2c8}
2101
+ .SPR_mapEdFoot{display:flex;align-items:center;gap:10px;padding:5px 10px;background:#383838;border-top:1px solid #232323;flex:none;flex-wrap:wrap}
2102
+ .SPR_mapEdFoot .SPR_notice{margin:0}
2103
+ .SPR_mapEdFootText{font-size:11px;color:#b9b3a8;font-variant-numeric:tabular-nums}
2104
+ /* 空态:一句话 + 两个按钮,点完一步到位(建项目 → 导素材 → 32×32 两层,直接可画) */
2105
+ .SPR_mapEdEmpty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;flex:1;min-height:320px;padding:30px 20px;text-align:center;background:#424242;border-radius:12px;border:1px solid var(--dsw-alias-border-l2)}
2106
+ .SPR_mapEdEmptyText{margin:0;font-size:15px;font-weight:600;color:#f7f3ec}
2107
+ .SPR_mapEdEmptyRow{display:flex;gap:10px;flex-wrap:wrap;justify-content:center}
2108
+
1709
2109
  .SPR_mapCell:hover .SPR_mapCellLabel{opacity:1}
1710
2110
  .SPR_step-active{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-state-business-primary)}
1711
2111
  .SPR_step-done .SPR_stepMark{color:var(--dsw-alias-state-success-primary,#2e7d32)}
@@ -1781,6 +2181,15 @@ window.__ModuleLoader__.load({
1781
2181
  .SPR_settingsGroup{border:1px solid var(--dsw-alias-border-l2);border-radius:12px;padding:14px;background:var(--dsw-alias-bg-layer-3)}
1782
2182
  .SPR_settingsGroup h3{margin:0 0 4px;font-size:13px;font-weight:600}
1783
2183
  .SPR_settingsGroup p{margin:0 0 10px;color:var(--dsw-alias-label-tertiary);font-size:12px}
2184
+ /* 功能管理:一行一个模块,勾选框在左、说明在中间、状态在右。 */
2185
+ .SPR_featureList{display:flex;flex-direction:column;gap:6px;margin-bottom:10px}
2186
+ .SPR_featureRow{display:flex;align-items:flex-start;gap:10px;padding:8px 10px;border-radius:10px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);cursor:pointer}
2187
+ .SPR_featureRow[data-hidden=true]{opacity:.62}
2188
+ .SPR_featureCheck{margin:2px 0 0;width:15px;height:15px;flex:none;accent-color:var(--dsw-alias-state-business-primary);cursor:pointer}
2189
+ .SPR_featureText{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1}
2190
+ .SPR_featureTitle{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary)}
2191
+ .SPR_featureHint{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary)}
2192
+ .SPR_featureState{font-size:11px;line-height:18px;flex:none;padding:0 8px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-tertiary)}
1784
2193
  .SPR_keyRow{display:flex;gap:8px;align-items:flex-end}
1785
2194
  .SPR_keyRow .SPR_field{flex:1}
1786
2195
  .SPR_badge{font-size:11px;padding:1px 7px;border-radius:999px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-tertiary)}
@@ -1819,7 +2228,8 @@ window.__ModuleLoader__.load({
1819
2228
  .SPR_axisRulerMid{text-align:center}
1820
2229
  .SPR_pickPanel{grid-column:1 / -1;border:1px solid var(--dsw-alias-border-l2);border-radius:12px;padding:12px;background:var(--dsw-alias-bg-layer-1)}
1821
2230
  .SPR_pickHead{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;flex-wrap:wrap}
1822
- .SPR_modules{display:flex;gap:8px;padding:10px 18px;border-bottom:1px solid var(--dsw-alias-border-l2);flex:none;flex-wrap:wrap}
2231
+ .SPR_modules{display:flex;gap:8px;padding:10px 18px;border-bottom:1px solid var(--dsw-alias-border-l2);flex:none;flex-wrap:wrap;align-items:center}
2232
+ .SPR_modulesHiddenNote{font-size:11px;color:var(--dsw-alias-label-tertiary);margin-left:auto}
1823
2233
  .SPR_module{font:inherit;cursor:pointer;text-align:left;display:flex;flex-direction:column;gap:1px;padding:6px 12px;border-radius:10px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary)}
1824
2234
  .SPR_module:hover{background:var(--dsw-alias-interactive-bg-hover-solid)}
1825
2235
  .SPR_module[data-active=true]{border-color:var(--dsw-alias-state-business-primary);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);box-shadow:0 0 0 1px color-mix(in srgb, var(--dsw-alias-state-business-primary) 30%, transparent)}
@@ -1977,6 +2387,25 @@ window.__ModuleLoader__.load({
1977
2387
  .SPR_gateMute{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-tertiary);cursor:pointer;margin-right:auto}
1978
2388
  .SPR_gate a.SPR_btn{text-decoration:none;display:inline-flex;align-items:center}
1979
2389
  .SPR_gate .SPR_link{align-self:flex-start}
2390
+
2391
+ /* ── 侧栏入口上的菜单按钮 ───────────────────────────────────────────────
2392
+ 宿主把这一坨渲染在它自己的 <button class=…panelRow> 里面,所以:
2393
+ · 图标本体保持原尺寸,右下角叠一个 14px 的折角触发器(命中区靠 padding 撑);
2394
+ · 菜单用 position:fixed —— 祖先里有 overflow:hidden 的容器,
2395
+ absolute 定位在某些窗口布局下会被裁掉。 */
2396
+ .SPR_railGlyph{position:relative;display:inline-flex;align-items:center;justify-content:center}
2397
+ .SPR_railMenuBtn{position:absolute;right:-9px;bottom:-7px;width:14px;height:14px;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;cursor:pointer;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l3);box-shadow:0 1px 3px rgba(0,0,0,.18)}
2398
+ .SPR_railMenuBtn:hover{background:var(--dsw-alias-interactive-bg-hover-solid);color:var(--dsw-alias-label-primary)}
2399
+ .SPR_railMenuBtn:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:1px}
2400
+ .SPR_railMenu{position:fixed;z-index:70;width:264px;max-height:min(70vh,420px);overflow:auto;box-sizing:border-box;display:flex;flex-direction:column;gap:2px;padding:8px;border-radius:12px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);box-shadow:0 16px 40px rgba(0,0,0,.28);font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary)}
2401
+ .SPR_railMenuHead{font-size:11px;color:var(--dsw-alias-label-tertiary);padding:2px 8px 6px}
2402
+ .SPR_railMenuEmpty{margin:0;padding:2px 8px 6px;font-size:12px;color:var(--dsw-alias-label-tertiary)}
2403
+ .SPR_railMenuItem{font:inherit;text-align:left;cursor:pointer;display:flex;flex-direction:column;gap:1px;padding:6px 8px;border-radius:8px;border:none;background:transparent;color:inherit}
2404
+ .SPR_railMenuItem:hover{background:var(--dsw-alias-interactive-bg-hover)}
2405
+ .SPR_railMenuItem:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:-2px}
2406
+ .SPR_railMenuItemTitle{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600}
2407
+ .SPR_railMenuItemHint{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary)}
2408
+ .SPR_railMenuFoot{margin-top:4px;padding:6px 8px 2px;border-top:1px solid var(--dsw-alias-border-l2);font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary)}
1980
2409
  `;
1981
2410
  // ── 小工具 ───────────────────────────────────────────────────────────
1982
2411
  function cls(...parts) {
@@ -1990,6 +2419,37 @@ window.__ModuleLoader__.load({
1990
2419
  return error.message;
1991
2420
  return String(error);
1992
2421
  }
2422
+ /**
2423
+ * 新建项目 / 任务时问一个名字(与「重命名」同一套 `window.prompt` 交互)。
2424
+ *
2425
+ * 返回值语义是**三态**,调用方必须照着写:
2426
+ * · `null` —— 用户点了取消 → **不要创建**(点了取消却多出一个项目,会被当成 bug)
2427
+ * · 空串/全空白 —— 用 `fallback`(默认名)
2428
+ * · 其余 —— 用户输入的名字(已 trim)
2429
+ * 没有 `window.prompt` 的宿主退回默认名,不阻断创建。
2430
+ */
2431
+ function askNewName(title, fallback) {
2432
+ if (typeof window === "undefined" || typeof window.prompt !== "function")
2433
+ return fallback;
2434
+ /**
2435
+ * ⚠️ `typeof window.prompt === "function"` **不足以判断能用**:Electron(DSH 桌面端)
2436
+ * 里这个函数存在,但一调用就抛「prompt() is and will not be supported」。抛出去的话
2437
+ * 调用方的 async 处理器直接变成未处理拒绝 —— 界面表现是「点了新建什么都没发生」。
2438
+ * 这里兜住并退回默认名:至少把项目建出来,用户随后改名即可。
2439
+ * (模块六的「新建项目」已经改成自带对话框,不再走这里。)
2440
+ */
2441
+ let value = null;
2442
+ try {
2443
+ value = window.prompt(title, fallback);
2444
+ }
2445
+ catch {
2446
+ return fallback;
2447
+ }
2448
+ if (value === null)
2449
+ return null;
2450
+ const trimmed = String(value).trim();
2451
+ return trimmed === "" ? fallback : trimmed;
2452
+ }
1993
2453
  function statusKind(node) {
1994
2454
  if (node === undefined)
1995
2455
  return { kind: "empty", text: T("未生成") };
@@ -2513,11 +2973,130 @@ window.__ModuleLoader__.load({
2513
2973
  const { approved, disabled, onToggle, idleText } = props;
2514
2974
  return h(Btn, { on: approved === true, disabled: disabled === true, onClick: onToggle }, approved === true ? T("已通过") : idleText ?? T("通过"));
2515
2975
  }
2516
- // ── 侧栏图标 ─────────────────────────────────────────────────────────
2517
- function StudioGlyph(props) {
2976
+ // ── 侧栏图标(入口按钮 + 快捷菜单)───────────────────────────────────
2977
+ /**
2978
+ * 图标本体。抽出来是因为 `StudioGlyph` 现在还要在旁边挂一个菜单按钮,
2979
+ * 而自检脚本会单独拿这个纯图形做断言。
2980
+ */
2981
+ function StudioGlyphIcon(props) {
2518
2982
  const size = props?.size ?? 18;
2519
2983
  return h("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true" }, h("rect", { x: 3.2, y: 3.2, width: 17.6, height: 17.6, rx: 3, stroke: "currentColor", strokeWidth: 1.6 }), h("rect", { x: 5.6, y: 5.6, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.9 }), h("rect", { x: 10.2, y: 5.6, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.55 }), h("rect", { x: 14.8, y: 5.6, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.9 }), h("rect", { x: 5.6, y: 10.2, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.55 }), h("rect", { x: 10.2, y: 10.2, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.28 }), h("rect", { x: 14.8, y: 10.2, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.55 }), h("rect", { x: 5.6, y: 14.8, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.9 }), h("rect", { x: 10.2, y: 14.8, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.55 }), h("rect", { x: 14.8, y: 14.8, width: 3.6, height: 3.6, rx: 1, fill: "currentColor", opacity: 0.9 }));
2520
2984
  }
2985
+ /** 菜单按钮上的小折角箭头。 */
2986
+ function ChevronGlyph() {
2987
+ return h("svg", { width: 8, height: 8, viewBox: "0 0 8 8", fill: "none", "aria-hidden": "true" }, h("path", { d: "M1.4 2.6 L4 5.4 L6.6 2.6", stroke: "currentColor", strokeWidth: 1.4, strokeLinecap: "round", strokeLinejoin: "round" }));
2988
+ }
2989
+ /**
2990
+ * 侧栏「游戏素材大师」入口。
2991
+ *
2992
+ * 宿主把这一坨渲染在**它自己的 `<button class=…panelRow>` 里面**(见
2993
+ * dsh-client-ui-sidebar 的 `PanelRow`),所以我们没法在旁边加一个平级的
2994
+ * `<button>`——那会变成嵌套按钮。做法是:图标右下角挂一个
2995
+ * `span[role=button]` 的小折角,点击时 `stopPropagation` 掉宿主那一下
2996
+ * (否则会顺带切面板),然后在它旁边弹出功能菜单。
2997
+ *
2998
+ * 菜单用 `position:fixed` 渲染:侧栏面板列本身不裁剪,但祖先里有
2999
+ * `overflow:hidden` 的容器,`absolute` 会在某些窗口布局下被切掉。
3000
+ */
3001
+ function StudioGlyph(props) {
3002
+ const size = props?.size ?? 18;
3003
+ const api = props?.api;
3004
+ const studioCtx = props?.studioCtx;
3005
+ const hidden = useHiddenModules(api);
3006
+ const [open, setOpen] = React.useState(false);
3007
+ const [anchor, setAnchor] = React.useState(null);
3008
+ const rootRef = React.useRef(null);
3009
+ const menuRef = React.useRef(null);
3010
+ const entries = visibleModulesOf(hidden);
3011
+ // 菜单开着时:点外面 / 按 Esc 关掉。监听挂在 document 上,
3012
+ // 用捕获阶段,避免被宿主自己的处理吞掉。
3013
+ React.useEffect(() => {
3014
+ if (!open)
3015
+ return undefined;
3016
+ const onPointerDown = (event) => {
3017
+ const root = rootRef.current;
3018
+ if (root !== null && root !== undefined && typeof root.contains === "function" && root.contains(event.target))
3019
+ return;
3020
+ setOpen(false);
3021
+ };
3022
+ const onKeyDown = (event) => {
3023
+ if (event.key === "Escape")
3024
+ setOpen(false);
3025
+ };
3026
+ document.addEventListener("mousedown", onPointerDown, true);
3027
+ document.addEventListener("keydown", onKeyDown);
3028
+ return () => {
3029
+ document.removeEventListener("mousedown", onPointerDown, true);
3030
+ document.removeEventListener("keydown", onKeyDown);
3031
+ };
3032
+ }, [open]);
3033
+ const toggle = (event) => {
3034
+ // 两下都要拦:宿主 `<button>` 的 onClick 也在这条冒泡路径上。
3035
+ event.preventDefault();
3036
+ event.stopPropagation();
3037
+ if (open) {
3038
+ setOpen(false);
3039
+ return;
3040
+ }
3041
+ const target = event.currentTarget;
3042
+ if (target !== null && target !== undefined && typeof target.getBoundingClientRect === "function") {
3043
+ const rect = target.getBoundingClientRect();
3044
+ setAnchor({ left: rect.right + 8, top: rect.top - 4, bottom: rect.bottom });
3045
+ }
3046
+ else {
3047
+ setAnchor(null);
3048
+ }
3049
+ setOpen(true);
3050
+ };
3051
+ const pick = (key) => {
3052
+ setOpen(false);
3053
+ openStudioIntent(studioCtx, { module: key });
3054
+ };
3055
+ // 菜单从按钮右上角展开;超出视口下沿时整体上移,别让它跑到屏幕外。
3056
+ let menuStyle = { left: 0, top: 0 };
3057
+ if (anchor !== null) {
3058
+ const viewportHeight = typeof window !== "undefined" && Number.isFinite(window.innerHeight) ? window.innerHeight : 0;
3059
+ const estimated = 96 + entries.length * 52;
3060
+ const top = viewportHeight > 0 ? Math.max(8, Math.min(anchor.top, viewportHeight - estimated - 12)) : anchor.top;
3061
+ menuStyle = { left: anchor.left, top };
3062
+ }
3063
+ return h("span", { className: "SPR_railGlyph", ref: rootRef }, h(StudioGlyphIcon, { size }), h("span", {
3064
+ className: "SPR_railMenuBtn",
3065
+ role: "button",
3066
+ tabIndex: 0,
3067
+ "aria-haspopup": "menu",
3068
+ "aria-expanded": open ? "true" : "false",
3069
+ "aria-label": T("功能菜单"),
3070
+ title: T("功能菜单"),
3071
+ "data-testid": "gmm-rail-menu-btn",
3072
+ onClick: toggle,
3073
+ onKeyDown: (event) => {
3074
+ if (event.key === "Enter" || event.key === " " || event.key === "Spacebar")
3075
+ toggle(event);
3076
+ }
3077
+ }, h(ChevronGlyph, null)), open
3078
+ ? h("div", {
3079
+ className: "SPR_railMenu",
3080
+ role: "menu",
3081
+ ref: menuRef,
3082
+ style: menuStyle,
3083
+ "data-testid": "gmm-rail-menu",
3084
+ onClick: (event) => event.stopPropagation(),
3085
+ onMouseDown: (event) => event.stopPropagation()
3086
+ }, h("div", { className: "SPR_railMenuHead" }, T("快捷进入功能")), entries.length === 0
3087
+ ? h("p", { className: "SPR_railMenuEmpty" }, T("所有功能都已被隐藏,请到「设置 → 游戏素材大师 → 功能管理」里打开至少一个。"))
3088
+ : entries.map((entry) => h("button", {
3089
+ key: entry.key,
3090
+ type: "button",
3091
+ role: "menuitem",
3092
+ className: "SPR_railMenuItem",
3093
+ "data-module": entry.key,
3094
+ onClick: () => pick(entry.key)
3095
+ }, h("span", { className: "SPR_railMenuItemTitle" }, entry.title, entry.experimental === true ? h("span", { className: "SPR_expTag" }, T("实验性")) : null), h("span", { className: "SPR_railMenuItemHint" }, entry.hint))), hidden.length > 0
3096
+ ? h("div", { className: "SPR_railMenuFoot" }, T("已隐藏 {n0} 个功能(设置 → 游戏素材大师 → 功能管理)", { n0: hidden.length }))
3097
+ : null)
3098
+ : null);
3099
+ }
2521
3100
  // ── 主体工作台 ───────────────────────────────────────────────────────
2522
3101
  function StudioPanel(props) {
2523
3102
  const localeTick = useLocaleTick();
@@ -2540,6 +3119,20 @@ window.__ModuleLoader__.load({
2540
3119
  const tasks = usePendingTasks();
2541
3120
  // 深链接意图:会话里点「查看验收」时落到对应模块 / 项目 / 阶段。
2542
3121
  const intent = useStudioIntent();
3122
+ // 功能管理:被隐藏的模块既不在页签里,也不该在别处被切进来(深链接也会被挡)。
3123
+ const hidden = useHiddenModules(api);
3124
+ const visibleModules = visibleModulesOf(hidden);
3125
+ /**
3126
+ * 真正渲染的模块:当前选中项被隐藏(或压根不存在)时落到第一个可见模块。
3127
+ *
3128
+ * 不用等 `useEffect` 把 state 改回来——那样会先渲染一帧隐藏模块,
3129
+ * 深链接进被隐藏的模块时就会闪一下它的界面。
3130
+ */
3131
+ const activeModule = visibleModules.some((entry) => entry.key === module) ? module : visibleModules.length > 0 ? visibleModules[0].key : null;
3132
+ React.useEffect(() => {
3133
+ if (activeModule !== null && activeModule !== module)
3134
+ setModule(activeModule);
3135
+ }, [activeModule, module]);
2543
3136
  React.useEffect(() => {
2544
3137
  if (intent === null)
2545
3138
  return;
@@ -2651,11 +3244,16 @@ window.__ModuleLoader__.load({
2651
3244
  return undefined;
2652
3245
  }
2653
3246
  }, [api, projectId, loadProject]);
2654
- const createProject = () => withApi(async () => {
2655
- const created = await api.createProject({ name: T("角色 {n0}", { n0: new Date().toLocaleString("zh-CN", { hour12: false }) }) });
2656
- await refreshProjects();
2657
- setProjectId(created.projectId);
2658
- }, { notice: T("已创建新项目") });
3247
+ const createProject = async () => {
3248
+ const name = askNewName(T("新项目的名字"), T("角色 {n0}", { n0: new Date().toLocaleString("zh-CN", { hour12: false }) }));
3249
+ if (name === null)
3250
+ return;
3251
+ await withApi(async () => {
3252
+ const created = await api.createProject({ name });
3253
+ await refreshProjects();
3254
+ setProjectId(created.projectId);
3255
+ }, { notice: T("已创建新项目") });
3256
+ };
2659
3257
  const deleteCurrent = async () => {
2660
3258
  if (project === null)
2661
3259
  return;
@@ -2740,15 +3338,20 @@ window.__ModuleLoader__.load({
2740
3338
  }
2741
3339
  const activeStageIndex = STAGES.findIndex((s) => s.key === stage);
2742
3340
  const activeStage = STAGES[activeStageIndex < 0 ? 0 : activeStageIndex];
2743
- return h("div", { className: "SPR_root" }, h("div", { className: "SPR_head" }, h("h2", null, T("游戏素材大师")), h("span", { className: "SPR_headSub" }, T("火山方舟 Seedream 生图 · MiniMax 图生视频 · 本地抠绿幕合成")), h("span", { className: "SPR_spacer" }), module === "sprite"
3341
+ return h("div", { className: "SPR_root" }, h("div", { className: "SPR_head" }, h("h2", null, T("游戏素材大师")), h("span", { className: "SPR_headSub" }, T("火山方舟 Seedream 生图 · MiniMax 图生视频 · 本地抠绿幕合成")), h("span", { className: "SPR_spacer" }), activeModule === "sprite"
2744
3342
  ? h(React.Fragment, null, h(Btn, { onClick: () => void refreshProjects(), disabled: loading }, T("刷新列表")), project !== null ? h(Btn, { onClick: renameCurrent }, T("重命名")) : null, project !== null ? h(Btn, { onClick: deleteCurrent, danger: true }, T("删除项目")) : null, h(Btn, { onClick: createProject, primary: true }, T("新建项目")))
2745
- : null), h("div", { className: "SPR_modules" }, MODULES.map((entry) => h("button", {
3343
+ : null), h("div", { className: "SPR_modules", "data-hidden-count": String(hidden.length) }, visibleModules.map((entry) => h("button", {
2746
3344
  key: entry.key,
2747
3345
  type: "button",
2748
3346
  className: "SPR_module",
2749
- "data-active": module === entry.key ? "true" : "false",
3347
+ "data-module": entry.key,
3348
+ "data-active": activeModule === entry.key ? "true" : "false",
2750
3349
  onClick: () => setModule(entry.key)
2751
- }, h("span", { className: "SPR_moduleTitleRow" }, h("span", { className: "SPR_moduleTitle" }, entry.title), entry.experimental === true ? h("span", { className: "SPR_expTag" }, T("实验性")) : null), h("span", { className: "SPR_moduleHint" }, entry.hint)))), module === "sprite"
3350
+ }, h("span", { className: "SPR_moduleTitleRow" }, h("span", { className: "SPR_moduleTitle" }, entry.title), entry.experimental === true ? h("span", { className: "SPR_expTag" }, T("实验性")) : null), h("span", { className: "SPR_moduleHint" }, entry.hint))), hidden.length > 0
3351
+ ? h("span", { className: "SPR_modulesHiddenNote" }, T("已隐藏 {n0} 个功能(设置 → 游戏素材大师 → 功能管理)", { n0: hidden.length }))
3352
+ : null), activeModule === null
3353
+ ? h("div", { className: "SPR_body" }, h("p", { className: "SPR_empty" }, T("所有功能都已被隐藏。请到「设置 → 游戏素材大师 → 功能管理」里打开至少一个。")))
3354
+ : null, activeModule === "sprite"
2752
3355
  ? h("div", { className: "SPR_body" }, h("div", { className: "SPR_side" }, h("div", { className: "SPR_sideTitle" }, T("项目({n0})", { n0: projects.length })), projects.length === 0
2753
3356
  ? h("p", { className: "SPR_hint" }, T("还没有项目,点右上角「新建项目」开始。"))
2754
3357
  : projects.map((summary) => h("button", {
@@ -2852,13 +3455,17 @@ window.__ModuleLoader__.load({
2852
3455
  event.target.value = "";
2853
3456
  }
2854
3457
  })))), renderLog(project), h("div", { className: "SPR_toolbar" }, h(Btn, { onClick: () => void loadProject(project.id) }, T("刷新状态")), h(Btn, { onClick: () => void withApi(() => api.revealProject({ projectId: project.id })) }, T("在访达中打开项目目录"))))))
2855
- : module === "image"
3458
+ : activeModule === "image"
2856
3459
  ? h(ImageModule, { api })
2857
- : module === "sequence"
3460
+ : activeModule === "sequence"
2858
3461
  ? h(SequenceModule, { api })
2859
- : module === "tile"
3462
+ : activeModule === "tile"
2860
3463
  ? h(TileModule, { api })
2861
- : h(RigModule, { api }));
3464
+ : activeModule === "map"
3465
+ ? h(MapModule, { api })
3466
+ : activeModule === "rig"
3467
+ ? h(RigModule, { api })
3468
+ : null);
2862
3469
  }
2863
3470
  /** 阶段卡片下方的说明文字(阶段①有两种生成方式,各说各的)。 */
2864
3471
  function stageHint(project, stage, activeStage) {
@@ -3999,131 +4606,2186 @@ window.__ModuleLoader__.load({
3999
4606
  hudAtRef.current = now;
4000
4607
  setHud({ compass: COMPASS_OF[pos.dirKey] ?? pos.dirKey, moving });
4001
4608
  }
4002
- };
4003
- rafRef.current = requestAnimationFrame(tick);
4004
- return () => cancelAnimationFrame(rafRef.current);
4005
- }, [sheetUrl, rowKey, cellWidth, cellHeight, frameCount]);
4006
- const handleKey = (down) => (event) => {
4007
- const axis = KEY_AXIS[event.key.toLowerCase()];
4008
- if (axis === undefined)
4609
+ };
4610
+ rafRef.current = requestAnimationFrame(tick);
4611
+ return () => cancelAnimationFrame(rafRef.current);
4612
+ }, [sheetUrl, rowKey, cellWidth, cellHeight, frameCount]);
4613
+ const handleKey = (down) => (event) => {
4614
+ const axis = KEY_AXIS[event.key.toLowerCase()];
4615
+ if (axis === undefined)
4616
+ return;
4617
+ event.preventDefault();
4618
+ keysRef.current[axis] = down;
4619
+ };
4620
+ const reset = () => {
4621
+ posRef.current = { x: STAGE_W / 2, y: STAGE_H - 8, dirKey: "front", frame: 0, acc: 0 };
4622
+ keysRef.current = { up: false, down: false, left: false, right: false };
4623
+ };
4624
+ if (!ready) {
4625
+ return h("p", { className: "SPR_empty" }, T("还没有可播放的整图。先完成第 ④ 步合成,再回到这里用 WASD 走一走。"));
4626
+ }
4627
+ return h(React.Fragment, null, h("div", { className: "SPR_fields" }, h(NumField, {
4628
+ label: T("角色缩放倍率"),
4629
+ value: scale,
4630
+ min: 0.3,
4631
+ max: 4,
4632
+ step: 0.1,
4633
+ onChange: setScale
4634
+ }), h(NumField, {
4635
+ label: T("移动速度(像素/秒)"),
4636
+ value: speed,
4637
+ min: 40,
4638
+ max: 600,
4639
+ step: 10,
4640
+ onChange: setSpeed
4641
+ }), h(NumField, {
4642
+ label: T("播放速度(倍,只影响步频)"),
4643
+ value: animSpeed,
4644
+ min: 0.25,
4645
+ max: 4,
4646
+ step: 0.25,
4647
+ onChange: setAnimSpeed
4648
+ }), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("背景参考网格")), h("select", { className: "SPR_input", value: grid ? "on" : "off", onChange: (event) => setGrid(event.target.value === "on") }, h("option", { value: "on" }, T("显示(更容易看出在移动)")), h("option", { value: "off" }, T("关闭(纯白)"))))), h("div", { className: "SPR_toolbar" }, h(Btn, { onClick: reset }, T("回到中间")), h("span", { className: "SPR_refRow" }, T("当前朝向:{n0}({n1}) · {n2}", { n0: hud.compass, n1: LABEL_OF[posRef.current.dirKey] ?? "", n2: hud.moving ? T("行走中") : T("站立") })), orderStale
4649
+ ? h("span", { className: "SPR_refRow" }, T("· 整图是按旧行序生成的,正在重新合成…"))
4650
+ : null, h("span", { className: "SPR_spacer" }), h("span", { className: "SPR_refRow" }, focused ? T("已获得键盘焦点") : T("点击画面后即可操控"))), h("div", {
4651
+ ref: boxRef,
4652
+ className: "SPR_stage",
4653
+ "data-focused": focused ? "true" : "false",
4654
+ tabIndex: 0,
4655
+ onClick: () => {
4656
+ if (boxRef.current !== null)
4657
+ boxRef.current.focus();
4658
+ },
4659
+ onFocus: () => setFocused(true),
4660
+ onBlur: () => {
4661
+ setFocused(false);
4662
+ keysRef.current = { up: false, down: false, left: false, right: false };
4663
+ },
4664
+ onKeyDown: handleKey(true),
4665
+ onKeyUp: handleKey(false)
4666
+ }, h("canvas", { ref: canvasRef, className: "SPR_canvas", width: STAGE_W, height: STAGE_H }), focused ? null : h("div", { className: "SPR_stageHint" }, T("点击这里,然后用 WASD 或 ↑↓←→ 操控角色")), h(LoadingOverlay, {
4667
+ show: rebuilding || (ready && !sheetLoaded),
4668
+ text: rebuilding ? rebuildingText : T("正在载入整图…")
4669
+ }), h("div", { className: "SPR_hud" }, h("span", { className: "SPR_hudDir" }, hud.compass), h("span", null, hud.moving ? T("行走") : T("站立")))), h("p", { className: "SPR_hint" }, T("方向按屏幕方位映射:按 ↑ 向北走(背对镜头)、↓ 向南走(正对镜头)、← 向西、→ 向东;斜向同时按两个键。"), h("br"), T("「播放速度」只改步频快慢,不影响角色移动速度;「移动速度」只改走得多快,不影响动画帧率。切图用的是整图自己记录的行序,所以改完行序即使还没重新合成,预览也不会取错方向。")));
4670
+ }
4671
+ // ── 公共小工具 ──────────────────────────────────────────────────────
4672
+ /** 把 File 读成不带 data: 前缀的 base64。 */
4673
+ function readFileBase64(file) {
4674
+ return new Promise((resolve, reject) => {
4675
+ const reader = new FileReader();
4676
+ reader.onload = () => {
4677
+ const text = String(reader.result ?? "");
4678
+ resolve(text.slice(text.indexOf(",") + 1));
4679
+ };
4680
+ reader.onerror = () => reject(new Error(T("读取文件失败")));
4681
+ reader.readAsDataURL(file);
4682
+ });
4683
+ }
4684
+ /** 一个「拖进来或点按钮选文件」的上传区。 */
4685
+ function UploadBox({ label, accept, multiple, onFiles, busy }) {
4686
+ const [over, setOver] = React.useState(false);
4687
+ const inputRef = React.useRef(null);
4688
+ const handle = (files) => {
4689
+ const list = Array.from(files ?? []);
4690
+ if (list.length > 0)
4691
+ void onFiles(list);
4692
+ };
4693
+ return h(React.Fragment, null, h("div", {
4694
+ className: "SPR_drop",
4695
+ "data-over": over ? "true" : "false",
4696
+ "data-busy": busy === true ? "true" : undefined,
4697
+ onDragOver: (event) => {
4698
+ event.preventDefault();
4699
+ setOver(true);
4700
+ },
4701
+ onDragLeave: () => setOver(false),
4702
+ onDrop: (event) => {
4703
+ event.preventDefault();
4704
+ setOver(false);
4705
+ handle(event.dataTransfer?.files);
4706
+ }
4707
+ }, busy === true
4708
+ ? h("span", { style: { display: "inline-flex", alignItems: "center", gap: 7, justifyContent: "center" } }, h("span", { className: "SPR_spinSm" }), T("正在上传…"))
4709
+ : label), h("div", { className: "SPR_toolbar" }, h(BusyBtn, { onClick: () => inputRef.current?.click(), busy: busy === true, busyText: T("正在上传…") }, T("选择文件")), h("input", {
4710
+ ref: inputRef,
4711
+ type: "file",
4712
+ accept,
4713
+ multiple: multiple === true,
4714
+ style: { display: "none" },
4715
+ onChange: (event) => {
4716
+ handle(event.target.files);
4717
+ event.target.value = "";
4718
+ }
4719
+ })));
4720
+ }
4721
+ /** 抠像参数表单(三个模块共用同一套字段)。 */
4722
+ function KeyingFields({ draft, onChange }) {
4723
+ return h("div", { className: "SPR_fields" }, h(NumField, { label: T("抠像下限(绿色优势)"), value: draft.keyLow ?? 14, min: 0, max: 255, onChange: (v) => onChange({ keyLow: v }) }), h(NumField, { label: T("抠像上限(绿色优势)"), value: draft.keyHigh ?? 80, min: 1, max: 255, onChange: (v) => onChange({ keyHigh: v }) }), h(NumField, { label: T("去绿溢出 0~1"), value: draft.despill ?? 0.65, min: 0, max: 1, step: 0.05, onChange: (v) => onChange({ despill: v }) }), h(NumField, { label: T("背景分割容差(0 = 只认绿色)"), value: draft.bgTolerance ?? 90, min: 0, max: 160, onChange: (v) => onChange({ bgTolerance: v }) }), h(NumField, { label: T("边缘收缩(px)"), value: draft.edgeShrink ?? 0, min: 0, max: 8, onChange: (v) => onChange({ edgeShrink: v }) }));
4724
+ }
4725
+ /** 一份任务/项目列表(左侧栏)。 */
4726
+ function JobSidebar({ title, items, activeId, onSelect, onCreate, renderMeta }) {
4727
+ return h("div", { className: "SPR_side" }, h("div", { className: "SPR_sideTitle" }, T("{n0}({n1})", { n0: title, n1: items.length })), items.length === 0 ? h("p", { className: "SPR_hint" }, T("还没有内容,点右上角新建一个。")) : null, items.map((item) => h("button", {
4728
+ key: item.id,
4729
+ type: "button",
4730
+ className: "SPR_projItem",
4731
+ "data-active": item.id === activeId ? "true" : "false",
4732
+ onClick: () => onSelect(item.id)
4733
+ }, h("span", { className: "SPR_projName" }, item.name), h("span", { className: "SPR_projMeta" }, renderMeta(item)))), items.length === 0 ? h(Btn, { onClick: onCreate, primary: true }, T("新建")) : null);
4734
+ }
4735
+ // ── 模块六 · 地图编辑器(单屏 · 零术语)────────────────────────────────
4736
+ //
4737
+ // 界面只做一件事:把宿主下发的绘制计划执行出来。
4738
+ // 「哪一格用哪一块、画在哪个像素、动起来是哪几块」全在宿主算好,这里连坐标变换
4739
+ // 都不做,只把计划里的 x / y 交给 canvas。
4740
+ //
4741
+ // 唯一被允许复刻的宿主逻辑是命中测试(下面四个坐标函数),那是鼠标必需;
4742
+ // 宿主真实现见 `src/mapgeom.ts`,自检拿它做黄金对照逐点比对。
4743
+ //
4744
+ // ⚠️ 变体挑选 / 自动连接 / 计划分块 / 绘制顺序**都不在这里**:多写一套口径,
4745
+ // 就是「预览好看、导出位移」的老路。
4746
+ /**
4747
+ * 宿主绘制计划里「一批绘制条目」的字段名。
4748
+ *
4749
+ * 只是个协议字段名(界面上不会出现这个词)。术语黑名单自检按**词边界**判,
4750
+ * 所以这里可以照实写 —— 别为了骗过自检去拼字符串。
4751
+ */
4752
+ const MAP_PLAN_LIST = "chunks";
4753
+ /** 取模到 0..size-1(负数也对):与宿主 `mapgeom` 的环绕口径一致。 */
4754
+ function MAP_wrapIndex(value, size) {
4755
+ if (!(size > 0))
4756
+ return value;
4757
+ const rest = value % size;
4758
+ return rest < 0 ? rest + size : rest;
4759
+ }
4760
+ /** 像素 → 格子。**与宿主 `mapgeom.pointToCell` 同构**(环绕时取模,且恒算在图内)。 */
4761
+ function MAP_pointToCell(layout, x, y) {
4762
+ const c = Math.floor(x / layout.stepX);
4763
+ const r = Math.floor(y / layout.stepY);
4764
+ if (layout.wrap === true) {
4765
+ return { r: MAP_wrapIndex(r, layout.rows), c: MAP_wrapIndex(c, layout.cols), inMap: true };
4766
+ }
4767
+ return { r, c, inMap: r >= 0 && c >= 0 && r < layout.rows && c < layout.cols };
4768
+ }
4769
+ /** 格子锚点 = 单元格底边中点。**与宿主 `mapgeom.cellAnchor` 同构**。 */
4770
+ function MAP_cellAnchor(layout, r, c) {
4771
+ return { x: c * layout.stepX + layout.grid.tileWidth / 2, y: (r + 1) * layout.stepY };
4772
+ }
4773
+ /** 贴图左上角。**与宿主 `mapgeom.cellTopLeft` 同构**。 */
4774
+ function MAP_cellTopLeft(layout, r, c, width, height, anchorX = 0.5, anchorY = 1) {
4775
+ const anchor = MAP_cellAnchor(layout, r, c);
4776
+ return { x: anchor.x - width * anchorX, y: anchor.y - height * anchorY };
4777
+ }
4778
+ /**
4779
+ * 两格之间的直线(拖动补间不能漏格)。
4780
+ * **与宿主 `mapdoc.lineCells` 同构**,黄金对照同样覆盖它。
4781
+ */
4782
+ function MAP_lineCells(r0, c0, r1, c1) {
4783
+ const out = [];
4784
+ let r = Math.round(r0);
4785
+ let c = Math.round(c0);
4786
+ const rEnd = Math.round(r1);
4787
+ const cEnd = Math.round(c1);
4788
+ const dr = Math.abs(rEnd - r);
4789
+ const dc = Math.abs(cEnd - c);
4790
+ const sr = r < rEnd ? 1 : -1;
4791
+ const sc = c < cEnd ? 1 : -1;
4792
+ let err = dr - dc;
4793
+ for (;;) {
4794
+ out.push({ r, c });
4795
+ if (r === rEnd && c === cEnd)
4796
+ break;
4797
+ const e2 = 2 * err;
4798
+ if (e2 > -dc) {
4799
+ err -= dc;
4800
+ r += sr;
4801
+ }
4802
+ if (e2 < dr) {
4803
+ err += dr;
4804
+ c += sc;
4805
+ }
4806
+ if (out.length > 20000)
4807
+ break;
4808
+ }
4809
+ return out;
4810
+ }
4811
+ /**
4812
+ * 工具格的图标:内联 SVG 自绘(形状语义对齐 AsLib)。
4813
+ *
4814
+ * 纯函数、不碰 state:面板重渲染时重建这几个图标,代价可以忽略。
4815
+ */
4816
+ function MapToolIcon(props) {
4817
+ const name = props.name;
4818
+ const box = { viewBox: "0 0 24 24", width: 20, height: 20, "aria-hidden": "true", focusable: "false", fill: "currentColor" };
4819
+ const path = (d, extra) => h("path", { d, ...(extra || {}) });
4820
+ const arrow = "M9 4.6 2.8 10.5 9 16.4v-3.7h4.1a4.4 4.4 0 0 1 0 8.8H7.6v3.2h5.5a7.6 7.6 0 0 0 0-15.2H9V4.6Z";
4821
+ if (name === "undo")
4822
+ return h("svg", box, path(arrow));
4823
+ if (name === "redo")
4824
+ return h("svg", box, h("g", { transform: "translate(24 0) scale(-1 1)" }, path(arrow)));
4825
+ if (name === "pen")
4826
+ return h("svg", box, path("M3.4 20.6l1-4.7L15.6 4.7a2.7 2.7 0 0 1 3.8 3.8L8.1 19.6l-4.7 1Z"));
4827
+ if (name === "eraser") {
4828
+ return h("svg", box, path("M13.4 3.6 4.2 12.8a2.4 2.4 0 0 0 0 3.4l3.6 3.6h6l8.1-8.1a2.4 2.4 0 0 0 0-3.4l-5.1-5.1a2.4 2.4 0 0 0-3.4 0Zm1.2 3.4 4 4-2.6 2.6-4-4 2.6-2.6Z"));
4829
+ }
4830
+ if (name === "bucket") {
4831
+ return h("svg", box, path("M11.2 2.6 3.9 9.9a2.2 2.2 0 0 0 0 3.1l4.7 4.7a2.2 2.2 0 0 0 3.1 0l7.3-7.3-7.8-7.8Z"), path("M19.4 13.6s2.5 3 2.5 4.5a2.5 2.5 0 1 1-5 0c0-1.5 2.5-4.5 2.5-4.5Z"));
4832
+ }
4833
+ if (name === "pipette")
4834
+ return h("svg", box, path("M15.6 3.4 20.6 8.4 18 11 13 6l2.6-2.6Z"), path("M11.9 7.1 3 16v5h5l8.9-8.9-5-5Z"));
4835
+ if (name === "hand") {
4836
+ return h("svg", box, path("M7.6 11V6.4a1.6 1.6 0 0 1 3.2 0V11h1V4.4a1.6 1.6 0 0 1 3.2 0V11h1V6.4a1.6 1.6 0 0 1 3.2 0V14a6.6 6.6 0 0 1-6.6 6.6h-1.1A5.7 5.7 0 0 1 5.4 15v-2.3a1.7 1.7 0 0 1 3-1l-.8-.7Z"));
4837
+ }
4838
+ if (name === "single") {
4839
+ return h("svg", box, path("M3 4h18v5H3z", { fillOpacity: 0.42 }), path("M3 10h18v5H3z"), path("M3 16h18v4H3z", { fillOpacity: 0.42 }));
4840
+ }
4841
+ if (name === "grid")
4842
+ return h("svg", box, path("M8.4 3h2.5v18H8.4zM13.1 3h2.5v18h-2.5zM3 8.4h18v2.5H3zM3 13.1h18v2.5H3z"));
4843
+ if (name === "magic") {
4844
+ return h("svg", box, path("M3.3 20.7 13.1 10.9l-1.9-1.9L1.4 18.8l1.9 1.9Z"), path("M17.6 1.8 19 5.3l3.5 1.4L19 8.1 17.6 11.6 16.2 8.1 12.7 6.7 16.2 5.3 17.6 1.8Z"));
4845
+ }
4846
+ if (name === "settings") {
4847
+ return h("svg", box, h("rect", { x: 3, y: 4.6, width: 18, height: 2.2, rx: 1.1 }), h("rect", { x: 6, y: 2.4, width: 4.4, height: 6.6, rx: 2.2 }), h("rect", { x: 3, y: 10.9, width: 18, height: 2.2, rx: 1.1 }), h("rect", { x: 13.6, y: 8.7, width: 4.4, height: 6.6, rx: 2.2 }), h("rect", { x: 3, y: 17.2, width: 18, height: 2.2, rx: 1.1 }), h("rect", { x: 8.4, y: 15, width: 4.4, height: 6.6, rx: 2.2 }));
4848
+ }
4849
+ if (name === "up")
4850
+ return h("svg", { viewBox: "0 0 10 6", width: 11, height: 7, "aria-hidden": "true", fill: "currentColor" }, path("M5 0 10 6H0z"));
4851
+ if (name === "down")
4852
+ return h("svg", { viewBox: "0 0 10 6", width: 11, height: 7, "aria-hidden": "true", fill: "currentColor" }, path("M0 0h10L5 6z"));
4853
+ return null;
4854
+ }
4855
+ /**
4856
+ * 模块六:单屏零术语地图编辑器。
4857
+ *
4858
+ * 一屏三块:顶栏(项目名 / 素材 / 导出 / 保存状态)、左列(素材调色板 + 12 个工具格)、
4859
+ * 画布。没有步骤条,也没有长说明 —— 名词解释一律贴着控件写一行小字。
4860
+ */
4861
+ function MapModule(props) {
4862
+ useLocaleTick();
4863
+ const api = props.api;
4864
+ // ── 项目与视图 ───────────────────────────────────────────────────────
4865
+ const [projects, setProjects] = React.useState([]);
4866
+ const [view, setView] = React.useState(null);
4867
+ const [notice, setNotice] = React.useState(null);
4868
+ const [openCard, setOpenCard] = React.useState(null);
4869
+ const [menuOpen, setMenuOpen] = React.useState(false);
4870
+ /** 素材卡片里正在看的那一张素材(只有一张时用不到)。 */
4871
+ const [tsIndex, setTsIndex] = React.useState(0);
4872
+ const [busyKey, setBusyKey] = React.useState(null);
4873
+ // ── 画布:缩放 / 平移 / 绘制计划 ──────────────────────────────────────
4874
+ const [zoom, setZoom] = React.useState(1);
4875
+ const [pan, setPan] = React.useState({ x: 0, y: 0 });
4876
+ const [viewport, setViewport] = React.useState({ w: 900, h: 520 });
4877
+ /** 画布尺寸量过一次没有:量之前不发计划请求(否则第一帧按默认尺寸算,白拉一遍)。 */
4878
+ const [measured, setMeasured] = React.useState(false);
4879
+ /** 计划缓存:key → 绘制条目。`have` 直接由它派发。 */
4880
+ const planRef = React.useRef(new Map());
4881
+ const [planOps, setPlanOps] = React.useState(new Map());
4882
+ const [visibleKeys, setVisibleKeys] = React.useState([]);
4883
+ const visibleRef = React.useRef([]);
4884
+ /** 自增一次=「重新问一遍宿主缺哪些块」(补拉用)。 */
4885
+ const [planEpoch, setPlanEpoch] = React.useState(0);
4886
+ const [planMeta, setPlanMeta] = React.useState({ fps: 1, frameCount: 1 });
4887
+ /** 动画速度:null = 跟宿主的 `fps` 走;选了慢 / 中 / 快就是用户指定。 */
4888
+ /**
4889
+ * 「新增素材」对话框的草稿。
4890
+ *
4891
+ * 产品约定:**素材属性在新增这一刻定下来,之后只能删掉重来** —— 所以形态、格子、
4892
+ * 会动吗这些都放进这个对话框,一次定死;列表里不再提供任何修改入口(内置素材更是
4893
+ * 连对话框都进不来)。
4894
+ */
4895
+ const [addDraft, setAddDraft] = React.useState(null);
4896
+ const addFileRef = React.useRef(null);
4897
+ /**
4898
+ * 预览节拍:一笔进行中每隔 ~80ms 自增一次,触发下面那个计划查询带上 `pending` ——
4899
+ * 宿主只**算**这份计划(盖在克隆上),不落盘、不进撤销栈。
4900
+ *
4901
+ * 用户要的是「画的过程中格子要显示出来,但别一边画一边存」:所以显示走预览查询,
4902
+ * 真正的提交仍然只在 `pointerup` / 离开 / 取消时发生一次。
4903
+ */
4904
+ const [previewTick, setPreviewTick] = React.useState(0);
4905
+ /** 预览取回来的块号:这些内容只反映了**当时那一部分 op**,提交后必须重拉。 */
4906
+ const previewKeys = React.useRef(new Set());
4907
+ const previewTimer = React.useRef(null);
4908
+ const [animFps, setAnimFps] = React.useState(null);
4909
+ const [frame, setFrame] = React.useState(0);
4910
+ const [truncated, setTruncated] = React.useState(false);
4911
+ const [planWarnings, setPlanWarnings] = React.useState([]);
4912
+ const [imagesReady, setImagesReady] = React.useState(0);
4913
+ // ── 工具 / 笔刷 / 图层 / 显示开关 ─────────────────────────────────────
4914
+ const [tool, setTool] = React.useState("pen");
4915
+ /** 当前笔刷(图例里的全局序号)。 */
4916
+ const [brush, setBrush] = React.useState(null);
4917
+ /** 多选(供「一键生成」取用)。 */
4918
+ const [multi, setMulti] = React.useState([]);
4919
+ const [layerIndex, setLayerIndex] = React.useState(0);
4920
+ const [single, setSingle] = React.useState(false);
4921
+ const [showGrid, setShowGrid] = React.useState(false);
4922
+ const [hover, setHover] = React.useState(null);
4923
+ // ── 保存状态 / 生成草稿 / 导出 ────────────────────────────────────────
4924
+ const [genKind, setGenKind] = React.useState("random");
4925
+ const [genSeed, setGenSeed] = React.useState(20261005);
4926
+ const [exportScale, setExportScale] = React.useState(1);
4927
+ /**
4928
+ * 导出内容(三个复选框),与宿主的 `formats` 一一对应。
4929
+ *
4930
+ * ⚠️ 这里刻意**只存选择、不执行**:以前是「点哪个按钮就导哪一份」,于是
4931
+ * 「导出图片 PNG」看起来像个被选中的页签、「导出存档 JSON」却是立即执行的动作 ——
4932
+ * 同一行里两个按钮一半是选择一半是提交。现在选择归复选框、执行归唯一的「导出」。
4933
+ */
4934
+ const [exportFormats, setExportFormats] = React.useState({ png: true, json: true, tilesets: false });
4935
+ const imageRefs = React.useRef({});
4936
+ const canvasRef = React.useRef(null);
4937
+ /**
4938
+ * 画布的 ref 回调:顺手挂一个 `{ passive: false }` 的滚轮监听。
4939
+ *
4940
+ * ⚠️ **不能只写 React 的 `onWheel`**:它是被动注册的,在里面 `preventDefault()`
4941
+ * 只会在控制台留一条「Unable to preventDefault inside passive event listener」
4942
+ * 并且**照旧滚动面板** —— 真机上就是「滚轮缩放地图的同时整块面板也在滚」。
4943
+ * 用 ref 回调而不是 `useEffect(..., [])`:空态时画布还不存在,空依赖的 effect
4944
+ * 不会在它后来出现时再跑一次,监听就永远挂不上。
4945
+ */
4946
+ const wheelOff = React.useRef(null);
4947
+ const zoomAtRef = React.useRef(null);
4948
+ const bindCanvas = React.useCallback((node) => {
4949
+ if (typeof wheelOff.current === "function") {
4950
+ wheelOff.current();
4951
+ wheelOff.current = null;
4952
+ }
4953
+ canvasRef.current = node === undefined ? null : node;
4954
+ if (node === null || node === undefined)
4955
+ return;
4956
+ const handler = (event) => {
4957
+ event.preventDefault();
4958
+ const zoom = zoomAtRef.current;
4959
+ if (typeof zoom === "function")
4960
+ zoom(event.clientX, event.clientY, event.deltaY < 0 ? 1.15 : 1 / 1.15);
4961
+ };
4962
+ node.addEventListener("wheel", handler, { passive: false });
4963
+ wheelOff.current = () => node.removeEventListener("wheel", handler);
4964
+ }, []);
4965
+ const stageRef = React.useRef(null);
4966
+ /**
4967
+ * 工具格上方那张小标签(名称 + 介绍 + 快捷键)。
4968
+ *
4969
+ * ⚠️ 位置用 `position:fixed` 而不是 `absolute`:工具栏的祖先里有 `overflow` 容器,
4970
+ * `absolute` 会让「按钮正上方」那一段被裁掉——和侧栏菜单踩的是同一个坑。
4971
+ * 坐标在 hover 时用 `getBoundingClientRect()` 现算,并夹在视口内(第一列的按钮
4972
+ * 居中后左半边会出界)。
4973
+ */
4974
+ const [toolTip, setToolTip] = React.useState(null);
4975
+ /** 当前悬浮的那个按钮(滚动 / 改窗口大小时靠它把标签重新锚回去)。 */
4976
+ const toolTipAnchor = React.useRef(null);
4977
+ /** 横向夹在视口内:半宽上限 = CSS max-width 236 + 内边距,防止第一列按钮的标签出界。 */
4978
+ const toolTipX = (rect) => {
4979
+ const half = 124;
4980
+ const viewWidth = typeof window === "undefined" ? 0 : window.innerWidth || 0;
4981
+ const center = rect.left + rect.width / 2;
4982
+ return Math.round(viewWidth > 0 ? Math.max(half, Math.min(center, viewWidth - half)) : center);
4983
+ };
4984
+ const showToolTip = (name, desc, shortcut) => (event) => {
4985
+ const node = event === undefined ? null : event.currentTarget;
4986
+ if (node === null || node === undefined || typeof node.getBoundingClientRect !== "function")
4987
+ return;
4988
+ toolTipAnchor.current = node;
4989
+ const rect = node.getBoundingClientRect();
4990
+ setToolTip({
4991
+ name,
4992
+ desc,
4993
+ shortcut: shortcut === undefined ? null : shortcut,
4994
+ x: toolTipX(rect),
4995
+ y: Math.round(rect.top - 8)
4996
+ });
4997
+ };
4998
+ const hideToolTip = () => {
4999
+ toolTipAnchor.current = null;
5000
+ setToolTip((current) => (current === null ? current : null));
5001
+ };
5002
+ /**
5003
+ * 滚动 / 改窗口大小时**把标签重新锚回按钮**,而不是直接收起来。
5004
+ *
5005
+ * 收起看着更省事,但真机上很难受:面板一滚(或窗口一缩)标签就没了,而鼠标还停在
5006
+ * 按钮上、`mouseenter` 不会再触发,用户得先把鼠标移开再挪回来才重新看到说明。
5007
+ * 依赖只取「有没有标签」这个布尔量:依赖 `toolTip` 本身的话,每次重新定位都会
5008
+ * 重新挂监听。
5009
+ */
5010
+ React.useEffect(() => {
5011
+ if (toolTip === null || typeof window === "undefined" || typeof window.addEventListener !== "function")
5012
+ return undefined;
5013
+ const reanchor = () => {
5014
+ const node = toolTipAnchor.current;
5015
+ if (node === null || node === undefined || typeof node.getBoundingClientRect !== "function" || node.isConnected === false) {
5016
+ hideToolTip();
5017
+ return;
5018
+ }
5019
+ const rect = node.getBoundingClientRect();
5020
+ setToolTip((current) => (current === null ? current : { ...current, x: toolTipX(rect), y: Math.round(rect.top - 8) }));
5021
+ };
5022
+ window.addEventListener("scroll", reanchor, true);
5023
+ window.addEventListener("resize", reanchor);
5024
+ return () => {
5025
+ window.removeEventListener("scroll", reanchor, true);
5026
+ window.removeEventListener("resize", reanchor);
5027
+ };
5028
+ }, [toolTip === null]);
5029
+ const fileRef = React.useRef(null);
5030
+ const pointersRef = React.useRef(new Map());
5031
+ const strokeRef = React.useRef(null);
5032
+ const strokeSeq = React.useRef(0);
5033
+ const currentStroke = React.useRef(null);
5034
+ const flushTimer = React.useRef(null);
5035
+ const pendingOps = React.useRef([]);
5036
+ const fittedRef = React.useRef(null);
5037
+ const spaceRef = React.useRef(false);
5038
+ const intent = useStudioIntent();
5039
+ /**
5040
+ * 实验性进入提示。
5041
+ *
5042
+ * ⚠️ Hook 必须在**任何提前 return 之前**:下面 `view === null` 那条早返回
5043
+ * 会绕过它,顺序一变就是 React error #310,整块白屏。
5044
+ */
5045
+ const [gateOpen, setGateOpen] = React.useState(experimentalGateMuted.map !== true);
5046
+ const closeGate = React.useCallback(() => setGateOpen(false), []);
5047
+ const viewId = view === null ? null : view.id;
5048
+ const layers = view === null ? [] : view.layers || [];
5049
+ const safeLayerIndex = layers.length === 0 ? 0 : Math.min(Math.max(0, layerIndex), layers.length - 1);
5050
+ const activeLayer = layers.length === 0 ? null : layers[safeLayerIndex];
5051
+ const tilesets = view === null ? [] : view.tilesets || [];
5052
+ const safeTsIndex = tilesets.length === 0 ? 0 : Math.min(Math.max(0, tsIndex), tilesets.length - 1);
5053
+ const tileset = tilesets.length === 0 ? null : tilesets[safeTsIndex];
5054
+ const legend = view === null ? [] : view.legend || [];
5055
+ const assetBase = view === null ? "" : view.assetBase;
5056
+ const exportFiles = view === null ? [] : view.exportFiles || [];
5057
+ /** 与宿主 `layoutOf` 同形的一份布局:坐标函数要用它的步长与环绕开关。 */
5058
+ const layout = React.useMemo(() => {
5059
+ if (view === null)
5060
+ return null;
5061
+ const grid = view.grid;
5062
+ const cols = view.cols;
5063
+ const rows = view.rows;
5064
+ return {
5065
+ grid,
5066
+ cols,
5067
+ rows,
5068
+ stepX: grid.tileWidth,
5069
+ stepY: grid.tileHeight,
5070
+ width: cols * grid.tileWidth,
5071
+ height: rows * grid.tileHeight,
5072
+ wrap: grid.wrap === true
5073
+ };
5074
+ }, [view]);
5075
+ /** 图例:全局序号 → { 素材, 源矩形 }。 */
5076
+ const legendMap = React.useMemo(() => {
5077
+ const map = new Map();
5078
+ for (const entry of legend)
5079
+ map.set(entry.index, entry);
5080
+ return map;
5081
+ }, [legend]);
5082
+ const tilesetReason = tileset === null ? "" : tileset.reason || "";
5083
+ const activeFps = animFps === null ? (planMeta.fps > 0 ? planMeta.fps : 1) : animFps;
5084
+ /** 当前缩放 / 平移的最新值:捏合与滚轮要在同一次事件里读到,不能靠 state。 */
5085
+ const zoomRef = React.useRef(zoom);
5086
+ zoomRef.current = zoom;
5087
+ const panRef = React.useRef(pan);
5088
+ panRef.current = pan;
5089
+ const viewportRef = React.useRef(viewport);
5090
+ viewportRef.current = viewport;
5091
+ const withApi = React.useCallback(async (fn, options) => {
5092
+ if (api === undefined) {
5093
+ setNotice({ kind: "error", text: T("远程服务尚未挂载完成,请稍候再试") });
5094
+ return undefined;
5095
+ }
5096
+ try {
5097
+ const value = await fn();
5098
+ if (options !== undefined && options.notice !== undefined)
5099
+ setNotice({ kind: "info", text: options.notice });
5100
+ return value;
5101
+ }
5102
+ catch (error) {
5103
+ setNotice({ kind: "error", text: msg(error) });
5104
+ return undefined;
5105
+ }
5106
+ }, [api]);
5107
+ /**
5108
+ * 每个缓存条目是**按哪次请求的视口**取回来的(键 → 视口矩形)。
5109
+ *
5110
+ * ⚠️ 宿主回的是「覆盖这个视口的那批条目」,所以一个键的内容取决于当时问的
5111
+ * 视口大小。只按 key 判断「我有没有」会让**视口变大后新露出来的格子一直空着**
5112
+ * (键还在缓存里,宿主就不重发了 —— 实测踩过)。这里只比较**客户端自己发出去的
5113
+ * 两个矩形**,不碰任何格 / 块的可见范围计算。
5114
+ */
5115
+ const fetchedRef = React.useRef(new Map());
5116
+ /**
5117
+ * 「内容可能已经过期、正等着重拉」的那几个块。
5118
+ *
5119
+ * ⚠️ 这里**故意不把 key 从 `planRef` 里删掉**。删掉的话,从「提交完」到「增量计划
5120
+ * 回来」之间这段时间里这一块是**没有内容的** —— 画布会整块变空再变回来。
5121
+ * 一块可能覆盖很大一片(块边长见 `mapgeom.MAP_CHUNK_SIZE`;地图不比块大多少时
5122
+ * 一块就是整张地图),于是拖动笔刷期间每 40ms 就闪一次,真机表现就是「画布一直闪烁」。
5123
+ * 现在改成:旧内容继续画,只是**不再向宿主声明「我有」**(`have` 里剔掉),
5124
+ * 于是宿主会把新内容重发一次,`applyQuery` 收到后把这个 key 移出集合。
5125
+ */
5126
+ const staleRef = React.useRef(new Set());
5127
+ /** 换项目 / 换层 / 大改之后:把计划整份作废(下次渲染重新问宿主)。 */
5128
+ const clearPlan = React.useCallback(() => {
5129
+ planRef.current = new Map();
5130
+ fetchedRef.current = new Map();
5131
+ staleRef.current = new Set();
5132
+ visibleRef.current = [];
5133
+ setPlanOps(new Map());
5134
+ setVisibleKeys([]);
5135
+ }, []);
5136
+ /**
5137
+ * 读一次项目视图。
5138
+ *
5139
+ * `keep` = 保留画布上的选择(图层 / 面板 / 缩放):验收打勾、导出回读这类
5140
+ * 「只是刷新一下状态」的调用不该把用户正在画的层顶掉。
5141
+ */
5142
+ const loadSeq = React.useRef(0);
5143
+ const loadProject = React.useCallback(async (id, keep) => {
5144
+ if (api === undefined || id === null || id === undefined || id === "")
5145
+ return;
5146
+ /**
5147
+ * ⚠️ 并发读盘要**按最后一次发起的请求收口**(丢弃迟到的旧响应)。
5148
+ *
5149
+ * 同一个项目可能同时在读好几次(挂载时那次、点导出后那次、`busy` 期间的 1.5s 轮询、
5150
+ * 打勾后的回读)。它们各自 await 一次读盘,**回来的顺序不保证与发出的一致** ——
5151
+ * 迟到的旧响应会把新状态顶回去。真机上的表现是「导出完了、文件也在盘上,
5152
+ * 但导出卡片一直写着『还没有导出过』」,而且重新点一次才好 —— 查起来像随机。
5153
+ */
5154
+ const seq = ++loadSeq.current;
5155
+ try {
5156
+ const next = await api.getMapProject({ projectId: id, lang: activeLang() });
5157
+ if (seq !== loadSeq.current)
5158
+ return;
5159
+ if (keep !== true) {
5160
+ clearPlan();
5161
+ setLayerIndex(0);
5162
+ setTsIndex(0);
5163
+ setPlanMeta({ fps: 1, frameCount: 1 });
5164
+ setAnimFps(null);
5165
+ setTruncated(false);
5166
+ setPlanWarnings([]);
5167
+ }
5168
+ setView(next);
5169
+ }
5170
+ catch (error) {
5171
+ setNotice({ kind: "error", text: msg(error) });
5172
+ }
5173
+ }, [api, clearPlan]);
5174
+ React.useEffect(() => {
5175
+ void (async () => {
5176
+ if (api === undefined)
5177
+ return;
5178
+ try {
5179
+ const result = await api.listMapProjects();
5180
+ const list = result.projects || [];
5181
+ setProjects(list);
5182
+ if (list.length > 0)
5183
+ await loadProject(list[0].id);
5184
+ }
5185
+ catch (error) {
5186
+ setNotice({ kind: "error", text: msg(error) });
5187
+ }
5188
+ })();
5189
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5190
+ }, [api]);
5191
+ // 深链接:`?dsh-gmm=1&module=map&job=<项目 id>&stage=assets|rules|paint|export`
5192
+ React.useEffect(() => {
5193
+ if (intent === null || intent.module !== "map")
5194
+ return;
5195
+ const id = typeof intent.jobId === "string" && intent.jobId !== "" ? intent.jobId : intent.projectId;
5196
+ if (typeof id === "string" && id !== "")
5197
+ void loadProject(id);
5198
+ if (intent.stage === "assets")
5199
+ setOpenCard("assets");
5200
+ else if (intent.stage === "export")
5201
+ setOpenCard("export");
5202
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5203
+ }, [intent]);
5204
+ // ── 绘制计划:什么时候问、怎么合并 ───────────────────────────────────
5205
+ const applyQuery = React.useCallback((result, view) => {
5206
+ const incoming = Array.isArray(result?.[MAP_PLAN_LIST]) ? result[MAP_PLAN_LIST] : [];
5207
+ const next = new Map(planRef.current);
5208
+ const previewing = currentStroke.current !== null && pendingOps.current.length > 0;
5209
+ for (const entry of incoming) {
5210
+ next.set(entry.key, Array.isArray(entry.ops) ? entry.ops : []);
5211
+ // 预览期间取回来的块:内容只反映「当时那一部分 op」,提交后要按真实数据重拉
5212
+ if (previewing)
5213
+ previewKeys.current.add(entry.key);
5214
+ // 这一份已经是新的了:不用再重拉
5215
+ staleRef.current.delete(entry.key);
5216
+ // 记下这一份是「按哪个视口」取回来的:视口再变大时它就不够画了
5217
+ if (view !== undefined)
5218
+ fetchedRef.current.set(entry.key, view);
5219
+ }
5220
+ const keys = Array.isArray(result?.visibleKeys) ? result.visibleKeys : [];
5221
+ /** 缓存上限:先丢「已经不在可见范围里」的键,免得看久了内存无限涨。 */
5222
+ if (next.size > 384) {
5223
+ const keep = new Set(keys);
5224
+ for (const key of [...next.keys()]) {
5225
+ if (next.size <= 256)
5226
+ break;
5227
+ if (!keep.has(key))
5228
+ next.delete(key);
5229
+ }
5230
+ }
5231
+ planRef.current = next;
5232
+ visibleRef.current = keys;
5233
+ setPlanOps(next);
5234
+ setVisibleKeys(keys);
5235
+ const fps = Number(result?.fps);
5236
+ const frames = Number(result?.frameCount);
5237
+ setPlanMeta({
5238
+ fps: Number.isFinite(fps) && fps > 0 ? fps : 1,
5239
+ frameCount: Number.isFinite(frames) && frames > 1 ? Math.floor(frames) : 1
5240
+ });
5241
+ setTruncated(result?.truncated === true);
5242
+ setPlanWarnings(Array.isArray(result?.warnings) ? result.warnings : []);
5243
+ }, []);
5244
+ /** 计划的「身份」:这张图变了(换项目 / 换层 / 换网格 / 换尺寸)就整份重来。 */
5245
+ const planKey = viewId === null || layout === null
5246
+ ? null
5247
+ : `${viewId}|${single === true ? safeLayerIndex : "all"}|${layout.wrap === true ? "w" : "n"}|${layout.stepX}x${layout.stepY}|${layout.cols}x${layout.rows}`;
5248
+ // 身份变了 → 旧计划一律作废(不同层的块里条目本来就不同)
5249
+ const planKeyRef = React.useRef(null);
5250
+ React.useEffect(() => {
5251
+ if (planKeyRef.current === planKey)
5252
+ return;
5253
+ planKeyRef.current = planKey;
5254
+ if (planKey === null)
5255
+ return;
5256
+ clearPlan();
5257
+ setPlanEpoch((value) => value + 1);
5258
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5259
+ }, [planKey]);
5260
+ /** 外框矩形是否盖住内框(只用来判断「这一份计划还够不够画当前视口」)。 */
5261
+ const viewCovers = (outer, inner) => outer.x <= inner.x && outer.y <= inner.y && outer.x + outer.width >= inner.x + inner.width && outer.y + outer.height >= inner.y + inner.height;
5262
+ React.useEffect(() => {
5263
+ if (api === undefined || viewId === null || layout === null || measured !== true)
5264
+ return undefined;
5265
+ let cancelled = false;
5266
+ const timer = setTimeout(() => {
5267
+ void (async () => {
5268
+ const strokeAtQuery = currentStroke.current;
5269
+ try {
5270
+ const size = viewportRef.current;
5271
+ const currentView = { x: pan.x, y: pan.y, width: size.w / zoom, height: size.h / zoom };
5272
+ const pending = currentStroke.current === null ? undefined : [...pendingOps.current];
5273
+ /**
5274
+ * ⚠️ **预览查询一律不带 `have`**(说自己什么都没有)。
5275
+ *
5276
+ * 真机踩过:预览改的格子往往落在**已经缓存过的块**里,宿主一看「你有这一块」
5277
+ * 就不回传 —— 于是拖动期间一片空白,松手提交后靠 `dropKeys` 重拉才出现。
5278
+ * 客户端又不许自己算「这一笔碰到哪些块」(那是宿主的几何),所以预览时
5279
+ * 干脆要一整份可视块:多传几十块,换「拖着就能看见」,值。
5280
+ * (宿主那边另有强制回传,见 `mapgen.mapPlan` 的 `forced`。)
5281
+ */
5282
+ const have = pending !== undefined ? [] : [...planRef.current.keys()].filter((key) => {
5283
+ // 待重拉的键不算「我有」:宿主据此把新内容发回来
5284
+ if (staleRef.current.has(key))
5285
+ return false;
5286
+ // 预览块同理:它只反映「当时那一部分 op」,这一笔还在长,必须重新算
5287
+ if (previewKeys.current.has(key))
5288
+ return false;
5289
+ const fetched = fetchedRef.current.get(key);
5290
+ return fetched !== undefined && viewCovers(fetched, currentView);
5291
+ });
5292
+ const result = await api.mapPlan({
5293
+ projectId: viewId,
5294
+ view: currentView,
5295
+ have,
5296
+ pending: Array.isArray(pending) && pending.length > 0 ? pending : undefined,
5297
+ layerIds: single === true ? [safeLayerIndex] : undefined
5298
+ });
5299
+ if (cancelled === true)
5300
+ return;
5301
+ /**
5302
+ * 预览响应回来时这一笔可能已经提交(或换了):它算的是**过时**的那部分 op,
5303
+ * 应用它会让缓存停在预览上(提交后的真实数据就补不进来了)。直接丢掉,
5304
+ * 交给提交后那次查询重发这几块。
5305
+ */
5306
+ if (strokeAtQuery !== null && strokeAtQuery !== currentStroke.current)
5307
+ return;
5308
+ applyQuery(result, currentView);
5309
+ }
5310
+ catch (error) {
5311
+ if (cancelled === true)
5312
+ return;
5313
+ setNotice({ kind: "error", text: msg(error) });
5314
+ }
5315
+ })();
5316
+ }, 32);
5317
+ return () => {
5318
+ cancelled = true;
5319
+ clearTimeout(timer);
5320
+ };
5321
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5322
+ }, [api, viewId, planKey, planEpoch, previewTick, pan, zoom, viewport, single, safeLayerIndex, measured]);
5323
+ // 视图尺寸变了(面板宽窄、窗口缩放):重新量一次
5324
+ React.useEffect(() => {
5325
+ const element = stageRef.current;
5326
+ if (element === null || element === undefined)
5327
+ return undefined;
5328
+ const measure = () => {
5329
+ const rect = element.getBoundingClientRect();
5330
+ setViewport({ w: Math.max(160, Math.round(rect.width)), h: Math.max(120, Math.round(rect.height)) });
5331
+ setMeasured(true);
5332
+ };
5333
+ measure();
5334
+ if (typeof ResizeObserver !== "function")
5335
+ return undefined;
5336
+ const observer = new ResizeObserver(measure);
5337
+ observer.observe(element);
5338
+ return () => observer.disconnect();
5339
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5340
+ }, [viewId]);
5341
+ // 换项目 / 改尺寸后把整张地图摆回视野中央(用户自己平移过就不再动)
5342
+ React.useEffect(() => {
5343
+ if (view === null || layout === null)
5344
+ return;
5345
+ const key = `${view.id}:${layout.cols}x${layout.rows}:${layout.stepX}`;
5346
+ if (fittedRef.current === key)
5347
+ return;
5348
+ fittedRef.current = key;
5349
+ const scale = Math.min(1, viewport.w / Math.max(1, layout.width), viewport.h / Math.max(1, layout.height));
5350
+ const next = Math.min(8, Math.max(0.25, Number.isFinite(scale) && scale > 0 ? scale : 1));
5351
+ setZoom(next);
5352
+ // 摆回视野:地图比视口小的方向会被夹到 0(左上角对齐),大的方向居中
5353
+ setPan(clampPan({ x: (layout.width - viewport.w / next) / 2, y: (layout.height - viewport.h / next) / 2 }));
5354
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5355
+ }, [viewId, layout === null ? "" : `${layout.cols}x${layout.rows}x${layout.stepX}`, viewport.w, viewport.h]);
5356
+ // ── 画布绘制 ─────────────────────────────────────────────────────────
5357
+ const draw = React.useCallback(() => {
5358
+ const canvas = canvasRef.current;
5359
+ if (canvas === null || canvas === undefined || layout === null)
5360
+ return;
5361
+ const ctx = canvas.getContext("2d");
5362
+ if (ctx === null || ctx === undefined)
5363
+ return;
5364
+ const width = Math.max(1, Math.round(viewport.w));
5365
+ const height = Math.max(1, Math.round(viewport.h));
5366
+ /**
5367
+ * 按 devicePixelRatio 放大 backing store。
5368
+ *
5369
+ * 不放大时每个地图像素只占 1 个物理像素 → 像素画在 Retina 上发糊。
5370
+ * 坐标仍按 CSS 像素记,倍率进 transform,所以计划里的目标坐标一个都不用改。
5371
+ */
5372
+ const dpr = Math.max(1, Math.min(3, (typeof window !== "undefined" && window.devicePixelRatio) || 1));
5373
+ const backingWidth = Math.round(width * dpr);
5374
+ const backingHeight = Math.round(height * dpr);
5375
+ if (canvas.width !== backingWidth)
5376
+ canvas.width = backingWidth;
5377
+ if (canvas.height !== backingHeight)
5378
+ canvas.height = backingHeight;
5379
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
5380
+ ctx.clearRect(0, 0, backingWidth, backingHeight);
5381
+ ctx.imageSmoothingEnabled = false;
5382
+ const scale = zoom * dpr;
5383
+ ctx.setTransform(scale, 0, 0, scale, -pan.x * scale, -pan.y * scale);
5384
+ // 单层预览:底铺绿。层过滤由宿主的计划做,这里一条条目都不筛。
5385
+ if (single === true) {
5386
+ ctx.fillStyle = "rgb(56,170,68)";
5387
+ ctx.fillRect(pan.x, pan.y, width / zoom, height / zoom);
5388
+ }
5389
+ const debug = typeof window !== "undefined" && window.__mapDebug === true;
5390
+ const stats = debug ? { keys: [], cached: 0, drawn: 0, noLegend: 0, noImage: 0, first: null, frame: 0 } : null;
5391
+ for (const key of visibleRef.current) {
5392
+ if (stats !== null)
5393
+ stats.keys.push(key);
5394
+ const ops = planOps.get(key);
5395
+ if (ops === undefined)
5396
+ continue;
5397
+ if (stats !== null)
5398
+ stats.cached += ops.length;
5399
+ for (const op of ops) {
5400
+ const index = op.cycle === undefined || op.cycle.length === 0 ? op.t : op.cycle[frame % op.cycle.length];
5401
+ const entry = legendMap.get(index);
5402
+ if (entry === undefined) {
5403
+ if (stats !== null)
5404
+ stats.noLegend++;
5405
+ continue;
5406
+ }
5407
+ const image = imageRefs.current[entry.tilesetId];
5408
+ if (image === undefined || image === null) {
5409
+ if (stats !== null)
5410
+ stats.noImage++;
5411
+ continue;
5412
+ }
5413
+ if (stats !== null) {
5414
+ stats.drawn++;
5415
+ if (stats.first === null)
5416
+ stats.first = { t: index, x: op.x, y: op.y, ts: entry.tilesetId };
5417
+ }
5418
+ ctx.globalAlpha = op.a === undefined ? 1 : op.a;
5419
+ ctx.drawImage(image, entry.rect.x, entry.rect.y, entry.rect.width, entry.rect.height, op.x, op.y, entry.rect.width, entry.rect.height);
5420
+ }
5421
+ }
5422
+ ctx.globalAlpha = 1;
5423
+ // 网格线:只是对位用的装饰,不参与任何绘制计划
5424
+ if (showGrid === true) {
5425
+ const stepX = layout.grid.tileWidth;
5426
+ const stepY = layout.grid.tileHeight;
5427
+ const thin = 1 / zoom;
5428
+ ctx.fillStyle = "rgba(255,255,255,0.22)";
5429
+ const right = pan.x + width / zoom;
5430
+ const bottom = pan.y + height / zoom;
5431
+ let count = 0;
5432
+ for (let x = Math.floor(pan.x / stepX) * stepX; x <= right && count < 800; x += stepX) {
5433
+ ctx.fillRect(x, pan.y, thin, height / zoom);
5434
+ count++;
5435
+ }
5436
+ for (let y = Math.floor(pan.y / stepY) * stepY; y <= bottom && count < 1600; y += stepY) {
5437
+ ctx.fillRect(pan.x, y, width / zoom, thin);
5438
+ count++;
5439
+ }
5440
+ }
5441
+ // 悬停格:2px 红框(四条细矩形,不用 stroke,免得被 DPR 影响粗细)
5442
+ // ⚠️ 用**未取模**的坐标定位:环绕时同一格在屏幕上有多份,红框必须画在指针
5443
+ // 所在的那一份上。拿取模后的 r/c 去算,指针在地图外那一份时红框会跳一整张地图。
5444
+ if (hover !== null && hover !== undefined) {
5445
+ const rawC = Math.floor(hover.x / layout.stepX);
5446
+ const rawR = Math.floor(hover.y / layout.stepY);
5447
+ const topLeft = MAP_cellTopLeft(layout, rawR, rawC, layout.grid.tileWidth, layout.grid.tileHeight);
5448
+ const thickness = 2 / zoom;
5449
+ const w = layout.grid.tileWidth;
5450
+ const hh = layout.grid.tileHeight;
5451
+ ctx.fillStyle = "#e23b2b";
5452
+ ctx.fillRect(topLeft.x, topLeft.y, w, thickness);
5453
+ ctx.fillRect(topLeft.x, topLeft.y + hh - thickness, w, thickness);
5454
+ ctx.fillRect(topLeft.x, topLeft.y + thickness, thickness, hh - thickness * 2);
5455
+ ctx.fillRect(topLeft.x + w - thickness, topLeft.y + thickness, thickness, hh - thickness * 2);
5456
+ }
5457
+ if (stats !== null && typeof window !== "undefined") {
5458
+ stats.frame = frame;
5459
+ window.__mapDrawStats = stats;
5460
+ /**
5461
+ * 顺手把**当前相机**暴露出来(同样只在 `__mapDebug` 打开时)。
5462
+ *
5463
+ * 自检里要按格坐标去点画布,而「格 → 客户端像素」必须用**此刻**的 pan/zoom;
5464
+ * 靠「最近一次计划查询的 view」推会读到过期的相机(切项目 / 自适应缩放之后),
5465
+ * 于是点到了地图外、断言莫名其妙地失败。就摆在绘制里,永远不会过期。
5466
+ */
5467
+ window.__mapCamera = { pan: { x: pan.x, y: pan.y }, zoom, viewport: { w: viewport.w, h: viewport.h } };
5468
+ }
5469
+ }, [layout, viewport, zoom, pan, planOps, legend, legendMap, single, showGrid, hover, frame]);
5470
+ React.useEffect(() => {
5471
+ draw();
5472
+ }, [draw, imagesReady]);
5473
+ /** 停帧条件:系统开了「减少动态效果」或页面被切到后台 → 永远停在第一帧。 */
5474
+ const stillFrame = (typeof window !== "undefined" &&
5475
+ typeof window.matchMedia === "function" &&
5476
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches === true) ||
5477
+ (typeof document !== "undefined" && document !== null && document.hidden === true);
5478
+ React.useEffect(() => {
5479
+ if (stillFrame === true || planMeta.frameCount <= 1) {
5480
+ setFrame(0);
5481
+ return undefined;
5482
+ }
5483
+ if (typeof window === "undefined" || typeof window.requestAnimationFrame !== "function")
5484
+ return undefined;
5485
+ const started = Date.now();
5486
+ let handle = 0;
5487
+ const tick = () => {
5488
+ const elapsed = (Date.now() - started) / 1000;
5489
+ setFrame(Math.floor(elapsed * activeFps) % planMeta.frameCount);
5490
+ handle = window.requestAnimationFrame(tick);
5491
+ };
5492
+ handle = window.requestAnimationFrame(tick);
5493
+ return () => window.cancelAnimationFrame(handle);
5494
+ }, [stillFrame, planMeta.frameCount, activeFps]);
5495
+ // ── 编辑:op 批量提交 ────────────────────────────────────────────────
5496
+ const applyResult = React.useCallback((result) => {
5497
+ if (result === undefined || result === null)
5498
+ return;
5499
+ const drop = Array.isArray(result.dropKeys) ? result.dropKeys : [];
5500
+ // 只标记「待重拉」,**不删缓存**:删除会让这一块在重拉回来之前没有内容,
5501
+ // 拖动时就是整块闪一下(详见 staleRef 的注释)。画面本身不用重画。
5502
+ for (const key of drop)
5503
+ staleRef.current.add(key);
5504
+ setView((prev) => (prev === null ? prev : { ...prev, canUndo: result.canUndo === true, canRedo: result.canRedo === true }));
5505
+ if (Array.isArray(result.skipped) && result.skipped.length > 0) {
5506
+ setNotice({ kind: "error", text: result.skipped.slice(0, 2).join(";") });
5507
+ }
5508
+ setPlanEpoch((value) => value + 1);
5509
+ }, []);
5510
+ const flushOps = React.useCallback(async () => {
5511
+ if (flushTimer.current !== null) {
5512
+ clearTimeout(flushTimer.current);
5513
+ flushTimer.current = null;
5514
+ }
5515
+ if (previewTimer.current !== null) {
5516
+ clearTimeout(previewTimer.current);
5517
+ previewTimer.current = null;
5518
+ }
5519
+ /**
5520
+ * 这一笔要真正提交了:先把它期间预览出来的块标成「待重拉」——
5521
+ * 那些内容是按**当时那一部分 op** 算的,最后几个格子可能还没进去。
5522
+ * 标记之后宿主会按真实数据把这几块重发一遍,画面不会停在预览上。
5523
+ */
5524
+ for (const key of previewKeys.current)
5525
+ staleRef.current.add(key);
5526
+ previewKeys.current = new Set();
5527
+ const ops = pendingOps.current;
5528
+ if (ops.length === 0)
5529
+ return;
5530
+ if (api === undefined || viewId === null) {
5531
+ // ⚠️ 这里**必须**把队列清掉再返回:服务还没挂上 / 项目已被切换时提交不了,
5532
+ // 留下的话它们会带着**上一笔的 stroke** 等到下一次 flush,被
5533
+ // `stroke: ops[0]?.stroke` 整批盖成一个 id —— 两笔不同的涂抹会被并成
5534
+ // 一条撤销;项目已删除时还会往旧 viewId 提交。
5535
+ pendingOps.current = [];
5536
+ return;
5537
+ }
5538
+ pendingOps.current = [];
5539
+ try {
5540
+ const result = await api.applyMapOps({ projectId: viewId, ops, stroke: ops[0]?.stroke, have: [...planRef.current.keys()] });
5541
+ applyResult(result);
5542
+ }
5543
+ catch (error) {
5544
+ setNotice({ kind: "error", text: msg(error) });
5545
+ }
5546
+ finally {
5547
+ }
5548
+ }, [api, viewId, applyResult]);
5549
+ /**
5550
+ * 把相机**夹在地图里**:地图比视口大的方向可以滚(`视口-地图 .. 0`),
5551
+ * 比视口小的方向钉在 0 —— 也就是「地图左上角贴着画布左上角」。
5552
+ *
5553
+ * ⚠️ 真机反馈两条都出在这里:拖到右下角时地图会「复位」、而且复位后左上角对不齐,
5554
+ * 于是「靠拖动很难把地图拖到左上角」。环绕地图上相机本来可以无限拖,视口越过
5555
+ * 地图边界后宿主只能回**折回来的那一份**,画面在「一份地图」的边界上整体跳一格,
5556
+ * 看起来就是复位;而 0 这个位置既没有参照物、又不在吸附点上,自然对不齐、也难拖到。
5557
+ * 夹住之后 `pan = 0` 就是「地图左上角 = 画布左上角」,拖到头就停,不再有跳变。
5558
+ */
5559
+ const clampPan = React.useCallback((next) => {
5560
+ if (layout === null)
5561
+ return next;
5562
+ const viewW = viewportRef.current.w / Math.max(0.01, zoomRef.current);
5563
+ const viewH = viewportRef.current.h / Math.max(0.01, zoomRef.current);
5564
+ /**
5565
+ * `pan` 的定义是「画布左上角落在地图的哪个像素」——所以取值范围是
5566
+ * `0 .. max(0, 地图 - 视口)`:
5567
+ * · `pan = 0`:地图左上角贴着画布左上角(用户要的「对齐」就是这里);
5568
+ * · `pan = 地图 - 视口`:滚到地图的右下角(地图比视口大时才滚得动);
5569
+ * · 地图比视口小 → 上界为 0 → 钉死在左上角,不会拖出空白。
5570
+ *
5571
+ * ⚠️ 别把符号想反(我第一版就写成了负区间):那样小图能拖进空白、大图反而一步不动,
5572
+ * 真机上「拖了地图纹丝不动 / 复位后又对不齐」就是这么来的。
5573
+ */
5574
+ const maxX = Math.max(0, layout.width - viewW);
5575
+ const maxY = Math.max(0, layout.height - viewH);
5576
+ return { x: Math.min(maxX, Math.max(0, next.x)), y: Math.min(maxY, Math.max(0, next.y)) };
5577
+ }, [layout]);
5578
+ /**
5579
+ * 入队一批 op。
5580
+ *
5581
+ * 一次按下 → 抬起算**一笔**:拖动期间每 40ms 提交一次,但都带同一个 `stroke`,
5582
+ * 宿主才会并成一条历史;否则一次拖拽要按好几次撤销才回得去。
5583
+ */
5584
+ const queueOps = React.useCallback((ops, immediate) => {
5585
+ const stroke = currentStroke.current === null ? `s${++strokeSeq.current}` : currentStroke.current;
5586
+ currentStroke.current = immediate === true ? null : stroke;
5587
+ pendingOps.current = pendingOps.current.concat(ops.map((op) => ({ ...op, stroke })));
5588
+ /**
5589
+ * ⚠️ 拖动期间**不再按 40ms 分批提交**,只攒着,等这一笔结束(pointerup /
5590
+ * 指针离开 / 被系统取消)一次性提交。用户要求「一笔画完再自动保存,不要一边画
5591
+ * 一边保存」—— 顺带也把拖动时的往返次数从每秒 25 次降到一笔一次。
5592
+ * 一步完成的编辑(油漆桶 / 一键生成之类)走 `immediate`,立刻提交。
5593
+ */
5594
+ if (immediate === true) {
5595
+ void flushOps();
5596
+ return;
5597
+ }
5598
+ // 节流预览:让这一笔**看得见**(宿主只算不存),真正的提交仍在 pointerup
5599
+ if (previewTimer.current === null) {
5600
+ previewTimer.current = setTimeout(() => {
5601
+ previewTimer.current = null;
5602
+ setPreviewTick((value) => value + 1);
5603
+ }, 80);
5604
+ }
5605
+ }, [flushOps]);
5606
+ const doUndo = async () => {
5607
+ if (api === undefined || viewId === null)
5608
+ return;
5609
+ try {
5610
+ applyResult(await api.mapUndo({ projectId: viewId, have: [...planRef.current.keys()] }));
5611
+ }
5612
+ catch (error) {
5613
+ setNotice({ kind: "error", text: msg(error) });
5614
+ }
5615
+ finally {
5616
+ }
5617
+ };
5618
+ const doRedo = async () => {
5619
+ if (api === undefined || viewId === null)
5620
+ return;
5621
+ try {
5622
+ applyResult(await api.mapRedo({ projectId: viewId, have: [...planRef.current.keys()] }));
5623
+ }
5624
+ catch (error) {
5625
+ setNotice({ kind: "error", text: msg(error) });
5626
+ }
5627
+ finally {
5628
+ }
5629
+ };
5630
+ // ── 画布命中测试与交互 ───────────────────────────────────────────────
5631
+ const cellFromEvent = React.useCallback((event) => {
5632
+ const canvas = canvasRef.current;
5633
+ if (canvas === null || canvas === undefined || layout === null)
5634
+ return null;
5635
+ const rect = canvas.getBoundingClientRect();
5636
+ const x = (event.clientX - rect.left) / zoom + pan.x;
5637
+ const y = (event.clientY - rect.top) / zoom + pan.y;
5638
+ const hit = MAP_pointToCell(layout, x, y);
5639
+ if (hit.inMap !== true)
5640
+ return null;
5641
+ /**
5642
+ * ⚠️ 只认**地图自己那一份**(未取模坐标落在 0..cols/rows 之内)。
5643
+ *
5644
+ * 环绕地图上,`pointToCell` 会把边界外的位置折回图内,于是「画超过右边缘」会点亮相
5645
+ * 反的左边缘、「超过下边缘」会点亮上边缘 —— 用户报的就是这个。画布上超出地图的那片
5646
+ * 区域本来就是空白,不该有落笔、也不该有红框。
5647
+ */
5648
+ const rawR = Math.floor(y / layout.stepY);
5649
+ const rawC = Math.floor(x / layout.stepX);
5650
+ if (rawR < 0 || rawC < 0 || rawR >= layout.rows || rawC >= layout.cols)
5651
+ return null;
5652
+ /**
5653
+ * ⚠️ 把**未取模**的地图坐标一起带出去,两个地方都要用:
5654
+ *
5655
+ * 1. 红框:环绕模式下同一格会在屏幕上出现好几次(地图比画布小的时候最常见)。
5656
+ * 只留取模后的 `r/c`,红框就画在「地图内的那一份」上 —— 真机表现是鼠标在左边、
5657
+ * 红框跑到右边一整张地图之外(实测偏差 ≈ 353.6px = 一张地图宽)。
5658
+ * 2. **补间**:`paintCells` 必须按未取模的格号插值。用取模后的格号时,指针跨过
5659
+ * 接缝(右边界那一份的 c=31 → 下一份的 c=0,屏幕上只差十几像素)会被算成
5660
+ * 「从第 31 列走到第 0 列」→ **整行被填满**。真机复现:清空图层后横扫一笔,
5661
+ * 整行 32 格全亮。
5662
+ */
5663
+ return { r: hit.r, c: hit.c, x, y, rawR, rawC };
5664
+ }, [layout, zoom, pan]);
5665
+ /**
5666
+ * 画笔从一个格拖到另一个格:把中间漏掉的格补上。
5667
+ *
5668
+ * ⚠️ 补间用**未取模**的格号(`rawR` / `rawC`),发出去的也允许越界 —— 宿主
5669
+ * `applyOps` 自己会取模。用取模后的格号补间的话,指针跨过地图接缝时会被算成
5670
+ * 「从第 31 列走到第 0 列」,一笔就把整行填满(真机复现过;横向扫一笔 → 整行 32 格)。
5671
+ * 没有 raw 的(理论上不会,防御式兜底)退回取模格号。
5672
+ */
5673
+ const paintCells = (from, to, tile) => {
5674
+ if (activeLayer === null)
5675
+ return;
5676
+ const rawOf = (cell) => ({ r: cell.rawR === undefined ? cell.r : cell.rawR, c: cell.rawC === undefined ? cell.c : cell.rawC });
5677
+ const end = rawOf(to);
5678
+ const cells = from === null || from === undefined ? [end] : MAP_lineCells(rawOf(from).r, rawOf(from).c, end.r, end.c);
5679
+ queueOps([{ kind: "paint", layerId: activeLayer.id, cells: cells.map((cell) => ({ r: cell.r, c: cell.c, tile })) }]);
5680
+ };
5681
+ const warnNoBrush = () => {
5682
+ if (brush === null) {
5683
+ setNotice({ kind: "error", text: T("先在左边点一块图当笔刷。") });
5684
+ return true;
5685
+ }
5686
+ return false;
5687
+ };
5688
+ /** 吸管:从宿主给的绘制条目里读「这一格最上面是哪一块」。 */
5689
+ const pickAt = (cell) => {
5690
+ let found = null;
5691
+ for (const key of visibleRef.current) {
5692
+ const ops = planOps.get(key);
5693
+ if (ops === undefined)
5694
+ continue;
5695
+ for (const op of ops) {
5696
+ if (op.r !== cell.r || op.c !== cell.c)
5697
+ continue;
5698
+ if (single === true && op.l !== safeLayerIndex)
5699
+ continue;
5700
+ if (found === null || (op.l ?? 0) >= (found.l ?? 0))
5701
+ found = op;
5702
+ }
5703
+ }
5704
+ if (found === null)
5705
+ return;
5706
+ // ⚠️ 吸管吸到的是**这一格实际贴的那一块**。对拼块素材来说那是一个 16px 小格,
5707
+ // 而调色板里只有该素材的**一个代表笔刷** —— 直接 setBrush(小格) 的话红框找不到
5708
+ // 对应的格子,用户会看到「当前笔刷」凭空消失(真机实测:吸海面后红框没了)。
5709
+ // 所以这里把它归到「拥有它的那个调色板条目」上;普通素材每格都有条目,等于原样。
5710
+ const owner = legendMap.get(found.t);
5711
+ const entries = view === null || view === undefined ? [] : view.tilesets;
5712
+ let index = found.t;
5713
+ if (owner !== undefined) {
5714
+ const tileset = entries.find((entry) => entry.id === owner.tilesetId);
5715
+ const palette = tileset === undefined ? [] : tileset.palette;
5716
+ if (palette.length > 0 && !palette.some((entry) => entry.index === found.t))
5717
+ index = palette[0].index;
5718
+ }
5719
+ setBrush({ index });
5720
+ setMulti([index]);
5721
+ };
5722
+ const zoomAt = (clientX, clientY, factor) => {
5723
+ const canvas = canvasRef.current;
5724
+ if (canvas === null || canvas === undefined)
5725
+ return;
5726
+ const rect = canvas.getBoundingClientRect();
5727
+ const prev = zoomRef.current;
5728
+ const next = Math.min(8, Math.max(0.25, prev * factor));
5729
+ const mapX = (clientX - rect.left) / prev + panRef.current.x;
5730
+ const mapY = (clientY - rect.top) / prev + panRef.current.y;
5731
+ setZoom(next);
5732
+ setPan((prev) => clampPan({ x: mapX - (clientX - rect.left) / next, y: mapY - (clientY - rect.top) / next }));
5733
+ };
5734
+ // 原生滚轮监听要在事件到来时拿到**最新**的 zoomAt(它闭包了 zoom/pan),
5735
+ // 所以用 ref 转发,而不是把 zoomAt 塞进 effect 依赖(那会每帧重新挂监听)。
5736
+ zoomAtRef.current = zoomAt;
5737
+ const onPointerDown = (event) => {
5738
+ if (layout === null)
5739
+ return;
5740
+ if (typeof event.preventDefault === "function")
5741
+ event.preventDefault();
5742
+ const canvas = canvasRef.current;
5743
+ if (canvas !== null && canvas !== undefined && typeof canvas.setPointerCapture === "function" && event.pointerId !== undefined) {
5744
+ try {
5745
+ canvas.setPointerCapture(event.pointerId);
5746
+ }
5747
+ catch {
5748
+ // 捕获失败不影响画图,只是拖出画布后会断线。
5749
+ }
5750
+ }
5751
+ const pointerId = event.pointerId === undefined ? 1 : event.pointerId;
5752
+ pointersRef.current.set(pointerId, { x: event.clientX, y: event.clientY });
5753
+ if (pointersRef.current.size === 2) {
5754
+ const [a, b] = [...pointersRef.current.values()];
5755
+ strokeRef.current = null;
5756
+ currentStroke.current = null;
5757
+ pointersRef.current.pinch = { distance: Math.hypot(a.x - b.x, a.y - b.y) };
5758
+ return;
5759
+ }
5760
+ const hit = cellFromEvent(event);
5761
+ if (hit === null)
5762
+ return;
5763
+ if (tool === "hand" || event.button === 1 || spaceRef.current === true) {
5764
+ strokeRef.current = { mode: "pan", clientX: event.clientX, clientY: event.clientY, pan: { ...pan } };
5765
+ return;
5766
+ }
5767
+ if (event.button === 2 || tool === "eraser") {
5768
+ currentStroke.current = null;
5769
+ strokeRef.current = { mode: "paint", from: hit, tile: 0 };
5770
+ paintCells(null, hit, 0);
5771
+ return;
5772
+ }
5773
+ if (tool === "pipette") {
5774
+ pickAt(hit);
5775
+ return;
5776
+ }
5777
+ if (tool === "bucket") {
5778
+ if (warnNoBrush() || activeLayer === null)
5779
+ return;
5780
+ queueOps([{ kind: "fill", layerId: activeLayer.id, r: hit.r, c: hit.c, tile: brush.index }], true);
5781
+ return;
5782
+ }
5783
+ if (warnNoBrush())
5784
+ return;
5785
+ currentStroke.current = null;
5786
+ strokeRef.current = { mode: "paint", from: hit, tile: brush.index };
5787
+ paintCells(null, hit, brush.index);
5788
+ };
5789
+ const onPointerMove = (event) => {
5790
+ if (layout === null)
5791
+ return;
5792
+ const pointerId = event.pointerId === undefined ? 1 : event.pointerId;
5793
+ if (pointersRef.current.has(pointerId))
5794
+ pointersRef.current.set(pointerId, { x: event.clientX, y: event.clientY });
5795
+ const pinch = pointersRef.current.pinch;
5796
+ if (pinch !== undefined && pointersRef.current.size === 2) {
5797
+ const [a, b] = [...pointersRef.current.values()];
5798
+ const distance = Math.hypot(a.x - b.x, a.y - b.y);
5799
+ if (pinch.distance > 0)
5800
+ zoomAt((a.x + b.x) / 2, (a.y + b.y) / 2, distance / pinch.distance);
5801
+ pinch.distance = distance;
5802
+ return;
5803
+ }
5804
+ const stroke = strokeRef.current;
5805
+ if (stroke !== null && stroke !== undefined && stroke.mode === "pan") {
5806
+ setPan(clampPan({
5807
+ x: stroke.pan.x - (event.clientX - stroke.clientX) / zoom,
5808
+ y: stroke.pan.y - (event.clientY - stroke.clientY) / zoom
5809
+ }));
5810
+ return;
5811
+ }
5812
+ const hit = cellFromEvent(event);
5813
+ if (hit === null) {
5814
+ setHover((prev) => (prev === null ? prev : null));
5815
+ return;
5816
+ }
5817
+ /**
5818
+ * ⚠️ 同一格内移动**不要**换新对象。`hover` 是绘制回调的依赖,换对象 = 整幅重画;
5819
+ * 拖动时每秒几十个 `pointermove`,一格又往往走上好几个事件,于是每秒几十次
5820
+ * 「清屏 + 重画所有条目」——真机表现就是画布一直在闪、CPU 一直满。
5821
+ * 红框是按格对齐的,格号没变画面就没变,返回同一个对象让 React 直接跳过这次渲染。
5822
+ */
5823
+ setHover((prev) => (prev !== null && prev.r === hit.r && prev.c === hit.c ? prev : hit));
5824
+ if (stroke !== null && stroke !== undefined && stroke.mode === "paint") {
5825
+ if (stroke.from.r !== hit.r || stroke.from.c !== hit.c) {
5826
+ paintCells(stroke.from, hit, stroke.tile);
5827
+ stroke.from = hit;
5828
+ }
5829
+ }
5830
+ };
5831
+ const onPointerUp = (event) => {
5832
+ const pointerId = event.pointerId === undefined ? 1 : event.pointerId;
5833
+ pointersRef.current.delete(pointerId);
5834
+ if (pointersRef.current.size < 2)
5835
+ delete pointersRef.current.pinch;
5836
+ strokeRef.current = null;
5837
+ currentStroke.current = null;
5838
+ void flushOps();
5839
+ };
5840
+ // 快捷键:B/E/G/I/H/V 与撤销重做;焦点在输入框里时全部失效
5841
+ React.useEffect(() => {
5842
+ const editable = (target) => target !== null && target !== undefined && /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName || "");
5843
+ const onKeyDown = (event) => {
5844
+ if (String(event.key) === " ") {
5845
+ spaceRef.current = true;
5846
+ if (editable(event.target) !== true && typeof event.preventDefault === "function")
5847
+ event.preventDefault();
5848
+ return;
5849
+ }
5850
+ const meta = event.metaKey === true || event.ctrlKey === true;
5851
+ if (meta === true) {
5852
+ if (editable(event.target) === true)
5853
+ return;
5854
+ const key = String(event.key).toLowerCase();
5855
+ if (key === "z" && event.shiftKey === true) {
5856
+ event.preventDefault();
5857
+ void doRedo();
5858
+ return;
5859
+ }
5860
+ if (key === "z" || key === "y") {
5861
+ event.preventDefault();
5862
+ void doUndo();
5863
+ }
5864
+ return;
5865
+ }
5866
+ if (editable(event.target) === true)
5867
+ return;
5868
+ const key = String(event.key).toLowerCase();
5869
+ if (key === "b")
5870
+ setTool("pen");
5871
+ else if (key === "e")
5872
+ setTool("eraser");
5873
+ else if (key === "g")
5874
+ setTool("bucket");
5875
+ else if (key === "i")
5876
+ setTool("pipette");
5877
+ else if (key === "h")
5878
+ setTool("hand");
5879
+ else if (key === "v")
5880
+ setSingle((value) => value !== true);
5881
+ };
5882
+ const onKeyUp = (event) => {
5883
+ if (String(event.key) === " ")
5884
+ spaceRef.current = false;
5885
+ };
5886
+ window.addEventListener("keydown", onKeyDown);
5887
+ window.addEventListener("keyup", onKeyUp);
5888
+ return () => {
5889
+ window.removeEventListener("keydown", onKeyDown);
5890
+ window.removeEventListener("keyup", onKeyUp);
5891
+ };
5892
+ });
5893
+ // ── 项目与素材的动作 ─────────────────────────────────────────────────
5894
+ const ensureTwoLayers = async (projectId) => {
5895
+ const next = await api.getMapProject({ projectId });
5896
+ if (((next.layers || []).length) < 2)
5897
+ await api.saveMapDoc({ projectId, addLayer: { name: T("图层 2") } });
5898
+ };
5899
+ /** 没有项目就地建一个:32×32、两层,建完就能画。 */
5900
+ const ensureProject = async () => {
5901
+ if (viewId !== null)
5902
+ return viewId;
5903
+ const created = await api.createMapProject({ name: T("我的地图"), cols: 32, rows: 32 });
5904
+ setProjects((prev) => [{ id: created.id, name: created.name }, ...prev]);
5905
+ await ensureTwoLayers(created.id);
5906
+ return created.id;
5907
+ };
5908
+ const readBase64 = (file) => new Promise((resolve, reject) => {
5909
+ const reader = new FileReader();
5910
+ reader.onload = () => resolve(String(reader.result).split(",")[1] || "");
5911
+ reader.onerror = () => reject(new Error(T("读文件失败")));
5912
+ reader.readAsDataURL(file);
5913
+ });
5914
+ const startWithFile = async (file) => {
5915
+ if (file === undefined || file === null || api === undefined)
5916
+ return;
5917
+ setBusyKey("upload");
5918
+ try {
5919
+ const projectId = await ensureProject();
5920
+ const base64 = await readBase64(file);
5921
+ const imported = await api.importMapTileset({ projectId, name: file.name, data: base64 });
5922
+ if (imported !== undefined && Array.isArray(imported.warnings) && imported.warnings.length > 0) {
5923
+ setNotice({ kind: "info", text: imported.warnings.join(";") });
5924
+ }
5925
+ else {
5926
+ setNotice({ kind: "info", text: T("已导入 {n0}", { n0: file.name }) });
5927
+ }
5928
+ await loadProject(projectId);
5929
+ const result = await api.listMapProjects();
5930
+ setProjects(result.projects || []);
5931
+ setOpenCard("assets");
5932
+ }
5933
+ catch (error) {
5934
+ setNotice({ kind: "error", text: msg(error) });
5935
+ }
5936
+ finally {
5937
+ setBusyKey(null);
5938
+ }
5939
+ };
5940
+ const startWithSample = async () => {
5941
+ if (api === undefined)
5942
+ return;
5943
+ setBusyKey("sample");
5944
+ try {
5945
+ const projectId = await ensureProject();
5946
+ await api.importSampleTileset({ projectId });
5947
+ await loadProject(projectId);
5948
+ const result = await api.listMapProjects();
5949
+ setProjects(result.projects || []);
5950
+ setOpenCard("assets");
5951
+ }
5952
+ catch (error) {
5953
+ setNotice({ kind: "error", text: msg(error) });
5954
+ }
5955
+ finally {
5956
+ setBusyKey(null);
5957
+ }
5958
+ };
5959
+ /** 打开「新增素材」:草稿全空 = 一切都走自动识别。 */
5960
+ const openAddTileset = () => setAddDraft({ file: null, name: "", cellW: "", cellH: "", shape: "auto", animRows: false });
5961
+ /**
5962
+ * 提交新增:把「图片 + 名字 + 属性」一次性交给宿主。
5963
+ *
5964
+ * 留空的项不发(宿主按自动识别处理);只有用户真的填了才带上,避免用空值把识别结果顶掉。
5965
+ */
5966
+ const submitAddTileset = async () => {
5967
+ const draft = addDraft;
5968
+ if (draft === null || api === undefined)
5969
+ return;
5970
+ if (draft.file === null) {
5971
+ setNotice({ kind: "error", text: T("先选一张素材图。") });
5972
+ return;
5973
+ }
5974
+ const projectId = await ensureProject();
5975
+ if (projectId === null)
5976
+ return;
5977
+ setBusyKey("upload");
5978
+ try {
5979
+ const base64 = await readBase64(draft.file);
5980
+ const cell = draft.cellW !== "" && draft.cellH !== "" ? { width: Number(draft.cellW), height: Number(draft.cellH) } : undefined;
5981
+ const imported = await api.importMapTileset({
5982
+ projectId,
5983
+ name: draft.name.trim() === "" ? draft.file.name : draft.name.trim(),
5984
+ data: base64,
5985
+ cell,
5986
+ shape: draft.shape === "auto" ? undefined : draft.shape,
5987
+ animRows: draft.animRows === true
5988
+ });
5989
+ setAddDraft(null);
5990
+ setNotice({ kind: "info", text: T("已新增素材 {n0}", { n0: draft.name.trim() === "" ? draft.file.name : draft.name.trim() }) });
5991
+ if (imported !== undefined && Array.isArray(imported.warnings) && imported.warnings.length > 0) {
5992
+ setNotice({ kind: "info", text: imported.warnings.join(";") });
5993
+ }
5994
+ await loadProject(projectId);
5995
+ const list = await api.listMapProjects();
5996
+ setProjects(list.projects || []);
5997
+ setOpenCard("assets");
5998
+ // 新加的那张直接选上(列表最后一张)
5999
+ const fresh = await api.listMapProjects();
6000
+ void fresh;
6001
+ }
6002
+ catch (error) {
6003
+ setNotice({ kind: "error", text: msg(error) });
6004
+ }
6005
+ finally {
6006
+ setBusyKey(null);
6007
+ }
6008
+ };
6009
+ /** 删掉列表里的某一张(内置也能删)。 */
6010
+ /**
6011
+ * 「这块素材怎么用」的四个选项:`[值, 按钮短标签, 悬停小标签标题, 解释]`。
6012
+ *
6013
+ * ⚠️ 原来是个 `<select>`,而原生 `<option>` **挂不了 tooltip** —— 可「自动 / 普通图块 /
6014
+ * 整格自动连接 / 拼块自动连接」这四个词对非专业用户等于没说(用户原话:意义不明)。
6015
+ * 换成四个按钮 + 悬停小标签:鼠标移上去就把这一项讲清楚(和工具格同一套标签)。
6016
+ */
6017
+ const shapeOptions = [
6018
+ ["auto", T("自动"), T("自动"), T("按图片尺寸自己认格子与用法。想重新认一次,就再上传一遍这张图。")],
6019
+ ["plain", T("普通"), T("普通图块"), T("一格贴一块图,不做任何拼接。")],
6020
+ ["corner16", T("整格"), T("整格自动连接"), T("按上下左右有没有同样的格子,自动从 16 块里挑一块:边缘、拐角会自己接上。")],
6021
+ ["a2quad", T("拼块"), T("拼块自动连接"), T("一小格再拆成 2×2 小块,按邻居自动拼成一片。草地、水面这类连着画的地面用它。")]
6022
+ ];
6023
+ /**
6024
+ * 一段「几个按钮里选一个」的控件(用法、会动吗都用它)。
6025
+ *
6026
+ * 对话框里的选择只改**草稿**,点「确定」才交给宿主 —— 属性一旦定下来就不能改了,
6027
+ * 不该边点边写。
6028
+ */
6029
+ const segPicker = (attr, options, current, onPick) => h("div", { className: "SPR_mapEdSeg" }, options.map(([value, short, title, desc]) => h("button", {
6030
+ key: value,
6031
+ type: "button",
6032
+ className: "SPR_mapEdSegBtn",
6033
+ [attr]: value,
6034
+ "data-on": current === value ? "true" : undefined,
6035
+ "aria-label": `${title}:${desc}`,
6036
+ onMouseEnter: showToolTip(title, desc, null),
6037
+ onFocus: showToolTip(title, desc, null),
6038
+ onMouseLeave: hideToolTip,
6039
+ onBlur: hideToolTip,
6040
+ onClick: () => onPick(value)
6041
+ }, short)));
6042
+ const animOptions = [
6043
+ ["off", T("不动"), T("不动"), T("这张图当作一堆静止的图块。")],
6044
+ ["rows", T("翻页图"), T("翻页图"), T("像手翻书:每一行是一页,连着播就动起来了。同一列的几行算同一块,画的时候点哪一行都行,整片会一起动。")]
6045
+ ];
6046
+ /** 「新增素材」对话框:图片 + 名字 + 属性一次填完,之后只能删。 */
6047
+ const addDialog = addDraft === null
6048
+ ? null
6049
+ : h("div", { className: "SPR_mapEdDlgMask", "data-testid": "map-add-mask", onClick: () => setAddDraft(null) }, h("div", {
6050
+ className: "SPR_mapEdDlg",
6051
+ role: "dialog",
6052
+ "aria-label": T("新增素材"),
6053
+ "data-testid": "map-add-dialog",
6054
+ onClick: (event) => {
6055
+ if (typeof event.stopPropagation === "function")
6056
+ event.stopPropagation();
6057
+ }
6058
+ }, h("div", { className: "SPR_mapEdDlgTitle" }, T("新增素材")), h("div", { className: "SPR_mapEdDlgLabel" }, T("素材图")), h("div", { className: "SPR_mapEdDlgRow" }, h(Btn, { onClick: () => addFileRef.current?.click() }, T("选择图片")), h("span", { className: "SPR_mapEdHint" }, addDraft.file === null ? T("还没选") : addDraft.file.name)), h("div", { className: "SPR_mapEdDlgLabel" }, T("叫什么")), h("input", {
6059
+ className: "SPR_mapEdDlgInput",
6060
+ "data-testid": "map-add-name",
6061
+ value: addDraft.name,
6062
+ placeholder: T("留空就用文件名"),
6063
+ onChange: (event) => setAddDraft((current) => (current === null ? current : { ...current, name: event.target.value }))
6064
+ }), h("div", { className: "SPR_mapEdDlgLabel" }, T("格子大小(留空就自动认)")), h("div", { className: "SPR_mapEdPair" }, h(NumField, {
6065
+ label: T("宽"),
6066
+ value: addDraft.cellW === "" ? "" : Number(addDraft.cellW),
6067
+ min: 1,
6068
+ max: 1024,
6069
+ onChange: (value) => setAddDraft((current) => (current === null ? current : { ...current, cellW: String(value) }))
6070
+ }), h("span", { className: "SPR_mapEdTimes" }, "×"), h(NumField, {
6071
+ label: T("高"),
6072
+ value: addDraft.cellH === "" ? "" : Number(addDraft.cellH),
6073
+ min: 1,
6074
+ max: 1024,
6075
+ onChange: (value) => setAddDraft((current) => (current === null ? current : { ...current, cellH: String(value) }))
6076
+ })), h("div", { className: "SPR_mapEdDlgLabel" }, T("这块素材怎么用")), segPicker("data-shape", shapeOptions, addDraft.shape, (value) => setAddDraft((current) => (current === null ? current : { ...current, shape: value }))), h("div", { className: "SPR_mapEdDlgLabel" }, T("会动吗")), segPicker("data-anim", animOptions, addDraft.animRows ? "rows" : "off", (value) => setAddDraft((current) => (current === null ? current : { ...current, animRows: value === "rows" }))), h("div", { className: "SPR_mapEdDlgRow" }, h(Btn, { "data-testid": "map-add-cancel", onClick: () => setAddDraft(null) }, T("取消")), h(Btn, { "data-testid": "map-add-ok", primary: true, busy: busyKey === "upload", onClick: () => void submitAddTileset() }, T("确定")))));
6077
+ const removeTilesetById = async (tilesetId, tilesetName) => {
6078
+ if (view === null || api === undefined)
6079
+ return;
6080
+ // eslint-disable-next-line no-alert
6081
+ if (typeof window !== "undefined" && !window.confirm(T("确定删除素材「{n0}」?它切出来的块会一起删掉,无法撤销。", { n0: tilesetName })))
6082
+ return;
6083
+ const result = await withApi(() => api.removeMapTileset({ projectId: view.id, tilesetId }), { notice: T("已删除素材") });
6084
+ if (result === undefined)
6085
+ return;
6086
+ await loadProject(view.id, true);
6087
+ };
6088
+ /** 一键恢复默认素材:把缺的内置素材补回来(已有的同名会跳过,不会变成两份)。 */
6089
+ const restoreSamples = async () => {
6090
+ if (api === undefined)
6091
+ return;
6092
+ setBusyKey("sample");
6093
+ try {
6094
+ const projectId = await ensureProject();
6095
+ if (projectId === null)
6096
+ return;
6097
+ const restored = await api.importSampleTileset({ projectId });
6098
+ const added = Array.isArray(restored?.tilesets) ? restored.tilesets.length : 0;
6099
+ setNotice({ kind: "info", text: added > 0 ? T("已恢复 {n0} 张默认素材", { n0: String(added) }) : T("默认素材都在。") });
6100
+ await loadProject(projectId, true);
6101
+ const list = await api.listMapProjects();
6102
+ setProjects(list.projects || []);
6103
+ }
6104
+ catch (error) {
6105
+ setNotice({ kind: "error", text: msg(error) });
6106
+ }
6107
+ finally {
6108
+ setBusyKey(null);
6109
+ }
6110
+ };
6111
+ /**
6112
+ * 新建 / 重命名项目:**自己弹一个窗口**,不用 `window.prompt`。
6113
+ *
6114
+ * ⚠️ 真机踩过:DSH 桌面端是 Electron,而 Electron **不实现 `window.prompt`**
6115
+ * (函数在、调用直接抛错)。原来「新建项目」点了什么都不发生,就是因为名字拿不到 ——
6116
+ * 而且 `typeof window.prompt === "function"` 这个判断完全看不出来。
6117
+ * 所以这里改成本地渲染的对话框:输入框 + 取消 / 确定,回车确认、Esc 取消。
6118
+ */
6119
+ const [nameAsk, setNameAsk] = React.useState(null);
6120
+ const askProjectName = (mode) => setNameAsk({
6121
+ mode,
6122
+ title: mode === "create" ? T("新建项目") : T("重命名项目"),
6123
+ label: mode === "create" ? T("新项目的名字") : T("新的项目名"),
6124
+ value: mode === "create" ? T("我的地图") : view === null ? "" : view.name
6125
+ });
6126
+ const submitNameAsk = async () => {
6127
+ const ask = nameAsk;
6128
+ if (ask === null)
6129
+ return;
6130
+ const trimmed = String(ask.value).trim();
6131
+ // 新建:空名用默认名(用户的意图是「建一个」,不该被空字符串卡住);
6132
+ // 重命名:空名等于没改,直接关掉。
6133
+ if (ask.mode === "rename" && trimmed === "") {
6134
+ setNameAsk(null);
6135
+ return;
6136
+ }
6137
+ setNameAsk(null);
6138
+ if (ask.mode === "create")
6139
+ await createProject(trimmed === "" ? T("我的地图") : trimmed);
6140
+ else
6141
+ await renameProject(trimmed);
6142
+ };
6143
+ /** 名字对话框。`position:fixed` 居中,不用原生 prompt / confirm。 */
6144
+ const nameDialog = nameAsk === null
6145
+ ? null
6146
+ : h("div", { className: "SPR_mapEdDlgMask", "data-testid": "map-name-mask", onClick: () => setNameAsk(null) }, h("div", {
6147
+ className: "SPR_mapEdDlg",
6148
+ role: "dialog",
6149
+ "aria-label": nameAsk.title,
6150
+ "data-testid": "map-name-dialog",
6151
+ onClick: (event) => {
6152
+ if (typeof event.stopPropagation === "function")
6153
+ event.stopPropagation();
6154
+ }
6155
+ }, h("div", { className: "SPR_mapEdDlgTitle" }, nameAsk.title), h("label", { className: "SPR_mapEdDlgLabel" }, nameAsk.label), h("input", {
6156
+ className: "SPR_mapEdDlgInput",
6157
+ "data-testid": "map-name-input",
6158
+ value: nameAsk.value,
6159
+ autoFocus: true,
6160
+ onChange: (event) => setNameAsk((current) => (current === null ? current : { ...current, value: event.target.value })),
6161
+ onKeyDown: (event) => {
6162
+ if (event.key === "Enter") {
6163
+ if (typeof event.preventDefault === "function")
6164
+ event.preventDefault();
6165
+ void submitNameAsk();
6166
+ }
6167
+ else if (event.key === "Escape") {
6168
+ setNameAsk(null);
6169
+ }
6170
+ }
6171
+ }), h("div", { className: "SPR_mapEdDlgRow" }, h(Btn, { "data-testid": "map-name-cancel", onClick: () => setNameAsk(null) }, T("取消")), h(Btn, { "data-testid": "map-name-ok", primary: true, onClick: () => void submitNameAsk() }, T("确定")))));
6172
+ const removeTileset = async () => {
6173
+ if (view === null || tileset === null || api === undefined)
6174
+ return;
6175
+ // eslint-disable-next-line no-alert
6176
+ if (typeof window !== "undefined" && !window.confirm(T("确定删除素材「{n0}」?它切出来的块会一起删掉,无法撤销。", { n0: tileset.name })))
6177
+ return;
6178
+ const result = await withApi(() => api.removeMapTileset({ projectId: view.id, tilesetId: tileset.id }), { notice: T("已删除素材") });
6179
+ if (result === undefined)
6180
+ return;
6181
+ await loadProject(view.id);
6182
+ };
6183
+ /**
6184
+ * 新建项目。**建完就把内置素材装进列表**(用户要求:内置素材默认在素材列表里)——
6185
+ * 装的是本机现算的那套,零成本;同名已存在会跳过。
6186
+ */
6187
+ const createProject = async (name) => {
6188
+ if (api === undefined)
6189
+ return;
6190
+ const created = await withApi(() => api.createMapProject({ name, cols: 32, rows: 32 }));
6191
+ if (created === undefined)
6192
+ return;
6193
+ await ensureTwoLayers(created.id);
6194
+ const result = await api.listMapProjects();
6195
+ setProjects(result.projects || []);
6196
+ await loadProject(created.id);
6197
+ // 新项目默认就带上内置素材(同名会跳过),装完再刷一次列表
6198
+ await api.importSampleTileset({ projectId: created.id }).catch(() => undefined);
6199
+ await loadProject(created.id, true);
6200
+ setOpenCard("assets");
6201
+ };
6202
+ const renameProject = async (name) => {
6203
+ if (view === null || api === undefined)
6204
+ return;
6205
+ const ok = await withApi(() => api.saveMapProject({ projectId: view.id, name }), { notice: T("已重命名") });
6206
+ if (ok === undefined)
6207
+ return;
6208
+ await loadProject(view.id, true);
6209
+ };
6210
+ const deleteProject = async () => {
6211
+ if (view === null || api === undefined)
6212
+ return;
6213
+ // eslint-disable-next-line no-alert
6214
+ if (typeof window !== "undefined" && !window.confirm(T("确定删除项目「{n0}」?项目目录会被整个移除,无法撤销。", { n0: view.name })))
6215
+ return;
6216
+ const done = await withApi(() => api.deleteMapProject({ projectId: view.id }), { notice: T("已删除项目") });
6217
+ if (done === undefined)
6218
+ return;
6219
+ const result = await api.listMapProjects();
6220
+ const rest = result.projects || [];
6221
+ setProjects(rest);
6222
+ if (rest.length > 0)
6223
+ await loadProject(rest[0].id);
6224
+ else {
6225
+ clearPlan();
6226
+ setView(null);
6227
+ }
6228
+ };
6229
+ const saveDoc = async (patch, note) => {
6230
+ if (view === null || api === undefined)
6231
+ return undefined;
6232
+ const result = await withApi(() => api.saveMapDoc({ projectId: view.id, ...patch }), note === undefined ? undefined : { notice: note });
6233
+ if (result === undefined)
6234
+ return undefined;
6235
+ const warnings = result.warnings;
6236
+ if (Array.isArray(warnings) && warnings.length > 0)
6237
+ setNotice({ kind: "info", text: warnings.join(";") });
6238
+ await loadProject(view.id, true);
6239
+ return result;
6240
+ };
6241
+ /**
6242
+ * 改地图尺寸:**宽高各自独立**(不再只给正方形)。
6243
+ *
6244
+ * 上限 512 与宿主 `MAX_MAP_DIM` 一致:超了宿主会拒绝并给出原因,这里先挡一道。
6245
+ */
6246
+ const applyMapSize = async (cols, rows) => {
6247
+ if (view === null)
6248
+ return;
6249
+ const nextCols = Math.round(Number(cols));
6250
+ const nextRows = Math.round(Number(rows));
6251
+ if (!Number.isFinite(nextCols) || !Number.isFinite(nextRows) || nextCols < 1 || nextRows < 1) {
6252
+ setNotice({ kind: "error", text: T("地图大小要是 1 以上的整数。") });
6253
+ return;
6254
+ }
6255
+ if (nextCols > 512 || nextRows > 512) {
6256
+ setNotice({ kind: "error", text: T("地图最大 512×512 格。") });
6257
+ return;
6258
+ }
6259
+ if (nextCols === view.cols && nextRows === view.rows)
6260
+ return;
6261
+ const shrinking = nextCols < view.cols || nextRows < view.rows;
6262
+ // eslint-disable-next-line no-alert
6263
+ if (shrinking === true && typeof window !== "undefined" && !window.confirm(T("改小地图会丢掉范围外的格子(可以撤销)。继续?")))
6264
+ return;
6265
+ await saveDoc({ cols: nextCols, rows: nextRows }, T("已改地图尺寸"));
6266
+ };
6267
+ const clearLayer = async () => {
6268
+ if (view === null || activeLayer === null)
6269
+ return;
6270
+ // eslint-disable-next-line no-alert
6271
+ if (typeof window !== "undefined" && !window.confirm(T("清掉这一层上已经画的格子?")))
6272
+ return;
6273
+ await saveDoc({ clearLayerId: activeLayer.id }, T("已清空这一层"));
6274
+ };
6275
+ const runGenerate = async () => {
6276
+ if (view === null || api === undefined)
6277
+ return;
6278
+ const tiles = multi.length > 0 ? multi : brush === null ? [] : [brush.index];
6279
+ if (tiles.length === 0) {
6280
+ setNotice({ kind: "error", text: T("先选至少一块图:在左边点一下,按住 Shift 或 Ctrl 可以多选。") });
6281
+ return;
6282
+ }
6283
+ setBusyKey("gen");
6284
+ try {
6285
+ const result = await api.runMapGenerate({
6286
+ projectId: view.id,
6287
+ kind: genKind,
6288
+ tiles,
6289
+ seed: genSeed,
6290
+ layerId: activeLayer === null ? undefined : activeLayer.id
6291
+ });
6292
+ if (result !== undefined && Number.isFinite(Number(result.seed)) && Number(result.seed) !== genSeed) {
6293
+ setGenSeed(Number(result.seed));
6294
+ }
6295
+ if (result !== undefined && Array.isArray(result.warnings) && result.warnings.length > 0) {
6296
+ setNotice({ kind: "info", text: result.warnings.join(";") });
6297
+ }
6298
+ // 一次生成可能动到整张图:计划整份作废,重新问宿主
6299
+ clearPlan();
6300
+ setPlanEpoch((value) => value + 1);
6301
+ }
6302
+ catch (error) {
6303
+ setNotice({ kind: "error", text: msg(error) });
6304
+ }
6305
+ finally {
6306
+ setBusyKey(null);
6307
+ }
6308
+ };
6309
+ /**
6310
+ * 导出:**按当前勾选导一次**。
6311
+ *
6312
+ * 打不打 zip 由宿主决定(产物超过一个就自动打),界面不自己判断 ——
6313
+ * 「几个文件算多」只有一处口径,免得界面显示的和盘上的对不上。
6314
+ */
6315
+ const runExport = async () => {
6316
+ if (view === null || api === undefined)
6317
+ return;
6318
+ if (exportFormats.png !== true && exportFormats.json !== true && exportFormats.tilesets !== true) {
6319
+ setNotice({ kind: "error", text: T("至少勾一项要导出的内容。") });
6320
+ return;
6321
+ }
6322
+ setBusyKey("export");
6323
+ try {
6324
+ const started = await api.runMapExport({
6325
+ projectId: view.id,
6326
+ scale: exportScale,
6327
+ formats: { png: exportFormats.png === true, json: exportFormats.json === true, tilesets: exportFormats.tilesets === true }
6328
+ });
6329
+ if (started !== undefined && started.started !== true && typeof started.reason === "string") {
6330
+ setNotice({ kind: "info", text: started.reason });
6331
+ }
6332
+ await loadProject(view.id, true);
6333
+ }
6334
+ catch (error) {
6335
+ setNotice({ kind: "error", text: msg(error) });
6336
+ }
6337
+ finally {
6338
+ setBusyKey(null);
6339
+ }
6340
+ };
6341
+ /** 导出产物的可点 URL(同源静态路由;zip 与单文件走同一条)。 */
6342
+ const exportUrlOf = (file) => `${assetBase}${view.exportBase}${file}`;
6343
+ /** `download` 属性要的是文件名,不是路径(`tilesets/x.png` 直接写上去浏览器会当非法文件名)。 */
6344
+ const baseNameOf = (file) => String(file).split("/").pop() ?? file;
6345
+ const isZip = (file) => /\.zip$/i.test(String(file));
6346
+ /**
6347
+ * 「另存为…」:浏览器原生的保存位置选择框(File System Access API)。
6348
+ *
6349
+ * ⚠️ 顺序不能反:`showSaveFilePicker` 必须在**用户手势**里调用,先 `await fetch`
6350
+ * 下载大文件会把手势耗掉,Chromium 直接抛「Must be handling a user gesture」。
6351
+ * 所以是「先弹框拿句柄 → 再取字节 → 再写盘」;用户取消(AbortError)什么都不提示。
6352
+ */
6353
+ const saveAsExport = async (file) => {
6354
+ /**
6355
+ * ⚠️ 用 `any` 取这个 API:它是 File System Access 的较新成员,
6356
+ * TS 自带的 `Window` 类型里不一定有;而它**存在与否必须运行时判**(Electron 壳、
6357
+ * 老浏览器、跨源 iframe 里都没有),写进类型当成一定有会在真机上直接抛。
6358
+ */
6359
+ const picker = typeof window === "undefined" ? undefined : window.showSaveFilePicker;
6360
+ if (typeof picker !== "function") {
6361
+ setNotice({ kind: "info", text: T("这个浏览器不支持「另存为」,请用下载(位置由浏览器的下载设置决定)。") });
4009
6362
  return;
4010
- event.preventDefault();
4011
- keysRef.current[axis] = down;
6363
+ }
6364
+ try {
6365
+ const handle = await picker({ suggestedName: baseNameOf(file) });
6366
+ const response = await fetch(exportUrlOf(file));
6367
+ if (response.ok !== true)
6368
+ throw new Error(`HTTP ${response.status}`);
6369
+ const writable = await handle.createWritable();
6370
+ await writable.write(await response.blob());
6371
+ await writable.close();
6372
+ setNotice({ kind: "ok", text: T("已保存到 {n0}", { n0: String(handle.name ?? baseNameOf(file)) }) });
6373
+ }
6374
+ catch (error) {
6375
+ // 用户在保存框里按了取消:不是错误,不要弹红字
6376
+ if (error !== null && typeof error === "object" && error.name === "AbortError")
6377
+ return;
6378
+ setNotice({ kind: "error", text: T("另存为失败:{n0}", { n0: msg(error) }) });
6379
+ }
4012
6380
  };
4013
- const reset = () => {
4014
- posRef.current = { x: STAGE_W / 2, y: STAGE_H - 8, dirKey: "front", frame: 0, acc: 0 };
4015
- keysRef.current = { up: false, down: false, left: false, right: false };
6381
+ /** 「打开导出目录」:打开**导出目录本身**(宿主按与导出同一处口径算路径,没导出过就退回项目目录)。 */
6382
+ const openExportFolder = async () => {
6383
+ if (view === null || api === undefined)
6384
+ return;
6385
+ const result = await withApi(() => api.revealMapProject({ projectId: view.id, target: "export" }));
6386
+ if (result === undefined)
6387
+ return;
6388
+ if (result.fallback === true) {
6389
+ setNotice({ kind: "info", text: T("还没有导出过,先点「导出」。现在打开的是项目目录。") });
6390
+ return;
6391
+ }
6392
+ setNotice({ kind: "ok", text: T("已打开 {n0}", { n0: String(result.dir ?? "") }) });
4016
6393
  };
4017
- if (!ready) {
4018
- return h("p", { className: "SPR_empty" }, T("还没有可播放的整图。先完成第 ④ 步合成,再回到这里用 WASD 走一走。"));
4019
- }
4020
- return h(React.Fragment, null, h("div", { className: "SPR_fields" }, h(NumField, {
4021
- label: T("角色缩放倍率"),
4022
- value: scale,
4023
- min: 0.3,
4024
- max: 4,
4025
- step: 0.1,
4026
- onChange: setScale
4027
- }), h(NumField, {
4028
- label: T("移动速度(像素/秒)"),
4029
- value: speed,
4030
- min: 40,
4031
- max: 600,
4032
- step: 10,
4033
- onChange: setSpeed
4034
- }), h(NumField, {
4035
- label: T("播放速度(倍,只影响步频)"),
4036
- value: animSpeed,
4037
- min: 0.25,
4038
- max: 4,
4039
- step: 0.25,
4040
- onChange: setAnimSpeed
4041
- }), h("label", { className: "SPR_field" }, h("span", { className: "SPR_fieldLabel" }, T("背景参考网格")), h("select", { className: "SPR_input", value: grid ? "on" : "off", onChange: (event) => setGrid(event.target.value === "on") }, h("option", { value: "on" }, T("显示(更容易看出在移动)")), h("option", { value: "off" }, T("关闭(纯白)"))))), h("div", { className: "SPR_toolbar" }, h(Btn, { onClick: reset }, T("回到中间")), h("span", { className: "SPR_refRow" }, T("当前朝向:{n0}({n1}) · {n2}", { n0: hud.compass, n1: LABEL_OF[posRef.current.dirKey] ?? "", n2: hud.moving ? T("行走中") : T("站立") })), orderStale
4042
- ? h("span", { className: "SPR_refRow" }, T("· 整图是按旧行序生成的,正在重新合成…"))
4043
- : null, h("span", { className: "SPR_spacer" }), h("span", { className: "SPR_refRow" }, focused ? T("已获得键盘焦点") : T("点击画面后即可操控"))), h("div", {
4044
- ref: boxRef,
4045
- className: "SPR_stage",
4046
- "data-focused": focused ? "true" : "false",
4047
- tabIndex: 0,
4048
- onClick: () => {
4049
- if (boxRef.current !== null)
4050
- boxRef.current.focus();
4051
- },
4052
- onFocus: () => setFocused(true),
4053
- onBlur: () => {
4054
- setFocused(false);
4055
- keysRef.current = { up: false, down: false, left: false, right: false };
4056
- },
4057
- onKeyDown: handleKey(true),
4058
- onKeyUp: handleKey(false)
4059
- }, h("canvas", { ref: canvasRef, className: "SPR_canvas", width: STAGE_W, height: STAGE_H }), focused ? null : h("div", { className: "SPR_stageHint" }, T("点击这里,然后用 WASD 或 ↑↓←→ 操控角色")), h(LoadingOverlay, {
4060
- show: rebuilding || (ready && !sheetLoaded),
4061
- text: rebuilding ? rebuildingText : T("正在载入整图…")
4062
- }), h("div", { className: "SPR_hud" }, h("span", { className: "SPR_hudDir" }, hud.compass), h("span", null, hud.moving ? T("行走") : T("站立")))), h("p", { className: "SPR_hint" }, T("方向按屏幕方位映射:按 ↑ 向北走(背对镜头)、↓ 向南走(正对镜头)、← 向西、→ 向东;斜向同时按两个键。"), h("br"), T("「播放速度」只改步频快慢,不影响角色移动速度;「移动速度」只改走得多快,不影响动画帧率。切图用的是整图自己记录的行序,所以改完行序即使还没重新合成,预览也不会取错方向。")));
4063
- }
4064
- // ── 公共小工具 ──────────────────────────────────────────────────────
4065
- /** 把 File 读成不带 data: 前缀的 base64。 */
4066
- function readFileBase64(file) {
4067
- return new Promise((resolve, reject) => {
4068
- const reader = new FileReader();
4069
- reader.onload = () => {
4070
- const text = String(reader.result ?? "");
4071
- resolve(text.slice(text.indexOf(",") + 1));
4072
- };
4073
- reader.onerror = () => reject(new Error(T("读取文件失败")));
4074
- reader.readAsDataURL(file);
4075
- });
4076
- }
4077
- /** 一个「拖进来或点按钮选文件」的上传区。 */
4078
- function UploadBox({ label, accept, multiple, onFiles, busy }) {
4079
- const [over, setOver] = React.useState(false);
4080
- const inputRef = React.useRef(null);
4081
- const handle = (files) => {
4082
- const list = Array.from(files ?? []);
4083
- if (list.length > 0)
4084
- void onFiles(list);
6394
+ /**
6395
+ * 「整个模块看过了」:一次把四步全打(宿主按「`stage` 省略 = 四阶段全打」处理)。
6396
+ *
6397
+ * 界面上**只剩这一条**改阶段标记的路 —— 卡片里那颗「确定」已经删掉了(用户:
6398
+ * 「和右上角的 x 没区别」),单阶段的标记仍可由验收流程 / 对话面 `setMapApproved` 改。
6399
+ * 已经打过再点一次是幂等的(宿主那边只是把 approved 再写成 true)。
6400
+ */
6401
+ const markWholeModuleSeen = async () => {
6402
+ if (view === null || api === undefined)
6403
+ return;
6404
+ const done = await withApi(() => api.setMapApproved({ projectId: view.id, approved: true }));
6405
+ if (done === undefined)
6406
+ return;
6407
+ await loadProject(view.id, true);
4085
6408
  };
4086
- return h(React.Fragment, null, h("div", {
4087
- className: "SPR_drop",
4088
- "data-over": over ? "true" : "false",
4089
- "data-busy": busy === true ? "true" : undefined,
4090
- onDragOver: (event) => {
4091
- event.preventDefault();
4092
- setOver(true);
4093
- },
4094
- onDragLeave: () => setOver(false),
4095
- onDrop: (event) => {
4096
- event.preventDefault();
4097
- setOver(false);
4098
- handle(event.dataTransfer?.files);
6409
+ const approvedOf = (stage) => {
6410
+ if (view === null)
6411
+ return false;
6412
+ const node = (view.stages || {})[stage];
6413
+ return node !== undefined && node.approved === true;
6414
+ };
6415
+ const approvedAll = ["assets", "rules", "paint", "export"].every((stage) => approvedOf(stage));
6416
+ // 作业进行中就轮询:验收预览 / 导出是宿主上的异步任务,提交那次读到的还是「进行中」
6417
+ const projectBusy = view !== null && view.busy === true;
6418
+ React.useEffect(() => {
6419
+ if (projectBusy !== true || viewId === null || api === undefined)
6420
+ return undefined;
6421
+ const timer = setInterval(() => {
6422
+ void loadProject(viewId, true);
6423
+ }, 1500);
6424
+ return () => clearInterval(timer);
6425
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6426
+ }, [projectBusy, viewId, api]);
6427
+ // ⚠️ 所有 Hook 都在上面;下面才开始早退(React #310,整个面板白屏)
6428
+ const fileInput = h("input", {
6429
+ ref: fileRef,
6430
+ type: "file",
6431
+ accept: "image/*",
6432
+ "data-testid": "map-tileset-input",
6433
+ style: { display: "none" },
6434
+ onChange: (event) => {
6435
+ void startWithFile(event.target.files?.[0]);
6436
+ event.target.value = "";
4099
6437
  }
4100
- }, busy === true
4101
- ? h("span", { style: { display: "inline-flex", alignItems: "center", gap: 7, justifyContent: "center" } }, h("span", { className: "SPR_spinSm" }), T("正在上传…"))
4102
- : label), h("div", { className: "SPR_toolbar" }, h(BusyBtn, { onClick: () => inputRef.current?.click(), busy: busy === true, busyText: T("正在上传…") }, T("选择文件")), h("input", {
4103
- ref: inputRef,
6438
+ });
6439
+ const addFileInput = h("input", {
6440
+ ref: addFileRef,
4104
6441
  type: "file",
4105
- accept,
4106
- multiple: multiple === true,
6442
+ accept: "image/*",
6443
+ "data-testid": "map-add-input",
4107
6444
  style: { display: "none" },
4108
6445
  onChange: (event) => {
4109
- handle(event.target.files);
6446
+ const file = event.target.files?.[0];
6447
+ if (file !== undefined && file !== null)
6448
+ setAddDraft((current) => (current === null ? current : { ...current, file }));
4110
6449
  event.target.value = "";
4111
6450
  }
4112
- })));
4113
- }
4114
- /** 抠像参数表单(三个模块共用同一套字段)。 */
4115
- function KeyingFields({ draft, onChange }) {
4116
- return h("div", { className: "SPR_fields" }, h(NumField, { label: T("抠像下限(绿色优势)"), value: draft.keyLow ?? 14, min: 0, max: 255, onChange: (v) => onChange({ keyLow: v }) }), h(NumField, { label: T("抠像上限(绿色优势)"), value: draft.keyHigh ?? 80, min: 1, max: 255, onChange: (v) => onChange({ keyHigh: v }) }), h(NumField, { label: T("去绿溢出 0~1"), value: draft.despill ?? 0.65, min: 0, max: 1, step: 0.05, onChange: (v) => onChange({ despill: v }) }), h(NumField, { label: T("背景分割容差(0 = 只认绿色)"), value: draft.bgTolerance ?? 90, min: 0, max: 160, onChange: (v) => onChange({ bgTolerance: v }) }), h(NumField, { label: T("边缘收缩(px)"), value: draft.edgeShrink ?? 0, min: 0, max: 8, onChange: (v) => onChange({ edgeShrink: v }) }));
4117
- }
4118
- /** 一份任务/项目列表(左侧栏)。 */
4119
- function JobSidebar({ title, items, activeId, onSelect, onCreate, renderMeta }) {
4120
- return h("div", { className: "SPR_side" }, h("div", { className: "SPR_sideTitle" }, T("{n0}({n1})", { n0: title, n1: items.length })), items.length === 0 ? h("p", { className: "SPR_hint" }, T("还没有内容,点右上角新建一个。")) : null, items.map((item) => h("button", {
4121
- key: item.id,
6451
+ });
6452
+ const shell = (inner) => h("div", { className: "SPR_moduleBody", "data-module": "map" }, gateOpen ? h(MapExperimentalDialog, { onClose: closeGate }) : null, inner, fileInput, addFileInput, addDialog);
6453
+ if (view === null || layout === null) {
6454
+ return shell(h("div", { className: "SPR_mapEdRoot" }, h("div", { className: "SPR_mapEdEmpty" }, h("p", { className: "SPR_mapEdEmptyText" }, T("还没有地图项目。")), h("p", { className: "SPR_mapEdHint" }, T("选一张素材图开始,或者先用自带素材试试。建出来就是 32×32、两层,可以直接画。")), h("div", { className: "SPR_mapEdEmptyRow" }, h(Btn, { onClick: () => askProjectName("create") }, T("新建项目")), h(Btn, { primary: true, onClick: () => fileRef.current?.click(), busy: busyKey === "upload" }, T("选一张素材图开始")), h(Btn, { onClick: () => void startWithSample(), busy: busyKey === "sample" }, T("用自带素材试试"))), notice === null ? null : h("div", { className: `SPR_notice SPR_notice-${notice.kind}` }, notice.text)), nameDialog));
6455
+ }
6456
+ // ── 顶栏 ─────────────────────────────────────────────────────────────
6457
+ const menu = h("div", { className: "SPR_mapEdMenu", role: "menu" }, h("button", {
4122
6458
  type: "button",
4123
- className: "SPR_projItem",
4124
- "data-active": item.id === activeId ? "true" : "false",
4125
- onClick: () => onSelect(item.id)
4126
- }, h("span", { className: "SPR_projName" }, item.name), h("span", { className: "SPR_projMeta" }, renderMeta(item)))), items.length === 0 ? h(Btn, { onClick: onCreate, primary: true }, T("新建")) : null);
6459
+ className: "SPR_mapEdMenuItem",
6460
+ onClick: () => {
6461
+ setMenuOpen(false);
6462
+ askProjectName("create");
6463
+ }
6464
+ }, T("新建项目")), h("button", {
6465
+ type: "button",
6466
+ className: "SPR_mapEdMenuItem",
6467
+ onClick: () => {
6468
+ setMenuOpen(false);
6469
+ askProjectName("rename");
6470
+ }
6471
+ }, T("重命名")), h("button", {
6472
+ type: "button",
6473
+ className: "SPR_mapEdMenuItem",
6474
+ "data-danger": "true",
6475
+ onClick: () => {
6476
+ setMenuOpen(false);
6477
+ void deleteProject();
6478
+ }
6479
+ }, T("删除项目")), h("div", { className: "SPR_mapEdMenuLabel" }, T("切换项目")), projects.map((entry) => h("button", {
6480
+ key: entry.id,
6481
+ type: "button",
6482
+ className: "SPR_mapEdMenuItem",
6483
+ "data-on": entry.id === view.id ? "true" : undefined,
6484
+ onClick: () => {
6485
+ setMenuOpen(false);
6486
+ void loadProject(entry.id);
6487
+ }
6488
+ }, entry.name)));
6489
+ const topBar = h("div", { className: "SPR_mapEdTop" }, h("div", { className: "SPR_mapEdProjWrap" }, h("button", {
6490
+ type: "button",
6491
+ className: "SPR_mapEdProj",
6492
+ "data-open": menuOpen === true ? "true" : undefined,
6493
+ "aria-expanded": menuOpen === true ? "true" : "false",
6494
+ onClick: () => setMenuOpen(menuOpen !== true)
6495
+ }, h("span", { className: "SPR_mapEdProjName" }, view.name), h("span", { className: "SPR_mapEdCaret" }, "▾")), menuOpen === true ? menu : null), h("span", { className: "SPR_mapEdSpacer" }), h("button", {
6496
+ type: "button",
6497
+ className: "SPR_mapEdTopBtn",
6498
+ "data-on": openCard === "assets" ? "true" : undefined,
6499
+ onClick: () => setOpenCard(openCard === "assets" ? null : "assets")
6500
+ }, T("素材")), h("button", {
6501
+ type: "button",
6502
+ className: "SPR_mapEdTopBtn",
6503
+ "data-on": openCard === "export" ? "true" : undefined,
6504
+ onClick: () => setOpenCard(openCard === "export" ? null : "export")
6505
+ }, T("导出")),
6506
+ /**
6507
+ * ⚠️ 这里原来有个「正在保存… / 已自动保存 HH:MM」的状态文字。
6508
+ * 用户反馈:画的时候它一直闪,不需要 —— 而且保存现在改成**一笔结束才提交**
6509
+ * (见 `queueOps`),本来也没什么可显示的。整块拿掉,连带 `savedAt` / `saving`。
6510
+ */
6511
+ null);
6512
+ // ── 左列:素材调色板 + 12 个工具格 ────────────────────────────────────
6513
+ /**
6514
+ * 可点的笔刷清单。
6515
+ *
6516
+ * ⚠️ 必须读宿主给的 `palette`,**不要自己从 `legend` 里推**:绘制图例是按
6517
+ * 「一格一块」列出来的(拼块素材还含 16px 小格),照它做调色板会让用户点到
6518
+ * 半个草地。A2 拼块在 `palette` 里只有一个条目(点它 = 用自动连接笔刷)。
6519
+ */
6520
+ const brushes = [];
6521
+ for (const owner of tilesets) {
6522
+ const list = Array.isArray(owner.palette) && owner.palette.length > 0 ? owner.palette : legend.filter((entry) => entry.tilesetId === owner.id);
6523
+ for (const item of list)
6524
+ brushes.push({ tilesetId: owner.id, index: item.index, rect: item.rect });
6525
+ }
6526
+ const paletteTile = (entry) => {
6527
+ const owner = tilesets.find((item) => item.id === entry.tilesetId);
6528
+ if (owner === undefined)
6529
+ return null;
6530
+ const cellW = owner.cell.width > 0 ? owner.cell.width : entry.rect.width;
6531
+ const cellH = owner.cell.height > 0 ? owner.cell.height : entry.rect.height;
6532
+ const scaleX = 32 / Math.max(1, cellW);
6533
+ const scaleY = 32 / Math.max(1, cellH);
6534
+ return h("button", {
6535
+ key: `${entry.tilesetId}:${entry.index}`,
6536
+ type: "button",
6537
+ className: "SPR_mapEdTile",
6538
+ "data-on": brush !== null && brush.index === entry.index ? "true" : undefined,
6539
+ "data-index": String(entry.index),
6540
+ title: T("第 {n0} 块", { n0: String(entry.index) }),
6541
+ style: {
6542
+ backgroundImage: `url(${assetBase}${owner.file})`,
6543
+ backgroundSize: `${owner.imageWidth * scaleX}px ${owner.imageHeight * scaleY}px`,
6544
+ backgroundPosition: `${-entry.rect.x * scaleX}px ${-entry.rect.y * scaleY}px`
6545
+ },
6546
+ onClick: (event) => {
6547
+ const additive = event.shiftKey === true || event.ctrlKey === true || event.metaKey === true;
6548
+ setBrush({ index: entry.index });
6549
+ setMulti((prev) => additive === true
6550
+ ? prev.includes(entry.index)
6551
+ ? prev.filter((value) => value !== entry.index)
6552
+ : prev.concat([entry.index])
6553
+ : [entry.index]);
6554
+ }
6555
+ });
6556
+ };
6557
+ const palette = h("div", { className: "SPR_mapEdPalette" }, brushes.length === 0
6558
+ ? h("p", { className: "SPR_mapEdHint" }, T("还没有素材,点上面的「素材」上传一张。"))
6559
+ : h("div", { className: "SPR_mapEdPaletteGrid" }, brushes.map(paletteTile)));
6560
+ /**
6561
+ * 一个工具格。
6562
+ *
6563
+ * ⚠️ **不要用 `title` 做说明**:原生 tooltip 要等一秒、样式不受控,还和我们自己那张
6564
+ * 小标签**同时出现**(两个框叠在一起)。所以这里 `aria-label` 承担无障碍名字,
6565
+ * 视觉说明交给 `SPR_mapEdTip` —— 鼠标悬浮 / 键盘聚焦时显示在按钮**正上方**。
6566
+ */
6567
+ const toolButton = (key, name, desc, config) => {
6568
+ const options = config === undefined ? {} : config;
6569
+ const shortcut = options.shortcut === undefined ? null : options.shortcut;
6570
+ return h("button", {
6571
+ key,
6572
+ type: "button",
6573
+ className: "SPR_mapEdTool",
6574
+ "aria-label": shortcut === null
6575
+ ? T("{n0}:{n1}", { n0: name, n1: desc })
6576
+ : T("{n0}:{n1}({n2})", { n0: name, n1: desc, n2: shortcut }),
6577
+ "data-tool": key,
6578
+ "data-on": options.on === true ? "true" : undefined,
6579
+ disabled: options.disabled === true,
6580
+ onMouseEnter: showToolTip(name, desc, shortcut),
6581
+ onFocus: showToolTip(name, desc, shortcut),
6582
+ onMouseLeave: hideToolTip,
6583
+ onBlur: hideToolTip,
6584
+ onPointerDown: hideToolTip,
6585
+ onClick: options.onClick
6586
+ }, options.icon === undefined ? null : h(MapToolIcon, { name: options.icon }));
6587
+ };
6588
+ const tools = h("div", { className: "SPR_mapEdTools" }, toolButton("undo", T("撤销"), T("撤回上一步"), { icon: "undo", shortcut: "⌘Z", onClick: () => void doUndo(), disabled: view.canUndo !== true }), toolButton("redo", T("重做"), T("把刚撤回的一步再做回来"), { icon: "redo", shortcut: "⇧⌘Z", onClick: () => void doRedo(), disabled: view.canRedo !== true }), toolButton("pen", T("画笔"), T("按住左键涂抹,铺当前选中的那块图"), { icon: "pen", shortcut: "B", on: tool === "pen", onClick: () => setTool("pen") }), toolButton("eraser", T("橡皮"), T("把这格擦成空;右键随时是橡皮"), { icon: "eraser", shortcut: "E", on: tool === "eraser", onClick: () => setTool("eraser") }), toolButton("bucket", T("油漆桶"), T("同色的连通区一次填满"), { icon: "bucket", shortcut: "G", on: tool === "bucket", onClick: () => setTool("bucket") }), toolButton("pipette", T("吸管"), T("吸取这一格用的图块,变成当前笔刷"), { icon: "pipette", shortcut: "I", on: tool === "pipette", onClick: () => setTool("pipette") }), toolButton("hand", T("抓手"), T("拖动平移画布;空格拖或中键拖也行"), { icon: "hand", shortcut: "H", on: tool === "hand", onClick: () => setTool("hand") }), toolButton("single", T("单层预览"), T("只显示当前这一层,底铺绿色"), { icon: "single", shortcut: "V", on: single === true, onClick: () => setSingle(single !== true) }), h("div", {
6589
+ key: "layer",
6590
+ className: "SPR_mapEdTool SPR_mapEdLayerBtn",
6591
+ onMouseEnter: showToolTip(T("图层"), T("上半换上一层、下半换下一层;中间的数字是当前层号"), null),
6592
+ onMouseLeave: hideToolTip
6593
+ }, h("button", {
6594
+ type: "button",
6595
+ className: "SPR_mapEdLayerHalf",
6596
+ "data-dir": "up",
6597
+ "aria-label": T("上一层"),
6598
+ disabled: safeLayerIndex >= layers.length - 1,
6599
+ onClick: () => setLayerIndex(Math.min(layers.length - 1, safeLayerIndex + 1))
6600
+ }, h(MapToolIcon, { name: "up" })), h("span", { className: "SPR_mapEdLayerNum" }, String(safeLayerIndex + 1)), h("button", {
6601
+ type: "button",
6602
+ className: "SPR_mapEdLayerHalf",
6603
+ "data-dir": "down",
6604
+ "aria-label": T("下一层"),
6605
+ disabled: safeLayerIndex <= 0,
6606
+ onClick: () => setLayerIndex(Math.max(0, safeLayerIndex - 1))
6607
+ }, h(MapToolIcon, { name: "down" }))), toolButton("grid", T("网格线"), T("显示或隐藏格线,方便数格子"), { icon: "grid", on: showGrid === true, onClick: () => setShowGrid(showGrid !== true) }), toolButton("gen", T("一键生成"), T("随机铺满 / 迷宫 / 大陆:用选中的图块一键铺满整层"), { icon: "magic", on: openCard === "gen", onClick: () => setOpenCard(openCard === "gen" ? null : "gen") }), toolButton("settings", T("设置"), T("地图大小、图层、帮助"), { icon: "settings", on: openCard === "settings", onClick: () => setOpenCard(openCard === "settings" ? null : "settings") }));
6608
+ const side = h("div", { className: "SPR_mapEdSide" }, h("div", { className: "SPR_mapEdSideTitle" }, T("素材调色板")), palette, tools);
6609
+ // ── 卡片:素材 / 导出 / 设置 / 一键生成 ──────────────────────────────
6610
+ const cardHead = (title) => h("div", { className: "SPR_mapEdCardHead" }, h("h4", null, title), h("span", { className: "SPR_mapEdSpacer" }), h("button", { type: "button", className: "SPR_mapEdCardClose", "aria-label": T("关闭"), onClick: () => setOpenCard(null) }, "×"));
6611
+ const row = (label, control, hint) => h("div", { className: "SPR_mapEdRow" }, h("span", { className: "SPR_mapEdLabel" }, label), control, hint === undefined || hint === "" ? null : h("span", { className: "SPR_mapEdRowHint" }, hint));
6612
+ /**
6613
+ * ⚠️ 卡片里**不再有「确定」按钮**(它曾经是「标记这一步看过了 + 收起卡片」)。
6614
+ *
6615
+ * 用户的判断很直接:「确定键可以删了,和右上角的 x 没区别」。这是对的 ——
6616
+ * 阶段标记在界面上**完全不可见**(上一版为了去掉「取消确认」把它做成了普通按钮,
6617
+ * 于是按与不按看起来一模一样),那么这颗按钮对用户就只剩「关掉卡片」这一个作用,
6618
+ * 和右上角那个 × 重复。
6619
+ *
6620
+ * 所以:关卡片只剩 ×;阶段标记仍可由验收流程 / 对话面(`setMapApproved`)改;
6621
+ * 界面上唯一还暴露它的地方是设置卡片里的「整个模块看过了」(那是一颗有状态按钮)。
6622
+ */
6623
+ const speedOptions = [
6624
+ ["0.5", T("慢")],
6625
+ ["1", T("中")],
6626
+ ["2", T("快")]
6627
+ ];
6628
+ const speedValue = String(animFps === null ? planMeta.fps : animFps);
6629
+ /**
6630
+ * 素材卡片 = **列表 + 新增 + 恢复默认**。
6631
+ *
6632
+ * 产品约定(用户定的):属性在「新增素材」那一刻填完就定死,之后**只能删掉重来** ——
6633
+ * 所以这张卡里没有任何「改格子 / 改形态 / 改动不动」的入口;内置素材同样在列表里、
6634
+ * 也能删,想拿回来点「恢复默认素材」(同名会跳过,不会变成两份)。
6635
+ */
6636
+ /**
6637
+ * 这张素材有几帧(列表上的徽章用)。
6638
+ *
6639
+ * 两种会动的情形都算进来:`a2quad` 的**变体就是帧**,`animRows`(翻页图)的**行数就是帧**
6640
+ * —— 宿主算好的 `variants` 在两种情形下都正好是帧数。
6641
+ */
6642
+ const frameCountOf = (entry) => entry.animRows === true ? entry.variants : entry.shape === "a2quad" && entry.variants > 1 ? entry.variants : 0;
6643
+ const assetsCard = h("div", { className: "SPR_mapEdCard", "data-testid": "map-assets-card" }, cardHead(T("素材")), h("div", { className: "SPR_mapEdCardRow" }, h(Btn, { primary: true, onClick: openAddTileset }, T("新增素材")), h(Btn, { onClick: () => void restoreSamples(), busy: busyKey === "sample" }, T("恢复默认素材"))), tilesets.length === 0
6644
+ ? h("p", { className: "SPR_mapEdHint" }, T("还没有素材。点「新增素材」加一张自己的,或者点「恢复默认素材」拿到自带的那套。"))
6645
+ : h("ul", { className: "SPR_mapEdTsList", "data-testid": "map-tileset-list" }, tilesets.map((entry, index) => h("li", { key: entry.id, className: "SPR_mapEdTsRow", "data-on": index === safeTsIndex ? "true" : undefined }, h("button", {
6646
+ type: "button",
6647
+ className: "SPR_mapEdTsPick",
6648
+ "data-tileset": entry.id,
6649
+ onClick: () => setTsIndex(index)
6650
+ }, h("span", { className: "SPR_mapEdTsName" }, entry.name), h("span", { className: "SPR_mapEdTsMeta" }, T("{n0}×{n1} · {n2} 块", { n0: String(entry.cell.width), n1: String(entry.cell.height), n2: String(entry.tileCount) })), frameCountOf(entry) > 0
6651
+ ? h("span", { className: "SPR_mapEdTsBadge", "data-anim": "true" }, T("会动 {n0} 帧", { n0: String(frameCountOf(entry)) }))
6652
+ : null, entry.builtin === true ? h("span", { className: "SPR_mapEdTsBadge" }, T("自带")) : null), h(Btn, { danger: true, onClick: () => void removeTilesetById(entry.id, entry.name) }, T("删除"))))), h("p", { className: "SPR_mapEdHint" }, T("素材的属性在新增时就定下来了,之后不能改 —— 要换就删掉重新新增。")));
6653
+ /**
6654
+ * 导出卡片 = **一次选完 → 一次导出 → 一次下载**。
6655
+ *
6656
+ * 老版本的坏处(用户原话:「导出功能窗口意味不明」):两个按钮并排,一个看着像
6657
+ * 页签、另一个点下去却是立即执行;导完给一堆文件链接却没有「存到哪」这件事;
6658
+ * 三个文件还得一个一个点。现在:
6659
+ *
6660
+ * 1. 内容用复选框选(勾几项都行),倍率只在勾了 PNG 时出现;
6661
+ * 2. 唯一的「导出」按钮执行;多份产物由宿主打成一个 zip,一次下载;
6662
+ * 3. 结果区写清「文件在哪」(本机绝对路径)+ 下载 / 另存为 / 打开导出目录。
6663
+ */
6664
+ const exportRows = [
6665
+ ["png", T("地图图片 PNG"), T("地图长什么样,直接能放进游戏")],
6666
+ ["json", T("存档数据 JSON"), T("每一格是什么,给引擎和工具读")],
6667
+ ["tilesets", T("素材原图"), T("把素材图一起拷进包里,换台机器也能用")]
6668
+ ];
6669
+ const exportNothingChosen = exportFormats.png !== true && exportFormats.json !== true && exportFormats.tilesets !== true;
6670
+ const zipFile = exportFiles.find((file) => isZip(file));
6671
+ const mainFile = zipFile ?? exportFiles.find((file) => file === "map.png") ?? exportFiles[0];
6672
+ // 排一下序:zip 在最前(它是「一次拿走全部」那一个),其余按产出顺序
6673
+ const listedFiles = exportFiles.slice().sort((a, b) => (isZip(a) === isZip(b) ? 0 : isZip(a) ? -1 : 1));
6674
+ const canSaveAs = typeof window !== "undefined" && typeof window.showSaveFilePicker === "function";
6675
+ const exportCard = h("div", { className: "SPR_mapEdCard", "data-testid": "map-export-card" }, cardHead(T("导出")), h("span", { className: "SPR_mapEdLabel" }, T("导出内容")), h("div", { className: "SPR_mapEdRows" }, exportRows.map(([key, label, hint]) => h("label", { key, className: "SPR_mapEdCheck", "data-testid": `map-export-row-${key}` }, h("input", {
6676
+ type: "checkbox",
6677
+ "data-testid": `map-export-${key}`,
6678
+ checked: exportFormats[key] === true,
6679
+ onChange: (event) => setExportFormats((current) => ({ ...current, [key]: event.target.checked }))
6680
+ }), label, h("span", { className: "SPR_mapEdTsMeta" }, hint)))), exportFormats.png === true
6681
+ ? row(T("倍率"), h("select", {
6682
+ className: "SPR_mapEdSelect",
6683
+ "data-testid": "map-export-scale",
6684
+ value: String(exportScale),
6685
+ onChange: (event) => setExportScale(Number(event.target.value))
6686
+ }, [1, 2, 3, 4].map((value) => h("option", { key: value, value: String(value) }, `${value}×`))), T("只影响 PNG 的尺寸,不影响存档数据"))
6687
+ : null, h("p", { className: "SPR_mapEdHint" }, T("产出不止一个文件时自动打成一个 ZIP;只有一个文件时就直接给你那个文件。")), h("div", { className: "SPR_mapEdCardRow" }, h(Btn, {
6688
+ primary: true,
6689
+ busy: busyKey === "export",
6690
+ disabled: exportNothingChosen,
6691
+ "data-testid": "map-export-run",
6692
+ onClick: () => void runExport()
6693
+ }, T("导出")), h(Btn, { onClick: () => void openExportFolder() }, T("打开导出目录"))), exportFiles.length === 0
6694
+ ? h("p", { className: "SPR_mapEdHint", "data-testid": "map-export-empty" }, T("还没有导出过。"))
6695
+ : h("div", { className: "SPR_mapEdExportResult", "data-testid": "map-export-result" }, h("span", { className: "SPR_mapEdLabel" }, T("最近一次导出:{n0} 个文件", { n0: String(exportFiles.length) })), mainFile === undefined
6696
+ ? null
6697
+ : h("div", { className: "SPR_mapEdCardRow" }, h("a", {
6698
+ className: "SPR_btn",
6699
+ "data-primary": "true",
6700
+ "data-testid": "map-export-download",
6701
+ href: exportUrlOf(mainFile),
6702
+ download: baseNameOf(mainFile),
6703
+ // 与别处的「下载」按钮同款:`<a>` 当按钮用,去掉下划线
6704
+ style: { textDecoration: "none" }
6705
+ }, T("下载 {n0}", { n0: baseNameOf(mainFile) })), canSaveAs
6706
+ ? h(Btn, { "data-testid": "map-export-save-as", onClick: () => void saveAsExport(mainFile) }, T("另存为…"))
6707
+ : null), h("p", { className: "SPR_mapEdHint" }, canSaveAs
6708
+ ? T("下载走浏览器(默认进它的下载目录);想自己挑位置就点「另存为…」。")
6709
+ : T("下载走浏览器:文件会进它的下载目录(想每次都自己挑位置,在浏览器里打开「下载前询问保存位置」)。")), h("ul", { className: "SPR_mapEdFiles", "data-testid": "map-export-files" }, listedFiles.map((file) => h("li", { key: file }, h("a", { href: exportUrlOf(file), download: baseNameOf(file), "data-testid": `map-export-file-${baseNameOf(file)}` }, file), isZip(file) ? h("span", { className: "SPR_mapEdTsBadge", "data-anim": "true" }, T("打包,含全部内容")) : null))), h("p", { className: "SPR_mapEdHint", "data-testid": "map-export-path" }, T("文件都在 {n0}", { n0: view.exportPath === "" ? "—" : String(view.exportPath) }))));
6710
+ const settingsCard = h("div", { className: "SPR_mapEdCard" }, cardHead(T("设置")), row(T("地图大小"), h("div", { className: "SPR_mapEdPair" }, h(NumField, { label: T("宽"), value: view.cols, min: 1, max: 512, onChange: (value) => void applyMapSize(value, view.rows) }), h("span", { className: "SPR_mapEdTimes" }, "×"), h(NumField, { label: T("高"), value: view.rows, min: 1, max: 512, onChange: (value) => void applyMapSize(view.cols, value) })), T("单位是格。改大只是多出空地;改小会丢掉范围外的格子(可撤销)")), row(T("动画速度"), h("select", {
6711
+ className: "SPR_mapEdSelect",
6712
+ "data-testid": "map-anim-speed",
6713
+ value: speedValue,
6714
+ onChange: (event) => setAnimFps(Number(event.target.value))
6715
+ }, speedOptions.map(([value, label]) => h("option", { key: value, value }, `${label} · ${value} 帧/秒`))), T("只影响会动的素材(水、翻页图这类)")), h("div", { className: "SPR_mapEdCardRow" }, h(Btn, { onClick: () => void saveDoc({ addLayer: { name: T("图层 {n0}", { n0: String(layers.length + 1) }) } }, T("已加一层")) }, T("加一层")), h(Btn, {
6716
+ disabled: layers.length <= 1,
6717
+ title: layers.length <= 1 ? T("至少要留一层") : T("删掉当前这一层"),
6718
+ onClick: () => void saveDoc({ removeLayerId: activeLayer.id }, T("已删掉这一层"))
6719
+ }, T("删一层")), h(Btn, { onClick: () => void clearLayer() }, T("清空当前图层"))), h("label", { className: "SPR_mapEdCheck" }, h("input", { type: "checkbox", checked: showGrid === true, onChange: (event) => setShowGrid(event.target.checked) }), T("网格线")), h("div", { className: "SPR_mapEdHelp" }, h("h5", null, T("帮助")), h("p", null, T("左键拖动=用当前工具画;空格拖动或中键拖动=平移;滚轮=缩放;右键=橡皮。")), h("p", null, T("调色板里点一下选一块图当笔刷,按住 Shift 或 Ctrl 可以多选,「一键生成」会用这些图块。")), h("p", null, T("地图四周是接上的:自动连接会把上下、左右两边接起来。画布拖不出地图 —— 拖到边就停,地图左上角对齐后不会再乱动;图外那片空白画不上。"))), h("div", { className: "SPR_mapEdCardRow" }, h(Btn, { onClick: () => void withApi(() => api.revealMapProject({ projectId: view.id })) }, T("在访达中打开项目目录")), h(Btn, { primary: true, on: approvedAll === true, onClick: () => void markWholeModuleSeen() }, T("整个模块看过了"))));
6720
+ const genTiles = multi.length > 0 ? multi : brush === null ? [] : [brush.index];
6721
+ const genCard = h("div", { className: "SPR_mapEdCard" }, cardHead(T("一键生成")), h("div", { className: "SPR_mapEdRadios" }, [
6722
+ ["random", T("随机铺满")],
6723
+ ["maze", T("迷宫")],
6724
+ ["continent", T("大陆")]
6725
+ ].map(([value, label]) => h("label", { key: value, className: "SPR_mapEdRadio" }, h("input", { type: "radio", name: "map-gen-kind", checked: genKind === value, onChange: () => setGenKind(value) }), label))), h("p", { className: "SPR_mapEdHint" }, genTiles.length === 0
6726
+ ? T("用的图块:还没选。在左边点一下选一块,按住 Shift 或 Ctrl 可以多选。")
6727
+ : T("用的图块:{n0}", { n0: genTiles.join("、") })), h("p", { className: "SPR_mapEdHint" }, genKind === "maze"
6728
+ ? T("迷宫:按顺序取两块,第一块当墙,第二块当路。")
6729
+ : genKind === "continent"
6730
+ ? T("大陆:按顺序取最多四块当四种地貌(水下 / 海面 / 草地 / 雪地)。")
6731
+ : T("随机铺满:在选中的图块里均匀随机。")), h("div", { className: "SPR_mapEdCardRow" }, h(NumField, { label: T("种子"), value: genSeed, onChange: (value) => setGenSeed(value) }), h(Btn, { onClick: () => setGenSeed(Math.floor(Math.random() * 1000000)) }, T("换一组")), h(Btn, { primary: true, busy: busyKey === "gen", onClick: () => void runGenerate() }, T("生成"))));
6732
+ const openCardNode = openCard === "assets" ? assetsCard : openCard === "export" ? exportCard : openCard === "settings" ? settingsCard : openCard === "gen" ? genCard : null;
6733
+ const canvas = h("canvas", {
6734
+ ref: bindCanvas,
6735
+ className: "SPR_mapEdCanvas",
6736
+ "data-testid": "map-canvas",
6737
+ onPointerDown,
6738
+ onPointerMove,
6739
+ onPointerUp,
6740
+ onPointerLeave: () => {
6741
+ strokeRef.current = null;
6742
+ currentStroke.current = null;
6743
+ setHover(null);
6744
+ void flushOps();
6745
+ },
6746
+ // ⚠️ 少了 onPointerCancel:指针被系统取消(触摸 / 手写笔被打断、指针捕获丢失)
6747
+ // 时 `strokeRef` 不清,之后**在没按键的情况下**一次普通 pointermove 就会继续涂抹,
6748
+ // 而且每段还各算一步撤销。`onPointerLeave` 兜不住「留在画布内被取消」这种。
6749
+ onPointerCancel: () => {
6750
+ strokeRef.current = null;
6751
+ currentStroke.current = null;
6752
+ setHover(null);
6753
+ void flushOps();
6754
+ },
6755
+ onContextMenu: (event) => event.preventDefault()
6756
+ });
6757
+ // 工具小标签:挂在面板根节点下、`position:fixed`,所以不会被任何祖先的 overflow 裁掉。
6758
+ const toolTipNode = toolTip === null
6759
+ ? null
6760
+ : h("div", {
6761
+ className: "SPR_mapEdTip",
6762
+ role: "tooltip",
6763
+ "data-tip": toolTip.name,
6764
+ style: { left: `${toolTip.x}px`, top: `${toolTip.y}px` }
6765
+ }, h("div", { className: "SPR_mapEdTipName" }, toolTip.name, toolTip.shortcut === null ? null : h("span", { className: "SPR_mapEdTipKey" }, toolTip.shortcut)), h("div", { className: "SPR_mapEdTipDesc" }, toolTip.desc));
6766
+ return shell(h("div", { className: "SPR_mapEdRoot" }, topBar, openCardNode === null ? null : h("div", { className: "SPR_mapEdCardWrap" }, openCardNode), h("div", { className: "SPR_mapEdBody" }, side, h("div", { className: "SPR_mapEdStage", ref: stageRef }, canvas, truncated === true ? h("div", { className: "SPR_mapEdToast" }, T("缩得太小,放大一点。")) : null, view.busy === true ? h("div", { className: "SPR_mapEdToast", "data-busy": "true" }, T("任务进行中…")) : null)), h("div", { className: "SPR_mapEdFoot" }, notice === null ? null : h("div", { className: `SPR_notice SPR_notice-${notice.kind}` }, notice.text), planWarnings.length === 0
6767
+ ? null
6768
+ : h("ul", { className: "SPR_mapEdWarnings" }, planWarnings.map((text, index) => h("li", { key: index }, text))), h("span", { className: "SPR_mapEdSpacer" }), single === true || activeLayer === null
6769
+ ? null
6770
+ : h("span", { className: "SPR_mapEdFootText" }, T("第 {n0} 层 / 共 {n1} 层", { n0: String(safeLayerIndex + 1), n1: String(layers.length) }))),
6771
+ // 隐藏的图源:canvas 拿它们当 drawImage 的源(避免再建一份缓存)
6772
+ h("div", { style: { display: "none" } }, tilesets.map((entry) => h("img", {
6773
+ key: entry.id,
6774
+ "data-tileset": entry.id,
6775
+ ref: (node) => {
6776
+ imageRefs.current[entry.id] = node;
6777
+ },
6778
+ src: `${assetBase}${entry.file}`,
6779
+ alt: "",
6780
+ onLoad: () => setImagesReady((value) => value + 1),
6781
+ // ⚠️ 只挂 onLoad 不挂 onError 的话,素材图 404 / 解码失败时
6782
+ // `imagesReady` 永远不递增,这张素材的格子**一条都不画**:
6783
+ // 画布静默空白、界面零提示(只有调试钩子的 noImage 看得到)。
6784
+ onError: () => {
6785
+ setImagesReady((value) => value + 1);
6786
+ setNotice({ kind: "error", text: T("素材图加载失败:{n0}(试试重新上传这张图)", { n0: entry.name }) });
6787
+ }
6788
+ }))), toolTipNode, nameDialog));
4127
6789
  }
4128
6790
  // ── 模块②:图片生成 ─────────────────────────────────────────────────
4129
6791
  /** 模块②的 pending key:整批生成、单张重生成、抠像、上传、新建任务。 */
@@ -5934,11 +8596,16 @@ window.__ModuleLoader__.load({
5934
8596
  return invoke();
5935
8597
  return tasks.run(feedback.key, feedback.label, invoke);
5936
8598
  };
5937
- const create = () => run(async () => {
5938
- const created = await api.createImageJob({ name: T("图片 {n0}", { n0: new Date().toLocaleString("zh-CN", { hour12: false }) }) });
5939
- await refresh();
5940
- setJobId(created.jobId);
5941
- }, T("已新建图片任务"), { key: K_IMG_CREATE, label: T("正在新建任务…") });
8599
+ const create = async () => {
8600
+ const name = askNewName(T("新图片任务的名字"), T("图片 {n0}", { n0: new Date().toLocaleString("zh-CN", { hour12: false }) }));
8601
+ if (name === null)
8602
+ return;
8603
+ await run(async () => {
8604
+ const created = await api.createImageJob({ name });
8605
+ await refresh();
8606
+ setJobId(created.jobId);
8607
+ }, T("已新建图片任务"), { key: K_IMG_CREATE, label: T("正在新建任务…") });
8608
+ };
5942
8609
  const saveJob = (patch) => run(() => api.saveImageJob({ jobId: job.id, ...patch }), T("已保存"));
5943
8610
  const del = async () => {
5944
8611
  if (job === null)
@@ -6034,6 +8701,12 @@ window.__ModuleLoader__.load({
6034
8701
  : h("div", { className: "SPR_grid" }, (job.items ?? []).map((item, index) => {
6035
8702
  const itemKey = K_IMG_ITEM(index);
6036
8703
  const itemBusy = item.status === "running" || tasks.has(itemKey);
8704
+ // 生成的原图(未抠像时就是唯一产物)也要能存下来:
8705
+ // 之前只有「抠像结果」给了下载链接,抠像关掉后整张卡片
8706
+ // 只剩 通过 / 重新生成 / 删除,用户只能右键另存。
8707
+ const rawExt = typeof item.file === "string" && item.file.includes(".")
8708
+ ? item.file.slice(item.file.lastIndexOf(".") + 1).toLowerCase()
8709
+ : "png";
6037
8710
  // 整批生成时,还没轮到的那些也要盖住(否则旧图看着像「没反应」)
6038
8711
  const waiting = item.status !== "running" && tasks.has(K_IMG_JOB);
6039
8712
  const keyingNow = item.status !== "running" && tasks.has(K_IMG_KEY);
@@ -6050,7 +8723,9 @@ window.__ModuleLoader__.load({
6050
8723
  approved: item.approved === true,
6051
8724
  disabled: overlay || item.status !== "ready",
6052
8725
  onToggle: () => void run(() => api.saveImageJob({ jobId: job.id, index, approved: item.approved !== true }), item.approved === true ? T("已取消通过") : T("已标记通过"))
6053
- }), item.keyedFile !== undefined
8726
+ }), item.file !== undefined
8727
+ ? h("a", { className: "SPR_btn", href: `${job.assetBase}${item.file}`, download: `image-${index + 1}.${rawExt}`, style: { textDecoration: "none" } }, T("下载原图"))
8728
+ : null, item.keyedFile !== undefined
6054
8729
  ? h("a", { className: "SPR_btn", href: `${job.assetBase}${item.keyedFile}`, download: `keyed-${index + 1}.png`, style: { textDecoration: "none" } }, T("下载 PNG"))
6055
8730
  : null, item.source === "generated"
6056
8731
  ? h(BusyBtn, {
@@ -6200,11 +8875,16 @@ window.__ModuleLoader__.load({
6200
8875
  }
6201
8876
  return value;
6202
8877
  };
6203
- const create = () => run(async () => {
6204
- const created = await api.createSequenceJob({ name: T("序列帧 {n0}", { n0: new Date().toLocaleString("zh-CN", { hour12: false }) }) });
6205
- await refresh();
6206
- setJobId(created.jobId);
6207
- }, T("已新建序列帧任务"), { key: K_SEQ_CREATE, label: T("正在新建任务…") });
8878
+ const create = async () => {
8879
+ const name = askNewName(T("新序列帧任务的名字"), T("序列帧 {n0}", { n0: new Date().toLocaleString("zh-CN", { hour12: false }) }));
8880
+ if (name === null)
8881
+ return;
8882
+ await run(async () => {
8883
+ const created = await api.createSequenceJob({ name });
8884
+ await refresh();
8885
+ setJobId(created.jobId);
8886
+ }, T("已新建序列帧任务"), { key: K_SEQ_CREATE, label: T("正在新建任务…") });
8887
+ };
6208
8888
  const saveJob = (patch) => run(() => api.saveSequenceJob({ jobId: job.id, ...patch }), undefined);
6209
8889
  const del = async () => {
6210
8890
  if (job === null)
@@ -6629,7 +9309,13 @@ window.__ModuleLoader__.load({
6629
9309
  return null;
6630
9310
  const sem = job.semantics ?? { errors: [], warnings: [], ok: true, ready: false, confirmed: false, count: 0 };
6631
9311
  const names = parts.map((part) => part.name);
6632
- const patch = (name, fields) => void run(() => api.setRigSemantics({ jobId: job.id, parts: [{ name, ...fields }], by: "human" }), T("已更新「{n0}」的语义", { n0: name }), activeKey);
9312
+ const patch = (name, fields) => void run(async () => {
9313
+ const result = await api.setRigSemantics({ jobId: job.id, parts: [{ name, ...fields }], by: "human" });
9314
+ if (result?.ok === false) {
9315
+ throw new Error((result.errors ?? []).map((issue) => issue.message).join(";") || T("语义校验失败"));
9316
+ }
9317
+ return result;
9318
+ }, T("已更新「{n0}」的语义", { n0: name }), activeKey);
6633
9319
  const anchorField = (part, key, index) => h(NumField, {
6634
9320
  key: `${part.name}:${key}:${index}`,
6635
9321
  label: T("{n0}{n1}", { n0: key === "proximal" ? T("近端") : T("远端"), n1: index === 0 ? "x" : "y" }),
@@ -7196,7 +9882,7 @@ window.__ModuleLoader__.load({
7196
9882
  label: "",
7197
9883
  value: entry.chain,
7198
9884
  min: 1,
7199
- max: 4,
9885
+ max: 1,
7200
9886
  step: 1,
7201
9887
  onChange: (value) => write([{ name: entry.name, bone: entry.bone, target: entry.target, chain: value, bendPositive: entry.bendPositive, weight: entry.weight }], T("已改「{n0}」的链长", { n0: entry.name }))
7202
9888
  })), h("td", null, h(Btn, {
@@ -8288,7 +10974,7 @@ window.__ModuleLoader__.load({
8288
10974
  * 「不再提示」,进 45° 地图地块时弹窗就再也不出现了 —— 两个模块的
8289
10975
  * 实验性说明内容完全不同,那样等于静默漏掉一次告知。
8290
10976
  */
8291
- const experimentalGateMuted = { rig: false, tile: false };
10977
+ const experimentalGateMuted = { rig: false, tile: false, map: false };
8292
10978
  /**
8293
10979
  * 实验性说明弹窗(模块④ / ⑤ 共用)。
8294
10980
  *
@@ -8345,6 +11031,16 @@ window.__ModuleLoader__.load({
8345
11031
  onClose
8346
11032
  });
8347
11033
  }
11034
+ /** 进入模块⑥时的实验性说明弹窗(地图编辑器)。 */
11035
+ function MapExperimentalDialog({ onClose }) {
11036
+ return h(ExperimentalDialog, {
11037
+ moduleKey: "map",
11038
+ title: T("地图编辑器仍在开发中"),
11039
+ ariaLabel: T("地图编辑器(实验性)"),
11040
+ points: MAP_EXPERIMENTAL_POINTS,
11041
+ onClose
11042
+ });
11043
+ }
8348
11044
  /**
8349
11045
  * 模块④的主体界面。
8350
11046
  *
@@ -8482,13 +11178,18 @@ window.__ModuleLoader__.load({
8482
11178
  const label = RIG_BUSY_LABEL[feedback] ?? (feedback.startsWith("rig:relayout") ? T("正在重新定位…") : T("正在处理…"));
8483
11179
  return tasks.run(feedback, label, invoke);
8484
11180
  };
8485
- const createJob = () => run(async () => {
8486
- const created = await api.createRigJob({ name: T("新骨骼动画任务") });
8487
- await refresh();
8488
- setJobId(created.jobId);
8489
- setStage("parts");
8490
- return created;
8491
- }, T("已新建骨骼动画任务"), K_RIG_CREATE);
11181
+ const createJob = async () => {
11182
+ const name = askNewName(T("新骨骼动画任务的名字"), T("新骨骼动画任务"));
11183
+ if (name === null)
11184
+ return;
11185
+ await run(async () => {
11186
+ const created = await api.createRigJob({ name });
11187
+ await refresh();
11188
+ setJobId(created.jobId);
11189
+ setStage("parts");
11190
+ return created;
11191
+ }, T("已新建骨骼动画任务"), K_RIG_CREATE);
11192
+ };
8492
11193
  const deleteJob = async () => {
8493
11194
  if (job === null)
8494
11195
  return;
@@ -8738,7 +11439,11 @@ window.__ModuleLoader__.load({
8738
11439
  if (api === undefined)
8739
11440
  return;
8740
11441
  try {
8741
- setConfig(await api.getConfig());
11442
+ const next = await api.getConfig();
11443
+ setConfig(next);
11444
+ // 可见性是全插件共享的状态(侧栏菜单 / 工作台页签都订阅它),
11445
+ // 每次读到配置就广播一次——包括保存后的重读。
11446
+ publishHiddenModules(next?.hiddenModules);
8742
11447
  }
8743
11448
  catch (error) {
8744
11449
  setNotice({ kind: "error", text: msg(error) });
@@ -8763,6 +11468,18 @@ window.__ModuleLoader__.load({
8763
11468
  return h("section", { className: "SPR_settings" }, h("p", { className: "SPR_hint" }, T("正在载入配置…")));
8764
11469
  }
8765
11470
  const patch = (values) => run(() => api.saveConfig(values), T("配置已保存"));
11471
+ /**
11472
+ * 功能管理:`hiddenModules` 的当前值(以宿主返回的为准)。
11473
+ *
11474
+ * 勾选立刻**乐观广播**一次,再落盘——工作台页签与侧栏菜单是另一个组件,
11475
+ * 等一个来回才变的话,用户会看到「勾了但菜单里还在」。
11476
+ */
11477
+ const hiddenNow = normalizeHiddenKeys(config.hiddenModules);
11478
+ const toggleFeature = (key, visible) => {
11479
+ const next = MODULES.map((entry) => entry.key).filter((item) => (item === key ? !visible : hiddenNow.includes(item)));
11480
+ publishHiddenModules(next);
11481
+ void patch({ hiddenModules: next });
11482
+ };
8766
11483
  // 模型能力决定分辨率档位与时长控件形态;切换模型后宿主会重新收敛,
8767
11484
  // 这里始终以「当前模型」的能力为准,避免下拉里出现非法档位。
8768
11485
  const minimaxCaps = config.minimaxCapabilitiesByModel?.[config.minimaxModel] ??
@@ -8959,7 +11676,26 @@ window.__ModuleLoader__.load({
8959
11676
  min: 0,
8960
11677
  max: 64,
8961
11678
  onChange: (value) => void patch({ bottomMargin: value })
8962
- }))), h("div", { className: "SPR_settingsGroup" }, h("h3", null, T("数据位置")), h("p", null, T("所有项目(源图、绿幕图、视频、序列帧、整图)都保存在:"), h("code", null, config.dataRoot)), h("div", { className: "SPR_toolbar" }, h(Btn, { onClick: () => void run(() => api.saveConfig({}), T("已刷新")) }, T("重新读取配置")))));
11679
+ }))), h("div", { className: "SPR_settingsGroup" }, h("h3", null, T("功能管理")), h("p", null, T("隐藏不用的功能。隐藏后界面里不再出现它的页签与侧栏菜单项,对话里的 AI 也无法调用它(工具会直接报错)。随时可以再打开,已有的项目数据不会被删除。")), h("div", { className: "SPR_featureList" }, MODULES.map((entry) => {
11680
+ const isHidden = hiddenNow.includes(entry.key);
11681
+ return h("label", {
11682
+ key: entry.key,
11683
+ className: "SPR_featureRow",
11684
+ "data-hidden": isHidden ? "true" : "false",
11685
+ "data-feature": entry.key
11686
+ }, h("input", {
11687
+ type: "checkbox",
11688
+ className: "SPR_featureCheck",
11689
+ "data-testid": `cfg-feature-${entry.key}`,
11690
+ checked: !isHidden,
11691
+ onChange: (event) => toggleFeature(entry.key, event.target.checked)
11692
+ }), h("span", { className: "SPR_featureText" }, h("span", { className: "SPR_featureTitle" }, entry.title, entry.experimental === true ? h("span", { className: "SPR_expTag" }, T("实验性")) : null), h("span", { className: "SPR_featureHint" }, entry.hint)), h("span", { className: "SPR_featureState" }, isHidden ? T("已隐藏") : T("显示中")));
11693
+ })), hiddenNow.length === 0
11694
+ ? h("p", { className: "SPR_hint" }, T("当前功能全部可见。"))
11695
+ : h("p", { className: "SPR_hint" }, T("已隐藏 {n0} 个功能:{n1}。隐藏的模块在对话里同样不可调用。", {
11696
+ n0: hiddenNow.length,
11697
+ n1: MODULES.filter((entry) => hiddenNow.includes(entry.key)).map((entry) => entry.title).join("、")
11698
+ }))), h("div", { className: "SPR_settingsGroup" }, h("h3", null, T("数据位置")), h("p", null, T("所有项目(源图、绿幕图、视频、序列帧、整图)都保存在:"), h("code", null, config.dataRoot)), h("div", { className: "SPR_toolbar" }, h(Btn, { onClick: () => void run(() => api.saveConfig({}), T("已刷新")) }, T("重新读取配置")))));
8963
11699
  }
8964
11700
  // ── cordis 插件体 ────────────────────────────────────────────────────
8965
11701
  const inject = ["slots", "remote"];
@@ -9111,7 +11847,28 @@ window.__ModuleLoader__.load({
9111
11847
  saveTileMapCells: (payload) => call("saveTileMapCells", payload),
9112
11848
  runTileExport: (payload) => call("runTileExport", payload),
9113
11849
  cancelTileJob: (payload) => call("cancelTileJob", payload),
9114
- revealTileProject: (payload) => call("revealTileProject", payload)
11850
+ revealTileProject: (payload) => call("revealTileProject", payload),
11851
+ // 地图编辑器(模块六):全本地,没有一步收费
11852
+ listMapProjects: () => call("listMapProjects"),
11853
+ createMapProject: (payload) => call("createMapProject", { lang: activeLang(), ...payload }),
11854
+ getMapProject: (payload) => call("getMapProject", { lang: activeLang(), ...payload }),
11855
+ saveMapProject: (payload) => call("saveMapProject", payload),
11856
+ deleteMapProject: (payload) => call("deleteMapProject", payload),
11857
+ importMapTileset: (payload) => call("importMapTileset", payload),
11858
+ importSampleTileset: (payload) => call("importSampleTileset", payload),
11859
+ saveMapTileset: (payload) => call("saveMapTileset", payload),
11860
+ removeMapTileset: (payload) => call("removeMapTileset", payload),
11861
+ saveMapDoc: (payload) => call("saveMapDoc", payload),
11862
+ applyMapOps: (payload) => call("applyMapOps", payload),
11863
+ mapUndo: (payload) => call("mapUndo", payload),
11864
+ mapRedo: (payload) => call("mapRedo", payload),
11865
+ mapPlan: (payload) => call("mapPlan", payload),
11866
+ runMapGenerate: (payload) => call("runMapGenerate", payload),
11867
+ runMapPreview: (payload) => call("runMapPreview", payload),
11868
+ runMapExport: (payload) => call("runMapExport", payload),
11869
+ cancelMapJob: (payload) => call("cancelMapJob", payload),
11870
+ setMapApproved: (payload) => call("setMapApproved", payload),
11871
+ revealMapProject: (payload) => call("revealMapProject", payload)
9115
11872
  };
9116
11873
  // ── 深链接:会话里的链接点一下切到本插件页面 ─────────────────────
9117
11874
  // 拦截器与生命周期绑定:插件停止 / 更新时监听器一定被摘掉。
@@ -9130,11 +11887,14 @@ window.__ModuleLoader__.load({
9130
11887
  return () => { };
9131
11888
  }, T("{n0}: 深链接引导", { n0: PACKAGE }));
9132
11889
  // 侧栏全局面板图标;id 与 main 的 key 必须一致,点击即切到工作台。
11890
+ // 额外注入 api / studioCtx:图标右下角的菜单按钮要靠它们读可见性、
11891
+ // 并在选中某一项时切到对应模块(`openStudioIntent`)。
9133
11892
  ctx.slots.inject("sidebar.panellist", () => ctx.slots.register({
9134
11893
  name: "sidebar.panellist",
9135
11894
  id: GAME_STUDIO_PANEL_ID,
9136
11895
  order: 40,
9137
- label: () => T("游戏素材大师")
11896
+ label: () => T("游戏素材大师"),
11897
+ inject: () => ({ api, studioCtx: ctx })
9138
11898
  }, StudioGlyph));
9139
11899
  ctx.slots.inject("main", () => ctx.slots.register({
9140
11900
  name: "main",
@@ -9154,7 +11914,14 @@ window.__ModuleLoader__.load({
9154
11914
  bundleModule.exports.GAME_STUDIO_PANEL_ID = GAME_STUDIO_PANEL_ID;
9155
11915
  // 仅测试用把手:三个模块组件在工厂闭包里,脚本要能拿出来单独渲染
9156
11916
  // (见 scripts/verify-feedback.mjs)。运行时没有任何调用点。
9157
- bundleModule.exports.__test = { StudioPanel, TileModule, ImageModule, SequenceModule, usePendingTasks, LoadingOverlay, MediaBox, BusyBtn, BusyBadge, NumField, ZoomableImage, CSS, subscribeIntent, parseIntents, openStudioIntent, OPEN_QUERY_KEY };
11917
+ /**
11918
+ * 给自检用的把手。
11919
+ *
11920
+ * `MAP_*` 那几个是**只读的坐标函数**:`verify-map-client.mjs` 拿宿主
11921
+ * `mapgeom` / `mapdoc` 的真实现做黄金对照逐点比对 —— 界面复刻的那部分几何
11922
+ * 必须有守门的,否则「预览与导出错位」会以静默的方式回来。
11923
+ */
11924
+ bundleModule.exports.__test = { StudioPanel, TileModule, ImageModule, SequenceModule, RigSemanticsPanel, MapModule, MapExperimentalDialog, MAP_pointToCell, MAP_cellAnchor, MAP_cellTopLeft, MAP_lineCells, usePendingTasks, LoadingOverlay, MediaBox, BusyBtn, BusyBadge, NumField, ZoomableImage, CSS, subscribeIntent, parseIntents, openStudioIntent, OPEN_QUERY_KEY, StudioGlyph, StudioGlyphIcon, publishHiddenModules, useHiddenModules, visibleModulesOf, normalizeHiddenKeys, ConfigSection };
9158
11925
  return bundleModule.exports;
9159
11926
  }
9160
11927
  });