From f4ffbfdff06b8a6bc09735adabb1c95db3b15ec1 Mon Sep 17 00:00:00 2001 From: Trang Doan Date: Wed, 16 Apr 2025 17:05:22 -0400 Subject: [PATCH 1/5] cur progress --- apps/roam/src/components/Export.tsx | 11 +- apps/roam/src/components/ExportGithub.tsx | 165 +++++++++++++----- .../settings/DiscourseRelationConfigPanel.tsx | 10 +- apps/roam/src/index.ts | 4 + apps/roam/src/utils/migrateSettings.ts | 38 ++++ apps/roam/src/utils/settings.ts | 96 ++++++++++ 6 files changed, 269 insertions(+), 55 deletions(-) create mode 100644 apps/roam/src/utils/migrateSettings.ts create mode 100644 apps/roam/src/utils/settings.ts diff --git a/apps/roam/src/components/Export.tsx b/apps/roam/src/components/Export.tsx index 92ba297cf..c34c46652 100644 --- a/apps/roam/src/components/Export.tsx +++ b/apps/roam/src/components/Export.tsx @@ -51,6 +51,7 @@ import createPage from "roamjs-components/writes/createPage"; import { createInitialTldrawProps } from "~/utils/createInitialTldrawProps"; import { isCanvasPage as checkIfCanvasPage } from "~/utils/isCanvasPage"; import sendErrorEmail from "~/utils/sendErrorEmail"; +import { getSetting, setSetting } from "~/utils/settings"; const ExportProgress = ({ id }: { id: string }) => { const [progress, setProgress] = useState(0); @@ -115,8 +116,8 @@ const ExportDialog: ExportDialogComponent = ({ isExportDiscourseGraph = false, initialPanel, }) => { - const [selectedRepo, setSelectedRepo] = useState( - localStorageGet("selected-repo"), + const [selectedRepo, setSelectedRepo] = useState( + getSetting("selected-repo", ""), ); const exportId = useMemo(() => nanoid(), []); useEffect(() => { @@ -169,8 +170,10 @@ const ExportDialog: ExportDialogComponent = ({ discourseGraphEnabled as boolean, ); const [gitHubAccessToken, setGitHubAccessToken] = useState( - localStorageGet("oauth-github"), + getSetting("oauth-github", null), ); + + console.log("gitHubAccessToken", gitHubAccessToken); const [canSendToGitHub, setCanSendToGitHub] = useState(false); const writeFileToRepo = async ({ @@ -199,7 +202,7 @@ const ExportDialog: ExportDialogComponent = ({ if (response.status === 401) { setGitHubAccessToken(null); setError("Authentication failed. Please log in again."); - localStorageSet("oauth-github", ""); + setSetting("oauth-github", ""); return { status: 401 }; } return { status: response.status }; diff --git a/apps/roam/src/components/ExportGithub.tsx b/apps/roam/src/components/ExportGithub.tsx index 36bfedcd0..89c50957f 100644 --- a/apps/roam/src/components/ExportGithub.tsx +++ b/apps/roam/src/components/ExportGithub.tsx @@ -11,8 +11,7 @@ import MenuItemSelect from "roamjs-components/components/MenuItemSelect"; import apiGet from "roamjs-components/util/apiGet"; import apiPost from "roamjs-components/util/apiPost"; import { getNodeEnv } from "roamjs-components/util/env"; -import localStorageGet from "roamjs-components/util/localStorageGet"; -import localStorageSet from "roamjs-components/util/localStorageSet"; +import { getSetting, setSetting } from "~/utils/settings"; type UserReposResponse = { data: [ @@ -57,15 +56,20 @@ export const ExportGithub = ({ const showGitHubLogin = isGitHubAppInstalled && !gitHubAccessToken; const repoSelectEnabled = isGitHubAppInstalled && gitHubAccessToken; - const isDev = useMemo(() => getNodeEnv() === "development", []); - + // const isDev = useMemo(() => getNodeEnv() === "development", []); + const isDev = false; const setRepo = (repo: string) => { setSelectedRepo(repo); - localStorageSet("selected-repo", repo); + setSetting("selected-repo", repo); }; const handleReceivedAccessToken = (token: string) => { - localStorageSet("oauth-github", token); + console.log("Received GitHub token:", !!token); + + // Store in both localStorage and extension settings for maximum compatibility + localStorage.setItem("oauth-github", token); + setSetting("oauth-github", token); + setGitHubAccessToken(token); setClickedInstall(false); authWindow.current?.close(); @@ -73,25 +77,55 @@ export const ExportGithub = ({ const fetchAndSetInstallation = useCallback(async () => { try { + // Try to get token directly from both sources + const tokenFromSettings = getSetting("oauth-github", ""); + const tokenFromLocalStorage = localStorage.getItem("oauth-github"); + const token = tokenFromSettings || tokenFromLocalStorage || ""; + + console.log( + "Using GitHub token from:", + tokenFromSettings + ? "extension settings" + : tokenFromLocalStorage + ? "localStorage" + : "nowhere", + ); + + if (!token) { + console.error("No GitHub token found in any storage location"); + return false; + } + const res = await apiGet<{ installations: { app_id: number }[] }>({ domain: "https://api.github.com", path: "user/installations", headers: { - Authorization: `token ${localStorageGet("oauth-github")}`, + Authorization: `token ${token}`, }, }); + const installations = res.installations; const APP_ID = isDev ? 882491 : 312167; // TODO - pull from process.env.GITHUB_APP_ID const isAppInstalled = installations.some( (installation) => installation.app_id === APP_ID, ); + + console.log( + "GitHub app installations:", + installations.length, + "App ID:", + APP_ID, + ); setIsGitHubAppInstalled(isAppInstalled); return isAppInstalled; } catch (error) { const e = error as Error; + console.error("GitHub installation check error:", e.message); + if (e.message === "Bad credentials") { setGitHubAccessToken(null); - localStorageSet("oauth-github", ""); + setSetting("oauth-github", ""); + localStorage.removeItem("oauth-github"); } return false; } @@ -99,14 +133,29 @@ export const ExportGithub = ({ // listen for messages from the auth window useEffect(() => { - const otp = nanoid().replace(/_/g, "-"); - const key = nanoid().replace(/_/g, "-"); - const state = `github_${otp}_${key}`; - setState(state); + // Create a stable state value that persists between renders + if (!state) { + const otp = nanoid().replace(/_/g, "-"); + const key = nanoid().replace(/_/g, "-"); + const newState = `github_${otp}_${key}`; + console.log("Setting GitHub OAuth state:", newState); + setState(newState); + // Store state in localStorage to preserve it across page refreshes + localStorage.setItem("github-oauth-state", newState); + } + const handleGitHubAuthMessage = (event: MessageEvent) => { const targetOrigin = isDev ? "https://samepage.ngrok.io" : "https://samepage.network"; + console.log( + "Received auth message:", + !!event.data, + "from:", + event.origin, + "expected:", + targetOrigin, + ); if (event.data && event.origin === targetOrigin) { handleReceivedAccessToken(event.data); } @@ -121,7 +170,7 @@ export const ExportGithub = ({ window.removeEventListener("message", handleGitHubAuthMessage); } }; - }, [isVisible]); + }, [isVisible, state]); // check for installation useEffect(() => { @@ -156,6 +205,62 @@ export const ExportGithub = ({ } }, [gitHubAccessToken, isGitHubAppInstalled, selectedRepo]); + const handleAuthButtonClick = async () => { + // Get the stored state or create a new one + const currentState = + state || localStorage.getItem("github-oauth-state") || ""; + console.log("Using OAuth state:", currentState); + + const params = isDev + ? `client_id=Iv1.4bf062a6c6636672&state=${currentState}` + : `client_id=Iv1.e7e282a385b7b2da&state=${currentState}`; + + authWindow.current = window.open( + `https://github.com/login/oauth/authorize?${params}`, + "_blank", + `width=${WINDOW_WIDTH}, height=${WINDOW_HEIGHT}, top=${WINDOW_TOP}, left=${WINDOW_LEFT}`, + ); + + let attemptCount = 0; + const check = () => { + if (attemptCount < 30) { + const apiDomain = isDev + ? "https://api.samepage.ngrok.io" + : "https://api.samepage.network"; + + console.log( + `Attempt ${attemptCount + 1}/30: Checking for token at ${apiDomain}/access-token`, + ); + + apiPost({ + path: "access-token", + domain: apiDomain, + data: { state: currentState }, + }) + .then((r) => { + console.log( + "Token API response:", + r.accessToken ? "has token" : "no token", + ); + if (r.accessToken) { + handleReceivedAccessToken(r.accessToken); + } else { + attemptCount++; + setTimeout(check, 1000); + } + }) + .catch((err) => { + console.error("Token check error:", err); + attemptCount++; + setTimeout(check, 1000); + }); + } else { + setError("Something went wrong. Please try again or contact support."); + } + }; + setTimeout(check, 1500); + }; + if (!isVisible) return null; return (
@@ -197,39 +302,7 @@ export const ExportGithub = ({ text="Authorize" icon="key" intent="primary" - onClick={async () => { - const params = isDev - ? `client_id=Iv1.4bf062a6c6636672&state=${state}` - : `client_id=Iv1.e7e282a385b7b2da&state=${state}`; - authWindow.current = window.open( - `https://github.com/login/oauth/authorize?${params}`, - "_blank", - `width=${WINDOW_WIDTH}, height=${WINDOW_HEIGHT}, top=${WINDOW_TOP}, left=${WINDOW_LEFT}`, - ); - - let attemptCount = 0; - const check = () => { - if (attemptCount < 30) { - apiPost({ - path: "access-token", - domain: isDev - ? "https://api.samepage.ngrok.io" - : "https://api.samepage.network", - data: { state }, - }).then((r) => { - if (r.accessToken) { - handleReceivedAccessToken(r.accessToken); - } else { - attemptCount++; - setTimeout(check, 1000); - } - }); - } else { - setError("Something went wrong. Please contact support."); - } - }; - setTimeout(check, 1500); - }} + onClick={handleAuthButtonClick} /> )} {repoSelectEnabled && ( diff --git a/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx b/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx index 83c6d3be8..02e6e480b 100644 --- a/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx +++ b/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx @@ -49,6 +49,7 @@ import getDiscourseNodes from "~/utils/getDiscourseNodes"; import { getConditionLabels } from "~/utils/conditionToDatalog"; import { formatHexColor } from "./DiscourseNodeCanvasSettings"; import posthog from "posthog-js"; +import { getRoamJSSetting, setRoamJSSetting } from "~/utils/settings"; const DEFAULT_SELECTED_RELATION = { display: "none", @@ -868,7 +869,7 @@ export const RelationEditPanel = ({ style={{ marginRight: 8 }} /> - {!!localStorage.getItem("roamjs:discourse-relation-copy") && ( + {!!getRoamJSSetting("discourse-relation-copy") && (
diff --git a/apps/roam/src/index.ts b/apps/roam/src/index.ts index 377518580..34efa56b5 100644 --- a/apps/roam/src/index.ts +++ b/apps/roam/src/index.ts @@ -22,7 +22,6 @@ import discourseGraphStyles from "./styles/discourseGraphStyles.css"; import posthog from "posthog-js"; import getDiscourseNodes from "./utils/getDiscourseNodes"; import { initFeedbackWidget } from "./components/BirdEatsBugs"; -import migrateSettings from "./utils/migrateSettings"; const initPostHog = () => { posthog.init("phc_SNMmBqwNfcEpNduQ41dBUjtGNEUEKAy6jTn63Fzsrax", { @@ -51,9 +50,6 @@ const initPostHog = () => { export const DEFAULT_CANVAS_PAGE_FORMAT = "Canvas/*"; export default runExtension(async (onloadArgs) => { - // Migrate settings from localStorage to extension settings API - migrateSettings(); - const isEncrypted = window.roamAlphaAPI.graph.isEncrypted; const isOffline = window.roamAlphaAPI.graph.type === "offline"; if (!isEncrypted && !isOffline) { diff --git a/apps/roam/src/utils/migrateSettings.ts b/apps/roam/src/utils/migrateSettings.ts deleted file mode 100644 index 216598aca..000000000 --- a/apps/roam/src/utils/migrateSettings.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { getSetting, setRoamJSSetting } from "./settings"; -const SETTINGS_TO_MIGRATE = ["selected-repo", "oauth-github"]; - -const ROAMJS_PREFIXED_SETTINGS = ["discourse-relation-copy"]; - -/** - * Migrates settings from localStorage to extension settings API - * Call this on plugin initialization - */ -export default function migrateSettings(): void { - // Migrate standard settings - SETTINGS_TO_MIGRATE.forEach((key) => { - // getSetting will automatically migrate from localStorage if needed - getSetting(key); - }); - - // Migrate roamjs: prefixed settings - ROAMJS_PREFIXED_SETTINGS.forEach((key) => { - const localKey = `roamjs:${key}`; - const localValue = localStorage.getItem(localKey); - - if (localValue !== null) { - try { - // Try to parse as JSON if possible - const parsedValue = JSON.parse(localValue); - setRoamJSSetting(key, parsedValue); - } catch { - // If not JSON, store as string - setRoamJSSetting(key, localValue); - } - - // Clean up localStorage - localStorage.removeItem(localKey); - } - }); - - console.log("Settings migration completed"); -} diff --git a/apps/roam/src/utils/settings.ts b/apps/roam/src/utils/settings.ts index a8968c5a7..3d6bd900b 100644 --- a/apps/roam/src/utils/settings.ts +++ b/apps/roam/src/utils/settings.ts @@ -1,96 +1,29 @@ import getExtensionAPI from "roamjs-components/util/extensionApiContext"; import localStorageGet from "roamjs-components/util/localStorageGet"; -import localStorageSet from "roamjs-components/util/localStorageSet"; -/** - * Get a setting from the extension API, with fallback to localStorage for backward compatibility - */ export function getSetting(key: string, defaultValue?: T): T { const extensionAPI = getExtensionAPI(); - - // Special handling for oauth tokens - if (key === "oauth-github") { - // For oauth tokens, try localStorage first for backward compatibility - const localValue = localStorageGet(key); - if (localValue !== null && localValue !== undefined && localValue !== "") { - console.log(`Found GitHub token in localStorage: ${typeof localValue}`); - - // Migrate to extension settings if found - extensionAPI.settings.set(key, localValue); - return localValue as T; - } - - // Then try extension settings - const value = extensionAPI.settings.get(key); - console.log(`Extension API GitHub token: ${typeof value}`); - - if (value !== undefined && value !== null && value !== "") { - return value as T; - } - - return defaultValue as T; - } - - // Regular path for non-oauth settings - // Try to get from extension settings first const value = extensionAPI.settings.get(key); if (value !== undefined && value !== null) { return value as T; } - // Fall back to localStorage for backward compatibility - const localValue = localStorageGet(key); + // Fall back to localStorage for backward compatibility then migrate to extension settings + const roamjsKey = `roamjs:${key}`; + const localValue = localStorageGet(key) || localStorageGet(roamjsKey); - // If found in localStorage, migrate it to extension settings if (localValue !== null && localValue !== undefined) { extensionAPI.settings.set(key, localValue); + localStorage.removeItem(key); + localStorage.removeItem(roamjsKey); return localValue as T; } return defaultValue as T; } -/** - * Set a setting in the extension API and remove it from localStorage - */ export function setSetting(key: string, value: T): void { const extensionAPI = getExtensionAPI(); extensionAPI.settings.set(key, value); - - // Clean up localStorage if it exists there - if (localStorageGet(key) !== null) { - localStorageSet(key, ""); - } -} - -/** - * Special handling for settings with roamjs: prefix - */ -export function getRoamJSSetting(key: string, defaultValue?: T): T { - const fullKey = `roamjs:${key}`; - - // Check localStorage directly for these special keys - const localValue = localStorage.getItem(fullKey); - - if (localValue !== null) { - try { - return JSON.parse(localValue) as T; - } catch { - return localValue as unknown as T; - } - } - - return getSetting(key, defaultValue); -} - -/** - * Set a roamjs: prefixed setting - */ -export function setRoamJSSetting(key: string, value: T): void { - const fullKey = `roamjs:${key}`; - setSetting(key, value); - - // Clean up localStorage - localStorage.removeItem(fullKey); -} +} \ No newline at end of file From cfc4d639e78274b73c3a2cee1b4875566a3dea29 Mon Sep 17 00:00:00 2001 From: Trang Doan Date: Fri, 18 Apr 2025 16:18:07 -0400 Subject: [PATCH 3/5] kinda works. need to test more --- apps/roam/src/components/ExportGithub.tsx | 90 ++++++++++------------- 1 file changed, 37 insertions(+), 53 deletions(-) diff --git a/apps/roam/src/components/ExportGithub.tsx b/apps/roam/src/components/ExportGithub.tsx index f8a89c36b..35e51d1c8 100644 --- a/apps/roam/src/components/ExportGithub.tsx +++ b/apps/roam/src/components/ExportGithub.tsx @@ -5,7 +5,8 @@ import MenuItemSelect from "roamjs-components/components/MenuItemSelect"; import apiGet from "roamjs-components/util/apiGet"; import apiPost from "roamjs-components/util/apiPost"; import { getNodeEnv } from "roamjs-components/util/env"; -import { getSetting, setSetting } from "~/utils/settings"; +import getExtensionApi from "roamjs-components/util/extensionApiContext"; +import { setSetting } from "~/utils/settings"; type UserReposResponse = { data: [ @@ -64,10 +65,8 @@ export const ExportGithub = ({ authWindow.current?.close(); }; - const fetchAndSetInstallation = useCallback(async () => { + const fetchAndSetInstallation = useCallback(async (token: string) => { try { - const token = getSetting("oauth-github"); - const res = await apiGet<{ installations: { app_id: number }[] }>({ domain: "https://api.github.com", path: "user/installations", @@ -124,7 +123,7 @@ export const ExportGithub = ({ // check for installation useEffect(() => { - if (gitHubAccessToken) fetchAndSetInstallation(); + if (gitHubAccessToken) fetchAndSetInstallation(gitHubAccessToken); }, [gitHubAccessToken]); // get the list of repos @@ -155,53 +154,6 @@ export const ExportGithub = ({ } }, [gitHubAccessToken, isGitHubAppInstalled, selectedRepo]); - const handleAuthButtonClick = async () => { - const params = isDev - ? `client_id=Iv1.4bf062a6c6636672&state=${state}` - : `client_id=Iv1.e7e282a385b7b2da&state=${state}`; - - authWindow.current = window.open( - `https://github.com/login/oauth/authorize?${params}`, - "_blank", - `width=${WINDOW_WIDTH}, height=${WINDOW_HEIGHT}, top=${WINDOW_TOP}, left=${WINDOW_LEFT}`, - ); - - let attemptCount = 0; - const check = () => { - if (attemptCount < 30) { - const apiDomain = isDev - ? "https://api.samepage.ngrok.io" - : "https://api.samepage.network"; - - console.log( - `Attempt ${attemptCount + 1}/30: Checking for token at ${apiDomain}/access-token`, - ); - - apiPost({ - path: "access-token", - domain: apiDomain, - data: { state }, - }) - .then((r) => { - if (r.accessToken) { - handleReceivedAccessToken(r.accessToken); - } else { - attemptCount++; - setTimeout(check, 1000); - } - }) - .catch((err) => { - console.error("Token check error:", err); - attemptCount++; - setTimeout(check, 1000); - }); - } else { - setError("Something went wrong. Please try again or contact support."); - } - }; - setTimeout(check, 1500); - }; - if (!isVisible) return null; return (
@@ -243,7 +195,39 @@ export const ExportGithub = ({ text="Authorize" icon="key" intent="primary" - onClick={handleAuthButtonClick} + onClick={async () => { + const params = isDev + ? `client_id=Iv1.4bf062a6c6636672&state=${state}` + : `client_id=Iv1.e7e282a385b7b2da&state=${state}`; + authWindow.current = window.open( + `https://github.com/login/oauth/authorize?${params}`, + "_blank", + `width=${WINDOW_WIDTH}, height=${WINDOW_HEIGHT}, top=${WINDOW_TOP}, left=${WINDOW_LEFT}`, + ); + + let attemptCount = 0; + const check = () => { + if (attemptCount < 30) { + apiPost({ + path: "access-token", + domain: isDev + ? "https://api.samepage.ngrok.io" + : "https://api.samepage.network", + data: { state }, + }).then((r) => { + if (r.accessToken) { + handleReceivedAccessToken(r.accessToken); + } else { + attemptCount++; + setTimeout(check, 1000); + } + }); + } else { + setError("Something went wrong. Please contact support."); + } + }; + setTimeout(check, 1500); + }} /> )} {repoSelectEnabled && ( From 7d81f3dfe670addf6157cd950e9a7d208c15179b Mon Sep 17 00:00:00 2001 From: Trang Doan Date: Mon, 21 Apr 2025 14:28:25 -0400 Subject: [PATCH 4/5] small fix --- apps/roam/src/components/ExportGithub.tsx | 11 ++++++++--- apps/roam/src/utils/settings.ts | 7 ++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/apps/roam/src/components/ExportGithub.tsx b/apps/roam/src/components/ExportGithub.tsx index 35e51d1c8..39d562926 100644 --- a/apps/roam/src/components/ExportGithub.tsx +++ b/apps/roam/src/components/ExportGithub.tsx @@ -1,6 +1,12 @@ import { Button } from "@blueprintjs/core"; import nanoid from "nanoid"; -import React, { useCallback, useEffect, useRef, useState } from "react"; +import React, { + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; import MenuItemSelect from "roamjs-components/components/MenuItemSelect"; import apiGet from "roamjs-components/util/apiGet"; import apiPost from "roamjs-components/util/apiPost"; @@ -51,8 +57,7 @@ export const ExportGithub = ({ const showGitHubLogin = isGitHubAppInstalled && !gitHubAccessToken; const repoSelectEnabled = isGitHubAppInstalled && gitHubAccessToken; - // const isDev = useMemo(() => getNodeEnv() === "development", []); - const isDev = false; + const isDev = useMemo(() => getNodeEnv() === "development", []); const setRepo = (repo: string) => { setSelectedRepo(repo); setSetting("selected-repo", repo); diff --git a/apps/roam/src/utils/settings.ts b/apps/roam/src/utils/settings.ts index 3d6bd900b..a2c9e5411 100644 --- a/apps/roam/src/utils/settings.ts +++ b/apps/roam/src/utils/settings.ts @@ -11,12 +11,17 @@ export function getSetting(key: string, defaultValue?: T): T { // Fall back to localStorage for backward compatibility then migrate to extension settings const roamjsKey = `roamjs:${key}`; - const localValue = localStorageGet(key) || localStorageGet(roamjsKey); + const roamjsKey2 = `roamjs:${key}:${window.roamAlphaAPI.graph.name}`; + const localValue = + localStorageGet(key) || + localStorageGet(roamjsKey) || + localStorageGet(roamjsKey2); if (localValue !== null && localValue !== undefined) { extensionAPI.settings.set(key, localValue); localStorage.removeItem(key); localStorage.removeItem(roamjsKey); + localStorage.removeItem(roamjsKey2); return localValue as T; } From 7c725f60833aff47b2ca2487367967300d0413b9 Mon Sep 17 00:00:00 2001 From: Trang Doan Date: Mon, 21 Apr 2025 17:01:39 -0400 Subject: [PATCH 5/5] address PR comments --- apps/roam/src/components/Export.tsx | 2 +- apps/roam/src/components/ExportGithub.tsx | 2 +- .../settings/DiscourseRelationConfigPanel.tsx | 2 +- apps/roam/src/utils/extensionSettings.ts | 16 +++++++++ apps/roam/src/utils/settings.ts | 34 ------------------- 5 files changed, 19 insertions(+), 37 deletions(-) create mode 100644 apps/roam/src/utils/extensionSettings.ts delete mode 100644 apps/roam/src/utils/settings.ts diff --git a/apps/roam/src/components/Export.tsx b/apps/roam/src/components/Export.tsx index 615998941..c44a91504 100644 --- a/apps/roam/src/components/Export.tsx +++ b/apps/roam/src/components/Export.tsx @@ -49,7 +49,7 @@ import createPage from "roamjs-components/writes/createPage"; import { createInitialTldrawProps } from "~/utils/createInitialTldrawProps"; import { isCanvasPage as checkIfCanvasPage } from "~/utils/isCanvasPage"; import sendErrorEmail from "~/utils/sendErrorEmail"; -import { getSetting, setSetting } from "~/utils/settings"; +import { getSetting, setSetting } from "~/utils/extensionSettings"; const ExportProgress = ({ id }: { id: string }) => { const [progress, setProgress] = useState(0); diff --git a/apps/roam/src/components/ExportGithub.tsx b/apps/roam/src/components/ExportGithub.tsx index 39d562926..b72b0181b 100644 --- a/apps/roam/src/components/ExportGithub.tsx +++ b/apps/roam/src/components/ExportGithub.tsx @@ -12,7 +12,7 @@ import apiGet from "roamjs-components/util/apiGet"; import apiPost from "roamjs-components/util/apiPost"; import { getNodeEnv } from "roamjs-components/util/env"; import getExtensionApi from "roamjs-components/util/extensionApiContext"; -import { setSetting } from "~/utils/settings"; +import { setSetting } from "~/utils/extensionSettings"; type UserReposResponse = { data: [ diff --git a/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx b/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx index 28222bb01..a9b81a214 100644 --- a/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx +++ b/apps/roam/src/components/settings/DiscourseRelationConfigPanel.tsx @@ -49,7 +49,7 @@ import getDiscourseNodes from "~/utils/getDiscourseNodes"; import { getConditionLabels } from "~/utils/conditionToDatalog"; import { formatHexColor } from "./DiscourseNodeCanvasSettings"; import posthog from "posthog-js"; -import { getSetting, setSetting } from "~/utils/settings"; +import { getSetting, setSetting } from "~/utils/extensionSettings"; const DEFAULT_SELECTED_RELATION = { display: "none", diff --git a/apps/roam/src/utils/extensionSettings.ts b/apps/roam/src/utils/extensionSettings.ts new file mode 100644 index 000000000..d53134b43 --- /dev/null +++ b/apps/roam/src/utils/extensionSettings.ts @@ -0,0 +1,16 @@ +import getExtensionAPI from "roamjs-components/util/extensionApiContext"; + +export function getSetting(key: string, defaultValue?: T): T { + const extensionAPI = getExtensionAPI(); + const value = extensionAPI.settings.get(key); + + if (value !== undefined && value !== null) { + return value as T; + } + return defaultValue as T; +} + +export function setSetting(key: string, value: T): void { + const extensionAPI = getExtensionAPI(); + extensionAPI.settings.set(key, value); +} diff --git a/apps/roam/src/utils/settings.ts b/apps/roam/src/utils/settings.ts deleted file mode 100644 index a2c9e5411..000000000 --- a/apps/roam/src/utils/settings.ts +++ /dev/null @@ -1,34 +0,0 @@ -import getExtensionAPI from "roamjs-components/util/extensionApiContext"; -import localStorageGet from "roamjs-components/util/localStorageGet"; - -export function getSetting(key: string, defaultValue?: T): T { - const extensionAPI = getExtensionAPI(); - const value = extensionAPI.settings.get(key); - - if (value !== undefined && value !== null) { - return value as T; - } - - // Fall back to localStorage for backward compatibility then migrate to extension settings - const roamjsKey = `roamjs:${key}`; - const roamjsKey2 = `roamjs:${key}:${window.roamAlphaAPI.graph.name}`; - const localValue = - localStorageGet(key) || - localStorageGet(roamjsKey) || - localStorageGet(roamjsKey2); - - if (localValue !== null && localValue !== undefined) { - extensionAPI.settings.set(key, localValue); - localStorage.removeItem(key); - localStorage.removeItem(roamjsKey); - localStorage.removeItem(roamjsKey2); - return localValue as T; - } - - return defaultValue as T; -} - -export function setSetting(key: string, value: T): void { - const extensionAPI = getExtensionAPI(); - extensionAPI.settings.set(key, value); -} \ No newline at end of file