wordcloud.src.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. /* *
  2. *
  3. * Experimental Highcharts module which enables visualization of a word cloud.
  4. *
  5. * (c) 2016-2020 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. import H from '../parts/Globals.js';
  14. import U from '../parts/Utilities.js';
  15. var extend = U.extend, find = U.find, isArray = U.isArray, isNumber = U.isNumber, isObject = U.isObject, merge = U.merge, seriesType = U.seriesType;
  16. import drawPoint from '../mixins/draw-point.js';
  17. import polygon from '../mixins/polygon.js';
  18. import '../parts/Series.js';
  19. var noop = H.noop, getBoundingBoxFromPolygon = polygon.getBoundingBoxFromPolygon, getPolygon = polygon.getPolygon, isPolygonsColliding = polygon.isPolygonsColliding, movePolygon = polygon.movePolygon, Series = H.Series;
  20. /**
  21. * Detects if there is a collision between two rectangles.
  22. *
  23. * @private
  24. * @function isRectanglesIntersecting
  25. *
  26. * @param {Highcharts.PolygonBoxObject} r1
  27. * First rectangle.
  28. *
  29. * @param {Highcharts.PolygonBoxObject} r2
  30. * Second rectangle.
  31. *
  32. * @return {boolean}
  33. * Returns true if the rectangles overlap.
  34. */
  35. function isRectanglesIntersecting(r1, r2) {
  36. return !(r2.left > r1.right ||
  37. r2.right < r1.left ||
  38. r2.top > r1.bottom ||
  39. r2.bottom < r1.top);
  40. }
  41. /**
  42. * Detects if a word collides with any previously placed words.
  43. *
  44. * @private
  45. * @function intersectsAnyWord
  46. *
  47. * @param {Highcharts.Point} point
  48. * Point which the word is connected to.
  49. *
  50. * @param {Array<Highcharts.Point>} points
  51. * Previously placed points to check against.
  52. *
  53. * @return {boolean}
  54. * Returns true if there is collision.
  55. */
  56. function intersectsAnyWord(point, points) {
  57. var intersects = false, rect = point.rect, polygon = point.polygon, lastCollidedWith = point.lastCollidedWith, isIntersecting = function (p) {
  58. var result = isRectanglesIntersecting(rect, p.rect);
  59. if (result &&
  60. (point.rotation % 90 || p.rotation % 90)) {
  61. result = isPolygonsColliding(polygon, p.polygon);
  62. }
  63. return result;
  64. };
  65. // If the point has already intersected a different point, chances are they
  66. // are still intersecting. So as an enhancement we check this first.
  67. if (lastCollidedWith) {
  68. intersects = isIntersecting(lastCollidedWith);
  69. // If they no longer intersects, remove the cache from the point.
  70. if (!intersects) {
  71. delete point.lastCollidedWith;
  72. }
  73. }
  74. // If not already found, then check if we can find a point that is
  75. // intersecting.
  76. if (!intersects) {
  77. intersects = !!find(points, function (p) {
  78. var result = isIntersecting(p);
  79. if (result) {
  80. point.lastCollidedWith = p;
  81. }
  82. return result;
  83. });
  84. }
  85. return intersects;
  86. }
  87. /**
  88. * Gives a set of cordinates for an Archimedian Spiral.
  89. *
  90. * @private
  91. * @function archimedeanSpiral
  92. *
  93. * @param {number} attempt
  94. * How far along the spiral we have traversed.
  95. *
  96. * @param {Highcharts.WordcloudSpiralParamsObject} [params]
  97. * Additional parameters.
  98. *
  99. * @return {boolean|Highcharts.PositionObject}
  100. * Resulting coordinates, x and y. False if the word should be dropped from the
  101. * visualization.
  102. */
  103. function archimedeanSpiral(attempt, params) {
  104. var field = params.field, result = false, maxDelta = (field.width * field.width) + (field.height * field.height), t = attempt * 0.8; // 0.2 * 4 = 0.8. Enlarging the spiral.
  105. // Emergency brake. TODO make spiralling logic more foolproof.
  106. if (attempt <= 10000) {
  107. result = {
  108. x: t * Math.cos(t),
  109. y: t * Math.sin(t)
  110. };
  111. if (!(Math.min(Math.abs(result.x), Math.abs(result.y)) < maxDelta)) {
  112. result = false;
  113. }
  114. }
  115. return result;
  116. }
  117. /**
  118. * Gives a set of cordinates for an rectangular spiral.
  119. *
  120. * @private
  121. * @function squareSpiral
  122. *
  123. * @param {number} attempt
  124. * How far along the spiral we have traversed.
  125. *
  126. * @param {Highcharts.WordcloudSpiralParamsObject} [params]
  127. * Additional parameters.
  128. *
  129. * @return {boolean|Highcharts.PositionObject}
  130. * Resulting coordinates, x and y. False if the word should be dropped from the
  131. * visualization.
  132. */
  133. function squareSpiral(attempt, params) {
  134. var a = attempt * 4, k = Math.ceil((Math.sqrt(a) - 1) / 2), t = 2 * k + 1, m = Math.pow(t, 2), isBoolean = function (x) {
  135. return typeof x === 'boolean';
  136. }, result = false;
  137. t -= 1;
  138. if (attempt <= 10000) {
  139. if (isBoolean(result) && a >= m - t) {
  140. result = {
  141. x: k - (m - a),
  142. y: -k
  143. };
  144. }
  145. m -= t;
  146. if (isBoolean(result) && a >= m - t) {
  147. result = {
  148. x: -k,
  149. y: -k + (m - a)
  150. };
  151. }
  152. m -= t;
  153. if (isBoolean(result)) {
  154. if (a >= m - t) {
  155. result = {
  156. x: -k + (m - a),
  157. y: k
  158. };
  159. }
  160. else {
  161. result = {
  162. x: k,
  163. y: k - (m - a - t)
  164. };
  165. }
  166. }
  167. result.x *= 5;
  168. result.y *= 5;
  169. }
  170. return result;
  171. }
  172. /**
  173. * Gives a set of cordinates for an rectangular spiral.
  174. *
  175. * @private
  176. * @function rectangularSpiral
  177. *
  178. * @param {number} attempt
  179. * How far along the spiral we have traversed.
  180. *
  181. * @param {Highcharts.WordcloudSpiralParamsObject} [params]
  182. * Additional parameters.
  183. *
  184. * @return {boolean|Higcharts.PositionObject}
  185. * Resulting coordinates, x and y. False if the word should be dropped from the
  186. * visualization.
  187. */
  188. function rectangularSpiral(attempt, params) {
  189. var result = squareSpiral(attempt, params), field = params.field;
  190. if (result) {
  191. result.x *= field.ratioX;
  192. result.y *= field.ratioY;
  193. }
  194. return result;
  195. }
  196. /**
  197. * @private
  198. * @function getRandomPosition
  199. *
  200. * @param {number} size
  201. * Random factor.
  202. *
  203. * @return {number}
  204. * Random position.
  205. */
  206. function getRandomPosition(size) {
  207. return Math.round((size * (Math.random() + 0.5)) / 2);
  208. }
  209. /**
  210. * Calculates the proper scale to fit the cloud inside the plotting area.
  211. *
  212. * @private
  213. * @function getScale
  214. *
  215. * @param {number} targetWidth
  216. * Width of target area.
  217. *
  218. * @param {number} targetHeight
  219. * Height of target area.
  220. *
  221. * @param {object} field
  222. * The playing field.
  223. *
  224. * @param {Highcharts.Series} series
  225. * Series object.
  226. *
  227. * @return {number}
  228. * Returns the value to scale the playing field up to the size of the target
  229. * area.
  230. */
  231. function getScale(targetWidth, targetHeight, field) {
  232. var height = Math.max(Math.abs(field.top), Math.abs(field.bottom)) * 2, width = Math.max(Math.abs(field.left), Math.abs(field.right)) * 2, scaleX = width > 0 ? 1 / width * targetWidth : 1, scaleY = height > 0 ? 1 / height * targetHeight : 1;
  233. return Math.min(scaleX, scaleY);
  234. }
  235. /**
  236. * Calculates what is called the playing field. The field is the area which all
  237. * the words are allowed to be positioned within. The area is proportioned to
  238. * match the target aspect ratio.
  239. *
  240. * @private
  241. * @function getPlayingField
  242. *
  243. * @param {number} targetWidth
  244. * Width of the target area.
  245. *
  246. * @param {number} targetHeight
  247. * Height of the target area.
  248. *
  249. * @param {Array<Highcharts.Point>} data
  250. * Array of points.
  251. *
  252. * @param {object} data.dimensions
  253. * The height and width of the word.
  254. *
  255. * @return {object}
  256. * The width and height of the playing field.
  257. */
  258. function getPlayingField(targetWidth, targetHeight, data) {
  259. var info = data.reduce(function (obj, point) {
  260. var dimensions = point.dimensions, x = Math.max(dimensions.width, dimensions.height);
  261. // Find largest height.
  262. obj.maxHeight = Math.max(obj.maxHeight, dimensions.height);
  263. // Find largest width.
  264. obj.maxWidth = Math.max(obj.maxWidth, dimensions.width);
  265. // Sum up the total maximum area of all the words.
  266. obj.area += x * x;
  267. return obj;
  268. }, {
  269. maxHeight: 0,
  270. maxWidth: 0,
  271. area: 0
  272. }),
  273. /**
  274. * Use largest width, largest height, or root of total area to give size
  275. * to the playing field.
  276. */
  277. x = Math.max(info.maxHeight, // Have enough space for the tallest word
  278. info.maxWidth, // Have enough space for the broadest word
  279. // Adjust 15% to account for close packing of words
  280. Math.sqrt(info.area) * 0.85), ratioX = targetWidth > targetHeight ? targetWidth / targetHeight : 1, ratioY = targetHeight > targetWidth ? targetHeight / targetWidth : 1;
  281. return {
  282. width: x * ratioX,
  283. height: x * ratioY,
  284. ratioX: ratioX,
  285. ratioY: ratioY
  286. };
  287. }
  288. /**
  289. * Calculates a number of degrees to rotate, based upon a number of orientations
  290. * within a range from-to.
  291. *
  292. * @private
  293. * @function getRotation
  294. *
  295. * @param {number} [orientations]
  296. * Number of orientations.
  297. *
  298. * @param {number} [index]
  299. * Index of point, used to decide orientation.
  300. *
  301. * @param {number} [from]
  302. * The smallest degree of rotation.
  303. *
  304. * @param {number} [to]
  305. * The largest degree of rotation.
  306. *
  307. * @return {boolean|number}
  308. * Returns the resulting rotation for the word. Returns false if invalid input
  309. * parameters.
  310. */
  311. function getRotation(orientations, index, from, to) {
  312. var result = false, // Default to false
  313. range, intervals, orientation;
  314. // Check if we have valid input parameters.
  315. if (isNumber(orientations) &&
  316. isNumber(index) &&
  317. isNumber(from) &&
  318. isNumber(to) &&
  319. orientations > 0 &&
  320. index > -1 &&
  321. to > from) {
  322. range = to - from;
  323. intervals = range / (orientations - 1 || 1);
  324. orientation = index % orientations;
  325. result = from + (orientation * intervals);
  326. }
  327. return result;
  328. }
  329. /**
  330. * Calculates the spiral positions and store them in scope for quick access.
  331. *
  332. * @private
  333. * @function getSpiral
  334. *
  335. * @param {Function} fn
  336. * The spiral function.
  337. *
  338. * @param {object} params
  339. * Additional parameters for the spiral.
  340. *
  341. * @return {Function}
  342. * Function with access to spiral positions.
  343. */
  344. function getSpiral(fn, params) {
  345. var length = 10000, i, arr = [];
  346. for (i = 1; i < length; i++) {
  347. arr.push(fn(i, params)); // @todo unnecessary amount of precaclulation
  348. }
  349. return function (attempt) {
  350. return attempt <= length ? arr[attempt - 1] : false;
  351. };
  352. }
  353. /**
  354. * Detects if a word is placed outside the playing field.
  355. *
  356. * @private
  357. * @function outsidePlayingField
  358. *
  359. * @param {Highcharts.PolygonBoxObject} rect
  360. * The word box.
  361. *
  362. * @param {Highcharts.WordcloudFieldObject} field
  363. * The width and height of the playing field.
  364. *
  365. * @return {boolean}
  366. * Returns true if the word is placed outside the field.
  367. */
  368. function outsidePlayingField(rect, field) {
  369. var playingField = {
  370. left: -(field.width / 2),
  371. right: field.width / 2,
  372. top: -(field.height / 2),
  373. bottom: field.height / 2
  374. };
  375. return !(playingField.left < rect.left &&
  376. playingField.right > rect.right &&
  377. playingField.top < rect.top &&
  378. playingField.bottom > rect.bottom);
  379. }
  380. /**
  381. * Check if a point intersects with previously placed words, or if it goes
  382. * outside the field boundaries. If a collision, then try to adjusts the
  383. * position.
  384. *
  385. * @private
  386. * @function intersectionTesting
  387. *
  388. * @param {Highcharts.Point} point
  389. * Point to test for intersections.
  390. *
  391. * @param {Highcharts.WordcloudTestOptionsObject} options
  392. * Options object.
  393. *
  394. * @return {boolean|Highcharts.PositionObject}
  395. * Returns an object with how much to correct the positions. Returns false if
  396. * the word should not be placed at all.
  397. */
  398. function intersectionTesting(point, options) {
  399. var placed = options.placed, field = options.field, rectangle = options.rectangle, polygon = options.polygon, spiral = options.spiral, attempt = 1, delta = {
  400. x: 0,
  401. y: 0
  402. },
  403. // Make a copy to update values during intersection testing.
  404. rect = point.rect = extend({}, rectangle);
  405. point.polygon = polygon;
  406. point.rotation = options.rotation;
  407. /* while w intersects any previously placed words:
  408. do {
  409. move w a little bit along a spiral path
  410. } while any part of w is outside the playing field and
  411. the spiral radius is still smallish */
  412. while (delta !== false &&
  413. (intersectsAnyWord(point, placed) ||
  414. outsidePlayingField(rect, field))) {
  415. delta = spiral(attempt);
  416. if (isObject(delta)) {
  417. // Update the DOMRect with new positions.
  418. rect.left = rectangle.left + delta.x;
  419. rect.right = rectangle.right + delta.x;
  420. rect.top = rectangle.top + delta.y;
  421. rect.bottom = rectangle.bottom + delta.y;
  422. point.polygon = movePolygon(delta.x, delta.y, polygon);
  423. }
  424. attempt++;
  425. }
  426. return delta;
  427. }
  428. /**
  429. * Extends the playing field to have enough space to fit a given word.
  430. *
  431. * @private
  432. * @function extendPlayingField
  433. *
  434. * @param {Highcharts.WordcloudFieldObject} field
  435. * The width, height and ratios of a playing field.
  436. *
  437. * @param {Highcharts.PolygonBoxObject} rectangle
  438. * The bounding box of the word to add space for.
  439. *
  440. * @return {Highcharts.WordcloudFieldObject}
  441. * Returns the extended playing field with updated height and width.
  442. */
  443. function extendPlayingField(field, rectangle) {
  444. var height, width, ratioX, ratioY, x, extendWidth, extendHeight, result;
  445. if (isObject(field) && isObject(rectangle)) {
  446. height = (rectangle.bottom - rectangle.top);
  447. width = (rectangle.right - rectangle.left);
  448. ratioX = field.ratioX;
  449. ratioY = field.ratioY;
  450. // Use the same variable to extend both the height and width.
  451. x = ((width * ratioX) > (height * ratioY)) ? width : height;
  452. // Multiply variable with ratios to preserve aspect ratio.
  453. extendWidth = x * ratioX;
  454. extendHeight = x * ratioY;
  455. // Calculate the size of the new field after adding space for the word.
  456. result = merge(field, {
  457. // Add space on the left and right.
  458. width: field.width + (extendWidth * 2),
  459. // Add space on the top and bottom.
  460. height: field.height + (extendHeight * 2)
  461. });
  462. }
  463. else {
  464. result = field;
  465. }
  466. // Return the new extended field.
  467. return result;
  468. }
  469. /**
  470. * If a rectangle is outside a give field, then the boundaries of the field is
  471. * adjusted accordingly. Modifies the field object which is passed as the first
  472. * parameter.
  473. *
  474. * @private
  475. * @function updateFieldBoundaries
  476. *
  477. * @param {Highcharts.WordcloudFieldObject} field
  478. * The bounding box of a playing field.
  479. *
  480. * @param {Highcharts.PolygonBoxObject} rectangle
  481. * The bounding box for a placed point.
  482. *
  483. * @return {Highcharts.WordcloudFieldObject}
  484. * Returns a modified field object.
  485. */
  486. function updateFieldBoundaries(field, rectangle) {
  487. // @todo improve type checking.
  488. if (!isNumber(field.left) || field.left > rectangle.left) {
  489. field.left = rectangle.left;
  490. }
  491. if (!isNumber(field.right) || field.right < rectangle.right) {
  492. field.right = rectangle.right;
  493. }
  494. if (!isNumber(field.top) || field.top > rectangle.top) {
  495. field.top = rectangle.top;
  496. }
  497. if (!isNumber(field.bottom) || field.bottom < rectangle.bottom) {
  498. field.bottom = rectangle.bottom;
  499. }
  500. return field;
  501. }
  502. /**
  503. * A word cloud is a visualization of a set of words, where the size and
  504. * placement of a word is determined by how it is weighted.
  505. *
  506. * @sample highcharts/demo/wordcloud
  507. * Word Cloud chart
  508. *
  509. * @extends plotOptions.column
  510. * @excluding allAreas, boostThreshold, clip, colorAxis, compare,
  511. * compareBase, crisp, cropTreshold, dataGrouping, dataLabels,
  512. * depth, dragDrop, edgeColor, findNearestPointBy,
  513. * getExtremesFromAll, grouping, groupPadding, groupZPadding,
  514. * joinBy, maxPointWidth, minPointLength, navigatorOptions,
  515. * negativeColor, pointInterval, pointIntervalUnit, pointPadding,
  516. * pointPlacement, pointRange, pointStart, pointWidth, pointStart,
  517. * pointWidth, shadow, showCheckbox, showInNavigator,
  518. * softThreshold, stacking, threshold, zoneAxis, zones,
  519. * dataSorting
  520. * @product highcharts
  521. * @since 6.0.0
  522. * @requires modules/wordcloud
  523. * @optionparent plotOptions.wordcloud
  524. */
  525. var wordCloudOptions = {
  526. /**
  527. * If there is no space for a word on the playing field, then this option
  528. * will allow the playing field to be extended to fit the word. If false
  529. * then the word will be dropped from the visualization.
  530. *
  531. * NB! This option is currently not decided to be published in the API, and
  532. * is therefore marked as private.
  533. *
  534. * @private
  535. */
  536. allowExtendPlayingField: true,
  537. animation: {
  538. /** @internal */
  539. duration: 500
  540. },
  541. borderWidth: 0,
  542. clip: false,
  543. colorByPoint: true,
  544. /**
  545. * A threshold determining the minimum font size that can be applied to a
  546. * word.
  547. */
  548. minFontSize: 1,
  549. /**
  550. * The word with the largest weight will have a font size equal to this
  551. * value. The font size of a word is the ratio between its weight and the
  552. * largest occuring weight, multiplied with the value of maxFontSize.
  553. */
  554. maxFontSize: 25,
  555. /**
  556. * This option decides which algorithm is used for placement, and rotation
  557. * of a word. The choice of algorith is therefore a crucial part of the
  558. * resulting layout of the wordcloud. It is possible for users to add their
  559. * own custom placement strategies for use in word cloud. Read more about it
  560. * in our
  561. * [documentation](https://www.highcharts.com/docs/chart-and-series-types/word-cloud-series#custom-placement-strategies)
  562. *
  563. * @validvalue: ["center", "random"]
  564. */
  565. placementStrategy: 'center',
  566. /**
  567. * Rotation options for the words in the wordcloud.
  568. *
  569. * @sample highcharts/plotoptions/wordcloud-rotation
  570. * Word cloud with rotation
  571. */
  572. rotation: {
  573. /**
  574. * The smallest degree of rotation for a word.
  575. */
  576. from: 0,
  577. /**
  578. * The number of possible orientations for a word, within the range of
  579. * `rotation.from` and `rotation.to`. Must be a number larger than 0.
  580. */
  581. orientations: 2,
  582. /**
  583. * The largest degree of rotation for a word.
  584. */
  585. to: 90
  586. },
  587. showInLegend: false,
  588. /**
  589. * Spiral used for placing a word after the initial position experienced a
  590. * collision with either another word or the borders.
  591. * It is possible for users to add their own custom spiralling algorithms
  592. * for use in word cloud. Read more about it in our
  593. * [documentation](https://www.highcharts.com/docs/chart-and-series-types/word-cloud-series#custom-spiralling-algorithm)
  594. *
  595. * @validvalue: ["archimedean", "rectangular", "square"]
  596. */
  597. spiral: 'rectangular',
  598. /**
  599. * CSS styles for the words.
  600. *
  601. * @type {Highcharts.CSSObject}
  602. * @default {"fontFamily":"sans-serif", "fontWeight": "900"}
  603. */
  604. style: {
  605. /** @ignore-option */
  606. fontFamily: 'sans-serif',
  607. /** @ignore-option */
  608. fontWeight: '900',
  609. /** @ignore-option */
  610. whiteSpace: 'nowrap'
  611. },
  612. tooltip: {
  613. followPointer: true,
  614. pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.weight}</b><br/>'
  615. }
  616. };
  617. // Properties of the WordCloud series.
  618. var wordCloudSeries = {
  619. animate: Series.prototype.animate,
  620. animateDrilldown: noop,
  621. animateDrillupFrom: noop,
  622. setClip: noop,
  623. bindAxes: function () {
  624. var wordcloudAxis = {
  625. endOnTick: false,
  626. gridLineWidth: 0,
  627. lineWidth: 0,
  628. maxPadding: 0,
  629. startOnTick: false,
  630. title: null,
  631. tickPositions: []
  632. };
  633. Series.prototype.bindAxes.call(this);
  634. extend(this.yAxis.options, wordcloudAxis);
  635. extend(this.xAxis.options, wordcloudAxis);
  636. },
  637. pointAttribs: function (point, state) {
  638. var attribs = H.seriesTypes.column.prototype
  639. .pointAttribs.call(this, point, state);
  640. delete attribs.stroke;
  641. delete attribs['stroke-width'];
  642. return attribs;
  643. },
  644. /**
  645. * Calculates the fontSize of a word based on its weight.
  646. *
  647. * @private
  648. * @function Highcharts.Series#deriveFontSize
  649. *
  650. * @param {number} [relativeWeight=0]
  651. * The weight of the word, on a scale 0-1.
  652. *
  653. * @param {number} [maxFontSize=1]
  654. * The maximum font size of a word.
  655. *
  656. * @param {number} [minFontSize=1]
  657. * The minimum font size of a word.
  658. *
  659. * @return {number}
  660. * Returns the resulting fontSize of a word. If minFontSize is larger then
  661. * maxFontSize the result will equal minFontSize.
  662. */
  663. deriveFontSize: function deriveFontSize(relativeWeight, maxFontSize, minFontSize) {
  664. var weight = isNumber(relativeWeight) ? relativeWeight : 0, max = isNumber(maxFontSize) ? maxFontSize : 1, min = isNumber(minFontSize) ? minFontSize : 1;
  665. return Math.floor(Math.max(min, weight * max));
  666. },
  667. drawPoints: function () {
  668. 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) {
  669. return p.weight;
  670. }), maxWeight = Math.max.apply(null, weights),
  671. // concat() prevents from sorting the original array.
  672. data = series.points.concat().sort(function (a, b) {
  673. return b.weight - a.weight; // Sort descending
  674. }), field;
  675. // Reset the scale before finding the dimensions (#11993).
  676. // SVGGRaphicsElement.getBBox() (used in SVGElement.getBBox(boolean))
  677. // returns slightly different values for the same element depending on
  678. // whether it is rendered in a group which has already defined scale
  679. // (e.g. 6) or in the group without a scale (scale = 1).
  680. series.group.attr({
  681. scaleX: 1,
  682. scaleY: 1
  683. });
  684. // Get the dimensions for each word.
  685. // Used in calculating the playing field.
  686. data.forEach(function (point) {
  687. var relativeWeight = 1 / maxWeight * point.weight, fontSize = series.deriveFontSize(relativeWeight, options.maxFontSize, options.minFontSize), css = extend({
  688. fontSize: fontSize + 'px'
  689. }, options.style), bBox;
  690. testElement.css(css).attr({
  691. x: 0,
  692. y: 0,
  693. text: point.name
  694. });
  695. bBox = testElement.getBBox(true);
  696. point.dimensions = {
  697. height: bBox.height,
  698. width: bBox.width
  699. };
  700. });
  701. // Calculate the playing field.
  702. field = getPlayingField(xAxis.len, yAxis.len, data);
  703. spiral = getSpiral(series.spirals[options.spiral], {
  704. field: field
  705. });
  706. // Draw all the points.
  707. data.forEach(function (point) {
  708. var relativeWeight = 1 / maxWeight * point.weight, fontSize = series.deriveFontSize(relativeWeight, options.maxFontSize, options.minFontSize), css = extend({
  709. fontSize: fontSize + 'px'
  710. }, options.style), placement = placementStrategy(point, {
  711. data: data,
  712. field: field,
  713. placed: placed,
  714. rotation: rotation
  715. }), attr = extend(series.pointAttribs(point, (point.selected && 'select')), {
  716. align: 'center',
  717. 'alignment-baseline': 'middle',
  718. x: placement.x,
  719. y: placement.y,
  720. text: point.name,
  721. rotation: placement.rotation
  722. }), polygon = getPolygon(placement.x, placement.y, point.dimensions.width, point.dimensions.height, placement.rotation), rectangle = getBoundingBoxFromPolygon(polygon), delta = intersectionTesting(point, {
  723. rectangle: rectangle,
  724. polygon: polygon,
  725. field: field,
  726. placed: placed,
  727. spiral: spiral,
  728. rotation: placement.rotation
  729. }), animate;
  730. // If there is no space for the word, extend the playing field.
  731. if (!delta && allowExtendPlayingField) {
  732. // Extend the playing field to fit the word.
  733. field = extendPlayingField(field, rectangle);
  734. // Run intersection testing one more time to place the word.
  735. delta = intersectionTesting(point, {
  736. rectangle: rectangle,
  737. polygon: polygon,
  738. field: field,
  739. placed: placed,
  740. spiral: spiral,
  741. rotation: placement.rotation
  742. });
  743. }
  744. // Check if point was placed, if so delete it, otherwise place it on
  745. // the correct positions.
  746. if (isObject(delta)) {
  747. attr.x += delta.x;
  748. attr.y += delta.y;
  749. rectangle.left += delta.x;
  750. rectangle.right += delta.x;
  751. rectangle.top += delta.y;
  752. rectangle.bottom += delta.y;
  753. field = updateFieldBoundaries(field, rectangle);
  754. placed.push(point);
  755. point.isNull = false;
  756. }
  757. else {
  758. point.isNull = true;
  759. }
  760. if (animation) {
  761. // Animate to new positions
  762. animate = {
  763. x: attr.x,
  764. y: attr.y
  765. };
  766. // Animate from center of chart
  767. if (!hasRendered) {
  768. attr.x = 0;
  769. attr.y = 0;
  770. // or animate from previous position
  771. }
  772. else {
  773. delete attr.x;
  774. delete attr.y;
  775. }
  776. }
  777. point.draw({
  778. animatableAttribs: animate,
  779. attribs: attr,
  780. css: css,
  781. group: group,
  782. renderer: renderer,
  783. shapeArgs: void 0,
  784. shapeType: 'text'
  785. });
  786. });
  787. // Destroy the element after use.
  788. testElement = testElement.destroy();
  789. // Scale the series group to fit within the plotArea.
  790. scale = getScale(xAxis.len, yAxis.len, field);
  791. series.group.attr({
  792. scaleX: scale,
  793. scaleY: scale
  794. });
  795. },
  796. hasData: function () {
  797. var series = this;
  798. return (isObject(series) &&
  799. series.visible === true &&
  800. isArray(series.points) &&
  801. series.points.length > 0);
  802. },
  803. // Strategies used for deciding rotation and initial position of a word. To
  804. // implement a custom strategy, have a look at the function random for
  805. // example.
  806. placementStrategy: {
  807. random: function (point, options) {
  808. var field = options.field, r = options.rotation;
  809. return {
  810. x: getRandomPosition(field.width) - (field.width / 2),
  811. y: getRandomPosition(field.height) - (field.height / 2),
  812. rotation: getRotation(r.orientations, point.index, r.from, r.to)
  813. };
  814. },
  815. center: function (point, options) {
  816. var r = options.rotation;
  817. return {
  818. x: 0,
  819. y: 0,
  820. rotation: getRotation(r.orientations, point.index, r.from, r.to)
  821. };
  822. }
  823. },
  824. pointArrayMap: ['weight'],
  825. // Spirals used for placing a word after the initial position experienced a
  826. // collision with either another word or the borders. To implement a custom
  827. // spiral, look at the function archimedeanSpiral for example.
  828. spirals: {
  829. 'archimedean': archimedeanSpiral,
  830. 'rectangular': rectangularSpiral,
  831. 'square': squareSpiral
  832. },
  833. utils: {
  834. extendPlayingField: extendPlayingField,
  835. getRotation: getRotation,
  836. isPolygonsColliding: isPolygonsColliding,
  837. rotate2DToOrigin: polygon.rotate2DToOrigin,
  838. rotate2DToPoint: polygon.rotate2DToPoint
  839. },
  840. getPlotBox: function () {
  841. var series = this, chart = series.chart, inverted = chart.inverted,
  842. // Swap axes for inverted (#2339)
  843. 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;
  844. return {
  845. translateX: x + (width / 2),
  846. translateY: y + (height / 2),
  847. scaleX: 1,
  848. scaleY: 1
  849. };
  850. }
  851. };
  852. // Properties of the Sunburst series.
  853. var wordCloudPoint = {
  854. draw: drawPoint,
  855. shouldDraw: function shouldDraw() {
  856. var point = this;
  857. return !point.isNull;
  858. },
  859. isValid: function isValid() {
  860. return true;
  861. },
  862. weight: 1
  863. };
  864. /**
  865. * A `wordcloud` series. If the [type](#series.wordcloud.type) option is not
  866. * specified, it is inherited from [chart.type](#chart.type).
  867. *
  868. * @extends series,plotOptions.wordcloud
  869. * @exclude dataSorting
  870. * @product highcharts
  871. * @requires modules/wordcloud
  872. * @apioption series.wordcloud
  873. */
  874. /**
  875. * An array of data points for the series. For the `wordcloud` series type,
  876. * points can be given in the following ways:
  877. *
  878. * 1. An array of arrays with 2 values. In this case, the values correspond to
  879. * `name,weight`.
  880. * ```js
  881. * data: [
  882. * ['Lorem', 4],
  883. * ['Ipsum', 1]
  884. * ]
  885. * ```
  886. *
  887. * 2. An array of objects with named values. The following snippet shows only a
  888. * few settings, see the complete options set below. If the total number of
  889. * data points exceeds the series'
  890. * [turboThreshold](#series.arearange.turboThreshold), this option is not
  891. * available.
  892. * ```js
  893. * data: [{
  894. * name: "Lorem",
  895. * weight: 4
  896. * }, {
  897. * name: "Ipsum",
  898. * weight: 1
  899. * }]
  900. * ```
  901. *
  902. * @type {Array<Array<string,number>|*>}
  903. * @extends series.line.data
  904. * @excluding drilldown, marker, x, y
  905. * @product highcharts
  906. * @apioption series.wordcloud.data
  907. */
  908. /**
  909. * The name decides the text for a word.
  910. *
  911. * @type {string}
  912. * @since 6.0.0
  913. * @product highcharts
  914. * @apioption series.sunburst.data.name
  915. */
  916. /**
  917. * The weighting of a word. The weight decides the relative size of a word
  918. * compared to the rest of the collection.
  919. *
  920. * @type {number}
  921. * @since 6.0.0
  922. * @product highcharts
  923. * @apioption series.sunburst.data.weight
  924. */
  925. /**
  926. * @private
  927. * @class
  928. * @name Highcharts.seriesTypes.wordcloud
  929. *
  930. * @augments Highcharts.Series
  931. */
  932. seriesType('wordcloud', 'column', wordCloudOptions, wordCloudSeries, wordCloudPoint);