projectPermission.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * <<
  3. * Davinci
  4. * ==
  5. * Copyright (C) 2016 - 2017 EDP
  6. * ==
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * >>
  19. */
  20. import { useSelector } from 'react-redux'
  21. import { makeSelectCurrentProject } from '../selectors'
  22. import { IProjectPermission } from '../types'
  23. function useProjectPermission<T>(
  24. component: T,
  25. permissionNames: keyof IProjectPermission,
  26. type?: 2 | 3
  27. ): T
  28. function useProjectPermission<T>(
  29. component: T,
  30. permissionNames: keyof IProjectPermission | Array<keyof IProjectPermission>,
  31. type?: 2 | 3
  32. ): T[]
  33. function useProjectPermission<T>(
  34. component: T,
  35. permissionNames: keyof IProjectPermission | Array<keyof IProjectPermission>,
  36. type?: 2 | 3
  37. ) {
  38. const currentProject = useSelector(makeSelectCurrentProject())
  39. const names: Array<keyof IProjectPermission> = [].concat(permissionNames)
  40. const authorizedComponents = names.map((permissionName) => {
  41. if (!currentProject) {
  42. return () => null
  43. }
  44. const { permission } = currentProject
  45. const typePermission = permission[permissionName]
  46. if (!typePermission) {
  47. return () => null
  48. }
  49. let hasPermission = false
  50. if (typeof typePermission === 'boolean') {
  51. hasPermission = typePermission
  52. } else {
  53. // 0 隐藏
  54. // 1 只读
  55. // 2 修改
  56. // 3 删除
  57. switch (+typePermission) {
  58. case 3:
  59. hasPermission = true
  60. break
  61. case 2:
  62. case 1:
  63. hasPermission = type ? typePermission >= type : true // default readonly
  64. break
  65. }
  66. }
  67. if (hasPermission) {
  68. return component
  69. }
  70. const nullComponent = Array.isArray(component)
  71. ? component.map(() => () => null)
  72. : () => null
  73. return nullComponent
  74. })
  75. return typeof permissionNames === 'string'
  76. ? authorizedComponents[0]
  77. : authorizedComponents
  78. }
  79. export default useProjectPermission