Filter out unused assets. (#1502)

Prunes unused assets when exporting to a file.

### Change Type

- [x] `patch` — Bug Fix

### Test Plan

1. Insert an image.
2. Delete the image.
3. Save to file.
4. The saved file should not have the asset record present.
5. The file size should also be quite small (around 2kb for a file with
no shapes).

### Release Notes

- Optimize file size of exported files.
This commit is contained in:
Mitja Bezenšek 2023-06-02 23:43:51 +02:00 committed by GitHub
parent a5e653b225
commit 0c9e8d323e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -3,6 +3,7 @@ import {
Editor,
fileToBase64,
TLAsset,
TLAssetId,
TLInstanceId,
TLRecord,
TLStore,
@ -153,7 +154,9 @@ export function parseTldrawJsonFile({
/** @public */
export async function serializeTldrawJson(store: TLStore): Promise<string> {
const recordsToSave: TLRecord[] = []
const records: TLRecord[] = []
const usedAssets = new Set<TLAssetId | null>()
const assets: TLAsset[] = []
for (const record of store.allRecords()) {
switch (record.typeName) {
case 'asset':
@ -171,22 +174,29 @@ export async function serializeTldrawJson(store: TLStore): Promise<string> {
assetSrcToSave = record.props.src
}
recordsToSave.push({
assets.push({
...record,
props: {
...record.props,
src: assetSrcToSave,
},
} as TLAsset)
})
} else {
recordsToSave.push(record)
assets.push(record)
}
break
case 'shape':
if ('assetId' in record.props) {
usedAssets.add(record.props.assetId)
}
records.push(record)
break
default:
recordsToSave.push(record)
records.push(record)
break
}
}
const recordsToSave = records.concat(assets.filter((a) => usedAssets.has(a.id)))
return JSON.stringify({
tldrawFileFormatVersion: LATEST_TLDRAW_FILE_FORMAT_VERSION,