use-slide-background-style.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { useMemo } from 'react';
  2. import type { SlideBackground } from '@/lib/types/slides';
  3. /**
  4. * Convert slide background data to CSS styles
  5. */
  6. export function useSlideBackgroundStyle(background: SlideBackground | undefined) {
  7. const backgroundStyle = useMemo<React.CSSProperties>(() => {
  8. if (!background) return { backgroundColor: '#fff' };
  9. const { type, color, image, gradient } = background;
  10. // Solid color background
  11. if (type === 'solid') return { backgroundColor: color };
  12. // Image background mode
  13. // Includes: background image, background size, whether to repeat
  14. if (type === 'image' && image) {
  15. const { src, size } = image;
  16. if (!src) return { backgroundColor: '#fff' };
  17. if (size === 'repeat') {
  18. return {
  19. backgroundImage: `url(${src})`,
  20. backgroundRepeat: 'repeat',
  21. backgroundSize: 'contain',
  22. };
  23. }
  24. return {
  25. backgroundImage: `url(${src})`,
  26. backgroundRepeat: 'no-repeat',
  27. backgroundSize: size || 'cover',
  28. };
  29. }
  30. // Gradient background
  31. if (type === 'gradient' && gradient) {
  32. const { type, colors, rotate } = gradient;
  33. const list = colors.map((item) => `${item.color} ${item.pos}%`);
  34. if (type === 'radial') {
  35. return { backgroundImage: `radial-gradient(${list.join(',')})` };
  36. }
  37. return {
  38. backgroundImage: `linear-gradient(${rotate}deg, ${list.join(',')})`,
  39. };
  40. }
  41. return { backgroundColor: '#fff' };
  42. }, [background]);
  43. return {
  44. backgroundStyle,
  45. };
  46. }