Skip to content

Commit b919885

Browse files
committed
move local storage methods to misc.ts
1 parent da7a85f commit b919885

4 files changed

Lines changed: 35 additions & 38 deletions

File tree

src/local_storage.ts

Lines changed: 0 additions & 33 deletions
This file was deleted.

src/main.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,7 @@ import {
1111
} from "./dictionary/dictionary.ts";
1212
import { parseDictionary } from "./dictionary/parser.ts";
1313
import { Dictionary } from "./dictionary/type.ts";
14-
import {
15-
assertQuotaExceededError,
16-
checkLocalStorage,
17-
} from "./local_storage.ts";
14+
import { assertQuotaExceededError, checkLocalStorage } from "./misc/misc.ts";
1815
import { hasXAlaX } from "./parser/lexer.ts";
1916
import { Position, PositionedError } from "./parser/parser_lib.ts";
2017
import { settings } from "./settings.ts";

src/misc/misc.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,36 @@ export function lazy<T>(fn: () => T): () => T {
4545
return value!;
4646
};
4747
}
48+
export const checkLocalStorage = lazy((): boolean => {
49+
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
50+
try {
51+
const x = "__storage_test__";
52+
localStorage.setItem(x, x);
53+
localStorage.removeItem(x);
54+
return true;
55+
} catch (e) {
56+
return e instanceof DOMException &&
57+
e.name === "QuotaExceededError" &&
58+
// acknowledge QuotaExceededError only if there's something already stored
59+
localStorage &&
60+
localStorage.length !== 0;
61+
}
62+
});
63+
64+
export function setIgnoreError(key: string, value: string): void {
65+
if (checkLocalStorage()) {
66+
try {
67+
localStorage.setItem(key, value);
68+
} catch (error) {
69+
assertQuotaExceededError(error);
70+
}
71+
}
72+
}
73+
74+
export function assertQuotaExceededError(error: unknown): void {
75+
if (
76+
!(error instanceof DOMException) || error.name !== "QuotaExceededError"
77+
) {
78+
throw error;
79+
}
80+
}

src/settings_frontend.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// this code is browser only
22

33
import { toKebabCase } from "@std/text/to-kebab-case";
4-
import { checkLocalStorage, setIgnoreError } from "./local_storage.ts";
4+
import { checkLocalStorage, setIgnoreError } from "./misc/misc.ts";
55
import { defaultSettings, Redundancy, Settings, settings } from "./settings.ts";
66

77
type Updater<T> = Readonly<{

0 commit comments

Comments
 (0)