@ohmygame/level-editor 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ohmygame-plugin/plugin.json +42 -0
- package/LICENSE +201 -0
- package/README.md +43 -2
- package/assets/icon.svg +1 -0
- package/locales/en.json +9 -0
- package/locales/zh-CN.json +9 -0
- package/package.json +27 -4
- package/panel/dom.js +79 -0
- package/panel/i18n.js +225 -0
- package/panel/index.html +15 -0
- package/panel/inspector.js +156 -0
- package/panel/main.js +1697 -0
- package/panel/new-map.js +112 -0
- package/panel/palette.js +196 -0
- package/panel/render.js +321 -0
- package/panel/style.css +137 -0
- package/panel/tmj.js +901 -0
- package/skills/level-maps/SKILL.md +28 -0
package/panel/main.js
ADDED
|
@@ -0,0 +1,1697 @@
|
|
|
1
|
+
// The Levels panel: lists the project's Tiled maps, draws the open one on a
|
|
2
|
+
// canvas, and edits its tiles, objects and layers. The map model, and how
|
|
3
|
+
// maps are read and written, is in tmj.js; drawing is in render.js.
|
|
4
|
+
import { connect } from "/_ohmygame/plugin-ui.js";
|
|
5
|
+
import * as tmj from "./tmj.js";
|
|
6
|
+
import { TEXT } from "./i18n.js";
|
|
7
|
+
import { h, icon, iconButton } from "./dom.js";
|
|
8
|
+
import { drawScene, drawTile, hitsObject, layerColor, mapBounds, objectBox, withAlpha } from "./render.js";
|
|
9
|
+
import { Palette } from "./palette.js";
|
|
10
|
+
import { createInspector } from "./inspector.js";
|
|
11
|
+
import { showNewMapDialog } from "./new-map.js";
|
|
12
|
+
|
|
13
|
+
const host = await connect();
|
|
14
|
+
const t = TEXT[host.locale] ?? TEXT.en;
|
|
15
|
+
document.documentElement.lang = host.locale;
|
|
16
|
+
|
|
17
|
+
const TOOLS = [
|
|
18
|
+
["brush", "brush", "B"],
|
|
19
|
+
["eraser", "eraser", "E"],
|
|
20
|
+
["fill", "fill", "G"],
|
|
21
|
+
["eyedropper", "eyedropper", "I"],
|
|
22
|
+
["rect", "rect", "R"],
|
|
23
|
+
["point", "point", "P"],
|
|
24
|
+
["select", "select", "V"],
|
|
25
|
+
];
|
|
26
|
+
const TILE_TOOLS = new Set(["brush", "eraser", "fill", "eyedropper"]);
|
|
27
|
+
const ZOOMS = [0.125, 0.25, 0.33, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 12, 16];
|
|
28
|
+
const HISTORY_LIMIT = 300;
|
|
29
|
+
const MAP_FILE = /\.(?:tmj|json)$/i;
|
|
30
|
+
/** JSON files that are never maps, so they aren't read to find out. */
|
|
31
|
+
const NOT_MAPS = /(?:^|\/)(?:package(?:-lock)?|tsconfig[^/]*|jsconfig|composer|bower|manifest|project|settings|launch|tasks|extensions)\.json$/i;
|
|
32
|
+
/** JSON that big isn't read to see whether it is a map. */
|
|
33
|
+
const MAX_PROBE_BYTES = 8 * 1024 * 1024;
|
|
34
|
+
/** At most this many JSON files are read when looking for maps. */
|
|
35
|
+
const MAX_PROBES = 400;
|
|
36
|
+
const isMac = /Mac|iPhone|iPad/.test(navigator.platform);
|
|
37
|
+
/** How long after its own save the panel takes a `files` event without paths to be that save. */
|
|
38
|
+
const OWN_WRITE_MS = 3000;
|
|
39
|
+
|
|
40
|
+
const state = {
|
|
41
|
+
maps: undefined,
|
|
42
|
+
map: undefined,
|
|
43
|
+
/** The map's text as last read from or written to disk. */
|
|
44
|
+
diskText: "",
|
|
45
|
+
/** Newer text on disk while there are unsaved edits. */
|
|
46
|
+
external: undefined,
|
|
47
|
+
removed: false,
|
|
48
|
+
openError: "",
|
|
49
|
+
tilesets: [],
|
|
50
|
+
paletteIndex: 0,
|
|
51
|
+
tool: "brush",
|
|
52
|
+
stamp: undefined,
|
|
53
|
+
active: undefined,
|
|
54
|
+
selection: undefined,
|
|
55
|
+
view: { zoom: 1, x: 0, y: 0 },
|
|
56
|
+
grid: true,
|
|
57
|
+
history: [],
|
|
58
|
+
at: 0,
|
|
59
|
+
savedAt: 0,
|
|
60
|
+
saving: false,
|
|
61
|
+
hover: undefined,
|
|
62
|
+
drag: undefined,
|
|
63
|
+
space: false,
|
|
64
|
+
message: "",
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// Theme colours for the canvases, read from the app's tokens.
|
|
69
|
+
|
|
70
|
+
const probe = h("span", { class: "probe", "aria-hidden": "true" });
|
|
71
|
+
document.body.append(probe);
|
|
72
|
+
let theme;
|
|
73
|
+
|
|
74
|
+
function colour(expression) {
|
|
75
|
+
probe.style.color = "";
|
|
76
|
+
probe.style.color = expression;
|
|
77
|
+
return getComputedStyle(probe).color;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function rgba(rgb, alpha) {
|
|
81
|
+
const parts = rgb.match(/[\d.]+/g)?.map(Number) ?? [128, 128, 128];
|
|
82
|
+
return `rgba(${parts[0]}, ${parts[1]}, ${parts[2]}, ${alpha})`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function readTheme() {
|
|
86
|
+
const text = colour("var(--color-text)");
|
|
87
|
+
theme = {
|
|
88
|
+
background: colour("var(--color-stage)"),
|
|
89
|
+
grid: rgba(text, 0.14),
|
|
90
|
+
bounds: rgba(text, 0.4),
|
|
91
|
+
text,
|
|
92
|
+
labelText: text,
|
|
93
|
+
labelBackground: rgba(colour("var(--color-surface)"), 0.85),
|
|
94
|
+
selection: colour("var(--omg-accent, var(--color-accent))"),
|
|
95
|
+
selectionFill: rgba(colour("var(--omg-accent, var(--color-accent))"), 0.28),
|
|
96
|
+
hover: rgba(text, 0.7),
|
|
97
|
+
shadow: "rgba(0, 0, 0, 0.55)",
|
|
98
|
+
collision: "#e5534b",
|
|
99
|
+
objects: "#4b8ef0",
|
|
100
|
+
danger: colour("var(--color-danger)"),
|
|
101
|
+
font: getComputedStyle(document.documentElement).getPropertyValue("--font-sans") || "sans-serif",
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
readTheme();
|
|
105
|
+
host.on("theme", () => {
|
|
106
|
+
readTheme();
|
|
107
|
+
invalidate();
|
|
108
|
+
palette.draw();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------------------
|
|
112
|
+
// Layout.
|
|
113
|
+
|
|
114
|
+
const els = {};
|
|
115
|
+
const palette = new Palette({ onPick: (stamp) => pickStamp(stamp, false), theme: () => theme });
|
|
116
|
+
|
|
117
|
+
function buildLayout() {
|
|
118
|
+
els.mapSelect = h("omg-select", { "aria-label": t.chooseMap, class: "map-select", on: { change: (event) => void switchMap(event.currentTarget.value) } });
|
|
119
|
+
els.newMap = h("omg-button", { on: { click: () => void openNewMapDialog() } }, icon("plus"), t.newMap);
|
|
120
|
+
els.tools = new Map();
|
|
121
|
+
const toolButtons = TOOLS.map(([tool, iconName, key]) => {
|
|
122
|
+
const wrapper = iconButton(iconName, `${t.tools[tool]} (${key})`, () => setTool(tool));
|
|
123
|
+
els.tools.set(tool, wrapper.firstElementChild);
|
|
124
|
+
return wrapper;
|
|
125
|
+
});
|
|
126
|
+
const mod = isMac ? "⌘" : "Ctrl+";
|
|
127
|
+
const undo = iconButton("undo", `${t.undo} (${mod}Z)`, () => undoStep());
|
|
128
|
+
const redo = iconButton("redo", `${t.redo} (${isMac ? "⇧⌘Z" : "Ctrl+Y"})`, () => redoStep());
|
|
129
|
+
els.undo = undo.firstElementChild;
|
|
130
|
+
els.redo = redo.firstElementChild;
|
|
131
|
+
els.zoomLabel = h("button", { class: "zoom-label", type: "button", on: { click: () => zoomTo(1) } }, "100%");
|
|
132
|
+
const grid = iconButton("grid", t.grid, () => {
|
|
133
|
+
state.grid = !state.grid;
|
|
134
|
+
updateToolbar();
|
|
135
|
+
invalidate();
|
|
136
|
+
});
|
|
137
|
+
els.grid = grid.firstElementChild;
|
|
138
|
+
els.dirty = h("span", { class: "dirty", hidden: true }, t.unsaved);
|
|
139
|
+
els.save = h("omg-button", { variant: "primary", on: { click: () => void save() } }, t.save);
|
|
140
|
+
|
|
141
|
+
els.toolbar = h(
|
|
142
|
+
"header",
|
|
143
|
+
{ class: "toolbar" },
|
|
144
|
+
h("div", { class: "group file" }, els.mapSelect, els.newMap),
|
|
145
|
+
h("div", { class: "group tools", role: "toolbar", "aria-label": t.toolbar }, toolButtons),
|
|
146
|
+
h("div", { class: "group" }, undo, redo),
|
|
147
|
+
h(
|
|
148
|
+
"div",
|
|
149
|
+
{ class: "group" },
|
|
150
|
+
iconButton("zoomOut", t.zoomOut, () => zoomStep(-1)),
|
|
151
|
+
els.zoomLabel,
|
|
152
|
+
iconButton("zoomIn", t.zoomIn, () => zoomStep(1)),
|
|
153
|
+
iconButton("fit", t.fit, () => fitView()),
|
|
154
|
+
grid,
|
|
155
|
+
),
|
|
156
|
+
h("div", { class: "group end" }, els.dirty, els.save),
|
|
157
|
+
);
|
|
158
|
+
els.notices = h("div", { class: "notices" });
|
|
159
|
+
|
|
160
|
+
els.canvas = h("canvas", { class: "map-canvas", tabindex: "0", "aria-label": t.title });
|
|
161
|
+
els.stageMessage = h("div", { class: "stage-message", hidden: true });
|
|
162
|
+
els.stage = h("div", { class: "stage" }, els.canvas, els.stageMessage);
|
|
163
|
+
|
|
164
|
+
els.layers = h("div", { class: "layer-list", role: "listbox", "aria-label": t.layers });
|
|
165
|
+
els.layerActions = h("div", { class: "section-actions" });
|
|
166
|
+
els.tilesetTabs = h("div", { class: "tileset-tabs" });
|
|
167
|
+
els.tilesetNote = h("p", { class: "note", hidden: true });
|
|
168
|
+
els.inspector = h("div", { class: "inspector" });
|
|
169
|
+
els.side = h(
|
|
170
|
+
"aside",
|
|
171
|
+
{ class: "side" },
|
|
172
|
+
h("section", { class: "side-section layers-section" }, h("div", { class: "section-head" }, h("h2", {}, t.layers), els.layerActions), els.layers),
|
|
173
|
+
h("section", { class: "side-section tileset-section" }, h("div", { class: "section-head" }, h("h2", {}, t.tileset)), els.tilesetTabs, palette.scroller, els.tilesetNote),
|
|
174
|
+
h("section", { class: "side-section object-section" }, h("div", { class: "section-head" }, h("h2", {}, t.object)), els.inspector),
|
|
175
|
+
);
|
|
176
|
+
els.status = {
|
|
177
|
+
cell: h("span", { class: "status-cell" }),
|
|
178
|
+
layer: h("span", { class: "status-layer" }),
|
|
179
|
+
message: h("span", { class: "status-message" }),
|
|
180
|
+
size: h("span", { class: "status-size" }),
|
|
181
|
+
};
|
|
182
|
+
els.footer = h("footer", { class: "status" }, els.status.cell, els.status.layer, els.status.message, els.status.size);
|
|
183
|
+
els.workspace = h("main", { class: "workspace" }, els.stage, els.side);
|
|
184
|
+
els.empty = h("div", { class: "empty-state", hidden: true });
|
|
185
|
+
els.app = h("div", { class: "app" }, els.toolbar, els.notices, els.workspace, els.empty, els.footer);
|
|
186
|
+
document.getElementById("app").replaceChildren(els.app);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
buildLayout();
|
|
190
|
+
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
// Finding maps.
|
|
193
|
+
|
|
194
|
+
let scanTimer;
|
|
195
|
+
let scanning;
|
|
196
|
+
/** Whether a JSON file is a Tiled map, by its path, size and time, so a scan reads only changed files. */
|
|
197
|
+
const probed = new Map();
|
|
198
|
+
|
|
199
|
+
async function scanMaps() {
|
|
200
|
+
const { entries } = await host.files.list("", { recursive: true });
|
|
201
|
+
state.files = entries.filter((entry) => entry.kind === "file");
|
|
202
|
+
const found = [];
|
|
203
|
+
const probes = [];
|
|
204
|
+
for (const entry of state.files) {
|
|
205
|
+
if (!MAP_FILE.test(entry.path)) continue;
|
|
206
|
+
if (/\.tmj$/i.test(entry.path)) found.push(entry.path);
|
|
207
|
+
else if (!NOT_MAPS.test(entry.path) && (entry.size ?? 0) <= MAX_PROBE_BYTES) {
|
|
208
|
+
const key = `${entry.path}\n${entry.size}\n${entry.modified}`;
|
|
209
|
+
if (probed.has(key)) {
|
|
210
|
+
if (probed.get(key)) found.push(entry.path);
|
|
211
|
+
} else probes.push(key);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Read JSON files a few at a time to see which are Tiled maps.
|
|
215
|
+
const queue = probes.slice(0, MAX_PROBES);
|
|
216
|
+
await Promise.all(
|
|
217
|
+
Array.from({ length: 6 }, async () => {
|
|
218
|
+
for (let key = queue.shift(); key !== undefined; key = queue.shift()) {
|
|
219
|
+
const path = key.slice(0, key.indexOf("\n"));
|
|
220
|
+
let map = false;
|
|
221
|
+
try {
|
|
222
|
+
const text = await host.files.text(path);
|
|
223
|
+
map = /"(?:tilesets|tilewidth)"/.test(text) && tmj.isTiledMap(JSON.parse(text));
|
|
224
|
+
} catch {
|
|
225
|
+
// Not readable JSON: not a map.
|
|
226
|
+
}
|
|
227
|
+
probed.set(key, map);
|
|
228
|
+
if (map) found.push(path);
|
|
229
|
+
}
|
|
230
|
+
}),
|
|
231
|
+
);
|
|
232
|
+
state.maps = found.sort((a, b) => a.localeCompare(b));
|
|
233
|
+
renderMapSelect();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function rescanSoon() {
|
|
237
|
+
clearTimeout(scanTimer);
|
|
238
|
+
scanTimer = setTimeout(() => {
|
|
239
|
+
scanning = scanMaps().catch(() => {});
|
|
240
|
+
}, 800);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function renderMapSelect() {
|
|
244
|
+
const current = state.map?.path ?? "";
|
|
245
|
+
const options = (state.maps ?? []).map((path) => h("option", { value: path }, path));
|
|
246
|
+
if (current && !state.maps?.includes(current)) options.unshift(h("option", { value: current }, current));
|
|
247
|
+
if (!current) options.unshift(h("option", { value: "" }, t.pickMap));
|
|
248
|
+
els.mapSelect.replaceChildren(...options);
|
|
249
|
+
els.mapSelect.value = current;
|
|
250
|
+
els.mapSelect.hidden = !options.length;
|
|
251
|
+
renderEmpty();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function renderEmpty() {
|
|
255
|
+
const nothing = state.maps !== undefined && !state.maps.length && !state.map;
|
|
256
|
+
els.empty.hidden = !nothing;
|
|
257
|
+
els.workspace.hidden = nothing;
|
|
258
|
+
els.footer.hidden = nothing;
|
|
259
|
+
if (nothing) {
|
|
260
|
+
els.empty.replaceChildren(
|
|
261
|
+
h(
|
|
262
|
+
"omg-empty",
|
|
263
|
+
{ heading: t.noMaps, description: t.noMapsHint },
|
|
264
|
+
h("omg-button", { variant: "primary", on: { click: () => void openNewMapDialog() } }, t.newMap),
|
|
265
|
+
),
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ---------------------------------------------------------------------------
|
|
271
|
+
// Opening and saving.
|
|
272
|
+
|
|
273
|
+
const isDirty = () => state.at !== state.savedAt;
|
|
274
|
+
const editable = () => Boolean(state.map && tmj.isEditable(state.map));
|
|
275
|
+
|
|
276
|
+
async function confirmDiscard() {
|
|
277
|
+
if (!state.map || !isDirty()) return true;
|
|
278
|
+
try {
|
|
279
|
+
return await host.request("ui.confirm", {
|
|
280
|
+
title: t.discardTitle,
|
|
281
|
+
message: t.discardMessage(tmj.basename(state.map.path)),
|
|
282
|
+
confirmLabel: t.discard,
|
|
283
|
+
});
|
|
284
|
+
} catch {
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function switchMap(path) {
|
|
290
|
+
if (!path || path === state.map?.path) return;
|
|
291
|
+
if (!(await confirmDiscard())) {
|
|
292
|
+
els.mapSelect.value = state.map?.path ?? "";
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
await openPath(path);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Counts calls to `openPath`, so only the latest one's result is used. */
|
|
299
|
+
let opening = 0;
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Opens a map. `keepView` keeps the zoom and position, as when the same map
|
|
303
|
+
* is read again; without `force`, a reload that finds edits made while it
|
|
304
|
+
* read the file shows the changed-on-disk notice instead of replacing them.
|
|
305
|
+
*/
|
|
306
|
+
async function openPath(path, { keepView = false, force = false } = {}) {
|
|
307
|
+
const ticket = ++opening;
|
|
308
|
+
state.openError = "";
|
|
309
|
+
let text;
|
|
310
|
+
let map;
|
|
311
|
+
try {
|
|
312
|
+
text = await host.files.text(path);
|
|
313
|
+
map = await tmj.openMap(text, path);
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (ticket !== opening) return;
|
|
316
|
+
state.openError = t.openFailed(errorText(error));
|
|
317
|
+
if (!keepView) {
|
|
318
|
+
state.map = undefined;
|
|
319
|
+
renderMapSelect();
|
|
320
|
+
}
|
|
321
|
+
refresh();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (ticket !== opening) return;
|
|
325
|
+
// Edits made while the file was read stay; the notice offers the choice.
|
|
326
|
+
if (!force && keepView && state.map?.path === path && isDirty()) {
|
|
327
|
+
if (text !== state.diskText) state.external = text;
|
|
328
|
+
renderNotices();
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
const previous = state.map?.path === path ? { active: state.active?.id, selected: state.selection?.object.id } : undefined;
|
|
332
|
+
state.map = map;
|
|
333
|
+
state.diskText = text;
|
|
334
|
+
state.external = undefined;
|
|
335
|
+
state.removed = false;
|
|
336
|
+
state.history = [];
|
|
337
|
+
state.at = state.savedAt = 0;
|
|
338
|
+
state.selection = undefined;
|
|
339
|
+
state.drag = undefined;
|
|
340
|
+
state.active = undefined;
|
|
341
|
+
if (previous) {
|
|
342
|
+
tmj.walkLayers(map.doc.layers, (layer) => {
|
|
343
|
+
if (layer.id !== undefined && layer.id === previous.active) state.active = layer;
|
|
344
|
+
for (const object of layer.objects ?? []) if (object.id === previous.selected) state.selection = { layer, object };
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
if (!state.active) {
|
|
348
|
+
tmj.walkLayers(map.doc.layers, (layer) => {
|
|
349
|
+
if (!state.active && layer.type === "tilelayer") state.active = layer;
|
|
350
|
+
});
|
|
351
|
+
state.active ??= map.doc.layers?.[0];
|
|
352
|
+
}
|
|
353
|
+
void host.request("storage.set", { key: "lastMap", value: path }).catch(() => {});
|
|
354
|
+
if (!tmj.isEditable(map)) state.tool = "select";
|
|
355
|
+
if (!keepView) state.paletteIndex = 0;
|
|
356
|
+
renderMapSelect();
|
|
357
|
+
try {
|
|
358
|
+
await loadTilesets();
|
|
359
|
+
} catch (error) {
|
|
360
|
+
// The map is open; say what went wrong with its tilesets.
|
|
361
|
+
state.openError = t.openFailed(errorText(error));
|
|
362
|
+
}
|
|
363
|
+
if (ticket !== opening) return;
|
|
364
|
+
if (!keepView) fitView();
|
|
365
|
+
// Start with the first tile of the first tileset on the brush.
|
|
366
|
+
if (!keepView && state.tilesets[0]?.ids.length) pickStamp(tmj.stampOf(1, 1, [state.tilesets[0].firstgid + state.tilesets[0].ids[0]]), true);
|
|
367
|
+
refresh();
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async function save() {
|
|
371
|
+
const map = state.map;
|
|
372
|
+
if (!map || !editable() || state.saving || !isDirty()) return;
|
|
373
|
+
// Not over a newer file on disk until the person chooses what to keep.
|
|
374
|
+
if (state.external !== undefined) {
|
|
375
|
+
say(t.chooseFirst);
|
|
376
|
+
renderNotices();
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
state.saving = true;
|
|
380
|
+
// A stroke in progress ends here; strokes don't continue while saving.
|
|
381
|
+
if (state.drag?.kind === "paint") {
|
|
382
|
+
tileStep(state.drag.tiles.gids, state.drag.changes);
|
|
383
|
+
state.drag = undefined;
|
|
384
|
+
}
|
|
385
|
+
updateToolbar();
|
|
386
|
+
try {
|
|
387
|
+
let disk;
|
|
388
|
+
try {
|
|
389
|
+
disk = await host.files.text(map.path);
|
|
390
|
+
} catch {
|
|
391
|
+
disk = undefined;
|
|
392
|
+
}
|
|
393
|
+
if (map !== state.map) return;
|
|
394
|
+
if (disk !== undefined && disk !== state.diskText) {
|
|
395
|
+
state.external = disk;
|
|
396
|
+
say(t.chooseFirst);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
const at = state.at;
|
|
400
|
+
const text = await tmj.serializeMap(map);
|
|
401
|
+
await host.files.write(map.path, text);
|
|
402
|
+
tmj.markSaved(map);
|
|
403
|
+
state.ownWrite = Date.now();
|
|
404
|
+
state.diskText = text;
|
|
405
|
+
state.savedAt = at;
|
|
406
|
+
state.external = undefined;
|
|
407
|
+
} catch (error) {
|
|
408
|
+
toast(t.saveFailed(errorText(error)));
|
|
409
|
+
} finally {
|
|
410
|
+
state.saving = false;
|
|
411
|
+
refresh();
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const errorText = (error) => (error instanceof Error ? error.message : String(error));
|
|
416
|
+
|
|
417
|
+
function toast(text) {
|
|
418
|
+
void host.request("ui.toast", { message: text.slice(0, 500), tone: "danger" }).catch(() => {});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// When the project's files change: the map list, and the open map if it
|
|
422
|
+
// (or its tilesets and images) changed on disk. Without `paths`, or when
|
|
423
|
+
// they were cut short, anything may have changed.
|
|
424
|
+
host.on("files", ({ paths, truncated }) => {
|
|
425
|
+
const known = paths && !truncated ? paths : undefined;
|
|
426
|
+
// The event that follows the panel's own save names no paths.
|
|
427
|
+
const ownSave = !known && Date.now() - (state.ownWrite ?? 0) < OWN_WRITE_MS;
|
|
428
|
+
if (known ? known.some((path) => MAP_FILE.test(path) || /\.png$/i.test(path)) : !ownSave) rescanSoon();
|
|
429
|
+
const map = state.map;
|
|
430
|
+
if (!map) return;
|
|
431
|
+
if (!known || known.includes(map.path)) void checkDisk();
|
|
432
|
+
const dependencies = state.dependencies ?? new Set();
|
|
433
|
+
const touched = known ? known.filter((path) => dependencies.has(path)) : ownSave ? [] : [...dependencies];
|
|
434
|
+
if (touched.length) void refreshDependencies(map, touched);
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
/** Reads changed tileset files and pictures again; the map keeps showing the old ones until then. */
|
|
438
|
+
async function refreshDependencies(map, paths) {
|
|
439
|
+
for (const tileset of state.tilesets) {
|
|
440
|
+
if (!tileset.external || !paths.includes(tileset.base)) continue;
|
|
441
|
+
const text = await host.files.text(tileset.base).catch(() => undefined);
|
|
442
|
+
if (text !== tileset.text) {
|
|
443
|
+
if (map === state.map) await loadTilesets();
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
for (const path of paths) if (images.get(path) !== undefined) void loadImage(path);
|
|
448
|
+
}
|
|
449
|
+
async function checkDisk() {
|
|
450
|
+
const map = state.map;
|
|
451
|
+
let text;
|
|
452
|
+
try {
|
|
453
|
+
text = await host.files.text(map.path);
|
|
454
|
+
} catch {
|
|
455
|
+
if (map !== state.map) return;
|
|
456
|
+
state.removed = true;
|
|
457
|
+
renderNotices();
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (map !== state.map) return;
|
|
461
|
+
state.removed = false;
|
|
462
|
+
if (text === state.diskText) {
|
|
463
|
+
renderNotices();
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (state.saving) return;
|
|
467
|
+
if (!isDirty()) await openPath(map.path, { keepView: true });
|
|
468
|
+
else {
|
|
469
|
+
state.external = text;
|
|
470
|
+
renderNotices();
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// ---------------------------------------------------------------------------
|
|
475
|
+
// Tilesets and images.
|
|
476
|
+
|
|
477
|
+
/** path → HTMLImageElement, or `null` while it loads or if it couldn't. */
|
|
478
|
+
const images = new Map();
|
|
479
|
+
|
|
480
|
+
function image(path) {
|
|
481
|
+
if (!path) return undefined;
|
|
482
|
+
const known = images.get(path);
|
|
483
|
+
if (known instanceof HTMLImageElement) return known;
|
|
484
|
+
if (known === undefined) {
|
|
485
|
+
images.set(path, null);
|
|
486
|
+
void loadImage(path);
|
|
487
|
+
}
|
|
488
|
+
return undefined;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Loads a picture from the project, replacing the one shown (if any) once it has loaded. */
|
|
492
|
+
async function loadImage(path) {
|
|
493
|
+
try {
|
|
494
|
+
const url = await host.files.url(path);
|
|
495
|
+
const element = new Image();
|
|
496
|
+
element.src = url;
|
|
497
|
+
await element.decode();
|
|
498
|
+
const previous = images.get(path);
|
|
499
|
+
images.set(path, element);
|
|
500
|
+
if (previous instanceof HTMLImageElement) URL.revokeObjectURL(previous.src);
|
|
501
|
+
} catch {
|
|
502
|
+
if (!(images.get(path) instanceof HTMLImageElement)) images.set(path, null);
|
|
503
|
+
}
|
|
504
|
+
tileCache.clear();
|
|
505
|
+
invalidate();
|
|
506
|
+
palette.draw();
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** gid without flags → what to draw it from, for the open map's tilesets. */
|
|
510
|
+
const tileCache = new Map();
|
|
511
|
+
|
|
512
|
+
async function loadTilesets() {
|
|
513
|
+
const map = state.map;
|
|
514
|
+
if (!map) return;
|
|
515
|
+
const dependencies = new Set();
|
|
516
|
+
const loaded = await Promise.all(
|
|
517
|
+
(map.doc.tilesets ?? []).map(async (entry) => {
|
|
518
|
+
if (!entry.source) return runtimeTileset(entry, entry.firstgid, map.path, false);
|
|
519
|
+
const path = tmj.resolvePath(map.path, entry.source);
|
|
520
|
+
if (!path) return runtimeTileset({ name: entry.source }, entry.firstgid, map.path, true, entry.source);
|
|
521
|
+
dependencies.add(path);
|
|
522
|
+
try {
|
|
523
|
+
const text = await host.files.text(path);
|
|
524
|
+
const data = /\.tsx$/i.test(path) || text.trimStart().startsWith("<")
|
|
525
|
+
? tmj.tilesetFromXml(new DOMParser().parseFromString(text, "application/xml").documentElement)
|
|
526
|
+
: JSON.parse(text);
|
|
527
|
+
return { ...runtimeTileset({ name: tmj.basename(path), ...data }, entry.firstgid, path, true), text };
|
|
528
|
+
} catch {
|
|
529
|
+
return runtimeTileset({ name: tmj.basename(path) }, entry.firstgid, path, true, path);
|
|
530
|
+
}
|
|
531
|
+
}),
|
|
532
|
+
);
|
|
533
|
+
if (map !== state.map) return;
|
|
534
|
+
for (const tileset of loaded) for (const path of tileset.images) dependencies.add(path);
|
|
535
|
+
tmj.walkLayers(map.doc.layers, (layer) => {
|
|
536
|
+
if (layer.type === "imagelayer" && layer.image) {
|
|
537
|
+
const path = tmj.resolvePath(map.path, layer.image);
|
|
538
|
+
if (path) dependencies.add(path);
|
|
539
|
+
}
|
|
540
|
+
});
|
|
541
|
+
state.dependencies = dependencies;
|
|
542
|
+
state.tilesets = loaded;
|
|
543
|
+
state.paletteIndex = Math.min(state.paletteIndex, Math.max(0, loaded.length - 1));
|
|
544
|
+
tileCache.clear();
|
|
545
|
+
// Tiles bigger than the grid can reach into cells off screen.
|
|
546
|
+
const { tilewidth, tileheight } = map.doc;
|
|
547
|
+
state.tilePad = Math.max(1, ...loaded.map((tileset) => Math.ceil(Math.max(tileset.tilewidth / tilewidth, tileset.tileheight / tileheight))));
|
|
548
|
+
for (const tileset of loaded) for (const path of tileset.images) image(path);
|
|
549
|
+
renderTilesets();
|
|
550
|
+
invalidate();
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** A tileset as the panel uses it: where its tiles come from, resolved against `base`, the file it is in. */
|
|
554
|
+
function runtimeTileset(data, firstgid, base, external, error) {
|
|
555
|
+
const atlas = Boolean(data.image) && data.columns > 0;
|
|
556
|
+
const paths = new Set();
|
|
557
|
+
if (data.image) paths.add(tmj.resolvePath(base, data.image));
|
|
558
|
+
for (const tile of tmj.tilesOf(data)) if (tile.image) paths.add(tmj.resolvePath(base, tile.image));
|
|
559
|
+
paths.delete(undefined);
|
|
560
|
+
return {
|
|
561
|
+
firstgid,
|
|
562
|
+
name: data.name || tmj.basename(base),
|
|
563
|
+
atlas,
|
|
564
|
+
columns: data.columns ?? 0,
|
|
565
|
+
tilewidth: data.tilewidth || state.map.doc.tilewidth,
|
|
566
|
+
tileheight: data.tileheight || state.map.doc.tileheight,
|
|
567
|
+
ids: error ? [] : tmj.tileIds(data),
|
|
568
|
+
data,
|
|
569
|
+
base,
|
|
570
|
+
external,
|
|
571
|
+
error,
|
|
572
|
+
images: [...paths],
|
|
573
|
+
/** The tile to draw for local id `id`, once its image has loaded. */
|
|
574
|
+
tile(id) {
|
|
575
|
+
const source = tmj.tileSource(data, id);
|
|
576
|
+
if (!source) return undefined;
|
|
577
|
+
const picture = image(tmj.resolvePath(base, source.image));
|
|
578
|
+
if (!picture) return undefined;
|
|
579
|
+
const width = source.width || picture.naturalWidth;
|
|
580
|
+
const height = source.height || picture.naturalHeight;
|
|
581
|
+
return { image: picture, sx: source.sx, sy: source.sy, sw: width, sh: height, width, height };
|
|
582
|
+
},
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** What to draw a map tile from: its picture, size and offset, and whether it fills one grid cell. */
|
|
587
|
+
function tileFor(gid) {
|
|
588
|
+
const plain = tmj.tileOf(gid);
|
|
589
|
+
if (tileCache.has(plain)) return tileCache.get(plain);
|
|
590
|
+
const found = tmj.findTileset(state.tilesets, plain);
|
|
591
|
+
const tile = found?.tileset.tile(found.id);
|
|
592
|
+
if (!tile) return undefined;
|
|
593
|
+
const { data } = found.tileset;
|
|
594
|
+
const doc = state.map.doc;
|
|
595
|
+
const offsetX = data.tileoffset?.x ?? 0;
|
|
596
|
+
const offsetY = data.tileoffset?.y ?? 0;
|
|
597
|
+
const grid = data.tilerendersize === "grid" || (tile.width === doc.tilewidth && tile.height === doc.tileheight && !offsetX && !offsetY);
|
|
598
|
+
const entry = { ...tile, offsetX, offsetY, grid };
|
|
599
|
+
tileCache.set(plain, entry);
|
|
600
|
+
return entry;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function renderTilesets() {
|
|
604
|
+
const { tilesets } = state;
|
|
605
|
+
if (tilesets.length > 1) {
|
|
606
|
+
const tabs = h(
|
|
607
|
+
"omg-tabs",
|
|
608
|
+
{
|
|
609
|
+
"aria-label": t.tileset,
|
|
610
|
+
value: String(state.paletteIndex),
|
|
611
|
+
on: {
|
|
612
|
+
"omg-tab-change": (event) => {
|
|
613
|
+
state.paletteIndex = Number(event.detail.value);
|
|
614
|
+
showPalette();
|
|
615
|
+
},
|
|
616
|
+
},
|
|
617
|
+
},
|
|
618
|
+
tilesets.map((tileset, index) => h("omg-tab", { name: String(index), heading: tileset.name })),
|
|
619
|
+
);
|
|
620
|
+
els.tilesetTabs.replaceChildren(tabs);
|
|
621
|
+
} else els.tilesetTabs.replaceChildren();
|
|
622
|
+
showPalette();
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function showPalette() {
|
|
626
|
+
const tileset = state.tilesets[state.paletteIndex];
|
|
627
|
+
palette.show(tileset);
|
|
628
|
+
const note = !state.tilesets.length ? t.noTilesets : tileset?.error ? t.tilesetMissing(tileset.error) : tileset?.external ? t.externalTileset : "";
|
|
629
|
+
els.tilesetNote.textContent = note;
|
|
630
|
+
els.tilesetNote.hidden = !note;
|
|
631
|
+
palette.scroller.hidden = !tileset || Boolean(tileset.error);
|
|
632
|
+
if (state.stamp?.width === 1 && state.stamp.height === 1) palette.mark(state.stamp.gids[0]);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// ---------------------------------------------------------------------------
|
|
636
|
+
// History: each step can be undone and redone. Tile strokes are applied as
|
|
637
|
+
// they are drawn, so they are recorded once done.
|
|
638
|
+
|
|
639
|
+
function record(step) {
|
|
640
|
+
if (state.savedAt > state.at) state.savedAt = -1;
|
|
641
|
+
state.history.length = state.at;
|
|
642
|
+
state.history.push(step);
|
|
643
|
+
if (state.history.length > HISTORY_LIMIT) {
|
|
644
|
+
state.history.shift();
|
|
645
|
+
state.savedAt--;
|
|
646
|
+
}
|
|
647
|
+
state.at = state.history.length;
|
|
648
|
+
changed();
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
function run(step) {
|
|
652
|
+
step.redo();
|
|
653
|
+
record(step);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
function undoStep() {
|
|
657
|
+
if (!state.at || state.drag || state.saving) return;
|
|
658
|
+
state.history[--state.at].undo();
|
|
659
|
+
changed();
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function redoStep() {
|
|
663
|
+
if (state.at >= state.history.length || state.drag || state.saving) return;
|
|
664
|
+
state.history[state.at++].redo();
|
|
665
|
+
changed();
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function changed() {
|
|
669
|
+
// An undo may take away the selected object or the active layer.
|
|
670
|
+
const layers = new Set();
|
|
671
|
+
tmj.walkLayers(state.map?.doc.layers, (layer) => void layers.add(layer));
|
|
672
|
+
if (state.selection && (!layers.has(state.selection.layer) || !state.selection.layer.objects?.includes(state.selection.object))) state.selection = undefined;
|
|
673
|
+
if (state.active && !layers.has(state.active)) state.active = state.map?.doc.layers?.at(-1);
|
|
674
|
+
invalidate();
|
|
675
|
+
refresh();
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Changes an object's fields as one step, if anything changed. */
|
|
679
|
+
function editFields(target, change) {
|
|
680
|
+
const before = tmj.captureFields(target);
|
|
681
|
+
change(target);
|
|
682
|
+
const after = tmj.captureFields(target);
|
|
683
|
+
if (JSON.stringify(before) === JSON.stringify(after)) return;
|
|
684
|
+
record({ undo: () => tmj.restoreFields(target, before), redo: () => tmj.restoreFields(target, after) });
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** Changes an array (layers, objects) as one step. */
|
|
688
|
+
function editList(list, change) {
|
|
689
|
+
const before = list.slice();
|
|
690
|
+
change(list);
|
|
691
|
+
const after = list.slice();
|
|
692
|
+
record({ undo: () => list.splice(0, list.length, ...before), redo: () => list.splice(0, list.length, ...after) });
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function tileStep(gids, changes) {
|
|
696
|
+
const list = [...changes.values()];
|
|
697
|
+
if (!list.length) return;
|
|
698
|
+
record({ undo: () => tmj.applyChanges(gids, list, true), redo: () => tmj.applyChanges(gids, list) });
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// ---------------------------------------------------------------------------
|
|
702
|
+
// The view.
|
|
703
|
+
|
|
704
|
+
let frame = 0;
|
|
705
|
+
function invalidate() {
|
|
706
|
+
if (!frame) frame = requestAnimationFrame(draw);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function canvasSize() {
|
|
710
|
+
return { width: els.stage.clientWidth, height: els.stage.clientHeight };
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
new ResizeObserver(() => {
|
|
714
|
+
const dpr = window.devicePixelRatio || 1;
|
|
715
|
+
const { width, height } = canvasSize();
|
|
716
|
+
els.canvas.width = Math.max(1, Math.round(width * dpr));
|
|
717
|
+
els.canvas.height = Math.max(1, Math.round(height * dpr));
|
|
718
|
+
if (state.needsFit) fitView();
|
|
719
|
+
draw();
|
|
720
|
+
}).observe(els.stage);
|
|
721
|
+
|
|
722
|
+
function draw() {
|
|
723
|
+
frame = 0;
|
|
724
|
+
const ctx = els.canvas.getContext("2d");
|
|
725
|
+
const map = state.map;
|
|
726
|
+
if (!map) {
|
|
727
|
+
ctx.clearRect(0, 0, els.canvas.width, els.canvas.height);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
drawScene(ctx, {
|
|
731
|
+
width: els.canvas.width,
|
|
732
|
+
height: els.canvas.height,
|
|
733
|
+
dpr: window.devicePixelRatio || 1,
|
|
734
|
+
zoom: state.view.zoom,
|
|
735
|
+
x: state.view.x,
|
|
736
|
+
y: state.view.y,
|
|
737
|
+
doc: map.doc,
|
|
738
|
+
tiles: map.tiles,
|
|
739
|
+
tile: tileFor,
|
|
740
|
+
tilePad: state.tilePad,
|
|
741
|
+
image: (path) => image(tmj.resolvePath(map.path, path)),
|
|
742
|
+
theme,
|
|
743
|
+
grid: state.grid,
|
|
744
|
+
overlay: drawOverlay,
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function fitView() {
|
|
749
|
+
const map = state.map;
|
|
750
|
+
const { width, height } = canvasSize();
|
|
751
|
+
if (!map || width < 10 || height < 10) {
|
|
752
|
+
state.needsFit = true;
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
state.needsFit = false;
|
|
756
|
+
const bounds = mapBounds(map);
|
|
757
|
+
const zoom = clampZoom(Math.min((width - 48) / bounds.width, (height - 48) / bounds.height, 8));
|
|
758
|
+
state.view = { zoom, x: Math.round((width - bounds.width * zoom) / 2 - bounds.x * zoom), y: Math.round((height - bounds.height * zoom) / 2 - bounds.y * zoom) };
|
|
759
|
+
updateToolbar();
|
|
760
|
+
invalidate();
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
const clampZoom = (zoom) => Math.min(16, Math.max(0.05, zoom));
|
|
764
|
+
|
|
765
|
+
function zoomAround(zoom, px, py) {
|
|
766
|
+
const next = clampZoom(zoom);
|
|
767
|
+
const { view } = state;
|
|
768
|
+
state.view = { zoom: next, x: px - ((px - view.x) * next) / view.zoom, y: py - ((py - view.y) * next) / view.zoom };
|
|
769
|
+
updateToolbar();
|
|
770
|
+
invalidate();
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function zoomTo(zoom) {
|
|
774
|
+
const { width, height } = canvasSize();
|
|
775
|
+
zoomAround(zoom, width / 2, height / 2);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
function zoomStep(direction) {
|
|
779
|
+
const current = state.view.zoom;
|
|
780
|
+
const next = direction > 0 ? ZOOMS.find((zoom) => zoom > current * 1.01) : ZOOMS.findLast((zoom) => zoom < current / 1.01);
|
|
781
|
+
zoomTo(next ?? (direction > 0 ? 16 : 0.05));
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** The pointer's position in the canvas, in CSS pixels, and on the map, in map pixels. */
|
|
785
|
+
function pointer(event) {
|
|
786
|
+
const rect = els.canvas.getBoundingClientRect();
|
|
787
|
+
const px = event.clientX - rect.left;
|
|
788
|
+
const py = event.clientY - rect.top;
|
|
789
|
+
const { zoom, x, y } = state.view;
|
|
790
|
+
return { px, py, wx: (px - x) / zoom, wy: (py - y) / zoom };
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
function cellAt(wx, wy) {
|
|
794
|
+
const doc = state.map.doc;
|
|
795
|
+
return [Math.floor(wx / doc.tilewidth), Math.floor(wy / doc.tileheight)];
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/** Map point (wx, wy) in `layer`'s own coordinates, its and its groups' offsets taken away. */
|
|
799
|
+
function local(layer, wx, wy) {
|
|
800
|
+
const [ox, oy] = layer ? layerOffset(layer) : [0, 0];
|
|
801
|
+
return [wx - ox, wy - oy];
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** The cell of `layer` under map point (wx, wy). */
|
|
805
|
+
function cellIn(layer, wx, wy) {
|
|
806
|
+
return cellAt(...local(layer, wx, wy));
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/** Whether a layer, or a group it is in, is locked against edits. */
|
|
810
|
+
function locked(target) {
|
|
811
|
+
let result = false;
|
|
812
|
+
const visit = (layers, inLocked) => {
|
|
813
|
+
for (const layer of layers ?? []) {
|
|
814
|
+
const here = inLocked || layer.locked === true;
|
|
815
|
+
if (layer === target) result = here;
|
|
816
|
+
if (layer.type === "group") visit(layer.layers, here);
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
visit(state.map?.doc.layers, false);
|
|
820
|
+
return result;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// ---------------------------------------------------------------------------
|
|
824
|
+
// Layers.
|
|
825
|
+
|
|
826
|
+
/** Every layer with its parent list and depth, topmost first, as the layers list shows them. */
|
|
827
|
+
function layerRows() {
|
|
828
|
+
const rows = [];
|
|
829
|
+
const visit = (layers, depth) => {
|
|
830
|
+
for (let i = (layers?.length ?? 0) - 1; i >= 0; i--) {
|
|
831
|
+
const layer = layers[i];
|
|
832
|
+
rows.push({ layer, parent: layers, depth });
|
|
833
|
+
if (layer.type === "group") visit(layer.layers, depth + 1);
|
|
834
|
+
}
|
|
835
|
+
};
|
|
836
|
+
visit(state.map?.doc.layers, 0);
|
|
837
|
+
return rows;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function parentOf(target) {
|
|
841
|
+
let found;
|
|
842
|
+
tmj.walkLayers(state.map.doc.layers, (layer, parent) => {
|
|
843
|
+
if (layer === target) found = parent;
|
|
844
|
+
});
|
|
845
|
+
return found;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** Whether a layer and every group around it is shown. */
|
|
849
|
+
function shown(target) {
|
|
850
|
+
let result = false;
|
|
851
|
+
const visit = (layers, visible) => {
|
|
852
|
+
for (const layer of layers ?? []) {
|
|
853
|
+
const here = visible && layer.visible !== false;
|
|
854
|
+
if (layer === target) result = here;
|
|
855
|
+
if (layer.type === "group") visit(layer.layers, here);
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
visit(state.map?.doc.layers, true);
|
|
859
|
+
return result;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
const LAYER_ICONS = { tilelayer: "tileLayer", objectgroup: "objectLayer", group: "group", imagelayer: "image" };
|
|
863
|
+
|
|
864
|
+
function renderLayers() {
|
|
865
|
+
const rows = layerRows();
|
|
866
|
+
const canEdit = editable();
|
|
867
|
+
els.layers.replaceChildren(
|
|
868
|
+
...rows.map(({ layer, depth }) => {
|
|
869
|
+
const visible = layer.visible !== false;
|
|
870
|
+
const name = h("span", { class: "layer-name", title: canEdit ? t.rename : undefined }, layer.name || " ");
|
|
871
|
+
const row = h(
|
|
872
|
+
"div",
|
|
873
|
+
{
|
|
874
|
+
class: "layer-row",
|
|
875
|
+
role: "option",
|
|
876
|
+
"aria-selected": String(layer === state.active),
|
|
877
|
+
"data-hidden": visible ? undefined : "",
|
|
878
|
+
style: `padding-inline-start: ${4 + depth * 14}px`,
|
|
879
|
+
on: {
|
|
880
|
+
click: () => {
|
|
881
|
+
state.active = layer;
|
|
882
|
+
refresh();
|
|
883
|
+
},
|
|
884
|
+
dblclick: () => canEdit && startRename(row, name, layer),
|
|
885
|
+
},
|
|
886
|
+
},
|
|
887
|
+
h(
|
|
888
|
+
"button",
|
|
889
|
+
{
|
|
890
|
+
class: "layer-eye",
|
|
891
|
+
type: "button",
|
|
892
|
+
"aria-label": visible ? t.hide : t.show,
|
|
893
|
+
title: visible ? t.hide : t.show,
|
|
894
|
+
disabled: !canEdit,
|
|
895
|
+
on: {
|
|
896
|
+
click: (event) => {
|
|
897
|
+
event.stopPropagation();
|
|
898
|
+
editFields(layer, (target) => tmj.setKey(target, "visible", !visible));
|
|
899
|
+
},
|
|
900
|
+
},
|
|
901
|
+
},
|
|
902
|
+
icon(visible ? "eye" : "eyeOff"),
|
|
903
|
+
),
|
|
904
|
+
h("span", { class: "layer-kind" }, icon(LAYER_ICONS[layer.type] ?? "tileLayer")),
|
|
905
|
+
name,
|
|
906
|
+
layer.locked === true ? h("span", { class: "layer-lock", title: t.locked, "aria-label": t.locked }, icon("lock")) : undefined,
|
|
907
|
+
);
|
|
908
|
+
return row;
|
|
909
|
+
}),
|
|
910
|
+
);
|
|
911
|
+
const active = state.active;
|
|
912
|
+
const parent = active && parentOf(active);
|
|
913
|
+
const index = parent?.indexOf(active) ?? -1;
|
|
914
|
+
els.layerActions.replaceChildren(
|
|
915
|
+
h(
|
|
916
|
+
"omg-menu",
|
|
917
|
+
{
|
|
918
|
+
label: t.addLayer,
|
|
919
|
+
class: "add-layer",
|
|
920
|
+
disabled: !canEdit,
|
|
921
|
+
props: { items: [{ value: "tilelayer", label: t.addTileLayer }, { value: "objectgroup", label: t.addObjectLayer }] },
|
|
922
|
+
on: { "omg-select": (event) => addLayer(event.detail.value) },
|
|
923
|
+
},
|
|
924
|
+
h("span", { slot: "trigger" }, icon("plus")),
|
|
925
|
+
),
|
|
926
|
+
iconButton("up", t.moveUp, () => moveLayer(1), { disabled: !canEdit || index < 0 || index >= parent.length - 1 }),
|
|
927
|
+
iconButton("down", t.moveDown, () => moveLayer(-1), { disabled: !canEdit || index <= 0 }),
|
|
928
|
+
iconButton("trash", t.deleteLayer, () => void deleteLayer(), { disabled: !canEdit || !active }),
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function startRename(row, name, layer) {
|
|
933
|
+
const input = h("input", { class: "omg-input layer-rename", value: layer.name ?? "", "aria-label": t.name });
|
|
934
|
+
let done = false;
|
|
935
|
+
const finish = (commit) => {
|
|
936
|
+
if (done) return;
|
|
937
|
+
done = true;
|
|
938
|
+
if (commit && input.value.trim() && input.value !== layer.name) editFields(layer, (target) => tmj.setKey(target, "name", input.value.trim()));
|
|
939
|
+
else renderLayers();
|
|
940
|
+
};
|
|
941
|
+
input.addEventListener("keydown", (event) => {
|
|
942
|
+
event.stopPropagation();
|
|
943
|
+
if (event.key === "Enter") finish(true);
|
|
944
|
+
if (event.key === "Escape") finish(false);
|
|
945
|
+
});
|
|
946
|
+
input.addEventListener("blur", () => finish(true));
|
|
947
|
+
input.addEventListener("click", (event) => event.stopPropagation());
|
|
948
|
+
name.replaceWith(input);
|
|
949
|
+
input.focus();
|
|
950
|
+
input.select();
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
function addLayer(kind) {
|
|
954
|
+
const doc = state.map.doc;
|
|
955
|
+
const parent = (state.active && parentOf(state.active)) ?? doc.layers;
|
|
956
|
+
const index = state.active ? parent.indexOf(state.active) + 1 : parent.length;
|
|
957
|
+
let like;
|
|
958
|
+
tmj.walkLayers(doc.layers, (layer) => {
|
|
959
|
+
if (!like && layer.type === "tilelayer" && layer.data !== undefined) like = layer;
|
|
960
|
+
});
|
|
961
|
+
let count = 0;
|
|
962
|
+
tmj.walkLayers(doc.layers, (layer) => void (layer.type === kind && count++));
|
|
963
|
+
const name = `${kind === "tilelayer" ? t.newTileLayer : t.newObjectLayer} ${count + 1}`;
|
|
964
|
+
const layer = tmj.createLayer(doc, kind, name, like);
|
|
965
|
+
if (kind === "tilelayer") state.map.tiles.set(layer, tmj.tilesFor(doc));
|
|
966
|
+
editList(parent, (list) => list.splice(index, 0, layer));
|
|
967
|
+
state.active = layer;
|
|
968
|
+
refresh();
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
function moveLayer(direction) {
|
|
972
|
+
const layer = state.active;
|
|
973
|
+
const parent = parentOf(layer);
|
|
974
|
+
const index = parent.indexOf(layer);
|
|
975
|
+
const target = index + direction;
|
|
976
|
+
if (target < 0 || target >= parent.length) return;
|
|
977
|
+
editList(parent, (list) => {
|
|
978
|
+
list.splice(index, 1);
|
|
979
|
+
list.splice(target, 0, layer);
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
async function deleteLayer() {
|
|
984
|
+
const layer = state.active;
|
|
985
|
+
if (!layer) return;
|
|
986
|
+
let agreed = false;
|
|
987
|
+
const name = layer.name ?? "";
|
|
988
|
+
try {
|
|
989
|
+
agreed = await host.request("ui.confirm", {
|
|
990
|
+
title: t.deleteLayerTitle(name.length > 60 ? `${name.slice(0, 59)}…` : name),
|
|
991
|
+
message: t.deleteLayerMessage,
|
|
992
|
+
confirmLabel: t.delete,
|
|
993
|
+
});
|
|
994
|
+
} catch (error) {
|
|
995
|
+
// The app couldn't ask (too many questions, or the panel isn't showing).
|
|
996
|
+
toast(t.couldNotAsk(errorText(error)));
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
if (!agreed || layer !== state.active) return;
|
|
1000
|
+
const parent = parentOf(layer);
|
|
1001
|
+
const index = parent.indexOf(layer);
|
|
1002
|
+
editList(parent, (list) => list.splice(index, 1));
|
|
1003
|
+
let group;
|
|
1004
|
+
tmj.walkLayers(state.map.doc.layers, (item) => {
|
|
1005
|
+
if (item.layers === parent) group = item;
|
|
1006
|
+
});
|
|
1007
|
+
state.active = parent[index] ?? parent[index - 1] ?? group ?? state.map.doc.layers.at(-1);
|
|
1008
|
+
refresh();
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// ---------------------------------------------------------------------------
|
|
1012
|
+
// Tools.
|
|
1013
|
+
|
|
1014
|
+
function setTool(tool) {
|
|
1015
|
+
state.tool = tool;
|
|
1016
|
+
state.message = "";
|
|
1017
|
+
updateToolbar();
|
|
1018
|
+
renderStatus();
|
|
1019
|
+
invalidate();
|
|
1020
|
+
els.canvas.focus({ preventScroll: true });
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function pickStamp(stamp, fromMap) {
|
|
1024
|
+
state.stamp = stamp;
|
|
1025
|
+
if (fromMap) {
|
|
1026
|
+
// Show the picked tile in its tileset.
|
|
1027
|
+
const found = tmj.findTileset(state.tilesets, stamp.gids[0]);
|
|
1028
|
+
const index = found ? state.tilesets.indexOf(found.tileset) : -1;
|
|
1029
|
+
if (index >= 0 && index !== state.paletteIndex) {
|
|
1030
|
+
state.paletteIndex = index;
|
|
1031
|
+
renderTilesets();
|
|
1032
|
+
}
|
|
1033
|
+
palette.mark(tmj.tileOf(stamp.gids[0]));
|
|
1034
|
+
}
|
|
1035
|
+
if (editable() && state.tool !== "brush" && state.tool !== "fill") setTool("brush");
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/** The active layer's tiles, if it is a tile layer that can be painted. */
|
|
1039
|
+
function activeTiles() {
|
|
1040
|
+
const layer = state.active;
|
|
1041
|
+
if (!layer || layer.type !== "tilelayer") return undefined;
|
|
1042
|
+
return state.map.tiles.get(layer)?.gids ? state.map.tiles.get(layer) : undefined;
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* The object layer a new object goes on: the active one, else for a
|
|
1047
|
+
* rectangle the collision layer and for a point another one, else the topmost.
|
|
1048
|
+
*/
|
|
1049
|
+
function objectLayer(shape) {
|
|
1050
|
+
if (state.active?.type === "objectgroup") return state.active;
|
|
1051
|
+
const layers = layerRows().map((row) => row.layer).filter((layer) => layer.type === "objectgroup" && !locked(layer));
|
|
1052
|
+
const collision = (layer) => /collision/i.test(layer.name ?? "");
|
|
1053
|
+
const found = layers.find((layer) => (shape === "rectangle" ? collision(layer) : !collision(layer))) ?? layers[0];
|
|
1054
|
+
if (found) state.active = found;
|
|
1055
|
+
return found;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
function say(message) {
|
|
1059
|
+
state.message = message;
|
|
1060
|
+
renderStatus();
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
function stampOrigin(cx, cy) {
|
|
1064
|
+
const stamp = state.stamp;
|
|
1065
|
+
return stamp ? [cx - ((stamp.width - 1) >> 1), cy - ((stamp.height - 1) >> 1)] : [cx, cy];
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/** Cells on the line from (x0, y0) to (x1, y1), so a fast stroke leaves no gaps. */
|
|
1069
|
+
function* line(x0, y0, x1, y1) {
|
|
1070
|
+
const dx = Math.abs(x1 - x0);
|
|
1071
|
+
const dy = -Math.abs(y1 - y0);
|
|
1072
|
+
const sx = x0 < x1 ? 1 : -1;
|
|
1073
|
+
const sy = y0 < y1 ? 1 : -1;
|
|
1074
|
+
let error = dx + dy;
|
|
1075
|
+
for (;;) {
|
|
1076
|
+
yield [x0, y0];
|
|
1077
|
+
if (x0 === x1 && y0 === y1) return;
|
|
1078
|
+
const twice = 2 * error;
|
|
1079
|
+
if (twice >= dy) {
|
|
1080
|
+
error += dy;
|
|
1081
|
+
x0 += sx;
|
|
1082
|
+
}
|
|
1083
|
+
if (twice <= dx) {
|
|
1084
|
+
error += dx;
|
|
1085
|
+
y0 += sy;
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
function paintCell(drag, cx, cy) {
|
|
1091
|
+
if (drag.erase) tmj.erase(drag.tiles, cx, cy, 1, 1, drag.changes);
|
|
1092
|
+
else {
|
|
1093
|
+
const [x, y] = stampOrigin(cx, cy);
|
|
1094
|
+
tmj.paintStamp(drag.tiles, x, y, state.stamp, drag.changes);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/** The topmost object under map point (wx, wy): the active layer's first, then any shown layer's. */
|
|
1099
|
+
function objectAt(wx, wy) {
|
|
1100
|
+
const radius = 7 / state.view.zoom;
|
|
1101
|
+
const offset = (layer) => {
|
|
1102
|
+
let x = 0;
|
|
1103
|
+
let y = 0;
|
|
1104
|
+
const visit = (layers, ox, oy) => {
|
|
1105
|
+
for (const item of layers ?? []) {
|
|
1106
|
+
const nx = ox + (item.offsetx ?? 0);
|
|
1107
|
+
const ny = oy + (item.offsety ?? 0);
|
|
1108
|
+
if (item === layer) [x, y] = [nx, ny];
|
|
1109
|
+
if (item.type === "group") visit(item.layers, nx, ny);
|
|
1110
|
+
}
|
|
1111
|
+
};
|
|
1112
|
+
visit(state.map.doc.layers, 0, 0);
|
|
1113
|
+
return [x, y];
|
|
1114
|
+
};
|
|
1115
|
+
const layers = layerRows()
|
|
1116
|
+
.map((row) => row.layer)
|
|
1117
|
+
.filter((layer) => layer.type === "objectgroup" && shown(layer));
|
|
1118
|
+
if (state.active?.type === "objectgroup") layers.sort((a, b) => (b === state.active) - (a === state.active));
|
|
1119
|
+
for (const layer of layers) {
|
|
1120
|
+
const [ox, oy] = offset(layer);
|
|
1121
|
+
const objects = layer.objects ?? [];
|
|
1122
|
+
for (let i = objects.length - 1; i >= 0; i--) {
|
|
1123
|
+
const object = objects[i];
|
|
1124
|
+
if (object.visible === false) continue;
|
|
1125
|
+
if (hitsObject(object, wx - ox, wy - oy, radius)) return { layer, object };
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
return undefined;
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
function onPointerDown(event) {
|
|
1132
|
+
if (!state.map) return;
|
|
1133
|
+
els.canvas.focus({ preventScroll: true });
|
|
1134
|
+
const at = pointer(event);
|
|
1135
|
+
if (event.button === 1 || (event.button === 0 && state.space)) {
|
|
1136
|
+
event.preventDefault();
|
|
1137
|
+
els.canvas.setPointerCapture(event.pointerId);
|
|
1138
|
+
state.drag = { kind: "pan", sx: event.clientX, sy: event.clientY, vx: state.view.x, vy: state.view.y };
|
|
1139
|
+
updateCursor();
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
if (event.button !== 0 || state.saving) return;
|
|
1143
|
+
const tool = state.tool;
|
|
1144
|
+
if (!editable() && tool !== "select") return;
|
|
1145
|
+
if (TILE_TOOLS.has(tool)) {
|
|
1146
|
+
if (tool === "eyedropper") return pickFromMap(at.wx, at.wy);
|
|
1147
|
+
const tiles = activeTiles();
|
|
1148
|
+
if (!tiles) return say(t.needTileLayer);
|
|
1149
|
+
if (locked(state.active)) return say(t.layerLocked);
|
|
1150
|
+
if (!shown(state.active)) say(t.hiddenLayer);
|
|
1151
|
+
const [cx, cy] = cellIn(state.active, at.wx, at.wy);
|
|
1152
|
+
if (tool !== "eraser" && !state.stamp) return;
|
|
1153
|
+
if (tool === "fill") {
|
|
1154
|
+
tileStep(tiles.gids, tmj.floodFill(tiles, cx, cy, state.stamp));
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
els.canvas.setPointerCapture(event.pointerId);
|
|
1158
|
+
state.drag = { kind: "paint", layer: state.active, tiles, erase: tool === "eraser", changes: new Map(), last: [cx, cy] };
|
|
1159
|
+
paintCell(state.drag, cx, cy);
|
|
1160
|
+
invalidate();
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
if (tool === "rect" || tool === "point") {
|
|
1164
|
+
const layer = objectLayer(tool === "rect" ? "rectangle" : "point");
|
|
1165
|
+
if (!layer) return say(t.needObjectLayer);
|
|
1166
|
+
if (locked(layer)) return say(t.layerLocked);
|
|
1167
|
+
const point = local(layer, at.wx, at.wy);
|
|
1168
|
+
if (tool === "point") {
|
|
1169
|
+
const [x, y] = snapPoint(...point, event.altKey);
|
|
1170
|
+
addObject(layer, { shape: "point", x, y });
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
els.canvas.setPointerCapture(event.pointerId);
|
|
1174
|
+
state.drag = { kind: "rect", layer, start: point, end: point, free: event.altKey };
|
|
1175
|
+
invalidate();
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
if (tool === "select") {
|
|
1179
|
+
const hit = objectAt(at.wx, at.wy);
|
|
1180
|
+
state.selection = hit;
|
|
1181
|
+
if (hit) {
|
|
1182
|
+
state.active = hit.layer;
|
|
1183
|
+
if (locked(hit.layer)) say(t.layerLocked);
|
|
1184
|
+
else if (editable()) {
|
|
1185
|
+
els.canvas.setPointerCapture(event.pointerId);
|
|
1186
|
+
state.drag = { kind: "move", ...hit, before: tmj.captureFields(hit.object), sx: at.wx, sy: at.wy, ox: hit.object.x, oy: hit.object.y, moved: false };
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
refresh();
|
|
1190
|
+
invalidate();
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
function onPointerMove(event) {
|
|
1195
|
+
if (!state.map) return;
|
|
1196
|
+
const at = pointer(event);
|
|
1197
|
+
// Cells are those of the active layer, which may be offset.
|
|
1198
|
+
const cell = cellIn(state.active, at.wx, at.wy);
|
|
1199
|
+
const hover = state.hover;
|
|
1200
|
+
state.hover = { ...at, cx: cell[0], cy: cell[1] };
|
|
1201
|
+
const drag = state.drag;
|
|
1202
|
+
if (drag?.kind === "pan") {
|
|
1203
|
+
state.view = { ...state.view, x: drag.vx + event.clientX - drag.sx, y: drag.vy + event.clientY - drag.sy };
|
|
1204
|
+
} else if (drag?.kind === "paint") {
|
|
1205
|
+
if (!state.saving) {
|
|
1206
|
+
const [cx, cy] = cellIn(drag.layer, at.wx, at.wy);
|
|
1207
|
+
for (const [x, y] of line(drag.last[0], drag.last[1], cx, cy)) paintCell(drag, x, y);
|
|
1208
|
+
drag.last = [cx, cy];
|
|
1209
|
+
}
|
|
1210
|
+
} else if (drag?.kind === "rect") {
|
|
1211
|
+
drag.end = local(drag.layer, at.wx, at.wy);
|
|
1212
|
+
drag.free = event.altKey;
|
|
1213
|
+
} else if (drag?.kind === "move") {
|
|
1214
|
+
const dx = Math.round(at.wx - drag.sx);
|
|
1215
|
+
const dy = Math.round(at.wy - drag.sy);
|
|
1216
|
+
if (dx || dy || drag.moved) {
|
|
1217
|
+
drag.moved = true;
|
|
1218
|
+
drag.object.x = drag.ox + dx;
|
|
1219
|
+
drag.object.y = drag.oy + dy;
|
|
1220
|
+
renderInspector();
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
if (!hover || hover.cx !== cell[0] || hover.cy !== cell[1] || drag || state.tool === "select" || state.tool === "point") invalidate();
|
|
1224
|
+
renderStatus();
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
function onPointerUp(event) {
|
|
1228
|
+
const drag = state.drag;
|
|
1229
|
+
if (!drag) return;
|
|
1230
|
+
els.canvas.releasePointerCapture?.(event.pointerId);
|
|
1231
|
+
state.drag = undefined;
|
|
1232
|
+
if (drag.kind === "paint") tileStep(drag.tiles.gids, drag.changes);
|
|
1233
|
+
else if (drag.kind === "rect") {
|
|
1234
|
+
const rect = rectOf(drag);
|
|
1235
|
+
addObject(drag.layer, { shape: "rectangle", ...rect });
|
|
1236
|
+
} else if (drag.kind === "move" && drag.moved) {
|
|
1237
|
+
const after = tmj.captureFields(drag.object);
|
|
1238
|
+
const { object, before } = drag;
|
|
1239
|
+
record({ undo: () => tmj.restoreFields(object, before), redo: () => tmj.restoreFields(object, after) });
|
|
1240
|
+
}
|
|
1241
|
+
updateCursor();
|
|
1242
|
+
invalidate();
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
/**
|
|
1246
|
+
* A rectangle drawn from `start` to `end`, in its layer's own coordinates:
|
|
1247
|
+
* whole cells unless free (Alt), at least one cell.
|
|
1248
|
+
*/
|
|
1249
|
+
function rectOf({ start, end, free }) {
|
|
1250
|
+
const { tilewidth: tw, tileheight: th } = state.map.doc;
|
|
1251
|
+
if (free) {
|
|
1252
|
+
const x = Math.round(Math.min(start[0], end[0]));
|
|
1253
|
+
const y = Math.round(Math.min(start[1], end[1]));
|
|
1254
|
+
const width = Math.round(Math.max(start[0], end[0])) - x;
|
|
1255
|
+
const height = Math.round(Math.max(start[1], end[1])) - y;
|
|
1256
|
+
if (width >= 1 && height >= 1) return { x, y, width, height };
|
|
1257
|
+
}
|
|
1258
|
+
const [c0, r0] = cellAt(...start);
|
|
1259
|
+
const [c1, r1] = cellAt(...end);
|
|
1260
|
+
return { x: Math.min(c0, c1) * tw, y: Math.min(r0, r1) * th, width: (Math.abs(c1 - c0) + 1) * tw, height: (Math.abs(r1 - r0) + 1) * th };
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** A point at the centre of its cell, or where it is with Alt, in its layer's own coordinates. */
|
|
1264
|
+
function snapPoint(wx, wy, free) {
|
|
1265
|
+
if (free) return [Math.round(wx), Math.round(wy)];
|
|
1266
|
+
const { tilewidth: tw, tileheight: th } = state.map.doc;
|
|
1267
|
+
return [Math.floor(wx / tw) * tw + tw / 2, Math.floor(wy / th) * th + th / 2];
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
function addObject(layer, fields) {
|
|
1271
|
+
const object = tmj.createObject(state.map.doc, layer, fields);
|
|
1272
|
+
editList(layer.objects, (list) => list.push(object));
|
|
1273
|
+
state.selection = { layer, object };
|
|
1274
|
+
refresh();
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
function deleteSelection() {
|
|
1278
|
+
const selection = state.selection;
|
|
1279
|
+
if (!selection || !editable() || state.drag) return;
|
|
1280
|
+
if (locked(selection.layer)) return say(t.layerLocked);
|
|
1281
|
+
const index = selection.layer.objects.indexOf(selection.object);
|
|
1282
|
+
if (index < 0) return;
|
|
1283
|
+
state.selection = undefined;
|
|
1284
|
+
editList(selection.layer.objects, (list) => list.splice(index, 1));
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
function nudge(dx, dy) {
|
|
1288
|
+
const object = state.selection?.object;
|
|
1289
|
+
if (!object || !editable() || state.drag) return;
|
|
1290
|
+
if (locked(state.selection.layer)) return say(t.layerLocked);
|
|
1291
|
+
editFields(object, (target) => {
|
|
1292
|
+
target.x += dx;
|
|
1293
|
+
target.y += dy;
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
function pickFromMap(wx, wy) {
|
|
1298
|
+
const map = state.map;
|
|
1299
|
+
const pick = (layer) => {
|
|
1300
|
+
const [cx, cy] = cellIn(layer, wx, wy);
|
|
1301
|
+
const tiles = map.tiles.get(layer);
|
|
1302
|
+
if (!tiles?.gids || cx < 0 || cy < 0 || cx >= tiles.width || cy >= tiles.height) return 0;
|
|
1303
|
+
return tiles.gids[cy * tiles.width + cx];
|
|
1304
|
+
};
|
|
1305
|
+
let gid = state.active?.type === "tilelayer" ? pick(state.active) : 0;
|
|
1306
|
+
if (!gid) {
|
|
1307
|
+
for (const { layer } of layerRows()) {
|
|
1308
|
+
if (layer.type !== "tilelayer" || !shown(layer)) continue;
|
|
1309
|
+
gid = pick(layer);
|
|
1310
|
+
if (gid) {
|
|
1311
|
+
state.active = layer;
|
|
1312
|
+
break;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
if (gid) pickStamp(tmj.stampOf(1, 1, [gid]), true);
|
|
1317
|
+
refresh();
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
function onWheel(event) {
|
|
1321
|
+
if (!state.map) return;
|
|
1322
|
+
event.preventDefault();
|
|
1323
|
+
const at = pointer(event);
|
|
1324
|
+
if (event.ctrlKey || event.metaKey) {
|
|
1325
|
+
// A mouse wheel moves in big steps, a trackpad pinch in small ones.
|
|
1326
|
+
const speed = event.deltaMode === 1 ? 0.05 : Math.abs(event.deltaY) >= 50 ? 0.0025 : 0.01;
|
|
1327
|
+
const factor = Math.exp(-event.deltaY * speed);
|
|
1328
|
+
zoomAround(state.view.zoom * factor, at.px, at.py);
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
const scale = event.deltaMode === 1 ? 16 : 1;
|
|
1332
|
+
const dx = event.shiftKey && !event.deltaX ? event.deltaY : event.deltaX;
|
|
1333
|
+
const dy = event.shiftKey && !event.deltaX ? 0 : event.deltaY;
|
|
1334
|
+
state.view = { ...state.view, x: state.view.x - dx * scale, y: state.view.y - dy * scale };
|
|
1335
|
+
invalidate();
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
els.canvas.addEventListener("pointerdown", onPointerDown);
|
|
1339
|
+
els.canvas.addEventListener("pointermove", onPointerMove);
|
|
1340
|
+
els.canvas.addEventListener("pointerup", onPointerUp);
|
|
1341
|
+
els.canvas.addEventListener("pointercancel", onPointerUp);
|
|
1342
|
+
els.canvas.addEventListener("pointerleave", () => {
|
|
1343
|
+
if (state.drag) return;
|
|
1344
|
+
state.hover = undefined;
|
|
1345
|
+
invalidate();
|
|
1346
|
+
renderStatus();
|
|
1347
|
+
});
|
|
1348
|
+
els.canvas.addEventListener("wheel", onWheel, { passive: false });
|
|
1349
|
+
els.canvas.addEventListener("contextmenu", (event) => event.preventDefault());
|
|
1350
|
+
// No autoscroll on a middle-button drag, which pans.
|
|
1351
|
+
els.canvas.addEventListener("mousedown", (event) => event.button === 1 && event.preventDefault());
|
|
1352
|
+
els.canvas.addEventListener("auxclick", (event) => event.preventDefault());
|
|
1353
|
+
|
|
1354
|
+
function updateCursor() {
|
|
1355
|
+
const panning = state.space || state.drag?.kind === "pan";
|
|
1356
|
+
els.canvas.dataset.cursor = panning ? (state.drag?.kind === "pan" ? "grabbing" : "grab") : state.tool;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
// ---------------------------------------------------------------------------
|
|
1360
|
+
// The tool's preview over the map.
|
|
1361
|
+
|
|
1362
|
+
function drawOverlay(ctx, toMap, scale) {
|
|
1363
|
+
const toDevice = toMap;
|
|
1364
|
+
const map = state.map;
|
|
1365
|
+
const { tilewidth: tw, tileheight: th } = map.doc;
|
|
1366
|
+
const dpr = window.devicePixelRatio || 1;
|
|
1367
|
+
const box = (x, y, w, h, color, dash) => {
|
|
1368
|
+
const [x0, y0] = toDevice(x, y);
|
|
1369
|
+
const [x1, y1] = toDevice(x + w, y + h);
|
|
1370
|
+
const left = Math.round(x0) + 0.5;
|
|
1371
|
+
const top = Math.round(y0) + 0.5;
|
|
1372
|
+
const width = Math.round(x1) - Math.round(x0) - 1;
|
|
1373
|
+
const height = Math.round(y1) - Math.round(y0) - 1;
|
|
1374
|
+
ctx.setLineDash(dash ? [4 * dpr, 3 * dpr] : []);
|
|
1375
|
+
ctx.lineWidth = 3 * dpr;
|
|
1376
|
+
ctx.strokeStyle = theme.shadow;
|
|
1377
|
+
ctx.strokeRect(left, top, width, height);
|
|
1378
|
+
ctx.lineWidth = 1.5 * dpr;
|
|
1379
|
+
ctx.strokeStyle = color;
|
|
1380
|
+
ctx.strokeRect(left, top, width, height);
|
|
1381
|
+
ctx.setLineDash([]);
|
|
1382
|
+
};
|
|
1383
|
+
const frame = box;
|
|
1384
|
+
|
|
1385
|
+
const drag = state.drag;
|
|
1386
|
+
if (drag?.kind === "rect") {
|
|
1387
|
+
const [ox, oy] = layerOffset(drag.layer);
|
|
1388
|
+
const local = rectOf(drag);
|
|
1389
|
+
const rect = { ...local, x: local.x + ox, y: local.y + oy };
|
|
1390
|
+
const [x0, y0] = toDevice(rect.x, rect.y);
|
|
1391
|
+
const [x1, y1] = toDevice(rect.x + rect.width, rect.y + rect.height);
|
|
1392
|
+
ctx.fillStyle = withAlpha(layerColor(drag.layer, theme), 0.25);
|
|
1393
|
+
ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
|
|
1394
|
+
box(rect.x, rect.y, rect.width, rect.height, layerColor(drag.layer, theme));
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
const hover = state.hover;
|
|
1398
|
+
if (hover && !drag && editable() && !locked(state.active)) {
|
|
1399
|
+
const { cx, cy } = hover;
|
|
1400
|
+
// Cells and points are those of the active layer, drawn where its offset puts them.
|
|
1401
|
+
const [ox, oy] = state.active ? layerOffset(state.active) : [0, 0];
|
|
1402
|
+
const box = (x, y, w, h, color, dash) => frame(x + ox, y + oy, w, h, color, dash);
|
|
1403
|
+
const toDevice = (x, y) => toMap(x + ox, y + oy);
|
|
1404
|
+
if (state.tool === "brush" && state.stamp && activeTiles()) {
|
|
1405
|
+
const [x, y] = stampOrigin(cx, cy);
|
|
1406
|
+
ctx.globalAlpha = 0.6;
|
|
1407
|
+
const { stamp } = state;
|
|
1408
|
+
for (let row = 0; row < stamp.height; row++) {
|
|
1409
|
+
for (let column = 0; column < stamp.width; column++) {
|
|
1410
|
+
const gid = stamp.gids[row * stamp.width + column];
|
|
1411
|
+
const tile = gid && tileFor(gid);
|
|
1412
|
+
if (!tile) continue;
|
|
1413
|
+
const [x0, y0] = toDevice((x + column) * tw, (y + row) * th);
|
|
1414
|
+
const [x1, y1] = toDevice((x + column + 1) * tw, (y + row + 1) * th);
|
|
1415
|
+
drawTile(ctx, tile, gid, x0, y0, x1, y1);
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
ctx.globalAlpha = 1;
|
|
1419
|
+
box(x * tw, y * th, stamp.width * tw, stamp.height * th, theme.selection);
|
|
1420
|
+
} else if (TILE_TOOLS.has(state.tool)) {
|
|
1421
|
+
box(cx * tw, cy * th, tw, th, state.tool === "eraser" ? theme.danger : theme.hover);
|
|
1422
|
+
} else if (state.tool === "rect") {
|
|
1423
|
+
box(cx * tw, cy * th, tw, th, theme.hover, true);
|
|
1424
|
+
} else if (state.tool === "point") {
|
|
1425
|
+
const [x, y] = snapPoint(...local(state.active, hover.wx, hover.wy), false);
|
|
1426
|
+
const [px, py] = toDevice(x, y);
|
|
1427
|
+
ctx.beginPath();
|
|
1428
|
+
ctx.arc(px, py, 4 * dpr, 0, Math.PI * 2);
|
|
1429
|
+
ctx.lineWidth = 1.5 * dpr;
|
|
1430
|
+
ctx.strokeStyle = theme.hover;
|
|
1431
|
+
ctx.stroke();
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
if (state.tool === "select" && hover && !drag) {
|
|
1435
|
+
const hit = objectAt(hover.wx, hover.wy);
|
|
1436
|
+
if (hit && hit.object !== state.selection?.object) {
|
|
1437
|
+
const [ox, oy] = layerOffset(hit.layer);
|
|
1438
|
+
const b = objectBox(hit.object, 7 / state.view.zoom);
|
|
1439
|
+
box(b.x + ox, b.y + oy, b.width, b.height, theme.hover, true);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
if (state.selection) {
|
|
1443
|
+
const { layer, object } = state.selection;
|
|
1444
|
+
const [ox, oy] = layerOffset(layer);
|
|
1445
|
+
const b = objectBox(object, 7 / state.view.zoom);
|
|
1446
|
+
box(b.x + ox, b.y + oy, Math.max(b.width, 1 / scale), Math.max(b.height, 1 / scale), theme.selection);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
function layerOffset(target) {
|
|
1451
|
+
let result = [0, 0];
|
|
1452
|
+
const visit = (layers, ox, oy) => {
|
|
1453
|
+
for (const layer of layers ?? []) {
|
|
1454
|
+
const x = ox + (layer.offsetx ?? 0);
|
|
1455
|
+
const y = oy + (layer.offsety ?? 0);
|
|
1456
|
+
if (layer === target) result = [x, y];
|
|
1457
|
+
if (layer.type === "group") visit(layer.layers, x, y);
|
|
1458
|
+
}
|
|
1459
|
+
};
|
|
1460
|
+
visit(state.map.doc.layers, 0, 0);
|
|
1461
|
+
return result;
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// ---------------------------------------------------------------------------
|
|
1465
|
+
// Keyboard.
|
|
1466
|
+
|
|
1467
|
+
const typing = (event) => {
|
|
1468
|
+
const target = event.composedPath?.()[0] ?? event.target;
|
|
1469
|
+
return target instanceof HTMLElement && (target.isContentEditable || /^(?:INPUT|TEXTAREA|SELECT)$/.test(target.tagName));
|
|
1470
|
+
};
|
|
1471
|
+
|
|
1472
|
+
window.addEventListener("keydown", (event) => {
|
|
1473
|
+
const mod = event.metaKey || event.ctrlKey;
|
|
1474
|
+
const key = event.key.toLowerCase();
|
|
1475
|
+
if (mod && key === "s") {
|
|
1476
|
+
event.preventDefault();
|
|
1477
|
+
// A field being typed in commits its value when it loses focus.
|
|
1478
|
+
const focused = document.activeElement;
|
|
1479
|
+
if (focused instanceof HTMLElement && focused !== document.body) focused.blur();
|
|
1480
|
+
void save();
|
|
1481
|
+
return;
|
|
1482
|
+
}
|
|
1483
|
+
if (typing(event) || document.querySelector("omg-dialog[open]")) return;
|
|
1484
|
+
if (mod && key === "z") {
|
|
1485
|
+
event.preventDefault();
|
|
1486
|
+
if (event.shiftKey) redoStep();
|
|
1487
|
+
else undoStep();
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
if (mod && key === "y") {
|
|
1491
|
+
event.preventDefault();
|
|
1492
|
+
redoStep();
|
|
1493
|
+
return;
|
|
1494
|
+
}
|
|
1495
|
+
if (mod || event.altKey || !state.map) return;
|
|
1496
|
+
if (event.key === " ") {
|
|
1497
|
+
event.preventDefault();
|
|
1498
|
+
if (!state.space) {
|
|
1499
|
+
state.space = true;
|
|
1500
|
+
updateCursor();
|
|
1501
|
+
}
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
const tool = TOOLS.find(([, , shortcut]) => shortcut.toLowerCase() === key);
|
|
1505
|
+
if (tool) {
|
|
1506
|
+
event.preventDefault();
|
|
1507
|
+
setTool(tool[0]);
|
|
1508
|
+
return;
|
|
1509
|
+
}
|
|
1510
|
+
if (event.key === "Escape") {
|
|
1511
|
+
state.selection = undefined;
|
|
1512
|
+
refresh();
|
|
1513
|
+
invalidate();
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
if ((event.key === "Delete" || event.key === "Backspace") && state.selection) {
|
|
1517
|
+
event.preventDefault();
|
|
1518
|
+
deleteSelection();
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
const arrows = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
|
|
1522
|
+
if (arrows && state.selection) {
|
|
1523
|
+
event.preventDefault();
|
|
1524
|
+
const { tilewidth, tileheight } = state.map.doc;
|
|
1525
|
+
nudge(arrows[0] * (event.shiftKey ? tilewidth : 1), arrows[1] * (event.shiftKey ? tileheight : 1));
|
|
1526
|
+
}
|
|
1527
|
+
});
|
|
1528
|
+
|
|
1529
|
+
window.addEventListener("keyup", (event) => {
|
|
1530
|
+
if (event.key === " " && state.space) {
|
|
1531
|
+
state.space = false;
|
|
1532
|
+
updateCursor();
|
|
1533
|
+
}
|
|
1534
|
+
});
|
|
1535
|
+
window.addEventListener("blur", () => {
|
|
1536
|
+
state.space = false;
|
|
1537
|
+
updateCursor();
|
|
1538
|
+
});
|
|
1539
|
+
|
|
1540
|
+
// ---------------------------------------------------------------------------
|
|
1541
|
+
// The inspector for the selected object (inspector.js).
|
|
1542
|
+
|
|
1543
|
+
const renderInspector = createInspector({
|
|
1544
|
+
element: els.inspector,
|
|
1545
|
+
t,
|
|
1546
|
+
selection: () => state.selection,
|
|
1547
|
+
doc: () => state.map.doc,
|
|
1548
|
+
editable: (selection) => editable() && !locked(selection.layer),
|
|
1549
|
+
editFields,
|
|
1550
|
+
deleteSelection,
|
|
1551
|
+
});
|
|
1552
|
+
|
|
1553
|
+
// ---------------------------------------------------------------------------
|
|
1554
|
+
// Toolbar, notices and status.
|
|
1555
|
+
|
|
1556
|
+
function updateToolbar() {
|
|
1557
|
+
const map = state.map;
|
|
1558
|
+
const canEdit = editable();
|
|
1559
|
+
for (const [tool, button] of els.tools) {
|
|
1560
|
+
const pressed = state.tool === tool;
|
|
1561
|
+
button.toggleAttribute("data-pressed", pressed);
|
|
1562
|
+
button.setAttribute("aria-pressed", String(pressed));
|
|
1563
|
+
button.disabled = !map || (!canEdit && tool !== "select");
|
|
1564
|
+
}
|
|
1565
|
+
els.undo.disabled = !state.at;
|
|
1566
|
+
els.redo.disabled = state.at >= state.history.length;
|
|
1567
|
+
els.zoomLabel.textContent = `${Math.round(state.view.zoom * 100)}%`;
|
|
1568
|
+
els.grid.toggleAttribute("data-pressed", state.grid);
|
|
1569
|
+
els.grid.setAttribute("aria-pressed", String(state.grid));
|
|
1570
|
+
els.dirty.hidden = !map || !isDirty();
|
|
1571
|
+
els.save.disabled = !map || !canEdit || !isDirty() || state.saving || state.external !== undefined;
|
|
1572
|
+
els.save.busy = state.saving;
|
|
1573
|
+
els.save.textContent = state.saving ? t.saving : t.save;
|
|
1574
|
+
updateCursor();
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
function renderNotices() {
|
|
1578
|
+
const notices = [];
|
|
1579
|
+
if (state.openError) notices.push(h("omg-banner", { tone: "bad" }, state.openError));
|
|
1580
|
+
if (state.map) {
|
|
1581
|
+
for (const reason of state.map.readOnly) notices.push(h("omg-banner", { tone: "warning" }, t.readOnly[reason] ?? reason));
|
|
1582
|
+
if (state.removed) notices.push(h("omg-banner", { tone: "warning" }, t.removedOnDisk));
|
|
1583
|
+
if (state.external !== undefined) {
|
|
1584
|
+
notices.push(
|
|
1585
|
+
h(
|
|
1586
|
+
"omg-banner",
|
|
1587
|
+
{ tone: "warning" },
|
|
1588
|
+
t.changedOnDisk,
|
|
1589
|
+
h("omg-button", { slot: "actions", on: { click: () => void openPath(state.map.path, { keepView: true, force: true }) } }, t.reload),
|
|
1590
|
+
h(
|
|
1591
|
+
"omg-button",
|
|
1592
|
+
{
|
|
1593
|
+
slot: "actions",
|
|
1594
|
+
variant: "ghost",
|
|
1595
|
+
on: {
|
|
1596
|
+
click: () => {
|
|
1597
|
+
// Saving now replaces what is on disk; don't ask again about this version.
|
|
1598
|
+
state.diskText = state.external;
|
|
1599
|
+
state.external = undefined;
|
|
1600
|
+
renderNotices();
|
|
1601
|
+
},
|
|
1602
|
+
},
|
|
1603
|
+
},
|
|
1604
|
+
t.keepMine,
|
|
1605
|
+
),
|
|
1606
|
+
),
|
|
1607
|
+
);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
els.notices.replaceChildren(...notices);
|
|
1611
|
+
els.notices.hidden = !notices.length;
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
function renderStatus() {
|
|
1615
|
+
const map = state.map;
|
|
1616
|
+
const { cell, layer, message, size } = els.status;
|
|
1617
|
+
if (!map) {
|
|
1618
|
+
for (const element of [cell, layer, message, size]) element.textContent = "";
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
const hover = state.hover;
|
|
1622
|
+
let text = "";
|
|
1623
|
+
if (hover) {
|
|
1624
|
+
text = t.cell(hover.cx, hover.cy);
|
|
1625
|
+
const tiles = state.active?.type === "tilelayer" ? map.tiles.get(state.active) : undefined;
|
|
1626
|
+
if (tiles?.gids && hover.cx >= 0 && hover.cy >= 0 && hover.cx < tiles.width && hover.cy < tiles.height) {
|
|
1627
|
+
const gid = tiles.gids[hover.cy * tiles.width + hover.cx];
|
|
1628
|
+
if (gid) text += ` · ${t.tileLabel(tmj.tileOf(gid))}${tmj.flagsOf(gid) ? ` (${t.flipped})` : ""}`;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
cell.textContent = text;
|
|
1632
|
+
layer.textContent = state.active?.name ?? "";
|
|
1633
|
+
message.textContent = state.message;
|
|
1634
|
+
const doc = map.doc;
|
|
1635
|
+
size.textContent = t.mapSize(doc.width, doc.height, doc.tilewidth, doc.tileheight);
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
function refresh() {
|
|
1639
|
+
updateToolbar();
|
|
1640
|
+
renderNotices();
|
|
1641
|
+
renderLayers();
|
|
1642
|
+
renderInspector();
|
|
1643
|
+
renderStatus();
|
|
1644
|
+
renderEmpty();
|
|
1645
|
+
els.workspace.toggleAttribute("data-read-only", !editable());
|
|
1646
|
+
els.stageMessage.hidden = Boolean(state.map) || state.maps === undefined || !state.maps.length;
|
|
1647
|
+
els.stageMessage.textContent = state.maps === undefined ? t.loading : t.pickMap;
|
|
1648
|
+
invalidate();
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
// ---------------------------------------------------------------------------
|
|
1652
|
+
// New map (new-map.js).
|
|
1653
|
+
|
|
1654
|
+
async function openNewMapDialog() {
|
|
1655
|
+
if (!(await confirmDiscard())) return;
|
|
1656
|
+
await (scanning ?? Promise.resolve());
|
|
1657
|
+
if (!state.files) await scanMaps().catch(() => {});
|
|
1658
|
+
showNewMapDialog({
|
|
1659
|
+
host,
|
|
1660
|
+
t,
|
|
1661
|
+
files: state.files ?? [],
|
|
1662
|
+
created: async (path) => {
|
|
1663
|
+
state.maps = [...new Set([...(state.maps ?? []), path])].sort((a, b) => a.localeCompare(b));
|
|
1664
|
+
state.files?.push({ path, kind: "file" });
|
|
1665
|
+
await openPath(path);
|
|
1666
|
+
},
|
|
1667
|
+
});
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
// ---------------------------------------------------------------------------
|
|
1671
|
+
// Start: find the maps and open the last one used, or the first.
|
|
1672
|
+
|
|
1673
|
+
refresh();
|
|
1674
|
+
scanning = scanMaps().catch(() => {
|
|
1675
|
+
state.maps = [];
|
|
1676
|
+
renderMapSelect();
|
|
1677
|
+
});
|
|
1678
|
+
// The last map used opens while the scan runs, when it is still a map.
|
|
1679
|
+
const last = await host.request("storage.get", { key: "lastMap" }).catch(() => undefined);
|
|
1680
|
+
const lastText = typeof last === "string" && MAP_FILE.test(last) ? await host.files.text(last).catch(() => undefined) : undefined;
|
|
1681
|
+
let lastIsMap = false;
|
|
1682
|
+
try {
|
|
1683
|
+
lastIsMap = lastText !== undefined && tmj.isTiledMap(JSON.parse(lastText));
|
|
1684
|
+
} catch {
|
|
1685
|
+
// Not JSON any more.
|
|
1686
|
+
}
|
|
1687
|
+
const start = (path) =>
|
|
1688
|
+
openPath(path).catch((error) => {
|
|
1689
|
+
state.openError = t.openFailed(errorText(error));
|
|
1690
|
+
refresh();
|
|
1691
|
+
});
|
|
1692
|
+
if (lastIsMap) await start(last);
|
|
1693
|
+
await scanning;
|
|
1694
|
+
if (!state.map && !state.openError) {
|
|
1695
|
+
if (state.maps?.[0]) await start(state.maps[0]);
|
|
1696
|
+
else refresh();
|
|
1697
|
+
}
|