Recurring cleanup round over the code since round 7 (bc688f3). The
issue now also asks to fix bugs and small inconsistencies found on the
way, so unlike the rounds before, this one changes behaviour in a few
places. Duplicated code in api went from 23 clones with 228 lines to
none (jscpd, at least 50 tokens). In src it stays at 22 clones with
271 lines, the same before and after.
Bugs:
- nginx served project and snapshot files as they were, so anyone who
knew a project id could read it without signing in. Every file the
API writes now goes through AtomicFile (temp file, mode, rename).
Projects, snapshots, releases, accounts and sessions are 0640, and
nginx answers 403 for them.
- Any signed-in account could delete a shared image, font or sound,
which projects of other accounts may wear. Deleting one is now for
administrators only. The editor never deleted a file, so the
client's delete is gone.
- Two saves of one project could run at once. The lock file was
removed after each save, so a waiting save and the next one locked
different files. The lock file now stays, and deleting a project
takes the lock as well.
- Bytes that are no picture got a 500 instead of a 422, because the
error handler also threw for warnings silenced with @.
- A session file was rewritten in place. A request reading it at that
moment found it empty and was signed out. It is replaced atomically.
- Delete did nothing for a shape picked in the vector art list. Delete
now goes through removeSelection, one case per kind of selection,
and a kind without a case fails the type check.
Inconsistencies:
- Escape on a question does what its Cancel does. Cancel on "Delete
project?" and "Restore snapshot?" leads back to the picker or the
list like the other questions did, and so does deleting a project.
- Editor texts use American spelling throughout, like the port names:
48 British spellings in 45 lines (colour, centre, initialised).
- objectName and groupName replace eleven copies of "own name, else
the asset's" and three of "Group". One copy fell back to the object
id instead of "?".
Duplicates, dead code, comments:
- routeFiles serves images, fonts and sounds instead of three copies.
HashedFileStore holds what the three stores shared: keeping a file
under its hash with its name, listing and deleting. The stores keep
only which bytes they take and what a record says.
- AtomicFile replaces nine copies of temp file plus rename.
- removeShapes is the one way the canvas, the inspector button and
Delete take shapes out.
- GraphInterpreter.fire was called by tests only. The 54 calls use a
helper in tests/helpers.ts now.
- FileStore.delete, HttpFileStore.delete and the PluginApi type were
unused. A doc comment in actions.ts sat above the wrong function.
Checked and left as is:
- solidCells is used by tests only. It is the per-cell view before the
merge into rectangles, the one place the largest-scale rule shows.
- An undo checker ran all 124 commands of the unit tests and compared
the project before and after undo. The only differences are empty
ports, groups and notes lists where there were none, which the file
format drops anyway.
Docs:
- README: the check sum.
- Wiki, own commit: API (admin-only deletes, 422, file modes, lock
file), Home (the "Not yet" list named three things that exist),
Concepts, Keyboard, Vector art, Architecture and Development, and
the 38 characters Gitea flagged as ambiguous on eight pages.
- .gitignore: the lock files, and pasted-*.png in any folder, which
keeps the screenshot archive out.
Tests:
- ./check.sh: 195 files, 2817 tests, exit 0 (+2 for the name helpers).
- PHP: accounts 52 in the web container and 53 in the CI image with
the race test (+2), snapshots 15 (+1), releases 20.
- Full e2e run: ALL PASSED, 1586 checks (+6 in 12, 47, 49 and 50).
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks. The example
project files were restored byte for byte afterwards.
- The file stores of HEAD and of this commit give byte-identical
output for the live folders and for store, list and delete in a
throwaway folder.
- Counter-checks, all fail as expected: a 500 for bad bytes fails 12,
no admin check fails 49, removing the lock file again loses saves
in 3 of 3 runs (151 to 170 of 321), Delete ignoring shapes fails 47,
Escape that only closes fails 50, and dropping the shape case fails
the type check (TS2366).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
7.4 KiB
TypeScript
174 lines
7.4 KiB
TypeScript
import { describe, expect, it, vi } from 'vitest';
|
||
import type { TextureAsset } from '../../src/core/model/Asset';
|
||
import { createEmptyProject } from '../../src/core/model/Project';
|
||
import type { TextureStore } from '../../src/core/store/TextureStore';
|
||
import { EditorState } from '../../src/editor/state';
|
||
import { assetNameForFile, type ImportOutcome, importNotice } from '../../src/editor/assetImport';
|
||
import {
|
||
encodeWithinBudget,
|
||
importStoredImage,
|
||
MAX_TEXTURE_SIDE,
|
||
MAX_UPLOAD_BYTES,
|
||
planImageFit,
|
||
} from '../../src/editor/textureImport';
|
||
|
||
/** A blob of exactly `size` bytes – `encodeWithinBudget` only ever looks at the size. */
|
||
function blobOf(size: number): Blob {
|
||
return new Blob([new Uint8Array(size)]);
|
||
}
|
||
|
||
function outcome(name: string, error: string | null = null): ImportOutcome {
|
||
return { name, assetId: error ? null : `id-${name}`, error, reused: false };
|
||
}
|
||
|
||
/** A file whose picture the project already had, so no asset was created for it. */
|
||
function reused(name: string): ImportOutcome {
|
||
return { name, assetId: `id-${name}`, error: null, reused: true };
|
||
}
|
||
|
||
describe('assetNameForFile', () => {
|
||
it('drops the extension and falls back when nothing readable is left', () => {
|
||
expect(assetNameForFile('hero-idle.png', 'Texture')).toBe('hero-idle');
|
||
// Only the last extension goes: a name with dots in it keeps them.
|
||
expect(assetNameForFile('walk.cycle.left.png', 'Texture')).toBe('walk.cycle.left');
|
||
expect(assetNameForFile('README', 'Texture')).toBe('README');
|
||
expect(assetNameForFile('.png', 'Texture')).toBe('Texture');
|
||
// What a file the server knows no name for looks like.
|
||
expect(assetNameForFile('', 'Font')).toBe('Font');
|
||
});
|
||
});
|
||
|
||
describe('planImageFit', () => {
|
||
it('leaves an image alone that fits in both senses', () => {
|
||
expect(planImageFit(32, 32, 900)).toEqual({ kind: 'keep' });
|
||
expect(planImageFit(MAX_TEXTURE_SIDE, 1024, MAX_UPLOAD_BYTES)).toEqual({ kind: 'keep' });
|
||
});
|
||
|
||
it('caps the longest side and keeps the aspect ratio', () => {
|
||
expect(planImageFit(4000, 3000, 3_000_000)).toEqual({ kind: 'reencode', width: 2048, height: 1536 });
|
||
expect(planImageFit(1000, 4096, 100)).toEqual({ kind: 'reencode', width: 500, height: 2048 });
|
||
});
|
||
|
||
it('re-encodes at the original size when only the byte count is over budget', () => {
|
||
expect(planImageFit(800, 600, MAX_UPLOAD_BYTES + 1)).toEqual({
|
||
kind: 'reencode',
|
||
width: 800,
|
||
height: 600,
|
||
});
|
||
});
|
||
|
||
it('never scales a picture away to nothing', () => {
|
||
expect(planImageFit(20000, 3, 9_000_000)).toEqual({ kind: 'reencode', width: 2048, height: 1 });
|
||
});
|
||
});
|
||
|
||
describe('encodeWithinBudget', () => {
|
||
it('stops at the first quality that fits', async () => {
|
||
const encode = vi.fn(() => Promise.resolve(blobOf(MAX_UPLOAD_BYTES - 1)));
|
||
const blob = await encodeWithinBudget(encode);
|
||
expect(blob.size).toBe(MAX_UPLOAD_BYTES - 1);
|
||
expect(encode).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('steps the quality down until the result fits', async () => {
|
||
const sizes = [MAX_UPLOAD_BYTES + 1000, MAX_UPLOAD_BYTES - 1000];
|
||
const encode = vi.fn((_quality: number) => Promise.resolve(blobOf(sizes.shift() ?? 0)));
|
||
const blob = await encodeWithinBudget(encode);
|
||
expect(blob.size).toBe(MAX_UPLOAD_BYTES - 1000);
|
||
expect(encode).toHaveBeenCalledTimes(2);
|
||
// Decreasing quality, so a later attempt is never larger than an earlier one.
|
||
const qualities = encode.mock.calls.map(([quality]) => quality);
|
||
expect(qualities).toEqual([...qualities].sort((a, b) => b - a));
|
||
});
|
||
|
||
it('returns the last attempt when nothing fits, so the caller can say how far off it was', async () => {
|
||
const encode = vi.fn(() => Promise.resolve(blobOf(MAX_UPLOAD_BYTES + 5)));
|
||
const blob = await encodeWithinBudget(encode);
|
||
expect(blob.size).toBe(MAX_UPLOAD_BYTES + 5);
|
||
expect(encode.mock.calls.length).toBeGreaterThan(1);
|
||
});
|
||
});
|
||
|
||
describe('importNotice', () => {
|
||
it('counts what arrived', () => {
|
||
expect(importNotice([outcome('a.png')])).toBe('Imported 1 image.');
|
||
expect(importNotice([outcome('a.png'), outcome('b.png')])).toBe('Imported 2 images.');
|
||
});
|
||
|
||
it('names the first casualty and how many followed', () => {
|
||
expect(importNotice([outcome('a.png', 'too large')])).toBe('Could not import "a.png": too large');
|
||
expect(importNotice([outcome('a.png', 'too large'), outcome('b.png', 'broken')])).toBe(
|
||
'Could not import "a.png": too large (and 1 more)',
|
||
);
|
||
});
|
||
|
||
it('reports a partial import as both', () => {
|
||
expect(importNotice([outcome('a.png'), outcome('b.png', 'too large')])).toBe(
|
||
'Imported 1 of 2. Could not import "b.png": too large',
|
||
);
|
||
});
|
||
|
||
it('says so when the picture was already in the project', () => {
|
||
// "Imported 1 image" would send the user looking for an asset that was never created.
|
||
expect(importNotice([reused('a.png')])).toBe('That image is already in the project.');
|
||
expect(importNotice([reused('a.png'), reused('b.png')])).toBe(
|
||
'Those 2 images are already in the project.',
|
||
);
|
||
expect(importNotice([outcome('a.png'), reused('b.png')])).toBe(
|
||
'Imported 1 image. One was already in the project.',
|
||
);
|
||
expect(importNotice([outcome('a.png'), reused('b.png'), outcome('c.png', 'broken')])).toBe(
|
||
'Imported 2 of 3. One was already in the project. Could not import "c.png": broken',
|
||
);
|
||
});
|
||
});
|
||
|
||
describe('importStoredImage', () => {
|
||
const FILE = `${'a'.repeat(64)}.png`;
|
||
const image = { file: FILE, name: '', width: 64, height: 48, bytes: 900 };
|
||
/** The picker takes the image from the list; nothing here ever uploads. */
|
||
const textures = { upload: vi.fn(), list: vi.fn() } as unknown as TextureStore;
|
||
|
||
function setup(): EditorState {
|
||
const state = new EditorState();
|
||
state.loadProject(createEmptyProject('p', 'P'), 1);
|
||
return state;
|
||
}
|
||
|
||
it('makes an asset out of a picture the server already holds', () => {
|
||
const state = setup();
|
||
const outcome = importStoredImage(image, { state, textures });
|
||
|
||
const asset = state.project.assets.find((a): a is TextureAsset => a.type === 'texture');
|
||
expect(asset).toMatchObject({ file: FILE, width: 64, height: 48, name: 'Texture' });
|
||
expect(outcome).toMatchObject({ assetId: asset?.id, error: null, reused: false });
|
||
expect(state.selection).toEqual({ kind: 'asset', assetId: asset?.id });
|
||
expect(state.notice).toBe('Added the image to the project.');
|
||
// Adopting is a command like any other, so it can be taken back.
|
||
state.undo();
|
||
expect(state.project.assets.filter((a) => a.type === 'texture')).toEqual([]);
|
||
});
|
||
|
||
it('names the asset after the file the picture was uploaded as, not "Texture"', () => {
|
||
const state = setup();
|
||
importStoredImage({ ...image, name: 'hero-idle.png' }, { state, textures });
|
||
|
||
expect(state.project.assets.find((a): a is TextureAsset => a.type === 'texture')).toMatchObject({
|
||
file: FILE,
|
||
name: 'hero-idle',
|
||
});
|
||
});
|
||
|
||
it('reuses the asset that already names the file instead of making a second one', () => {
|
||
const state = setup();
|
||
const first = importStoredImage(image, { state, textures });
|
||
const again = importStoredImage(image, { state, textures });
|
||
|
||
expect(again.assetId).toBe(first.assetId);
|
||
expect(again.reused).toBe(true);
|
||
// Two assets on one file would disagree about `filter`, which is a property of the picture.
|
||
expect(state.project.assets.filter((a) => a.type === 'texture')).toHaveLength(1);
|
||
expect(state.notice).toBe('That image is already in the project.');
|
||
});
|
||
});
|