index.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { useEffect, useState } from 'react';
  2. import type { BUTTON_PERMISSION, MENUS_CODE_TYPE } from '@/utils/menu/router';
  3. import { BUTTON_PERMISSION_ENUM } from '@/utils/menu/router';
  4. import { MENUS_BUTTONS_CACHE } from '@/utils/menu';
  5. export type permissionKeyType = keyof typeof BUTTON_PERMISSION_ENUM;
  6. export type permissionType = Record<permissionKeyType, boolean>;
  7. const usePermissions = (
  8. code: MENUS_CODE_TYPE,
  9. ): {
  10. /**
  11. * 是否有改权限
  12. */
  13. permission: Partial<permissionType>;
  14. /**
  15. * 获取额外权限,比如组合权限
  16. * @example getOtherPermission(['add', 'delete']) => boolean
  17. * @return Boolean
  18. */
  19. getOtherPermission: (permission: BUTTON_PERMISSION | BUTTON_PERMISSION[]) => boolean;
  20. } => {
  21. const [permission, setPermission] = useState<Partial<permissionType>>({});
  22. let buttons = {};
  23. const permissionButton: Partial<permissionType> = {};
  24. try {
  25. const buttonString = localStorage.getItem(MENUS_BUTTONS_CACHE);
  26. buttons = JSON.parse(buttonString || '{}');
  27. } catch (e) {
  28. console.warn(e);
  29. }
  30. const getOtherPermission = (permissionCode: string | string[]) => {
  31. if (!!Object.keys(buttons).length && permissionCode) {
  32. const _buttonArray = buttons[code];
  33. if (!_buttonArray) {
  34. return false;
  35. }
  36. return _buttonArray.some((btnId: string) => {
  37. if (typeof permissionCode === 'string') {
  38. return permissionCode === btnId;
  39. } else {
  40. return permissionCode.includes(btnId);
  41. }
  42. return false;
  43. });
  44. }
  45. return false;
  46. };
  47. useEffect(() => {
  48. Object.keys(BUTTON_PERMISSION_ENUM).forEach((key) => {
  49. permissionButton[key] = getOtherPermission(key);
  50. });
  51. setPermission(permissionButton);
  52. }, [code]);
  53. return { permission, getOtherPermission };
  54. };
  55. export default usePermissions;