A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): drag a 9-slice border on the sprite instead of typing four numbers
yhh1c4313dce10e
diff --git a/desktop/src/components/NineSliceEditor.tsx b/desktop/src/components/NineSliceEditor.tsxnew file mode 100644index 000000000..7893a1e48--- /dev/null+++ b/desktop/src/components/NineSliceEditor.tsx@@ -0,0 +1,168 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file NineSliceEditor.tsx+ * @brief Drag the 9-slice border straight on the sprite, in the asset+ * inspector — the visual half of the four `sliceBorder.*` numbers.+ *+ * The border is import-time data (a texture's `.meta`), so this writes through+ * the SAME `FieldWrite` door the numeric fields use: the numbers, the dirty dot+ * and Save all keep working, and there is no second path into the `.meta`. The+ * control is a derived VIEW of those four fields, never its own state — the one+ * exception being the edge currently under the pointer, which is transient+ * interaction state.+ *+ * Geometry (letterbox fit, box↔texture conversion, the clamping that keeps a+ * centre slice alive) lives in `project/nineSlice.ts` as pure functions.+ */+import { useEffect, useRef, useState } from 'react';+import { t } from '@/i18n';+import type { FieldWrite } from '@/types';+import {+ SLICE_EDGES, borderFromImporter, clampBorder, edgeFromPointer, fitRect,+ guidePosition, hasBorder, isHorizontalEdge, pickEdge,+ type SliceEdge,+} from '@/project/nineSlice';++/** Box height — tall enough to aim a guide at, short enough that Import+ * Settings still open above the fold. */+const BOX_H = 168;++const EDGE_LABEL = {+ left: 'det.sliceLeft',+ right: 'det.sliceRight',+ top: 'det.sliceTop',+ bottom: 'det.sliceBottom',+} as const;++export function NineSliceEditor({ path, importer, write }: {+ path: string;+ importer: Record<string, unknown> | null;+ write: FieldWrite;+}) {+ const boxRef = useRef<HTMLDivElement>(null);+ const [tex, setTex] = useState<{ w: number; h: number } | null>(null);+ const [box, setBox] = useState({ w: 0, h: BOX_H });+ const [drag, setDrag] = useState<SliceEdge | null>(null);+ const [hover, setHover] = useState<SliceEdge | null>(null);++ // The texture's natural size — the units the border is expressed in.+ useEffect(() => {+ let alive = true;+ setTex(null);+ const img = new Image();+ img.onload = () => alive && setTex({ w: img.naturalWidth, h: img.naturalHeight });+ img.src = `estella://project/${path}`;+ return () => { alive = false; };+ }, [path]);++ // The drawn box is width-fluid (the inspector column), so measure it.+ useEffect(() => {+ const el = boxRef.current;+ if (!el) return;+ const measure = () => setBox({ w: el.clientWidth, h: el.clientHeight });+ measure();+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ const texW = tex?.w ?? 0;+ const texH = tex?.h ?? 0;+ // Values straight from the `.meta`, clamped for display: a hand-edited block+ // can hold a border that would collapse the centre slice.+ const border = clampBorder(borderFromImporter(importer), texW, texH);+ const fit = fitRect(texW, texH, box.w, box.h);++ const pointerIn = (e: React.PointerEvent): { x: number; y: number } => {+ const r = (e.currentTarget as HTMLElement).getBoundingClientRect();+ return { x: e.clientX - r.left, y: e.clientY - r.top };+ };++ const onPointerDown = (e: React.PointerEvent) => {+ if (fit.scale <= 0) return;+ const edge = pickEdge(pointerIn(e), border, fit, texW, texH);+ if (!edge) return;+ e.preventDefault();+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);+ setDrag(edge);+ };++ const onPointerMove = (e: React.PointerEvent) => {+ if (fit.scale <= 0) return;+ const at = pointerIn(e);+ if (!drag) {+ setHover(pickEdge(at, border, fit, texW, texH));+ return;+ }+ const next = edgeFromPointer(drag, at, fit, border, texW, texH);+ if (next !== border[drag]) write(`sliceBorder.${drag}`, 'number', next);+ };++ const endDrag = (e: React.PointerEvent) => {+ if (!drag) return;+ (e.currentTarget as HTMLElement).releasePointerCapture?.(e.pointerId);+ setDrag(null);+ };++ const active = drag ?? hover;+ const guides = fit.scale > 0+ ? SLICE_EDGES.map((edge) => ({ edge, at: guidePosition(edge, border, fit, texW, texH) }))+ : [];++ return (+ <div className="nse">+ <div+ ref={boxRef}+ className={`nse-box${drag ? ' is-dragging' : ''}`}+ style={{ height: BOX_H }}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={endDrag}+ onPointerCancel={endDrag}+ onPointerLeave={() => !drag && setHover(null)}+ title={t('det.sliceDragTip')}+ >+ {tex && (+ <img+ className="nse-img"+ src={`estella://project/${path}`}+ alt=""+ draggable={false}+ style={{ left: fit.x, top: fit.y, width: fit.w, height: fit.h }}+ />+ )}+ {/* The centre slice — the region that stretches. Shading it is what makes+ the border read as a 3x3 at a glance. */}+ {fit.scale > 0 && hasBorder(border) && (+ <div+ className="nse-center"+ style={{+ left: guidePosition('left', border, fit, texW, texH),+ top: guidePosition('top', border, fit, texW, texH),+ width: Math.max(0, guidePosition('right', border, fit, texW, texH) - guidePosition('left', border, fit, texW, texH)),+ height: Math.max(0, guidePosition('bottom', border, fit, texW, texH) - guidePosition('top', border, fit, texW, texH)),+ }}+ />+ )}+ {guides.map(({ edge, at }) => (+ <div+ key={edge}+ className={`nse-guide ${isHorizontalEdge(edge) ? 'v' : 'h'}${active === edge ? ' is-active' : ''}`}+ style={isHorizontalEdge(edge) ? { left: at } : { top: at }}+ />+ ))}+ {!tex && <div className="nse-empty">{t('det.sliceNoImage')}</div>}+ </div>+ <div className="nse-read">+ {SLICE_EDGES.map((edge) => (+ <span key={edge} className={`nse-val${active === edge ? ' is-active' : ''}`}>+ <em>{t(EDGE_LABEL[edge])}</em>+ {border[edge]}+ </span>+ ))}+ {tex && <span className="nse-dim">{texW} × {texH}</span>}+ </div>+ </div>+ );+}diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex 71f0e02e5..bff87a288 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -216,6 +216,17 @@ export const detailsMessages = defineMessages({'det.importSaved': { en: 'Import settings saved — size / compression apply on the next build', zh: '导入设置已保存——尺寸 / 压缩在下次构建时生效' },'det.importSaveFailed': { en: 'Failed to save import settings: {error}', zh: '保存导入设置失败:{error}' },'det.noImportSettings': { en: 'This asset type has no import settings.', zh: '此资产类型没有导入设置。' },++ // — 9-slice border editor (texture assets) —+ 'det.sliceDragTip': {+ en: 'Drag a guide to set the 9-slice border. The shaded centre is the part that stretches.',+ zh: '拖动参考线设置九宫格边框。阴影中心区域是会被拉伸的部分。',+ },+ 'det.sliceNoImage': { en: 'Image unavailable', zh: '图片不可用' },+ 'det.sliceLeft': { en: 'L', zh: '左' },+ 'det.sliceRight': { en: 'R', zh: '右' },+ 'det.sliceTop': { en: 'T', zh: '上' },+ 'det.sliceBottom': { en: 'B', zh: '下' },'det.audioSeekTip': { en: 'Click to seek', zh: '点击跳转播放位置' },'det.audioPlayTip': { en: 'Play / pause', zh: '播放 / 暂停' },'det.audioDecodeFailed': { en: 'Could not decode audio', zh: '无法解码音频' },diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex d1d4bda02..8609976f5 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -53,6 +53,8 @@ import { AssetIcon } from '@/components/icons';import { EventBindingSection } from '@/events/EventBindingSection';import { COMP_COLLIDER_SHAPE, type ColliderShapeKind } from '@/engine/colliderConvert';import { AudioWavePreview } from '@/components/AudioWavePreview';+import { NineSliceEditor } from '@/components/NineSliceEditor';+import { fsRefresh } from '@/project/fsWatch';import { Toasts } from '@/store/Toasts';import { baseName, assetTypeOf, IMAGE_RE } from '@/project/assetMeta';import { BUILTIN_PLATFORMS, type BuiltinPlatform } from '@/project/platforms';@@ -115,7 +117,7 @@ import { SearchField } from '@/components/SearchField';import { Select } from '@/components/Select';import { Segmented, type SegmentedOption } from '@/components/Segmented';import { AddComponentMenu } from '@/components/AddComponentMenu';-import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption, AssetType, GradientValue, GradientStop, CurveValue, CurveKey, DimensionValue, MapValue, InspectSource } from '@/types';+import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption, AssetType, GradientValue, GradientStop, CurveValue, CurveKey, DimensionValue, MapValue, InspectSource, FieldWrite } from '@/types';const AXES = ['x', 'y', 'z', 'w'];@@ -1167,7 +1169,8 @@ export function AssetControl({// A field write override (the live "Game" inspector routes edits to the realm// instead of the undoable SceneCommands path). When set, gestures are no-ops.-type FieldWrite = (key: string, type: InspectorField['type'], value: number | boolean | string | number[] | GradientValue | CurveValue | DimensionValue | MapValue) => void;+// The contract itself lives in types.ts — controls outside this panel (the+// 9-slice editor) write through the same one.// The write primitives for one field, shared by FieldRow and the compound// BoxSidesControl so both commit through the identical door: an edit fans out to@@ -3358,11 +3361,23 @@ function GenericAssetInspector({ path }: { path: string }) {const [collapsed, setCollapsed] = useState(false);const [usagesOpen, setUsagesOpen] = useState(false);- // Load the `.meta` importer block on (re)selection.+ // Reset to the loading state when the SELECTION moves (not on a refresh).useEffect(() => {- let alive = true;setImporter(null);setDirty(false);+ }, [path]);++ // Load the `.meta` importer block on (re)selection, and re-read whenever the+ // watcher reports a filesystem change: a `.meta` written outside this panel —+ // git, a build step, an automation client — otherwise leaves the inspector+ // showing values that no longer exist on disk. An unsaved edit always wins;+ // re-reading over it would silently discard the user's work.+ const fsVersion = useSyncExternalStore(fsRefresh.subscribe, fsRefresh.get);+ const dirtyNow = useRef(dirty);+ dirtyNow.current = dirty;+ useEffect(() => {+ if (dirtyNow.current) return;+ let alive = true;void window.estella.fs.read(path + '.meta').then((t) => alive && setImporter(((JSON.parse(t).importer as Record<string, unknown>) ?? {})))@@ -3370,7 +3385,7 @@ function GenericAssetInspector({ path }: { path: string }) {return () => {alive = false;};- }, [path]);+ }, [path, fsVersion]);// Metadata: disk stat, image dimensions, and how many assets reference this one.useEffect(() => {@@ -3470,6 +3485,11 @@ function GenericAssetInspector({ path }: { path: string }) {Import Settings sit above the fold (the reason to open an asset). */}{type === 'audio' ? (<AudioWavePreview path={path} />+ ) : isImage && importer && (type === 'texture' || type === 'sprite') ? (+ // A texture's preview IS its 9-slice editor: the border is the one+ // import setting you cannot sensibly type in, and it writes through+ // the same `write` door as the numbers below.+ <NineSliceEditor path={path} importer={importer} write={write} />) : type === 'video' ? (<div className="cb-prev" style={{ height: 160 }}><videodiff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex 9153421f5..acf3b17f8 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -18,7 +18,7 @@*/import {Folder, Film, Image, FileImage, PersonStanding, Music,- Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints, Sparkles, Plug,+ Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints, Sparkles, Plug, Type,type LucideIcon,} from 'lucide-react';import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';@@ -63,6 +63,9 @@ export const ASSET_TYPES: Record<BuiltinAssetType, AssetTypeDef> = {badge: 'DB', icon: PersonStanding, tint: '#a89b6b',},audio: { extensions: ['ogg', 'mp3', 'wav', 'aac', 'flac', 'm4a', 'webm'], badge: 'AUD', icon: Music, tint: '#7faf9c' },+ // Outline fonts a project ships (Text.font). Bitmap fonts (.fnt/.bmfont) are a+ // different asset — a baked page + metrics for BitmapText — and stay separate.+ font: { extensions: ['ttf', 'otf', 'woff', 'woff2'], badge: 'FNT', icon: Type, tint: '#9a9fc4' },video: { extensions: ['mp4', 'm4v', 'mov'], badge: 'VID', icon: Video, tint: '#c08fb5' },prefab: { extensions: ['esprefab'], badge: 'PFB', icon: Component, tint: '#c2a274' },// .esmaterial is the real extension (the SDK MaterialAssetLoader only loads it);diff --git a/desktop/src/project/nineSlice.ts b/desktop/src/project/nineSlice.tsnew file mode 100644index 000000000..df92a34cc--- /dev/null+++ b/desktop/src/project/nineSlice.ts@@ -0,0 +1,146 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file nineSlice.ts — the geometry behind the 9-slice border editor.+ *+ * A 9-slice border is four insets in TEXTURE pixels, one per edge. The editor+ * draws the texture letterboxed into whatever box the inspector gives it and+ * lets the user drag four guides; everything that converts between those two+ * spaces, and every rule about what a border may be, lives here as pure+ * functions so it is testable without a DOM.+ *+ * The invariant that matters: opposite borders may never cross or meet, because+ * the centre slice would collapse and the renderer would have nothing to+ * stretch. Each edge is therefore clamped against its opposite, not just+ * against the texture bounds.+ */++/** The four edge insets, in texture pixels. */+export interface SliceBorder {+ left: number;+ right: number;+ top: number;+ bottom: number;+}++export type SliceEdge = keyof SliceBorder;++export const SLICE_EDGES: readonly SliceEdge[] = ['left', 'right', 'top', 'bottom'];++/** Which axis an edge runs against: left/right are horizontal insets. */+export const isHorizontalEdge = (edge: SliceEdge): boolean => edge === 'left' || edge === 'right';++/** A texture letterboxed into `box`, centred, never upscaled past the box. */+export interface FitRect {+ x: number;+ y: number;+ w: number;+ h: number;+ /** Box pixels per texture pixel. */+ scale: number;+}++export function fitRect(texW: number, texH: number, boxW: number, boxH: number): FitRect {+ // scale 0 marks "no mapping exists" — callers convert box↔texture through it,+ // and a fake 1:1 here would silently turn a not-yet-measured box into edits.+ if (texW <= 0 || texH <= 0 || boxW <= 0 || boxH <= 0) return { x: 0, y: 0, w: 0, h: 0, scale: 0 };+ const scale = Math.min(boxW / texW, boxH / texH);+ const w = texW * scale;+ const h = texH * scale;+ return { x: (boxW - w) / 2, y: (boxH - h) / 2, w, h, scale };+}++/** Round to whole texture pixels — a border is a pixel count, never a fraction. */+const snap = (n: number): number => Math.round(n);++/**+ * Clamp one edge against the texture bounds and its opposite edge, leaving at+ * least one pixel of centre slice. `size` is the texture extent on that edge's+ * axis (width for left/right, height for top/bottom).+ */+export function clampEdge(value: number, opposite: number, size: number): number {+ const room = Math.max(0, size - Math.max(0, opposite) - 1);+ return Math.max(0, Math.min(snap(value), room));+}++/** Clamp a whole border — used when adopting values from a hand-edited `.meta`. */+export function clampBorder(border: SliceBorder, texW: number, texH: number): SliceBorder {+ const left = Math.max(0, Math.min(snap(border.left), Math.max(0, texW - 1)));+ const top = Math.max(0, Math.min(snap(border.top), Math.max(0, texH - 1)));+ return {+ left,+ top,+ right: clampEdge(border.right, left, texW),+ bottom: clampEdge(border.bottom, top, texH),+ };+}++/**+ * The new value for `edge` when its guide is dragged to `pointer` (box-space+ * px, relative to the box origin). Converts to texture space through `fit`,+ * measures the inset from that edge, and clamps.+ */+export function edgeFromPointer(+ edge: SliceEdge,+ pointer: { x: number; y: number },+ fit: FitRect,+ border: SliceBorder,+ texW: number,+ texH: number,+): number {+ if (fit.scale <= 0) return border[edge];+ const tx = (pointer.x - fit.x) / fit.scale;+ const ty = (pointer.y - fit.y) / fit.scale;+ switch (edge) {+ case 'left': return clampEdge(tx, border.right, texW);+ case 'right': return clampEdge(texW - tx, border.left, texW);+ case 'top': return clampEdge(ty, border.bottom, texH);+ case 'bottom': return clampEdge(texH - ty, border.top, texH);+ }+}++/** Where an edge's guide sits in box space (px from the box origin). */+export function guidePosition(edge: SliceEdge, border: SliceBorder, fit: FitRect, texW: number, texH: number): number {+ switch (edge) {+ case 'left': return fit.x + border.left * fit.scale;+ case 'right': return fit.x + (texW - border.right) * fit.scale;+ case 'top': return fit.y + border.top * fit.scale;+ case 'bottom': return fit.y + (texH - border.bottom) * fit.scale;+ }+}++/**+ * The edge whose guide is within `slop` box-px of `pointer`, or null. Ties go to+ * the nearest; a click in open space grabs nothing (so the user can't nudge a+ * border by mis-clicking the middle of the image).+ */+export function pickEdge(+ pointer: { x: number; y: number },+ border: SliceBorder,+ fit: FitRect,+ texW: number,+ texH: number,+ slop = 6,+): SliceEdge | null {+ let best: SliceEdge | null = null;+ let bestD = slop;+ for (const edge of SLICE_EDGES) {+ const at = guidePosition(edge, border, fit, texW, texH);+ const d = Math.abs((isHorizontalEdge(edge) ? pointer.x : pointer.y) - at);+ if (d <= bestD) {+ bestD = d;+ best = edge;+ }+ }+ return best;+}++/** True when the border actually slices — all-zero means "no 9-slice". */+export const hasBorder = (b: SliceBorder): boolean => b.left > 0 || b.right > 0 || b.top > 0 || b.bottom > 0;++/** Read a border out of an importer block (dotted `sliceBorder.*` keys). */+export function borderFromImporter(importer: Record<string, unknown> | null | undefined): SliceBorder {+ const raw = (importer?.sliceBorder ?? {}) as Partial<Record<SliceEdge, unknown>>;+ const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0);+ return { left: num(raw.left), right: num(raw.right), top: num(raw.top), bottom: num(raw.bottom) };+}diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex 18ad5c937..022ef9a85 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -397,6 +397,79 @@font-variant-numeric: tabular-nums;}+/* 9-slice border editor (NineSliceEditor) — drag the border on the sprite. */+.nse {+ display: flex;+ flex-direction: column;+ border-bottom: 1px solid var(--line);+ background: var(--inset);+}+.nse-box {+ position: relative;+ width: 100%;+ overflow: hidden;+ cursor: crosshair;+ touch-action: none;+ /* Checkerboard, so a transparent sprite's own edges stay readable against+ the guides that are being placed on top of them. */+ background-image:+ linear-gradient(45deg, var(--srf-2) 25%, transparent 25%),+ linear-gradient(-45deg, var(--srf-2) 25%, transparent 25%),+ linear-gradient(45deg, transparent 75%, var(--srf-2) 75%),+ linear-gradient(-45deg, transparent 75%, var(--srf-2) 75%);+ background-size: 12px 12px;+ background-position: 0 0, 0 6px, 6px -6px, -6px 0;+}+.nse-box.is-dragging { cursor: grabbing; }+.nse-img {+ position: absolute;+ image-rendering: pixelated;+ user-select: none;+ pointer-events: none;+}+.nse-center {+ position: absolute;+ pointer-events: none;+ background: var(--star-dim);+ outline: 1px dashed var(--star-line);+ outline-offset: -1px;+}+.nse-guide {+ position: absolute;+ pointer-events: none;+ background: var(--star);+ opacity: 0.75;+}+.nse-guide.v { top: 0; bottom: 0; width: 1px; margin-left: -0.5px; }+.nse-guide.h { left: 0; right: 0; height: 1px; margin-top: -0.5px; }+.nse-guide.is-active { opacity: 1; box-shadow: 0 0 0 1px var(--star-dim); }+.nse-guide.v.is-active { width: 2px; margin-left: -1px; }+.nse-guide.h.is-active { height: 2px; margin-top: -1px; }+.nse-empty {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ color: var(--text-faint);+ font-size: var(--fs-2xs);+}+.nse-read {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 4px 8px;+ border-top: 1px solid var(--line);+ background: var(--srf-2);+ font-size: var(--fs-2xs);+ font-variant-numeric: tabular-nums;+ color: var(--text-dim);+}+.nse-val { display: inline-flex; gap: 3px; }+.nse-val em { font-style: normal; color: var(--text-faint); }+.nse-val.is-active { color: var(--star-hi); }+.nse-val.is-active em { color: var(--star-hi); }+.nse-dim { margin-left: auto; color: var(--text-faint); }+/* Map (key→value) field editor — Marker custom properties. One row per pair. */.map-field { display: flex; flex-direction: column; gap: 4px; width: 100%; }.map-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr) auto; gap: 4px; align-items: center; }diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 4c310cf01..d68bca97b 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -101,6 +101,20 @@ export type InspectorFieldValue =| DimensionValue| MapValue;+/**+ * How an inspector control commits a value. The one write contract shared by+ * every inspector surface — entity components, materials, the anim-clip+ * document, and asset import settings — so a control written against it drops+ * into any of them without knowing which store is behind it.+ */+export type FieldWrite = (+ key: string,+ type: InspectorFieldType,+ // `number[]` alongside the fixed-length tuples: the vec/sides controls build+ // their arrays by mapping over edges, which widens the tuple away.+ value: InspectorFieldValue | number[],+) => void;+export interface InspectorField {/** key in the component data object */key: string;@@ -220,6 +234,7 @@ export type BuiltinAssetType =| 'animatorcontroller'| 'behaviortree'| 'locale'+ | 'font'| 'file';/** A built-in asset type, or one a plugin contributed. */diff --git a/desktop/tests/nine-slice.test.ts b/desktop/tests/nine-slice.test.tsnew file mode 100644index 000000000..ef9a97274--- /dev/null+++ b/desktop/tests/nine-slice.test.ts@@ -0,0 +1,137 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The 9-slice border editor's geometry. Pure functions, no DOM: the+ * letterbox fit, the box↔texture conversion a drag goes through, and the+ * clamping rule that keeps a centre slice alive.+ */+import { describe, it, expect } from 'vitest';+import {+ fitRect, clampEdge, clampBorder, edgeFromPointer, guidePosition, pickEdge,+ hasBorder, borderFromImporter, type SliceBorder,+} from '@/project/nineSlice';++const B = (left = 0, right = 0, top = 0, bottom = 0): SliceBorder => ({ left, right, top, bottom });++describe('fitRect', () => {+ it('letterboxes a wide texture into a square box and centres it', () => {+ const f = fitRect(200, 100, 100, 100);+ expect(f.scale).toBe(0.5);+ expect(f).toMatchObject({ x: 0, y: 25, w: 100, h: 50 });+ });++ it('pillarboxes a tall texture', () => {+ const f = fitRect(100, 200, 100, 100);+ expect(f).toMatchObject({ x: 25, y: 0, w: 50, h: 100, scale: 0.5 });+ });++ it('degenerates safely on a zero-sized texture or box', () => {+ expect(fitRect(0, 100, 50, 50)).toMatchObject({ w: 0, h: 0 });+ expect(fitRect(100, 100, 0, 50)).toMatchObject({ w: 0, h: 0 });+ });+});++describe('clampEdge', () => {+ it('snaps to whole pixels and floors at zero', () => {+ expect(clampEdge(12.4, 0, 100)).toBe(12);+ expect(clampEdge(-5, 0, 100)).toBe(0);+ });++ it('leaves at least one pixel of centre slice against the opposite edge', () => {+ // 100 wide with a 40px opposite border → this edge may reach 59, not 60.+ expect(clampEdge(999, 40, 100)).toBe(59);+ expect(clampEdge(59, 40, 100)).toBe(59);+ });++ it('collapses to zero when the opposite edge already fills the texture', () => {+ expect(clampEdge(10, 100, 100)).toBe(0);+ });+});++describe('clampBorder', () => {+ it('passes a legal border through untouched', () => {+ expect(clampBorder(B(10, 12, 8, 9), 64, 64)).toEqual(B(10, 12, 8, 9));+ });++ it('reins in a hand-edited .meta whose borders overlap', () => {+ const c = clampBorder(B(60, 60, 0, 0), 64, 64);+ expect(c.left).toBe(60);+ expect(c.right).toBe(3); // 64 - 60 - 1+ });+});++describe('edgeFromPointer', () => {+ // A 100x100 texture drawn 1:1 at the box origin.+ const fit = fitRect(100, 100, 100, 100);++ it('measures left/top from the near edge', () => {+ expect(edgeFromPointer('left', { x: 20, y: 50 }, fit, B(), 100, 100)).toBe(20);+ expect(edgeFromPointer('top', { x: 50, y: 15 }, fit, B(), 100, 100)).toBe(15);+ });++ it('measures right/bottom from the FAR edge', () => {+ expect(edgeFromPointer('right', { x: 70, y: 50 }, fit, B(), 100, 100)).toBe(30);+ expect(edgeFromPointer('bottom', { x: 50, y: 80 }, fit, B(), 100, 100)).toBe(20);+ });++ it('converts through the letterbox scale and offset', () => {+ const half = fitRect(200, 200, 100, 100); // scale 0.5, no offset+ expect(edgeFromPointer('left', { x: 20, y: 0 }, half, B(), 200, 200)).toBe(40);+ const boxed = fitRect(100, 50, 100, 100); // scale 1, y offset 25+ expect(edgeFromPointer('top', { x: 0, y: 35 }, boxed, B(), 100, 50)).toBe(10);+ });++ it('cannot be dragged past its opposite edge', () => {+ expect(edgeFromPointer('left', { x: 95, y: 50 }, fit, B(0, 30), 100, 100)).toBe(69);+ });++ it('is a no-op on a degenerate fit', () => {+ expect(edgeFromPointer('left', { x: 10, y: 10 }, fitRect(0, 0, 0, 0), B(7), 0, 0)).toBe(7);+ });+});++describe('guidePosition', () => {+ it('round-trips with edgeFromPointer', () => {+ const fit = fitRect(128, 64, 256, 256); // scale 2, y offset 64+ const border = B(12, 20, 5, 9);+ for (const edge of ['left', 'right', 'top', 'bottom'] as const) {+ const at = guidePosition(edge, border, fit, 128, 64);+ const p = edge === 'left' || edge === 'right' ? { x: at, y: 0 } : { x: 0, y: at };+ expect(edgeFromPointer(edge, p, fit, border, 128, 64)).toBe(border[edge]);+ }+ });+});++describe('pickEdge', () => {+ const fit = fitRect(100, 100, 100, 100);+ const border = B(20, 20, 20, 20);++ it('grabs the guide under the pointer', () => {+ expect(pickEdge({ x: 21, y: 50 }, border, fit, 100, 100)).toBe('left');+ expect(pickEdge({ x: 79, y: 50 }, border, fit, 100, 100)).toBe('right');+ expect(pickEdge({ x: 50, y: 22 }, border, fit, 100, 100)).toBe('top');+ });++ it('grabs nothing in open space, so a stray click cannot nudge a border', () => {+ expect(pickEdge({ x: 50, y: 50 }, border, fit, 100, 100)).toBeNull();+ });++ it('honours the slop radius', () => {+ expect(pickEdge({ x: 28, y: 50 }, border, fit, 100, 100, 2)).toBeNull();+ expect(pickEdge({ x: 28, y: 50 }, border, fit, 100, 100, 10)).toBe('left');+ });+});++describe('reading a border', () => {+ it('hasBorder is false only when every edge is zero', () => {+ expect(hasBorder(B())).toBe(false);+ expect(hasBorder(B(0, 0, 1))).toBe(true);+ });++ it('borderFromImporter tolerates a missing or junk block', () => {+ expect(borderFromImporter(null)).toEqual(B());+ expect(borderFromImporter({})).toEqual(B());+ expect(borderFromImporter({ sliceBorder: { left: 8, right: 'x', top: null } })).toEqual(B(8));+ expect(borderFromImporter({ sliceBorder: { left: 4, right: 5, top: 6, bottom: 7 } })).toEqual(B(4, 5, 6, 7));+ });+});