2021-09-13 20:41:05 +00:00
|
|
|
/* eslint-disable no-shadow */
|
|
|
|
import React, { useContext, useState } from 'react';
|
2022-05-26 14:07:17 +00:00
|
|
|
import { BlockContext } from '@rocket.chat/ui-kit';
|
2021-09-13 20:41:05 +00:00
|
|
|
|
2022-05-26 14:07:17 +00:00
|
|
|
import { IText } from './interfaces';
|
2022-03-16 19:07:49 +00:00
|
|
|
|
2022-03-29 20:06:50 +00:00
|
|
|
export const textParser = ([{ text }]: IText[]) => text;
|
2021-09-13 20:41:05 +00:00
|
|
|
|
|
|
|
export const defaultContext: any = {
|
|
|
|
action: (...args: any) => console.log(args),
|
|
|
|
state: console.log,
|
|
|
|
appId: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
|
|
|
|
errors: {}
|
|
|
|
};
|
|
|
|
|
|
|
|
export const KitContext = React.createContext(defaultContext);
|
|
|
|
|
2022-03-16 19:07:49 +00:00
|
|
|
type TObjectReturn = {
|
|
|
|
loading: boolean;
|
|
|
|
setLoading: React.Dispatch<React.SetStateAction<boolean>>;
|
|
|
|
error: any;
|
|
|
|
value: any;
|
|
|
|
language: any;
|
|
|
|
};
|
|
|
|
|
|
|
|
type TFunctionReturn = (value: any) => Promise<void>;
|
|
|
|
|
|
|
|
type TReturn = [TObjectReturn, TFunctionReturn];
|
|
|
|
|
2022-03-29 20:06:50 +00:00
|
|
|
interface IUseBlockContext {
|
|
|
|
blockId?: string;
|
|
|
|
actionId: string;
|
|
|
|
appId?: string;
|
|
|
|
initialValue?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useBlockContext = ({ blockId, actionId, appId, initialValue }: IUseBlockContext, context: BlockContext): TReturn => {
|
2021-09-13 20:41:05 +00:00
|
|
|
const { action, appId: appIdFromContext, viewId, state, language, errors, values = {} } = useContext(KitContext);
|
|
|
|
const { value = initialValue } = values[actionId] || {};
|
|
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
|
|
|
|
const error = errors && actionId && errors[actionId];
|
|
|
|
|
2022-05-26 14:07:17 +00:00
|
|
|
if ([BlockContext.SECTION, BlockContext.ACTION].includes(context)) {
|
2021-09-13 20:41:05 +00:00
|
|
|
return [
|
|
|
|
{
|
|
|
|
loading,
|
|
|
|
setLoading,
|
|
|
|
error,
|
|
|
|
value,
|
|
|
|
language
|
|
|
|
},
|
|
|
|
async ({ value }: any) => {
|
|
|
|
setLoading(true);
|
|
|
|
try {
|
|
|
|
await action({
|
|
|
|
blockId,
|
|
|
|
appId: appId || appIdFromContext,
|
|
|
|
actionId,
|
|
|
|
value,
|
|
|
|
viewId
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
// do nothing
|
|
|
|
}
|
|
|
|
setLoading(false);
|
|
|
|
}
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
return [
|
|
|
|
{
|
|
|
|
loading,
|
|
|
|
setLoading,
|
|
|
|
value,
|
|
|
|
error,
|
|
|
|
language
|
|
|
|
},
|
|
|
|
async ({ value }: any) => {
|
|
|
|
setLoading(true);
|
|
|
|
try {
|
|
|
|
await state({
|
|
|
|
blockId,
|
|
|
|
appId,
|
|
|
|
actionId,
|
|
|
|
value
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
// do nothing
|
|
|
|
}
|
|
|
|
setLoading(false);
|
|
|
|
}
|
|
|
|
];
|
|
|
|
};
|