Add widget catalog and restore canvas preview tools
This commit is contained in:
1 parent
12a8c24441
commit
beeca041ef
13 files changed
+489
-35
No files matched your search
+5
-1
@@ -61,6 +61,8 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
|
|||||||
|
|
||||||
手机断网、令牌无效或新布局校验失败时,继续显示本地布局。冷启动依次读取主布局、上次有效布局和内置布局,如果三个来源都不可用则显示内存兜底桌面。
|
手机断网、令牌无效或新布局校验失败时,继续显示本地布局。冷启动依次读取主布局、上次有效布局和内置布局,如果三个来源都不可用则显示内存兜底桌面。
|
||||||
|
|
||||||
|
画布的「小组件目录」与「布局发布」共用当前页面的管理员令牌。读取目录后可切换「第三方小组件」和「系统小组件」,并按组件名称、应用名称、组件类名或应用包名搜索并添加到当前页,再调整尺寸和位置。添加到画布后按正常流程发布,设备首次使用组件仍需进行 Android 授权。
|
||||||
|
|
||||||
## HTTP 接口
|
## HTTP 接口
|
||||||
|
|
||||||
管理接口使用 `Authorization: Bearer <ADMIN_TOKEN>`。设备接口使用 `Authorization: Bearer <DEVICE_TOKEN>`。
|
管理接口使用 `Authorization: Bearer <ADMIN_TOKEN>`。设备接口使用 `Authorization: Bearer <DEVICE_TOKEN>`。
|
||||||
@@ -70,6 +72,8 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
|
|||||||
| `GET /healthz` | 服务健康状态 |
|
| `GET /healthz` | 服务健康状态 |
|
||||||
| `GET /api/layout` | 下发 v3 布局。设备可传 `If-None-Match`,版本内容相同时返回 304 |
|
| `GET /api/layout` | 下发 v3 布局。设备可传 `If-None-Match`,版本内容相同时返回 304 |
|
||||||
| `GET /api/admin/layout` | 获取线上布局及其 `ETag` |
|
| `GET /api/admin/layout` | 获取线上布局及其 `ETag` |
|
||||||
|
| `GET /api/admin/widget-providers` | 读取系统与第三方 AppWidget Provider 目录 |
|
||||||
|
| `PUT /api/admin/widget-providers` | 幂等导入目录。每项可用组件字符串,或包含 `component`、`label`、`appLabel` 和可选 `category` 的对象(`system` 或 `third-party`) |
|
||||||
| `PUT /api/admin/layout` | 发布布局 JSON。通过 `If-Match` 传入当前线上 `ETag` |
|
| `PUT /api/admin/layout` | 发布布局 JSON。通过 `If-Match` 传入当前线上 `ETag` |
|
||||||
| `GET /api/admin/history?before=整数` | 按版本倒序读取历史,每次最多 50 条。首次查询省略 `before` |
|
| `GET /api/admin/history?before=整数` | 按版本倒序读取历史,每次最多 50 条。首次查询省略 `before` |
|
||||||
| `GET /api/admin/history/{revision}` | 获取某一版本的布局 |
|
| `GET /api/admin/history/{revision}` | 获取某一版本的布局 |
|
||||||
@@ -91,7 +95,7 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 服务器 | `175.178.213.60`,Debian 12,k3s 单节点,SSH 密钥登录 |
|
| 服务器 | `175.178.213.60`,Debian 12,k3s 单节点,SSH 密钥登录 |
|
||||||
| 命名空间 / 工作负载 | `vibe-launcher` / `deploy/vibe-launcher-backend`,单副本 `Recreate` |
|
| 命名空间 / 工作负载 | `vibe-launcher` / `deploy/vibe-launcher-backend`,单副本 `Recreate` |
|
||||||
| 镜像 | `docker.io/library/vibe-launcher-backend:1.1.0-deploy3`,`imagePullPolicy: IfNotPresent` |
|
| 镜像 | `docker.io/library/vibe-launcher-backend:1.1.0-deploy7`,`imagePullPolicy: IfNotPresent` |
|
||||||
| 端口 | 容器 8080,Service NodePort **30830**(30800 是 youlai-boot,30810 是 tts-server,30820 是 compose-remote-server) |
|
| 端口 | 容器 8080,Service NodePort **30830**(30800 是 youlai-boot,30810 是 tts-server,30820 是 compose-remote-server) |
|
||||||
| 公网入口 | `https://api.ttstd.com/launcher/`(灰云直连源站,不走 Cloudflare);nginx 剥掉 `/launcher/` 前缀后反代 `127.0.0.1:30830` |
|
| 公网入口 | `https://api.ttstd.com/launcher/`(灰云直连源站,不走 Cloudflare);nginx 剥掉 `/launcher/` 前缀后反代 `127.0.0.1:30830` |
|
||||||
| 数据 | 宿主机 `/opt/vibe-launcher/data/layouts.sqlite` 挂到容器 `/data`,Pod 重建不丢版本历史 |
|
| 数据 | 宿主机 `/opt/vibe-launcher/data/layouts.sqlite` 挂到容器 `/data`,Pod 重建不丢版本历史 |
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ spec:
|
|||||||
spec:
|
spec:
|
||||||
containers:
|
containers:
|
||||||
- name: server
|
- name: server
|
||||||
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy3
|
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy7
|
||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
ports:
|
ports:
|
||||||
- name: http
|
- name: http
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ import java.nio.ByteBuffer;
|
|||||||
import java.nio.charset.CharacterCodingException;
|
import java.nio.charset.CharacterCodingException;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import org.springframework.core.io.ClassPathResource;
|
import org.springframework.core.io.ClassPathResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.http.CacheControl;
|
import org.springframework.http.CacheControl;
|
||||||
@@ -28,6 +31,8 @@ import tools.jackson.databind.node.ObjectNode;
|
|||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
class LayoutController {
|
class LayoutController {
|
||||||
|
private static final Pattern WIDGET_COMPONENT = Pattern.compile(
|
||||||
|
"[a-zA-Z_$][a-zA-Z0-9_.$]*/(?:\\.)?[a-zA-Z_$][a-zA-Z0-9_.$]*");
|
||||||
private static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L;
|
private static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L;
|
||||||
private static final MediaType JSON = new MediaType("application", "json", StandardCharsets.UTF_8);
|
private static final MediaType JSON = new MediaType("application", "json", StandardCharsets.UTF_8);
|
||||||
private static final String EDITOR_CSP = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
private static final String EDITOR_CSP = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
||||||
@@ -78,6 +83,52 @@ class LayoutController {
|
|||||||
return serve(release);
|
return serve(release);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/api/admin/widget-providers")
|
||||||
|
Map<String, List<LayoutStore.WidgetProvider>> widgetProviders(HttpServletRequest request, HttpServletResponse response)
|
||||||
|
throws SQLException {
|
||||||
|
policy.requireAdmin(request, response);
|
||||||
|
return Map.of("providers", store.widgetProviders());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/api/admin/widget-providers")
|
||||||
|
Map<String, List<LayoutStore.WidgetProvider>> addWidgetProviders(HttpServletRequest request, HttpServletResponse response)
|
||||||
|
throws IOException, SQLException {
|
||||||
|
policy.requireAdmin(request, response);
|
||||||
|
var providers = readJson(request).path("providers");
|
||||||
|
if (!providers.isArray() || providers.isEmpty() || providers.size() > 1000) {
|
||||||
|
throw new ApiError(400, "请选择 1–1000 个小组件 Provider");
|
||||||
|
}
|
||||||
|
var components = new ArrayList<LayoutStore.WidgetProvider>();
|
||||||
|
for (var provider : providers) {
|
||||||
|
var component = (provider.isObject() ? provider.path("component") : provider).stringValue("");
|
||||||
|
if (component.length() > 512 || !WIDGET_COMPONENT.matcher(component).matches()) {
|
||||||
|
throw new ApiError(400, "小组件 Provider 格式无效");
|
||||||
|
}
|
||||||
|
int slash = component.indexOf('/');
|
||||||
|
if (component.charAt(slash + 1) == '.') component = component.substring(0, slash + 1)
|
||||||
|
+ component.substring(0, slash) + component.substring(slash + 1);
|
||||||
|
var categoryNode = provider.path("category");
|
||||||
|
var category = categoryNode.stringValue("");
|
||||||
|
if (!categoryNode.isMissingNode() && !category.equals("system") && !category.equals("third-party")) {
|
||||||
|
throw new ApiError(400, "小组件分类格式无效");
|
||||||
|
}
|
||||||
|
components.add(new LayoutStore.WidgetProvider(component,
|
||||||
|
widgetLabel(provider.path("label")), widgetLabel(provider.path("appLabel")),
|
||||||
|
categoryNode.isMissingNode() ? null : category));
|
||||||
|
}
|
||||||
|
store.addWidgetProviders(components);
|
||||||
|
return Map.of("providers", store.widgetProviders());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String widgetLabel(JsonNode node) {
|
||||||
|
if (node.isMissingNode() || node.isNull()) return null;
|
||||||
|
var label = node.stringValue(null);
|
||||||
|
if (label == null || label.length() > 256 || label.codePoints().anyMatch(Character::isISOControl)) {
|
||||||
|
throw new ApiError(400, "小组件名称格式无效");
|
||||||
|
}
|
||||||
|
return label.isBlank() ? null : label.strip();
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/api/admin/layout")
|
@GetMapping("/api/admin/layout")
|
||||||
ResponseEntity<byte[]> adminLayout(HttpServletRequest request, HttpServletResponse response) throws SQLException {
|
ResponseEntity<byte[]> adminLayout(HttpServletRequest request, HttpServletResponse response) throws SQLException {
|
||||||
policy.requireAdmin(request, response);
|
policy.requireAdmin(request, response);
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ class LayoutStore {
|
|||||||
return "\"" + java.util.HexFormat.of().formatHex(RequestPolicy.sha256(layout)) + "\"";
|
return "\"" + java.util.HexFormat.of().formatHex(RequestPolicy.sha256(layout)) + "\"";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
record WidgetProvider(String component, String label, String appLabel, String category) {}
|
||||||
record HistoryEntry(int revision, String publishedAt, Integer restoredFrom) {}
|
record HistoryEntry(int revision, String publishedAt, Integer restoredFrom) {}
|
||||||
record History(List<HistoryEntry> revisions, Integer nextBefore) {}
|
record History(List<HistoryEntry> revisions, Integer nextBefore) {}
|
||||||
|
|
||||||
@@ -63,6 +64,22 @@ class LayoutStore {
|
|||||||
restoredFrom INTEGER REFERENCES releases(revision)
|
restoredFrom INTEGER REFERENCES releases(revision)
|
||||||
) STRICT
|
) STRICT
|
||||||
""");
|
""");
|
||||||
|
statement.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS widget_providers (
|
||||||
|
component TEXT PRIMARY KEY
|
||||||
|
) STRICT
|
||||||
|
""");
|
||||||
|
for (var column : List.of("label", "app_label", "category")) {
|
||||||
|
boolean exists;
|
||||||
|
try (var check = connection.prepareStatement(
|
||||||
|
"SELECT 1 FROM pragma_table_info('widget_providers') WHERE name = ?")) {
|
||||||
|
check.setString(1, column);
|
||||||
|
try (var rows = check.executeQuery()) {
|
||||||
|
exists = rows.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!exists) statement.execute("ALTER TABLE widget_providers ADD COLUMN " + column + " TEXT");
|
||||||
|
}
|
||||||
try (var seed = connection.prepareStatement("""
|
try (var seed = connection.prepareStatement("""
|
||||||
INSERT OR IGNORE INTO releases (revision, layout, publishedAt, restoredFrom)
|
INSERT OR IGNORE INTO releases (revision, layout, publishedAt, restoredFrom)
|
||||||
VALUES (1, ?, ?, NULL)
|
VALUES (1, ?, ?, NULL)
|
||||||
@@ -87,6 +104,43 @@ class LayoutStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<WidgetProvider> widgetProviders() throws SQLException {
|
||||||
|
var providers = new ArrayList<WidgetProvider>();
|
||||||
|
try (var connection = connect(); var statement = connection.createStatement();
|
||||||
|
var rows = statement.executeQuery("""
|
||||||
|
SELECT component, label, app_label, COALESCE(category, 'third-party') AS category
|
||||||
|
FROM widget_providers
|
||||||
|
ORDER BY COALESCE(app_label, component), COALESCE(label, component), component
|
||||||
|
""")) {
|
||||||
|
while (rows.next()) {
|
||||||
|
providers.add(new WidgetProvider(rows.getString("component"), rows.getString("label"),
|
||||||
|
rows.getString("app_label"), rows.getString("category")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return providers;
|
||||||
|
}
|
||||||
|
|
||||||
|
void addWidgetProviders(List<WidgetProvider> providers) throws SQLException {
|
||||||
|
try (var connection = connect(); var insert = connection.prepareStatement("""
|
||||||
|
INSERT INTO widget_providers (component, label, app_label, category) VALUES (?, ?, ?, ?)
|
||||||
|
ON CONFLICT (component) DO UPDATE SET
|
||||||
|
label = COALESCE(excluded.label, widget_providers.label),
|
||||||
|
app_label = COALESCE(excluded.app_label, widget_providers.app_label),
|
||||||
|
category = COALESCE(excluded.category, widget_providers.category)
|
||||||
|
""")) {
|
||||||
|
connection.setAutoCommit(false);
|
||||||
|
for (var provider : providers) {
|
||||||
|
insert.setString(1, provider.component());
|
||||||
|
insert.setString(2, provider.label());
|
||||||
|
insert.setString(3, provider.appLabel());
|
||||||
|
insert.setString(4, provider.category());
|
||||||
|
insert.addBatch();
|
||||||
|
}
|
||||||
|
insert.executeBatch();
|
||||||
|
connection.commit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Release latest() throws SQLException {
|
Release latest() throws SQLException {
|
||||||
try (var connection = connect(); var statement = connection.createStatement();
|
try (var connection = connect(); var statement = connection.createStatement();
|
||||||
var rows = statement.executeQuery(LATEST)) {
|
var rows = statement.executeQuery(LATEST)) {
|
||||||
|
|||||||
@@ -34,6 +34,43 @@ class LayoutApiTest {
|
|||||||
|
|
||||||
@TempDir Path dir;
|
@TempDir Path dir;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void widgetCatalogRequiresAdminAndPersistsUniqueComponents() throws Exception {
|
||||||
|
String path = "/api/admin/widget-providers";
|
||||||
|
Path database = dir.resolve("widgets.sqlite");
|
||||||
|
try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database);
|
||||||
|
var statement = connection.createStatement()) {
|
||||||
|
statement.execute("CREATE TABLE widget_providers (component TEXT PRIMARY KEY) STRICT");
|
||||||
|
}
|
||||||
|
MockMvc mvc = mvc(database);
|
||||||
|
mvc.perform(get(path).header("Authorization", DEVICE)).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(put(path)).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(put(path).header("Authorization", ADMIN).contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("""
|
||||||
|
{"providers":["com.example/.Widget","invalid"]}
|
||||||
|
"""))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
mvc.perform(get(path).header("Authorization", ADMIN)).andExpect(content().json("""
|
||||||
|
{"providers":[]}
|
||||||
|
"""));
|
||||||
|
mvc.perform(put(path).header("Authorization", ADMIN).contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("""
|
||||||
|
{"providers":[{"component":"com.example/.Widget","label":"快捷搜索","appLabel":"示例应用"},
|
||||||
|
"com.example/com.example.Widget",
|
||||||
|
{"component":"com.android.deskclock/.Clock","label":"时钟","category":"system"},
|
||||||
|
"com.android.deskclock/com.android.deskclock.Clock"]}
|
||||||
|
"""))
|
||||||
|
.andExpect(status().isOk());
|
||||||
|
mvc(database).perform(get(path).header("Authorization", ADMIN))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().json("""
|
||||||
|
{"providers":[{"component":"com.example/com.example.Widget","label":"快捷搜索","appLabel":"示例应用",
|
||||||
|
"category":"third-party"},
|
||||||
|
{"component":"com.android.deskclock/com.android.deskclock.Clock","label":"时钟",
|
||||||
|
"category":"system"}]}
|
||||||
|
"""));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void migratedDatabaseRetainsLayoutsAndSupportsPublishRollbackAndRestart() throws Exception {
|
void migratedDatabaseRetainsLayoutsAndSupportsPublishRollbackAndRestart() throws Exception {
|
||||||
Path database = dir.resolve("layouts.sqlite");
|
Path database = dir.resolve("layouts.sqlite");
|
||||||
|
|||||||
@@ -361,11 +361,11 @@ const LIB = [
|
|||||||
|
|
||||||
const DEVICES = [
|
const DEVICES = [
|
||||||
{ name:'16 : 9', w:1080, h:1920 },
|
{ name:'16 : 9', w:1080, h:1920 },
|
||||||
{ name:'16 : 8', w:1080, h:2160 },
|
{ name:'18 : 9', w:1080, h:2160 },
|
||||||
{ name:'19.5 : 9', w:1080, h:2340 },
|
{ name:'19.5 : 9', w:1080, h:2340 },
|
||||||
{ name:'2K 20:9', w:1440, h:3120 },
|
{ name:'2K 20:9', w:1440, h:3200 },
|
||||||
{ name:'16:10', w:1440, h:2304 },
|
{ name:'16:10', w:1440, h:2304 },
|
||||||
{ name:'平板 4:3', w:1600, h:2560 },
|
{ name:'平板 4:3', w:1536, h:2048 },
|
||||||
];
|
];
|
||||||
|
|
||||||
let state = newState();
|
let state = newState();
|
||||||
@@ -692,7 +692,7 @@ function renderDevices() {
|
|||||||
} else if (fit === 'elastic' && buildMapper({w:1080,h:2160}, items, fit, anchor).elastic) {
|
} else if (fit === 'elastic' && buildMapper({w:1080,h:2160}, items, fit, anchor).elastic) {
|
||||||
const mm = buildMapper({w:1080,h:2160}, items, 'elastic', anchor);
|
const mm = buildMapper({w:1080,h:2160}, items, 'elastic', anchor);
|
||||||
$('devSummary').innerHTML =
|
$('devSummary').innerHTML =
|
||||||
`弹性行距 · 纵向余量按原空白比例放大到行间距(16:8 上 ×${mm.elastic.k.toFixed(2)}),元素尺寸不变`;
|
`弹性行距 · 纵向余量按原空白比例放大到行间距(18:9 上 ×${mm.elastic.k.toFixed(2)}),元素尺寸不变`;
|
||||||
} else {
|
} else {
|
||||||
let vC = 0, hC = 0, mV = 0, mH = 0;
|
let vC = 0, hC = 0, mV = 0, mH = 0;
|
||||||
DEVICES.forEach(d => {
|
DEVICES.forEach(d => {
|
||||||
|
|||||||
+152
-15
@@ -1,14 +1,15 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
||||||
import {
|
import {
|
||||||
ElButton, ElCheckbox, ElConfigProvider, ElInput, ElInputNumber, ElMessage, ElMessageBox,
|
ElButton, ElCheckbox, ElConfigProvider, ElDialog, ElInput, ElInputNumber, ElMessage, ElMessageBox,
|
||||||
ElOption, ElSelect, ElTabPane, ElTabs,
|
ElOption, ElSelect, ElTabPane, ElTabs,
|
||||||
} from "element-plus";
|
} from "element-plus";
|
||||||
import zhCn from "element-plus/es/locale/lang/zh-cn";
|
import zhCn from "element-plus/es/locale/lang/zh-cn";
|
||||||
import ReleaseDialog from "./ReleaseDialog.vue";
|
import ReleaseDialog from "./ReleaseDialog.vue";
|
||||||
import LayoutSurface from "./LayoutSurface.vue";
|
import LayoutSurface from "./LayoutSurface.vue";
|
||||||
|
import DevicePreview from "./DevicePreview.vue";
|
||||||
import {
|
import {
|
||||||
builtInLayout, clamp, copyLayout, devices, normalizeLayout, templates, validate,
|
alignmentGuide, builtInLayout, clamp, copyLayout, normalizeLayout, templates, validate,
|
||||||
type Layout, type LayoutItem, type Payload, type Template,
|
type Layout, type LayoutItem, type Payload, type Template,
|
||||||
} from "./layout";
|
} from "./layout";
|
||||||
|
|
||||||
@@ -55,6 +56,99 @@ const tab = ref("preview");
|
|||||||
const snap = ref(true);
|
const snap = ref(true);
|
||||||
const guides = ref(true);
|
const guides = ref(true);
|
||||||
const release = ref(false);
|
const release = ref(false);
|
||||||
|
const adminToken = ref("");
|
||||||
|
const widgetCatalog = ref(false);
|
||||||
|
type WidgetCategory = "third-party" | "system";
|
||||||
|
interface WidgetProvider {
|
||||||
|
component: string;
|
||||||
|
label: string | null;
|
||||||
|
appLabel: string | null;
|
||||||
|
category: WidgetCategory;
|
||||||
|
}
|
||||||
|
const widgetCategory = ref<WidgetCategory>("third-party");
|
||||||
|
const widgetProviders = ref<WidgetProvider[]>([]);
|
||||||
|
const widgetQuery = ref("");
|
||||||
|
const categoryWidgets = computed(() => widgetProviders.value.filter(provider => provider.category === widgetCategory.value));
|
||||||
|
const widgetNames = computed(() => {
|
||||||
|
const names = new Map<string, number>();
|
||||||
|
for (const provider of categoryWidgets.value) {
|
||||||
|
const name = widgetDisplayName(provider);
|
||||||
|
names.set(name, (names.get(name) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
});
|
||||||
|
const visibleWidgets = computed(() => {
|
||||||
|
const query = widgetQuery.value.trim().toLowerCase();
|
||||||
|
return categoryWidgets.value.filter(provider =>
|
||||||
|
[provider.component, provider.label, provider.appLabel].some(value => value?.toLowerCase().includes(query)),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const widgetChoice = ref<string>();
|
||||||
|
const widgetStatus = ref("");
|
||||||
|
const widgetLoading = ref(false);
|
||||||
|
|
||||||
|
watch(widgetCategory, () => {
|
||||||
|
widgetChoice.value = undefined;
|
||||||
|
widgetQuery.value = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(adminToken, () => {
|
||||||
|
widgetProviders.value = [];
|
||||||
|
widgetChoice.value = undefined;
|
||||||
|
widgetQuery.value = "";
|
||||||
|
widgetStatus.value = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
async function readWidgetProviders() {
|
||||||
|
if (widgetLoading.value) return;
|
||||||
|
const token = adminToken.value.trim();
|
||||||
|
if (!token) {
|
||||||
|
widgetStatus.value = "请输入管理员令牌";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
widgetLoading.value = true;
|
||||||
|
widgetStatus.value = "";
|
||||||
|
try {
|
||||||
|
const url = new URL("./api/admin/widget-providers", location.href);
|
||||||
|
const response = await fetch(url, {
|
||||||
|
headers: { Authorization: "Bearer " + token },
|
||||||
|
cache: "no-store", redirect: "error", signal: AbortSignal.timeout(10000),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(response.status === 401 ? "管理员令牌无效" : "目录读取失败");
|
||||||
|
const data = await response.json() as { providers: WidgetProvider[] };
|
||||||
|
if (adminToken.value.trim() !== token) return;
|
||||||
|
widgetProviders.value = data.providers;
|
||||||
|
if (!data.providers.length) widgetStatus.value = "后端尚未导入小组件";
|
||||||
|
} catch (error) {
|
||||||
|
widgetStatus.value = error instanceof Error ? error.message : "目录读取失败";
|
||||||
|
} finally {
|
||||||
|
widgetLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function widgetClass(component: string) {
|
||||||
|
return component.split("/").at(-1)?.split(".").at(-1) ?? component;
|
||||||
|
}
|
||||||
|
|
||||||
|
function widgetDisplayName(provider: WidgetProvider) {
|
||||||
|
const app = provider.appLabel || provider.component.split("/")[0];
|
||||||
|
const label = provider.label || widgetClass(provider.component);
|
||||||
|
return label === app ? label : label + " · " + app;
|
||||||
|
}
|
||||||
|
|
||||||
|
function widgetOptionLabel(provider: WidgetProvider) {
|
||||||
|
const name = widgetDisplayName(provider);
|
||||||
|
return (widgetNames.value.get(name) ?? 0) > 1 ? name + " · " + widgetClass(provider.component) : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addCatalogWidget() {
|
||||||
|
const provider = widgetProviders.value.find(entry => entry.component === widgetChoice.value);
|
||||||
|
if (!provider || page.value.items.length >= 80) return;
|
||||||
|
const label = provider.label || widgetClass(provider.component);
|
||||||
|
addItem({ type: "widget", label, w: 420, h: 300, payload: { provider: provider.component, label } });
|
||||||
|
widgetCatalog.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
const fileInput = ref<HTMLInputElement>();
|
const fileInput = ref<HTMLInputElement>();
|
||||||
const stage = ref<HTMLElement>();
|
const stage = ref<HTMLElement>();
|
||||||
const stageSize = ref({ width: 0, height: 0 });
|
const stageSize = ref({ width: 0, height: 0 });
|
||||||
@@ -164,6 +258,11 @@ function changeLayer(item: LayoutItem, top: boolean) {
|
|||||||
: Math.max(-2147483648, Math.min(...layers) - 1);
|
: Math.max(-2147483648, Math.min(...layers) - 1);
|
||||||
updateValue(item, "z", layer);
|
updateValue(item, "z", layer);
|
||||||
}
|
}
|
||||||
|
function centerHorizontally() {
|
||||||
|
const item = selected.value;
|
||||||
|
if (!item || item.w > canvas.value.designWidth) return;
|
||||||
|
updateValue(item, "x", (canvas.value.designWidth - item.w) / 2);
|
||||||
|
}
|
||||||
function align() {
|
function align() {
|
||||||
remember();
|
remember();
|
||||||
const round = (n: number) => Math.round(n / 12) * 12;
|
const round = (n: number) => Math.round(n / 12) * 12;
|
||||||
@@ -176,14 +275,19 @@ function align() {
|
|||||||
ElMessage.success("已对齐到 12px 栅格");
|
ElMessage.success("已对齐到 12px 栅格");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const dragGuides = ref<{ x?: number; y?: number }>({});
|
||||||
let drag: { item: LayoutItem; original: LayoutItem; pointer: number; clientX: number; clientY: number;
|
let drag: { item: LayoutItem; original: LayoutItem; pointer: number; clientX: number; clientY: number;
|
||||||
resize: boolean; moved: boolean; scale: number } | undefined;
|
resize: boolean; moved: boolean; scale: number; columns: number[]; rows: number[] } | undefined;
|
||||||
function startDrag(event: PointerEvent, item: LayoutItem, resize: boolean) {
|
function startDrag(event: PointerEvent, item: LayoutItem, resize: boolean) {
|
||||||
if (!event.isPrimary || event.button !== 0 || drag) return;
|
if (!event.isPrimary || event.button !== 0 || drag) return;
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
selectedId.value = item.id;
|
selectedId.value = item.id;
|
||||||
|
const neighbors = resize ? [] : page.value.items.filter(entry => entry.id !== item.id);
|
||||||
drag = { item, original: { ...item }, pointer: event.pointerId, clientX: event.clientX,
|
drag = { item, original: { ...item }, pointer: event.pointerId, clientX: event.clientX,
|
||||||
clientY: event.clientY, resize, moved: false, scale: designScale.value };
|
clientY: event.clientY, resize, moved: false, scale: designScale.value,
|
||||||
|
columns: [canvas.value.designWidth / 2, ...neighbors.flatMap(({ x, w }) => [x, x + w / 2, x + w])],
|
||||||
|
rows: [canvas.value.designHeight / 2, ...neighbors.flatMap(({ y, h }) => [y, y + h / 2, y + h])],
|
||||||
|
};
|
||||||
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
|
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
|
||||||
}
|
}
|
||||||
function moveDrag(event: PointerEvent) {
|
function moveDrag(event: PointerEvent) {
|
||||||
@@ -204,13 +308,22 @@ function moveDrag(event: PointerEvent) {
|
|||||||
} else {
|
} else {
|
||||||
item.x = clamp(grid(original.x + dx), 0, Math.max(0, canvas.value.designWidth - item.w));
|
item.x = clamp(grid(original.x + dx), 0, Math.max(0, canvas.value.designWidth - item.w));
|
||||||
item.y = clamp(grid(original.y + dy), 0, Math.max(0, canvas.value.designHeight - item.h));
|
item.y = clamp(grid(original.y + dy), 0, Math.max(0, canvas.value.designHeight - item.h));
|
||||||
|
if (guides.value) {
|
||||||
|
const tolerance = 4 / drag.scale;
|
||||||
|
dragGuides.value = {
|
||||||
|
x: alignmentGuide(item.x, item.w, drag.columns, tolerance),
|
||||||
|
y: alignmentGuide(item.y, item.h, drag.rows, tolerance),
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function finishDrag(event: PointerEvent) {
|
function finishDrag(event: PointerEvent) {
|
||||||
if (drag?.pointer === event.pointerId) drag = undefined;
|
if (drag?.pointer !== event.pointerId) return;
|
||||||
|
drag = undefined;
|
||||||
|
dragGuides.value = {};
|
||||||
}
|
}
|
||||||
function keys(event: KeyboardEvent) {
|
function keys(event: KeyboardEvent) {
|
||||||
if (release.value || drag || event.defaultPrevented ||
|
if (release.value || widgetCatalog.value || drag || event.defaultPrevented ||
|
||||||
(event.target instanceof Element && event.target.closest("input,textarea,select,[contenteditable]"))) return;
|
(event.target instanceof Element && event.target.closest("input,textarea,select,[contenteditable]"))) return;
|
||||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") {
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -288,6 +401,7 @@ onUnmounted(() => {
|
|||||||
<ElButton :disabled="!undoStack.length" @click="restore(undoStack, redoStack)">撤销</ElButton>
|
<ElButton :disabled="!undoStack.length" @click="restore(undoStack, redoStack)">撤销</ElButton>
|
||||||
<ElButton :disabled="!redoStack.length" @click="restore(redoStack, undoStack)">重做</ElButton>
|
<ElButton :disabled="!redoStack.length" @click="restore(redoStack, undoStack)">重做</ElButton>
|
||||||
<ElButton :disabled="!page.items.length" @click="align">对齐栅格</ElButton>
|
<ElButton :disabled="!page.items.length" @click="align">对齐栅格</ElButton>
|
||||||
|
<ElButton :disabled="!selected || selected.w > canvas.designWidth" @click="centerHorizontally">水平居中</ElButton>
|
||||||
<ElButton :disabled="!selected" @click="removeItem">删除元素</ElButton>
|
<ElButton :disabled="!selected" @click="removeItem">删除元素</ElButton>
|
||||||
<ElButton @click="showIssues">校验</ElButton>
|
<ElButton @click="showIssues">校验</ElButton>
|
||||||
<ElButton @click="fileInput?.click()">导入</ElButton>
|
<ElButton @click="fileInput?.click()">导入</ElButton>
|
||||||
@@ -304,6 +418,10 @@ onUnmounted(() => {
|
|||||||
<div class="templates">
|
<div class="templates">
|
||||||
<ElButton v-for="template in templates" :key="template.label" :disabled="page.items.length >= 80"
|
<ElButton v-for="template in templates" :key="template.label" :disabled="page.items.length >= 80"
|
||||||
@click="addItem(template)">{{ template.label }}</ElButton>
|
@click="addItem(template)">{{ template.label }}</ElButton>
|
||||||
|
<ElButton v-if="hosted" :disabled="page.items.length >= 80"
|
||||||
|
@click="widgetCatalog = true; if (adminToken && !widgetProviders.length) readWidgetProviders()">
|
||||||
|
小组件目录
|
||||||
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section>
|
<section>
|
||||||
@@ -357,7 +475,7 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
<div ref="stage" class="stage" @pointermove="moveDrag" @pointerup="finishDrag"
|
<div ref="stage" class="stage" @pointermove="moveDrag" @pointerup="finishDrag"
|
||||||
@pointercancel="finishDrag" @lostpointercapture="finishDrag">
|
@pointercancel="finishDrag" @lostpointercapture="finishDrag">
|
||||||
<LayoutSurface :layout="layout" :page="page" :selected-id="selectedId" :guides="guides" editable
|
<LayoutSurface :layout="layout" :page="page" :selected-id="selectedId" :guides="guides" :drag-guides="dragGuides" editable
|
||||||
:style="{ width: (canvas.designWidth * designScale) + 'px' }"
|
:style="{ width: (canvas.designWidth * designScale) + 'px' }"
|
||||||
@start-drag="startDrag" @clear="selectedId = undefined" @dblclick="clickBlank" />
|
@start-drag="startDrag" @clear="selectedId = undefined" @dblclick="clickBlank" />
|
||||||
</div>
|
</div>
|
||||||
@@ -374,19 +492,14 @@ onUnmounted(() => {
|
|||||||
<aside class="inspector" aria-label="预览与属性">
|
<aside class="inspector" aria-label="预览与属性">
|
||||||
<ElTabs v-model="tab" stretch>
|
<ElTabs v-model="tab" stretch>
|
||||||
<ElTabPane label="设备预览" name="preview" lazy>
|
<ElTabPane label="设备预览" name="preview" lazy>
|
||||||
<div class="previews">
|
<DevicePreview :layout="layout" :page="page" />
|
||||||
<figure v-for="device in devices" :key="device.name">
|
|
||||||
<LayoutSurface :layout="layout" :page="page" :device="device" />
|
|
||||||
<figcaption>{{ device.name }}<small>{{ device.w }} × {{ device.h }}</small></figcaption>
|
|
||||||
</figure>
|
|
||||||
</div>
|
|
||||||
</ElTabPane>
|
</ElTabPane>
|
||||||
<ElTabPane label="属性" name="properties" lazy>
|
<ElTabPane label="属性" name="properties" lazy>
|
||||||
<div v-if="selected" :key="selected.id" class="item-properties">
|
<div v-if="selected" :key="selected.id" class="item-properties">
|
||||||
<h2>{{ selected.payload.label || selected.type }}</h2>
|
<h2>{{ selected.payload.label || selected.type }}</h2>
|
||||||
<label>ID <ElInput :model-value="selected.id" readonly /></label>
|
<label>ID <ElInput :model-value="selected.id" readonly /></label>
|
||||||
<label v-for="field in fields" :key="field">{{ field.toUpperCase() }}
|
<label v-for="field in fields" :key="field">{{ field.toUpperCase() }}
|
||||||
<ElInputNumber :model-value="selected[field]" :precision="0" :aria-label="field"
|
<ElInputNumber :model-value="selected[field]" :precision="field === 'x' ? undefined : 0" :aria-label="field"
|
||||||
@change="updateValue(selected!, field, $event)" />
|
@change="updateValue(selected!, field, $event)" />
|
||||||
</label>
|
</label>
|
||||||
<label v-for="field in visiblePayload" :key="field.key">{{ field.label }}
|
<label v-for="field in visiblePayload" :key="field.key">{{ field.label }}
|
||||||
@@ -394,6 +507,7 @@ onUnmounted(() => {
|
|||||||
@change="updateValue(selected!.payload, field.key, ($event.target as HTMLInputElement).value)">
|
@change="updateValue(selected!.payload, field.key, ($event.target as HTMLInputElement).value)">
|
||||||
</label>
|
</label>
|
||||||
<div class="json-actions">
|
<div class="json-actions">
|
||||||
|
<ElButton :disabled="selected.w > canvas.designWidth" @click="centerHorizontally">水平居中</ElButton>
|
||||||
<ElButton @click="changeLayer(selected!, true)">置顶</ElButton>
|
<ElButton @click="changeLayer(selected!, true)">置顶</ElButton>
|
||||||
<ElButton @click="changeLayer(selected!, false)">置底</ElButton>
|
<ElButton @click="changeLayer(selected!, false)">置底</ElButton>
|
||||||
<ElButton @click="removeItem">删除</ElButton>
|
<ElButton @click="removeItem">删除</ElButton>
|
||||||
@@ -425,7 +539,30 @@ onUnmounted(() => {
|
|||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ReleaseDialog v-if="hosted" v-model="release" :layout="layout" :has-errors="issues.some(issue => issue.level === 'error')"
|
<ElDialog v-model="widgetCatalog" title="小组件目录" width="min(660px, calc(100vw - 32px))">
|
||||||
|
<label class="token-field">管理员令牌
|
||||||
|
<ElInput v-model="adminToken" type="password" autocomplete="off" :disabled="widgetLoading"
|
||||||
|
@keyup.enter="readWidgetProviders" />
|
||||||
|
</label>
|
||||||
|
<ElButton :loading="widgetLoading" @click="readWidgetProviders">读取目录</ElButton>
|
||||||
|
<p v-if="widgetStatus" role="status">{{ widgetStatus }}</p>
|
||||||
|
<ElTabs v-if="widgetProviders.length" v-model="widgetCategory">
|
||||||
|
<ElTabPane label="第三方小组件" name="third-party" />
|
||||||
|
<ElTabPane label="系统小组件" name="system" />
|
||||||
|
</ElTabs>
|
||||||
|
<ElSelect v-if="categoryWidgets.length" :key="widgetCategory" v-model="widgetChoice" filterable
|
||||||
|
:filter-method="query => widgetQuery = query"
|
||||||
|
placeholder="搜索组件名、应用名或包名" aria-label="小组件" style="width: 100%; margin-top: 12px">
|
||||||
|
<ElOption v-for="provider in visibleWidgets" :key="provider.component" :value="provider.component"
|
||||||
|
:label="widgetOptionLabel(provider)" :title="provider.component" />
|
||||||
|
</ElSelect>
|
||||||
|
<p v-else-if="widgetProviders.length">此分类暂无小组件</p>
|
||||||
|
<template #footer>
|
||||||
|
<ElButton type="primary" :disabled="!widgetChoice || page.items.length >= 80"
|
||||||
|
@click="addCatalogWidget">添加到当前页</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElDialog>
|
||||||
|
<ReleaseDialog v-if="hosted" v-model="release" v-model:token="adminToken" :layout="layout" :has-errors="issues.some(issue => issue.level === 'error')"
|
||||||
:confirm-replace="confirmReplace" :warnings="issues.filter(issue => issue.level === 'warning')"
|
:confirm-replace="confirmReplace" :warnings="issues.filter(issue => issue.level === 'warning')"
|
||||||
@load="loadLayout" @published="markPublished" />
|
@load="loadLayout" @published="markPublished" />
|
||||||
</ElConfigProvider>
|
</ElConfigProvider>
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from "vue";
|
||||||
|
import LayoutSurface from "./LayoutSurface.vue";
|
||||||
|
import { deviceMapper, devices, type Layout, type Page } from "./layout";
|
||||||
|
|
||||||
|
const props = defineProps<{ layout: Layout; page: Page }>();
|
||||||
|
const comparisons = computed(() => devices.map(device => {
|
||||||
|
const mapping = deviceMapper(props.layout.canvas, props.layout.fit, props.page.items, device);
|
||||||
|
const { left = 0, right = 0, top = 0, bottom = 0 } = mapping.insets ?? {};
|
||||||
|
return {
|
||||||
|
device, mapping,
|
||||||
|
horizontal: left + right,
|
||||||
|
vertical: top + bottom,
|
||||||
|
distortion: (mapping.sy / mapping.sx - 1) * 100,
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
const anchorExamples = [
|
||||||
|
{ label: "贴顶", anchorY: 0 },
|
||||||
|
{ label: "偏上", anchorY: 0.42 },
|
||||||
|
{ label: "居中", anchorY: 0.5 },
|
||||||
|
];
|
||||||
|
const tallExample = computed(() => ({
|
||||||
|
name: "高屏示例",
|
||||||
|
w: props.layout.canvas.designWidth,
|
||||||
|
h: Math.round(props.layout.canvas.designHeight * 1.25),
|
||||||
|
}));
|
||||||
|
const examples = computed(() => anchorExamples.map(example => ({
|
||||||
|
...example,
|
||||||
|
layout: { ...props.layout, fit: { mode: "contain", anchorY: example.anchorY } },
|
||||||
|
})));
|
||||||
|
const pixels = (value: number) => Math.round(value) + " px";
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="device-comparison" aria-label="设备比例对比">
|
||||||
|
<p class="preview-legend"><span class="preview-swatch" aria-hidden="true" /> 斜纹表示画布外的留白</p>
|
||||||
|
<div class="previews">
|
||||||
|
<figure v-for="{ device, mapping, horizontal, vertical, distortion } in comparisons" :key="device.name">
|
||||||
|
<LayoutSurface :layout="layout" :page="page" :device="device" show-whitespace />
|
||||||
|
<figcaption>
|
||||||
|
<strong>{{ device.name }}</strong>
|
||||||
|
<small>{{ device.w }} × {{ device.h }}</small>
|
||||||
|
<small>缩放 {{ mapping.sx.toFixed(3) }}×</small>
|
||||||
|
<small>形变 {{ Math.abs(distortion) < 0.05 ? "0" : distortion.toFixed(1) }}%</small>
|
||||||
|
<small v-if="mapping.mode === 'elastic'">行距 {{ mapping.gapScale?.toFixed(2) }}×</small>
|
||||||
|
<small v-else>纵留白 {{ pixels(vertical) }}</small>
|
||||||
|
<small>横留白 {{ pixels(horizontal) }}</small>
|
||||||
|
</figcaption>
|
||||||
|
</figure>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section class="whitespace-examples" aria-labelledby="whitespace-heading">
|
||||||
|
<h2 id="whitespace-heading">留白位置示例</h2>
|
||||||
|
<p>同一画布在更高屏幕上的等比预览。更宽的屏幕会在左右留白。</p>
|
||||||
|
<div class="previews">
|
||||||
|
<figure v-for="example in examples" :key="example.anchorY">
|
||||||
|
<LayoutSurface :layout="example.layout" :page="page" :device="tallExample" show-whitespace />
|
||||||
|
<figcaption>{{ example.label }} <small>{{ example.anchorY }}</small></figcaption>
|
||||||
|
</figure>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
@@ -12,6 +12,8 @@ const props = defineProps<{
|
|||||||
selectedId?: string;
|
selectedId?: string;
|
||||||
editable?: boolean;
|
editable?: boolean;
|
||||||
guides?: boolean;
|
guides?: boolean;
|
||||||
|
dragGuides?: { x?: number; y?: number };
|
||||||
|
showWhitespace?: boolean;
|
||||||
}>();
|
}>();
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
startDrag: [event: PointerEvent, item: LayoutItem, resize: boolean];
|
startDrag: [event: PointerEvent, item: LayoutItem, resize: boolean];
|
||||||
@@ -20,9 +22,20 @@ const emit = defineEmits<{
|
|||||||
const canvas = computed(() => props.layout.canvas);
|
const canvas = computed(() => props.layout.canvas);
|
||||||
const width = computed(() => props.device?.w ?? canvas.value.designWidth);
|
const width = computed(() => props.device?.w ?? canvas.value.designWidth);
|
||||||
const height = computed(() => props.device?.h ?? canvas.value.designHeight);
|
const height = computed(() => props.device?.h ?? canvas.value.designHeight);
|
||||||
const mapper = computed(() => props.device
|
const deviceMap = computed(() => props.device
|
||||||
? deviceMapper(canvas.value, props.layout.fit, props.page.items, props.device)
|
? deviceMapper(canvas.value, props.layout.fit, props.page.items, props.device)
|
||||||
: { sx: 1, sy: 1, x: (n: number) => n, y: (n: number) => n });
|
: undefined);
|
||||||
|
const mapper = computed(() => deviceMap.value ?? { sx: 1, sy: 1, x: (n: number) => n, y: (n: number) => n });
|
||||||
|
const whitespace = computed(() => {
|
||||||
|
const insets = deviceMap.value?.insets;
|
||||||
|
if (!props.showWhitespace || !insets || !Object.values(insets).some(value => value > 0.5)) return undefined;
|
||||||
|
return {
|
||||||
|
top: percent(insets.top, height.value),
|
||||||
|
bottom: percent(insets.bottom, height.value),
|
||||||
|
left: percent(insets.left, width.value),
|
||||||
|
right: percent(insets.right, width.value),
|
||||||
|
};
|
||||||
|
});
|
||||||
const items = computed(() => sortedItems(props.page));
|
const items = computed(() => sortedItems(props.page));
|
||||||
const known = new Set(["app_icon", "widget", "shortcut", "dock_bg"]);
|
const known = new Set(["app_icon", "widget", "shortcut", "dock_bg"]);
|
||||||
const visible = computed(() => props.editable ? items.value : items.value.filter(item => known.has(item.type)));
|
const visible = computed(() => props.editable ? items.value : items.value.filter(item => known.has(item.type)));
|
||||||
@@ -63,5 +76,16 @@ function title(item: LayoutItem) {
|
|||||||
<span v-if="editable" class="resize-handle" aria-hidden="true"
|
<span v-if="editable" class="resize-handle" aria-hidden="true"
|
||||||
@pointerdown="emit('startDrag', $event, item, true)"></span>
|
@pointerdown="emit('startDrag', $event, item, true)"></span>
|
||||||
</div>
|
</div>
|
||||||
|
<template v-if="editable && guides && dragGuides">
|
||||||
|
<div v-if="dragGuides.x !== undefined" class="drag-guide vertical"
|
||||||
|
:style="{ left: percent(dragGuides.x, width) }" aria-hidden="true" />
|
||||||
|
<div v-if="dragGuides.y !== undefined" class="drag-guide horizontal"
|
||||||
|
:style="{ top: percent(dragGuides.y, height) }" aria-hidden="true" />
|
||||||
|
</template>
|
||||||
|
<template v-if="whitespace">
|
||||||
|
<div v-for="(size, side) in whitespace" :key="side" class="preview-gap" :class="side"
|
||||||
|
:style="{ '--gap-size': size }" aria-hidden="true" />
|
||||||
|
<div class="preview-content-boundary" :style="whitespace" aria-hidden="true" />
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -9,7 +9,7 @@ interface History { revisions: HistoryEntry[]; nextBefore: number | null }
|
|||||||
const open = defineModel<boolean>({ required: true });
|
const open = defineModel<boolean>({ required: true });
|
||||||
const props = defineProps<{ layout: Layout; hasErrors: boolean; confirmReplace: () => Promise<boolean>; warnings: Issue[] }>();
|
const props = defineProps<{ layout: Layout; hasErrors: boolean; confirmReplace: () => Promise<boolean>; warnings: Issue[] }>();
|
||||||
const emit = defineEmits<{ load: [layout: Layout, online?: boolean]; published: [revision: number] }>();
|
const emit = defineEmits<{ load: [layout: Layout, online?: boolean]; published: [revision: number] }>();
|
||||||
const token = ref("");
|
const token = defineModel<string>("token", { required: true });
|
||||||
const tag = ref<string>();
|
const tag = ref<string>();
|
||||||
const revision = ref<number>();
|
const revision = ref<number>();
|
||||||
const history = ref<HistoryEntry[]>([]);
|
const history = ref<HistoryEntry[]>([]);
|
||||||
|
|||||||
+42
-10
@@ -46,11 +46,11 @@ export const templates: Template[] = [
|
|||||||
|
|
||||||
export const devices = [
|
export const devices = [
|
||||||
{ name: "16:9", w: 1080, h: 1920 },
|
{ name: "16:9", w: 1080, h: 1920 },
|
||||||
{ name: "16:8", w: 1080, h: 2160 },
|
{ name: "18:9", w: 1080, h: 2160 },
|
||||||
{ name: "19.5:9", w: 1080, h: 2340 },
|
{ name: "19.5:9", w: 1080, h: 2340 },
|
||||||
{ name: "2K 20:9", w: 1440, h: 3120 },
|
{ name: "2K 20:9", w: 1440, h: 3200 },
|
||||||
{ name: "16:10", w: 1440, h: 2304 },
|
{ name: "16:10", w: 1440, h: 2304 },
|
||||||
{ name: "平板 4:3", w: 1600, h: 2560 },
|
{ name: "平板 4:3", w: 1536, h: 2048 },
|
||||||
];
|
];
|
||||||
|
|
||||||
const canvasDefaults = { designWidth: 1080, designHeight: 1920, safeTop: 132, safeBottom: 72 };
|
const canvasDefaults = { designWidth: 1080, designHeight: 1920, safeTop: 132, safeBottom: 72 };
|
||||||
@@ -153,11 +153,22 @@ export function validate(layout: Layout): Issue[] {
|
|||||||
return issues;
|
return issues;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deviceMapper(canvas: Layout["canvas"], fit: Layout["fit"], items: LayoutItem[], dev: typeof devices[number]) {
|
interface DeviceMapping {
|
||||||
|
mode: "contain" | "elastic" | "stretch";
|
||||||
|
sx: number;
|
||||||
|
sy: number;
|
||||||
|
x: (value: number) => number;
|
||||||
|
y: (value: number) => number;
|
||||||
|
insets?: { left: number; right: number; top: number; bottom: number };
|
||||||
|
gapScale?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deviceMapper(canvas: Layout["canvas"], fit: Layout["fit"], items: LayoutItem[],
|
||||||
|
dev: Pick<typeof devices[number], "w" | "h">): DeviceMapping {
|
||||||
const sx = dev.w / canvas.designWidth;
|
const sx = dev.w / canvas.designWidth;
|
||||||
const sy = dev.h / canvas.designHeight;
|
const sy = dev.h / canvas.designHeight;
|
||||||
const mode = fit.mode.toLowerCase();
|
const mode = fit.mode.toLowerCase();
|
||||||
if (mode === "stretch") return { sx, sy, x: (x: number) => x * sx, y: (y: number) => y * sy };
|
if (mode === "stretch") return { mode, sx, sy, x: x => x * sx, y: y => y * sy };
|
||||||
const extra = dev.h - canvas.designHeight * sx;
|
const extra = dev.h - canvas.designHeight * sx;
|
||||||
if (mode === "elastic" && extra > 0.5) {
|
if (mode === "elastic" && extra > 0.5) {
|
||||||
const bands: [number, number][] = [];
|
const bands: [number, number][] = [];
|
||||||
@@ -174,9 +185,10 @@ export function deviceMapper(canvas: Layout["canvas"], fit: Layout["fit"], items
|
|||||||
previous = bottom;
|
previous = bottom;
|
||||||
return [top, cumulative] as const;
|
return [top, cumulative] as const;
|
||||||
});
|
});
|
||||||
const totalBlank = cumulative + Math.max(0, canvas.designHeight - previous) || 1;
|
const blankHeight = cumulative + Math.max(0, canvas.designHeight - previous);
|
||||||
|
const totalBlank = blankHeight > 0.5 ? blankHeight : 1;
|
||||||
return {
|
return {
|
||||||
sx, sy: sx,
|
mode, sx, sy: sx, gapScale: 1 + extra / totalBlank,
|
||||||
x: (x: number) => x * sx,
|
x: (x: number) => x * sx,
|
||||||
y: (y: number) => {
|
y: (y: number) => {
|
||||||
let blank = 0;
|
let blank = 0;
|
||||||
@@ -189,9 +201,29 @@ export function deviceMapper(canvas: Layout["canvas"], fit: Layout["fit"], items
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
const scale = Math.min(sx, sy);
|
const scale = Math.min(sx, sy);
|
||||||
const ox = (dev.w - canvas.designWidth * scale) / 2;
|
const horizontal = Math.max(0, dev.w - canvas.designWidth * scale);
|
||||||
const oy = (dev.h - canvas.designHeight * scale) * clamp(fit.anchorY, 0, 1);
|
const vertical = Math.max(0, dev.h - canvas.designHeight * scale);
|
||||||
return { sx: scale, sy: scale, x: (x: number) => ox + x * scale, y: (y: number) => oy + y * scale };
|
const ox = horizontal / 2;
|
||||||
|
const oy = vertical * clamp(fit.anchorY, 0, 1);
|
||||||
|
return {
|
||||||
|
mode: "contain", sx: scale, sy: scale,
|
||||||
|
x: x => ox + x * scale, y: y => oy + y * scale,
|
||||||
|
insets: { left: ox, right: horizontal - ox, top: oy, bottom: vertical - oy },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function alignmentGuide(start: number, size: number, targetPoints: number[], tolerance: number) {
|
||||||
|
let nearest: number | undefined;
|
||||||
|
let bestDistance = Infinity;
|
||||||
|
for (const target of targetPoints) {
|
||||||
|
const distance = Math.min(Math.abs(target - start), Math.abs(target - (start + size / 2)),
|
||||||
|
Math.abs(target - (start + size)));
|
||||||
|
if (distance <= tolerance && distance < bestDistance) {
|
||||||
|
nearest = target;
|
||||||
|
bestDistance = distance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nearest;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function iconColor(item: LayoutItem) {
|
export function iconColor(item: LayoutItem) {
|
||||||
|
|||||||
@@ -56,6 +56,12 @@ small { color: #9caec3; }
|
|||||||
background: linear-gradient(#b3c8ea12 1px, transparent 1px), linear-gradient(90deg, #b3c8ea12 1px, transparent 1px);
|
background: linear-gradient(#b3c8ea12 1px, transparent 1px), linear-gradient(90deg, #b3c8ea12 1px, transparent 1px);
|
||||||
background-size: 8.333% 5%;
|
background-size: 8.333% 5%;
|
||||||
}
|
}
|
||||||
|
.drag-guide {
|
||||||
|
position: absolute; z-index: 1; pointer-events: none;
|
||||||
|
background: #ffcb70; box-shadow: 0 0 2px #684418;
|
||||||
|
}
|
||||||
|
.drag-guide.vertical { top: 0; bottom: 0; width: 1px; }
|
||||||
|
.drag-guide.horizontal { left: 0; right: 0; height: 1px; }
|
||||||
.safe-zone { position: absolute; left: 0; right: 0; pointer-events: none; background: #4b9cf22a; }
|
.safe-zone { position: absolute; left: 0; right: 0; pointer-events: none; background: #4b9cf22a; }
|
||||||
.safe-zone.top { top: 0; border-bottom: 1px dashed #79b9fc; }
|
.safe-zone.top { top: 0; border-bottom: 1px dashed #79b9fc; }
|
||||||
.safe-zone.bottom { bottom: 0; border-top: 1px dashed #79b9fc; }
|
.safe-zone.bottom { bottom: 0; border-top: 1px dashed #79b9fc; }
|
||||||
@@ -120,3 +126,22 @@ pre { color: #a7ccea; font-size: 11px; max-width: 100%; overflow: auto; }
|
|||||||
.editor { order: -1; min-height: 520px; }
|
.editor { order: -1; min-height: 520px; }
|
||||||
.settings { display: grid; grid-template-columns: 1fr 1fr; }
|
.settings { display: grid; grid-template-columns: 1fr 1fr; }
|
||||||
}
|
}
|
||||||
|
.preview-gap, .preview-content-boundary {
|
||||||
|
position: absolute;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
.preview-gap, .preview-swatch {
|
||||||
|
background: repeating-linear-gradient(135deg, #f4bb6655 0 2px, #503a2d66 2px 6px);
|
||||||
|
}
|
||||||
|
.preview-gap.top, .preview-gap.bottom { left: 0; right: 0; height: var(--gap-size); }
|
||||||
|
.preview-gap.left, .preview-gap.right { top: 0; bottom: 0; width: var(--gap-size); }
|
||||||
|
.preview-gap.top { top: 0; }
|
||||||
|
.preview-gap.bottom { bottom: 0; }
|
||||||
|
.preview-gap.left { left: 0; }
|
||||||
|
.preview-gap.right { right: 0; }
|
||||||
|
.preview-content-boundary { border: 1px dashed #f4bb66; }
|
||||||
|
.preview-legend { display: flex; align-items: center; gap: 6px; margin-bottom: 10px; }
|
||||||
|
.preview-swatch { width: 14px; height: 10px; border: 1px solid #f4bb66; border-radius: 2px; }
|
||||||
|
.preview-legend, .whitespace-examples p { font-size: 12px; color: #b7c5d7; }
|
||||||
|
.whitespace-examples { display: grid; gap: 9px; margin-top: 16px; padding-top: 12px; border-top: 1px solid #2a3547; }
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import { runInNewContext } from "node:vm";
|
import { runInNewContext } from "node:vm";
|
||||||
import { normalizeLayout, validate } from "./src/layout.ts";
|
import { alignmentGuide, builtInLayout, deviceMapper, normalizeLayout, validate } from "./src/layout.ts";
|
||||||
|
|
||||||
const fixtures = JSON.parse(readFileSync(new URL("../docs/layout-cases.json", import.meta.url), "utf8"));
|
const fixtures = JSON.parse(readFileSync(new URL("../docs/layout-cases.json", import.meta.url), "utf8"));
|
||||||
const offline = readFileSync(new URL("./canvas.html", import.meta.url), "utf8");
|
const offline = readFileSync(new URL("./canvas.html", import.meta.url), "utf8");
|
||||||
@@ -39,3 +39,31 @@ for (const { name, accepted, layout } of fixtures) {
|
|||||||
assert.equal(offlineAccepted, accepted, "Offline editor: " + name);
|
assert.equal(offlineAccepted, accepted, "Offline editor: " + name);
|
||||||
}
|
}
|
||||||
console.log(`${fixtures.length} shared cases passed in both editors`);
|
console.log(`${fixtures.length} shared cases passed in both editors`);
|
||||||
|
|
||||||
|
const layout = builtInLayout();
|
||||||
|
const { canvas } = layout;
|
||||||
|
const items = layout.pages[0].items;
|
||||||
|
const tall = { w: 1080, h: 2160 };
|
||||||
|
const wide = { w: 1536, h: 2048 };
|
||||||
|
const centered = { mode: "contain", anchorY: 0.5 };
|
||||||
|
assert.deepEqual(deviceMapper(canvas, centered, items, tall).insets,
|
||||||
|
{ top: 120, bottom: 120, left: 0, right: 0 });
|
||||||
|
assert.deepEqual(deviceMapper(canvas, { ...centered, anchorY: 0 }, items, tall).insets,
|
||||||
|
{ top: 0, bottom: 240, left: 0, right: 0 });
|
||||||
|
assert.deepEqual(deviceMapper(canvas, centered, items, wide).insets,
|
||||||
|
{ top: 0, bottom: 0, left: 192, right: 192 });
|
||||||
|
const elastic = deviceMapper(canvas, { ...centered, mode: "elastic" }, items, tall);
|
||||||
|
assert.equal(elastic.mode, "elastic");
|
||||||
|
assert.ok(elastic.gapScale > 1);
|
||||||
|
assert.equal(elastic.insets, undefined);
|
||||||
|
assert.equal(deviceMapper(canvas, { ...centered, mode: "elastic" }, items, wide).mode, "contain");
|
||||||
|
const stretch = deviceMapper(canvas, { ...centered, mode: "stretch" }, items, tall);
|
||||||
|
assert.equal(stretch.insets, undefined);
|
||||||
|
assert.ok(stretch.sy > stretch.sx);
|
||||||
|
console.log("Tall and wide preview mappings passed");
|
||||||
|
|
||||||
|
assert.equal(alignmentGuide(82, 36, [100, 120], 4), 100);
|
||||||
|
assert.equal(alignmentGuide(82, 36, [120, 118], 4), 118);
|
||||||
|
assert.equal(alignmentGuide(82, 36, [122], 3), undefined);
|
||||||
|
assert.equal(alignmentGuide(0, 36, [0], 0), 0);
|
||||||
|
console.log("Drag alignment guides passed");
|
||||||
Reference in new issue
Block a user