TextRenderer.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import { assign } from 'min-dash';
  2. import TextUtil from 'diagram-js/lib/util/Text';
  3. var DEFAULT_FONT_SIZE = 12;
  4. var LINE_HEIGHT_RATIO = 1.2;
  5. var MIN_TEXT_ANNOTATION_HEIGHT = 30;
  6. export default function TextRenderer(config) {
  7. var defaultStyle = assign({
  8. fontFamily: 'Arial, sans-serif',
  9. fontSize: DEFAULT_FONT_SIZE,
  10. fontWeight: 'normal',
  11. lineHeight: LINE_HEIGHT_RATIO
  12. }, config && config.defaultStyle || {});
  13. var fontSize = parseInt(defaultStyle.fontSize, 10) - 1;
  14. var externalStyle = assign({}, defaultStyle, {
  15. fontSize: fontSize
  16. }, config && config.externalStyle || {});
  17. var textUtil = new TextUtil({
  18. style: defaultStyle
  19. });
  20. /**
  21. * Get the new bounds of an externally rendered,
  22. * layouted label.
  23. *
  24. * @param {Bounds} bounds
  25. * @param {string} text
  26. *
  27. * @return {Bounds}
  28. */
  29. this.getExternalLabelBounds = function(bounds, text) {
  30. var layoutedDimensions = textUtil.getDimensions(text, {
  31. box: {
  32. width: 90,
  33. height: 30,
  34. x: bounds.width / 2 + bounds.x,
  35. y: bounds.height / 2 + bounds.y
  36. },
  37. style: externalStyle
  38. });
  39. // resize label shape to fit label text
  40. return {
  41. x: Math.round(bounds.x + bounds.width / 2 - layoutedDimensions.width / 2),
  42. y: Math.round(bounds.y),
  43. width: Math.ceil(layoutedDimensions.width),
  44. height: Math.ceil(layoutedDimensions.height)
  45. };
  46. };
  47. /**
  48. * Get the new bounds of text annotation.
  49. *
  50. * @param {Bounds} bounds
  51. * @param {string} text
  52. *
  53. * @return {Bounds}
  54. */
  55. this.getTextAnnotationBounds = function(bounds, text) {
  56. var layoutedDimensions = textUtil.getDimensions(text, {
  57. box: bounds,
  58. style: defaultStyle,
  59. align: 'left-top',
  60. padding: 5
  61. });
  62. return {
  63. x: bounds.x,
  64. y: bounds.y,
  65. width: bounds.width,
  66. height: Math.max(MIN_TEXT_ANNOTATION_HEIGHT, Math.round(layoutedDimensions.height))
  67. };
  68. };
  69. /**
  70. * Create a layouted text element.
  71. *
  72. * @param {string} text
  73. * @param {Object} [options]
  74. *
  75. * @return {SVGElement} rendered text
  76. */
  77. this.createText = function(text, options) {
  78. return textUtil.createText(text, options || {});
  79. };
  80. /**
  81. * Get default text style.
  82. */
  83. this.getDefaultStyle = function() {
  84. return defaultStyle;
  85. };
  86. /**
  87. * Get the external text style.
  88. */
  89. this.getExternalStyle = function() {
  90. return externalStyle;
  91. };
  92. }
  93. TextRenderer.$inject = [
  94. 'config.textRenderer'
  95. ];