feat: 布局编辑器支持草稿发布、版本历史与图片资源库
This commit is contained in:
1 parent
a77293dadd
commit
5c24941d50
5 files changed
+745
-50
No files matched your search
@@ -22,7 +22,7 @@ spec:
|
|||||||
spec:
|
spec:
|
||||||
containers:
|
containers:
|
||||||
- name: server
|
- name: server
|
||||||
image: composeremote/server:1.0.0-editor5
|
image: composeremote/server:1.0.0-editor6
|
||||||
imagePullPolicy: Never
|
imagePullPolicy: Never
|
||||||
ports:
|
ports:
|
||||||
- name: http
|
- name: http
|
||||||
|
|||||||
+73
-16
@@ -9,50 +9,61 @@ import org.springframework.http.ResponseEntity;
|
|||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
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.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 布局编辑接口,供后台拖拽编辑器读写。
|
* 布局编辑接口,供后台拖拽编辑器读写。
|
||||||
*
|
*
|
||||||
* <p>布局以 JSON 落盘(目录由 {@code app.layout-dir} / {@code LAYOUT_DIR} 指定),
|
* <p>布局以 JSON 落盘(目录由 {@code app.layout-dir} / {@code LAYOUT_DIR} 指定)。
|
||||||
* 保存后下一次 {@code GET /api/remote-ui/{page}} 就会编译新布局下发。
|
* 保存只写草稿,发布后才生效:{@code GET /api/remote-ui/{page}} 编译的是已发布布局,
|
||||||
* 当前演示环境不鉴权。
|
* 编辑器看到的是草稿(没有草稿时回落到已发布)。当前演示环境不鉴权。
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/layouts")
|
@RequestMapping("/api/layouts")
|
||||||
public class LayoutAdminController {
|
public class LayoutAdminController {
|
||||||
|
|
||||||
/** 布局列表,编辑器启动时用来发现页面。 */
|
/** 布局列表,编辑器启动时用来发现页面;{@code draft} 标记该页面存在未发布草稿。 */
|
||||||
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
|
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
public List<LayoutSummary> list() {
|
public List<LayoutSummary> list() {
|
||||||
return LayoutStore.INSTANCE.all().stream()
|
return LayoutStore.INSTANCE.summaries().stream()
|
||||||
.map(document -> new LayoutSummary(
|
.map(summary -> new LayoutSummary(
|
||||||
document.getId(),
|
summary.getId(),
|
||||||
document.getTitle(),
|
summary.getTitle(),
|
||||||
document.getItems().size()
|
summary.getItems(),
|
||||||
|
summary.getDraft()
|
||||||
))
|
))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 读取单个布局;不存在返回 404。 */
|
/** 读取单个布局(优先草稿);不存在返回 404。 */
|
||||||
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
public LayoutDocument get(@PathVariable("id") String id) {
|
public Map<String, Object> get(@PathVariable("id") String id) {
|
||||||
LayoutDocument document = LayoutStore.INSTANCE.get(id);
|
LayoutStore.EditableLayout editable = LayoutStore.INSTANCE.getEditable(id);
|
||||||
if (document == null) {
|
if (editable == null) {
|
||||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "布局不存在: " + id);
|
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "布局不存在: " + id);
|
||||||
}
|
}
|
||||||
return document;
|
LayoutDocument document = editable.getDocument();
|
||||||
|
Map<String, Object> 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 保存布局。
|
* 保存草稿。
|
||||||
*
|
*
|
||||||
* <p>以路径上的 id 为准,避免请求体里的 id 与路径不一致;
|
* <p>以路径上的 id 为准,避免请求体里的 id 与路径不一致;
|
||||||
* 校验失败返回 400,错误信息是直接给编辑器展示的中文提示。
|
* 校验失败返回 400,错误信息是直接给编辑器展示的中文提示。
|
||||||
@@ -76,6 +87,52 @@ public class LayoutAdminController {
|
|||||||
return ResponseEntity.ok(document);
|
return ResponseEntity.ok(document);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 发布草稿:把旧版本归档后覆盖已发布布局;页面完全不存在时返回 404。 */
|
||||||
|
@PostMapping(value = "/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
public ResponseEntity<Object> 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<Object> 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<LayoutStore.LayoutVersion> versions(@PathVariable("id") String id) {
|
||||||
|
return LayoutStore.INSTANCE.versions(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把历史版本恢复成草稿,返回恢复后的文档。 */
|
||||||
|
@PostMapping(value = "/{id}/versions/{version}/restore",
|
||||||
|
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
public ResponseEntity<Object> 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}")
|
@DeleteMapping("/{id}")
|
||||||
public ResponseEntity<Object> delete(@PathVariable("id") String id) {
|
public ResponseEntity<Object> 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) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+107
@@ -9,6 +9,7 @@ import org.springframework.http.CacheControl;
|
|||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
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.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
@@ -20,6 +21,8 @@ import org.springframework.web.multipart.MultipartFile;
|
|||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
import javax.imageio.ImageIO;
|
import javax.imageio.ImageIO;
|
||||||
|
import javax.imageio.ImageReader;
|
||||||
|
import javax.imageio.stream.ImageInputStream;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -28,10 +31,13 @@ import java.nio.file.Path;
|
|||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.security.NoSuchAlgorithmException;
|
import java.security.NoSuchAlgorithmException;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.HexFormat;
|
import java.util.HexFormat;
|
||||||
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -176,6 +182,103 @@ public class RemoteUIController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图片资源库:列出上传目录里的所有图片。
|
||||||
|
*
|
||||||
|
* <p>只读外部资源目录({@code app.assets-dir}),classpath 内置图片不参与管理。
|
||||||
|
* 尺寸通过 ImageReader 只读文件头,不会把整张图解码进内存。
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/assets", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
public List<AssetInfo> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除资源库里的图片。
|
||||||
|
*
|
||||||
|
* <p>只要还有布局(已发布或草稿)的图片组件引用它,就返回 400 并列出页面,
|
||||||
|
* 避免线上页面出现空白图片。
|
||||||
|
*/
|
||||||
|
@DeleteMapping(value = "/assets/{name:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
public ResponseEntity<Object> deleteAsset(@PathVariable("name") String name) {
|
||||||
|
if (!name.matches("[A-Za-z0-9._-]+")) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
List<String> 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<ImageReader> 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) {
|
private static String extensionOf(String filename) {
|
||||||
int dot = filename.lastIndexOf('.');
|
int dot = filename.lastIndexOf('.');
|
||||||
@@ -231,4 +334,8 @@ public class RemoteUIController {
|
|||||||
}
|
}
|
||||||
return MediaType.IMAGE_PNG;
|
return MediaType.IMAGE_PNG;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 资源库列表项。 */
|
||||||
|
public record AssetInfo(String name, String path, int pixelWidth, int pixelHeight, long size) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+238
-25
@@ -7,24 +7,46 @@ import org.slf4j.LoggerFactory
|
|||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
import java.nio.file.Path
|
import java.nio.file.Path
|
||||||
import java.nio.file.StandardCopyOption
|
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
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 布局文档存储。
|
* 布局文档存储(草稿 / 已发布分离)。
|
||||||
*
|
*
|
||||||
* 文档以 JSON 文件落在磁盘目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖),
|
* 目录结构(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖):
|
||||||
* 启动时整体加载进内存,保存时先写临时文件再原子替换,避免写一半留下坏文件。
|
* - `<id>.json`:已发布布局,页面接口 `/api/remote-ui/{page}` 只编译它;
|
||||||
* 页面接口仍然走 [LayoutCompiler] 编译,客户端无需感知存储实现。
|
* - `<id>.draft.json`:编辑器草稿,保存只写草稿,发布时才覆盖已发布布局;
|
||||||
|
* - `history/<id>/<yyyyMMdd-HHmmss-SSS>.json`:每次发布前的旧版本快照,保留最近 [MAX_VERSIONS] 份。
|
||||||
|
*
|
||||||
|
* 保存时先写临时文件再原子替换,避免写一半留下坏文件。
|
||||||
*/
|
*/
|
||||||
object LayoutStore {
|
object LayoutStore {
|
||||||
|
|
||||||
private val log = LoggerFactory.getLogger(LayoutStore::class.java)
|
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()
|
private val mapper = ObjectMapper()
|
||||||
.registerKotlinModule()
|
.registerKotlinModule()
|
||||||
.enable(SerializationFeature.INDENT_OUTPUT)
|
.enable(SerializationFeature.INDENT_OUTPUT)
|
||||||
|
|
||||||
private val layouts = ConcurrentHashMap<String, LayoutDocument>()
|
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<String, LayoutDocument>()
|
||||||
|
|
||||||
|
/** 编辑器草稿,保存时只写这里,发布后才合并到 [published]。 */
|
||||||
|
private val drafts = ConcurrentHashMap<String, LayoutDocument>()
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var dir: Path? = null
|
private var dir: Path? = null
|
||||||
@@ -34,42 +56,159 @@ object LayoutStore {
|
|||||||
fun initialize(directory: Path) {
|
fun initialize(directory: Path) {
|
||||||
Files.createDirectories(directory)
|
Files.createDirectories(directory)
|
||||||
dir = directory
|
dir = directory
|
||||||
|
published.clear()
|
||||||
|
drafts.clear()
|
||||||
|
|
||||||
Files.list(directory).use { stream ->
|
Files.list(directory).use { stream ->
|
||||||
stream.filter { it.fileName.toString().endsWith(".json") }
|
stream.filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".json") }
|
||||||
.forEach { file ->
|
.forEach { file ->
|
||||||
|
val isDraft = file.fileName.toString().endsWith(DRAFT_SUFFIX)
|
||||||
runCatching { mapper.readValue(file.toFile(), LayoutDocument::class.java) }
|
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) }
|
.onFailure { log.warn("布局文件读取失败: {}", file, it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (layouts[DESKTOP_PAGE] == null) {
|
if (published[DESKTOP_PAGE] == null) {
|
||||||
val default = desktopLayout()
|
val default = desktopLayout()
|
||||||
layouts[default.id] = default
|
published[default.id] = default
|
||||||
persist(default)
|
persist(default, fileOf(default.id))
|
||||||
log.info("写入默认布局: {}", 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<LayoutDocument> = 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<LayoutSummary> {
|
||||||
|
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 {
|
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)) }
|
runCatching { Files.deleteIfExists(fileOf(id)) }
|
||||||
.onFailure { log.warn("布局文件删除失败: {}", fileOf(id), it) }
|
.onFailure { log.warn("布局文件删除失败: {}", fileOf(id), it) }
|
||||||
|
runCatching { Files.deleteIfExists(draftFileOf(id)) }
|
||||||
|
.onFailure { log.warn("草稿文件删除失败: {}", draftFileOf(id), it) }
|
||||||
|
deleteTree(historyDirOf(id))
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 校验并保存布局;校验不通过时抛 [IllegalArgumentException]。 */
|
/** 历史版本列表,按时间倒序;最多 [MAX_VERSIONS] 条。 */
|
||||||
fun put(document: LayoutDocument) {
|
@Synchronized
|
||||||
|
fun versions(id: String): List<LayoutVersion> {
|
||||||
|
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)
|
validate(document)
|
||||||
layouts[document.id] = document
|
drafts[id] = document
|
||||||
persist(document)
|
persist(document, draftFileOf(id))
|
||||||
|
return document
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 返回引用了指定图片资源的页面 id(已发布与草稿都会检查),用于阻止误删。 */
|
||||||
|
fun pagesReferencingAsset(name: String): List<String> {
|
||||||
|
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 与点击行为,错误信息直接返回给编辑器。 */
|
/** 校验布局的坐标范围、组件 id 与点击行为,错误信息直接返回给编辑器。 */
|
||||||
@@ -101,12 +240,11 @@ object LayoutStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 原子写入单个布局文件:先写 `.tmp`,再替换目标文件。 */
|
/** 原子写入文件:先写 `.tmp`,再替换目标文件。 */
|
||||||
private fun persist(document: LayoutDocument) {
|
private fun persist(document: LayoutDocument, target: Path) {
|
||||||
val directory = dir ?: return
|
val directory = target.parent ?: return
|
||||||
val target = fileOf(document.id)
|
|
||||||
Files.createDirectories(directory)
|
Files.createDirectories(directory)
|
||||||
val temp = target.resolveSibling("${document.id}.json.tmp")
|
val temp = target.resolveSibling("${target.fileName}.tmp")
|
||||||
mapper.writeValue(temp.toFile(), document)
|
mapper.writeValue(temp.toFile(), document)
|
||||||
runCatching {
|
runCatching {
|
||||||
Files.move(
|
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<Path>()).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}")
|
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 列网格 + 千分比坐标的示例布局。
|
* 默认桌面:12 列网格 + 千分比坐标的示例布局。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -335,6 +335,59 @@
|
|||||||
}
|
}
|
||||||
.modal h3 { margin: 0 0 14px; font-size: 15px; }
|
.modal h3 { margin: 0 0 14px; font-size: 15px; }
|
||||||
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
|
.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) {
|
@media (max-width: 1050px) {
|
||||||
.brand { display: none; }
|
.brand { display: none; }
|
||||||
@@ -353,6 +406,7 @@
|
|||||||
<div class="toolbar">
|
<div class="toolbar">
|
||||||
<select id="page-select" class="page-select" title="切换布局页面"></select>
|
<select id="page-select" class="page-select" title="切换布局页面"></select>
|
||||||
<span class="dirty-dot" title="有未保存修改"></span>
|
<span class="dirty-dot" title="有未保存修改"></span>
|
||||||
|
<span id="publish-state" class="state-badge" data-state="published">已发布</span>
|
||||||
<button id="btn-new-page" title="新建页面">+ 页面</button>
|
<button id="btn-new-page" title="新建页面">+ 页面</button>
|
||||||
<button id="btn-del-page" class="ghost">删除页面</button>
|
<button id="btn-del-page" class="ghost">删除页面</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -365,8 +419,10 @@
|
|||||||
<button id="btn-undo" title="撤销 (Ctrl+Z)">撤销</button>
|
<button id="btn-undo" title="撤销 (Ctrl+Z)">撤销</button>
|
||||||
<button id="btn-redo" title="重做 (Ctrl+Y)">重做</button>
|
<button id="btn-redo" title="重做 (Ctrl+Y)">重做</button>
|
||||||
<span class="divider"></span>
|
<span class="divider"></span>
|
||||||
|
<button id="btn-history" class="ghost" title="版本历史">历史</button>
|
||||||
<button id="btn-reload" class="ghost" title="重新加载">重载</button>
|
<button id="btn-reload" class="ghost" title="重新加载">重载</button>
|
||||||
<button id="btn-save" class="primary" title="保存并发布 (Ctrl+S)">保存</button>
|
<button id="btn-save" title="保存草稿 (Ctrl+S)">保存草稿</button>
|
||||||
|
<button id="btn-publish" class="primary" title="发布到线上">发布</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -435,6 +491,26 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-mask" id="history-modal">
|
||||||
|
<div class="modal wide">
|
||||||
|
<h3>版本历史</h3>
|
||||||
|
<div class="history-list" id="history-list"></div>
|
||||||
|
<div class="actions">
|
||||||
|
<button id="btn-history-close" class="ghost">关闭</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-mask" id="assets-modal">
|
||||||
|
<div class="modal wide">
|
||||||
|
<h3>图片资源库</h3>
|
||||||
|
<div class="asset-grid" id="assets-list"></div>
|
||||||
|
<div class="actions">
|
||||||
|
<button id="btn-assets-close" class="ghost">关闭</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<input type="file" id="image-file" accept="image/png,image/jpeg,image/gif" hidden>
|
<input type="file" id="image-file" accept="image/png,image/jpeg,image/gif" hidden>
|
||||||
|
|
||||||
<div id="toast"></div>
|
<div id="toast"></div>
|
||||||
@@ -473,6 +549,7 @@
|
|||||||
pages: [],
|
pages: [],
|
||||||
selectedId: null,
|
selectedId: null,
|
||||||
dirty: false,
|
dirty: false,
|
||||||
|
hasDraft: false,
|
||||||
savedJson: '',
|
savedJson: '',
|
||||||
clipboard: null
|
clipboard: null
|
||||||
};
|
};
|
||||||
@@ -521,7 +598,7 @@
|
|||||||
state.pages.forEach((page) => {
|
state.pages.forEach((page) => {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = page.id;
|
option.value = page.id;
|
||||||
option.textContent = `${page.title}(${page.id})`;
|
option.textContent = `${page.title}(${page.id}${page.draft ? ' · 草稿' : ''})`;
|
||||||
select.appendChild(option);
|
select.appendChild(option);
|
||||||
});
|
});
|
||||||
if (!state.pages.some((page) => page.id === state.pageId)) {
|
if (!state.pages.some((page) => page.id === state.pageId)) {
|
||||||
@@ -538,8 +615,11 @@
|
|||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/layouts/${encodeURIComponent(id)}`);
|
const res = await fetch(`/api/layouts/${encodeURIComponent(id)}`);
|
||||||
if (!res.ok) throw new Error(await readError(res));
|
if (!res.ok) throw new Error(await readError(res));
|
||||||
|
const data = await res.json();
|
||||||
state.pageId = id;
|
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.doc.canvas = state.doc.canvas || {};
|
||||||
state.selectedId = null;
|
state.selectedId = null;
|
||||||
state.savedJson = snapshot();
|
state.savedJson = snapshot();
|
||||||
@@ -554,8 +634,10 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function save() {
|
/** 保存草稿;返回是否成功。silent 用于发布前自动保存,不弹提示。 */
|
||||||
if (!state.doc) return;
|
async function save(options) {
|
||||||
|
if (!state.doc) return false;
|
||||||
|
const silent = !!(options && options.silent);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}`, {
|
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
@@ -565,11 +647,203 @@
|
|||||||
if (!res.ok) throw new Error(await readError(res));
|
if (!res.ok) throw new Error(await readError(res));
|
||||||
state.doc = await res.json();
|
state.doc = await res.json();
|
||||||
state.savedJson = snapshot();
|
state.savedJson = snapshot();
|
||||||
|
state.hasDraft = true;
|
||||||
state.dirty = false;
|
state.dirty = false;
|
||||||
updateDirty();
|
updateDirty();
|
||||||
renderAll();
|
renderAll();
|
||||||
await refreshPages();
|
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 = '<div class="empty">加载中…</div>';
|
||||||
|
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 = `<div class="empty">${escapeHtml(e.message)}</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderHistory(versions) {
|
||||||
|
const list = $('history-list');
|
||||||
|
if (!versions.length) {
|
||||||
|
list.innerHTML = '<div class="empty">还没有历史版本。<br>每次点「发布」都会自动保存一份快照。</div>';
|
||||||
|
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 = '<div class="empty" style="grid-column:1/-1">加载中…</div>';
|
||||||
|
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 = `<div class="empty" style="grid-column:1/-1">${escapeHtml(e.message)}</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderAssets(assets) {
|
||||||
|
const grid = $('assets-list');
|
||||||
|
if (!assets.length) {
|
||||||
|
grid.innerHTML = '<div class="empty" style="grid-column:1/-1">资源库还没有图片,先在图片组件里上传。</div>';
|
||||||
|
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) {
|
} catch (e) {
|
||||||
toast(e.message, true);
|
toast(e.message, true);
|
||||||
}
|
}
|
||||||
@@ -587,7 +861,17 @@
|
|||||||
$('btn-add-text').onclick = () => addItem('TEXT');
|
$('btn-add-text').onclick = () => addItem('TEXT');
|
||||||
$('btn-add-card').onclick = () => addItem('CARD');
|
$('btn-add-card').onclick = () => addItem('CARD');
|
||||||
$('btn-add-image').onclick = () => addItem('IMAGE');
|
$('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-undo').onclick = undo;
|
||||||
$('btn-redo').onclick = redo;
|
$('btn-redo').onclick = redo;
|
||||||
$('btn-reload').onclick = () => {
|
$('btn-reload').onclick = () => {
|
||||||
@@ -876,7 +1160,8 @@
|
|||||||
|
|
||||||
const uploadBlock = item.type === 'IMAGE'
|
const uploadBlock = item.type === 'IMAGE'
|
||||||
? `<button data-act="upload-image" style="width:100%;margin-bottom:6px">上传图片</button>
|
? `<button data-act="upload-image" style="width:100%;margin-bottom:6px">上传图片</button>
|
||||||
<div class="hint" style="margin-bottom:10px">上传后自动回填 URL 与像素尺寸,文件保存到服务端 assets 目录。</div>`
|
<button data-act="pick-asset" style="width:100%;margin-bottom:6px">从资源库选择</button>
|
||||||
|
<div class="hint" style="margin-bottom:10px">上传或选择后自动回填 URL 与像素尺寸,文件保存到服务端 assets 目录。</div>`
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
inspector.innerHTML = `
|
inspector.innerHTML = `
|
||||||
@@ -989,6 +1274,8 @@
|
|||||||
$('image-file').click();
|
$('image-file').click();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
const pickButton = inspector.querySelector('[data-act="pick-asset"]');
|
||||||
|
if (pickButton) pickButton.onclick = openAssets;
|
||||||
}
|
}
|
||||||
|
|
||||||
function moveLayer(item, direction) {
|
function moveLayer(item, direction) {
|
||||||
@@ -1372,6 +1659,24 @@
|
|||||||
|
|
||||||
function updateDirty() {
|
function updateDirty() {
|
||||||
document.body.classList.toggle('dirty', state.dirty);
|
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) {
|
function pct(value) {
|
||||||
@@ -1411,6 +1716,19 @@
|
|||||||
return (window.CSS && CSS.escape) ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&');
|
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;
|
let toastTimer = null;
|
||||||
function toast(message, isError = false) {
|
function toast(message, isError = false) {
|
||||||
const node = $('toast');
|
const node = $('toast');
|
||||||
|
|||||||
Reference in new issue
Block a user