diff options
| author | sameerasw <[email protected]> | 2025-04-29 22:07:14 +0530 | 
|---|---|---|
| committer | sameerasw <[email protected]> | 2025-04-29 22:07:14 +0530 | 
| commit | 76c2fbe1b5c63a9f6ad74a5a726f9a308b1ab9db (patch) | |
| tree | 7f6883682f7f1b95cdf3e0041ec6f13b3c9a6f80 | |
| parent | 3abd67a040c840738684a78d91f654d583550f41 (diff) | |
Fixed theming for existing users
| -rw-r--r-- | background.js | 135 | ||||
| -rw-r--r-- | content-script.js | 85 | ||||
| -rw-r--r-- | manifest.json | 7 | ||||
| -rw-r--r-- | popup/popup.js | 59 | ||||
| -rw-r--r-- | shared/defaults.js | 31 | 
5 files changed, 249 insertions, 68 deletions
diff --git a/background.js b/background.js index e31e8c1..2696887 100644 --- a/background.js +++ b/background.js @@ -1,24 +1,60 @@  let SKIP_FORCE_THEMING_KEY = "skipForceThemingList";  let SKIP_THEMING_KEY = "skipThemingList"; +let BROWSER_STORAGE_KEY = "transparentZenSettings";  let logging = true; // Enable logging for debugging  // Create a cache for pre-processed CSS to speed up repeated visits  const cssCache = new Map();  const activeTabs = new Map(); +// Default settings to use when values are missing +const DEFAULT_SETTINGS = { +  enableStyling: true, // Enable styling globally +  autoUpdate: true, // Auto-update styles +  forceStyling: false, // Force styling on sites without themes +  whitelistMode: false, // Use blacklist mode by default for force styling +  whitelistStyleMode: false, // Use blacklist mode by default for regular styling +  disableTransparency: false, // Don't disable transparency by default +}; +  // Helper function to normalize hostnames by removing www. prefix  function normalizeHostname(hostname) {    return hostname.startsWith("www.") ? hostname.substring(4) : hostname;  } +// Ensure all required settings exist +function ensureDefaultSettings(settings = {}) { +  const result = { ...settings }; + +  // Apply default values for any missing settings +  for (const [key, defaultValue] of Object.entries(DEFAULT_SETTINGS)) { +    if (result[key] === undefined) { +      result[key] = defaultValue; +    } +  } + +  return result; +} +  // Preload styles for faster injection  async function preloadStyles() {    try {      const data = await browser.storage.local.get([        "styles", -      "transparentZenSettings", +      BROWSER_STORAGE_KEY,      ]); -    const settings = data.transparentZenSettings || {}; + +    // Ensure we have all required settings with defaults +    const settings = ensureDefaultSettings(data[BROWSER_STORAGE_KEY] || {}); + +    // Save the validated settings back to storage if any defaults were applied +    if ( +      JSON.stringify(settings) !== JSON.stringify(data[BROWSER_STORAGE_KEY]) +    ) { +      if (logging) +        console.log("Missing settings detected, applying defaults:", settings); +      await browser.storage.local.set({ [BROWSER_STORAGE_KEY]: settings }); +    }      // No point in preloading if styling is disabled      if (settings.enableStyling === false) return; @@ -64,10 +100,10 @@ browser.runtime.onMessage.addListener(async (message, sender) => {        const normalizedHostname = normalizeHostname(message.hostname);        // Get settings to check if styling is enabled -      const settingsData = await browser.storage.local.get( -        "transparentZenSettings" +      const settingsData = await browser.storage.local.get(BROWSER_STORAGE_KEY); +      const settings = ensureDefaultSettings( +        settingsData[BROWSER_STORAGE_KEY] || {}        ); -      const settings = settingsData.transparentZenSettings || {};        if (settings.enableStyling === false) return; @@ -100,6 +136,9 @@ browser.runtime.onMessage.addListener(async (message, sender) => {  // Get appropriate styles for a hostname based on all rules  async function getStylesForHostname(hostname, settings) { +  // Ensure all required settings have defaults before proceeding +  settings = ensureDefaultSettings(settings); +    console.log("DEBUG: Finding styles for hostname:", hostname);    // Check for exact matches first (highest priority) @@ -192,10 +231,12 @@ async function getStylesForHostname(hostname, settings) {  // Prepare styles for a URL that's about to load  async function prepareStylesForUrl(hostname, tabId) {    try { -    const settingsData = await browser.storage.local.get( -      "transparentZenSettings" +    const settingsData = await browser.storage.local.get(BROWSER_STORAGE_KEY); + +    // Ensure all required settings have defaults +    const settings = ensureDefaultSettings( +      settingsData[BROWSER_STORAGE_KEY] || {}      ); -    const settings = settingsData.transparentZenSettings || {};      if (settings.enableStyling === false) return; @@ -228,13 +269,33 @@ async function applyCSSToTab(tab) {        ")"      ); -    const settings = await browser.storage.local.get("transparentZenSettings"); -    const globalSettings = settings.transparentZenSettings || {}; +    const settings = await browser.storage.local.get(BROWSER_STORAGE_KEY); + +    // Ensure defaults for any missing settings +    const globalSettings = ensureDefaultSettings( +      settings[BROWSER_STORAGE_KEY] || {} +    ); + +    // Save back any missing defaults +    if ( +      JSON.stringify(globalSettings) !== +      JSON.stringify(settings[BROWSER_STORAGE_KEY]) +    ) { +      await browser.storage.local.set({ +        [BROWSER_STORAGE_KEY]: globalSettings, +      }); +      if (logging) +        console.log("Applied missing default settings during CSS application"); +    } +      console.log("DEBUG: Global settings:", JSON.stringify(globalSettings));      const skipStyleListData = await browser.storage.local.get(SKIP_THEMING_KEY);      const skipStyleList = skipStyleListData[SKIP_THEMING_KEY] || []; -    const styleMode = globalSettings.whitelistStyleMode ?? true; + +    // Use default from settings if not explicitly set +    const styleMode = +      globalSettings.whitelistStyleMode ?? DEFAULT_SETTINGS.whitelistStyleMode;      if (        globalSettings.enableStyling === false || @@ -368,6 +429,11 @@ async function applyCSSToTab(tab) {        const siteInList = siteList.includes(hostname);        console.log("DEBUG: Site in list:", siteInList); +      // Use default from settings if not explicitly set +      const isWhitelistMode = +        globalSettings.whitelistMode ?? DEFAULT_SETTINGS.whitelistMode; +      console.log("DEBUG: Using whitelist mode:", isWhitelistMode); +        // In whitelist mode: apply only if site is in the list        // In blacklist mode: apply only if site is NOT in the list        const shouldApplyForcedStyling = @@ -414,10 +480,13 @@ async function applyCSS(tabId, hostname, features) {    console.log("DEBUG: Features count:", Object.keys(features).length); -  const settingsData = await browser.storage.local.get( -    "transparentZenSettings" +  const settingsData = await browser.storage.local.get(BROWSER_STORAGE_KEY); + +  // Ensure defaults for any missing settings +  const globalSettings = ensureDefaultSettings( +    settingsData[BROWSER_STORAGE_KEY] || {}    ); -  const globalSettings = settingsData.transparentZenSettings || {}; +    console.log(      "DEBUG: Global settings in applyCSS:",      JSON.stringify(globalSettings) @@ -517,10 +586,8 @@ async function refetchCSS() {      await browser.storage.local.set({ styles });      // Check if we need to initialize default settings -    const settingsData = await browser.storage.local.get( -      "transparentZenSettings" -    ); -    if (!settingsData.transparentZenSettings) { +    const settingsData = await browser.storage.local.get(BROWSER_STORAGE_KEY); +    if (!settingsData[BROWSER_STORAGE_KEY]) {        // Initialize default settings if none exist        const defaultSettings = {          enableStyling: true, @@ -533,7 +600,7 @@ async function refetchCSS() {        // Save default settings        await browser.storage.local.set({ -        transparentZenSettings: defaultSettings, +        [BROWSER_STORAGE_KEY]: defaultSettings,        });        console.info("Initialized default settings during first fetch");      } else { @@ -552,12 +619,38 @@ async function refetchCSS() {  // Create a directory to store CSS files  async function initializeExtension() { +  // Check and initialize default settings +  const data = await browser.storage.local.get(BROWSER_STORAGE_KEY); +  const currentSettings = data[BROWSER_STORAGE_KEY] || {}; +  const validatedSettings = ensureDefaultSettings(currentSettings); + +  // If we had to apply any defaults, save them +  if (JSON.stringify(validatedSettings) !== JSON.stringify(currentSettings)) { +    console.info( +      "Initializing missing settings with defaults:", +      validatedSettings +    ); +    await browser.storage.local.set({ +      [BROWSER_STORAGE_KEY]: validatedSettings, +    }); +  } + +  // Ensure empty lists exist +  const skipForceData = await browser.storage.local.get(SKIP_FORCE_THEMING_KEY); +  if (!skipForceData[SKIP_FORCE_THEMING_KEY]) { +    await browser.storage.local.set({ [SKIP_FORCE_THEMING_KEY]: [] }); +  } + +  const skipThemingData = await browser.storage.local.get(SKIP_THEMING_KEY); +  if (!skipThemingData[SKIP_THEMING_KEY]) { +    await browser.storage.local.set({ [SKIP_THEMING_KEY]: [] }); +  } +    // Preload styles immediately    await preloadStyles();    // Initialize auto-update based on stored settings -  const settings = await browser.storage.local.get("transparentZenSettings"); -  if (settings.transparentZenSettings?.autoUpdate) { +  if (validatedSettings.autoUpdate) {      startAutoUpdate();    }  } diff --git a/content-script.js b/content-script.js index 4f02174..4e99e29 100644 --- a/content-script.js +++ b/content-script.js @@ -1,42 +1,51 @@ -(function() { -    const stylesheetId = 'zeninternet-custom-styles'; -     -    // Create or get our stylesheet element -    function getStylesheet() { -        let stylesheet = document.getElementById(stylesheetId); -        if (!stylesheet) { -            stylesheet = document.createElement('style'); -            stylesheet.id = stylesheetId; -            stylesheet.type = 'text/css'; -            document.head.appendChild(stylesheet); -        } -        return stylesheet; +(function () { +  const stylesheetId = "zeninternet-custom-styles"; + +  // Create or get our stylesheet element +  function getStylesheet() { +    let stylesheet = document.getElementById(stylesheetId); +    if (!stylesheet) { +      stylesheet = document.createElement("style"); +      stylesheet.id = stylesheetId; +      stylesheet.type = "text/css"; +      document.head.appendChild(stylesheet);      } -     -    // Update our stylesheet content -    function updateStyles(css) { -        const stylesheet = getStylesheet(); -        stylesheet.textContent = css || ''; -        console.log('ZenInternet: Styles were ' + (css ? 'updated' : 'removed')); -    } -     -    // Announce content script is ready and provide current hostname -    function announceReady() { -        browser.runtime.sendMessage({ -            action: 'contentScriptReady', -            hostname: window.location.hostname, +    return stylesheet; +  } + +  // Update our stylesheet content +  function updateStyles(css) { +    const stylesheet = getStylesheet(); +    stylesheet.textContent = css || ""; +    console.log("ZenInternet: Styles were " + (css ? "updated" : "removed")); +  } + +  // Announce content script is ready and provide current hostname +  function announceReady() { +    try { +      browser.runtime +        .sendMessage({ +          action: "contentScriptReady", +          hostname: window.location.hostname, +        }) +        .catch((err) => { +          // Silent fail - background might not be ready yet +          console.log("ZenInternet: Could not announce ready state");          }); +    } catch (e) { +      // Fail silently +    } +  } + +  // Listen for messages from background script +  browser.runtime.onMessage.addListener((message) => { +    if (message.action === "applyStyles") { +      updateStyles(message.css); +      return Promise.resolve({ success: true });      } -     -    // Listen for messages from background script -    browser.runtime.onMessage.addListener((message) => { -        if (message.action === 'applyStyles') { -            updateStyles(message.css); -            return Promise.resolve({ success: true }); -        } -        return false; -    }); -     -    // Announce content script is ready on load -    announceReady(); +    return false; +  }); + +  // Announce content script is ready on load +  announceReady();  })(); diff --git a/manifest.json b/manifest.json index f5ef723..aeb6de8 100644 --- a/manifest.json +++ b/manifest.json @@ -1,8 +1,8 @@  {    "manifest_version": 2,    "name": "Zen Internet", -  "version": "1.9.1", -  "description": "Inject custom css from my repository in real time", +  "version": "1.9.2", +  "description": "Make the internet feel native and elegant. Zen Internet is a browser extension that enhances your browsing experience by providing a clean and minimalistic interface with transparency and a focus on content. Customize the features in the addon popup.",    "browser_specific_settings": {      "gecko": {        "id": "{91aa3897-2634-4a8a-9092-279db23a7689}" @@ -34,6 +34,7 @@      "data-viewer/data-viewer.html",      "data-viewer/data-viewer.js",      "data-viewer/data-viewer.css", -    "styling/*" +    "styling/*", +    "shared/*"    ]  } diff --git a/popup/popup.js b/popup/popup.js index d87debb..e9882c2 100644 --- a/popup/popup.js +++ b/popup/popup.js @@ -2,6 +2,30 @@ let logging = false;  let SKIP_FORCE_THEMING_KEY = "skipForceThemingList";  let SKIP_THEMING_KEY = "skipThemingList"; +// Default settings to use when values are missing +const DEFAULT_SETTINGS = { +  enableStyling: true, // Enable styling globally +  autoUpdate: true, // Auto-update styles +  forceStyling: false, // Force styling on sites without themes +  whitelistMode: false, // Use blacklist mode by default for force styling +  whitelistStyleMode: false, // Use blacklist mode by default for regular styling +  disableTransparency: false, // Don't disable transparency by default +}; + +// Helper function to ensure all required settings exist +function ensureDefaultSettings(settings = {}) { +  const result = { ...settings }; + +  // Apply default values for any missing settings +  for (const [key, defaultValue] of Object.entries(DEFAULT_SETTINGS)) { +    if (result[key] === undefined) { +      result[key] = defaultValue; +    } +  } + +  return result; +} +  // Helper function to normalize hostnames by removing www. prefix  function normalizeHostname(hostname) {    return hostname.startsWith("www.") ? hostname.substring(4) : hostname; @@ -196,12 +220,22 @@ new (class ExtensionPopup {      const globalData = await browser.storage.local.get(        this.BROWSER_STORAGE_KEY      ); -    this.globalSettings = globalData[this.BROWSER_STORAGE_KEY] || { -      enableStyling: true, -      autoUpdate: false, -      lastFetchedTime: null, -      forceStyling: false, -    }; + +    // Apply defaults for any missing settings +    this.globalSettings = ensureDefaultSettings( +      globalData[this.BROWSER_STORAGE_KEY] || {} +    ); + +    // Save back any applied defaults +    if ( +      JSON.stringify(this.globalSettings) !== +      JSON.stringify(globalData[this.BROWSER_STORAGE_KEY]) +    ) { +      await browser.storage.local.set({ +        [this.BROWSER_STORAGE_KEY]: this.globalSettings, +      }); +      if (logging) console.log("Applied missing default settings"); +    }      // Load site-specific settings if on a specific site      if (this.currentSiteHostname) { @@ -287,11 +321,23 @@ new (class ExtensionPopup {    async loadSkipForceThemingList() {      const data = await browser.storage.local.get(SKIP_FORCE_THEMING_KEY);      this.skipForceThemingList = data[SKIP_FORCE_THEMING_KEY] || []; + +    // Initialize with empty array if missing +    if (!data[SKIP_FORCE_THEMING_KEY]) { +      await browser.storage.local.set({ [SKIP_FORCE_THEMING_KEY]: [] }); +      if (logging) console.log("Initialized empty skip force theming list"); +    }    }    async loadSkipThemingList() {      const data = await browser.storage.local.get(SKIP_THEMING_KEY);      this.skipThemingList = data[SKIP_THEMING_KEY] || []; + +    // Initialize with empty array if missing +    if (!data[SKIP_THEMING_KEY]) { +      await browser.storage.local.set({ [SKIP_THEMING_KEY]: [] }); +      if (logging) console.log("Initialized empty skip theming list"); +    }    }    saveSkipForceThemingList() { @@ -861,6 +907,7 @@ new (class ExtensionPopup {    shouldApplyCSS(hostname) {      if (logging) console.log("shouldApplyCSS called with", hostname); +    // Use default if not explicitly set      return this.globalSettings.enableStyling !== false;    } diff --git a/shared/defaults.js b/shared/defaults.js new file mode 100644 index 0000000..0c3d027 --- /dev/null +++ b/shared/defaults.js @@ -0,0 +1,31 @@ +/** + * Default settings for Zen Internet extension + * These defaults are used when settings are missing or undefined + */ + +export const DEFAULT_SETTINGS = { +  enableStyling: true, // Enable styling globally +  autoUpdate: true, // Auto-update styles +  forceStyling: false, // Force styling on sites without themes +  whitelistMode: false, // Use blacklist mode by default for force styling +  whitelistStyleMode: false, // Use blacklist mode by default for regular styling +  disableTransparency: false, // Don't disable transparency by default +}; + +/** + * Ensures all required settings are present with default values + * @param {Object} settings - Current settings object + * @returns {Object} - Settings object with defaults applied where needed + */ +export function ensureDefaultSettings(settings = {}) { +  const result = { ...settings }; + +  // Apply default values for any missing settings +  for (const [key, defaultValue] of Object.entries(DEFAULT_SETTINGS)) { +    if (result[key] === undefined) { +      result[key] = defaultValue; +    } +  } + +  return result; +}  | 
