Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/local-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ Or delete everything stored in the namespace:
delete storage :: #0FBD8C
```

These next blocks are used to inspect and iterate through all namespace items.

```scratch
(number of keys in storage :: #0FBD8C)
```

This block reports the total number of stored variables.

```scratch
(key # [1] in storage :: #0FBD8C)
```

This block reports the name of a key at a specific index position.

## Performance

The local storage extension is inevitably slower than regular variables.
Expand Down
44 changes: 44 additions & 0 deletions extensions/local-storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
}

const getNamespace = () =>
Scratch.vm.runtime.extensionStorage["localstorage"]?.namespace;

Check warning on line 16 in extensions/local-storage.js

View workflow job for this annotation

GitHub Actions / type-warnings

Type warning - may indicate a bug - ignore if no bug

Property 'namespace' does not exist on type 'JSONSerializable'. Property 'namespace' does not exist on type 'string'.

/**
* @param {string} newNamespace
Expand Down Expand Up @@ -204,6 +204,25 @@
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("delete storage"),
},
"---",
{
opcode: "keyCount",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("number of keys in storage"),
disableMonitor: true,
},
{
opcode: "itemOfKey",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("key # [NUM] in storage"),
arguments: {
NUM: {
type: Scratch.ArgumentType.NUMBER,
defaultValue: 1,
},
},
},
"---",
{
opcode: "whenChanged",
blockType: Scratch.BlockType.EVENT,
Expand Down Expand Up @@ -258,13 +277,38 @@
saveToLocalStorage();
}

getAll() {
if (!validNamespace()) {
return "";
}

return JSON.stringify(Object.keys(namespaceValues));
}

removeAll() {
if (!validNamespace()) {
return "";
}
namespaceValues = Object.create(null);
saveToLocalStorage();
}

keyCount() {
if (!validNamespace()) {
return 0;
}

return Object.keys(namespaceValues).length;
}

itemOfKey(args) {
if (!validNamespace()) {
return "";
}

const keys = Object.keys(namespaceValues);
return keys[Scratch.Cast.toNumber(args.NUM) - 1] ?? "";
}
}

Scratch.extensions.register(new LocalStorage());
Expand Down