WordcloudSeries.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /* *
  2. *
  3. * Experimental Highcharts module which enables visualization of a word cloud.
  4. *
  5. * (c) 2016-2021 Highsoft AS
  6. * Authors: Jon Arild Nygard
  7. *
  8. * License: www.highcharts.com/license
  9. *
  10. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  11. * */
  12. 'use strict';
  13. var __extends = (this && this.__extends) || (function () {
  14. var extendStatics = function (d, b) {
  15. extendStatics = Object.setPrototypeOf ||
  16. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  17. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  18. return extendStatics(d, b);
  19. };
  20. return function (d, b) {
  21. extendStatics(d, b);
  22. function __() { this.constructor = d; }
  23. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  24. };
  25. })();
  26. import H from '../../Core/Globals.js';
  27. var noop = H.noop;
  28. import PolygonMixin from '../../Mixins/Polygon.js';
  29. var getBoundingBoxFromPolygon = PolygonMixin.getBoundingBoxFromPolygon, getPolygon = PolygonMixin.getPolygon, isPolygonsColliding = PolygonMixin.isPolygonsColliding, rotate2DToOrigin = PolygonMixin.rotate2DToOrigin, rotate2DToPoint = PolygonMixin.rotate2DToPoint;
  30. import Series from '../../Core/Series/Series.js';
  31. import SeriesRegistry from '../../Core/Series/SeriesRegistry.js';
  32. var ColumnSeries = SeriesRegistry.seriesTypes.column;
  33. import U from '../../Core/Utilities.js';
  34. var extend = U.extend, find = U.find, isArray = U.isArray, isNumber = U.isNumber, isObject = U.isObject, merge = U.merge;
  35. import WordcloudPoint from './WordcloudPoint.js';
  36. import WordcloudUtils from './WordcloudUtils.js';
  37. /**
  38. * @private
  39. * @class
  40. * @name Highcharts.seriesTypes.wordcloud
  41. *
  42. * @augments Highcharts.Series
  43. */
  44. var WordcloudSeries = /** @class */ (function (_super) {
  45. __extends(WordcloudSeries, _super);
  46. function WordcloudSeries() {
  47. /* *
  48. *
  49. * Static properties
  50. *
  51. * */
  52. var _this = _super !== null && _super.apply(this, arguments) || this;
  53. /* *
  54. *
  55. * Properties
  56. *
  57. * */
  58. _this.data = void 0;
  59. _this.options = void 0;
  60. _this.points = void 0;
  61. return _this;
  62. }
  63. /**
  64. *
  65. * Functions
  66. *
  67. */
  68. WordcloudSeries.prototype.bindAxes = function () {
  69. var wordcloudAxis = {
  70. endOnTick: false,
  71. gridLineWidth: 0,
  72. lineWidth: 0,
  73. maxPadding: 0,
  74. startOnTick: false,
  75. title: null,
  76. tickPositions: []
  77. };
  78. Series.prototype.bindAxes.call(this);
  79. extend(this.yAxis.options, wordcloudAxis);
  80. extend(this.xAxis.options, wordcloudAxis);
  81. };
  82. WordcloudSeries.prototype.pointAttribs = function (point, state) {
  83. var attribs = H.seriesTypes.column.prototype
  84. .pointAttribs.call(this, point, state);
  85. delete attribs.stroke;
  86. delete attribs['stroke-width'];
  87. return attribs;
  88. };
  89. /**
  90. * Calculates the fontSize of a word based on its weight.
  91. *
  92. * @private
  93. * @function Highcharts.Series#deriveFontSize
  94. *
  95. * @param {number} [relativeWeight=0]
  96. * The weight of the word, on a scale 0-1.
  97. *
  98. * @param {number} [maxFontSize=1]
  99. * The maximum font size of a word.
  100. *
  101. * @param {number} [minFontSize=1]
  102. * The minimum font size of a word.
  103. *
  104. * @return {number}
  105. * Returns the resulting fontSize of a word. If minFontSize is larger then
  106. * maxFontSize the result will equal minFontSize.
  107. */
  108. WordcloudSeries.prototype.deriveFontSize = function (relativeWeight, maxFontSize, minFontSize) {
  109. var weight = isNumber(relativeWeight) ? relativeWeight : 0, max = isNumber(maxFontSize) ? maxFontSize : 1, min = isNumber(minFontSize) ? minFontSize : 1;
  110. return Math.floor(Math.max(min, weight * max));
  111. };
  112. WordcloudSeries.prototype.drawPoints = function () {
  113. var series = this, hasRendered = series.hasRendered, xAxis = series.xAxis, yAxis = series.yAxis, chart = series.chart, group = series.group, options = series.options, animation = options.animation, allowExtendPlayingField = options.allowExtendPlayingField, renderer = chart.renderer, testElement = renderer.text().add(group), placed = [], placementStrategy = series.placementStrategy[options.placementStrategy], spiral, rotation = options.rotation, scale, weights = series.points.map(function (p) {
  114. return p.weight;
  115. }), maxWeight = Math.max.apply(null, weights),
  116. // concat() prevents from sorting the original array.
  117. data = series.points.concat().sort(function (a, b) {
  118. return b.weight - a.weight; // Sort descending
  119. }), field;
  120. // Reset the scale before finding the dimensions (#11993).
  121. // SVGGRaphicsElement.getBBox() (used in SVGElement.getBBox(boolean))
  122. // returns slightly different values for the same element depending on
  123. // whether it is rendered in a group which has already defined scale
  124. // (e.g. 6) or in the group without a scale (scale = 1).
  125. series.group.attr({
  126. scaleX: 1,
  127. scaleY: 1
  128. });
  129. // Get the dimensions for each word.
  130. // Used in calculating the playing field.
  131. data.forEach(function (point) {
  132. var relativeWeight = 1 / maxWeight * point.weight, fontSize = series.deriveFontSize(relativeWeight, options.maxFontSize, options.minFontSize), css = extend({
  133. fontSize: fontSize + 'px'
  134. }, options.style), bBox;
  135. testElement.css(css).attr({
  136. x: 0,
  137. y: 0,
  138. text: point.name
  139. });
  140. bBox = testElement.getBBox(true);
  141. point.dimensions = {
  142. height: bBox.height,
  143. width: bBox.width
  144. };
  145. });
  146. // Calculate the playing field.
  147. field = WordcloudUtils.getPlayingField(xAxis.len, yAxis.len, data);
  148. spiral = WordcloudUtils.getSpiral(series.spirals[options.spiral], {
  149. field: field
  150. });
  151. // Draw all the points.
  152. data.forEach(function (point) {
  153. var relativeWeight = 1 / maxWeight * point.weight, fontSize = series.deriveFontSize(relativeWeight, options.maxFontSize, options.minFontSize), css = extend({
  154. fontSize: fontSize + 'px'
  155. }, options.style), placement = placementStrategy(point, {
  156. data: data,
  157. field: field,
  158. placed: placed,
  159. rotation: rotation
  160. }), attr = extend(series.pointAttribs(point, (point.selected && 'select')), {
  161. align: 'center',
  162. 'alignment-baseline': 'middle',
  163. x: placement.x,
  164. y: placement.y,
  165. text: point.name,
  166. rotation: placement.rotation
  167. }), polygon = getPolygon(placement.x, placement.y, point.dimensions.width, point.dimensions.height, placement.rotation), rectangle = getBoundingBoxFromPolygon(polygon), delta = WordcloudUtils.intersectionTesting(point, {
  168. rectangle: rectangle,
  169. polygon: polygon,
  170. field: field,
  171. placed: placed,
  172. spiral: spiral,
  173. rotation: placement.rotation
  174. }), animate;
  175. // If there is no space for the word, extend the playing field.
  176. if (!delta && allowExtendPlayingField) {
  177. // Extend the playing field to fit the word.
  178. field = WordcloudUtils.extendPlayingField(field, rectangle);
  179. // Run intersection testing one more time to place the word.
  180. delta = WordcloudUtils.intersectionTesting(point, {
  181. rectangle: rectangle,
  182. polygon: polygon,
  183. field: field,
  184. placed: placed,
  185. spiral: spiral,
  186. rotation: placement.rotation
  187. });
  188. }
  189. // Check if point was placed, if so delete it, otherwise place it
  190. // on the correct positions.
  191. if (isObject(delta)) {
  192. attr.x += delta.x;
  193. attr.y += delta.y;
  194. rectangle.left += delta.x;
  195. rectangle.right += delta.x;
  196. rectangle.top += delta.y;
  197. rectangle.bottom += delta.y;
  198. field = WordcloudUtils.updateFieldBoundaries(field, rectangle);
  199. placed.push(point);
  200. point.isNull = false;
  201. }
  202. else {
  203. point.isNull = true;
  204. }
  205. if (animation) {
  206. // Animate to new positions
  207. animate = {
  208. x: attr.x,
  209. y: attr.y
  210. };
  211. // Animate from center of chart
  212. if (!hasRendered) {
  213. attr.x = 0;
  214. attr.y = 0;
  215. // or animate from previous position
  216. }
  217. else {
  218. delete attr.x;
  219. delete attr.y;
  220. }
  221. }
  222. point.draw({
  223. animatableAttribs: animate,
  224. attribs: attr,
  225. css: css,
  226. group: group,
  227. renderer: renderer,
  228. shapeArgs: void 0,
  229. shapeType: 'text'
  230. });
  231. });
  232. // Destroy the element after use.
  233. testElement = testElement.destroy();
  234. // Scale the series group to fit within the plotArea.
  235. scale = WordcloudUtils.getScale(xAxis.len, yAxis.len, field);
  236. series.group.attr({
  237. scaleX: scale,
  238. scaleY: scale
  239. });
  240. };
  241. WordcloudSeries.prototype.hasData = function () {
  242. var series = this;
  243. return (isObject(series) &&
  244. series.visible === true &&
  245. isArray(series.points) &&
  246. series.points.length > 0);
  247. };
  248. WordcloudSeries.prototype.getPlotBox = function () {
  249. var series = this, chart = series.chart, inverted = chart.inverted,
  250. // Swap axes for inverted (#2339)
  251. xAxis = series[(inverted ? 'yAxis' : 'xAxis')], yAxis = series[(inverted ? 'xAxis' : 'yAxis')], width = xAxis ? xAxis.len : chart.plotWidth, height = yAxis ? yAxis.len : chart.plotHeight, x = xAxis ? xAxis.left : chart.plotLeft, y = yAxis ? yAxis.top : chart.plotTop;
  252. return {
  253. translateX: x + (width / 2),
  254. translateY: y + (height / 2),
  255. scaleX: 1,
  256. scaleY: 1
  257. };
  258. };
  259. /**
  260. * A word cloud is a visualization of a set of words, where the size and
  261. * placement of a word is determined by how it is weighted.
  262. *
  263. * @sample highcharts/demo/wordcloud
  264. * Word Cloud chart
  265. *
  266. * @extends plotOptions.column
  267. * @excluding allAreas, boostThreshold, clip, colorAxis, compare,
  268. * compareBase, crisp, cropTreshold, dataGrouping, dataLabels,
  269. * depth, dragDrop, edgeColor, findNearestPointBy,
  270. * getExtremesFromAll, grouping, groupPadding, groupZPadding,
  271. * joinBy, maxPointWidth, minPointLength, navigatorOptions,
  272. * negativeColor, pointInterval, pointIntervalUnit,
  273. * pointPadding, pointPlacement, pointRange, pointStart,
  274. * pointWidth, pointStart, pointWidth, shadow, showCheckbox,
  275. * showInNavigator, softThreshold, stacking, threshold,
  276. * zoneAxis, zones, dataSorting, boostBlending
  277. * @product highcharts
  278. * @since 6.0.0
  279. * @requires modules/wordcloud
  280. * @optionparent plotOptions.wordcloud
  281. */
  282. WordcloudSeries.defaultOptions = merge(ColumnSeries.defaultOptions, {
  283. /**
  284. * If there is no space for a word on the playing field, then this
  285. * option will allow the playing field to be extended to fit the word.
  286. * If false then the word will be dropped from the visualization.
  287. *
  288. * NB! This option is currently not decided to be published in the API,
  289. * and is therefore marked as private.
  290. *
  291. * @private
  292. */
  293. allowExtendPlayingField: true,
  294. animation: {
  295. /** @internal */
  296. duration: 500
  297. },
  298. borderWidth: 0,
  299. clip: false,
  300. colorByPoint: true,
  301. /**
  302. * A threshold determining the minimum font size that can be applied to
  303. * a word.
  304. */
  305. minFontSize: 1,
  306. /**
  307. * The word with the largest weight will have a font size equal to this
  308. * value. The font size of a word is the ratio between its weight and
  309. * the largest occuring weight, multiplied with the value of
  310. * maxFontSize.
  311. */
  312. maxFontSize: 25,
  313. /**
  314. * This option decides which algorithm is used for placement, and
  315. * rotation of a word. The choice of algorith is therefore a crucial
  316. * part of the resulting layout of the wordcloud. It is possible for
  317. * users to add their own custom placement strategies for use in word
  318. * cloud. Read more about it in our
  319. * [documentation](https://www.highcharts.com/docs/chart-and-series-types/word-cloud-series#custom-placement-strategies)
  320. *
  321. * @validvalue: ["center", "random"]
  322. */
  323. placementStrategy: 'center',
  324. /**
  325. * Rotation options for the words in the wordcloud.
  326. *
  327. * @sample highcharts/plotoptions/wordcloud-rotation
  328. * Word cloud with rotation
  329. */
  330. rotation: {
  331. /**
  332. * The smallest degree of rotation for a word.
  333. */
  334. from: 0,
  335. /**
  336. * The number of possible orientations for a word, within the range
  337. * of `rotation.from` and `rotation.to`. Must be a number larger
  338. * than 0.
  339. */
  340. orientations: 2,
  341. /**
  342. * The largest degree of rotation for a word.
  343. */
  344. to: 90
  345. },
  346. showInLegend: false,
  347. /**
  348. * Spiral used for placing a word after the initial position
  349. * experienced a collision with either another word or the borders.
  350. * It is possible for users to add their own custom spiralling
  351. * algorithms for use in word cloud. Read more about it in our
  352. * [documentation](https://www.highcharts.com/docs/chart-and-series-types/word-cloud-series#custom-spiralling-algorithm)
  353. *
  354. * @validvalue: ["archimedean", "rectangular", "square"]
  355. */
  356. spiral: 'rectangular',
  357. /**
  358. * CSS styles for the words.
  359. *
  360. * @type {Highcharts.CSSObject}
  361. * @default {"fontFamily":"sans-serif", "fontWeight": "900"}
  362. */
  363. style: {
  364. /** @ignore-option */
  365. fontFamily: 'sans-serif',
  366. /** @ignore-option */
  367. fontWeight: '900',
  368. /** @ignore-option */
  369. whiteSpace: 'nowrap'
  370. },
  371. tooltip: {
  372. followPointer: true,
  373. pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.weight}</b><br/>'
  374. }
  375. });
  376. return WordcloudSeries;
  377. }(ColumnSeries));
  378. extend(WordcloudSeries.prototype, {
  379. animate: Series.prototype.animate,
  380. animateDrilldown: noop,
  381. animateDrillupFrom: noop,
  382. pointClass: WordcloudPoint,
  383. setClip: noop,
  384. // Strategies used for deciding rotation and initial position of a word. To
  385. // implement a custom strategy, have a look at the function random for
  386. // example.
  387. placementStrategy: {
  388. random: function (point, options) {
  389. var field = options.field, r = options.rotation;
  390. return {
  391. x: WordcloudUtils.getRandomPosition(field.width) - (field.width / 2),
  392. y: WordcloudUtils.getRandomPosition(field.height) - (field.height / 2),
  393. rotation: WordcloudUtils.getRotation(r.orientations, point.index, r.from, r.to)
  394. };
  395. },
  396. center: function (point, options) {
  397. var r = options.rotation;
  398. return {
  399. x: 0,
  400. y: 0,
  401. rotation: WordcloudUtils.getRotation(r.orientations, point.index, r.from, r.to)
  402. };
  403. }
  404. },
  405. pointArrayMap: ['weight'],
  406. // Spirals used for placing a word after the initial position experienced a
  407. // collision with either another word or the borders. To implement a custom
  408. // spiral, look at the function archimedeanSpiral for example.
  409. spirals: {
  410. 'archimedean': WordcloudUtils.archimedeanSpiral,
  411. 'rectangular': WordcloudUtils.rectangularSpiral,
  412. 'square': WordcloudUtils.squareSpiral
  413. },
  414. utils: {
  415. extendPlayingField: WordcloudUtils.extendPlayingField,
  416. getRotation: WordcloudUtils.getRotation,
  417. isPolygonsColliding: isPolygonsColliding,
  418. rotate2DToOrigin: rotate2DToOrigin,
  419. rotate2DToPoint: rotate2DToPoint
  420. }
  421. });
  422. SeriesRegistry.registerSeriesType('wordcloud', WordcloudSeries);
  423. /* *
  424. *
  425. * Export Default
  426. *
  427. * */
  428. export default WordcloudSeries;
  429. /* *
  430. *
  431. * API Options
  432. *
  433. * */
  434. /**
  435. * A `wordcloud` series. If the [type](#series.wordcloud.type) option is not
  436. * specified, it is inherited from [chart.type](#chart.type).
  437. *
  438. * @extends series,plotOptions.wordcloud
  439. * @exclude dataSorting, boostThreshold, boostBlending
  440. * @product highcharts
  441. * @requires modules/wordcloud
  442. * @apioption series.wordcloud
  443. */
  444. /**
  445. * An array of data points for the series. For the `wordcloud` series type,
  446. * points can be given in the following ways:
  447. *
  448. * 1. An array of arrays with 2 values. In this case, the values correspond to
  449. * `name,weight`.
  450. * ```js
  451. * data: [
  452. * ['Lorem', 4],
  453. * ['Ipsum', 1]
  454. * ]
  455. * ```
  456. *
  457. * 2. An array of objects with named values. The following snippet shows only a
  458. * few settings, see the complete options set below. If the total number of
  459. * data points exceeds the series'
  460. * [turboThreshold](#series.arearange.turboThreshold), this option is not
  461. * available.
  462. * ```js
  463. * data: [{
  464. * name: "Lorem",
  465. * weight: 4
  466. * }, {
  467. * name: "Ipsum",
  468. * weight: 1
  469. * }]
  470. * ```
  471. *
  472. * @type {Array<Array<string,number>|*>}
  473. * @extends series.line.data
  474. * @excluding drilldown, marker, x, y
  475. * @product highcharts
  476. * @apioption series.wordcloud.data
  477. */
  478. /**
  479. * The name decides the text for a word.
  480. *
  481. * @type {string}
  482. * @since 6.0.0
  483. * @product highcharts
  484. * @apioption series.sunburst.data.name
  485. */
  486. /**
  487. * The weighting of a word. The weight decides the relative size of a word
  488. * compared to the rest of the collection.
  489. *
  490. * @type {number}
  491. * @since 6.0.0
  492. * @product highcharts
  493. * @apioption series.sunburst.data.weight
  494. */
  495. ''; // detach doclets above