git feature

This commit is contained in:
2026-06-30 14:46:19 +07:00
parent 251c1b7573
commit 11e5a76977
23 changed files with 1680 additions and 28 deletions

View File

@@ -0,0 +1,86 @@
import { useCallback, useEffect, useState } from 'react';
import { apiGitHub } from '../api';
export function useGitHubConnection() {
const [connected, setConnected] = useState(false);
const [githubLogin, setGithubLogin] = useState('');
const [connecting, setConnecting] = useState(false);
const [error, setError] = useState('');
const [message, setMessage] = useState('');
const refresh = useCallback(async () => {
try {
const st = await apiGitHub.status();
setConnected(!!st.connected);
setGithubLogin(st.githubLogin || '');
} catch (e) {
console.error(e);
setConnected(false);
setGithubLogin('');
}
}, []);
useEffect(() => {
refresh().catch(console.error);
}, [refresh]);
useEffect(() => {
const onMessage = (e: MessageEvent) => {
const data = e.data as { type?: string; ok?: boolean; detail?: string };
if (data?.type !== 'simple-care-github-connected') return;
setConnecting(false);
if (data.ok) {
refresh().catch(console.error);
setMessage(typeof data.detail === 'string' ? `Đã kết nối GitHub @${data.detail}` : 'Đã kết nối GitHub');
setError('');
} else {
setError(typeof data.detail === 'string' ? data.detail : 'Kết nối GitHub thất bại');
}
};
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
}, [refresh]);
const connect = async () => {
setError('');
setMessage('');
setConnecting(true);
try {
const { authorizeUrl } = await apiGitHub.authorizeUrl();
const w = window.open(authorizeUrl, 'simple_care_github_oauth', 'width=720,height=760');
if (!w) {
setConnecting(false);
setError('Trình duyệt chặn popup — cho phép popup rồi thử lại.');
}
} catch (e: any) {
setConnecting(false);
setError(e?.message || 'Không mở được OAuth GitHub');
}
};
const disconnect = async () => {
setError('');
setMessage('');
try {
await apiGitHub.disconnect();
setConnected(false);
setGithubLogin('');
setMessage('Đã ngắt kết nối GitHub');
} catch (e: any) {
setError(e?.message || 'Ngắt kết nối thất bại');
}
};
return {
connected,
githubLogin,
connecting,
error,
message,
setError,
setMessage,
refresh,
connect,
disconnect,
};
}