diff --git a/ComposeRemoteServer/k8s/deploy.yaml b/ComposeRemoteServer/k8s/deploy.yaml index 2237c62..344e28c 100644 --- a/ComposeRemoteServer/k8s/deploy.yaml +++ b/ComposeRemoteServer/k8s/deploy.yaml @@ -22,7 +22,7 @@ spec: spec: containers: - name: server - image: composeremote/server:1.0.0-editor5 + image: composeremote/server:1.0.0-editor6 imagePullPolicy: Never ports: - name: http diff --git a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/LayoutAdminController.java b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/LayoutAdminController.java index 587ebb8..76bf43b 100644 --- a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/LayoutAdminController.java +++ b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/LayoutAdminController.java @@ -9,50 +9,61 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * 布局编辑接口,供后台拖拽编辑器读写。 * - *

布局以 JSON 落盘(目录由 {@code app.layout-dir} / {@code LAYOUT_DIR} 指定), - * 保存后下一次 {@code GET /api/remote-ui/{page}} 就会编译新布局下发。 - * 当前演示环境不鉴权。 + *

布局以 JSON 落盘(目录由 {@code app.layout-dir} / {@code LAYOUT_DIR} 指定)。 + * 保存只写草稿,发布后才生效:{@code GET /api/remote-ui/{page}} 编译的是已发布布局, + * 编辑器看到的是草稿(没有草稿时回落到已发布)。当前演示环境不鉴权。 */ @RestController @RequestMapping("/api/layouts") public class LayoutAdminController { - /** 布局列表,编辑器启动时用来发现页面。 */ + /** 布局列表,编辑器启动时用来发现页面;{@code draft} 标记该页面存在未发布草稿。 */ @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public List list() { - return LayoutStore.INSTANCE.all().stream() - .map(document -> new LayoutSummary( - document.getId(), - document.getTitle(), - document.getItems().size() + return LayoutStore.INSTANCE.summaries().stream() + .map(summary -> new LayoutSummary( + summary.getId(), + summary.getTitle(), + summary.getItems(), + summary.getDraft() )) .toList(); } - /** 读取单个布局;不存在返回 404。 */ + /** 读取单个布局(优先草稿);不存在返回 404。 */ @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public LayoutDocument get(@PathVariable("id") String id) { - LayoutDocument document = LayoutStore.INSTANCE.get(id); - if (document == null) { + public Map get(@PathVariable("id") String id) { + LayoutStore.EditableLayout editable = LayoutStore.INSTANCE.getEditable(id); + if (editable == null) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "布局不存在: " + id); } - return document; + LayoutDocument document = editable.getDocument(); + Map body = new LinkedHashMap<>(); + body.put("id", document.getId()); + body.put("title", document.getTitle()); + body.put("canvas", document.getCanvas()); + body.put("backgroundColor", document.getBackgroundColor()); + body.put("items", document.getItems()); + body.put("draft", editable.getDraft()); + return body; } /** - * 保存布局。 + * 保存草稿。 * *

以路径上的 id 为准,避免请求体里的 id 与路径不一致; * 校验失败返回 400,错误信息是直接给编辑器展示的中文提示。 @@ -76,6 +87,52 @@ public class LayoutAdminController { return ResponseEntity.ok(document); } + /** 发布草稿:把旧版本归档后覆盖已发布布局;页面完全不存在时返回 404。 */ + @PostMapping(value = "/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity publish(@PathVariable("id") String id) { + LayoutDocument document; + try { + document = LayoutStore.INSTANCE.publish(id); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body(Map.of("error", e.getMessage())); + } + if (document == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "布局不存在: " + id); + } + return ResponseEntity.ok(document); + } + + /** 放弃草稿,回落到已发布布局;没有草稿返回 404。 */ + @DeleteMapping("/{id}/draft") + public ResponseEntity discardDraft(@PathVariable("id") String id) { + if (!LayoutStore.INSTANCE.discardDraft(id)) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "草稿不存在: " + id); + } + return ResponseEntity.noContent().build(); + } + + /** 历史版本列表(时间倒序,最多 20 条)。 */ + @GetMapping(value = "/{id}/versions", produces = MediaType.APPLICATION_JSON_VALUE) + public List versions(@PathVariable("id") String id) { + return LayoutStore.INSTANCE.versions(id); + } + + /** 把历史版本恢复成草稿,返回恢复后的文档。 */ + @PostMapping(value = "/{id}/versions/{version}/restore", + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity restore(@PathVariable("id") String id, + @PathVariable("version") String version) { + try { + LayoutDocument document = LayoutStore.INSTANCE.restore(id, version); + if (document == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "版本不存在: " + version); + } + return ResponseEntity.ok(document); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body(Map.of("error", e.getMessage())); + } + } + /** 删除布局;默认桌面不允许删除,避免客户端首页无布局可编译。 */ @DeleteMapping("/{id}") public ResponseEntity delete(@PathVariable("id") String id) { @@ -89,6 +146,6 @@ public class LayoutAdminController { } /** 布局摘要。 */ - public record LayoutSummary(String id, String title, int items) { + public record LayoutSummary(String id, String title, int items, boolean draft) { } } diff --git a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java index c51a666..bf023ee 100644 --- a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java +++ b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java @@ -9,6 +9,7 @@ import org.springframework.http.CacheControl; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -20,6 +21,8 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.web.server.ResponseStatusException; import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -28,10 +31,13 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; +import java.util.Comparator; import java.util.HexFormat; +import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -176,6 +182,103 @@ public class RemoteUIController { } } + /** + * 图片资源库:列出上传目录里的所有图片。 + * + *

只读外部资源目录({@code app.assets-dir}),classpath 内置图片不参与管理。 + * 尺寸通过 ImageReader 只读文件头,不会把整张图解码进内存。 + */ + @GetMapping(value = "/assets", produces = MediaType.APPLICATION_JSON_VALUE) + public List listAssets() throws IOException { + Path directory = Path.of(assetsDir).toAbsolutePath().normalize(); + if (!Files.isDirectory(directory)) { + return List.of(); + } + try (var stream = Files.list(directory)) { + return stream.filter(Files::isRegularFile) + .filter(path -> UPLOAD_EXTENSIONS.contains(extensionOf(path.getFileName().toString()))) + .sorted(Comparator + .comparingLong((Path path) -> lastModified(path)).reversed() + .thenComparing(path -> path.getFileName().toString())) + .map(this::assetInfo) + .filter(Objects::nonNull) + .toList(); + } + } + + /** + * 删除资源库里的图片。 + * + *

只要还有布局(已发布或草稿)的图片组件引用它,就返回 400 并列出页面, + * 避免线上页面出现空白图片。 + */ + @DeleteMapping(value = "/assets/{name:.+}", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity deleteAsset(@PathVariable("name") String name) { + if (!name.matches("[A-Za-z0-9._-]+")) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND); + } + List pages = LayoutStore.INSTANCE.pagesReferencingAsset(name); + if (!pages.isEmpty()) { + return ResponseEntity.badRequest().body(Map.of( + "error", "图片仍被页面 " + String.join("、", pages) + " 引用,请先替换后再删除", + "pages", pages + )); + } + try { + Path directory = Path.of(assetsDir).toAbsolutePath().normalize(); + Path file = directory.resolve(name).normalize(); + if (!file.startsWith(directory) || !Files.isRegularFile(file)) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "图片不存在: " + name); + } + Files.delete(file); + return ResponseEntity.noContent().build(); + } catch (IOException e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(Map.of("error", "图片删除失败: " + e.getMessage())); + } + } + + /** 单个资源信息;读不到尺寸时宽高记为 0。 */ + private AssetInfo assetInfo(Path file) { + String name = file.getFileName().toString(); + int[] size = imageSize(file); + try { + return new AssetInfo(name, "/api/remote-ui/assets/" + name, size[0], size[1], Files.size(file)); + } catch (IOException e) { + return null; + } + } + + /** 只读图片头拿宽高,避免整图解码。 */ + private static int[] imageSize(Path file) { + try (ImageInputStream input = ImageIO.createImageInputStream(file.toFile())) { + if (input == null) { + return new int[]{0, 0}; + } + Iterator readers = ImageIO.getImageReaders(input); + if (!readers.hasNext()) { + return new int[]{0, 0}; + } + ImageReader reader = readers.next(); + try { + reader.setInput(input, true, true); + return new int[]{reader.getWidth(0), reader.getHeight(0)}; + } finally { + reader.dispose(); + } + } catch (IOException e) { + return new int[]{0, 0}; + } + } + + private static long lastModified(Path path) { + try { + return Files.getLastModifiedTime(path).toMillis(); + } catch (IOException e) { + return 0L; + } + } + /** 取文件扩展名(小写);没有扩展名时返回空串。 */ private static String extensionOf(String filename) { int dot = filename.lastIndexOf('.'); @@ -231,4 +334,8 @@ public class RemoteUIController { } return MediaType.IMAGE_PNG; } + + /** 资源库列表项。 */ + public record AssetInfo(String name, String path, int pixelWidth, int pixelHeight, long size) { + } } diff --git a/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt b/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt index 080841d..8633dc8 100644 --- a/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt +++ b/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt @@ -7,24 +7,46 @@ import org.slf4j.LoggerFactory import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption +import java.time.Instant +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Comparator import java.util.concurrent.ConcurrentHashMap /** - * 布局文档存储。 + * 布局文档存储(草稿 / 已发布分离)。 * - * 文档以 JSON 文件落在磁盘目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖), - * 启动时整体加载进内存,保存时先写临时文件再原子替换,避免写一半留下坏文件。 - * 页面接口仍然走 [LayoutCompiler] 编译,客户端无需感知存储实现。 + * 目录结构(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖): + * - `.json`:已发布布局,页面接口 `/api/remote-ui/{page}` 只编译它; + * - `.draft.json`:编辑器草稿,保存只写草稿,发布时才覆盖已发布布局; + * - `history//.json`:每次发布前的旧版本快照,保留最近 [MAX_VERSIONS] 份。 + * + * 保存时先写临时文件再原子替换,避免写一半留下坏文件。 */ object LayoutStore { private val log = LoggerFactory.getLogger(LayoutStore::class.java) + /** 每个页面保留的历史版本数量。 */ + private const val MAX_VERSIONS = 20 + + /** 草稿文件后缀,文件名形如 `desktop.draft.json`。 */ + private const val DRAFT_SUFFIX = ".draft.json" + private val mapper = ObjectMapper() .registerKotlinModule() .enable(SerializationFeature.INDENT_OUTPUT) - private val layouts = ConcurrentHashMap() + private val VERSION_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss-SSS") + private val VERSION_NAME = Regex("\\d{8}-\\d{6}-\\d{3}") + private val SAVED_AT_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") + + /** 已发布布局,页面接口与 Android 播放端看到的就是这份。 */ + private val published = ConcurrentHashMap() + + /** 编辑器草稿,保存时只写这里,发布后才合并到 [published]。 */ + private val drafts = ConcurrentHashMap() @Volatile private var dir: Path? = null @@ -34,42 +56,159 @@ object LayoutStore { fun initialize(directory: Path) { Files.createDirectories(directory) dir = directory + published.clear() + drafts.clear() Files.list(directory).use { stream -> - stream.filter { it.fileName.toString().endsWith(".json") } + stream.filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".json") } .forEach { file -> + val isDraft = file.fileName.toString().endsWith(DRAFT_SUFFIX) runCatching { mapper.readValue(file.toFile(), LayoutDocument::class.java) } - .onSuccess { document -> layouts[document.id] = document } + .onSuccess { document -> + if (isDraft) drafts[document.id] = document else published[document.id] = document + } .onFailure { log.warn("布局文件读取失败: {}", file, it) } } } - if (layouts[DESKTOP_PAGE] == null) { + if (published[DESKTOP_PAGE] == null) { val default = desktopLayout() - layouts[default.id] = default - persist(default) + published[default.id] = default + persist(default, fileOf(default.id)) log.info("写入默认布局: {}", fileOf(default.id)) } - log.info("布局已加载 {} 个,目录: {}", layouts.size, directory.toAbsolutePath()) + log.info( + "布局已加载 {} 个(草稿 {} 个),目录: {}", + published.size, drafts.size, directory.toAbsolutePath() + ) } - fun get(id: String): LayoutDocument? = layouts[id] + /** 已发布布局;页面编译只认这份。 */ + fun get(id: String): LayoutDocument? = published[id] - fun all(): List = layouts.values.sortedBy { it.id } + /** 编辑器读取:优先草稿,其次已发布;都没有时返回 null。 */ + fun getEditable(id: String): EditableLayout? { + drafts[id]?.let { return EditableLayout(it, true) } + published[id]?.let { return EditableLayout(it, false) } + return null + } - /** 删除布局并移除落盘文件;布局不存在时返回 false。 */ + /** 页面摘要:草稿与已发布取并集,草稿覆盖同 id 的展示信息。 */ + fun summaries(): List { + val ids = (published.keys + drafts.keys).toSortedSet() + return ids.map { id -> + val draft = drafts.containsKey(id) + val document = drafts[id] ?: published[id]!! + LayoutSummary(document.id, document.title, document.items.size, draft) + } + } + + /** 校验并保存草稿;校验不通过时抛 [IllegalArgumentException]。 */ + @Synchronized + fun put(document: LayoutDocument) { + validate(document) + drafts[document.id] = document + persist(document, draftFileOf(document.id)) + } + + /** + * 发布草稿:先把当前已发布布局归档到历史目录,再把草稿写成已发布布局。 + * + * 没有草稿时直接返回已发布布局(重复发布是幂等的);页面完全不存在时返回 null。 + */ + @Synchronized + fun publish(id: String): LayoutDocument? { + val draft = drafts[id] ?: return published[id] + validate(draft) + published[id]?.let { archive(it) } + published[draft.id] = draft + persist(draft, fileOf(draft.id)) + drafts.remove(id) + runCatching { Files.deleteIfExists(draftFileOf(id)) } + .onFailure { log.warn("草稿文件删除失败: {}", draftFileOf(id), it) } + return draft + } + + /** 放弃草稿;没有草稿时返回 false。 */ + @Synchronized + fun discardDraft(id: String): Boolean { + val removed = drafts.remove(id) != null + runCatching { Files.deleteIfExists(draftFileOf(id)) } + .onFailure { log.warn("草稿文件删除失败: {}", draftFileOf(id), it) } + return removed + } + + /** 删除布局、草稿与历史目录;布局不存在时返回 false。 */ + @Synchronized fun remove(id: String): Boolean { - if (layouts.remove(id) == null) return false + val existed = (published.remove(id) != null) or (drafts.remove(id) != null) + if (!existed) return false runCatching { Files.deleteIfExists(fileOf(id)) } .onFailure { log.warn("布局文件删除失败: {}", fileOf(id), it) } + runCatching { Files.deleteIfExists(draftFileOf(id)) } + .onFailure { log.warn("草稿文件删除失败: {}", draftFileOf(id), it) } + deleteTree(historyDirOf(id)) return true } - /** 校验并保存布局;校验不通过时抛 [IllegalArgumentException]。 */ - fun put(document: LayoutDocument) { + /** 历史版本列表,按时间倒序;最多 [MAX_VERSIONS] 条。 */ + @Synchronized + fun versions(id: String): List { + val directory = historyDirOf(id) + if (!Files.isDirectory(directory)) return emptyList() + return Files.list(directory).use { stream -> + stream.map { it.fileName.toString() } + .filter { it.endsWith(".json") } + .sorted(Comparator.reverseOrder()) + .limit(MAX_VERSIONS.toLong()) + .map { name -> + val file = directory.resolve(name) + val version = name.removeSuffix(".json") + val document = runCatching { + mapper.readValue(file.toFile(), LayoutDocument::class.java) + }.getOrNull() + LayoutVersion( + version = version, + savedAt = savedAtOf(file), + title = document?.title.orEmpty(), + items = document?.items?.size ?: 0 + ) + } + .toList() + } + } + + /** + * 把历史版本恢复成草稿;版本不存在返回 null。 + * + * 恢复只改草稿,不直接覆盖已发布布局,编辑器确认后再点「发布」生效。 + */ + @Synchronized + fun restore(id: String, version: String): LayoutDocument? { + require(VERSION_NAME.matches(version)) { "版本号格式不正确: $version" } + val file = historyDirOf(id).resolve("$version.json") + if (!Files.isRegularFile(file)) return null + val document = mapper.readValue(file.toFile(), LayoutDocument::class.java).copy(id = id) validate(document) - layouts[document.id] = document - persist(document) + drafts[id] = document + persist(document, draftFileOf(id)) + return document + } + + /** 返回引用了指定图片资源的页面 id(已发布与草稿都会检查),用于阻止误删。 */ + fun pagesReferencingAsset(name: String): List { + val suffix = "/api/remote-ui/assets/$name" + return (published.values + drafts.values) + .filter { document -> + document.items.any { item -> + item.type == ItemType.IMAGE && + item.props["url"].orEmpty().substringBefore('?').endsWith(suffix) + } + } + .map { it.id } + .distinct() + .sorted() + .toList() } /** 校验布局的坐标范围、组件 id 与点击行为,错误信息直接返回给编辑器。 */ @@ -101,12 +240,11 @@ object LayoutStore { } } - /** 原子写入单个布局文件:先写 `.tmp`,再替换目标文件。 */ - private fun persist(document: LayoutDocument) { - val directory = dir ?: return - val target = fileOf(document.id) + /** 原子写入文件:先写 `.tmp`,再替换目标文件。 */ + private fun persist(document: LayoutDocument, target: Path) { + val directory = target.parent ?: return Files.createDirectories(directory) - val temp = target.resolveSibling("${document.id}.json.tmp") + val temp = target.resolveSibling("${target.fileName}.tmp") mapper.writeValue(temp.toFile(), document) runCatching { Files.move( @@ -120,10 +258,85 @@ object LayoutStore { } } - private fun fileOf(id: String): Path = (dir ?: Path.of("data", "layouts")).resolve("$id.json") + /** 把当前已发布布局复制一份到历史目录,并清理超出上限的旧版本。 */ + private fun archive(document: LayoutDocument) { + runCatching { + val directory = historyDirOf(document.id) + Files.createDirectories(directory) + var stamp = LocalDateTime.now() + var target = directory.resolve("${stamp.format(VERSION_FORMAT)}.json") + while (Files.exists(target)) { + stamp = stamp.plusNanos(1_000_000) + target = directory.resolve("${stamp.format(VERSION_FORMAT)}.json") + } + mapper.writeValue(target.toFile(), document) + prune(directory) + }.onFailure { log.warn("布局历史归档失败: {}", document.id, it) } + } + + /** 只保留最近 [MAX_VERSIONS] 个版本(文件名按时间递增,天然有序)。 */ + private fun prune(directory: Path) { + val names = Files.list(directory).use { stream -> + stream.map { it.fileName.toString() } + .filter { it.endsWith(".json") } + .sorted() + .toList() + } + if (names.size <= MAX_VERSIONS) return + names.take(names.size - MAX_VERSIONS).forEach { name -> + runCatching { Files.deleteIfExists(directory.resolve(name)) } + } + } + + private fun savedAtOf(file: Path): String = runCatching { + LocalDateTime.ofInstant( + Instant.ofEpochMilli(Files.getLastModifiedTime(file).toMillis()), + ZoneId.systemDefault() + ).format(SAVED_AT_FORMAT) + }.getOrDefault("") + + /** 递归删除目录(历史版本随页面一起清理)。 */ + private fun deleteTree(directory: Path) { + if (!Files.isDirectory(directory)) return + runCatching { + Files.walk(directory).use { stream -> + stream.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) } + } + }.onFailure { log.warn("布局历史目录删除失败: {}", directory, it) } + } + + private fun root(): Path = dir ?: Path.of("data", "layouts") + + private fun fileOf(id: String): Path = root().resolve("$id.json") + + private fun draftFileOf(id: String): Path = root().resolve("$id$DRAFT_SUFFIX") + + private fun historyDirOf(id: String): Path = root().resolve("history").resolve(id) private val LAYOUT_ID = Regex("[A-Za-z0-9_-]{1,64}") + /** 列表接口的页面摘要。 */ + data class LayoutSummary( + val id: String, + val title: String, + val items: Int, + val draft: Boolean, + ) + + /** 编辑器读取结果:文档 + 是否来自草稿。 */ + data class EditableLayout( + val document: LayoutDocument, + val draft: Boolean, + ) + + /** 历史版本摘要。 */ + data class LayoutVersion( + val version: String, + val savedAt: String, + val title: String, + val items: Int, + ) + /** * 默认桌面:12 列网格 + 千分比坐标的示例布局。 * diff --git a/ComposeRemoteServer/src/main/resources/static/editor.html b/ComposeRemoteServer/src/main/resources/static/editor.html index 0c52278..b726ced 100644 --- a/ComposeRemoteServer/src/main/resources/static/editor.html +++ b/ComposeRemoteServer/src/main/resources/static/editor.html @@ -335,6 +335,59 @@ } .modal h3 { margin: 0 0 14px; font-size: 15px; } .modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; } + .modal.wide { width: 460px; } + + .state-badge { + display: inline-block; + padding: 3px 8px; + border-radius: 999px; + font-size: 11px; + border: 1px solid var(--line); + color: var(--muted); + background: #0b1220; + white-space: nowrap; + } + .state-badge[data-state="published"] { color: #6ee7b7; border-color: #065f46; background: #052e2b; } + .state-badge[data-state="draft"] { color: #fcd34d; border-color: #854d0e; background: #3b2a08; } + .state-badge[data-state="dirty"] { color: #fca5a5; border-color: #7f1d1d; background: #3f1d1d; } + + .history-list { max-height: 56vh; overflow: auto; display: flex; flex-direction: column; gap: 8px; } + .history-row { + display: flex; + align-items: center; + gap: 10px; + padding: 10px; + border: 1px solid var(--line); + border-radius: 10px; + background: #0b1220; + } + .history-row .meta { flex: 1; min-width: 0; } + .history-row .meta strong { display: block; font-size: 13px; font-weight: 600; } + .history-row .meta span { color: var(--muted); font-size: 11px; } + .history-row button { padding: 5px 10px; font-size: 12px; } + + .asset-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; + max-height: 56vh; + overflow: auto; + } + .asset-card { + border: 1px solid var(--line); + border-radius: 10px; + overflow: hidden; + background: #0b1220; + cursor: pointer; + transition: border-color .15s ease; + } + .asset-card:hover { border-color: var(--primary); } + .asset-card img { width: 100%; height: 76px; object-fit: cover; display: block; background: #111827; } + .asset-card .meta { padding: 6px 8px; } + .asset-card .meta strong { display: block; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .asset-card .meta span { color: var(--muted); font-size: 10px; } + .asset-card .ops { display: flex; justify-content: flex-end; padding: 0 8px 8px; } + .asset-card .ops button { padding: 3px 8px; font-size: 11px; } @media (max-width: 1050px) { .brand { display: none; } @@ -353,6 +406,7 @@
+ 已发布
@@ -365,8 +419,10 @@ + - + + @@ -435,6 +491,26 @@ + + + +
@@ -473,6 +549,7 @@ pages: [], selectedId: null, dirty: false, + hasDraft: false, savedJson: '', clipboard: null }; @@ -521,7 +598,7 @@ state.pages.forEach((page) => { const option = document.createElement('option'); option.value = page.id; - option.textContent = `${page.title}(${page.id})`; + option.textContent = `${page.title}(${page.id}${page.draft ? ' · 草稿' : ''})`; select.appendChild(option); }); if (!state.pages.some((page) => page.id === state.pageId)) { @@ -538,8 +615,11 @@ try { const res = await fetch(`/api/layouts/${encodeURIComponent(id)}`); if (!res.ok) throw new Error(await readError(res)); + const data = await res.json(); state.pageId = id; - state.doc = await res.json(); + state.hasDraft = !!data.draft; + delete data.draft; + state.doc = data; state.doc.canvas = state.doc.canvas || {}; state.selectedId = null; state.savedJson = snapshot(); @@ -554,8 +634,10 @@ } } - async function save() { - if (!state.doc) return; + /** 保存草稿;返回是否成功。silent 用于发布前自动保存,不弹提示。 */ + async function save(options) { + if (!state.doc) return false; + const silent = !!(options && options.silent); try { const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}`, { method: 'PUT', @@ -565,11 +647,203 @@ if (!res.ok) throw new Error(await readError(res)); state.doc = await res.json(); state.savedJson = snapshot(); + state.hasDraft = true; state.dirty = false; updateDirty(); renderAll(); await refreshPages(); - toast('已保存:Android 端重新进入该页面后生效'); + if (!silent) toast('已保存草稿,点「发布」后 Android 端生效'); + return true; + } catch (e) { + toast('保存失败:' + e.message, true); + return false; + } + } + + /** 发布草稿;有未保存改动时先自动保存。 */ + async function publish() { + if (!state.doc) return; + if (state.dirty && !(await save({ silent: true }))) return; + if (!confirm('发布后会用当前草稿覆盖线上布局,确定发布吗?')) return; + try { + const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}/publish`, { + method: 'POST' + }); + if (!res.ok) throw new Error(await readError(res)); + const data = await res.json(); + data.canvas = data.canvas || {}; + state.doc = data; + state.savedJson = snapshot(); + state.hasDraft = false; + state.dirty = false; + renderAll(); + await refreshPages(); + toast('已发布:Android 端重新进入该页面后生效'); + } catch (e) { + toast('发布失败:' + e.message, true); + } + } + + /* ---------------- 版本历史 ---------------- */ + + function closeHistory() { + $('history-modal').classList.remove('show'); + } + + async function openHistory() { + if (!state.doc) return; + $('history-modal').classList.add('show'); + $('history-list').innerHTML = '
加载中…
'; + try { + const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}/versions`); + if (!res.ok) throw new Error(await readError(res)); + renderHistory(await res.json()); + } catch (e) { + $('history-list').innerHTML = `
${escapeHtml(e.message)}
`; + } + } + + function renderHistory(versions) { + const list = $('history-list'); + if (!versions.length) { + list.innerHTML = '
还没有历史版本。
每次点「发布」都会自动保存一份快照。
'; + return; + } + list.innerHTML = ''; + versions.forEach((version) => { + const row = document.createElement('div'); + row.className = 'history-row'; + const meta = document.createElement('div'); + meta.className = 'meta'; + const title = document.createElement('strong'); + title.textContent = version.title || '(无标题)'; + const detail = document.createElement('span'); + detail.textContent = `${version.savedAt} · ${version.items} 个组件 · ${version.version}`; + meta.append(title, detail); + const button = document.createElement('button'); + button.textContent = '恢复'; + button.onclick = () => restoreVersion(version.version); + row.append(meta, button); + list.appendChild(row); + }); + } + + async function restoreVersion(version) { + if (!confirm('把该版本恢复成草稿?恢复后需要点「发布」才会影响线上。')) return; + try { + const res = await fetch( + `/api/layouts/${encodeURIComponent(state.pageId)}/versions/${encodeURIComponent(version)}/restore`, + { method: 'POST' } + ); + if (!res.ok) throw new Error(await readError(res)); + const data = await res.json(); + data.canvas = data.canvas || {}; + state.doc = data; + state.selectedId = null; + state.hasDraft = true; + state.savedJson = snapshot(); + state.dirty = false; + undoStack.length = 0; + redoStack.length = 0; + closeHistory(); + renderAll(); + toast('已恢复到草稿,确认无误后点「发布」'); + } catch (e) { + toast('恢复失败:' + e.message, true); + } + } + + /* ---------------- 图片资源库 ---------------- */ + + function closeAssets() { + $('assets-modal').classList.remove('show'); + } + + async function openAssets() { + const item = currentItem(); + if (!item || item.type !== 'IMAGE') { + toast('先选中一个图片组件,再从资源库选择图片', true); + return; + } + $('assets-modal').classList.add('show'); + await loadAssets(); + } + + async function loadAssets() { + const grid = $('assets-list'); + grid.innerHTML = '
加载中…
'; + try { + const res = await fetch('/api/remote-ui/assets'); + if (!res.ok) throw new Error(await readError(res)); + renderAssets(await res.json()); + } catch (e) { + grid.innerHTML = `
${escapeHtml(e.message)}
`; + } + } + + function renderAssets(assets) { + const grid = $('assets-list'); + if (!assets.length) { + grid.innerHTML = '
资源库还没有图片,先在图片组件里上传。
'; + return; + } + grid.innerHTML = ''; + assets.forEach((asset) => { + const card = document.createElement('div'); + card.className = 'asset-card'; + card.title = '点击使用这张图片'; + + const image = document.createElement('img'); + image.src = location.origin + asset.path; + image.alt = asset.name; + image.loading = 'lazy'; + + const meta = document.createElement('div'); + meta.className = 'meta'; + const name = document.createElement('strong'); + name.textContent = asset.name; + const info = document.createElement('span'); + info.textContent = `${asset.pixelWidth}×${asset.pixelHeight} · ${formatSize(asset.size)}`; + meta.append(name, info); + + const ops = document.createElement('div'); + ops.className = 'ops'; + const remove = document.createElement('button'); + remove.className = 'danger'; + remove.textContent = '删除'; + remove.onclick = (event) => { + event.stopPropagation(); + deleteAsset(asset); + }; + ops.appendChild(remove); + + card.append(image, meta, ops); + card.onclick = () => applyAsset(asset); + grid.appendChild(card); + }); + } + + function applyAsset(asset) { + const item = currentItem(); + if (!item || item.type !== 'IMAGE') return; + pushHistory(); + item.props = item.props || {}; + item.props.url = location.origin + asset.path; + item.props.pixelWidth = String(asset.pixelWidth); + item.props.pixelHeight = String(asset.pixelHeight); + closeAssets(); + renderAll(); + refreshDirty(); + toast(`已使用 ${asset.name}(${asset.pixelWidth}×${asset.pixelHeight})`); + } + + async function deleteAsset(asset) { + if (!confirm(`确定删除图片「${asset.name}」吗?`)) return; + try { + const res = await fetch(`/api/remote-ui/assets/${encodeURIComponent(asset.name)}`, { method: 'DELETE' }); + if (!res.ok) throw new Error(await readError(res)); + toast('图片已删除'); + await loadAssets(); } catch (e) { toast(e.message, true); } @@ -587,7 +861,17 @@ $('btn-add-text').onclick = () => addItem('TEXT'); $('btn-add-card').onclick = () => addItem('CARD'); $('btn-add-image').onclick = () => addItem('IMAGE'); - $('btn-save').onclick = save; + $('btn-save').onclick = () => save(); + $('btn-publish').onclick = publish; + $('btn-history').onclick = openHistory; + $('btn-history-close').onclick = closeHistory; + $('history-modal').addEventListener('click', (event) => { + if (event.target === $('history-modal')) closeHistory(); + }); + $('btn-assets-close').onclick = closeAssets; + $('assets-modal').addEventListener('click', (event) => { + if (event.target === $('assets-modal')) closeAssets(); + }); $('btn-undo').onclick = undo; $('btn-redo').onclick = redo; $('btn-reload').onclick = () => { @@ -876,7 +1160,8 @@ const uploadBlock = item.type === 'IMAGE' ? ` -
上传后自动回填 URL 与像素尺寸,文件保存到服务端 assets 目录。
` + +
上传或选择后自动回填 URL 与像素尺寸,文件保存到服务端 assets 目录。
` : ''; inspector.innerHTML = ` @@ -989,6 +1274,8 @@ $('image-file').click(); }; } + const pickButton = inspector.querySelector('[data-act="pick-asset"]'); + if (pickButton) pickButton.onclick = openAssets; } function moveLayer(item, direction) { @@ -1372,6 +1659,24 @@ function updateDirty() { document.body.classList.toggle('dirty', state.dirty); + updatePublishState(); + } + + /** 顶栏状态徽标:未保存 / 草稿未发布 / 已发布。 */ + function updatePublishState() { + const node = $('publish-state'); + if (!node) return; + let text = '已发布'; + let kind = 'published'; + if (state.dirty) { + text = '未保存'; + kind = 'dirty'; + } else if (state.hasDraft) { + text = '草稿未发布'; + kind = 'draft'; + } + node.textContent = text; + node.dataset.state = kind; } function pct(value) { @@ -1411,6 +1716,19 @@ return (window.CSS && CSS.escape) ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&'); } + function escapeHtml(value) { + return String(value).replace(/[&<>"']/g, (ch) => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' + }[ch])); + } + + function formatSize(bytes) { + if (!Number.isFinite(bytes)) return ''; + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; + } + let toastTimer = null; function toast(message, isError = false) { const node = $('toast');