Initialize Compose Launcher source and deployment

This commit is contained in:
tongtong committed 2026-11-26 02:34:19 +08:00
commit 12a8c24441
77 files changed
+9594

No files matched your search

+432
View File
@@ -0,0 +1,432 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import {
ElButton, ElCheckbox, ElConfigProvider, ElInput, ElInputNumber, ElMessage, ElMessageBox,
ElOption, ElSelect, ElTabPane, ElTabs,
} from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import ReleaseDialog from "./ReleaseDialog.vue";
import LayoutSurface from "./LayoutSurface.vue";
import {
builtInLayout, clamp, copyLayout, devices, normalizeLayout, templates, validate,
type Layout, type LayoutItem, type Payload, type Template,
} from "./layout";
const draftKey = "vibe-launcher-draft-v3";
const layout = ref(builtInLayout());
const savedLayout = ref(JSON.stringify(layout.value));
try {
const draft = localStorage.getItem(draftKey);
if (draft) layout.value = normalizeLayout(JSON.parse(draft));
} catch {
ElMessage.warning("本地草稿无法读取");
}
const dirty = computed(() => JSON.stringify(layout.value) !== savedLayout.value);
watch(layout, () => {
try {
if (dirty.value) localStorage.setItem(draftKey, JSON.stringify(layout.value));
else localStorage.removeItem(draftKey);
} catch {
ElMessage.warning("无法保存本地草稿,请导出当前布局");
}
}, { deep: true });
async function confirmReplace() {
if (!dirty.value) return true;
try {
await ElMessageBox.confirm("当前画布有未发布的改动。替换前可以取消并导出草稿。", "替换当前画布", {
type: "warning", confirmButtonText: "替换", cancelButtonText: "取消",
});
return true;
} catch {
return false;
}
}
function markPublished(revision: number) {
layout.value.revision = revision;
savedLayout.value = JSON.stringify(layout.value);
}
const pageIndex = ref(0);
const selectedId = ref<string>();
const page = computed(() => layout.value.pages[pageIndex.value]!);
const selected = computed(() => page.value.items.find(item => item.id === selectedId.value));
const tab = ref("preview");
const snap = ref(true);
const guides = ref(true);
const release = ref(false);
const fileInput = ref<HTMLInputElement>();
const stage = ref<HTMLElement>();
const stageSize = ref({ width: 0, height: 0 });
const undoStack = ref<Layout[]>([]);
const redoStack = ref<Layout[]>([]);
const canvas = computed(() => layout.value.canvas);
const designScale = computed(() => Math.min(
1, Math.max(1, stageSize.value.width - 36) / canvas.value.designWidth,
Math.max(1, stageSize.value.height - 36) / canvas.value.designHeight,
));
const issues = computed(() => validate(layout.value));
const json = computed(() => JSON.stringify(layout.value, null, 2));
const hosted = ["https:", "http:"].includes(location.protocol);
const sizes = ["1080x1920", "1080x2160", "1080x2340", "1080x2400"];
const size = computed(() => canvas.value.designWidth + "x" + canvas.value.designHeight);
const fitModes = [
{ value: "contain", label: "等比居中" },
{ value: "elastic", label: "弹性行距" },
{ value: "stretch", label: "拉伸" },
];
const background = computed(() => page.value.background);
const backgrounds = [
{ value: "wallpaper", label: "系统壁纸" },
{ value: "solid", label: "纯色" },
{ value: "gradient", label: "渐变" },
];
const payloadFields: { key: keyof Pick<Payload, "label" | "package" | "provider" | "intent">; label: string; type?: string }[] = [
{ key: "label", label: "显示名称" }, { key: "package", label: "应用包名", type: "app_icon" },
{ key: "provider", label: "组件 Provider", type: "widget" }, { key: "intent", label: "快捷方式 Intent", type: "shortcut" },
];
const visiblePayload = computed(() => payloadFields.filter(field => !field.type || field.type === selected.value?.type));
const fields = ["x", "y", "w", "h", "z"] as const;
function remember() {
undoStack.value.push(copyLayout(layout.value));
if (undoStack.value.length > 60) undoStack.value.shift();
redoStack.value = [];
}
function restore(from: Layout[], to: Layout[]) {
const saved = from.pop();
if (!saved) return;
to.push(copyLayout(layout.value));
layout.value = { ...saved, revision: layout.value.revision };
selectPage(Math.min(pageIndex.value, saved.pages.length - 1));
}
function selectPage(index: number) {
pageIndex.value = index;
selectedId.value = undefined;
}
function changePages(add: boolean) {
remember();
if (add) {
layout.value.pages.splice(pageIndex.value + 1, 0, { index: 0, background: { type: "wallpaper" }, items: [] });
} else {
layout.value.pages.splice(pageIndex.value, 1);
}
layout.value.pages.forEach((entry, index) => { entry.index = index; });
selectPage(Math.min(pageIndex.value + Number(add), layout.value.pages.length - 1));
}
function changeSize(value: string) {
const [w, h] = value.split("x").map(Number);
if (!w || !h || value === size.value) return;
remember();
canvas.value.designWidth = w;
canvas.value.designHeight = h;
}
function updateValue<T extends object, K extends keyof T>(record: T, key: K, value: T[K] | undefined) {
if (value === undefined || value === record[key]) return;
remember();
record[key] = value;
}
const grid = (n: number) => snap.value ? Math.round(n / 12) * 12 : Math.round(n);
function addItem(template: Template, x?: number, y?: number) {
const count = page.value.items.length;
if (count >= 80) { ElMessage.warning("本页最多 80 个元素"); return; }
remember();
const w = Math.min(template.w, canvas.value.designWidth);
const h = Math.min(template.h, canvas.value.designHeight);
let suffix = count + 1;
while (page.value.items.some(item => item.id === "e" + suffix)) suffix++;
const item = {
id: "e" + suffix, type: template.type, w, h, z: 2, payload: { ...template.payload },
x: clamp(grid(x ?? 108 + count % 4 * 216), 0, canvas.value.designWidth - w),
y: clamp(grid(y ?? 300 + count % 3 * 60), 0, canvas.value.designHeight - h),
};
page.value.items.push(item);
selectedId.value = item.id;
tab.value = "properties";
}
function clickBlank(event: MouseEvent) {
if ((event.target as HTMLElement).closest(".layout-item")) return;
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
addItem(templates[0]!, (event.clientX - rect.left) / designScale.value - 66,
(event.clientY - rect.top) / designScale.value - 84);
}
function removeItem() {
if (!selected.value) return;
remember();
page.value.items = page.value.items.filter(item => item.id !== selectedId.value);
selectedId.value = undefined;
}
function changeLayer(item: LayoutItem, top: boolean) {
const layers = page.value.items.filter(entry => entry !== item).map(entry => entry.z);
if (!layers.length) return;
const layer = top ? Math.min(2147483647, Math.max(...layers) + 1)
: Math.max(-2147483648, Math.min(...layers) - 1);
updateValue(item, "z", layer);
}
function align() {
remember();
const round = (n: number) => Math.round(n / 12) * 12;
for (const item of page.value.items) {
item.w = clamp(round(item.w), 1, canvas.value.designWidth);
item.h = clamp(round(item.h), 1, canvas.value.designHeight);
item.x = clamp(round(item.x), 0, canvas.value.designWidth - item.w);
item.y = clamp(round(item.y), 0, canvas.value.designHeight - item.h);
}
ElMessage.success("已对齐到 12px 栅格");
}
let drag: { item: LayoutItem; original: LayoutItem; pointer: number; clientX: number; clientY: number;
resize: boolean; moved: boolean; scale: number } | undefined;
function startDrag(event: PointerEvent, item: LayoutItem, resize: boolean) {
if (!event.isPrimary || event.button !== 0 || drag) return;
event.stopPropagation();
selectedId.value = item.id;
drag = { item, original: { ...item }, pointer: event.pointerId, clientX: event.clientX,
clientY: event.clientY, resize, moved: false, scale: designScale.value };
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
}
function moveDrag(event: PointerEvent) {
if (!drag || event.pointerId !== drag.pointer) return;
const dx = (event.clientX - drag.clientX) / drag.scale;
const dy = (event.clientY - drag.clientY) / drag.scale;
if (!drag.moved) {
if (Math.hypot(event.clientX - drag.clientX, event.clientY - drag.clientY) < 3) return;
remember();
drag.moved = true;
}
const { item, original, resize } = drag;
if (resize) {
const right = Math.max(1, canvas.value.designWidth - item.x);
const bottom = Math.max(1, canvas.value.designHeight - item.y);
item.w = clamp(grid(original.w + dx), Math.min(24, right), right);
item.h = clamp(grid(original.h + dy), Math.min(24, bottom), bottom);
} else {
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));
}
}
function finishDrag(event: PointerEvent) {
if (drag?.pointer === event.pointerId) drag = undefined;
}
function keys(event: KeyboardEvent) {
if (release.value || drag || event.defaultPrevented ||
(event.target instanceof Element && event.target.closest("input,textarea,select,[contenteditable]"))) return;
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") {
event.preventDefault();
if (event.shiftKey) restore(redoStack.value, undoStack.value);
else restore(undoStack.value, redoStack.value);
} else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "y") {
event.preventDefault();
restore(redoStack.value, undoStack.value);
} else if (event.key === "Delete" && selected.value) {
event.preventDefault();
removeItem();
}
}
function loadLayout(value: Layout, online = false) {
remember();
layout.value = value;
if (online) savedLayout.value = JSON.stringify(value);
selectPage(0);
}
async function importFile(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
if (!file) return;
try {
if (file.size > 1024 * 1024) throw new Error("布局超过 1 MiB");
const imported = normalizeLayout(JSON.parse(await file.text()));
if (!(await confirmReplace())) return;
loadLayout(imported);
ElMessage.success("已导入 " + file.name);
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : "布局导入失败");
}
}
function download() {
const url = URL.createObjectURL(new Blob([json.value], { type: "application/json" }));
const link = document.createElement("a");
link.href = url;
link.download = "launcher_layout.json";
link.click();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
async function copyJson() {
try {
await navigator.clipboard.writeText(json.value);
ElMessage.success("已复制 JSON");
} catch {
tab.value = "json";
ElMessage.warning("无法访问剪贴板,可在 JSON 面板中复制");
}
}
function showIssues() {
tab.value = "rules";
if (!issues.value.length) ElMessage.success("校验通过");
}
const stageObserver = new ResizeObserver(([entry]) => {
if (entry) stageSize.value = { width: entry.contentRect.width, height: entry.contentRect.height };
});
onMounted(() => {
if (stage.value) stageObserver.observe(stage.value);
window.addEventListener("keydown", keys);
});
onUnmounted(() => {
stageObserver.disconnect();
window.removeEventListener("keydown", keys);
});
</script>
<template>
<ElConfigProvider :locale="zhCn" size="small">
<header class="toolbar">
<h1>桌面布局编辑器</h1>
<nav aria-label="编辑命令">
<ElButton :disabled="!undoStack.length" @click="restore(undoStack, redoStack)">撤销</ElButton>
<ElButton :disabled="!redoStack.length" @click="restore(redoStack, undoStack)">重做</ElButton>
<ElButton :disabled="!page.items.length" @click="align">对齐栅格</ElButton>
<ElButton :disabled="!selected" @click="removeItem">删除元素</ElButton>
<ElButton @click="showIssues">校验</ElButton>
<ElButton @click="fileInput?.click()">导入</ElButton>
<ElButton @click="download">导出</ElButton>
<ElButton v-if="hosted" type="primary" @click="release = true">布局发布</ElButton>
</nav>
<input ref="fileInput" type="file" accept=".json,application/json" hidden @change="importFile">
</header>
<div class="workspace">
<aside class="settings" aria-label="画布设置">
<section>
<h2>添加内容</h2>
<div class="templates">
<ElButton v-for="template in templates" :key="template.label" :disabled="page.items.length >= 80"
@click="addItem(template)">{{ template.label }}</ElButton>
</div>
</section>
<section>
<h2>画布</h2>
<label>基准尺寸
<ElSelect :model-value="size" aria-label="基准尺寸" @change="changeSize">
<ElOption v-for="option in new Set([...sizes, size])" :key="option" :value="option"
:label="option.replace('x', ' × ')" />
</ElSelect>
</label>
<label>顶部安全区 <ElInputNumber :model-value="canvas.safeTop" :min="0" :max="8192" :precision="0"
aria-label="顶部安全区" @change="updateValue(canvas, 'safeTop', $event)" /></label>
<label>底部安全区 <ElInputNumber :model-value="canvas.safeBottom" :min="0" :max="8192" :precision="0"
aria-label="底部安全区" @change="updateValue(canvas, 'safeBottom', $event)" /></label>
<ElCheckbox v-model="snap">吸附 12px 栅格</ElCheckbox>
<ElCheckbox v-model="guides">显示参考线</ElCheckbox>
</section>
<section>
<h2>本页背景</h2>
<ElSelect :model-value="background.type" aria-label="本页背景" @change="updateValue(background, 'type', $event)">
<ElOption v-for="option in backgrounds" :key="option.value" v-bind="option" />
<ElOption v-if="!backgrounds.some(option => option.value === background.type)" :value="background.type" />
</ElSelect>
<label v-if="background.type === 'solid'">背景颜色
<input type="color" :value="background.color || '#151a22'"
@change="updateValue(background, 'color', ($event.target as HTMLInputElement).value)">
</label>
<template v-if="background.type === 'gradient'">
<label>渐变起点 <input type="color" :value="background.from || '#151a22'"
@change="updateValue(background, 'from', ($event.target as HTMLInputElement).value)"></label>
<label>渐变终点 <input type="color" :value="background.to || '#151a22'"
@change="updateValue(background, 'to', ($event.target as HTMLInputElement).value)"></label>
</template>
</section>
<section>
<h2>映射策略</h2>
<ElSelect :model-value="layout.fit.mode" aria-label="映射策略" @change="updateValue(layout.fit, 'mode', $event)">
<ElOption v-for="option in fitModes" :key="option.value" v-bind="option" />
<ElOption v-if="!fitModes.some(option => option.value === layout.fit.mode)" :value="layout.fit.mode" />
</ElSelect>
<label>留白位置 <ElInputNumber :model-value="layout.fit.anchorY" :min="0" :max="1" :step="0.05"
aria-label="留白位置" @change="updateValue(layout.fit, 'anchorY', $event)" /></label>
</section>
</aside>
<main class="editor">
<div class="canvas-head">
<strong>设计稿</strong>
<span>{{ canvas.designWidth }} × {{ canvas.designHeight }}</span>
<span class="hint">双击空白添加图标 · 拖动右下角调整尺寸</span>
</div>
<div ref="stage" class="stage" @pointermove="moveDrag" @pointerup="finishDrag"
@pointercancel="finishDrag" @lostpointercapture="finishDrag">
<LayoutSurface :layout="layout" :page="page" :selected-id="selectedId" :guides="guides" editable
:style="{ width: (canvas.designWidth * designScale) + 'px' }"
@start-drag="startDrag" @clear="selectedId = undefined" @dblclick="clickBlank" />
</div>
<div class="page-bar" aria-label="布局页面">
<ElButton v-for="(_, index) in layout.pages" :key="index"
:type="index === pageIndex ? 'primary' : 'default'" @click="selectPage(index)">
第 {{ index + 1 }} 页
</ElButton>
<ElButton :disabled="layout.pages.length >= 20" @click="changePages(true)">新增页</ElButton>
<ElButton :disabled="layout.pages.length === 1" @click="changePages(false)">删除本页</ElButton>
</div>
</main>
<aside class="inspector" aria-label="预览与属性">
<ElTabs v-model="tab" stretch>
<ElTabPane label="设备预览" name="preview" lazy>
<div class="previews">
<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 label="属性" name="properties" lazy>
<div v-if="selected" :key="selected.id" class="item-properties">
<h2>{{ selected.payload.label || selected.type }}</h2>
<label>ID <ElInput :model-value="selected.id" readonly /></label>
<label v-for="field in fields" :key="field">{{ field.toUpperCase() }}
<ElInputNumber :model-value="selected[field]" :precision="0" :aria-label="field"
@change="updateValue(selected!, field, $event)" />
</label>
<label v-for="field in visiblePayload" :key="field.key">{{ field.label }}
<input class="property-input" :value="selected.payload[field.key] ?? ''"
@change="updateValue(selected!.payload, field.key, ($event.target as HTMLInputElement).value)">
</label>
<div class="json-actions">
<ElButton @click="changeLayer(selected!, true)">置顶</ElButton>
<ElButton @click="changeLayer(selected!, false)">置底</ElButton>
<ElButton @click="removeItem">删除</ElButton>
</div>
<label v-if="selected.type === 'dock_bg'">圆角
<ElInputNumber :model-value="selected.payload.radius ?? 56" :min="0" :precision="0"
aria-label="圆角" @change="updateValue(selected!.payload, 'radius', $event)" />
</label>
</div>
<p v-else class="empty">选择画布上的元素查看属性。</p>
</ElTabPane>
<ElTabPane :label="issues.length ? '校验 (' + issues.length + ')' : '校验'" name="rules" lazy>
<ul v-if="issues.length" class="issues">
<li v-for="(issue, index) in issues" :key="index" :class="issue.level">
<b>{{ issue.path }}</b><span>{{ issue.message }}</span>
</li>
</ul>
<p v-else class="empty">校验通过。</p>
</ElTabPane>
<ElTabPane label="JSON" name="json" lazy>
<div class="json-actions">
<ElButton @click="copyJson">复制 JSON</ElButton>
<ElButton @click="download">下载 JSON</ElButton>
<ElButton @click="loadLayout(builtInLayout())">重置示例</ElButton>
</div>
<pre>{{ json }}</pre>
</ElTabPane>
</ElTabs>
</aside>
</div>
<ReleaseDialog v-if="hosted" v-model="release" :layout="layout" :has-errors="issues.some(issue => issue.level === 'error')"
:confirm-replace="confirmReplace" :warnings="issues.filter(issue => issue.level === 'warning')"
@load="loadLayout" @published="markPublished" />
</ElConfigProvider>
</template>
+67
View File
@@ -0,0 +1,67 @@
<script setup lang="ts">
import { computed } from "vue";
import {
backgroundStyle, clamp, deviceMapper, devices, iconColor, sortedItems,
type Layout, type LayoutItem, type Page,
} from "./layout";
const props = defineProps<{
layout: Layout;
page: Page;
device?: typeof devices[number];
selectedId?: string;
editable?: boolean;
guides?: boolean;
}>();
const emit = defineEmits<{
startDrag: [event: PointerEvent, item: LayoutItem, resize: boolean];
clear: [];
}>();
const canvas = computed(() => props.layout.canvas);
const width = computed(() => props.device?.w ?? canvas.value.designWidth);
const height = computed(() => props.device?.h ?? canvas.value.designHeight);
const mapper = computed(() => 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 });
const items = computed(() => sortedItems(props.page));
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 percent = (n: number, total: number) => (n / total * 100) + "%";
function itemStyle(item: LayoutItem) {
const m = mapper.value;
return {
left: percent(m.x(item.x), width.value),
top: percent(m.y(item.y), height.value),
width: percent(item.w * m.sx, width.value),
height: percent(item.h * m.sy, height.value),
borderRadius: item.type === "dock_bg" ? Math.max(0, item.payload.radius ?? 56) * m.sx / width.value * 100 + "cqw" : undefined,
"--icon-fill": iconColor(item),
};
}
function title(item: LayoutItem) {
return item.payload.label || item.payload.package || item.payload.provider || item.payload.intent || item.type;
}
</script>
<template>
<div class="layout-surface" :class="{ editable, 'with-guides': guides }"
:style="{ aspectRatio: width + '/' + height, background: backgroundStyle(page.background) }"
@pointerdown="editable && emit('clear')">
<template v-if="editable">
<div class="safe-zone top" :style="{ height: percent(clamp(canvas.safeTop, 0, height), height) }"></div>
<div class="safe-zone bottom" :style="{ height: percent(clamp(canvas.safeBottom, 0, height), height) }"></div>
</template>
<div v-for="item in visible" :key="item.id" class="layout-item"
:class="[item.type, { selected: item.id === selectedId }]" :style="itemStyle(item)"
:title="title(item)" :tabindex="editable ? 0 : undefined"
@pointerdown="editable && emit('startDrag', $event, item, false)">
<template v-if="item.type === 'app_icon' || item.type === 'shortcut'">
<span class="icon-art">{{ (item.payload.label || title(item)).slice(0, 1).toUpperCase() }}</span>
<span class="icon-label">{{ title(item) }}</span>
</template>
<span v-else-if="item.type !== 'dock_bg'" class="widget-label">{{ title(item) }}</span>
<span v-if="editable" class="resize-handle" aria-hidden="true"
@pointerdown="emit('startDrag', $event, item, true)"></span>
</div>
</div>
</template>
+173
View File
@@ -0,0 +1,173 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import { ElButton, ElDialog, ElInput, ElMessageBox } from "element-plus";
import { normalizeLayout, type Issue, type Layout } from "./layout";
interface HistoryEntry { revision: number; publishedAt: string; restoredFrom?: number }
interface History { revisions: HistoryEntry[]; nextBefore: number | null }
const open = defineModel<boolean>({ required: true });
const props = defineProps<{ layout: Layout; hasErrors: boolean; confirmReplace: () => Promise<boolean>; warnings: Issue[] }>();
const emit = defineEmits<{ load: [layout: Layout, online?: boolean]; published: [revision: number] }>();
const token = ref("");
const tag = ref<string>();
const revision = ref<number>();
const history = ref<HistoryEntry[]>([]);
const nextBefore = ref<number | null>(null);
const busy = ref(false);
const status = ref("");
const error = ref(false);
const apiBase = new URL("./api/admin/", location.href);
watch(token, () => {
tag.value = revision.value = undefined;
nextBefore.value = null;
history.value = [];
status.value = "";
error.value = false;
});
async function request<T>(path: string, options: RequestInit = {}) {
const credential = token.value.trim();
if (!credential) throw new Error("请输入管理员令牌");
const headers = new Headers(options.headers);
headers.set("Authorization", "Bearer " + credential);
const response = await fetch(new URL(path, apiBase), {
...options, headers, cache: "no-store", redirect: "error",
signal: AbortSignal.timeout(10000),
});
if (response.status === 401 || response.status === 412 || response.status === 428) tag.value = undefined;
const data = await response.json().catch(() => null);
if (!response.ok) {
const issues: Issue[] = Array.isArray(data?.issues) ? data.issues.slice(0, 8) : [];
const message = response.status === 412
? "线上布局已更新。请先导出本地改动,再读取线上布局。"
: data?.message || "HTTP " + response.status;
throw new Error([message, ...issues.map(issue => issue.path + " · " + issue.message)].join("\n"));
}
if (!data) throw new Error("服务端返回的内容不是有效 JSON");
return { data: data as T, etag: response.headers.get("ETag") ?? undefined };
}
async function run(action: () => Promise<string>) {
if (busy.value) return;
busy.value = true;
error.value = false;
status.value = "正在连接服务端…";
try {
status.value = await action();
} catch (failure) {
error.value = true;
status.value = failure instanceof Error ? failure.message : "请求失败";
} finally {
busy.value = false;
}
}
async function loadHistory(append = false) {
const path = append ? "history?before=" + nextBefore.value : "history";
const { data } = await request<History>(path);
history.value = append ? [...history.value, ...data.revisions] : data.revisions;
nextBefore.value = data.nextBefore;
}
async function refreshHistory(message: string) {
history.value = [];
nextBefore.value = null;
try {
await loadHistory();
return message;
} catch {
return message + " 版本历史暂时读取失败。";
}
}
async function loadOnline() {
if (busy.value || !(await props.confirmReplace())) return;
return run(async () => {
const { data, etag } = await request<unknown>("layout");
const layout = normalizeLayout(data);
tag.value = etag;
revision.value = layout.revision;
emit("load", layout, true);
return refreshHistory("已读取线上 v" + layout.revision + ",可返回画布编辑。");
});
}
async function loadVersion(version: number) {
if (busy.value || !(await props.confirmReplace())) return;
return run(async () => {
const { data } = await request<unknown>("history/" + version);
const layout = normalizeLayout(data);
emit("load", { ...layout, revision: revision.value ?? layout.revision });
return "已载入 v" + version + ",当前线上为 v" + revision.value + "。";
});
}
async function confirmPublish(version?: number) {
const rollback = version !== undefined;
if (rollback && !(await props.confirmReplace())) return;
const warnings = props.warnings.slice(0, 5).map(issue => issue.path + " · " + issue.message);
if (props.warnings.length > 5) warnings.push("其余警告可在校验面板查看");
try {
await ElMessageBox.confirm(rollback ? "将 v" + version + " 的布局发布为新版本,应用到所有已连接设备?"
: ["将当前画布发布到所有已连接设备?", ...warnings].join("\n"), rollback ? "确认回滚" : "确认发布", {
type: "warning", confirmButtonText: rollback ? "回滚" : "发布", cancelButtonText: "取消",
});
} catch {
return;
}
return run(async () => {
if (!tag.value) throw new Error("发布前请先读取线上版本");
const { data, etag } = await request<Layout>(rollback ? "rollback" : "layout", {
method: rollback ? "POST" : "PUT",
headers: { "If-Match": tag.value, "Content-Type": "application/json" },
body: JSON.stringify(rollback ? { revision: version } : props.layout),
});
tag.value = etag;
revision.value = data.revision;
if (rollback) emit("load", normalizeLayout(data), true);
else emit("published", data.revision);
return refreshHistory("已发布 v" + data.revision + ",设备会在下次同步时更新。");
});
}
function moreHistory() {
return run(async () => {
await loadHistory(true);
return "当前线上为 v" + revision.value + "。";
});
}
</script>
<template>
<ElDialog v-model="open" title="布局发布" width="min(600px, calc(100vw - 32px))"
:close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy">
<label class="token-field">管理员令牌
<ElInput v-model="token" type="password" autocomplete="off" spellcheck="false"
aria-label="管理员令牌" :disabled="busy" @keyup.enter="loadOnline" />
</label>
<div class="release-actions">
<ElButton :disabled="busy" @click="loadOnline">读取线上布局</ElButton>
<ElButton type="primary" :disabled="busy || !tag || hasErrors" @click="confirmPublish()">发布当前画布</ElButton>
<ElButton :disabled="busy" @click="open = false">返回编辑</ElButton>
</div>
<p v-if="hasErrors" class="release-error">请先修正画布校验错误。</p>
<output class="release-status" :class="{ 'release-error': error }" aria-live="polite">{{ status }}</output>
<h2 v-if="history.length">发布历史</h2>
<ol v-if="history.length" class="release-history">
<li v-for="entry in history" :key="entry.revision">
<span>
<strong>v{{ entry.revision }}{{ entry.revision === revision ? '(当前)' : '' }}</strong>
<small v-if="entry.restoredFrom">回滚自 v{{ entry.restoredFrom }}</small>
<small>{{ new Date(entry.publishedAt).toLocaleString() }}</small>
</span>
<div v-if="entry.revision !== revision">
<ElButton :disabled="busy || !tag" @click="loadVersion(entry.revision)">载入编辑</ElButton>
<ElButton :disabled="busy || !tag" @click="confirmPublish(entry.revision)">回滚</ElButton>
</div>
</li>
</ol>
<ElButton v-if="nextBefore !== null" :disabled="busy || !tag" @click="moreHistory">更多版本</ElButton>
</ElDialog>
</template>
+203
View File
@@ -0,0 +1,203 @@
import defaultLayout from "../../android/app/src/main/assets/default_layout.json" with { type: "json" };
export interface Payload {
label?: string | null;
package?: string | null;
provider?: string | null;
intent?: string | null;
radius?: number | null;
}
export interface LayoutItem {
id: string;
type: string;
x: number;
y: number;
w: number;
h: number;
z: number;
payload: Payload;
}
export interface Background {
type: string;
color?: string;
from?: string;
to?: string;
}
export interface Page { index: number; background: Background; items: LayoutItem[] }
export interface Layout {
schemaVersion: 3;
revision: number;
canvas: { designWidth: number; designHeight: number; safeTop: number; safeBottom: number };
fit: { mode: string; anchorY: number };
pages: Page[];
}
export interface Issue { level: "error" | "warning"; path: string; message: string }
export type Template = Pick<LayoutItem, "type" | "w" | "h" | "payload"> & { label: string };
export const templates: Template[] = [
{ type: "app_icon", label: "应用图标", w: 132, h: 168, payload: { package: "com.tencent.mm", label: "微信" } },
{ type: "app_icon", label: "相机", w: 132, h: 168, payload: { package: "com.android.camera", label: "相机" } },
{ type: "widget", label: "时钟组件", w: 864, h: 320, payload: { provider: "com.android.deskclock/.ClockWidget", label: "时钟" } },
{ type: "widget", label: "天气组件", w: 420, h: 300, payload: { provider: "com.android.weather/.WeatherWidget", label: "天气" } },
{ type: "widget", label: "音乐组件", w: 420, h: 300, payload: { provider: "com.spotify/.MusicWidget", label: "音乐" } },
{ type: "shortcut", label: "快捷方式", w: 132, h: 168, payload: { intent: "weixin://scanqrcode", label: "扫一扫" } },
{ type: "dock_bg", label: "Dock 底板", w: 936, h: 200, payload: { radius: 56 } },
];
export const devices = [
{ name: "16:9", w: 1080, h: 1920 },
{ name: "16:8", w: 1080, h: 2160 },
{ name: "19.5:9", w: 1080, h: 2340 },
{ name: "2K 20:9", w: 1440, h: 3120 },
{ name: "16:10", w: 1440, h: 2304 },
{ name: "平板 4:3", w: 1600, h: 2560 },
];
const canvasDefaults = { designWidth: 1080, designHeight: 1920, safeTop: 132, safeBottom: 72 };
const fitDefaults = { mode: "contain", anchorY: 0.5 };
const object = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);
const int = (value: unknown): value is number => finite(value) && Number.isInteger(value)
&& value >= -2147483648 && value <= 2147483647;
export function normalizeLayout(raw: unknown): Layout {
if (!object(raw) || (raw.schemaVersion !== undefined && raw.schemaVersion !== 3)) throw new Error("仅支持 v3 布局");
if (raw.canvas !== undefined && !object(raw.canvas) || raw.fit !== undefined && !object(raw.fit)) {
throw new Error("画布或映射字段格式不正确");
}
const canvas = { ...canvasDefaults, ...raw.canvas };
const fit = { ...fitDefaults, ...raw.fit };
if (!Object.keys(canvasDefaults).every(key => int(canvas[key as keyof typeof canvasDefaults]))
|| canvas.designWidth < 320 || canvas.designHeight < 480 || canvas.designWidth > 8192
|| canvas.designHeight > 8192 || typeof fit.mode !== "string" || !finite(fit.anchorY)) {
throw new Error("画布尺寸或映射参数无效");
}
if (raw.revision !== undefined && !int(raw.revision)) throw new Error("版本号必须是整数");
if (!Array.isArray(raw.pages) || !raw.pages.length || raw.pages.length > 20) throw new Error("布局必须包含 1–20 页");
const pages = raw.pages.map((page, index) => {
if (!object(page) || page.items !== undefined && (!Array.isArray(page.items) || page.items.length > 80)) {
throw new Error("第 " + (index + 1) + " 页的元素格式有误或超过 80 项");
}
if (page.background !== undefined && (!object(page.background) ||
page.background.type !== undefined && typeof page.background.type !== "string" ||
["color", "from", "to"].some(key => object(page.background) && page.background[key] != null && typeof page.background[key] !== "string"))) {
throw new Error("页面背景格式无效");
}
const items = (page.items ?? []) as unknown[];
return {
...page, index, background: { type: "wallpaper", ...page.background } as Background,
items: items.map(item => {
if (!object(item) || typeof item.id !== "string" || typeof item.type !== "string" ||
!finite(item.x) || !finite(item.y) || !finite(item.w) || !finite(item.h) ||
item.z !== undefined && !int(item.z)) {
throw new Error("元素 ID、类型、尺寸或层级格式无效");
}
const payload = item.payload === undefined ? {} : item.payload;
if (!object(payload) || ["label", "package", "provider", "intent"].some(
key => payload[key] != null && typeof payload[key] !== "string",
) || payload.radius != null && !int(payload.radius)) throw new Error("元素内容格式无效");
return { ...item, id: item.id, type: item.type, x: item.x, y: item.y, w: item.w, h: item.h,
z: item.z ?? 1, payload };
}),
};
});
return { ...raw, schemaVersion: 3, revision: raw.revision ?? 1, canvas, fit, pages };
}
export const builtInLayout = () => normalizeLayout(structuredClone(defaultLayout));
export const copyLayout = (layout: Layout): Layout => JSON.parse(JSON.stringify(layout));
export const sortedItems = (page: Page) => [...page.items].sort((a, b) => a.z - b.z);
export const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, n));
const color = (value: string | undefined) =>
typeof value === "string" && /^#(?:[\da-f]{6}|[\da-f]{3})$/i.test(value) ? value : "#151a22";
export function backgroundStyle(bg: Background) {
if (bg.type === "solid") return color(bg.color);
if (bg.type === "gradient") return "linear-gradient(" + color(bg.from) + "," + color(bg.to) + ")";
return undefined;
}
export function validate(layout: Layout): Issue[] {
const issues: Issue[] = [];
const { designWidth, designHeight, safeTop, safeBottom } = layout.canvas;
const add = (level: Issue["level"], path: string, message: string) => issues.push({ level, path, message });
if (safeTop < 0 || safeBottom < 0) add("error", "画布", "安全区不能为负数");
if (safeTop + safeBottom >= designHeight) add("warning", "画布", "安全区总和达到画布高度");
if (safeTop < 118) add("warning", "顶部安全区", "顶部安全区偏小,内容可能被状态栏遮挡");
if (safeBottom < 40) add("warning", "底部安全区", "底部安全区偏小,内容可能被手势条遮挡");
if (!["contain", "elastic", "stretch"].includes(layout.fit.mode)) add("warning", "映射策略", "手机会按等比居中处理");
if (layout.fit.anchorY < 0 || layout.fit.anchorY > 1) add("warning", "留白位置", "应在 0–1 之间");
layout.pages.forEach((page, index) => {
const ids = new Set<string>();
page.items.forEach((item, i) => {
const path = "第 " + (index + 1) + " 页 · " + (item.payload.label || item.id || (i + 1));
if (!item.id.trim() || ids.has(item.id)) add("error", path, "ID 为空或重复");
ids.add(item.id);
if (item.x < 0 || item.y < 0 || item.w <= 0 || item.h <= 0 ||
item.x + item.w > designWidth + 0.5 || item.y + item.h > designHeight + 0.5) {
add("error", path, "尺寸无效或元素超出画布");
}
if (item.type === "app_icon" && !item.payload.package?.trim()) add("error", path, "应用图标需要包名");
if (item.type === "widget" && !item.payload.provider?.includes("/")) add("error", path, "组件需填写包名/类名");
if (item.type === "shortcut" && !item.payload.intent?.trim()) add("warning", path, "快捷方式缺少 Intent");
if (!templates.some(template => template.type === item.type)) add("warning", path, "手机会跳过未知类型");
if (item.y < safeTop || item.y + item.h > designHeight - safeBottom) add("warning", path, "元素进入安全区");
if (item.type !== "dock_bg" && page.items.slice(i + 1).some(other => other.type !== "dock_bg" &&
item.x < other.x + other.w && item.x + item.w > other.x &&
item.y < other.y + other.h && item.y + item.h > other.y)) {
add("warning", path, "元素与同页其他元素重叠");
}
});
});
return issues;
}
export function deviceMapper(canvas: Layout["canvas"], fit: Layout["fit"], items: LayoutItem[], dev: typeof devices[number]) {
const sx = dev.w / canvas.designWidth;
const sy = dev.h / canvas.designHeight;
const mode = fit.mode.toLowerCase();
if (mode === "stretch") return { sx, sy, x: (x: number) => x * sx, y: (y: number) => y * sy };
const extra = dev.h - canvas.designHeight * sx;
if (mode === "elastic" && extra > 0.5) {
const bands: [number, number][] = [];
const spans = items.map(item => [item.y, item.y + item.h] as const).sort((a, b) => a[0] - b[0]);
for (const [top, bottom] of spans) {
const last = bands.at(-1);
if (last && top < last[1] - 0.5) last[1] = Math.max(last[1], bottom);
else bands.push([top, bottom]);
}
let previous = 0;
let cumulative = 0;
const gaps = bands.map(([top, bottom]) => {
cumulative += Math.max(0, top - previous);
previous = bottom;
return [top, cumulative] as const;
});
const totalBlank = cumulative + Math.max(0, canvas.designHeight - previous) || 1;
return {
sx, sy: sx,
x: (x: number) => x * sx,
y: (y: number) => {
let blank = 0;
for (const [top, offset] of gaps) {
if (y < top - 0.5) break;
blank = offset;
}
return y * sx + blank * extra / totalBlank;
},
};
}
const scale = Math.min(sx, sy);
const ox = (dev.w - canvas.designWidth * scale) / 2;
const oy = (dev.h - canvas.designHeight * scale) * clamp(fit.anchorY, 0, 1);
return { sx: scale, sy: scale, x: (x: number) => ox + x * scale, y: (y: number) => oy + y * scale };
}
export function iconColor(item: LayoutItem) {
let hue = 0;
for (const char of item.payload.package || item.payload.label || item.id) {
hue = (hue * 31 + char.charCodeAt(0)) % 360;
}
return "linear-gradient(150deg,hsl(" + hue + " 62% 56%),hsl(" + (hue + 25) + " 55% 34%))";
}
+8
View File
@@ -0,0 +1,8 @@
import { createApp } from "vue";
import "element-plus/theme-chalk/index.css";
import "element-plus/theme-chalk/dark/css-vars.css";
import "./styles.css";
import App from "./App.vue";
document.documentElement.classList.add("dark");
createApp(App).mount("#app");
+122
View File
@@ -0,0 +1,122 @@
:root {
color-scheme: dark;
font-family: system-ui, "Microsoft YaHei UI", sans-serif;
font-size: 14px;
color: #e0e8f2;
background: #10151e;
}
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; }
#app { min-width: 320px; }
h1, h2, p, figure { margin: 0; }
h1 { font-size: 17px; white-space: nowrap; }
h2 { font-size: 13px; font-weight: 650; }
small { color: #9caec3; }
.toolbar {
display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap;
gap: 12px; padding: 14px 20px; border-bottom: 1px solid #2a3547; background: #161e2a;
}
.toolbar nav, .page-bar, .templates, .json-actions, .release-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.toolbar .el-button, .page-bar .el-button, .templates .el-button, .json-actions .el-button, .release-actions .el-button {
margin: 0;
}
.workspace {
display: grid; grid-template-columns: 224px minmax(0, 1fr) 348px;
height: calc(100dvh - 54px); min-height: 610px;
}
.settings, .inspector { overflow: auto; background: #151d29; }
.settings { border-right: 1px solid #2a3547; }
.settings section { display: grid; gap: 10px; padding: 16px; border-bottom: 1px solid #2a3547; }
.settings .el-checkbox { margin: 0; height: auto; }
.settings label, .item-properties label, .token-field {
display: grid; gap: 5px; font-size: 12px; color: #b7c5d7;
}
.settings label.el-checkbox { display: inline-flex; }
.settings .el-input-number, .item-properties .el-input-number { width: 100%; }
.settings input[type=color] { width: 100%; height: 28px; cursor: pointer; }
.editor { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.canvas-head {
display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; padding: 12px 16px;
color: #aebed0; border-bottom: 1px solid #2a3547;
}
.canvas-head strong { color: #e0e8f2; }
.hint { margin-left: auto; font-size: 12px; }
.stage {
flex: 1; min-height: 0; display: grid; place-items: center; overflow: hidden;
background: radial-gradient(ellipse at center, #222e42, #10151e 75%);
}
.layout-surface {
position: relative; overflow: hidden; width: 100%; container-type: inline-size;
isolation: isolate; background: linear-gradient(155deg, #263748, #141b2b 68%);
outline: 1px solid #42536b; border-radius: 5px;
}
.layout-surface.editable { touch-action: none; user-select: none; box-shadow: 0 12px 36px #050b16a6; }
.layout-surface.with-guides::before {
content: ""; position: absolute; inset: 0; pointer-events: none;
background: linear-gradient(#b3c8ea12 1px, transparent 1px), linear-gradient(90deg, #b3c8ea12 1px, transparent 1px);
background-size: 8.333% 5%;
}
.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.bottom { bottom: 0; border-top: 1px dashed #79b9fc; }
.layout-item {
position: absolute; display: flex; align-items: center; justify-content: center; flex-direction: column;
min-width: 0; min-height: 0; padding: 0; color: #f4f8fb; overflow: hidden;
}
.editable .layout-item { cursor: grab; }
.layout-item.selected, .editable .layout-item:focus-visible { outline: 1px solid #7bc2ff; outline-offset: -1px; }
.layout-item.widget { background: #6f91b442; border: 1px solid #9ab6d267; border-radius: 1.6cqw; }
.layout-item.dock_bg { background: #b0bfdd30; border: 1px solid #a3b8d44a; }
.icon-art {
display: grid; place-items: center; width: 74%; max-width: 15cqw; aspect-ratio: 1;
border-radius: 26%; background: var(--icon-fill); font-size: 4cqw; font-weight: bold;
}
.icon-label, .widget-label {
font-size: 2.55cqw; max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.widget-label { font-size: 3.1cqw; }
.resize-handle {
position: absolute; inset: auto 0 0 auto; width: 11px; height: 11px;
background: #a2d0fa; border-radius: 3px 0 0 0; cursor: nwse-resize; opacity: 0;
}
.selected > .resize-handle, .layout-item:hover > .resize-handle, .layout-item:focus-visible > .resize-handle { opacity: 1; }
.page-bar { border-top: 1px solid #2a3547; padding: 10px 12px; background: #161e2a; }
.inspector { border-left: 1px solid #2a3547; padding: 0 12px 12px; }
.previews { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 17px 12px; }
.previews figure { display: flex; align-items: center; flex-direction: column; justify-content: flex-end; gap: 8px; }
.previews figcaption { text-align: center; font-size: 12px; }
.previews small, .release-history small { display: block; font-size: 11px; }
.item-properties { display: grid; gap: 10px; }
.property-input {
width: 100%; height: 24px; padding: 0 8px; border: 1px solid var(--el-border-color);
border-radius: 4px; color: var(--el-text-color-regular); background: var(--el-fill-color-blank);
}
.property-input:focus { outline: 1px solid var(--el-color-primary); }
.empty { color: #9caec3; padding: 10px 0; }
.issues, .release-history { list-style: none; padding: 0; margin: 8px 0; }
.issues li { display: grid; gap: 4px; margin-bottom: 8px; padding: 8px; border-left: 2px solid #d7a754; }
.issues li.error { border-color: #f17c7c; }
pre { color: #a7ccea; font-size: 11px; max-width: 100%; overflow: auto; }
.release-actions { margin: 12px 0; }
.release-status { display: block; white-space: pre-wrap; margin-bottom: 12px; }
.release-error { color: #f49797; }
.release-history { max-height: 38vh; overflow: auto; }
.release-history li {
display: flex; gap: 10px; align-items: center; justify-content: space-between;
padding: 8px 0; border-top: 1px solid #394254;
}
@media (max-width: 1120px) {
.workspace { grid-template-columns: 188px minmax(0, 1fr) 288px; }
.hint { margin-left: 0; }
}
@media (max-width: 820px) {
.workspace { height: auto; grid-template-columns: 180px minmax(0, 1fr); }
.editor { min-height: 550px; }
.inspector { grid-column: 1 / -1; }
.previews { grid-template-columns: repeat(auto-fit, minmax(85px, 120px)); }
}
@media (max-width: 540px) {
.workspace { display: flex; flex-direction: column; }
.editor { order: -1; min-height: 520px; }
.settings { display: grid; grid-template-columns: 1fr 1fr; }
}