2023-10-15 20:26:32 +11:00
|
|
|
'use client';
|
|
|
|
|
|
2023-10-22 11:18:00 +11:00
|
|
|
import { createContext, useContext, useEffect, useState } from 'react';
|
2023-10-21 13:08:29 +11:00
|
|
|
|
|
|
|
|
import { equals } from 'remeda';
|
2023-10-15 20:26:32 +11:00
|
|
|
|
|
|
|
|
import { getLimits } from '../client';
|
|
|
|
|
import { FREE_PLAN_LIMITS } from '../constants';
|
2024-02-06 16:16:10 +11:00
|
|
|
import type { TLimitsResponseSchema } from '../schema';
|
2023-10-15 20:26:32 +11:00
|
|
|
|
|
|
|
|
export type LimitsContextValue = TLimitsResponseSchema;
|
|
|
|
|
|
|
|
|
|
const LimitsContext = createContext<LimitsContextValue | null>(null);
|
|
|
|
|
|
|
|
|
|
export const useLimits = () => {
|
|
|
|
|
const limits = useContext(LimitsContext);
|
|
|
|
|
|
|
|
|
|
if (!limits) {
|
|
|
|
|
throw new Error('useLimits must be used within a LimitsProvider');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return limits;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export type LimitsProviderProps = {
|
|
|
|
|
initialValue?: LimitsContextValue;
|
2024-02-06 16:16:10 +11:00
|
|
|
teamId?: number;
|
2023-10-15 20:26:32 +11:00
|
|
|
children?: React.ReactNode;
|
|
|
|
|
};
|
|
|
|
|
|
2024-02-06 16:16:10 +11:00
|
|
|
export const LimitsProvider = ({
|
|
|
|
|
initialValue = {
|
2023-10-15 20:26:32 +11:00
|
|
|
quota: FREE_PLAN_LIMITS,
|
|
|
|
|
remaining: FREE_PLAN_LIMITS,
|
2024-02-06 16:16:10 +11:00
|
|
|
},
|
|
|
|
|
teamId,
|
|
|
|
|
children,
|
|
|
|
|
}: LimitsProviderProps) => {
|
|
|
|
|
const [limits, setLimits] = useState(() => initialValue);
|
2023-10-21 13:08:29 +11:00
|
|
|
|
|
|
|
|
const refreshLimits = async () => {
|
2024-02-06 16:16:10 +11:00
|
|
|
const newLimits = await getLimits({ teamId });
|
2023-10-21 13:08:29 +11:00
|
|
|
|
2023-10-22 11:18:00 +11:00
|
|
|
setLimits((oldLimits) => {
|
|
|
|
|
if (equals(oldLimits, newLimits)) {
|
|
|
|
|
return oldLimits;
|
|
|
|
|
}
|
2023-10-21 13:08:29 +11:00
|
|
|
|
2023-10-22 11:18:00 +11:00
|
|
|
return newLimits;
|
|
|
|
|
});
|
2023-10-21 13:08:29 +11:00
|
|
|
};
|
2023-10-15 20:26:32 +11:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
2023-10-21 13:08:29 +11:00
|
|
|
void refreshLimits();
|
2023-10-15 20:26:32 +11:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const onFocus = () => {
|
2023-10-21 13:08:29 +11:00
|
|
|
void refreshLimits();
|
2023-10-15 20:26:32 +11:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
window.addEventListener('focus', onFocus);
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
window.removeEventListener('focus', onFocus);
|
|
|
|
|
};
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return <LimitsContext.Provider value={limits}>{children}</LimitsContext.Provider>;
|
|
|
|
|
};
|