62 lines
2.1 KiB
TypeScript
62 lines
2.1 KiB
TypeScript
import { create } from 'zustand';
|
|
import { persist } from 'zustand/middleware';
|
|
import { CHANNELS } from '../constants/channels';
|
|
import type { ChannelState } from '../types';
|
|
|
|
interface ChannelConnectStore {
|
|
channels: Record<string, ChannelState>;
|
|
expandedId: string | null;
|
|
connectedCount: number;
|
|
setExpandedId: (id: string | null) => void;
|
|
handleFieldChange: (channelId: string, fieldKey: string, value: string) => void;
|
|
handleConnect: (channelId: string) => void;
|
|
handleDisconnect: (channelId: string) => void;
|
|
}
|
|
|
|
const initialChannels: Record<string, ChannelState> = {};
|
|
for (const ch of CHANNELS) {
|
|
initialChannels[ch.id] = { status: 'disconnected', values: {} };
|
|
}
|
|
|
|
export const useChannelConnectStore = create<ChannelConnectStore>()(
|
|
persist(
|
|
(set) => ({
|
|
channels: initialChannels,
|
|
expandedId: null,
|
|
connectedCount: 0,
|
|
|
|
setExpandedId: (expandedId) => set({ expandedId }),
|
|
|
|
handleFieldChange: (channelId, fieldKey, value) => set((s) => ({
|
|
channels: {
|
|
...s.channels,
|
|
[channelId]: {
|
|
...s.channels[channelId],
|
|
values: { ...s.channels[channelId].values, [fieldKey]: value },
|
|
},
|
|
},
|
|
})),
|
|
|
|
handleConnect: (channelId) => {
|
|
set((s) => ({
|
|
channels: { ...s.channels, [channelId]: { ...s.channels[channelId], status: 'connecting' } },
|
|
}));
|
|
setTimeout(() => {
|
|
set((s) => {
|
|
const channels = { ...s.channels, [channelId]: { ...s.channels[channelId], status: 'connected' as const } };
|
|
const connectedCount = Object.values(channels).filter(c => c.status === 'connected').length;
|
|
return { channels, connectedCount };
|
|
});
|
|
}, 2000);
|
|
},
|
|
|
|
handleDisconnect: (channelId) => set((s) => {
|
|
const channels = { ...s.channels, [channelId]: { status: 'disconnected' as const, values: {} } };
|
|
const connectedCount = Object.values(channels).filter(c => c.status === 'connected').length;
|
|
return { channels, connectedCount };
|
|
}),
|
|
}),
|
|
{ name: 'channel-connect' }
|
|
)
|
|
);
|