numericRenderer.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import numbro from 'numbro';
  2. import { getRenderer } from './index';
  3. import { isNumeric } from './../helpers/number';
  4. /**
  5. * Numeric cell renderer
  6. *
  7. * @private
  8. * @renderer NumericRenderer
  9. * @param {Object} instance Handsontable instance
  10. * @param {Element} TD Table cell where to render
  11. * @param {Number} row
  12. * @param {Number} col
  13. * @param {String|Number} prop Row object property name
  14. * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
  15. * @param {Object} cellProperties Cell properties (shared by cell renderer and editor)
  16. */
  17. function numericRenderer(instance, TD, row, col, prop, value, cellProperties) {
  18. let newValue = value;
  19. if (isNumeric(newValue)) {
  20. const numericFormat = cellProperties.numericFormat;
  21. const cellCulture = numericFormat && numericFormat.culture || '-';
  22. const cellFormatPattern = numericFormat && numericFormat.pattern;
  23. const className = cellProperties.className || '';
  24. const classArr = className.length ? className.split(' ') : [];
  25. if (numericFormat && numericFormat.zeroFormat !== undefined) {
  26. numbro.zeroFormat(numericFormat.zeroFormat);
  27. } else {
  28. numbro.zeroFormat(null);
  29. }
  30. if (typeof cellCulture !== 'undefined' && !numbro.languages()[cellCulture]) {
  31. const shortTag = cellCulture.replace('-', '');
  32. const langData = numbro.allLanguages ? numbro.allLanguages[cellCulture] : numbro[shortTag];
  33. if (langData) {
  34. numbro.registerLanguage(langData);
  35. }
  36. }
  37. numbro.setLanguage(cellCulture);
  38. newValue = numbro(newValue).format(cellFormatPattern || '0');
  39. if (classArr.indexOf('htLeft') < 0 && classArr.indexOf('htCenter') < 0 &&
  40. classArr.indexOf('htRight') < 0 && classArr.indexOf('htJustify') < 0) {
  41. classArr.push('htRight');
  42. }
  43. if (classArr.indexOf('htNumeric') < 0) {
  44. classArr.push('htNumeric');
  45. }
  46. cellProperties.className = classArr.join(' ');
  47. }
  48. getRenderer('text')(instance, TD, row, col, prop, newValue, cellProperties);
  49. }
  50. export default numericRenderer;