useGetBones.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import React, { Children, useCallback } from 'react';
  2. import { View } from 'react-native';
  3. import { useRenderBone } from './useRenderBone';
  4. import StaticBone from '../StaticBone';
  5. import ShiverBone from '../ShiverBone';
  6. import type {
  7. ICustomViewStyle,
  8. IGeneralStyles,
  9. IComponentSize,
  10. } from '../constants';
  11. interface UseGetBonesProps {
  12. bonesLayout: ICustomViewStyle[];
  13. children: React.ReactNode;
  14. prefix?: string | number;
  15. generalStyles: IGeneralStyles;
  16. }
  17. /**
  18. * This hook is used to get the bones based on the layout prop.
  19. * @componentSize is the size of the component.
  20. */
  21. export const useGetBones = (componentSize: IComponentSize) => {
  22. const renderBone = useRenderBone(componentSize);
  23. const renderNestedBones = useCallback(
  24. (
  25. bones: ICustomViewStyle[],
  26. prefix: string | number | undefined,
  27. generalStyles: IGeneralStyles,
  28. ) => {
  29. return bones.map((bone, index) => {
  30. const keyIndex = prefix ? `${prefix}_${index}` : index;
  31. const { children: childBones, ...layoutStyle } = bone;
  32. if (childBones?.length) {
  33. return (
  34. <View key={keyIndex} style={layoutStyle}>
  35. {renderNestedBones(childBones, keyIndex, generalStyles)}
  36. </View>
  37. );
  38. }
  39. return renderBone({
  40. generalStyles,
  41. bonesLayout: bones,
  42. index,
  43. keyIndex,
  44. });
  45. });
  46. },
  47. [renderBone],
  48. );
  49. return useCallback(
  50. ({ bonesLayout, children, prefix, generalStyles }: UseGetBonesProps) => {
  51. if (bonesLayout && bonesLayout.length > 0) {
  52. return renderNestedBones(bonesLayout, prefix, generalStyles);
  53. }
  54. return Children.map(children, (child, i) => {
  55. const styling = child.props.style || {};
  56. if (
  57. generalStyles.animationType === 'pulse' ||
  58. generalStyles.animationType === 'none'
  59. ) {
  60. return (
  61. <StaticBone
  62. key={prefix ? `${prefix}_${i}` : i}
  63. index={i}
  64. boneLayout={styling}
  65. componentSize={componentSize}
  66. {...generalStyles}
  67. />
  68. );
  69. }
  70. return (
  71. <ShiverBone
  72. index={prefix ? `${prefix}_${i}` : i}
  73. componentSize={componentSize}
  74. boneLayout={styling}
  75. {...generalStyles}
  76. />
  77. );
  78. });
  79. },
  80. [componentSize, renderNestedBones],
  81. );
  82. };