bigbluebutton-Github/bigbluebutton-html5/imports/ui/components/video-preview/virtual-background/context.jsx

105 lines
2.4 KiB
React
Raw Normal View History

import React, { useReducer } from 'react';
import _ from 'lodash';
import Service from './service';
export const CustomVirtualBackgroundsContext = React.createContext();
const reducer = (state, action) => {
const { save, del, update } = Service;
switch (action.type) {
case 'load': {
2022-07-08 05:59:30 +08:00
const backgrounds = { ...state.backgrounds };
action.backgrounds.forEach((background) => {
backgrounds[background.uniqueId] = background;
});
return {
...state,
loaded: true,
2022-07-08 05:59:30 +08:00
backgrounds,
};
}
case 'new': {
save(action.background);
return {
...state,
2022-07-08 05:59:30 +08:00
backgrounds: {
...state.backgrounds,
[action.background.uniqueId]: action.background,
},
};
}
case 'delete': {
2022-07-08 05:59:30 +08:00
const { backgrounds } = state;
delete backgrounds[action.uniqueId];
del(action.uniqueId);
return {
2022-06-01 23:31:56 +08:00
...state,
2022-07-08 05:59:30 +08:00
backgrounds,
};
}
case 'update': {
if (action.background.custom) update(action.background);
return {
...state,
backgrounds: {
...state.backgrounds,
[action.background.uniqueId]: action.background,
},
};
}
case 'setDefault': {
const backgrounds = { ...state.backgrounds };
action.backgrounds.forEach((background) => {
backgrounds[background.uniqueId] = background;
});
return {
...state,
defaultSetUp: true,
backgrounds,
};
}
default: {
throw new Error('Unknown custom background action.');
}
}
};
export const CustomBackgroundsProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, {
loaded: false,
defaultSetUp: false,
2022-07-08 05:59:30 +08:00
backgrounds: {},
});
const { load } = Service;
const loadFromDB = () => {
const onError = () => dispatch({
type: 'load',
2022-07-08 05:59:30 +08:00
backgrounds: {},
});
const onSuccess = (backgrounds) => dispatch({
type: 'load',
backgrounds,
});
load(onError, onSuccess);
};
return (
<CustomVirtualBackgroundsContext.Provider
value={{
dispatch,
loaded: state.loaded,
defaultSetUp: state.defaultSetUp,
2022-07-08 05:59:30 +08:00
backgrounds: state.backgrounds,
loadFromDB: _.throttle(loadFromDB, 500, { leading: true, trailing: false }),
}}
>
{children}
</CustomVirtualBackgroundsContext.Provider>
);
};