getSizingData.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Reference to https://github.com/andreypopp/react-textarea-autosize/
  2. import { pick } from 'lodash-es';
  3. const SIZING_STYLE = [
  4. 'borderBottomWidth',
  5. 'borderLeftWidth',
  6. 'borderRightWidth',
  7. 'borderTopWidth',
  8. 'boxSizing',
  9. 'fontFamily',
  10. 'fontSize',
  11. 'fontStyle',
  12. 'fontWeight',
  13. 'letterSpacing',
  14. 'lineHeight',
  15. 'paddingBottom',
  16. 'paddingLeft',
  17. 'paddingRight',
  18. 'paddingTop',
  19. // non-standard
  20. 'tabSize',
  21. 'textIndent',
  22. // non-standard
  23. 'textRendering',
  24. 'textTransform',
  25. 'width',
  26. ];
  27. const getSizingData = (node: any) => {
  28. const style = window.getComputedStyle(node);
  29. if (style === null) {
  30. return null;
  31. }
  32. const sizingStyle = pick(style, SIZING_STYLE);
  33. const { boxSizing } = sizingStyle;
  34. // probably node is detached from DOM, can't read computed dimensions
  35. if (boxSizing === '') {
  36. return null;
  37. }
  38. const paddingSize =
  39. parseFloat(sizingStyle.paddingBottom) +
  40. parseFloat(sizingStyle.paddingTop);
  41. const borderSize =
  42. parseFloat(sizingStyle.borderBottomWidth) +
  43. parseFloat(sizingStyle.borderTopWidth);
  44. return {
  45. sizingStyle,
  46. paddingSize,
  47. borderSize,
  48. };
  49. };
  50. export default getSizingData;