Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ feat: import settings from url #2226

Merged
merged 11 commits into from Apr 30, 2024
2 changes: 2 additions & 0 deletions src/const/url.ts
Expand Up @@ -38,3 +38,5 @@ export const SESSION_CHAT_URL = (id: string = INBOX_SESSION_ID, mobile?: boolean
mobile ? `/chat/mobile?session=${id}` : `/chat?session=${id}`;

export const imageUrl = (filename: string) => withBasePath(`/images/${filename}`);

export const LOBE_URL_IMPORT_NAME = 'settings';
23 changes: 22 additions & 1 deletion src/hooks/useImportConfig.ts
@@ -1,13 +1,17 @@
import { useMemo } from 'react';

import { ImportResults, configService } from '@/services/config';
import { shareGPTService } from '@/services/share';
arvinxx marked this conversation as resolved.
Show resolved Hide resolved
import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { useSessionStore } from '@/store/session';
import { importConfigFile } from '@/utils/config';
import { merge } from '@/utils/merge';

export const useImportConfig = () => {
const refreshSessions = useSessionStore((s) => s.refreshSessions);
const [refreshMessages, refreshTopics] = useChatStore((s) => [s.refreshMessages, s.refreshTopic]);
const [settings, setSettings] = useGlobalStore((s) => [s.settings, s.setSettings]);

const importConfig = async (file: File) =>
new Promise<ImportResults | undefined>((resolve) => {
Expand All @@ -22,5 +26,22 @@ export const useImportConfig = () => {
});
});

return useMemo(() => ({ importConfig }), []);
/**
* Import settings from a string in json format
* @param settingsParams
* @returns
*/
const importSettings = (settingsParams: string | null) => {
if (settingsParams) {
const importSettings = shareGPTService.decodeShareSettings(settingsParams);
if (importSettings?.message || !importSettings?.data) {
// handle some error
return;
}
const mergedState = merge(settings, importSettings.data);
arvinxx marked this conversation as resolved.
Show resolved Hide resolved
setSettings(mergedState);
}
};

return useMemo(() => ({ importConfig, importSettings }), []);
};
11 changes: 10 additions & 1 deletion src/layout/GlobalProvider/StoreInitialization.tsx
@@ -1,9 +1,11 @@
'use client';

import { useRouter } from 'next/navigation';
import { useRouter, useSearchParams } from 'next/navigation';
import { memo, useEffect } from 'react';
import { createStoreUpdater } from 'zustand-utils';

import { LOBE_URL_IMPORT_NAME } from '@/const/url';
import { useImportConfig } from '@/hooks/useImportConfig';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useEnabledDataSync } from '@/hooks/useSyncData';
import { useGlobalStore } from '@/store/global';
Expand All @@ -30,6 +32,13 @@ const StoreInitialization = memo(() => {
useStoreUpdater('isMobile', mobile);
useStoreUpdater('router', router);

// Import settings from the url
const { importSettings } = useImportConfig();
const searchParam = useSearchParams().get(LOBE_URL_IMPORT_NAME);
useEffect(() => {
importSettings(searchParam);
arvinxx marked this conversation as resolved.
Show resolved Hide resolved
}, [searchParam]);

useEffect(() => {
router.prefetch('/chat');
router.prefetch('/chat/settings');
Expand Down
45 changes: 45 additions & 0 deletions src/services/__tests__/share.test.ts
@@ -1,5 +1,8 @@
import { DeepPartial } from 'utility-types';
import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { LOBE_URL_IMPORT_NAME } from '@/const/url';
import { GlobalSettings } from '@/types/settings';
import { ShareGPTConversation } from '@/types/share';
import { parseMarkdown } from '@/utils/parseMarkdown';

Expand Down Expand Up @@ -84,3 +87,45 @@ describe('ShareGPTService', () => {
await expect(shareGPTService.createShareGPTUrl(conversation)).rejects.toThrow();
});
});

describe('ShareViaUrl', () => {
describe('createShareSettingsUrl', () => {
it('should create a share settings URL with the provided settings', () => {
const settings: DeepPartial<GlobalSettings> = {
languageModel: {
openai: {
apiKey: 'user-key',
},
},
};
const url = shareGPTService.createShareSettingsUrl(settings);
expect(url).toBe(
`/?${LOBE_URL_IMPORT_NAME}=%7B%22languageModel%22:%7B%22openai%22:%7B%22apiKey%22:%22user-key%22%7D%7D%7D`,
);
});
});

describe('decodeShareSettings', () => {
it('should decode share settings from search params', () => {
const settings = '{"languageModel":{"openai":{"apiKey":"user-key"}}}';
const decodedSettings = shareGPTService.decodeShareSettings(settings);
expect(decodedSettings).toEqual({
data: {
languageModel: {
openai: {
apiKey: 'user-key',
},
},
},
});
});

it('should return an error message if decoding fails', () => {
const settings = '%7B%22theme%22%3A%22dark%22%2C%22fontSize%22%3A16%';
const decodedSettings = shareGPTService.decodeShareSettings(settings);
expect(decodedSettings).toEqual({
message: expect.any(String),
});
});
});
});
27 changes: 27 additions & 0 deletions src/services/share.ts
arvinxx marked this conversation as resolved.
Show resolved Hide resolved
@@ -1,4 +1,9 @@
import { DeepPartial } from 'utility-types';

import { LOBE_URL_IMPORT_NAME } from '@/const/url';
import { GlobalSettings } from '@/types/settings';
import { ShareGPTConversation } from '@/types/share';
import { withBasePath } from '@/utils/basePath';
import { parseMarkdown } from '@/utils/parseMarkdown';

export const SHARE_GPT_URL = 'https://sharegpt.com/api/conversations';
Expand Down Expand Up @@ -29,6 +34,28 @@ class ShareGPTService {
// short link to the ShareGPT post
return `https://shareg.pt/${id}`;
}

/**
* Creates a share settings URL with the provided settings.
* @param settings - The settings object to be encoded in the URL.
* @returns The share settings URL.
*/
public createShareSettingsUrl(settings: DeepPartial<GlobalSettings>) {
return withBasePath(`/?${LOBE_URL_IMPORT_NAME}=${encodeURI(JSON.stringify(settings))}`);
}

/**
* Decode share settings from search params
* @param settings
* @returns
*/
public decodeShareSettings(settings: string) {
try {
return { data: JSON.parse(settings) as DeepPartial<GlobalSettings> };
} catch (e) {
return { message: JSON.stringify(e) };
}
}
}

export const shareGPTService = new ShareGPTService();