2020-02-11 14:01:35 +00:00
|
|
|
/* eslint-disable no-shadow */
|
|
|
|
import React, { useContext, useState } from 'react';
|
|
|
|
import { BLOCK_CONTEXT } from '@rocket.chat/ui-kit';
|
|
|
|
|
2021-07-26 22:33:27 +00:00
|
|
|
export const textParser = ([{ text }]: any) => text;
|
2020-02-11 14:01:35 +00:00
|
|
|
|
2021-07-26 22:33:27 +00:00
|
|
|
export const defaultContext: any = {
|
|
|
|
action: (...args: any) => console.log(args),
|
2020-02-11 14:01:35 +00:00
|
|
|
state: console.log,
|
|
|
|
appId: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
|
|
|
|
errors: {}
|
|
|
|
};
|
|
|
|
|
|
|
|
export const KitContext = React.createContext(defaultContext);
|
|
|
|
|
|
|
|
export const useBlockContext = ({
|
|
|
|
blockId, actionId, appId, initialValue
|
2021-07-26 22:33:27 +00:00
|
|
|
}: any, context: any) => {
|
2020-02-11 14:01:35 +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];
|
|
|
|
|
|
|
|
if ([BLOCK_CONTEXT.SECTION, BLOCK_CONTEXT.ACTION].includes(context)) {
|
|
|
|
return [{
|
|
|
|
loading, setLoading, error, value, language
|
2021-07-26 22:33:27 +00:00
|
|
|
}, async({ value }: any) => {
|
2020-02-11 14:01:35 +00:00
|
|
|
setLoading(true);
|
2020-02-11 16:00:58 +00:00
|
|
|
try {
|
|
|
|
await action({
|
|
|
|
blockId,
|
|
|
|
appId: appId || appIdFromContext,
|
|
|
|
actionId,
|
|
|
|
value,
|
|
|
|
viewId
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
// do nothing
|
|
|
|
}
|
2020-02-11 14:01:35 +00:00
|
|
|
setLoading(false);
|
|
|
|
}];
|
|
|
|
}
|
|
|
|
|
|
|
|
return [{
|
|
|
|
loading, setLoading, value, error, language
|
2021-07-26 22:33:27 +00:00
|
|
|
}, async({ value }: any) => {
|
2020-02-11 14:01:35 +00:00
|
|
|
setLoading(true);
|
2020-02-11 16:00:58 +00:00
|
|
|
try {
|
|
|
|
await state({
|
|
|
|
blockId,
|
|
|
|
appId,
|
|
|
|
actionId,
|
|
|
|
value
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
// do nothing
|
|
|
|
}
|
2020-02-11 14:01:35 +00:00
|
|
|
setLoading(false);
|
|
|
|
}];
|
|
|
|
};
|