UNPKG

2.94 kBJavaScriptView Raw
1/**
2 * @licstart The following is the entire license notice for the
3 * JavaScript code in this page
4 *
5 * Copyright 2022 Mozilla Foundation
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * @licend The above is the entire license notice for the
20 * JavaScript code in this page
21 */
22"use strict";
23
24Object.defineProperty(exports, "__esModule", {
25 value: true
26});
27exports.ViewHistory = void 0;
28const DEFAULT_VIEW_HISTORY_CACHE_SIZE = 20;
29
30class ViewHistory {
31 constructor(fingerprint, cacheSize = DEFAULT_VIEW_HISTORY_CACHE_SIZE) {
32 this.fingerprint = fingerprint;
33 this.cacheSize = cacheSize;
34 this._initializedPromise = this._readFromStorage().then(databaseStr => {
35 const database = JSON.parse(databaseStr || "{}");
36 let index = -1;
37
38 if (!Array.isArray(database.files)) {
39 database.files = [];
40 } else {
41 while (database.files.length >= this.cacheSize) {
42 database.files.shift();
43 }
44
45 for (let i = 0, ii = database.files.length; i < ii; i++) {
46 const branch = database.files[i];
47
48 if (branch.fingerprint === this.fingerprint) {
49 index = i;
50 break;
51 }
52 }
53 }
54
55 if (index === -1) {
56 index = database.files.push({
57 fingerprint: this.fingerprint
58 }) - 1;
59 }
60
61 this.file = database.files[index];
62 this.database = database;
63 });
64 }
65
66 async _writeToStorage() {
67 const databaseStr = JSON.stringify(this.database);
68 localStorage.setItem("pdfjs.history", databaseStr);
69 }
70
71 async _readFromStorage() {
72 return localStorage.getItem("pdfjs.history");
73 }
74
75 async set(name, val) {
76 await this._initializedPromise;
77 this.file[name] = val;
78 return this._writeToStorage();
79 }
80
81 async setMultiple(properties) {
82 await this._initializedPromise;
83
84 for (const name in properties) {
85 this.file[name] = properties[name];
86 }
87
88 return this._writeToStorage();
89 }
90
91 async get(name, defaultValue) {
92 await this._initializedPromise;
93 const val = this.file[name];
94 return val !== undefined ? val : defaultValue;
95 }
96
97 async getMultiple(properties) {
98 await this._initializedPromise;
99 const values = Object.create(null);
100
101 for (const name in properties) {
102 const val = this.file[name];
103 values[name] = val !== undefined ? val : properties[name];
104 }
105
106 return values;
107 }
108
109}
110
111exports.ViewHistory = ViewHistory;
\No newline at end of file