copy-style.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const oneDepthCopy = (obj, nestKeys) => ({
  2. ...obj,
  3. ...nestKeys.reduce((memo, key) => {
  4. if (obj[key]) memo[key] = {...obj[key]};
  5. return memo;
  6. }, {}),
  7. });
  8. const setIfExists = (src, dst, key, nestKeys = []) => {
  9. if (src[key]) dst[key] = oneDepthCopy(src[key], nestKeys);
  10. };
  11. const isEmptyObj = obj => Object.keys(obj).length === 0;
  12. const copyStyle = style => {
  13. if (!style) return style;
  14. if (isEmptyObj(style)) return {};
  15. const copied = {...style};
  16. setIfExists(style, copied, 'font', ['color']);
  17. setIfExists(style, copied, 'alignment');
  18. setIfExists(style, copied, 'protection');
  19. if (style.border) {
  20. setIfExists(style, copied, 'border');
  21. setIfExists(style.border, copied.border, 'top', ['color']);
  22. setIfExists(style.border, copied.border, 'left', ['color']);
  23. setIfExists(style.border, copied.border, 'bottom', ['color']);
  24. setIfExists(style.border, copied.border, 'right', ['color']);
  25. setIfExists(style.border, copied.border, 'diagonal', ['color']);
  26. }
  27. if (style.fill) {
  28. setIfExists(style, copied, 'fill', ['fgColor', 'bgColor', 'center']);
  29. if (style.fill.stops) {
  30. copied.fill.stops = style.fill.stops.map(s => oneDepthCopy(s, ['color']));
  31. }
  32. }
  33. return copied;
  34. };
  35. exports.copyStyle = copyStyle;