Skip to content

Commit 9b07c16

Browse files
committed
refactor: extract cleanFlyoutInfo method in workspace-backpack
Extract the key-stripping logic from blockToJsonString into a reusable cleanFlyoutInfo method. Also fix a potential null dereference when Blockly.serialization.blocks.save returns null. Co-Authored-By: Claude Opus 4.6 (1M context) noreply@anthropic.com
1 parent 1565867 commit 9b07c16

1 file changed

Lines changed: 34 additions & 23 deletions

File tree

plugins/workspace-backpack/src/backpack.ts

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -467,32 +467,47 @@ export class Backpack
467467
* @returns The JSON object as a string.
468468
*/
469469
private blockToJsonString(block: Blockly.Block): string {
470-
const json = Blockly.serialization.blocks.save(block);
470+
const json = Blockly.serialization.blocks.save(
471+
block,
472+
) as Blockly.utils.toolbox.FlyoutItemInfo | null;
471473

472-
// Add a 'kind' key so the flyout can recognize it as a block.
473-
(json as Blockly.utils.toolbox.FlyoutItemInfo).kind = 'BLOCK';
474+
if (json) {
475+
// Add a 'kind' key so the flyout can recognize it as a block.
476+
json.kind = 'BLOCK';
477+
this.cleanFlyoutInfo(json);
478+
}
479+
480+
return JSON.stringify(json);
481+
}
474482

483+
/**
484+
* Removes unnecessary keys from flyout info in place.
485+
*
486+
* @param dirtyInfo The flyout info object to clean.
487+
*/
488+
private cleanFlyoutInfo(dirtyInfo: Blockly.utils.toolbox.FlyoutItemInfo) {
475489
// The keys to remove.
476-
const keys = ['id', 'height', 'width', 'pinned', 'enabled'];
477-
478-
// Traverse the JSON recursively.
479-
const traverseJson = function (json: StateWithIndex, keys: string[]) {
480-
for (const key in json) {
481-
if (key) {
482-
if (keys.indexOf(key) !== -1) {
483-
delete json[key];
484-
}
485-
if (json[key] && typeof json[key] === 'object') {
486-
traverseJson(json[key] as StateWithIndex, keys);
487-
}
490+
const removeKeys = ['id', 'height', 'width', 'pinned', 'enabled'];
491+
492+
// Traverse the object recursively.
493+
const traverseClean = function (
494+
obj: {[key: string]: unknown},
495+
keys: string[],
496+
) {
497+
for (const key of Object.keys(obj)) {
498+
if (keys.indexOf(key) !== -1) {
499+
delete obj[key];
500+
continue;
501+
}
502+
503+
const item = obj[key];
504+
if (item !== null && typeof item === 'object') {
505+
traverseClean(item as {[key: string]: unknown}, keys);
488506
}
489507
}
490508
};
491509

492-
if (json) {
493-
traverseJson(json as StateWithIndex, keys);
494-
}
495-
return JSON.stringify(json);
510+
traverseClean(dirtyInfo as unknown as {[key: string]: unknown}, removeKeys);
496511
}
497512

498513
/**
@@ -1033,7 +1048,3 @@ class BackpackSerializer {
10331048
backpack?.empty();
10341049
}
10351050
}
1036-
1037-
interface StateWithIndex extends Blockly.serialization.blocks.State {
1038-
[key: string]: unknown;
1039-
}

0 commit comments

Comments
 (0)