simple-dark-mode-toggle
Version:
A simple dark mode toggle
364 lines • 16.6 kB
JavaScript
"use strict";
/* simple-dark-mode-toggle
* Copyright (c) 2024 Steve Kieffer
* SPDX-License-Identifier: MIT
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtensionDarkModeManager = exports.DarkModeManager = void 0;
exports.setupDarkMode = setupDarkMode;
exports.setupDarkModeForExt = setupDarkModeForExt;
/* This is a convenience function to set up and activate dark mode.
* It is for use in page scripts. For content scripts, see `setupDarkModeForExt()`.
*
* toggleElement: The DOM element you want to be the dark mode toggle button.
* Generally this should be some empty div or span. The manager will only
* write a sun or moon character into it, to show the current mode.
* You are encouraged to set up your own CSS to set the element's font size,
* padding, margins, etc. This is deliberately left open, for flexibility.
* options: See above.
*/
function setupDarkMode(toggleElement, options) {
var mgr = new DarkModeManager(toggleElement, options);
mgr.restore();
mgr.activate();
return mgr;
}
/* This is a convenience function to set up and activate dark mode.
* It is for use in content scripts. For page scripts, see `setupDarkMode()`.
*
* toggleElement: The DOM element you want to be the dark mode toggle button.
* Generally this should be some empty div or span. The manager will only
* write a sun or moon character into it, to show the current mode.
* You are encouraged to set up your own CSS to set the element's font size,
* padding, margins, etc. This is deliberately left open, for flexibility.
* options: See above.
*/
function setupDarkModeForExt(toggleElement, options) {
return __awaiter(this, void 0, void 0, function () {
var mgr;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options = options || {};
options.storage = 'ext-' + (options.storage || 'none');
mgr = new ExtensionDarkModeManager(toggleElement, options);
return [4 /*yield*/, mgr.restore()];
case 1:
_a.sent();
mgr.activate();
return [2 /*return*/, mgr];
}
});
});
}
var storageTypes = {
local: 'local',
session: 'session',
extLocal: 'ext-local',
extSession: 'ext-session',
};
/* Wrapper class providing an abstraction layer over the various storage options provided
* by the web browser.
*
* Specifically, an instance of this class can represent any of the following storages:
* - window.localStorage
* - window.sessionStorage
* - (browser|chrome).storage.local
* - (browser|chrome).storage.session
*/
var AbstractStorage = /** @class */ (function () {
/* storageType must be one of: 'local', 'session', 'ext-local', 'ext-session'.
* The first two use the local and session storages of the window object; the last two
* use those of the extension (when working within a browser extension).
*/
function AbstractStorage(storageType) {
this.storageType = storageType;
this.inChrome = typeof chrome !== 'undefined';
}
AbstractStorage.prototype.getItem = function (key) {
switch (this.storageType) {
case storageTypes.local:
return window.localStorage.getItem(key);
case storageTypes.session:
return window.sessionStorage.getItem(key);
default:
return null;
}
};
AbstractStorage.prototype.getItemAsync = function (key) {
return __awaiter(this, void 0, void 0, function () {
var results, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.storageType;
switch (_a) {
case storageTypes.extLocal: return [3 /*break*/, 1];
case storageTypes.extSession: return [3 /*break*/, 3];
}
return [3 /*break*/, 5];
case 1: return [4 /*yield*/, (this.inChrome ?
new Promise(function (resolve) { return chrome.storage.local.get(key, resolve); }) :
browser.storage.local.get(key))];
case 2:
results = _b.sent();
return [2 /*return*/, results[key]];
case 3: return [4 /*yield*/, (this.inChrome ?
new Promise(function (resolve) { return chrome.storage.session.get(key, resolve); }) :
browser.storage.session.get(key))];
case 4:
results = _b.sent();
return [2 /*return*/, results[key]];
case 5: return [2 /*return*/, null];
}
});
});
};
AbstractStorage.prototype.setItem = function (key, value) {
switch (this.storageType) {
case storageTypes.local:
return window.localStorage.setItem(key, value);
case storageTypes.session:
return window.sessionStorage.setItem(key, value);
default:
return null;
}
};
AbstractStorage.prototype.setItemAsync = function (key, value) {
return __awaiter(this, void 0, void 0, function () {
var keys;
var _a;
return __generator(this, function (_b) {
keys = (_a = {}, _a[key] = value, _a);
switch (this.storageType) {
case storageTypes.extLocal:
return [2 /*return*/, this.inChrome ?
new Promise(function (resolve) { return chrome.storage.local.set(keys, function () {
resolve(null);
}); }) :
browser.storage.local.set(keys)];
case storageTypes.extSession:
return [2 /*return*/, this.inChrome ?
new Promise(function (resolve) { return chrome.storage.session.set(keys, function () {
resolve(null);
}); }) :
browser.storage.session.set(keys)];
default:
return [2 /*return*/, null];
}
return [2 /*return*/];
});
});
};
return AbstractStorage;
}());
/* Abstract base class for the dark mode managers.
*/
var BaseDarkModeManager = /** @class */ (function () {
function BaseDarkModeManager(toggleElement, options) {
var _a = options || {}, _b = _a.classElement, classElement = _b === void 0 ? document.body : _b, _c = _a.darkClassName, darkClassName = _c === void 0 ? 'dark-mode' : _c, _d = _a.title, title = _d === void 0 ? 'Light/Dark Mode' : _d, _e = _a.storage, storage = _e === void 0 ? 'local' : _e, _f = _a.storageName, storageName = _f === void 0 ? 'dark-mode' : _f, _g = _a.darkByDefault, darkByDefault = _g === void 0 ? true : _g;
this.toggleElement = toggleElement;
this.classElement = classElement;
this.darkClassName = darkClassName;
this.title = title;
this.storage = new AbstractStorage(storage);
this.storageName = storageName;
this.darkByDefault = darkByDefault;
}
BaseDarkModeManager.prototype._activate = function () {
this.toggleElement.style.cursor = 'pointer';
this.toggleElement.style.userSelect = 'none';
this.toggleElement.title = this.title;
};
BaseDarkModeManager.prototype._toggle = function () {
var dark = this.darkByDefault;
var currentValue = this.toggleElement.dataset.dark;
if (currentValue) {
dark = !+currentValue;
}
return dark;
};
BaseDarkModeManager.prototype._setDarkMode = function (dark) {
if (dark) {
this.classElement.classList.add(this.darkClassName);
this.toggleElement.dataset.dark = '1';
this.toggleElement.innerHTML = '☾'; // moon
}
else {
this.classElement.classList.remove(this.darkClassName);
this.toggleElement.dataset.dark = '0';
this.toggleElement.innerHTML = '☼'; // sun
}
};
return BaseDarkModeManager;
}());
/* Dark mode manager for use in ordinary page scripts (*not* in browser extensions).
*
* Uses the synchronous storage classes available in the window.
*/
var DarkModeManager = /** @class */ (function (_super) {
__extends(DarkModeManager, _super);
function DarkModeManager() {
return _super !== null && _super.apply(this, arguments) || this;
}
DarkModeManager.prototype.activate = function () {
var _this = this;
this._activate();
this.toggleElement.onclick = function (e) {
_this.toggle();
};
};
/* Restore the previous setting from localStorage (or default).
*/
DarkModeManager.prototype.restore = function () {
var storedValue = this.storage.getItem(this.storageName);
var dark = this.darkByDefault;
if (storedValue) {
dark = !!+storedValue;
}
this.setDarkMode(dark);
};
/* Switch to the opposite setting currently expressed by the toggle element.
*/
DarkModeManager.prototype.toggle = function () {
var dark = this._toggle();
this.setDarkMode(dark);
};
DarkModeManager.prototype.setDarkMode = function (dark) {
this._setDarkMode(dark);
this.storage.setItem(this.storageName, this.toggleElement.dataset.dark);
};
return DarkModeManager;
}(BaseDarkModeManager));
exports.DarkModeManager = DarkModeManager;
/* Dark mode manager for use in browser extension content scripts.
*
* Uses the asynchronous storage classes available to browser extensions.
*/
var ExtensionDarkModeManager = /** @class */ (function (_super) {
__extends(ExtensionDarkModeManager, _super);
function ExtensionDarkModeManager() {
return _super !== null && _super.apply(this, arguments) || this;
}
ExtensionDarkModeManager.prototype.activate = function () {
var _this = this;
this._activate();
this.toggleElement.onclick = function (e) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.toggle()];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); };
};
/* Restore the previous setting from localStorage (or default).
*/
ExtensionDarkModeManager.prototype.restore = function () {
return __awaiter(this, void 0, void 0, function () {
var storedValue, dark;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.storage.getItemAsync(this.storageName)];
case 1:
storedValue = _a.sent();
dark = this.darkByDefault;
if (storedValue) {
dark = !!+storedValue;
}
return [4 /*yield*/, this.setDarkMode(dark)];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
/* Switch to the opposite setting currently expressed by the toggle element.
*/
ExtensionDarkModeManager.prototype.toggle = function () {
return __awaiter(this, void 0, void 0, function () {
var dark;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
dark = this._toggle();
return [4 /*yield*/, this.setDarkMode(dark)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
ExtensionDarkModeManager.prototype.setDarkMode = function (dark) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this._setDarkMode(dark);
return [4 /*yield*/, this.storage.setItemAsync(this.storageName, this.toggleElement.dataset.dark)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
return ExtensionDarkModeManager;
}(BaseDarkModeManager));
exports.ExtensionDarkModeManager = ExtensionDarkModeManager;
//# sourceMappingURL=main.js.map