Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/lib/modules/editor/core/document/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,14 +232,29 @@ export const newCondition = (): Condition => ({ source: 0x19, op: "gte", value:
// byte (meaning unknown) so a round trip stays exact. The 0x86 node toLegacy writes is derived
// from `name`, so it needs nothing here.
export function withName(doc: Doc, name: string): Doc {
const tail = doc.nameRaw ? unhex(doc.nameRaw)[15] : 0x0a;
const tail = capabilityByte(doc);
const head = new Uint8Array(16);

new TextEncoder().encodeInto(name.slice(0, 14), head.subarray(0, 15));
head[15] = tail;
return { ...doc, name, nameRaw: hex(head) };
}

/** Byte 0x17 controls which on-watch customization modes a face exposes. It is the last byte
* of the 16-byte header name field and buildBin mirrors the whole header into the footer. */
export const capabilityByte = (doc: Doc): number =>
doc.nameRaw ? (unhex(doc.nameRaw)[15] ?? 0x0a) : 0x0a;

export function withCapabilityByte(doc: Doc, byte: number): Doc {
const head = doc.nameRaw ? unhex(doc.nameRaw).slice() : new Uint8Array(16);

if (!doc.nameRaw) {
new TextEncoder().encodeInto((doc.name ?? "").slice(0, 14), head.subarray(0, 15));
}
head[15] = byte & 0xff;
return { ...doc, nameRaw: hex(head) };
}

const assetOf = (r: Resource): ImageAsset => ({
id: newImageId(),
cf: r.cf,
Expand Down
10 changes: 9 additions & 1 deletion src/lib/modules/editor/model/doc.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { createEvent, createStore, sample } from "effector";
import { reset } from "patronum";
import { findLayer, patchLayer } from "../core/document/edits";
import { withName } from "../core/document/factory";
import { withCapabilityByte, withName } from "../core/document/factory";
import {
toLegacy,
type Doc,
Expand Down Expand Up @@ -70,6 +70,7 @@ export const checkpoint = createEvent<number | void>();
export const undo = createEvent();
export const redo = createEvent();
export const renameFace = createEvent<string>();
export const capabilityByteSet = createEvent<number>();
/** A freshly opened or created document, replacing whatever was loaded. `cache` carries the
* decoded pixels, so the document and something to draw arrive in the same update. */
export const docLoaded = createEvent<{
Expand Down Expand Up @@ -151,6 +152,13 @@ sample({
fn: (doc, name) => withName(doc!, name),
target: $doc,
});
sample({
clock: capabilityByteSet,
source: $doc,
filter: Boolean,
fn: (doc, byte) => ({ edit: (current: Doc) => withCapabilityByte(current, byte) }),
target: committed,
});

// ---- history ----
sample({
Expand Down
79 changes: 62 additions & 17 deletions src/lib/modules/editor/model/edit.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,23 +292,69 @@ sample({
target: committed,
});

// ponytail: the copy shares its assets with the original, so resize/adjust/invert on one hits
// both. Splitting them means cloning every frame — do it if that ever surprises anyone.
const duplicated = createEvent<{
edit: (doc: Doc) => Doc;
added: NodeId;
cache: Map<ImageId, ImageCache>;
}>();

sample({
clock: duplicated,
fn: ({ edit }) => ({ edit }),
target: committed,
});
sample({
clock: duplicated,
fn: ({ added }) => ({ added }),
target: selectAdded,
});
sample({
clock: duplicated,
filter: ({ cache }) => cache.size > 0,
fn: ({ cache }) => cache,
target: cachePatched,
});

// Duplicates own their image assets, so adjustments to either layer stay independent.
sample({
clock: duplicateRequested,
source: $selected,
filter: (selected) => selected.length > 0,
source: { selected: $selected, doc: $doc, cache: $cache },
filter: ({ selected, doc }) => selected.length > 0 && Boolean(doc),
// cloned here rather than inside the edit so the new ids are known now and the selection can
// move to the copy, the way duplicating in any editor behaves
fn: (selected) => {
const copies = selected.map(cloneLayer);
fn: ({ selected, doc, cache }) => {
const images = new Map<ImageId, ImageAsset>();
const cached = new Map<ImageId, ImageCache>();
const copies = selected.map((layer) => {
const copy = cloneLayer(layer);
const remap = new Map<ImageId, ImageId>();

for (const id of assetsOf(layer)) {
const asset = doc!.images.get(id);

if (!asset) continue;
const fresh = newImageId();

remap.set(id, fresh);
images.set(fresh, { ...asset, id: fresh, data: asset.data.slice() });
const imageCache = cache.get(id);

if (imageCache) cached.set(fresh, { ...imageCache });
}
return repointFrames(copy, remap);
});

return {
edit: (doc: Doc) => selected.reduce((d, l, i) => insertAfter(d, l.id, copies[i]), doc),
edit: (current: Doc) => {
const withCopies = { ...current, images: new Map([...current.images, ...images]) };

return selected.reduce<Doc>((d, l, i) => insertAfter(d, l.id, copies[i]), withCopies);
},
added: copies[0].id,
cache: cached,
};
},
target: [committed, selectAdded],
target: duplicated,
});

// ---- clipboard ----
Expand Down Expand Up @@ -382,21 +428,20 @@ sample({
}),
target: committed,
});
const resolvePaste = (clip: Clip, doc: Doc): Pasted => {
// An id already in this document is the same picture only when it's the very same object —
// the counters restart per document, so everything else gets a fresh id and a copied asset.
const resolvePaste = (clip: Clip): Pasted => {
// Every paste gets private assets, even within the same document, so edits don't leak to the
// source layer. Asset IDs are also per-document, so copies need fresh IDs across documents.
const remap = new Map<ImageId, ImageId>();
const images = new Map<ImageId, ImageAsset>();
const cache = new Map<ImageId, ImageCache>();

for (const [id, a] of clip.images) {
if (doc.images.get(id) === a) continue;
const fresh = newImageId();
const c = clip.cache.get(id);

remap.set(id, fresh);
images.set(fresh, { ...a, id: fresh });
if (c) cache.set(fresh, c);
images.set(fresh, { ...a, id: fresh, data: a.data.slice() });
if (c) cache.set(fresh, { ...c });
}
return { layers: clip.layers.map((l) => repointFrames(cloneLayer(l), remap)), images, cache };
};
Expand All @@ -405,7 +450,7 @@ sample({
clock: pasteRequested,
source: { clip: $clipboard, doc: $doc },
filter: ({ clip, doc }) => Boolean(clip?.layers.length && doc),
fn: ({ clip, doc }) => resolvePaste(clip!, doc!),
fn: ({ clip }) => resolvePaste(clip!),
target: pasted,
});

Expand Down Expand Up @@ -446,9 +491,9 @@ sample({
});
sample({
clock: imported,
fn: ({ doc, clips }) =>
fn: ({ clips }) =>
clips
.map((clip) => resolvePaste(clip, doc!))
.map((clip) => resolvePaste(clip))
.reduce((a, b) => ({
layers: [...a.layers, ...b.layers],
images: new Map([...a.images, ...b.images]),
Expand Down
32 changes: 32 additions & 0 deletions src/lib/modules/editor/pages/editor.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { Icon } from "$lib/shared/components/icon";
import { holdCursor } from "$lib/shared/lib/hold-cursor";
import { Menu, MenuItem } from "$lib/shared/components/menu";
import { Select } from "$lib/shared/components/select";
import { authModel } from "$lib/modules/auth/model";
import { marketModel } from "$lib/modules/market/model";
import PublishDialog from "../components/PublishDialog.svelte";
Expand Down Expand Up @@ -48,6 +49,7 @@
type ShortcutActions,
} from "../shared/shortcuts";
import { editorModel } from "../model";
import { capabilityByte } from "../core/document/factory";
import TreePanel from "../components/TreePanel.svelte";
import PropsPanel from "../components/PropsPanel.svelte";
import SimPanel from "../components/SimPanel.svelte";
Expand Down Expand Up @@ -120,13 +122,30 @@
buildCurrentBin,
previewBlob,
previewThumb,
capabilityByteSet,
$showWatchFrame: showWatchFrame,
watchFrameToggled,
$rightPanel: rightPanel,
rightPanelSet,
$loading: loading,
} = editorModel;

const customizationOptions = [
{ value: "0x08", label: "No customization", short: "None" },
{ value: "0x0a", label: "Accent color customization", short: "Accent color" },
{ value: "0x0e", label: "Functions and color customization", short: "Functions + colors" },
];

function customizationValue() {
const byte = $doc ? capabilityByte($doc) : 0x0a;

// Stock files also contain function-only and mixed legacy flags. Classify them into the
// closest option until the user chooses a mode explicitly.
if (byte & 0x04) return "0x0e";
if (byte & 0x02) return "0x0a";
return "0x08";
}

let canvas = $state<HTMLCanvasElement | null>(null);
let fileInput = $state<HTMLInputElement>();
let dirInput = $state<HTMLInputElement>();
Expand Down Expand Up @@ -640,6 +659,13 @@
/>
</div>
<div class="zone end">
<span class="tool-slot customization" title="Watch customization">
<Select
options={customizationOptions}
value={customizationValue()}
onChange={(value) => capabilityByteSet(Number(value))}
/>
</span>
{#if $user}
<span
class="tool-slot"
Expand Down Expand Up @@ -971,6 +997,9 @@
.tool-slot {
display: inline-flex;
}
.customization {
width: 10.5rem;
}
/* a phone: document left, output right in the toolbar; the screen switch floats over the
top of the canvas instead of taking a row of its own */
@media (max-width: 767px) {
Expand All @@ -992,6 +1021,9 @@
backdrop-filter: blur(1rem);
}
}
.customization {
width: 7.5rem;
}
}
@media (min-width: 768px) {
.wf-name {
Expand Down
13 changes: 13 additions & 0 deletions tests/doc-factory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ import {
newProgressLine,
newRing,
progressLineOf,
capabilityByte,
withName,
withCapabilityByte,
} from "../src/lib/modules/editor/core/document/factory";
import {
progressLineColor,
Expand Down Expand Up @@ -130,6 +132,17 @@ test("renaming keeps the header's trailing byte and cuts only the header copy",
);
});

test("the selected customization mode reaches byte 0x17 and its footer mirror", () => {
const fresh = blankDoc("Custom", res(2, 2), res(SCREEN, SCREEN));
const doc = withCapabilityByte(fresh, 0x0e);
const built = buildBin(toLegacy(doc));

expect(capabilityByte(doc)).toBe(0x0e);
expect(built[0x17]).toBe(0x0e);
expect(built[built.length - 36 + 0x17]).toBe(0x0e);
expect(capabilityByte(withName(doc, "Renamed"))).toBe(0x0e);
});

// #61: the format has no linear gauge, so a progress line is a battery picker with one frame per
// percent — the node shape of Hemisphere's battery-percent text, whose 101 frames are rotated
// '0%'..'100%' text, not a gauge (a filling bar on it is unverified on a watch). Pinned against
Expand Down
28 changes: 22 additions & 6 deletions tests/editor-clipboard.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const importBins = (files: File[]) =>
/** A layer that actually carries pixels — the interesting case for the asset handling. */
const withFrames = (): Layer => layers().find((l) => framesOf(l).length > 0)!;

test("paste into the same document adds copies that share the original's assets", async () => {
test("paste into the same document adds copies with private assets", async () => {
await load("clip-same", dialUrl);
const src = withFrames();
const n = layers().length;
Expand All @@ -60,8 +60,18 @@ test("paste into the same document adds copies that share the original's assets"
const copy = layers().at(-1)!;

expect(copy.id).not.toBe(src.id);
expect(framesOf(copy)).toEqual(framesOf(src)); // same ids: no pixels were duplicated
expect(doc().images.size).toBe(assets);
const sourceFrames = framesOf(src);
const copiedFrames = framesOf(copy);

expect(copiedFrames).toHaveLength(sourceFrames.length);
expect(copiedFrames.some((id) => sourceFrames.includes(id))).toBe(false);
expect(doc().images.size).toBe(assets + new Set(copiedFrames).size);
copiedFrames.forEach((id, index) => {
const sourceId = sourceFrames[index];

expect(doc().images.get(id)!.data).not.toBe(doc().images.get(sourceId)!.data);
expect(doc().images.get(id)!.data).toEqual(doc().images.get(sourceId)!.data);
});
// and the paste is what's selected, the way it behaves in any editor
expect(editorModel.$sel.getState()).toBe(copy.id);
});
Expand Down Expand Up @@ -118,6 +128,8 @@ test("copying multiple layers pastes all of them, selected together", async () =
test("cut removes the layers and still pastes them back", async () => {
await load("clip-cut", dialUrl);
const src = withFrames();
const sourceFrames = framesOf(src);
const sourceData = sourceFrames.map((id) => doc().images.get(id)!.data);
const n = layers().length;

editorModel.select(src.id);
Expand All @@ -129,9 +141,13 @@ test("cut removes the layers and still pastes them back", async () => {
expect(layers().length).toBe(n);
const back = layers().at(-1)!;

// the clipboard was filled before the delete, so the pixels came back with it
expect(framesOf(back)).toEqual(framesOf(src));
expect(framesOf(back).every((id) => doc().images.has(id))).toBe(true);
// the clipboard was filled before the delete, so the pixels came back under fresh ids
const pastedFrames = framesOf(back);

expect(pastedFrames).toHaveLength(sourceFrames.length);
expect(pastedFrames.some((id) => sourceFrames.includes(id))).toBe(false);
expect(pastedFrames.every((id) => doc().images.has(id))).toBe(true);
expect(pastedFrames.map((id) => doc().images.get(id)!.data)).toEqual(sourceData);
});

test("importing several .bin files pastes every file's layers, each with its own pixels", async () => {
Expand Down
8 changes: 6 additions & 2 deletions tests/editor-new-nodes.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,12 @@ test("group wraps in place and duplicate copies the whole subtree", async () =>

expect(copy.id).not.toBe(groupId);
expect(copy.children).toHaveLength((byId(groupId) as GroupLayer).children.length);
// the copy shares the original's assets rather than cloning the pixels
expect(framesOf(copy.children[0])).toEqual(framesOf((byId(groupId) as GroupLayer).children[0]));
const sourceFrames = framesOf((byId(groupId) as GroupLayer).children[0]);
const copiedFrames = framesOf(copy.children[0]);

expect(copiedFrames).toHaveLength(sourceFrames.length);
expect(copiedFrames.some((id) => sourceFrames.includes(id))).toBe(false);
for (const id of copiedFrames) expect(doc().images.get(id)).toBeDefined();
});

test("visibility conditions stack up on the selection", async () => {
Expand Down