| 1 | import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; |
| 2 | |
| 3 | /** |
| 4 | * Editor chunk saves and reloads share the same `EDITOR_CHUNK` reply. |
| 5 | * After `EDITOR_SAVE_CHUNK` the local draft is still dirty (baseline is not |
| 6 | * updated until the ack is applied). Treating that ack like a reconnect reload |
| 7 | * leaves the Save button dirty even though the server already persisted. |
| 8 | */ |
| 9 | |
| 10 | export function editorChunkSaveKey (dimensionId, chunkX, chunkY) |
| 11 | { |
| 12 | return `${normalizeDimensionId(dimensionId ?? OVERWORLD_ID)}:${chunkX | 0},${chunkY | 0}`; |
| 13 | } |
| 14 | |
| 15 | /** Identity of the chunk a local editor draft belongs to. */ |
| 16 | export function editorDraftOwner (dimensionId, chunkX, chunkY) |
| 17 | { |
| 18 | return { |
| 19 | dimensionId: normalizeDimensionId(dimensionId ?? OVERWORLD_ID), |
| 20 | chunkX: chunkX | 0, |
| 21 | chunkY: chunkY | 0 |
| 22 | }; |
| 23 | } |
| 24 | |
| 25 | export function sameEditorChunk (a, b) |
| 26 | { |
| 27 | if (!a || !b) |
| 28 | { return false; } |
| 29 | return editorChunkSaveKey(a.dimensionId, a.chunkX, a.chunkY) |
| 30 | === editorChunkSaveKey(b.dimensionId, b.chunkX, b.chunkY); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Chunk the pending local edits belong to — used for save, discard, and |
| 35 | * sessionStorage backup. Never the chunk merely selected after navigation. |
| 36 | */ |
| 37 | export function editorDirtyChunk (draftOwner, viewed) |
| 38 | { |
| 39 | return draftOwner ?? viewed; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Whether an incoming selected-chunk `EDITOR_CHUNK` should replace the local draft. |
| 44 | * Save acks must apply even while dirty. Non-ack reloads must not wipe unsaved paint |
| 45 | * on the same chunk. A payload for a *different* chunk must not inherit leftover |
| 46 | * dirty paint from the chunk that was just left. |
| 47 | * |
| 48 | * @param {{ |
| 49 | * isSaveAck?: boolean, |
| 50 | * isDirty?: boolean, |
| 51 | * incoming?: { dimensionId?: string, chunkX?: number, chunkY?: number }|null, |
| 52 | * draftOwner?: { dimensionId?: string, chunkX?: number, chunkY?: number }|null |
| 53 | * }} options |
| 54 | */ |
| 55 | export function shouldApplySelectedEditorChunk ({ |
| 56 | isSaveAck = false, |
| 57 | isDirty = false, |
| 58 | incoming = null, |
| 59 | draftOwner = null |
| 60 | } = {}) |
| 61 | { |
| 62 | if (isSaveAck || !isDirty) |
| 63 | { return true; } |
| 64 | if (incoming && draftOwner && !sameEditorChunk(incoming, draftOwner)) |
| 65 | { return true; } |
| 66 | return false; |
| 67 | } |