feat: 新增后台布局拖拽编辑器
- 布局改为 JSON 文件持久化,新增 /api/layouts 读写接口与坐标/组件校验 - 新增 /editor 拖拽编辑器:12 列网格画布、拖动缩放、属性面板、增删组件 - 图片接口支持外部目录,Content-Type 按扩展名返回 - deploy.yaml 挂载 /opt/composeremote/data,布局与图片持久化
This commit is contained in:
1 parent
484380b11a
commit
07b038b4e7
10 files changed
+1183
-13
No files matched your search
@@ -22,6 +22,9 @@ gradle-app.setting
|
||||
# 本地配置
|
||||
local.properties
|
||||
|
||||
# 服务端本地运行时的布局数据
|
||||
ComposeRemoteServer/data/
|
||||
|
||||
# 上游只读第三方仓库(不纳入本仓库版本管理)
|
||||
remotecompose/
|
||||
remotecompose-android/
|
||||
@@ -22,7 +22,7 @@ spec:
|
||||
spec:
|
||||
containers:
|
||||
- name: server
|
||||
image: composeremote/server:1.0.0-layout2
|
||||
image: composeremote/server:1.0.0-editor2
|
||||
imagePullPolicy: Never
|
||||
ports:
|
||||
- name: http
|
||||
@@ -30,6 +30,13 @@ spec:
|
||||
env:
|
||||
- name: JAVA_TOOL_OPTIONS
|
||||
value: "-XX:MaxRAMPercentage=60 -XX:+ExitOnOutOfMemoryError"
|
||||
- name: LAYOUT_DIR
|
||||
value: /app/data/layouts
|
||||
- name: ASSETS_DIR
|
||||
value: /app/data/assets
|
||||
volumeMounts:
|
||||
- name: layouts
|
||||
mountPath: /app/data
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
@@ -47,6 +54,12 @@ spec:
|
||||
port: 8000
|
||||
initialDelaySeconds: 30
|
||||
periodSeconds: 20
|
||||
volumes:
|
||||
# 布局 JSON 落在宿主机,Pod 重建 / 镜像升级不丢数据。
|
||||
- name: layouts
|
||||
hostPath:
|
||||
path: /opt/composeremote/data
|
||||
type: DirectoryOrCreate
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
|
||||
@@ -45,6 +45,11 @@
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
<!-- 布局文件是 Kotlin data class,反序列化需要 Kotlin 模块 -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.module</groupId>
|
||||
<artifactId>jackson-module-kotlin</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.ttstd.composeremote.server.controller;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
/**
|
||||
* 布局编辑器页面。
|
||||
*
|
||||
* <p>编辑器是单文件 HTML;静态资源统一配置了 30 天缓存,
|
||||
* 这里单独关掉缓存,方便改完编辑器刷新就生效。
|
||||
*/
|
||||
@Controller
|
||||
public class EditorPageController {
|
||||
|
||||
@GetMapping({"/editor", "/editor/"})
|
||||
public ResponseEntity<Resource> editor() {
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("text/html;charset=UTF-8"))
|
||||
.cacheControl(CacheControl.noCache())
|
||||
.body(new ClassPathResource("static/editor.html"));
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.ttstd.composeremote.server.controller;
|
||||
|
||||
import com.ttstd.composeremote.server.layout.LayoutDocument;
|
||||
import com.ttstd.composeremote.server.layout.LayoutStore;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 布局编辑接口,供后台拖拽编辑器读写。
|
||||
*
|
||||
* <p>布局以 JSON 落盘(目录由 {@code app.layout-dir} / {@code LAYOUT_DIR} 指定),
|
||||
* 保存后下一次 {@code GET /api/remote-ui/{page}} 就会编译新布局下发。
|
||||
* 当前演示环境不鉴权。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/layouts")
|
||||
public class LayoutAdminController {
|
||||
|
||||
/** 布局列表,编辑器启动时用来发现页面。 */
|
||||
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public List<LayoutSummary> list() {
|
||||
return LayoutStore.INSTANCE.all().stream()
|
||||
.map(document -> new LayoutSummary(
|
||||
document.getId(),
|
||||
document.getTitle(),
|
||||
document.getItems().size()
|
||||
))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** 读取单个布局;不存在返回 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) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "布局不存在: " + id);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存布局。
|
||||
*
|
||||
* <p>以路径上的 id 为准,避免请求体里的 id 与路径不一致;
|
||||
* 校验失败返回 400,错误信息是直接给编辑器展示的中文提示。
|
||||
*/
|
||||
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<Object> save(@PathVariable("id") String id,
|
||||
@RequestBody LayoutDocument body) {
|
||||
LayoutDocument document = new LayoutDocument(
|
||||
id,
|
||||
body.getTitle(),
|
||||
body.getCanvas(),
|
||||
body.getBackgroundColor(),
|
||||
body.getItems()
|
||||
);
|
||||
try {
|
||||
LayoutStore.INSTANCE.put(document);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
return ResponseEntity.ok(document);
|
||||
}
|
||||
|
||||
/** 布局摘要。 */
|
||||
public record LayoutSummary(String id, String title, int items) {
|
||||
}
|
||||
}
|
||||
+45
-7
@@ -2,6 +2,7 @@ package com.ttstd.composeremote.server.controller;
|
||||
|
||||
import com.ttstd.composeremote.server.RemoteDocumentBuilderKt;
|
||||
import com.ttstd.composeremote.server.layout.LayoutPages;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -14,8 +15,11 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 服务端驱动 UI 接口。
|
||||
@@ -35,6 +39,10 @@ import java.util.List;
|
||||
@RequestMapping("/api/remote-ui")
|
||||
public class RemoteUIController {
|
||||
|
||||
/** 图片资源目录,优先于 classpath 里的内置资源;容器中由 ASSETS_DIR 指向挂载卷。 */
|
||||
@Value("${app.assets-dir:./data/assets}")
|
||||
private String assetsDir;
|
||||
|
||||
@GetMapping(
|
||||
value = {"/{page}", ""},
|
||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
|
||||
@@ -60,20 +68,50 @@ public class RemoteUIController {
|
||||
/**
|
||||
* 页面引用的图片资源。
|
||||
*
|
||||
* <p>图片 URL 带内容标识时,可以在此长期缓存;当前先固定 30 天。
|
||||
* <p>先找外部资源目录({@code app.assets-dir},默认 {@code ./data/assets}),
|
||||
* 找不到再回落到 classpath 内置图片。图片 URL 带内容标识时,可以在此长期缓存;当前先固定 30 天。
|
||||
*/
|
||||
@GetMapping(value = "/assets/{name:.+}", produces = MediaType.IMAGE_PNG_VALUE)
|
||||
@GetMapping(value = "/assets/{name:.+}")
|
||||
public ResponseEntity<byte[]> getAsset(@PathVariable("name") String name) throws IOException {
|
||||
if (!name.matches("[A-Za-z0-9._-]+")) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
ClassPathResource resource = new ClassPathResource("static/api/" + name);
|
||||
if (!resource.exists()) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
byte[] body = readExternalAsset(name);
|
||||
if (body == null) {
|
||||
ClassPathResource resource = new ClassPathResource("static/api/" + name);
|
||||
if (!resource.exists()) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
body = resource.getContentAsByteArray();
|
||||
}
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.IMAGE_PNG)
|
||||
.contentType(mediaTypeFor(name))
|
||||
.cacheControl(CacheControl.maxAge(Duration.ofDays(30)).cachePublic())
|
||||
.body(resource.getContentAsByteArray());
|
||||
.body(body);
|
||||
}
|
||||
|
||||
/** 读取外部图片目录里的文件;不存在或越界时返回 null。 */
|
||||
private byte[] readExternalAsset(String name) throws IOException {
|
||||
Path directory = Path.of(assetsDir).toAbsolutePath().normalize();
|
||||
Path file = directory.resolve(name).normalize();
|
||||
if (!file.startsWith(directory) || !Files.isRegularFile(file)) {
|
||||
return null;
|
||||
}
|
||||
return Files.readAllBytes(file);
|
||||
}
|
||||
|
||||
/** 按扩展名给出图片类型,Android 端解码与浏览器预览都依赖正确的 Content-Type。 */
|
||||
private static MediaType mediaTypeFor(String name) {
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) {
|
||||
return MediaType.IMAGE_JPEG;
|
||||
}
|
||||
if (lower.endsWith(".webp")) {
|
||||
return MediaType.parseMediaType("image/webp");
|
||||
}
|
||||
if (lower.endsWith(".gif")) {
|
||||
return MediaType.IMAGE_GIF;
|
||||
}
|
||||
return MediaType.IMAGE_PNG;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.ttstd.composeremote.server.config
|
||||
|
||||
import com.ttstd.composeremote.server.layout.LayoutStore
|
||||
import jakarta.annotation.PostConstruct
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import java.nio.file.Path
|
||||
|
||||
/** 启动时把布局目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖)交给 [LayoutStore]。 */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class LayoutStoreConfiguration(
|
||||
@Value("\${app.layout-dir:./data/layouts}") private val layoutDir: String,
|
||||
) {
|
||||
|
||||
@PostConstruct
|
||||
fun init() {
|
||||
LayoutStore.initialize(Path.of(layoutDir))
|
||||
}
|
||||
}
|
||||
+101
-5
@@ -1,25 +1,121 @@
|
||||
package com.ttstd.composeremote.server.layout
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import com.fasterxml.jackson.databind.SerializationFeature
|
||||
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 布局文档的内存存储。
|
||||
* 布局文档存储。
|
||||
*
|
||||
* 当前先内置一份桌面布局,后续接入后台编辑器时,把保存结果 [put] 进来即可,
|
||||
* 文档以 JSON 文件落在磁盘目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖),
|
||||
* 启动时整体加载进内存,保存时先写临时文件再原子替换,避免写一半留下坏文件。
|
||||
* 页面接口仍然走 [LayoutCompiler] 编译,客户端无需感知存储实现。
|
||||
*/
|
||||
object LayoutStore {
|
||||
|
||||
private val layouts = mutableMapOf<String, LayoutDocument>()
|
||||
private val log = LoggerFactory.getLogger(LayoutStore::class.java)
|
||||
|
||||
init {
|
||||
put(desktopLayout())
|
||||
private val mapper = ObjectMapper()
|
||||
.registerKotlinModule()
|
||||
.enable(SerializationFeature.INDENT_OUTPUT)
|
||||
|
||||
private val layouts = ConcurrentHashMap<String, LayoutDocument>()
|
||||
|
||||
@Volatile
|
||||
private var dir: Path? = null
|
||||
|
||||
/** 由 Spring 启动时调用:加载目录下已有布局,缺失桌面布局时写入默认布局。 */
|
||||
@Synchronized
|
||||
fun initialize(directory: Path) {
|
||||
Files.createDirectories(directory)
|
||||
dir = directory
|
||||
|
||||
Files.list(directory).use { stream ->
|
||||
stream.filter { it.fileName.toString().endsWith(".json") }
|
||||
.forEach { file ->
|
||||
runCatching { mapper.readValue(file.toFile(), LayoutDocument::class.java) }
|
||||
.onSuccess { document -> layouts[document.id] = document }
|
||||
.onFailure { log.warn("布局文件读取失败: {}", file, it) }
|
||||
}
|
||||
}
|
||||
|
||||
if (layouts[DESKTOP_PAGE] == null) {
|
||||
val default = desktopLayout()
|
||||
layouts[default.id] = default
|
||||
persist(default)
|
||||
log.info("写入默认布局: {}", fileOf(default.id))
|
||||
}
|
||||
log.info("布局已加载 {} 个,目录: {}", layouts.size, directory.toAbsolutePath())
|
||||
}
|
||||
|
||||
fun get(id: String): LayoutDocument? = layouts[id]
|
||||
|
||||
fun all(): List<LayoutDocument> = layouts.values.sortedBy { it.id }
|
||||
|
||||
/** 校验并保存布局;校验不通过时抛 [IllegalArgumentException]。 */
|
||||
fun put(document: LayoutDocument) {
|
||||
validate(document)
|
||||
layouts[document.id] = document
|
||||
persist(document)
|
||||
}
|
||||
|
||||
/** 校验布局的坐标范围、组件 id 与点击行为,错误信息直接返回给编辑器。 */
|
||||
private fun validate(document: LayoutDocument) {
|
||||
require(document.id.matches(LAYOUT_ID)) {
|
||||
"布局 id 只能包含字母、数字、下划线和短横线: ${document.id}"
|
||||
}
|
||||
require(document.title.isNotBlank() && document.title.length <= 100) {
|
||||
"页面标题不能为空且不超过 100 个字符"
|
||||
}
|
||||
require(document.canvas.aspectWidth > 0 && document.canvas.aspectHeight > 0) {
|
||||
"画布宽高比必须大于 0"
|
||||
}
|
||||
require(document.canvas.columns in 1..24) { "网格列数需在 1..24 之间" }
|
||||
require(document.items.size <= 200) { "单页组件不能超过 200 个" }
|
||||
|
||||
val ids = HashSet<String>()
|
||||
document.items.forEachIndexed { index, item ->
|
||||
val label = "第 ${index + 1} 个组件(${item.id})"
|
||||
require(item.id.matches(LAYOUT_ID)) { "$label: id 只能包含字母、数字、下划线和短横线" }
|
||||
require(ids.add(item.id)) { "$label: id 重复" }
|
||||
require(item.x in 0..999 && item.y in 0..999) { "$label: x、y 需在 0..999" }
|
||||
require(item.w in 1..1000 && item.h in 1..1000) { "$label: w、h 需在 1..1000" }
|
||||
require(item.x + item.w <= 1000) { "$label: x + w 超过 1000" }
|
||||
require(item.y + item.h <= 1000) { "$label: y + h 超过 1000" }
|
||||
item.action?.let { action ->
|
||||
require(action.target.isNotBlank()) { "$label: 点击目标不能为空" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 原子写入单个布局文件:先写 `.tmp`,再替换目标文件。 */
|
||||
private fun persist(document: LayoutDocument) {
|
||||
val directory = dir ?: return
|
||||
val target = fileOf(document.id)
|
||||
Files.createDirectories(directory)
|
||||
val temp = target.resolveSibling("${document.id}.json.tmp")
|
||||
mapper.writeValue(temp.toFile(), document)
|
||||
runCatching {
|
||||
Files.move(
|
||||
temp,
|
||||
target,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
StandardCopyOption.ATOMIC_MOVE
|
||||
)
|
||||
}.onFailure {
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
}
|
||||
|
||||
private fun fileOf(id: String): Path = (dir ?: Path.of("data", "layouts")).resolve("$id.json")
|
||||
|
||||
private val LAYOUT_ID = Regex("[A-Za-z0-9_-]{1,64}")
|
||||
|
||||
/**
|
||||
* 默认桌面:12 列网格 + 千分比坐标的示例布局。
|
||||
*
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
server:
|
||||
port: 8000
|
||||
|
||||
app:
|
||||
# 布局 JSON 的落盘目录,容器里由 LAYOUT_DIR 指向挂载卷。
|
||||
layout-dir: ${LAYOUT_DIR:./data/layouts}
|
||||
# 页面上传的图片目录,接口 /api/remote-ui/assets/{name} 优先读这里。
|
||||
assets-dir: ${ASSETS_DIR:./data/assets}
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: ComposeRemoteServer
|
||||
|
||||
@@ -0,0 +1,883 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Remote UI 布局编辑器</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f172a;
|
||||
--bg-soft: #1e293b;
|
||||
--line: #334155;
|
||||
--text: #e2e8f0;
|
||||
--muted: #94a3b8;
|
||||
--primary: #3b82f6;
|
||||
--primary-hover: #2563eb;
|
||||
--danger: #ef4444;
|
||||
--card-bg: #e3f2fd;
|
||||
--title-color: #0d47a1;
|
||||
--body-color: #212121;
|
||||
--accent-color: #1565c0;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
body { display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 12px 18px;
|
||||
background: var(--bg-soft);
|
||||
border-bottom: 1px solid var(--line);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.brand { font-size: 15px; font-weight: 600; letter-spacing: .3px; }
|
||||
.brand small { color: var(--muted); font-weight: 400; margin-left: 8px; }
|
||||
|
||||
.toolbar { display: flex; align-items: center; gap: 8px; margin-left: auto; flex-wrap: wrap; }
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: #273449;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 7px 12px;
|
||||
cursor: pointer;
|
||||
transition: background .15s ease, border-color .15s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
button:hover { background: #31415c; }
|
||||
button.primary { background: var(--primary); border-color: var(--primary); }
|
||||
button.primary:hover { background: var(--primary-hover); border-color: var(--primary-hover); }
|
||||
button.danger { color: #fecaca; border-color: #7f1d1d; background: #3f1d1d; }
|
||||
button.danger:hover { background: #552020; }
|
||||
button.ghost { background: transparent; }
|
||||
|
||||
main { flex: 1; display: flex; min-height: 0; }
|
||||
|
||||
.stage {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 18px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.stage-head { color: var(--muted); font-size: 12px; text-align: center; line-height: 1.7; }
|
||||
|
||||
.canvas-wrap {
|
||||
position: relative;
|
||||
border-radius: 26px;
|
||||
padding: 8px;
|
||||
background: #020617;
|
||||
border: 1px solid var(--line);
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, .45);
|
||||
}
|
||||
|
||||
.canvas {
|
||||
position: relative;
|
||||
height: min(calc(100vh - 215px), 880px);
|
||||
aspect-ratio: 9 / 19.5;
|
||||
overflow: hidden;
|
||||
border-radius: 20px;
|
||||
background: #ffffff;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.guides {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
background-image:
|
||||
linear-gradient(to right, rgba(21, 101, 192, .10) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(21, 101, 192, .06) 1px, transparent 1px);
|
||||
background-size: calc(100% / 12) 100%, 100% 5%;
|
||||
background-position: 0 0;
|
||||
}
|
||||
|
||||
.item {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
overflow: hidden;
|
||||
border-radius: 6px;
|
||||
cursor: grab;
|
||||
outline: 1px dashed rgba(21, 101, 192, .28);
|
||||
}
|
||||
.item:hover { outline: 1px dashed rgba(21, 101, 192, .7); }
|
||||
.item.selected {
|
||||
outline: 2px solid #1976d2;
|
||||
box-shadow: 0 0 0 3px rgba(25, 118, 210, .18);
|
||||
cursor: grabbing;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.item .handle {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: nwse-resize;
|
||||
background: linear-gradient(135deg, transparent 46%, #1976d2 47%, #1976d2 100%);
|
||||
border-bottom-right-radius: 5px;
|
||||
opacity: 0;
|
||||
z-index: 4;
|
||||
}
|
||||
.item.selected .handle { opacity: 1; }
|
||||
|
||||
.item .chip {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 2px;
|
||||
padding: 1px 5px;
|
||||
border-radius: 999px;
|
||||
background: rgba(25, 118, 210, .92);
|
||||
color: #fff;
|
||||
font-size: 9px;
|
||||
line-height: 1.4;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pv-text {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
color: var(--title-color);
|
||||
line-height: 1.25;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.pv-card {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--card-bg);
|
||||
color: var(--body-color);
|
||||
}
|
||||
.pv-card .pv-title { color: var(--title-color); font-weight: 600; }
|
||||
.pv-card .pv-hint { color: var(--accent-color); }
|
||||
|
||||
.pv-image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: #cbd5e1 center/cover no-repeat;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #475569;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
aside {
|
||||
width: 300px;
|
||||
flex: none;
|
||||
background: var(--bg-soft);
|
||||
border-left: 1px solid var(--line);
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
aside h2 {
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .12em;
|
||||
color: var(--muted);
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
.section { margin-bottom: 22px; }
|
||||
|
||||
.field { margin-bottom: 10px; }
|
||||
.field label {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
input, select, textarea {
|
||||
width: 100%;
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: #0b1220;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
padding: 6px 8px;
|
||||
outline: none;
|
||||
}
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--primary); }
|
||||
input[type="color"] { padding: 2px; height: 30px; cursor: pointer; }
|
||||
textarea { resize: vertical; min-height: 54px; }
|
||||
|
||||
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||
.grid2 .field { margin-bottom: 0; }
|
||||
|
||||
.static {
|
||||
padding: 6px 8px;
|
||||
border-radius: 7px;
|
||||
background: #0b1220;
|
||||
border: 1px dashed var(--line);
|
||||
color: var(--text);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: var(--muted);
|
||||
line-height: 1.8;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.hint { color: var(--muted); font-size: 11px; line-height: 1.6; margin-top: 4px; }
|
||||
|
||||
.dirty-dot {
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: #f59e0b;
|
||||
margin-left: 6px;
|
||||
visibility: hidden;
|
||||
}
|
||||
.dirty .dirty-dot { visibility: visible; }
|
||||
|
||||
#toast {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: 26px;
|
||||
transform: translate(-50%, 16px);
|
||||
background: #0f766e;
|
||||
color: #f0fdfa;
|
||||
padding: 10px 18px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 12px 30px rgba(0, 0, 0, .4);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity .2s ease, transform .2s ease;
|
||||
max-width: 80vw;
|
||||
z-index: 99;
|
||||
}
|
||||
#toast.show { opacity: 1; transform: translate(-50%, 0); }
|
||||
#toast.error { background: #7f1d1d; color: #fee2e2; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
main { flex-direction: column; }
|
||||
aside { width: auto; border-left: 0; border-top: 1px solid var(--line); max-height: 42vh; }
|
||||
.canvas { height: min(calc(100vh - 330px), 620px); }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<div class="brand">Remote UI 布局编辑器<small id="page-label">desktop</small><span class="dirty-dot"></span></div>
|
||||
<div class="toolbar">
|
||||
<button id="btn-add-text">+ 文字</button>
|
||||
<button id="btn-add-card">+ 卡片</button>
|
||||
<button id="btn-add-image">+ 图片</button>
|
||||
<button id="btn-reload" class="ghost">重新加载</button>
|
||||
<button id="btn-save" class="primary">保存并发布</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<section class="stage">
|
||||
<div class="stage-head">
|
||||
拖动组件移动 · 右下角缩放 · 自动吸附网格<br>
|
||||
x / w 吸附 1/12 列,y / h 吸附 5‰,方向键微调,Delete 删除
|
||||
</div>
|
||||
<div class="canvas-wrap">
|
||||
<div class="canvas" id="canvas">
|
||||
<div class="guides"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stage-head" id="canvas-meta"></div>
|
||||
</section>
|
||||
|
||||
<aside>
|
||||
<div class="section">
|
||||
<h2>画布</h2>
|
||||
<div class="field">
|
||||
<label>页面标题</label>
|
||||
<input id="page-title" maxlength="100">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>背景颜色</label>
|
||||
<input id="bg-color" type="color">
|
||||
</div>
|
||||
<div class="grid2">
|
||||
<div class="field"><label>宽高比</label><div class="static" id="aspect">9 : 19.5</div></div>
|
||||
<div class="field"><label>网格列数</label><div class="static" id="columns">12</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2>组件</h2>
|
||||
<div id="inspector"></div>
|
||||
</div>
|
||||
</aside>
|
||||
</main>
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<script>
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const PM = 1000; // 坐标总长(千分比)
|
||||
const SNAP_Y = 5; // 纵向吸附步长(千分比)
|
||||
const MIN_ITEM = 10; // 组件最小尺寸(千分比)
|
||||
const CANVAS_DP = 400; // 编译器里的文档逻辑宽度,用于预估预览字号
|
||||
|
||||
const PROP_FIELDS = {
|
||||
TEXT: [
|
||||
{ key: 'text', label: '文字', type: 'textarea' },
|
||||
{ key: 'fontSize', label: '字号 (sp)', type: 'number' }
|
||||
],
|
||||
CARD: [
|
||||
{ key: 'title', label: '标题' },
|
||||
{ key: 'body', label: '正文', type: 'textarea' },
|
||||
{ key: 'hint', label: '提示(可选)' }
|
||||
],
|
||||
IMAGE: [
|
||||
{ key: 'url', label: '图片 URL' },
|
||||
{ key: 'pixelWidth', label: '像素宽', type: 'number' },
|
||||
{ key: 'pixelHeight', label: '像素高', type: 'number' }
|
||||
]
|
||||
};
|
||||
|
||||
const state = {
|
||||
pageId: 'desktop',
|
||||
doc: null,
|
||||
selectedId: null,
|
||||
dirty: false
|
||||
};
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const canvas = $('canvas');
|
||||
const inspector = $('inspector');
|
||||
|
||||
init();
|
||||
|
||||
async function init() {
|
||||
state.pageId = new URLSearchParams(location.search).get('id') || 'desktop';
|
||||
$('page-label').textContent = state.pageId;
|
||||
await load();
|
||||
bindToolbar();
|
||||
bindCanvasKeys();
|
||||
// 画布尺寸变化时,预览字号需要按新的缩放比例重算。
|
||||
new ResizeObserver(() => renderItems()).observe(canvas);
|
||||
}
|
||||
|
||||
/* ---------------- 数据加载与保存 ---------------- */
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}`);
|
||||
if (!res.ok) throw new Error(await readError(res));
|
||||
state.doc = await res.json();
|
||||
state.selectedId = null;
|
||||
state.dirty = false;
|
||||
updateDirty();
|
||||
renderAll();
|
||||
toast('布局已加载');
|
||||
} catch (e) {
|
||||
toast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!state.doc) return;
|
||||
try {
|
||||
const res = await fetch(`/api/layouts/${encodeURIComponent(state.pageId)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(state.doc)
|
||||
});
|
||||
if (!res.ok) throw new Error(await readError(res));
|
||||
state.doc = await res.json();
|
||||
state.dirty = false;
|
||||
updateDirty();
|
||||
renderAll();
|
||||
toast('已保存:Android 端重新进入该页面后生效');
|
||||
} catch (e) {
|
||||
toast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function readError(res) {
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (body && body.error) return body.error;
|
||||
} catch (ignored) { /* 非 JSON 响应 */ }
|
||||
return `请求失败(HTTP ${res.status})`;
|
||||
}
|
||||
|
||||
function bindToolbar() {
|
||||
$('btn-add-text').onclick = () => addItem('TEXT');
|
||||
$('btn-add-card').onclick = () => addItem('CARD');
|
||||
$('btn-add-image').onclick = () => addItem('IMAGE');
|
||||
$('btn-save').onclick = save;
|
||||
$('btn-reload').onclick = () => {
|
||||
if (state.dirty && !confirm('有未保存的修改,确定重新加载吗?')) return;
|
||||
load();
|
||||
};
|
||||
|
||||
$('page-title').oninput = (e) => {
|
||||
if (!state.doc) return;
|
||||
state.doc.title = e.target.value;
|
||||
markDirty();
|
||||
};
|
||||
$('bg-color').oninput = (e) => {
|
||||
if (!state.doc) return;
|
||||
state.doc.backgroundColor = hexToInt(e.target.value);
|
||||
canvas.style.backgroundColor = e.target.value;
|
||||
markDirty();
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------------- 渲染 ---------------- */
|
||||
|
||||
function renderAll() {
|
||||
if (!state.doc) return;
|
||||
$('page-title').value = state.doc.title || '';
|
||||
$('bg-color').value = intToHex(state.doc.backgroundColor);
|
||||
canvas.style.backgroundColor = intToHex(state.doc.backgroundColor);
|
||||
|
||||
const canvasSpec = state.doc.canvas || {};
|
||||
$('aspect').textContent = `${canvasSpec.aspectWidth ?? 9} : ${canvasSpec.aspectHeight ?? 19.5}`;
|
||||
$('columns').textContent = `${canvasSpec.columns ?? 12} 列`;
|
||||
$('canvas-meta').textContent =
|
||||
`${state.doc.items.length} 个组件 · 坐标范围 0–${PM}‰ · 预览按 9:19.5 等比缩放`;
|
||||
|
||||
renderItems();
|
||||
renderInspector();
|
||||
}
|
||||
|
||||
function renderItems() {
|
||||
if (!state.doc) return;
|
||||
canvas.querySelectorAll('.item').forEach((node) => node.remove());
|
||||
state.doc.items.forEach((item) => canvas.appendChild(buildItemNode(item)));
|
||||
}
|
||||
|
||||
function buildItemNode(item) {
|
||||
const node = document.createElement('div');
|
||||
node.className = 'item' + (item.id === state.selectedId ? ' selected' : '');
|
||||
node.dataset.id = item.id;
|
||||
applyBox(node, item);
|
||||
node.appendChild(buildPreview(item));
|
||||
|
||||
if (item.action) {
|
||||
const chip = document.createElement('span');
|
||||
chip.className = 'chip';
|
||||
chip.textContent = item.action.type === 'OPEN_ACTIVITY' ? '新窗' : '跳转';
|
||||
node.appendChild(chip);
|
||||
}
|
||||
|
||||
const handle = document.createElement('div');
|
||||
handle.className = 'handle';
|
||||
handle.title = '拖动缩放';
|
||||
handle.addEventListener('pointerdown', (e) => startDrag(e, item, 'resize'));
|
||||
node.appendChild(handle);
|
||||
|
||||
node.addEventListener('pointerdown', (e) => startDrag(e, item, 'move'));
|
||||
return node;
|
||||
}
|
||||
|
||||
function buildPreview(item) {
|
||||
const scale = Math.max(canvas.clientWidth, 1) / CANVAS_DP;
|
||||
const props = item.props || {};
|
||||
|
||||
if (item.type === 'TEXT') {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'pv-text';
|
||||
div.style.fontSize = `${num(props.fontSize, 15) * scale}px`;
|
||||
div.textContent = props.text || '';
|
||||
return div;
|
||||
}
|
||||
|
||||
if (item.type === 'CARD') {
|
||||
const box = document.createElement('div');
|
||||
box.className = 'pv-card';
|
||||
box.style.padding = `${10 * scale}px`;
|
||||
const title = document.createElement('div');
|
||||
title.className = 'pv-title';
|
||||
title.style.fontSize = `${16 * scale}px`;
|
||||
title.textContent = props.title || '';
|
||||
const body = document.createElement('div');
|
||||
body.style.fontSize = `${13 * scale}px`;
|
||||
body.style.marginTop = `${4 * scale}px`;
|
||||
body.textContent = props.body || '';
|
||||
box.append(title, body);
|
||||
if (props.hint) {
|
||||
const hint = document.createElement('div');
|
||||
hint.className = 'pv-hint';
|
||||
hint.style.fontSize = `${12 * scale}px`;
|
||||
hint.style.marginTop = `${4 * scale}px`;
|
||||
hint.textContent = props.hint;
|
||||
box.appendChild(hint);
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
const div = document.createElement('div');
|
||||
div.className = 'pv-image';
|
||||
if (props.url) {
|
||||
div.style.backgroundImage = `url("${props.url.replace(/"/g, '%22')}")`;
|
||||
div.style.color = 'transparent';
|
||||
} else {
|
||||
div.textContent = '图片(未设置 URL)';
|
||||
}
|
||||
return div;
|
||||
}
|
||||
|
||||
function applyBox(node, item) {
|
||||
if (!node) return;
|
||||
node.style.left = pct(item.x);
|
||||
node.style.top = pct(item.y);
|
||||
node.style.width = pct(item.w);
|
||||
node.style.height = pct(item.h);
|
||||
}
|
||||
|
||||
/* ---------------- 选中与属性面板 ---------------- */
|
||||
|
||||
function select(id) {
|
||||
state.selectedId = id;
|
||||
canvas.querySelectorAll('.item').forEach((node) => {
|
||||
node.classList.toggle('selected', node.dataset.id === id);
|
||||
});
|
||||
renderInspector();
|
||||
}
|
||||
|
||||
function renderInspector() {
|
||||
const item = currentItem();
|
||||
if (!item) {
|
||||
inspector.innerHTML = '<div class="empty">点击画布中的组件进行编辑<br>或从上方新增文字 / 卡片 / 图片</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const props = item.props || {};
|
||||
const propFields = (PROP_FIELDS[item.type] || []).map((field) => {
|
||||
const long = field.type === 'textarea';
|
||||
const input = long
|
||||
? `<textarea data-prop="${field.key}"></textarea>`
|
||||
: `<input data-prop="${field.key}" ${field.type === 'number' ? 'type="number" step="1"' : ''}>`;
|
||||
return `<div class="field"><label>${field.label}</label>${input}</div>`;
|
||||
}).join('');
|
||||
|
||||
inspector.innerHTML = `
|
||||
<div class="field"><label>类型</label><div class="static">${item.type}</div></div>
|
||||
<div class="field"><label>组件 id</label><div class="static">${item.id}</div></div>
|
||||
<div class="grid2" style="margin-bottom:10px">
|
||||
<div class="field"><label>x</label><input data-box="x" type="number" min="0" max="${PM - 1}"></div>
|
||||
<div class="field"><label>y</label><input data-box="y" type="number" min="0" max="${PM - 1}"></div>
|
||||
<div class="field"><label>w</label><input data-box="w" type="number" min="1" max="${PM}"></div>
|
||||
<div class="field"><label>h</label><input data-box="h" type="number" min="1" max="${PM}"></div>
|
||||
</div>
|
||||
<h2>内容</h2>
|
||||
${propFields}
|
||||
<h2>点击行为</h2>
|
||||
<div class="field">
|
||||
<label>动作</label>
|
||||
<select data-action="type">
|
||||
<option value="">无</option>
|
||||
<option value="NAVIGATE">页面内跳转</option>
|
||||
<option value="OPEN_ACTIVITY">新 Activity 打开</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>目标页面</label>
|
||||
<input data-action="target" placeholder="例如 detail / list">
|
||||
</div>
|
||||
<button class="danger" data-act="delete" style="width:100%;margin-top:6px">删除该组件</button>
|
||||
<div class="hint">提示:图片组件的像素宽高需与真实图片一致,否则播放端解码会失败。</div>
|
||||
`;
|
||||
|
||||
inspector.querySelectorAll('[data-box]').forEach((input) => {
|
||||
input.value = item[input.dataset.box];
|
||||
input.oninput = () => {
|
||||
const value = clampInt(input.value, 0, PM);
|
||||
if (value === null) return;
|
||||
if (input.dataset.box === 'x') item.x = Math.min(value, PM - item.w);
|
||||
if (input.dataset.box === 'y') item.y = Math.min(value, PM - item.h);
|
||||
if (input.dataset.box === 'w') item.w = Math.max(1, Math.min(value, PM - item.x));
|
||||
if (input.dataset.box === 'h') item.h = Math.max(1, Math.min(value, PM - item.y));
|
||||
applyBox(itemNode(item.id), item);
|
||||
markDirty();
|
||||
};
|
||||
});
|
||||
|
||||
inspector.querySelectorAll('[data-prop]').forEach((input) => {
|
||||
input.value = props[input.dataset.prop] ?? '';
|
||||
input.oninput = () => {
|
||||
item.props = item.props || {};
|
||||
item.props[input.dataset.prop] = input.value;
|
||||
const node = itemNode(item.id);
|
||||
if (node) {
|
||||
node.replaceChild(buildPreview(item), node.firstElementChild);
|
||||
}
|
||||
markDirty();
|
||||
};
|
||||
});
|
||||
|
||||
const actionSelect = inspector.querySelector('[data-action="type"]');
|
||||
const actionTarget = inspector.querySelector('[data-action="target"]');
|
||||
actionSelect.value = item.action ? item.action.type : '';
|
||||
actionTarget.value = item.action ? item.action.target : '';
|
||||
actionTarget.disabled = !item.action;
|
||||
|
||||
const onActionChange = () => {
|
||||
if (!actionSelect.value) {
|
||||
item.action = null;
|
||||
actionTarget.value = '';
|
||||
actionTarget.disabled = true;
|
||||
} else {
|
||||
item.action = { type: actionSelect.value, target: actionTarget.value.trim() };
|
||||
actionTarget.disabled = false;
|
||||
}
|
||||
renderItems();
|
||||
markDirty();
|
||||
};
|
||||
actionSelect.onchange = onActionChange;
|
||||
actionTarget.oninput = () => {
|
||||
if (!item.action) return;
|
||||
item.action.target = actionTarget.value.trim();
|
||||
markDirty();
|
||||
};
|
||||
|
||||
inspector.querySelector('[data-act="delete"]').onclick = () => {
|
||||
state.doc.items = state.doc.items.filter((it) => it.id !== item.id);
|
||||
state.selectedId = null;
|
||||
renderAll();
|
||||
markDirty();
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------------- 拖拽与缩放 ---------------- */
|
||||
|
||||
function startDrag(event, item, mode) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
select(item.id);
|
||||
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const start = { x: item.x, y: item.y, w: item.w, h: item.h, px: event.clientX, py: event.clientY };
|
||||
const columns = (state.doc.canvas && state.doc.canvas.columns) || 12;
|
||||
const colWidth = PM / columns;
|
||||
const node = itemNode(item.id);
|
||||
let moved = false;
|
||||
|
||||
const onMove = (ev) => {
|
||||
const dxPm = ((ev.clientX - start.px) / rect.width) * PM;
|
||||
const dyPm = ((ev.clientY - start.py) / rect.height) * PM;
|
||||
if (Math.abs(ev.clientX - start.px) + Math.abs(ev.clientY - start.py) > 2) moved = true;
|
||||
|
||||
if (mode === 'move') {
|
||||
item.x = clamp(snap(start.x + dxPm, colWidth), 0, PM - item.w);
|
||||
item.y = clamp(snap(start.y + dyPm, SNAP_Y), 0, PM - item.h);
|
||||
} else {
|
||||
const minW = Math.max(MIN_ITEM, colWidth / 2);
|
||||
item.w = clamp(snap(start.w + dxPm, colWidth), minW, PM - item.x);
|
||||
item.h = clamp(snap(start.h + dyPm, SNAP_Y), Math.max(MIN_ITEM, SNAP_Y), PM - item.y);
|
||||
}
|
||||
applyBox(node, item);
|
||||
};
|
||||
|
||||
const onUp = () => {
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
if (moved) markDirty();
|
||||
renderAll();
|
||||
};
|
||||
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp);
|
||||
}
|
||||
|
||||
function bindCanvasKeys() {
|
||||
window.addEventListener('keydown', (event) => {
|
||||
const tag = (event.target.tagName || '').toLowerCase();
|
||||
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
|
||||
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
|
||||
event.preventDefault();
|
||||
save();
|
||||
return;
|
||||
}
|
||||
|
||||
const item = currentItem();
|
||||
if (!item) return;
|
||||
|
||||
if (event.key === 'Delete' || event.key === 'Backspace') {
|
||||
event.preventDefault();
|
||||
state.doc.items = state.doc.items.filter((it) => it.id !== item.id);
|
||||
state.selectedId = null;
|
||||
renderAll();
|
||||
markDirty();
|
||||
return;
|
||||
}
|
||||
|
||||
const step = event.shiftKey ? 25 : SNAP_Y;
|
||||
const delta = {
|
||||
ArrowLeft: [-step, 0], ArrowRight: [step, 0],
|
||||
ArrowUp: [0, -step], ArrowDown: [0, step]
|
||||
}[event.key];
|
||||
if (!delta) return;
|
||||
|
||||
event.preventDefault();
|
||||
item.x = clamp(item.x + delta[0], 0, PM - item.w);
|
||||
item.y = clamp(item.y + delta[1], 0, PM - item.h);
|
||||
applyBox(itemNode(item.id), item);
|
||||
renderInspectorNumbers(item);
|
||||
markDirty();
|
||||
});
|
||||
}
|
||||
|
||||
function renderInspectorNumbers(item) {
|
||||
inspector.querySelectorAll('[data-box]').forEach((input) => {
|
||||
input.value = item[input.dataset.box];
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------- 新增组件 ---------------- */
|
||||
|
||||
let sequence = 0;
|
||||
|
||||
function addItem(type) {
|
||||
if (!state.doc) return;
|
||||
const preset = {
|
||||
TEXT: { w: 1000, h: 70, props: { text: '新文字', fontSize: '20' } },
|
||||
CARD: { w: 480, h: 160, props: { title: '新卡片', body: '描述文字' } },
|
||||
IMAGE: {
|
||||
w: 1000, h: 240,
|
||||
props: {
|
||||
url: 'https://ttstd.com/api/remote-ui/assets/spike-image.png',
|
||||
pixelWidth: '800', pixelHeight: '450'
|
||||
}
|
||||
}
|
||||
}[type];
|
||||
|
||||
if (!preset) return;
|
||||
const id = uniqueId(type.toLowerCase());
|
||||
const y = Math.min(PM - preset.h, maxBottom() + 20);
|
||||
state.doc.items.push({
|
||||
id,
|
||||
type,
|
||||
x: 0,
|
||||
y: Math.max(0, y),
|
||||
w: preset.w,
|
||||
h: preset.h,
|
||||
props: { ...preset.props },
|
||||
action: null
|
||||
});
|
||||
renderAll();
|
||||
select(id);
|
||||
markDirty();
|
||||
}
|
||||
|
||||
function uniqueId(prefix) {
|
||||
let id;
|
||||
do {
|
||||
sequence += 1;
|
||||
id = `${prefix}-${Date.now().toString(36).slice(-4)}${sequence}`;
|
||||
} while (state.doc.items.some((item) => item.id === id));
|
||||
return id;
|
||||
}
|
||||
|
||||
function maxBottom() {
|
||||
return state.doc.items.reduce((max, item) => Math.max(max, item.y + item.h), 0);
|
||||
}
|
||||
|
||||
/* ---------------- 工具函数 ---------------- */
|
||||
|
||||
function currentItem() {
|
||||
if (!state.doc || !state.selectedId) return null;
|
||||
return state.doc.items.find((item) => item.id === state.selectedId) || null;
|
||||
}
|
||||
|
||||
function itemNode(id) {
|
||||
return canvas.querySelector(`.item[data-id="${cssEscape(id)}"]`);
|
||||
}
|
||||
|
||||
function markDirty() {
|
||||
state.dirty = true;
|
||||
updateDirty();
|
||||
}
|
||||
|
||||
function updateDirty() {
|
||||
document.body.classList.toggle('dirty', state.dirty);
|
||||
}
|
||||
|
||||
function pct(value) {
|
||||
return `${value / 10}%`;
|
||||
}
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.round(Math.min(Math.max(value, min), max));
|
||||
}
|
||||
|
||||
function clampInt(raw, min, max) {
|
||||
const value = Number.parseInt(raw, 10);
|
||||
if (Number.isNaN(value)) return null;
|
||||
return Math.round(Math.min(Math.max(value, min), max));
|
||||
}
|
||||
|
||||
function snap(value, step) {
|
||||
return Math.round(value / step) * step;
|
||||
}
|
||||
|
||||
function num(raw, fallback) {
|
||||
const value = Number.parseFloat(raw);
|
||||
return Number.isFinite(value) ? value : fallback;
|
||||
}
|
||||
|
||||
function intToHex(value) {
|
||||
const n = (Number(value) >>> 0).toString(16).padStart(8, '0');
|
||||
return `#${n.slice(-6)}`;
|
||||
}
|
||||
|
||||
function hexToInt(hex) {
|
||||
const rgb = Number.parseInt(hex.replace('#', ''), 16) || 0;
|
||||
return (0xff000000 | rgb) | 0;
|
||||
}
|
||||
|
||||
function cssEscape(value) {
|
||||
return (window.CSS && CSS.escape) ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
let toastTimer = null;
|
||||
function toast(message, isError = false) {
|
||||
const node = $('toast');
|
||||
node.textContent = message;
|
||||
node.classList.toggle('error', !!isError);
|
||||
node.classList.add('show');
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => node.classList.remove('show'), isError ? 4000 : 2400);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user