diff --git a/packages/tldraw/src/lib/utils/tldr/file.ts b/packages/tldraw/src/lib/utils/tldr/file.ts index 54427ea34..6fe97ad38 100644 --- a/packages/tldraw/src/lib/utils/tldr/file.ts +++ b/packages/tldraw/src/lib/utils/tldr/file.ts @@ -10,7 +10,6 @@ import { SerializedSchemaV2, SerializedStore, T, - TLAsset, TLAssetId, TLRecord, TLSchema, @@ -135,7 +134,8 @@ export function parseTldrawJsonFile({ // latest version let migrationResult: MigrationResult> try { - const storeSnapshot = Object.fromEntries(data.records.map((r) => [r.id, r as TLRecord])) + const records = pruneUnusedAssets(data.records as TLRecord[]) + const storeSnapshot = Object.fromEntries(records.map((r) => [r.id, r])) migrationResult = schema.migrateStoreSnapshot({ store: storeSnapshot, schema: data.schema }) } catch (e) { // junk data in the migration @@ -164,11 +164,19 @@ export function parseTldrawJsonFile({ } } +function pruneUnusedAssets(records: TLRecord[]) { + const usedAssets = new Set() + for (const record of records) { + if (record.typeName === 'shape' && 'assetId' in record.props && record.props.assetId) { + usedAssets.add(record.props.assetId) + } + } + return records.filter((r) => r.typeName !== 'asset' || usedAssets.has(r.id)) +} + /** @public */ export async function serializeTldrawJson(store: TLStore): Promise { const records: TLRecord[] = [] - const usedAssets = new Set() - const assets: TLAsset[] = [] for (const record of store.allRecords()) { switch (record.typeName) { case 'asset': @@ -188,7 +196,7 @@ export async function serializeTldrawJson(store: TLStore): Promise { assetSrcToSave = record.props.src } - assets.push({ + records.push({ ...record, props: { ...record.props, @@ -196,26 +204,19 @@ export async function serializeTldrawJson(store: TLStore): Promise { }, }) } else { - assets.push(record) + records.push(record) } break - case 'shape': - if ('assetId' in record.props) { - usedAssets.add(record.props.assetId) - } - records.push(record) - break default: records.push(record) break } } - const recordsToSave = records.concat(assets.filter((a) => usedAssets.has(a.id))) return JSON.stringify({ tldrawFileFormatVersion: LATEST_TLDRAW_FILE_FORMAT_VERSION, schema: store.schema.serialize(), - records: recordsToSave, + records: pruneUnusedAssets(records), }) }