0cee09eab61e831a76574dbd85e7dfe11b1866607d070ea03fe0b56afb40de042b1d1bd01647b0fdb208c0cafa2f6899be73806dee68747060eb68b546bc53 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. import BasePlugin from './../_base';
  2. import {arrayEach, arrayFilter, arrayReduce, arrayMap} from './../../helpers/array';
  3. import {cancelAnimationFrame, requestAnimationFrame} from './../../helpers/feature';
  4. import {isVisible} from './../../helpers/dom/element';
  5. import GhostTable from './../../utils/ghostTable';
  6. import {isObject, objectEach, hasOwnProperty} from './../../helpers/object';
  7. import {valueAccordingPercent, rangeEach} from './../../helpers/number';
  8. import {registerPlugin} from './../../plugins';
  9. import SamplesGenerator from './../../utils/samplesGenerator';
  10. import {isPercentValue} from './../../helpers/string';
  11. import {ViewportColumnsCalculator} from './../../3rdparty/walkontable/src';
  12. const privatePool = new WeakMap();
  13. /**
  14. * @plugin AutoColumnSize
  15. *
  16. * @description
  17. * This plugin allows to set column widths based on their widest cells.
  18. *
  19. * By default, the plugin is declared as `undefined`, which makes it enabled (same as if it was declared as `true`).
  20. * Enabling this plugin may decrease the overall table performance, as it needs to calculate the widths of all cells to
  21. * resize the columns accordingly.
  22. * If you experience problems with the performance, try turning this feature off and declaring the column widths manually.
  23. *
  24. * Column width calculations are divided into sync and async part. Each of this parts has their own advantages and
  25. * disadvantages. Synchronous calculations are faster but they block the browser UI, while the slower asynchronous operations don't
  26. * block the browser UI.
  27. *
  28. * To configure the sync/async distribution, you can pass an absolute value (number of columns) or a percentage value to a config object:
  29. * ```js
  30. * ...
  31. * // as a number (300 columns in sync, rest async)
  32. * autoColumnSize: {syncLimit: 300},
  33. * ...
  34. *
  35. * ...
  36. * // as a string (percent)
  37. * autoColumnSize: {syncLimit: '40%'},
  38. * ...
  39. * ```
  40. *
  41. * To configure this plugin see {@link Options#autoColumnSize}.
  42. *
  43. * @example
  44. * ```js
  45. * ...
  46. * var hot = new Handsontable(document.getElementById('example'), {
  47. * date: getData(),
  48. * autoColumnSize: true
  49. * });
  50. * // Access to plugin instance:
  51. * var plugin = hot.getPlugin('autoColumnSize');
  52. *
  53. * plugin.getColumnWidth(4);
  54. *
  55. * if (plugin.isEnabled()) {
  56. * // code...
  57. * }
  58. * ...
  59. * ```
  60. */
  61. class AutoColumnSize extends BasePlugin {
  62. static get CALCULATION_STEP() {
  63. return 50;
  64. }
  65. static get SYNC_CALCULATION_LIMIT() {
  66. return 50;
  67. }
  68. constructor(hotInstance) {
  69. super(hotInstance);
  70. privatePool.set(this, {
  71. /**
  72. * Cached column header names. It is used to diff current column headers with previous state and detect which
  73. * columns width should be updated.
  74. *
  75. * @private
  76. * @type {Array}
  77. */
  78. cachedColumnHeaders: [],
  79. });
  80. /**
  81. * Cached columns widths.
  82. *
  83. * @type {Array}
  84. */
  85. this.widths = [];
  86. /**
  87. * Instance of {@link GhostTable} for rows and columns size calculations.
  88. *
  89. * @type {GhostTable}
  90. */
  91. this.ghostTable = new GhostTable(this.hot);
  92. /**
  93. * Instance of {@link SamplesGenerator} for generating samples necessary for columns width calculations.
  94. *
  95. * @type {SamplesGenerator}
  96. */
  97. this.samplesGenerator = new SamplesGenerator((row, col) => this.hot.getDataAtCell(row, col));
  98. /**
  99. * `true` only if the first calculation was performed
  100. *
  101. * @type {Boolean}
  102. */
  103. this.firstCalculation = true;
  104. /**
  105. * `true` if the size calculation is in progress.
  106. *
  107. * @type {Boolean}
  108. */
  109. this.inProgress = false;
  110. // moved to constructor to allow auto-sizing the columns when the plugin is disabled
  111. this.addHook('beforeColumnResize', (col, size, isDblClick) => this.onBeforeColumnResize(col, size, isDblClick));
  112. }
  113. /**
  114. * Check if the plugin is enabled in the handsontable settings.
  115. *
  116. * @returns {Boolean}
  117. */
  118. isEnabled() {
  119. return this.hot.getSettings().autoColumnSize !== false && !this.hot.getSettings().colWidths;
  120. }
  121. /**
  122. * Enable plugin for this Handsontable instance.
  123. */
  124. enablePlugin() {
  125. if (this.enabled) {
  126. return;
  127. }
  128. let setting = this.hot.getSettings().autoColumnSize;
  129. if (setting && setting.useHeaders != null) {
  130. this.ghostTable.setSetting('useHeaders', setting.useHeaders);
  131. }
  132. this.addHook('afterLoadData', () => this.onAfterLoadData());
  133. this.addHook('beforeChange', (changes) => this.onBeforeChange(changes));
  134. this.addHook('beforeRender', (force) => this.onBeforeRender(force));
  135. this.addHook('modifyColWidth', (width, col) => this.getColumnWidth(col, width));
  136. this.addHook('afterInit', () => this.onAfterInit());
  137. super.enablePlugin();
  138. }
  139. /**
  140. * Update plugin state.
  141. */
  142. updatePlugin() {
  143. const changedColumns = this.findColumnsWhereHeaderWasChanged();
  144. if (changedColumns.length) {
  145. this.clearCache(changedColumns);
  146. }
  147. super.updatePlugin();
  148. }
  149. /**
  150. * Disable plugin for this Handsontable instance.
  151. */
  152. disablePlugin() {
  153. super.disablePlugin();
  154. }
  155. /**
  156. * Calculate a columns width.
  157. *
  158. * @param {Number|Object} colRange Column range object.
  159. * @param {Number|Object} rowRange Row range object.
  160. * @param {Boolean} [force=false] If `true` force calculate width even when value was cached earlier.
  161. */
  162. calculateColumnsWidth(colRange = {from: 0, to: this.hot.countCols() - 1}, rowRange = {from: 0, to: this.hot.countRows() - 1}, force = false) {
  163. if (typeof colRange === 'number') {
  164. colRange = {from: colRange, to: colRange};
  165. }
  166. if (typeof rowRange === 'number') {
  167. rowRange = {from: rowRange, to: rowRange};
  168. }
  169. rangeEach(colRange.from, colRange.to, (col) => {
  170. if (force || (this.widths[col] === void 0 && !this.hot._getColWidthFromSettings(col))) {
  171. const samples = this.samplesGenerator.generateColumnSamples(col, rowRange);
  172. samples.forEach((sample, col) => this.ghostTable.addColumn(col, sample));
  173. }
  174. });
  175. if (this.ghostTable.columns.length) {
  176. this.ghostTable.getWidths((col, width) => {
  177. this.widths[col] = width;
  178. });
  179. this.ghostTable.clean();
  180. }
  181. }
  182. /**
  183. * Calculate all columns width.
  184. *
  185. * @param {Object|Number} rowRange Row range object.
  186. */
  187. calculateAllColumnsWidth(rowRange = {from: 0, to: this.hot.countRows() - 1}) {
  188. let current = 0;
  189. let length = this.hot.countCols() - 1;
  190. let timer = null;
  191. this.inProgress = true;
  192. let loop = () => {
  193. // When hot was destroyed after calculating finished cancel frame
  194. if (!this.hot) {
  195. cancelAnimationFrame(timer);
  196. this.inProgress = false;
  197. return;
  198. }
  199. this.calculateColumnsWidth({
  200. from: current,
  201. to: Math.min(current + AutoColumnSize.CALCULATION_STEP, length)
  202. }, rowRange);
  203. current = current + AutoColumnSize.CALCULATION_STEP + 1;
  204. if (current < length) {
  205. timer = requestAnimationFrame(loop);
  206. } else {
  207. cancelAnimationFrame(timer);
  208. this.inProgress = false;
  209. // @TODO Should call once per render cycle, currently fired separately in different plugins
  210. this.hot.view.wt.wtOverlays.adjustElementsSize(true);
  211. // tmp
  212. if (this.hot.view.wt.wtOverlays.leftOverlay.needFullRender) {
  213. this.hot.view.wt.wtOverlays.leftOverlay.clone.draw();
  214. }
  215. }
  216. };
  217. // sync
  218. if (this.firstCalculation && this.getSyncCalculationLimit()) {
  219. this.calculateColumnsWidth({from: 0, to: this.getSyncCalculationLimit()}, rowRange);
  220. this.firstCalculation = false;
  221. current = this.getSyncCalculationLimit() + 1;
  222. }
  223. // async
  224. if (current < length) {
  225. loop();
  226. } else {
  227. this.inProgress = false;
  228. }
  229. }
  230. /**
  231. * Set the sampling options.
  232. *
  233. * @private
  234. */
  235. setSamplingOptions() {
  236. let setting = this.hot.getSettings().autoColumnSize;
  237. let samplingRatio = setting && hasOwnProperty(setting, 'samplingRatio') ? this.hot.getSettings().autoColumnSize.samplingRatio : void 0;
  238. let allowSampleDuplicates = setting && hasOwnProperty(setting, 'allowSampleDuplicates') ? this.hot.getSettings().autoColumnSize.allowSampleDuplicates : void 0;
  239. if (samplingRatio && !isNaN(samplingRatio)) {
  240. this.samplesGenerator.setSampleCount(parseInt(samplingRatio, 10));
  241. }
  242. if (allowSampleDuplicates) {
  243. this.samplesGenerator.setAllowDuplicates(allowSampleDuplicates);
  244. }
  245. }
  246. /**
  247. * Recalculate all columns width (overwrite cache values).
  248. */
  249. recalculateAllColumnsWidth() {
  250. if (this.hot.view && isVisible(this.hot.view.wt.wtTable.TABLE)) {
  251. this.clearCache();
  252. this.calculateAllColumnsWidth();
  253. }
  254. }
  255. /**
  256. * Get value which tells how many columns should be calculated synchronously. Rest of the columns will be calculated asynchronously.
  257. *
  258. * @returns {Number}
  259. */
  260. getSyncCalculationLimit() {
  261. /* eslint-disable no-bitwise */
  262. let limit = AutoColumnSize.SYNC_CALCULATION_LIMIT;
  263. let colsLimit = this.hot.countCols() - 1;
  264. if (isObject(this.hot.getSettings().autoColumnSize)) {
  265. limit = this.hot.getSettings().autoColumnSize.syncLimit;
  266. if (isPercentValue(limit)) {
  267. limit = valueAccordingPercent(colsLimit, limit);
  268. } else {
  269. // Force to Number
  270. limit >>= 0;
  271. }
  272. }
  273. return Math.min(limit, colsLimit);
  274. }
  275. /**
  276. * Get the calculated column width.
  277. *
  278. * @param {Number} col Column index.
  279. * @param {Number} [defaultWidth] Default column width. It will be picked up if no calculated width found.
  280. * @param {Boolean} [keepMinimum=true] If `true` then returned value won't be smaller then 50 (default column width).
  281. * @returns {Number}
  282. */
  283. getColumnWidth(col, defaultWidth = void 0, keepMinimum = true) {
  284. let width = defaultWidth;
  285. if (width === void 0) {
  286. width = this.widths[col];
  287. if (keepMinimum && typeof width === 'number') {
  288. width = Math.max(width, ViewportColumnsCalculator.DEFAULT_WIDTH);
  289. }
  290. }
  291. return width;
  292. }
  293. /**
  294. * Get the first visible column.
  295. *
  296. * @returns {Number} Returns column index or -1 if table is not rendered.
  297. */
  298. getFirstVisibleColumn() {
  299. const wot = this.hot.view.wt;
  300. if (wot.wtViewport.columnsVisibleCalculator) {
  301. return wot.wtTable.getFirstVisibleColumn();
  302. }
  303. if (wot.wtViewport.columnsRenderCalculator) {
  304. return wot.wtTable.getFirstRenderedColumn();
  305. }
  306. return -1;
  307. }
  308. /**
  309. * Get the last visible column.
  310. *
  311. * @returns {Number} Returns column index or -1 if table is not rendered.
  312. */
  313. getLastVisibleColumn() {
  314. const wot = this.hot.view.wt;
  315. if (wot.wtViewport.columnsVisibleCalculator) {
  316. return wot.wtTable.getLastVisibleColumn();
  317. }
  318. if (wot.wtViewport.columnsRenderCalculator) {
  319. return wot.wtTable.getLastRenderedColumn();
  320. }
  321. return -1;
  322. }
  323. /**
  324. * Collects all columns which titles has been changed in comparison to the previous state.
  325. *
  326. * @returns {Array} It returns an array of physical column indexes.
  327. */
  328. findColumnsWhereHeaderWasChanged() {
  329. const columnHeaders = this.hot.getColHeader();
  330. const {cachedColumnHeaders} = privatePool.get(this);
  331. const changedColumns = arrayReduce(columnHeaders, (acc, columnTitle, physicalColumn) => {
  332. const cachedColumnsLength = cachedColumnHeaders.length;
  333. if (cachedColumnsLength - 1 < physicalColumn || cachedColumnHeaders[physicalColumn] !== columnTitle) {
  334. acc.push(physicalColumn);
  335. }
  336. if (cachedColumnsLength - 1 < physicalColumn) {
  337. cachedColumnHeaders.push(columnTitle);
  338. } else {
  339. cachedColumnHeaders[physicalColumn] = columnTitle;
  340. }
  341. return acc;
  342. }, []);
  343. return changedColumns;
  344. }
  345. /**
  346. * Clear cache of calculated column widths. If you want to clear only selected columns pass an array with their indexes.
  347. * Otherwise whole cache will be cleared.
  348. *
  349. * @param {Array} [columns=[]] List of column indexes (physical indexes) to clear.
  350. */
  351. clearCache(columns = []) {
  352. if (columns.length) {
  353. arrayEach(columns, (physicalIndex) => {
  354. this.widths[physicalIndex] = void 0;
  355. });
  356. } else {
  357. this.widths.length = 0;
  358. }
  359. }
  360. /**
  361. * Check if all widths were calculated. If not then return `true` (need recalculate).
  362. *
  363. * @returns {Boolean}
  364. */
  365. isNeedRecalculate() {
  366. return !!arrayFilter(this.widths, (item) => (item === void 0)).length;
  367. }
  368. /**
  369. * On before render listener.
  370. *
  371. * @private
  372. */
  373. onBeforeRender() {
  374. const force = this.hot.renderCall;
  375. const rowsCount = this.hot.countRows();
  376. // Keep last column widths unchanged for situation when all rows was deleted or trimmed (pro #6)
  377. if (!rowsCount) {
  378. return;
  379. }
  380. this.calculateColumnsWidth({from: this.getFirstVisibleColumn(), to: this.getLastVisibleColumn()}, void 0, force);
  381. if (this.isNeedRecalculate() && !this.inProgress) {
  382. this.calculateAllColumnsWidth();
  383. }
  384. }
  385. /**
  386. * On after load data listener.
  387. *
  388. * @private
  389. */
  390. onAfterLoadData() {
  391. if (this.hot.view) {
  392. this.recalculateAllColumnsWidth();
  393. } else {
  394. // first load - initialization
  395. setTimeout(() => {
  396. if (this.hot) {
  397. this.recalculateAllColumnsWidth();
  398. }
  399. }, 0);
  400. }
  401. }
  402. /**
  403. * On before change listener.
  404. *
  405. * @private
  406. * @param {Array} changes
  407. */
  408. onBeforeChange(changes) {
  409. const changedColumns = arrayMap(changes, ([row, column]) => this.hot.propToCol(column));
  410. this.clearCache(changedColumns);
  411. }
  412. /**
  413. * On before column resize listener.
  414. *
  415. * @private
  416. * @param {Number} col
  417. * @param {Number} size
  418. * @param {Boolean} isDblClick
  419. * @returns {Number}
  420. */
  421. onBeforeColumnResize(col, size, isDblClick) {
  422. if (isDblClick) {
  423. this.calculateColumnsWidth(col, void 0, true);
  424. size = this.getColumnWidth(col, void 0, false);
  425. }
  426. return size;
  427. }
  428. /**
  429. * On after Handsontable init fill plugin with all necessary values.
  430. *
  431. * @private
  432. */
  433. onAfterInit() {
  434. privatePool.get(this).cachedColumnHeaders = this.hot.getColHeader();
  435. }
  436. /**
  437. * Destroy plugin instance.
  438. */
  439. destroy() {
  440. this.ghostTable.clean();
  441. super.destroy();
  442. }
  443. }
  444. registerPlugin('autoColumnSize', AutoColumnSize);
  445. export default AutoColumnSize;