core.js 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347
  1. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  2. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  3. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  4. import numbro from 'numbro';
  5. import { addClass, empty, isChildOfWebComponentTable, removeClass } from './helpers/dom/element';
  6. import { columnFactory } from './helpers/setting';
  7. import { isFunction } from './helpers/function';
  8. import { isDefined, isUndefined, isRegExp } from './helpers/mixed';
  9. import { isMobileBrowser } from './helpers/browser';
  10. import DataMap from './dataMap';
  11. import EditorManager from './editorManager';
  12. import EventManager from './eventManager';
  13. import { deepClone, duckSchema, extend, isObject, isObjectEquals, deepObjectSize, hasOwnProperty, createObjectPropListener } from './helpers/object';
  14. import { arrayFlatten, arrayMap } from './helpers/array';
  15. import { getPlugin } from './plugins';
  16. import { getRenderer } from './renderers';
  17. import { getValidator } from './validators';
  18. import { randomString } from './helpers/string';
  19. import { rangeEach } from './helpers/number';
  20. import TableView from './tableView';
  21. import DataSource from './dataSource';
  22. import { translateRowsToColumns, cellMethodLookupFactory, spreadsheetColumnLabel } from './helpers/data';
  23. import { getTranslator } from './utils/recordTranslator';
  24. import { CellCoords, CellRange, ViewportColumnsCalculator } from './3rdparty/walkontable/src';
  25. import Hooks from './pluginHooks';
  26. import DefaultSettings from './defaultSettings';
  27. import { getCellType } from './cellTypes';
  28. var activeGuid = null;
  29. /**
  30. * Handsontable constructor
  31. *
  32. * @core
  33. * @dependencies numbro
  34. * @constructor Core
  35. * @description
  36. *
  37. * After Handsontable is constructed, you can modify the grid behavior using the available public methods.
  38. *
  39. * ---
  40. * ## How to call methods
  41. *
  42. * These are 2 equal ways to call a Handsontable method:
  43. *
  44. * ```js
  45. * // all following examples assume that you constructed Handsontable like this
  46. * var ht = new Handsontable(document.getElementById('example1'), options);
  47. *
  48. * // now, to use setDataAtCell method, you can either:
  49. * ht.setDataAtCell(0, 0, 'new value');
  50. * ```
  51. *
  52. * Alternatively, you can call the method using jQuery wrapper (__obsolete__, requires initialization using our jQuery guide
  53. * ```js
  54. * $('#example1').handsontable('setDataAtCell', 0, 0, 'new value');
  55. * ```
  56. * ---
  57. */
  58. export default function Core(rootElement, userSettings) {
  59. var priv,
  60. datamap,
  61. dataSource,
  62. grid,
  63. selection,
  64. editorManager,
  65. instance = this,
  66. GridSettings = function GridSettings() {},
  67. eventManager = new EventManager(instance);
  68. extend(GridSettings.prototype, DefaultSettings.prototype); // create grid settings as a copy of default settings
  69. extend(GridSettings.prototype, userSettings); // overwrite defaults with user settings
  70. extend(GridSettings.prototype, expandType(userSettings));
  71. this.rootElement = rootElement;
  72. this.isHotTableEnv = isChildOfWebComponentTable(this.rootElement);
  73. EventManager.isHotTableEnv = this.isHotTableEnv;
  74. this.container = document.createElement('DIV');
  75. this.renderCall = false;
  76. rootElement.insertBefore(this.container, rootElement.firstChild);
  77. this.guid = 'ht_' + randomString(); // this is the namespace for global events
  78. var recordTranslator = getTranslator(instance);
  79. dataSource = new DataSource(instance);
  80. if (!this.rootElement.id || this.rootElement.id.substring(0, 3) === 'ht_') {
  81. this.rootElement.id = this.guid; // if root element does not have an id, assign a random id
  82. }
  83. priv = {
  84. cellSettings: [],
  85. columnSettings: [],
  86. columnsSettingConflicts: ['data', 'width'],
  87. settings: new GridSettings(), // current settings instance
  88. selRange: null, // exposed by public method `getSelectedRange`
  89. isPopulated: null,
  90. scrollable: null,
  91. firstRun: true
  92. };
  93. grid = {
  94. /**
  95. * Inserts or removes rows and columns
  96. *
  97. * @memberof Core#
  98. * @function alter
  99. * @private
  100. * @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col"
  101. * @param {Number} index
  102. * @param {Number} amount
  103. * @param {String} [source] Optional. Source of hook runner.
  104. * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
  105. */
  106. alter: function alter(action, index, amount, source, keepEmptyRows) {
  107. var delta;
  108. amount = amount || 1;
  109. function spliceWith(data, index, count, toInject) {
  110. var valueFactory = function valueFactory() {
  111. var result = void 0;
  112. if (toInject === 'array') {
  113. result = [];
  114. } else if (toInject === 'object') {
  115. result = {};
  116. }
  117. return result;
  118. };
  119. var spliceArgs = arrayMap(new Array(count), function () {
  120. return valueFactory();
  121. });
  122. spliceArgs.unshift(index, 0);
  123. data.splice.apply(data, _toConsumableArray(spliceArgs));
  124. }
  125. /* eslint-disable no-case-declarations */
  126. switch (action) {
  127. case 'insert_row':
  128. var numberOfSourceRows = instance.countSourceRows();
  129. if (instance.getSettings().maxRows === numberOfSourceRows) {
  130. return;
  131. }
  132. index = isDefined(index) ? index : numberOfSourceRows;
  133. delta = datamap.createRow(index, amount, source);
  134. spliceWith(priv.cellSettings, index, amount, 'array');
  135. if (delta) {
  136. if (selection.isSelected() && priv.selRange.from.row >= index) {
  137. priv.selRange.from.row += delta;
  138. selection.transformEnd(delta, 0); // will call render() internally
  139. } else {
  140. selection.refreshBorders(); // it will call render and prepare methods
  141. }
  142. }
  143. break;
  144. case 'insert_col':
  145. delta = datamap.createCol(index, amount, source);
  146. for (var row = 0, len = instance.countSourceRows(); row < len; row++) {
  147. if (priv.cellSettings[row]) {
  148. spliceWith(priv.cellSettings[row], index, amount);
  149. }
  150. }
  151. if (delta) {
  152. if (Array.isArray(instance.getSettings().colHeaders)) {
  153. var spliceArray = [index, 0];
  154. spliceArray.length += delta; // inserts empty (undefined) elements at the end of an array
  155. Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); // inserts empty (undefined) elements into the colHeader array
  156. }
  157. if (selection.isSelected() && priv.selRange.from.col >= index) {
  158. priv.selRange.from.col += delta;
  159. selection.transformEnd(0, delta); // will call render() internally
  160. } else {
  161. selection.refreshBorders(); // it will call render and prepare methods
  162. }
  163. }
  164. break;
  165. case 'remove_row':
  166. datamap.removeRow(index, amount, source);
  167. priv.cellSettings.splice(index, amount);
  168. var totalRows = instance.countRows();
  169. var fixedRowsTop = instance.getSettings().fixedRowsTop;
  170. if (fixedRowsTop >= index + 1) {
  171. instance.getSettings().fixedRowsTop -= Math.min(amount, fixedRowsTop - index);
  172. }
  173. var fixedRowsBottom = instance.getSettings().fixedRowsBottom;
  174. if (fixedRowsBottom && index >= totalRows - fixedRowsBottom) {
  175. instance.getSettings().fixedRowsBottom -= Math.min(amount, fixedRowsBottom);
  176. }
  177. grid.adjustRowsAndCols();
  178. selection.refreshBorders(); // it will call render and prepare methods
  179. break;
  180. case 'remove_col':
  181. var logicalColumnIndex = recordTranslator.toPhysicalColumn(index);
  182. datamap.removeCol(index, amount, source);
  183. for (var _row = 0, _len = instance.countSourceRows(); _row < _len; _row++) {
  184. if (priv.cellSettings[_row]) {
  185. // if row hasn't been rendered it wouldn't have cellSettings
  186. priv.cellSettings[_row].splice(logicalColumnIndex, amount);
  187. }
  188. }
  189. var fixedColumnsLeft = instance.getSettings().fixedColumnsLeft;
  190. if (fixedColumnsLeft >= index + 1) {
  191. instance.getSettings().fixedColumnsLeft -= Math.min(amount, fixedColumnsLeft - index);
  192. }
  193. if (Array.isArray(instance.getSettings().colHeaders)) {
  194. if (typeof logicalColumnIndex == 'undefined') {
  195. logicalColumnIndex = -1;
  196. }
  197. instance.getSettings().colHeaders.splice(logicalColumnIndex, amount);
  198. }
  199. grid.adjustRowsAndCols();
  200. selection.refreshBorders(); // it will call render and prepare methods
  201. break;
  202. default:
  203. throw new Error('There is no such action "' + action + '"');
  204. }
  205. if (!keepEmptyRows) {
  206. grid.adjustRowsAndCols(); // makes sure that we did not add rows that will be removed in next refresh
  207. }
  208. },
  209. /**
  210. * Makes sure there are empty rows at the bottom of the table
  211. */
  212. adjustRowsAndCols: function adjustRowsAndCols() {
  213. if (priv.settings.minRows) {
  214. // should I add empty rows to data source to meet minRows?
  215. var rows = instance.countRows();
  216. if (rows < priv.settings.minRows) {
  217. for (var r = 0, minRows = priv.settings.minRows; r < minRows - rows; r++) {
  218. datamap.createRow(instance.countRows(), 1, 'auto');
  219. }
  220. }
  221. }
  222. if (priv.settings.minSpareRows) {
  223. var emptyRows = instance.countEmptyRows(true);
  224. // should I add empty rows to meet minSpareRows?
  225. if (emptyRows < priv.settings.minSpareRows) {
  226. for (; emptyRows < priv.settings.minSpareRows && instance.countSourceRows() < priv.settings.maxRows; emptyRows++) {
  227. datamap.createRow(instance.countRows(), 1, 'auto');
  228. }
  229. }
  230. }
  231. {
  232. var emptyCols = void 0;
  233. // count currently empty cols
  234. if (priv.settings.minCols || priv.settings.minSpareCols) {
  235. emptyCols = instance.countEmptyCols(true);
  236. }
  237. // should I add empty cols to meet minCols?
  238. if (priv.settings.minCols && !priv.settings.columns && instance.countCols() < priv.settings.minCols) {
  239. for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
  240. datamap.createCol(instance.countCols(), 1, 'auto');
  241. }
  242. }
  243. // should I add empty cols to meet minSpareCols?
  244. if (priv.settings.minSpareCols && !priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
  245. for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
  246. datamap.createCol(instance.countCols(), 1, 'auto');
  247. }
  248. }
  249. }
  250. var rowCount = instance.countRows();
  251. var colCount = instance.countCols();
  252. if (rowCount === 0 || colCount === 0) {
  253. selection.deselect();
  254. }
  255. if (selection.isSelected()) {
  256. var selectionChanged = false;
  257. var fromRow = priv.selRange.from.row;
  258. var fromCol = priv.selRange.from.col;
  259. var toRow = priv.selRange.to.row;
  260. var toCol = priv.selRange.to.col;
  261. // if selection is outside, move selection to last row
  262. if (fromRow > rowCount - 1) {
  263. fromRow = rowCount - 1;
  264. selectionChanged = true;
  265. if (toRow > fromRow) {
  266. toRow = fromRow;
  267. }
  268. } else if (toRow > rowCount - 1) {
  269. toRow = rowCount - 1;
  270. selectionChanged = true;
  271. if (fromRow > toRow) {
  272. fromRow = toRow;
  273. }
  274. }
  275. // if selection is outside, move selection to last row
  276. if (fromCol > colCount - 1) {
  277. fromCol = colCount - 1;
  278. selectionChanged = true;
  279. if (toCol > fromCol) {
  280. toCol = fromCol;
  281. }
  282. } else if (toCol > colCount - 1) {
  283. toCol = colCount - 1;
  284. selectionChanged = true;
  285. if (fromCol > toCol) {
  286. fromCol = toCol;
  287. }
  288. }
  289. if (selectionChanged) {
  290. instance.selectCell(fromRow, fromCol, toRow, toCol);
  291. }
  292. }
  293. if (instance.view) {
  294. instance.view.wt.wtOverlays.adjustElementsSize();
  295. }
  296. },
  297. /**
  298. * Populate the data from the provided 2d array from the given cell coordinates.
  299. *
  300. * @private
  301. * @param {Object} start Start selection position.
  302. * @param {Array} input 2d data array.
  303. * @param {Object} [end] End selection position (only for drag-down mode).
  304. * @param {String} [source="populateFromArray"] Source information string.
  305. * @param {String} [method="overwrite"] Populate method. Possible options: `shift_down`, `shift_right`, `overwrite`.
  306. * @param {String} direction (left|right|up|down) String specifying the direction.
  307. * @param {Array} deltas The deltas array.
  308. * @returns {Object|undefined} ending td in pasted area (only if any cell was changed).
  309. */
  310. populateFromArray: function populateFromArray(start, input, end, source, method, direction, deltas) {
  311. var r,
  312. rlen,
  313. c,
  314. clen,
  315. setData = [],
  316. current = {};
  317. rlen = input.length;
  318. if (rlen === 0) {
  319. return false;
  320. }
  321. var repeatCol,
  322. repeatRow,
  323. cmax,
  324. rmax,
  325. baseEnd = {
  326. row: end === null ? null : end.row,
  327. col: end === null ? null : end.col
  328. };
  329. /* eslint-disable no-case-declarations */
  330. // insert data with specified pasteMode method
  331. switch (method) {
  332. case 'shift_down':
  333. repeatCol = end ? end.col - start.col + 1 : 0;
  334. repeatRow = end ? end.row - start.row + 1 : 0;
  335. input = translateRowsToColumns(input);
  336. for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
  337. if (c < clen) {
  338. var _instance;
  339. for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
  340. input[c].push(input[c][r % rlen]);
  341. }
  342. input[c].unshift(start.col + c, start.row, 0);
  343. (_instance = instance).spliceCol.apply(_instance, _toConsumableArray(input[c]));
  344. } else {
  345. var _instance2;
  346. input[c % clen][0] = start.col + c;
  347. (_instance2 = instance).spliceCol.apply(_instance2, _toConsumableArray(input[c % clen]));
  348. }
  349. }
  350. break;
  351. case 'shift_right':
  352. repeatCol = end ? end.col - start.col + 1 : 0;
  353. repeatRow = end ? end.row - start.row + 1 : 0;
  354. for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
  355. if (r < rlen) {
  356. var _instance3;
  357. for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
  358. input[r].push(input[r][c % clen]);
  359. }
  360. input[r].unshift(start.row + r, start.col, 0);
  361. (_instance3 = instance).spliceRow.apply(_instance3, _toConsumableArray(input[r]));
  362. } else {
  363. var _instance4;
  364. input[r % rlen][0] = start.row + r;
  365. (_instance4 = instance).spliceRow.apply(_instance4, _toConsumableArray(input[r % rlen]));
  366. }
  367. }
  368. break;
  369. case 'overwrite':
  370. default:
  371. // overwrite and other not specified options
  372. current.row = start.row;
  373. current.col = start.col;
  374. var selected = { // selected range
  375. row: end && start ? end.row - start.row + 1 : 1,
  376. col: end && start ? end.col - start.col + 1 : 1
  377. };
  378. var skippedRow = 0;
  379. var skippedColumn = 0;
  380. var pushData = true;
  381. var cellMeta = void 0;
  382. var getInputValue = function getInputValue(row) {
  383. var col = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  384. var rowValue = input[row % input.length];
  385. if (col !== null) {
  386. return rowValue[col % rowValue.length];
  387. }
  388. return rowValue;
  389. };
  390. var rowInputLength = input.length;
  391. var rowSelectionLength = end ? end.row - start.row + 1 : 0;
  392. if (end) {
  393. rlen = rowSelectionLength;
  394. } else {
  395. rlen = Math.max(rowInputLength, rowSelectionLength);
  396. }
  397. for (r = 0; r < rlen; r++) {
  398. if (end && current.row > end.row && rowSelectionLength > rowInputLength || !priv.settings.allowInsertRow && current.row > instance.countRows() - 1 || current.row >= priv.settings.maxRows) {
  399. break;
  400. }
  401. var logicalRow = r - skippedRow;
  402. var colInputLength = getInputValue(logicalRow).length;
  403. var colSelectionLength = end ? end.col - start.col + 1 : 0;
  404. if (end) {
  405. clen = colSelectionLength;
  406. } else {
  407. clen = Math.max(colInputLength, colSelectionLength);
  408. }
  409. current.col = start.col;
  410. cellMeta = instance.getCellMeta(current.row, current.col);
  411. if ((source === 'CopyPaste.paste' || source === 'Autofill.autofill') && cellMeta.skipRowOnPaste) {
  412. skippedRow++;
  413. current.row++;
  414. rlen++;
  415. /* eslint-disable no-continue */
  416. continue;
  417. }
  418. skippedColumn = 0;
  419. for (c = 0; c < clen; c++) {
  420. if (end && current.col > end.col && colSelectionLength > colInputLength || !priv.settings.allowInsertColumn && current.col > instance.countCols() - 1 || current.col >= priv.settings.maxCols) {
  421. break;
  422. }
  423. cellMeta = instance.getCellMeta(current.row, current.col);
  424. if ((source === 'CopyPaste.paste' || source === 'Autofill.fill') && cellMeta.skipColumnOnPaste) {
  425. skippedColumn++;
  426. current.col++;
  427. clen++;
  428. continue;
  429. }
  430. if (cellMeta.readOnly) {
  431. current.col++;
  432. /* eslint-disable no-continue */
  433. continue;
  434. }
  435. var logicalColumn = c - skippedColumn;
  436. var value = getInputValue(logicalRow, logicalColumn);
  437. var orgValue = instance.getDataAtCell(current.row, current.col);
  438. var index = {
  439. row: logicalRow,
  440. col: logicalColumn
  441. };
  442. if (source === 'Autofill.fill') {
  443. var result = instance.runHooks('beforeAutofillInsidePopulate', index, direction, input, deltas, {}, selected);
  444. if (result) {
  445. value = isUndefined(result.value) ? value : result.value;
  446. }
  447. }
  448. if (value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
  449. if (orgValue === null || (typeof orgValue === 'undefined' ? 'undefined' : _typeof(orgValue)) !== 'object') {
  450. pushData = false;
  451. } else {
  452. var orgValueSchema = duckSchema(orgValue[0] || orgValue);
  453. var valueSchema = duckSchema(value[0] || value);
  454. /* eslint-disable max-depth */
  455. if (isObjectEquals(orgValueSchema, valueSchema)) {
  456. value = deepClone(value);
  457. } else {
  458. pushData = false;
  459. }
  460. }
  461. } else if (orgValue !== null && (typeof orgValue === 'undefined' ? 'undefined' : _typeof(orgValue)) === 'object') {
  462. pushData = false;
  463. }
  464. if (pushData) {
  465. setData.push([current.row, current.col, value]);
  466. }
  467. pushData = true;
  468. current.col++;
  469. }
  470. current.row++;
  471. }
  472. instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
  473. break;
  474. }
  475. }
  476. };
  477. /* eslint-disable no-multi-assign */
  478. this.selection = selection = { // this public assignment is only temporary
  479. inProgress: false,
  480. selectedHeader: {
  481. cols: false,
  482. rows: false
  483. },
  484. /**
  485. * @param {Boolean} [rows=false]
  486. * @param {Boolean} [cols=false]
  487. * @param {Boolean} [corner=false]
  488. */
  489. setSelectedHeaders: function setSelectedHeaders() {
  490. var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  491. var cols = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  492. var corner = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  493. instance.selection.selectedHeader.rows = rows;
  494. instance.selection.selectedHeader.cols = cols;
  495. instance.selection.selectedHeader.corner = corner;
  496. },
  497. /**
  498. * Sets inProgress to `true`. This enables onSelectionEnd and onSelectionEndByProp to function as desired.
  499. */
  500. begin: function begin() {
  501. instance.selection.inProgress = true;
  502. },
  503. /**
  504. * Sets inProgress to `false`. Triggers onSelectionEnd and onSelectionEndByProp.
  505. */
  506. finish: function finish() {
  507. var sel = instance.getSelected();
  508. instance.runHooks('afterSelectionEnd', sel[0], sel[1], sel[2], sel[3]);
  509. instance.runHooks('afterSelectionEndByProp', sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3]));
  510. instance.selection.inProgress = false;
  511. },
  512. /**
  513. * @returns {Boolean}
  514. */
  515. isInProgress: function isInProgress() {
  516. return instance.selection.inProgress;
  517. },
  518. /**
  519. * Starts selection range on given td object.
  520. *
  521. * @param {CellCoords} coords
  522. * @param keepEditorOpened
  523. */
  524. setRangeStart: function setRangeStart(coords, keepEditorOpened) {
  525. instance.runHooks('beforeSetRangeStart', coords);
  526. priv.selRange = new CellRange(coords, coords, coords);
  527. selection.setRangeEnd(coords, null, keepEditorOpened);
  528. },
  529. /**
  530. * Starts selection range on given td object.
  531. *
  532. * @param {CellCoords} coords
  533. * @param keepEditorOpened
  534. */
  535. setRangeStartOnly: function setRangeStartOnly(coords) {
  536. instance.runHooks('beforeSetRangeStartOnly', coords);
  537. priv.selRange = new CellRange(coords, coords, coords);
  538. },
  539. /**
  540. * Ends selection range on given td object.
  541. *
  542. * @param {CellCoords} coords
  543. * @param {Boolean} [scrollToCell=true] If `true`, viewport will be scrolled to range end
  544. * @param {Boolean} [keepEditorOpened] If `true`, cell editor will be still opened after changing selection range
  545. */
  546. setRangeEnd: function setRangeEnd(coords, scrollToCell, keepEditorOpened) {
  547. if (priv.selRange === null) {
  548. return;
  549. }
  550. var disableVisualSelection,
  551. isHeaderSelected = false,
  552. areCoordsPositive = true;
  553. var firstVisibleRow = instance.view.wt.wtTable.getFirstVisibleRow();
  554. var firstVisibleColumn = instance.view.wt.wtTable.getFirstVisibleColumn();
  555. var newRangeCoords = {
  556. row: null,
  557. col: null
  558. };
  559. // trigger handlers
  560. instance.runHooks('beforeSetRangeEnd', coords);
  561. instance.selection.begin();
  562. newRangeCoords.row = coords.row < 0 ? firstVisibleRow : coords.row;
  563. newRangeCoords.col = coords.col < 0 ? firstVisibleColumn : coords.col;
  564. priv.selRange.to = new CellCoords(newRangeCoords.row, newRangeCoords.col);
  565. if (!priv.settings.multiSelect) {
  566. priv.selRange.from = coords;
  567. }
  568. // set up current selection
  569. instance.view.wt.selections.current.clear();
  570. disableVisualSelection = instance.getCellMeta(priv.selRange.highlight.row, priv.selRange.highlight.col).disableVisualSelection;
  571. if (typeof disableVisualSelection === 'string') {
  572. disableVisualSelection = [disableVisualSelection];
  573. }
  574. if (disableVisualSelection === false || Array.isArray(disableVisualSelection) && disableVisualSelection.indexOf('current') === -1) {
  575. instance.view.wt.selections.current.add(priv.selRange.highlight);
  576. }
  577. // set up area selection
  578. instance.view.wt.selections.area.clear();
  579. if ((disableVisualSelection === false || Array.isArray(disableVisualSelection) && disableVisualSelection.indexOf('area') === -1) && selection.isMultiple()) {
  580. instance.view.wt.selections.area.add(priv.selRange.from);
  581. instance.view.wt.selections.area.add(priv.selRange.to);
  582. }
  583. // set up highlight
  584. if (priv.settings.currentHeaderClassName || priv.settings.currentRowClassName || priv.settings.currentColClassName) {
  585. instance.view.wt.selections.highlight.clear();
  586. instance.view.wt.selections.highlight.add(priv.selRange.from);
  587. instance.view.wt.selections.highlight.add(priv.selRange.to);
  588. }
  589. var preventScrolling = createObjectPropListener('value');
  590. // trigger handlers
  591. instance.runHooks('afterSelection', priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col, preventScrolling);
  592. instance.runHooks('afterSelectionByProp', priv.selRange.from.row, datamap.colToProp(priv.selRange.from.col), priv.selRange.to.row, datamap.colToProp(priv.selRange.to.col), preventScrolling);
  593. if (priv.selRange.from.row === 0 && priv.selRange.to.row === instance.countRows() - 1 && instance.countRows() > 1 || priv.selRange.from.col === 0 && priv.selRange.to.col === instance.countCols() - 1 && instance.countCols() > 1) {
  594. isHeaderSelected = true;
  595. }
  596. if (coords.row < 0 || coords.col < 0) {
  597. areCoordsPositive = false;
  598. }
  599. if (preventScrolling.isTouched()) {
  600. scrollToCell = !preventScrolling.value;
  601. }
  602. if (scrollToCell !== false && !isHeaderSelected && areCoordsPositive) {
  603. if (priv.selRange.from && !selection.isMultiple()) {
  604. instance.view.scrollViewport(priv.selRange.from);
  605. } else {
  606. instance.view.scrollViewport(coords);
  607. }
  608. }
  609. if (selection.selectedHeader.rows && selection.selectedHeader.cols) {
  610. addClass(instance.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
  611. } else if (selection.selectedHeader.rows) {
  612. removeClass(instance.rootElement, 'ht__selection--columns');
  613. addClass(instance.rootElement, 'ht__selection--rows');
  614. } else if (selection.selectedHeader.cols) {
  615. removeClass(instance.rootElement, 'ht__selection--rows');
  616. addClass(instance.rootElement, 'ht__selection--columns');
  617. } else {
  618. removeClass(instance.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
  619. }
  620. selection.refreshBorders(null, keepEditorOpened);
  621. },
  622. /**
  623. * Destroys editor, redraws borders around cells, prepares editor.
  624. *
  625. * @param {Boolean} [revertOriginal]
  626. * @param {Boolean} [keepEditor]
  627. */
  628. refreshBorders: function refreshBorders(revertOriginal, keepEditor) {
  629. if (!keepEditor) {
  630. editorManager.destroyEditor(revertOriginal);
  631. }
  632. instance.view.render();
  633. if (selection.isSelected() && !keepEditor) {
  634. editorManager.prepareEditor();
  635. }
  636. },
  637. /**
  638. * Returns information if we have a multiselection.
  639. *
  640. * @returns {Boolean}
  641. */
  642. isMultiple: function isMultiple() {
  643. var isMultiple = !(priv.selRange.to.col === priv.selRange.from.col && priv.selRange.to.row === priv.selRange.from.row),
  644. modifier = instance.runHooks('afterIsMultipleSelection', isMultiple);
  645. if (isMultiple) {
  646. return modifier;
  647. }
  648. },
  649. /**
  650. * Selects cell relative to current cell (if possible).
  651. */
  652. transformStart: function transformStart(rowDelta, colDelta, force, keepEditorOpened) {
  653. var delta = new CellCoords(rowDelta, colDelta),
  654. rowTransformDir = 0,
  655. colTransformDir = 0,
  656. totalRows,
  657. totalCols,
  658. coords,
  659. fixedRowsBottom;
  660. instance.runHooks('modifyTransformStart', delta);
  661. totalRows = instance.countRows();
  662. totalCols = instance.countCols();
  663. fixedRowsBottom = instance.getSettings().fixedRowsBottom;
  664. if (priv.selRange.highlight.row + rowDelta > totalRows - 1) {
  665. if (force && priv.settings.minSpareRows > 0 && !(fixedRowsBottom && priv.selRange.highlight.row >= totalRows - fixedRowsBottom - 1)) {
  666. instance.alter('insert_row', totalRows);
  667. totalRows = instance.countRows();
  668. } else if (priv.settings.autoWrapCol) {
  669. delta.row = 1 - totalRows;
  670. delta.col = priv.selRange.highlight.col + delta.col == totalCols - 1 ? 1 - totalCols : 1;
  671. }
  672. } else if (priv.settings.autoWrapCol && priv.selRange.highlight.row + delta.row < 0 && priv.selRange.highlight.col + delta.col >= 0) {
  673. delta.row = totalRows - 1;
  674. delta.col = priv.selRange.highlight.col + delta.col == 0 ? totalCols - 1 : -1;
  675. }
  676. if (priv.selRange.highlight.col + delta.col > totalCols - 1) {
  677. if (force && priv.settings.minSpareCols > 0) {
  678. instance.alter('insert_col', totalCols);
  679. totalCols = instance.countCols();
  680. } else if (priv.settings.autoWrapRow) {
  681. delta.row = priv.selRange.highlight.row + delta.row == totalRows - 1 ? 1 - totalRows : 1;
  682. delta.col = 1 - totalCols;
  683. }
  684. } else if (priv.settings.autoWrapRow && priv.selRange.highlight.col + delta.col < 0 && priv.selRange.highlight.row + delta.row >= 0) {
  685. delta.row = priv.selRange.highlight.row + delta.row == 0 ? totalRows - 1 : -1;
  686. delta.col = totalCols - 1;
  687. }
  688. coords = new CellCoords(priv.selRange.highlight.row + delta.row, priv.selRange.highlight.col + delta.col);
  689. if (coords.row < 0) {
  690. rowTransformDir = -1;
  691. coords.row = 0;
  692. } else if (coords.row > 0 && coords.row >= totalRows) {
  693. rowTransformDir = 1;
  694. coords.row = totalRows - 1;
  695. }
  696. if (coords.col < 0) {
  697. colTransformDir = -1;
  698. coords.col = 0;
  699. } else if (coords.col > 0 && coords.col >= totalCols) {
  700. colTransformDir = 1;
  701. coords.col = totalCols - 1;
  702. }
  703. instance.runHooks('afterModifyTransformStart', coords, rowTransformDir, colTransformDir);
  704. selection.setRangeStart(coords, keepEditorOpened);
  705. },
  706. /**
  707. * Sets selection end cell relative to current selection end cell (if possible).
  708. */
  709. transformEnd: function transformEnd(rowDelta, colDelta) {
  710. var delta = new CellCoords(rowDelta, colDelta),
  711. rowTransformDir = 0,
  712. colTransformDir = 0,
  713. totalRows,
  714. totalCols,
  715. coords;
  716. instance.runHooks('modifyTransformEnd', delta);
  717. totalRows = instance.countRows();
  718. totalCols = instance.countCols();
  719. coords = new CellCoords(priv.selRange.to.row + delta.row, priv.selRange.to.col + delta.col);
  720. if (coords.row < 0) {
  721. rowTransformDir = -1;
  722. coords.row = 0;
  723. } else if (coords.row > 0 && coords.row >= totalRows) {
  724. rowTransformDir = 1;
  725. coords.row = totalRows - 1;
  726. }
  727. if (coords.col < 0) {
  728. colTransformDir = -1;
  729. coords.col = 0;
  730. } else if (coords.col > 0 && coords.col >= totalCols) {
  731. colTransformDir = 1;
  732. coords.col = totalCols - 1;
  733. }
  734. instance.runHooks('afterModifyTransformEnd', coords, rowTransformDir, colTransformDir);
  735. selection.setRangeEnd(coords, true);
  736. },
  737. /**
  738. * Returns `true` if currently there is a selection on screen, `false` otherwise.
  739. *
  740. * @returns {Boolean}
  741. */
  742. isSelected: function isSelected() {
  743. return priv.selRange !== null;
  744. },
  745. /**
  746. * Returns `true` if coords is within current selection coords.
  747. *
  748. * @param {CellCoords} coords
  749. * @returns {Boolean}
  750. */
  751. inInSelection: function inInSelection(coords) {
  752. if (!selection.isSelected()) {
  753. return false;
  754. }
  755. return priv.selRange.includes(coords);
  756. },
  757. /**
  758. * Deselects all selected cells
  759. */
  760. deselect: function deselect() {
  761. if (!selection.isSelected()) {
  762. return;
  763. }
  764. instance.selection.inProgress = false; // needed by HT inception
  765. priv.selRange = null;
  766. instance.view.wt.selections.current.clear();
  767. instance.view.wt.selections.area.clear();
  768. if (priv.settings.currentHeaderClassName || priv.settings.currentRowClassName || priv.settings.currentColClassName) {
  769. instance.view.wt.selections.highlight.clear();
  770. }
  771. editorManager.destroyEditor();
  772. selection.refreshBorders();
  773. removeClass(instance.rootElement, ['ht__selection--rows', 'ht__selection--columns']);
  774. instance.runHooks('afterDeselect');
  775. },
  776. /**
  777. * Select all cells
  778. */
  779. selectAll: function selectAll() {
  780. if (!priv.settings.multiSelect) {
  781. return;
  782. }
  783. selection.setSelectedHeaders(true, true, true);
  784. selection.setRangeStart(new CellCoords(0, 0));
  785. selection.setRangeEnd(new CellCoords(instance.countRows() - 1, instance.countCols() - 1), false);
  786. },
  787. /**
  788. * Deletes data from selected cells
  789. */
  790. empty: function empty() {
  791. if (!selection.isSelected()) {
  792. return;
  793. }
  794. var topLeft = priv.selRange.getTopLeftCorner();
  795. var bottomRight = priv.selRange.getBottomRightCorner();
  796. var r,
  797. c,
  798. changes = [];
  799. for (r = topLeft.row; r <= bottomRight.row; r++) {
  800. for (c = topLeft.col; c <= bottomRight.col; c++) {
  801. if (!instance.getCellMeta(r, c).readOnly) {
  802. changes.push([r, c, '']);
  803. }
  804. }
  805. }
  806. instance.setDataAtCell(changes);
  807. }
  808. };
  809. this.init = function () {
  810. dataSource.setData(priv.settings.data);
  811. instance.runHooks('beforeInit');
  812. if (isMobileBrowser()) {
  813. addClass(instance.rootElement, 'mobile');
  814. }
  815. this.updateSettings(priv.settings, true);
  816. this.view = new TableView(this);
  817. editorManager = new EditorManager(instance, priv, selection, datamap);
  818. this.forceFullRender = true; // used when data was changed
  819. instance.runHooks('init');
  820. this.view.render();
  821. if (_typeof(priv.firstRun) === 'object') {
  822. instance.runHooks('afterChange', priv.firstRun[0], priv.firstRun[1]);
  823. priv.firstRun = false;
  824. }
  825. instance.runHooks('afterInit');
  826. };
  827. function ValidatorsQueue() {
  828. // moved this one level up so it can be used in any function here. Probably this should be moved to a separate file
  829. var resolved = false;
  830. return {
  831. validatorsInQueue: 0,
  832. valid: true,
  833. addValidatorToQueue: function addValidatorToQueue() {
  834. this.validatorsInQueue++;
  835. resolved = false;
  836. },
  837. removeValidatorFormQueue: function removeValidatorFormQueue() {
  838. this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1;
  839. this.checkIfQueueIsEmpty();
  840. },
  841. onQueueEmpty: function onQueueEmpty(valid) {},
  842. checkIfQueueIsEmpty: function checkIfQueueIsEmpty() {
  843. if (this.validatorsInQueue == 0 && resolved == false) {
  844. resolved = true;
  845. this.onQueueEmpty(this.valid);
  846. }
  847. }
  848. };
  849. }
  850. function validateChanges(changes, source, callback) {
  851. var waitingForValidator = new ValidatorsQueue();
  852. waitingForValidator.onQueueEmpty = resolve;
  853. for (var i = changes.length - 1; i >= 0; i--) {
  854. if (changes[i] === null) {
  855. changes.splice(i, 1);
  856. } else {
  857. var row = changes[i][0];
  858. var col = datamap.propToCol(changes[i][1]);
  859. var cellProperties = instance.getCellMeta(row, col);
  860. if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') {
  861. if (changes[i][3].length > 0 && (/^-?[\d\s]*(\.|,)?\d*$/.test(changes[i][3]) || cellProperties.format)) {
  862. var len = changes[i][3].length;
  863. if (isUndefined(cellProperties.language)) {
  864. numbro.culture('en-US');
  865. } else if (changes[i][3].indexOf('.') === len - 3 && changes[i][3].indexOf(',') === -1) {
  866. // this input in format XXXX.XX is likely to come from paste. Let's parse it using international rules
  867. numbro.culture('en-US');
  868. } else {
  869. numbro.culture(cellProperties.language);
  870. }
  871. var _numbro$cultureData = numbro.cultureData(numbro.culture()),
  872. delimiters = _numbro$cultureData.delimiters;
  873. // try to parse to float - https://github.com/foretagsplatsen/numbro/pull/183
  874. if (numbro.validate(changes[i][3]) && !isNaN(changes[i][3])) {
  875. changes[i][3] = parseFloat(changes[i][3]);
  876. } else {
  877. changes[i][3] = numbro().unformat(changes[i][3]) || changes[i][3];
  878. }
  879. }
  880. }
  881. /* eslint-disable no-loop-func */
  882. if (instance.getCellValidator(cellProperties)) {
  883. waitingForValidator.addValidatorToQueue();
  884. instance.validateCell(changes[i][3], cellProperties, function (i, cellProperties) {
  885. return function (result) {
  886. if (typeof result !== 'boolean') {
  887. throw new Error('Validation error: result is not boolean');
  888. }
  889. if (result === false && cellProperties.allowInvalid === false) {
  890. changes.splice(i, 1); // cancel the change
  891. cellProperties.valid = true; // we cancelled the change, so cell value is still valid
  892. var cell = instance.getCell(cellProperties.row, cellProperties.col);
  893. removeClass(cell, instance.getSettings().invalidCellClassName);
  894. --i;
  895. }
  896. waitingForValidator.removeValidatorFormQueue();
  897. };
  898. }(i, cellProperties), source);
  899. }
  900. }
  901. }
  902. waitingForValidator.checkIfQueueIsEmpty();
  903. function resolve() {
  904. var beforeChangeResult;
  905. if (changes.length) {
  906. beforeChangeResult = instance.runHooks('beforeChange', changes, source);
  907. if (isFunction(beforeChangeResult)) {
  908. console.warn('Your beforeChange callback returns a function. It\'s not supported since Handsontable 0.12.1 (and the returned function will not be executed).');
  909. } else if (beforeChangeResult === false) {
  910. changes.splice(0, changes.length); // invalidate all changes (remove everything from array)
  911. }
  912. }
  913. callback(); // called when async validators are resolved and beforeChange was not async
  914. }
  915. }
  916. /**
  917. * Internal function to apply changes. Called after validateChanges
  918. *
  919. * @private
  920. * @param {Array} changes Array in form of [row, prop, oldValue, newValue]
  921. * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
  922. * @fires Hooks#beforeChangeRender
  923. * @fires Hooks#afterChange
  924. */
  925. function applyChanges(changes, source) {
  926. var i = changes.length - 1;
  927. if (i < 0) {
  928. return;
  929. }
  930. for (; i >= 0; i--) {
  931. var skipThisChange = false;
  932. if (changes[i] === null) {
  933. changes.splice(i, 1);
  934. /* eslint-disable no-continue */
  935. continue;
  936. }
  937. if (changes[i][2] == null && changes[i][3] == null) {
  938. /* eslint-disable no-continue */
  939. continue;
  940. }
  941. if (priv.settings.allowInsertRow) {
  942. while (changes[i][0] > instance.countRows() - 1) {
  943. var numberOfCreatedRows = datamap.createRow(void 0, void 0, source);
  944. if (numberOfCreatedRows === 0) {
  945. skipThisChange = true;
  946. break;
  947. }
  948. }
  949. }
  950. if (skipThisChange) {
  951. /* eslint-disable no-continue */
  952. continue;
  953. }
  954. if (instance.dataType === 'array' && (!priv.settings.columns || priv.settings.columns.length === 0) && priv.settings.allowInsertColumn) {
  955. while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
  956. datamap.createCol(void 0, void 0, source);
  957. }
  958. }
  959. datamap.set(changes[i][0], changes[i][1], changes[i][3]);
  960. }
  961. instance.forceFullRender = true; // used when data was changed
  962. grid.adjustRowsAndCols();
  963. instance.runHooks('beforeChangeRender', changes, source);
  964. selection.refreshBorders(null, true);
  965. instance.view.wt.wtOverlays.adjustElementsSize();
  966. instance.runHooks('afterChange', changes, source || 'edit');
  967. var activeEditor = instance.getActiveEditor();
  968. if (activeEditor && isDefined(activeEditor.refreshValue)) {
  969. activeEditor.refreshValue();
  970. }
  971. }
  972. this.validateCell = function (value, cellProperties, callback, source) {
  973. var validator = instance.getCellValidator(cellProperties);
  974. function done(valid) {
  975. var col = cellProperties.visualCol,
  976. row = cellProperties.visualRow,
  977. td = instance.getCell(row, col, true);
  978. if (td && td.nodeName != 'TH') {
  979. instance.view.wt.wtSettings.settings.cellRenderer(row, col, td);
  980. }
  981. callback(valid);
  982. }
  983. if (isRegExp(validator)) {
  984. validator = function (validator) {
  985. return function (value, callback) {
  986. callback(validator.test(value));
  987. };
  988. }(validator);
  989. }
  990. if (isFunction(validator)) {
  991. value = instance.runHooks('beforeValidate', value, cellProperties.visualRow, cellProperties.prop, source);
  992. // To provide consistent behaviour, validation should be always asynchronous
  993. instance._registerTimeout(setTimeout(function () {
  994. validator.call(cellProperties, value, function (valid) {
  995. valid = instance.runHooks('afterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source);
  996. cellProperties.valid = valid;
  997. done(valid);
  998. instance.runHooks('postAfterValidate', valid, value, cellProperties.visualRow, cellProperties.prop, source);
  999. });
  1000. }, 0));
  1001. } else {
  1002. // resolve callback even if validator function was not found
  1003. instance._registerTimeout(setTimeout(function () {
  1004. cellProperties.valid = true;
  1005. done(cellProperties.valid);
  1006. }, 0));
  1007. }
  1008. };
  1009. function setDataInputToArray(row, propOrCol, value) {
  1010. if ((typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
  1011. // is it an array of changes
  1012. return row;
  1013. }
  1014. return [[row, propOrCol, value]];
  1015. }
  1016. /**
  1017. * @description
  1018. * Set new value to a cell. To change many cells at once, pass an array of `changes` in format `[[row, col, value], ...]` as
  1019. * the only parameter. `col` is the index of a __visible__ column (note that if columns were reordered,
  1020. * the current visible order will be used). `source` is a flag for before/afterChange events. If you pass only array of
  1021. * changes then `source` could be set as second parameter.
  1022. *
  1023. * @memberof Core#
  1024. * @function setDataAtCell
  1025. * @param {Number|Array} row Row index or array of changes in format `[[row, col, value], ...]`.
  1026. * @param {Number} col Column index.
  1027. * @param {String} value New value.
  1028. * @param {String} [source] String that identifies how this change will be described in the changes array (useful in onAfterChange or onBeforeChange callback).
  1029. */
  1030. this.setDataAtCell = function (row, col, value, source) {
  1031. var input = setDataInputToArray(row, col, value),
  1032. i,
  1033. ilen,
  1034. changes = [],
  1035. prop;
  1036. for (i = 0, ilen = input.length; i < ilen; i++) {
  1037. if (_typeof(input[i]) !== 'object') {
  1038. throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
  1039. }
  1040. if (typeof input[i][1] !== 'number') {
  1041. throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
  1042. }
  1043. prop = datamap.colToProp(input[i][1]);
  1044. changes.push([input[i][0], prop, dataSource.getAtCell(recordTranslator.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]);
  1045. }
  1046. if (!source && (typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
  1047. source = col;
  1048. }
  1049. instance.runHooks('afterSetDataAtCell', changes, source);
  1050. validateChanges(changes, source, function () {
  1051. applyChanges(changes, source);
  1052. });
  1053. };
  1054. /**
  1055. * @description
  1056. * Set new value to a cell. To change many cells at once, pass an array of `changes` in format `[[row, prop, value], ...]` as
  1057. * the only parameter. `prop` is the name of the object property (e.g. `first.name`). `source` is a flag for before/afterChange events.
  1058. * If you pass only array of changes then `source` could be set as second parameter.
  1059. *
  1060. * @memberof Core#
  1061. * @function setDataAtRowProp
  1062. * @param {Number|Array} row Row index or array of changes in format `[[row, prop, value], ...]`.
  1063. * @param {String} prop Property name or the source string.
  1064. * @param {String} value Value to be set.
  1065. * @param {String} [source] String that identifies how this change will be described in changes array (useful in onChange callback).
  1066. */
  1067. this.setDataAtRowProp = function (row, prop, value, source) {
  1068. var input = setDataInputToArray(row, prop, value),
  1069. i,
  1070. ilen,
  1071. changes = [];
  1072. for (i = 0, ilen = input.length; i < ilen; i++) {
  1073. changes.push([input[i][0], input[i][1], dataSource.getAtCell(recordTranslator.toPhysicalRow(input[i][0]), input[i][1]), input[i][2]]);
  1074. }
  1075. if (!source && (typeof row === 'undefined' ? 'undefined' : _typeof(row)) === 'object') {
  1076. source = prop;
  1077. }
  1078. instance.runHooks('afterSetDataAtRowProp', changes, source);
  1079. validateChanges(changes, source, function () {
  1080. applyChanges(changes, source);
  1081. });
  1082. };
  1083. /**
  1084. * Listen to the keyboard input on document body.
  1085. *
  1086. * @memberof Core#
  1087. * @function listen
  1088. * @since 0.11
  1089. */
  1090. this.listen = function () {
  1091. activeGuid = instance.guid;
  1092. };
  1093. /**
  1094. * Stop listening to keyboard input on the document body.
  1095. *
  1096. * @memberof Core#
  1097. * @function unlisten
  1098. * @since 0.11
  1099. */
  1100. this.unlisten = function () {
  1101. activeGuid = null;
  1102. };
  1103. /**
  1104. * Returns `true` if the current Handsontable instance is listening to keyboard input on document body.
  1105. *
  1106. * @memberof Core#
  1107. * @function isListening
  1108. * @since 0.11
  1109. * @returns {Boolean} `true` if the instance is listening, `false` otherwise.
  1110. */
  1111. this.isListening = function () {
  1112. return activeGuid === instance.guid;
  1113. };
  1114. /**
  1115. * Destroys the current editor, renders and selects the current cell.
  1116. *
  1117. * @memberof Core#
  1118. * @function destroyEditor
  1119. * @param {Boolean} [revertOriginal] If != `true`, edited data is saved. Otherwise the previous value is restored.
  1120. */
  1121. this.destroyEditor = function (revertOriginal) {
  1122. selection.refreshBorders(revertOriginal);
  1123. };
  1124. /**
  1125. * Populate cells at position with 2D input array (e.g. `[[1, 2], [3, 4]]`).
  1126. * Use `endRow`, `endCol` when you want to cut input when a certain row is reached.
  1127. * Optional `source` parameter (default value "populateFromArray") is used to identify this call in the resulting events (beforeChange, afterChange).
  1128. * Optional `populateMethod` parameter (default value "overwrite", possible values "shift_down" and "shift_right")
  1129. * has the same effect as pasteMode option {@link Options#pasteMode}
  1130. *
  1131. * @memberof Core#
  1132. * @function populateFromArray
  1133. * @since 0.9.0
  1134. * @param {Number} row Start row
  1135. * @param {Number} col Start column
  1136. * @param {Array} input 2d array
  1137. * @param {Number} [endRow] End row (use when you want to cut input when certain row is reached)
  1138. * @param {Number} [endCol] End column (use when you want to cut input when certain column is reached)
  1139. * @param {String} [source="populateFromArray"] Source string.
  1140. * @param {String} [method="overwrite"] Populate method. Possible options: `shift_down`, `shift_right`, `overwrite`.
  1141. * @param {String} direction Populate direction. (left|right|up|down)
  1142. * @param {Array} deltas Deltas array.
  1143. * @returns {Object|undefined} The ending TD element in pasted area (only if any cells were changed).
  1144. */
  1145. this.populateFromArray = function (row, col, input, endRow, endCol, source, method, direction, deltas) {
  1146. var c;
  1147. if (!((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && _typeof(input[0]) === 'object')) {
  1148. throw new Error('populateFromArray parameter `input` must be an array of arrays'); // API changed in 0.9-beta2, let's check if you use it correctly
  1149. }
  1150. c = typeof endRow === 'number' ? new CellCoords(endRow, endCol) : null;
  1151. return grid.populateFromArray(new CellCoords(row, col), input, c, source, method, direction, deltas);
  1152. };
  1153. /**
  1154. * Adds/removes data from the column. This function is modelled after Array.splice.
  1155. * Parameter `col` is the index of the column in which do you want to do splice.
  1156. * Parameter `index` is the row index at which to start changing the array.
  1157. * If negative, will begin that many elements from the end. Parameter `amount`, is the number of the old array elements to remove.
  1158. * If the amount is 0, no elements are removed. Fourth and further parameters are the `elements` to add to the array.
  1159. * If you don't specify any elements, spliceCol simply removes elements from the array.
  1160. * {@link DataMap#spliceCol}
  1161. *
  1162. * @memberof Core#
  1163. * @function spliceCol
  1164. * @since 0.9-beta2
  1165. * @param {Number} col Index of the column in which do you want to do splice.
  1166. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
  1167. * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed.
  1168. * @param {*} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array.
  1169. */
  1170. this.spliceCol = function (col, index, amount /* , elements... */) {
  1171. var _datamap;
  1172. return (_datamap = datamap).spliceCol.apply(_datamap, arguments);
  1173. };
  1174. /**
  1175. * Adds/removes data from the row. This function works is modelled after Array.splice.
  1176. * Parameter `row` is the index of row in which do you want to do splice.
  1177. * Parameter `index` is the column index at which to start changing the array.
  1178. * If negative, will begin that many elements from the end. Parameter `amount`, is the number of old array elements to remove.
  1179. * If the amount is 0, no elements are removed. Fourth and further parameters are the `elements` to add to the array.
  1180. * If you don't specify any elements, spliceCol simply removes elements from the array.
  1181. * {@link DataMap#spliceRow}
  1182. *
  1183. * @memberof Core#
  1184. * @function spliceRow
  1185. * @since 0.11
  1186. * @param {Number} row Index of column in which do you want to do splice.
  1187. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
  1188. * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed.
  1189. * @param {*} [elements] The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array.
  1190. */
  1191. this.spliceRow = function (row, index, amount /* , elements... */) {
  1192. var _datamap2;
  1193. return (_datamap2 = datamap).spliceRow.apply(_datamap2, arguments);
  1194. };
  1195. /**
  1196. * Returns indexes of the currently selected cells as an array `[startRow, startCol, endRow, endCol]`.
  1197. *
  1198. * Start row and start col are the coordinates of the active cell (where the selection was started).
  1199. *
  1200. * @memberof Core#
  1201. * @function getSelected
  1202. * @returns {Array} Array of the selection's indexes.
  1203. */
  1204. this.getSelected = function () {
  1205. // https://github.com/handsontable/handsontable/issues/44 //cjl
  1206. if (selection.isSelected()) {
  1207. return [priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col];
  1208. }
  1209. };
  1210. /**
  1211. * Returns the current selection as a CellRange object.
  1212. *
  1213. * @memberof Core#
  1214. * @function getSelectedRange
  1215. * @since 0.11
  1216. * @returns {CellRange} Selected range object or undefined` if there is no selection.
  1217. */
  1218. this.getSelectedRange = function () {
  1219. // https://github.com/handsontable/handsontable/issues/44 //cjl
  1220. if (selection.isSelected()) {
  1221. return priv.selRange;
  1222. }
  1223. };
  1224. /**
  1225. * Rerender the table.
  1226. *
  1227. * @memberof Core#
  1228. * @function render
  1229. */
  1230. this.render = function () {
  1231. if (instance.view) {
  1232. instance.renderCall = true;
  1233. instance.forceFullRender = true; // used when data was changed
  1234. selection.refreshBorders(null, true);
  1235. }
  1236. };
  1237. /**
  1238. * Reset all cells in the grid to contain data from the data array.
  1239. *
  1240. * @memberof Core#
  1241. * @function loadData
  1242. * @param {Array} data Array of arrays or array of objects containing data.
  1243. * @fires Hooks#afterLoadData
  1244. * @fires Hooks#afterChange
  1245. */
  1246. this.loadData = function (data) {
  1247. if (Array.isArray(priv.settings.dataSchema)) {
  1248. instance.dataType = 'array';
  1249. } else if (isFunction(priv.settings.dataSchema)) {
  1250. instance.dataType = 'function';
  1251. } else {
  1252. instance.dataType = 'object';
  1253. }
  1254. if (datamap) {
  1255. datamap.destroy();
  1256. }
  1257. datamap = new DataMap(instance, priv, GridSettings);
  1258. if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object' && data !== null) {
  1259. if (!(data.push && data.splice)) {
  1260. // check if data is array. Must use duck-type check so Backbone Collections also pass it
  1261. // when data is not an array, attempt to make a single-row array of it
  1262. data = [data];
  1263. }
  1264. } else if (data === null) {
  1265. data = [];
  1266. var row;
  1267. var r = 0;
  1268. var rlen = 0;
  1269. var dataSchema = datamap.getSchema();
  1270. for (r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
  1271. if ((instance.dataType === 'object' || instance.dataType === 'function') && priv.settings.dataSchema) {
  1272. row = deepClone(dataSchema);
  1273. data.push(row);
  1274. } else if (instance.dataType === 'array') {
  1275. row = deepClone(dataSchema[0]);
  1276. data.push(row);
  1277. } else {
  1278. row = [];
  1279. for (var c = 0, clen = priv.settings.startCols; c < clen; c++) {
  1280. row.push(null);
  1281. }
  1282. data.push(row);
  1283. }
  1284. }
  1285. } else {
  1286. throw new Error('loadData only accepts array of objects or array of arrays (' + (typeof data === 'undefined' ? 'undefined' : _typeof(data)) + ' given)');
  1287. }
  1288. priv.isPopulated = false;
  1289. GridSettings.prototype.data = data;
  1290. if (Array.isArray(data[0])) {
  1291. instance.dataType = 'array';
  1292. }
  1293. datamap.dataSource = data;
  1294. dataSource.data = data;
  1295. dataSource.dataType = instance.dataType;
  1296. dataSource.colToProp = datamap.colToProp.bind(datamap);
  1297. dataSource.propToCol = datamap.propToCol.bind(datamap);
  1298. clearCellSettingCache();
  1299. grid.adjustRowsAndCols();
  1300. instance.runHooks('afterLoadData', priv.firstRun);
  1301. if (priv.firstRun) {
  1302. priv.firstRun = [null, 'loadData'];
  1303. } else {
  1304. instance.runHooks('afterChange', null, 'loadData');
  1305. instance.render();
  1306. }
  1307. priv.isPopulated = true;
  1308. function clearCellSettingCache() {
  1309. priv.cellSettings.length = 0;
  1310. }
  1311. };
  1312. /**
  1313. * Returns the current data object (the same one that was passed by `data` configuration option or `loadData` method,
  1314. * unless the `modifyRow` hook was used to trim some of the rows. If that's the case - use the {@link Core#getSourceData} method.).
  1315. * Optionally you can provide cell range by defining `row`, `col`, `row2`, `col2` to get only a fragment of grid data.
  1316. *
  1317. * Note: getData functionality changed with the release of version 0.20. If you're looking for the previous functionality,
  1318. * you should use the {@link Core#getSourceData} method.
  1319. *
  1320. * @memberof Core#
  1321. * @function getData
  1322. * @param {Number} [r] From row.
  1323. * @param {Number} [c] From column.
  1324. * @param {Number} [r2] To row.
  1325. * @param {Number} [c2] To column.
  1326. * @returns {Array} Array with the data.
  1327. */
  1328. this.getData = function (r, c, r2, c2) {
  1329. if (isUndefined(r)) {
  1330. return datamap.getAll();
  1331. }
  1332. return datamap.getRange(new CellCoords(r, c), new CellCoords(r2, c2), datamap.DESTINATION_RENDERER);
  1333. };
  1334. /**
  1335. * Returns a string value of the selected range. Each column is separated by tab, each row is separated by a new line character.
  1336. * {@link DataMap#getCopyableText}
  1337. *
  1338. * @memberof Core#
  1339. * @function getCopyableText
  1340. * @since 0.11
  1341. * @param {Number} startRow From row.
  1342. * @param {Number} startCol From column.
  1343. * @param {Number} endRow To row.
  1344. * @param {Number} endCol To column.
  1345. * @returns {String}
  1346. */
  1347. this.getCopyableText = function (startRow, startCol, endRow, endCol) {
  1348. return datamap.getCopyableText(new CellCoords(startRow, startCol), new CellCoords(endRow, endCol));
  1349. };
  1350. /**
  1351. * Returns the data's copyable value at specified row and column index ({@link DataMap#getCopyable}).
  1352. *
  1353. * @memberof Core#
  1354. * @function getCopyableData
  1355. * @since 0.19.0
  1356. * @param {Number} row Row index.
  1357. * @param {Number} column Column index.
  1358. * @returns {String}
  1359. */
  1360. this.getCopyableData = function (row, column) {
  1361. return datamap.getCopyable(row, datamap.colToProp(column));
  1362. };
  1363. /**
  1364. * Returns schema provided by constructor settings. If it doesn't exist then it returns the schema based on the data
  1365. * structure in the first row.
  1366. *
  1367. * @memberof Core#
  1368. * @function getSchema
  1369. * @since 0.13.2
  1370. * @returns {Object} Schema object.
  1371. */
  1372. this.getSchema = function () {
  1373. return datamap.getSchema();
  1374. };
  1375. /**
  1376. * Use it if you need to change configuration after initialization. The `settings` parameter is an object containing the new
  1377. * settings, declared the same way as in the initial settings object.
  1378. * Note, that although the `updateSettings` method doesn't overwrite the previously declared settings, it might reset
  1379. * the settings made post-initialization. (for example - ignore changes made using the columnResize feature).
  1380. *
  1381. * @memberof Core#
  1382. * @function updateSettings
  1383. * @param {Object} settings New settings object.
  1384. * @param {Boolean} init
  1385. * @example
  1386. * ```js
  1387. * hot.updateSettings({
  1388. * contextMenu: true,
  1389. * colHeaders: true,
  1390. * fixedRowsTop: 2
  1391. * });
  1392. * ```
  1393. * @fires Hooks#afterCellMetaReset
  1394. * @fires Hooks#afterUpdateSettings
  1395. */
  1396. this.updateSettings = function (settings, init) {
  1397. var columnsAsFunc = false;
  1398. var i = void 0;
  1399. var j = void 0;
  1400. var clen = void 0;
  1401. if (isDefined(settings.rows)) {
  1402. throw new Error('"rows" setting is no longer supported. do you mean startRows, minRows or maxRows?');
  1403. }
  1404. if (isDefined(settings.cols)) {
  1405. throw new Error('"cols" setting is no longer supported. do you mean startCols, minCols or maxCols?');
  1406. }
  1407. for (i in settings) {
  1408. if (i === 'data') {
  1409. /* eslint-disable no-continue */
  1410. continue; // loadData will be triggered later
  1411. } else if (Hooks.getSingleton().getRegistered().indexOf(i) > -1) {
  1412. if (isFunction(settings[i]) || Array.isArray(settings[i])) {
  1413. settings[i].initialHook = true;
  1414. instance.addHook(i, settings[i]);
  1415. }
  1416. } else if (!init && hasOwnProperty(settings, i)) {
  1417. // Update settings
  1418. GridSettings.prototype[i] = settings[i];
  1419. }
  1420. }
  1421. // Load data or create data map
  1422. if (settings.data === void 0 && priv.settings.data === void 0) {
  1423. instance.loadData(null); // data source created just now
  1424. } else if (settings.data !== void 0) {
  1425. instance.loadData(settings.data); // data source given as option
  1426. } else if (settings.columns !== void 0) {
  1427. datamap.createMap();
  1428. }
  1429. clen = instance.countCols();
  1430. var columnSetting = settings.columns || GridSettings.prototype.columns;
  1431. // Init columns constructors configuration
  1432. if (columnSetting && isFunction(columnSetting)) {
  1433. clen = instance.countSourceCols();
  1434. columnsAsFunc = true;
  1435. }
  1436. // Clear cellSettings cache
  1437. if (settings.cell !== void 0 || settings.cells !== void 0 || settings.columns !== void 0) {
  1438. priv.cellSettings.length = 0;
  1439. }
  1440. if (clen > 0) {
  1441. var proto = void 0;
  1442. var column = void 0;
  1443. for (i = 0, j = 0; i < clen; i++) {
  1444. if (columnsAsFunc && !columnSetting(i)) {
  1445. /* eslint-disable no-continue */
  1446. continue;
  1447. }
  1448. priv.columnSettings[j] = columnFactory(GridSettings, priv.columnsSettingConflicts);
  1449. // shortcut for prototype
  1450. proto = priv.columnSettings[j].prototype;
  1451. // Use settings provided by user
  1452. if (columnSetting) {
  1453. if (columnsAsFunc) {
  1454. column = columnSetting(i);
  1455. } else {
  1456. column = columnSetting[j];
  1457. }
  1458. if (column) {
  1459. extend(proto, column);
  1460. extend(proto, expandType(column));
  1461. }
  1462. }
  1463. j++;
  1464. }
  1465. }
  1466. if (isDefined(settings.cell)) {
  1467. for (var key in settings.cell) {
  1468. if (hasOwnProperty(settings.cell, key)) {
  1469. var cell = settings.cell[key];
  1470. instance.setCellMetaObject(cell.row, cell.col, cell);
  1471. }
  1472. }
  1473. }
  1474. instance.runHooks('afterCellMetaReset');
  1475. if (isDefined(settings.className)) {
  1476. if (GridSettings.prototype.className) {
  1477. removeClass(instance.rootElement, GridSettings.prototype.className);
  1478. }
  1479. if (settings.className) {
  1480. addClass(instance.rootElement, settings.className);
  1481. }
  1482. }
  1483. var currentHeight = instance.rootElement.style.height;
  1484. if (currentHeight !== '') {
  1485. currentHeight = parseInt(instance.rootElement.style.height, 10);
  1486. }
  1487. var height = settings.height;
  1488. if (isFunction(height)) {
  1489. height = height();
  1490. }
  1491. if (init) {
  1492. var initialStyle = instance.rootElement.getAttribute('style');
  1493. if (initialStyle) {
  1494. instance.rootElement.setAttribute('data-initialstyle', instance.rootElement.getAttribute('style'));
  1495. }
  1496. }
  1497. if (height === null) {
  1498. var _initialStyle = instance.rootElement.getAttribute('data-initialstyle');
  1499. if (_initialStyle && (_initialStyle.indexOf('height') > -1 || _initialStyle.indexOf('overflow') > -1)) {
  1500. instance.rootElement.setAttribute('style', _initialStyle);
  1501. } else {
  1502. instance.rootElement.style.height = '';
  1503. instance.rootElement.style.overflow = '';
  1504. }
  1505. } else if (height !== void 0) {
  1506. instance.rootElement.style.height = height + 'px';
  1507. instance.rootElement.style.overflow = 'hidden';
  1508. }
  1509. if (typeof settings.width != 'undefined') {
  1510. var width = settings.width;
  1511. if (isFunction(width)) {
  1512. width = width();
  1513. }
  1514. instance.rootElement.style.width = width + 'px';
  1515. }
  1516. if (!init) {
  1517. datamap.clearLengthCache(); // force clear cache length on updateSettings() #3416
  1518. if (instance.view) {
  1519. instance.view.wt.wtViewport.resetHasOversizedColumnHeadersMarked();
  1520. }
  1521. instance.runHooks('afterUpdateSettings');
  1522. }
  1523. grid.adjustRowsAndCols();
  1524. if (instance.view && !priv.firstRun) {
  1525. instance.forceFullRender = true; // used when data was changed
  1526. selection.refreshBorders(null, true);
  1527. }
  1528. if (!init && instance.view && (currentHeight === '' || height === '' || height === void 0) && currentHeight !== height) {
  1529. instance.view.wt.wtOverlays.updateMainScrollableElements();
  1530. }
  1531. };
  1532. /**
  1533. * Get value from the selected cell.
  1534. *
  1535. * @memberof Core#
  1536. * @function getValue
  1537. * @since 0.11
  1538. * @returns {*} Value of selected cell.
  1539. */
  1540. this.getValue = function () {
  1541. var sel = instance.getSelected();
  1542. if (GridSettings.prototype.getValue) {
  1543. if (isFunction(GridSettings.prototype.getValue)) {
  1544. return GridSettings.prototype.getValue.call(instance);
  1545. } else if (sel) {
  1546. return instance.getData()[sel[0]][GridSettings.prototype.getValue];
  1547. }
  1548. } else if (sel) {
  1549. return instance.getDataAtCell(sel[0], sel[1]);
  1550. }
  1551. };
  1552. function expandType(obj) {
  1553. if (!hasOwnProperty(obj, 'type')) {
  1554. // ignore obj.prototype.type
  1555. return;
  1556. }
  1557. var type,
  1558. expandedType = {};
  1559. if (_typeof(obj.type) === 'object') {
  1560. type = obj.type;
  1561. } else if (typeof obj.type === 'string') {
  1562. type = getCellType(obj.type);
  1563. }
  1564. for (var i in type) {
  1565. if (hasOwnProperty(type, i) && !hasOwnProperty(obj, i)) {
  1566. expandedType[i] = type[i];
  1567. }
  1568. }
  1569. return expandedType;
  1570. }
  1571. /**
  1572. * Returns the object settings.
  1573. *
  1574. * @memberof Core#
  1575. * @function getSettings
  1576. * @returns {Object} Object containing the current grid settings.
  1577. */
  1578. this.getSettings = function () {
  1579. return priv.settings;
  1580. };
  1581. /**
  1582. * Clears the data from the grid. (The table settings remain intact.)
  1583. *
  1584. * @memberof Core#
  1585. * @function clear
  1586. * @since 0.11
  1587. */
  1588. this.clear = function () {
  1589. selection.selectAll();
  1590. selection.empty();
  1591. };
  1592. /**
  1593. * @memberof Core#
  1594. * @function alter
  1595. * @param {String} action See grid.alter for possible values: `"insert_row"`, `"insert_col"`, `"remove_row"`, `"remove_col"`
  1596. * @param {Number} index Index of the row/column before which the new row/column will be inserted/removed.
  1597. * @param {Number} [amount = 1] Amound of rows/columns to be inserted/removed.
  1598. * @param {String} [source] Source indicator.
  1599. * @param {Boolean} [keepEmptyRows] Flag for preventing deletion of empty rows.
  1600. * @description
  1601. *
  1602. * Allows altering the table structure by either inserting/removing rows or inserting/removing columns:
  1603. *
  1604. * Insert new row(s) above the row with a given `index`. If index is `null` or `undefined`, the new row will be
  1605. * added after the last row.
  1606. * ```js
  1607. * var hot = new Handsontable(document.getElementById('example'));
  1608. * hot.alter('insert_row', 10);
  1609. * ```
  1610. *
  1611. * Insert new column(s) before the column with a given `index`. If index is `null` or `undefined`, the new column
  1612. * will be added after the last column.
  1613. * ```js
  1614. * var hot = new Handsontable(document.getElementById('example'));
  1615. * hot.alter('insert_col', 10);
  1616. * ```
  1617. *
  1618. * Remove the row(s) at the given `index`.
  1619. * ```js
  1620. * var hot = new Handsontable(document.getElementById('example'));
  1621. * hot.alter('remove_row', 10);
  1622. * ```
  1623. *
  1624. * Remove the column(s) at the given `index`.
  1625. * ```js
  1626. * var hot = new Handsontable(document.getElementById('example'));
  1627. * hot.alter('remove_col', 10);
  1628. * ```
  1629. */
  1630. this.alter = function (action, index, amount, source, keepEmptyRows) {
  1631. grid.alter(action, index, amount, source, keepEmptyRows);
  1632. };
  1633. /**
  1634. * Returns a TD element for the given `row` and `col` arguments, if it is rendered on screen.
  1635. * Returns `null` if the TD is not rendered on screen (probably because that part of the table is not visible).
  1636. *
  1637. * @memberof Core#
  1638. * @function getCell
  1639. * @param {Number} row Row index.
  1640. * @param {Number} col Column index.
  1641. * @param {Boolean} topmost If set to true, it returns the TD element from the topmost overlay. For example,
  1642. * if the wanted cell is in the range of fixed rows, it will return a TD element from the `top` overlay.
  1643. * @returns {Element} The cell's TD element.
  1644. */
  1645. this.getCell = function (row, col, topmost) {
  1646. return instance.view.getCellAtCoords(new CellCoords(row, col), topmost);
  1647. };
  1648. /**
  1649. * Returns the coordinates of the cell, provided as a HTML Element.
  1650. *
  1651. * @memberof Core#
  1652. * @function getCoords
  1653. * @param {Element} elem The HTML Element representing the cell.
  1654. * @returns {CellCoords} Coordinates object.
  1655. */
  1656. this.getCoords = function (elem) {
  1657. return this.view.wt.wtTable.getCoords.call(this.view.wt.wtTable, elem);
  1658. };
  1659. /**
  1660. * Returns the property name that corresponds with the given column index. {@link DataMap#colToProp}
  1661. * If the data source is an array of arrays, it returns the columns index.
  1662. *
  1663. * @memberof Core#
  1664. * @function colToProp
  1665. * @param {Number} col Column index
  1666. * @returns {String|Number} Column property or column index.
  1667. */
  1668. this.colToProp = function (col) {
  1669. return datamap.colToProp(col);
  1670. };
  1671. /**
  1672. * Returns column index that corresponds with the given property. {@link DataMap#propToCol}
  1673. *
  1674. * @memberof Core#
  1675. * @function propToCol
  1676. * @param {String|Number} prop Property name or column index.
  1677. * @returns {Number} Column index.
  1678. */
  1679. this.propToCol = function (prop) {
  1680. return datamap.propToCol(prop);
  1681. };
  1682. /**
  1683. * Translate physical row index into visual.
  1684. *
  1685. * @since 0.29.0
  1686. * @memberof Core#
  1687. * @function toVisualRow
  1688. * @param {Number} row Physical row index.
  1689. * @returns {Number} Returns visual row index.
  1690. */
  1691. this.toVisualRow = function (row) {
  1692. return recordTranslator.toVisualRow(row);
  1693. };
  1694. /**
  1695. * Translate physical column index into visual.
  1696. *
  1697. * @since 0.29.0
  1698. * @memberof Core#
  1699. * @function toVisualColumn
  1700. * @param {Number} column Physical column index.
  1701. * @returns {Number} Returns visual column index.
  1702. */
  1703. this.toVisualColumn = function (column) {
  1704. return recordTranslator.toVisualColumn(column);
  1705. };
  1706. /**
  1707. * Translate visual row index into physical.
  1708. * If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied)
  1709. * to retrieve valid physical row index you can use this method.
  1710. *
  1711. * @since 0.29.0
  1712. * @memberof Core#
  1713. * @function toPhysicalRow
  1714. * @param {Number} row Visual row index.
  1715. * @returns {Number} Returns physical row index.
  1716. */
  1717. this.toPhysicalRow = function (row) {
  1718. return recordTranslator.toPhysicalRow(row);
  1719. };
  1720. /**
  1721. * Translate visual column index into physical.
  1722. * If displayed columns order is different than the order of columns stored in memory (i.e. manual column move is applied)
  1723. * to retrieve valid physical column index you can use this method.
  1724. *
  1725. * @since 0.29.0
  1726. * @memberof Core#
  1727. * @function toPhysicalColumn
  1728. * @param {Number} column Visual column index.
  1729. * @returns {Number} Returns physical column index.
  1730. */
  1731. this.toPhysicalColumn = function (column) {
  1732. return recordTranslator.toPhysicalColumn(column);
  1733. };
  1734. /**
  1735. * @description
  1736. * Returns the cell value at `row`, `col`. `row` and `col` are the __visible__ indexes (note, that if columns were reordered or sorted,
  1737. * the currently visible order will be used).
  1738. *
  1739. * @memberof Core#
  1740. * @function getDataAtCell
  1741. * @param {Number} row Row index.
  1742. * @param {Number} col Column index.
  1743. * @returns {String|Boolean|null} Data at cell.
  1744. */
  1745. this.getDataAtCell = function (row, col) {
  1746. return datamap.get(row, datamap.colToProp(col));
  1747. };
  1748. /**
  1749. * Return value at `row`, `prop`. (Uses {@link DataMap#get})
  1750. *
  1751. * @memberof Core#
  1752. * @function getDataAtRowProp
  1753. * @param {Number} row Row index.
  1754. * @param {String} prop Property name.
  1755. * @returns {*} Cell value.
  1756. */
  1757. this.getDataAtRowProp = function (row, prop) {
  1758. return datamap.get(row, prop);
  1759. };
  1760. /**
  1761. * @description
  1762. * Returns array of column values from the data source. `col` is the __visible__ index of the column.
  1763. * Note, that if columns were reordered or sorted, the currently visible order will be used.
  1764. *
  1765. * @memberof Core#
  1766. * @function getDataAtCol
  1767. * @since 0.9-beta2
  1768. * @param {Number} col Column index.
  1769. * @returns {Array} Array of cell values.
  1770. */
  1771. this.getDataAtCol = function (col) {
  1772. var out = [];
  1773. return out.concat.apply(out, _toConsumableArray(datamap.getRange(new CellCoords(0, col), new CellCoords(priv.settings.data.length - 1, col), datamap.DESTINATION_RENDERER)));
  1774. };
  1775. /**
  1776. * Given the object property name (e.g. `'first.name'`), returns an array of column's values from the data source.
  1777. * You can also provide a column index as the first argument.
  1778. *
  1779. * @memberof Core#
  1780. * @function getDataAtProp
  1781. * @since 0.9-beta2
  1782. * @param {String|Number} prop Property name / column index.
  1783. * @returns {Array} Array of cell values.
  1784. */
  1785. this.getDataAtProp = function (prop) {
  1786. var out = [],
  1787. range;
  1788. range = datamap.getRange(new CellCoords(0, datamap.propToCol(prop)), new CellCoords(priv.settings.data.length - 1, datamap.propToCol(prop)), datamap.DESTINATION_RENDERER);
  1789. return out.concat.apply(out, _toConsumableArray(range));
  1790. };
  1791. /**
  1792. * Returns the source data object (the same that was passed by `data` configuration option or `loadData` method).
  1793. * Optionally you can provide a cell range by using the `row`, `col`, `row2`, `col2` arguments, to get only a fragment of grid data.
  1794. *
  1795. * @memberof Core#
  1796. * @function getSourceData
  1797. * @since 0.20.0
  1798. * @param {Number} [r] From row.
  1799. * @param {Number} [c] From column.
  1800. * @param {Number} [r2] To row.
  1801. * @param {Number} [c2] To column.
  1802. * @returns {Array} Array of grid data.
  1803. */
  1804. this.getSourceData = function (r, c, r2, c2) {
  1805. var data = void 0;
  1806. if (r === void 0) {
  1807. data = dataSource.getData();
  1808. } else {
  1809. data = dataSource.getByRange(new CellCoords(r, c), new CellCoords(r2, c2));
  1810. }
  1811. return data;
  1812. };
  1813. /**
  1814. * Returns the source data object as an arrays of arrays format even when source data was provided in another format.
  1815. * Optionally you can provide a cell range by using the `row`, `col`, `row2`, `col2` arguments, to get only a fragment of grid data.
  1816. *
  1817. * @memberof Core#
  1818. * @function getSourceDataArray
  1819. * @since 0.28.0
  1820. * @param {Number} [r] From row.
  1821. * @param {Number} [c] From column.
  1822. * @param {Number} [r2] To row.
  1823. * @param {Number} [c2] To column.
  1824. * @returns {Array} An array of arrays.
  1825. */
  1826. this.getSourceDataArray = function (r, c, r2, c2) {
  1827. var data = void 0;
  1828. if (r === void 0) {
  1829. data = dataSource.getData(true);
  1830. } else {
  1831. data = dataSource.getByRange(new CellCoords(r, c), new CellCoords(r2, c2), true);
  1832. }
  1833. return data;
  1834. };
  1835. /**
  1836. * Returns an array of column values from the data source. `col` is the index of the row in the data source.
  1837. *
  1838. * @memberof Core#
  1839. * @function getSourceDataAtCol
  1840. * @since 0.11.0-beta3
  1841. * @param {Number} column Column index.
  1842. * @returns {Array} Array of the column's cell values.
  1843. */
  1844. this.getSourceDataAtCol = function (column) {
  1845. return dataSource.getAtColumn(column);
  1846. };
  1847. /**
  1848. * Returns a single row of the data (array or object, depending on what you have). `row` is the index of the row in the data source.
  1849. *
  1850. * @memberof Core#
  1851. * @function getSourceDataAtRow
  1852. * @since 0.11.0-beta3
  1853. * @param {Number} row Row index.
  1854. * @returns {Array|Object} Single row of data.
  1855. */
  1856. this.getSourceDataAtRow = function (row) {
  1857. return dataSource.getAtRow(row);
  1858. };
  1859. /**
  1860. * Returns a single value from the data source.
  1861. *
  1862. * @memberof Core#
  1863. * @function getSourceDataAtCell
  1864. * @param {Number} row Row index.
  1865. * @param {Number} column Column index.
  1866. * @returns {*} Cell data.
  1867. * @since 0.20.0
  1868. */
  1869. this.getSourceDataAtCell = function (row, column) {
  1870. return dataSource.getAtCell(row, column);
  1871. };
  1872. /**
  1873. * @description
  1874. * Returns a single row of the data. The `row` argument is the __visible__ index of the row.
  1875. *
  1876. * @memberof Core#
  1877. * @function getDataAtRow
  1878. * @param {Number} row Row index.
  1879. * @returns {Array} Array of row's cell data.
  1880. * @since 0.9-beta2
  1881. */
  1882. this.getDataAtRow = function (row) {
  1883. var data = datamap.getRange(new CellCoords(row, 0), new CellCoords(row, this.countCols() - 1), datamap.DESTINATION_RENDERER);
  1884. return data[0] || [];
  1885. };
  1886. /**
  1887. * @description
  1888. * Returns a data type defined in the Handsontable settings under the `type` key ([Options#type](http://docs.handsontable.com/Options.html#type)).
  1889. * If there are cells with different types in the selected range, it returns `'mixed'`.
  1890. *
  1891. * @since 0.18.1
  1892. * @memberof Core#
  1893. * @function getDataType
  1894. * @param {Number} rowFrom From row index.
  1895. * @param {Number} columnFrom To row index.
  1896. * @param {Number} rowTo From column index.
  1897. * @param {Number} columnTo To column index.
  1898. * @returns {String} Cell type (e.q: `'mixed'`, `'text'`, `'numeric'`, `'autocomplete'`).
  1899. */
  1900. this.getDataType = function (rowFrom, columnFrom, rowTo, columnTo) {
  1901. var _this = this;
  1902. var previousType = null;
  1903. var currentType = null;
  1904. if (rowFrom === void 0) {
  1905. rowFrom = 0;
  1906. rowTo = this.countRows();
  1907. columnFrom = 0;
  1908. columnTo = this.countCols();
  1909. }
  1910. if (rowTo === void 0) {
  1911. rowTo = rowFrom;
  1912. }
  1913. if (columnTo === void 0) {
  1914. columnTo = columnFrom;
  1915. }
  1916. var type = 'mixed';
  1917. rangeEach(Math.min(rowFrom, rowTo), Math.max(rowFrom, rowTo), function (row) {
  1918. var isTypeEqual = true;
  1919. rangeEach(Math.min(columnFrom, columnTo), Math.max(columnFrom, columnTo), function (column) {
  1920. var cellType = _this.getCellMeta(row, column);
  1921. currentType = cellType.type;
  1922. if (previousType) {
  1923. isTypeEqual = previousType === currentType;
  1924. } else {
  1925. previousType = currentType;
  1926. }
  1927. return isTypeEqual;
  1928. });
  1929. type = isTypeEqual ? currentType : 'mixed';
  1930. return isTypeEqual;
  1931. });
  1932. return type;
  1933. };
  1934. /**
  1935. * Remove a property defined by the `key` argument from the cell meta object for the provided `row` and `col` coordinates.
  1936. *
  1937. * @memberof Core#
  1938. * @function removeCellMeta
  1939. * @param {Number} row Row index.
  1940. * @param {Number} col Column index.
  1941. * @param {String} key Property name.
  1942. */
  1943. this.removeCellMeta = function (row, col, key) {
  1944. var cellMeta = instance.getCellMeta(row, col);
  1945. if (cellMeta[key] != undefined) {
  1946. delete priv.cellSettings[row][col][key];
  1947. }
  1948. };
  1949. /**
  1950. * Remove one or more rows from the cell meta object.
  1951. *
  1952. * @since 0.30.0
  1953. * @param {Number} index An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.
  1954. * @param {Number} deleteAmount The number of items to be removed. If set to 0, no items will be removed.
  1955. * @param {Array} items The new items to be added to the array.
  1956. */
  1957. this.spliceCellsMeta = function (index, deleteAmount) {
  1958. var _priv$cellSettings;
  1959. for (var _len2 = arguments.length, items = Array(_len2 > 2 ? _len2 - 2 : 0), _key = 2; _key < _len2; _key++) {
  1960. items[_key - 2] = arguments[_key];
  1961. }
  1962. (_priv$cellSettings = priv.cellSettings).splice.apply(_priv$cellSettings, [index, deleteAmount].concat(items));
  1963. };
  1964. /**
  1965. * Set cell meta data object defined by `prop` to the corresponding params `row` and `col`.
  1966. *
  1967. * @memberof Core#
  1968. * @function setCellMetaObject
  1969. * @since 0.11
  1970. * @param {Number} row Row index.
  1971. * @param {Number} col Column index.
  1972. * @param {Object} prop Meta object.
  1973. */
  1974. this.setCellMetaObject = function (row, col, prop) {
  1975. if ((typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) === 'object') {
  1976. for (var key in prop) {
  1977. if (hasOwnProperty(prop, key)) {
  1978. var value = prop[key];
  1979. this.setCellMeta(row, col, key, value);
  1980. }
  1981. }
  1982. }
  1983. };
  1984. /**
  1985. * Sets a property defined by the `key` object to the meta object of a cell corresponding to params `row` and `col`.
  1986. *
  1987. * @memberof Core#
  1988. * @function setCellMeta
  1989. * @since 0.11
  1990. * @param {Number} row Row index.
  1991. * @param {Number} col Column index.
  1992. * @param {String} key Property name.
  1993. * @param {String} val Property value.
  1994. * @fires Hooks#afterSetCellMeta
  1995. */
  1996. this.setCellMeta = function (row, col, key, val) {
  1997. var _recordTranslator$toP = recordTranslator.toPhysical(row, col);
  1998. var _recordTranslator$toP2 = _slicedToArray(_recordTranslator$toP, 2);
  1999. row = _recordTranslator$toP2[0];
  2000. col = _recordTranslator$toP2[1];
  2001. if (!priv.columnSettings[col]) {
  2002. priv.columnSettings[col] = columnFactory(GridSettings, priv.columnsSettingConflicts);
  2003. }
  2004. if (!priv.cellSettings[row]) {
  2005. priv.cellSettings[row] = [];
  2006. }
  2007. if (!priv.cellSettings[row][col]) {
  2008. priv.cellSettings[row][col] = new priv.columnSettings[col]();
  2009. }
  2010. priv.cellSettings[row][col][key] = val;
  2011. instance.runHooks('afterSetCellMeta', row, col, key, val);
  2012. };
  2013. /**
  2014. * Get all the cells meta settings at least once generated in the table (in order of cell initialization).
  2015. *
  2016. * @since 0.19.0
  2017. * @returns {Array} Returns Array of ColumnSettings object.
  2018. */
  2019. this.getCellsMeta = function () {
  2020. return arrayFlatten(priv.cellSettings);
  2021. };
  2022. /**
  2023. * Returns the cell properties object for the given `row` and `col` coordinates.
  2024. *
  2025. * @memberof Core#
  2026. * @function getCellMeta
  2027. * @param {Number} row Row index.
  2028. * @param {Number} col Column index.
  2029. * @returns {Object} The cell properties object.
  2030. * @fires Hooks#beforeGetCellMeta
  2031. * @fires Hooks#afterGetCellMeta
  2032. */
  2033. this.getCellMeta = function (row, col) {
  2034. var prop = datamap.colToProp(col),
  2035. cellProperties;
  2036. var visualRow = row;
  2037. var visualCol = col;
  2038. var _recordTranslator$toP3 = recordTranslator.toPhysical(row, col);
  2039. var _recordTranslator$toP4 = _slicedToArray(_recordTranslator$toP3, 2);
  2040. row = _recordTranslator$toP4[0];
  2041. col = _recordTranslator$toP4[1];
  2042. if (!priv.columnSettings[col]) {
  2043. priv.columnSettings[col] = columnFactory(GridSettings, priv.columnsSettingConflicts);
  2044. }
  2045. if (!priv.cellSettings[row]) {
  2046. priv.cellSettings[row] = [];
  2047. }
  2048. if (!priv.cellSettings[row][col]) {
  2049. priv.cellSettings[row][col] = new priv.columnSettings[col]();
  2050. }
  2051. cellProperties = priv.cellSettings[row][col]; // retrieve cellProperties from cache
  2052. cellProperties.row = row;
  2053. cellProperties.col = col;
  2054. cellProperties.visualRow = visualRow;
  2055. cellProperties.visualCol = visualCol;
  2056. cellProperties.prop = prop;
  2057. cellProperties.instance = instance;
  2058. instance.runHooks('beforeGetCellMeta', row, col, cellProperties);
  2059. extend(cellProperties, expandType(cellProperties)); // for `type` added in beforeGetCellMeta
  2060. if (cellProperties.cells) {
  2061. var settings = cellProperties.cells.call(cellProperties, row, col, prop);
  2062. if (settings) {
  2063. extend(cellProperties, settings);
  2064. extend(cellProperties, expandType(settings)); // for `type` added in cells
  2065. }
  2066. }
  2067. instance.runHooks('afterGetCellMeta', row, col, cellProperties);
  2068. return cellProperties;
  2069. };
  2070. /**
  2071. * Returns a row off the cell meta array.
  2072. *
  2073. * @memberof Core#
  2074. * @function getCellMetaAtRow
  2075. * @since 0.30.0
  2076. * @param {Number} row Index of the row to return cell meta for.
  2077. * @returns {Array}
  2078. */
  2079. this.getCellMetaAtRow = function (row) {
  2080. return priv.cellSettings[row];
  2081. };
  2082. /**
  2083. * Checks if the data format and config allows user to modify the column structure.
  2084. * @returns {boolean}
  2085. */
  2086. this.isColumnModificationAllowed = function () {
  2087. return !(instance.dataType === 'object' || instance.getSettings().columns);
  2088. };
  2089. var rendererLookup = cellMethodLookupFactory('renderer');
  2090. /**
  2091. * Returns the cell renderer function by given `row` and `col` arguments.
  2092. *
  2093. * @memberof Core#
  2094. * @function getCellRenderer
  2095. * @since 0.11
  2096. * @param {Number|Object} row Row index or cell meta object.
  2097. * @param {Number} [col] Column index.
  2098. * @returns {Function} The renderer function.
  2099. */
  2100. this.getCellRenderer = function (row, col) {
  2101. return getRenderer(rendererLookup.call(this, row, col));
  2102. };
  2103. /**
  2104. * Returns the cell editor by the provided `row` and `col` arguments.
  2105. *
  2106. * @memberof Core#
  2107. * @function getCellEditor
  2108. * @param {Number} row Row index.
  2109. * @param {Number} col Column index.
  2110. * @returns {Object} The Editor object.
  2111. */
  2112. this.getCellEditor = cellMethodLookupFactory('editor');
  2113. var validatorLookup = cellMethodLookupFactory('validator');
  2114. /**
  2115. * Returns the cell validator by `row` and `col`, provided a validator is defined. If not - it doesn't return anything.
  2116. *
  2117. * @memberof Core#
  2118. * @function getCellValidator
  2119. * @param {Number} row Row index.
  2120. * @param {Number} col Column index.
  2121. * @returns {Function|RegExp|undefined} The validator function.
  2122. */
  2123. this.getCellValidator = function (row, col) {
  2124. var validator = validatorLookup.call(this, row, col);
  2125. if (typeof validator === 'string') {
  2126. validator = getValidator(validator);
  2127. }
  2128. return validator;
  2129. };
  2130. /**
  2131. * Validates all cells using their validator functions and calls callback when finished.
  2132. *
  2133. * If one of the cells is invalid, the callback will be fired with `'valid'` arguments as `false` - otherwise it would equal `true`.
  2134. *
  2135. * @memberof Core#
  2136. * @function validateCells
  2137. * @param {Function} [callback] The callback function.
  2138. */
  2139. this.validateCells = function (callback) {
  2140. var waitingForValidator = new ValidatorsQueue();
  2141. if (callback) {
  2142. waitingForValidator.onQueueEmpty = callback;
  2143. }
  2144. var i = instance.countRows() - 1;
  2145. while (i >= 0) {
  2146. var j = instance.countCols() - 1;
  2147. while (j >= 0) {
  2148. waitingForValidator.addValidatorToQueue();
  2149. instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function (result) {
  2150. if (typeof result !== 'boolean') {
  2151. throw new Error('Validation error: result is not boolean');
  2152. }
  2153. if (result === false) {
  2154. waitingForValidator.valid = false;
  2155. }
  2156. waitingForValidator.removeValidatorFormQueue();
  2157. }, 'validateCells');
  2158. j--;
  2159. }
  2160. i--;
  2161. }
  2162. waitingForValidator.checkIfQueueIsEmpty();
  2163. };
  2164. /**
  2165. * Returns an array of row headers' values (if they are enabled). If param `row` was given, it returns the header of the given row as a string.
  2166. *
  2167. * @memberof Core#
  2168. * @function getRowHeader
  2169. * @param {Number} [row] Row index.
  2170. * @fires Hooks#modifyRowHeader
  2171. * @returns {Array|String} Array of header values / single header value.
  2172. */
  2173. this.getRowHeader = function (row) {
  2174. var rowHeader = priv.settings.rowHeaders;
  2175. if (row !== void 0) {
  2176. row = instance.runHooks('modifyRowHeader', row);
  2177. }
  2178. if (row === void 0) {
  2179. rowHeader = [];
  2180. rangeEach(instance.countRows() - 1, function (i) {
  2181. rowHeader.push(instance.getRowHeader(i));
  2182. });
  2183. } else if (Array.isArray(rowHeader) && rowHeader[row] !== void 0) {
  2184. rowHeader = rowHeader[row];
  2185. } else if (isFunction(rowHeader)) {
  2186. rowHeader = rowHeader(row);
  2187. } else if (rowHeader && typeof rowHeader !== 'string' && typeof rowHeader !== 'number') {
  2188. rowHeader = row + 1;
  2189. }
  2190. return rowHeader;
  2191. };
  2192. /**
  2193. * Returns information about if this table is configured to display row headers.
  2194. *
  2195. * @memberof Core#
  2196. * @function hasRowHeaders
  2197. * @returns {Boolean} `true` if the instance has the row headers enabled, `false` otherwise.
  2198. * @since 0.11
  2199. */
  2200. this.hasRowHeaders = function () {
  2201. return !!priv.settings.rowHeaders;
  2202. };
  2203. /**
  2204. * Returns information about if this table is configured to display column headers.
  2205. *
  2206. * @memberof Core#
  2207. * @function hasColHeaders
  2208. * @since 0.11
  2209. * @returns {Boolean} `True` if the instance has the column headers enabled, `false` otherwise.
  2210. */
  2211. this.hasColHeaders = function () {
  2212. if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) {
  2213. // Polymer has empty value = null
  2214. return !!priv.settings.colHeaders;
  2215. }
  2216. for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
  2217. if (instance.getColHeader(i)) {
  2218. return true;
  2219. }
  2220. }
  2221. return false;
  2222. };
  2223. /**
  2224. * Returns an array of column headers (in string format, if they are enabled). If param `col` is given, it returns the header at the given column as a string.
  2225. *
  2226. * @memberof Core#
  2227. * @function getColHeader
  2228. * @param {Number} [col] Column index.
  2229. * @fires Hooks#modifyColHeader
  2230. * @returns {Array|String} The column header(s).
  2231. */
  2232. this.getColHeader = function (col) {
  2233. var columnsAsFunc = priv.settings.columns && isFunction(priv.settings.columns);
  2234. var result = priv.settings.colHeaders;
  2235. col = instance.runHooks('modifyColHeader', col);
  2236. if (col === void 0) {
  2237. var out = [];
  2238. var ilen = columnsAsFunc ? instance.countSourceCols() : instance.countCols();
  2239. for (var i = 0; i < ilen; i++) {
  2240. out.push(instance.getColHeader(i));
  2241. }
  2242. result = out;
  2243. } else {
  2244. var translateVisualIndexToColumns = function translateVisualIndexToColumns(col) {
  2245. var arr = [];
  2246. var columnsLen = instance.countSourceCols();
  2247. var index = 0;
  2248. for (; index < columnsLen; index++) {
  2249. if (isFunction(instance.getSettings().columns) && instance.getSettings().columns(index)) {
  2250. arr.push(index);
  2251. }
  2252. }
  2253. return arr[col];
  2254. };
  2255. var baseCol = col;
  2256. col = instance.runHooks('modifyCol', col);
  2257. var prop = translateVisualIndexToColumns(col);
  2258. if (priv.settings.columns && isFunction(priv.settings.columns) && priv.settings.columns(prop) && priv.settings.columns(prop).title) {
  2259. result = priv.settings.columns(prop).title;
  2260. } else if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
  2261. result = priv.settings.columns[col].title;
  2262. } else if (Array.isArray(priv.settings.colHeaders) && priv.settings.colHeaders[col] !== void 0) {
  2263. result = priv.settings.colHeaders[col];
  2264. } else if (isFunction(priv.settings.colHeaders)) {
  2265. result = priv.settings.colHeaders(col);
  2266. } else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
  2267. result = spreadsheetColumnLabel(baseCol); // see #1458
  2268. }
  2269. }
  2270. return result;
  2271. };
  2272. /**
  2273. * Return column width from settings (no guessing). Private use intended.
  2274. *
  2275. * @private
  2276. * @memberof Core#
  2277. * @function _getColWidthFromSettings
  2278. * @param {Number} col
  2279. * @returns {Number}
  2280. */
  2281. this._getColWidthFromSettings = function (col) {
  2282. var cellProperties = instance.getCellMeta(0, col);
  2283. var width = cellProperties.width;
  2284. if (width === void 0 || width === priv.settings.width) {
  2285. width = cellProperties.colWidths;
  2286. }
  2287. if (width !== void 0 && width !== null) {
  2288. switch (typeof width === 'undefined' ? 'undefined' : _typeof(width)) {
  2289. case 'object':
  2290. // array
  2291. width = width[col];
  2292. break;
  2293. case 'function':
  2294. width = width(col);
  2295. break;
  2296. default:
  2297. break;
  2298. }
  2299. if (typeof width === 'string') {
  2300. width = parseInt(width, 10);
  2301. }
  2302. }
  2303. return width;
  2304. };
  2305. /**
  2306. * Returns the width of the requested column.
  2307. *
  2308. * @memberof Core#
  2309. * @function getColWidth
  2310. * @since 0.11
  2311. * @param {Number} col Column index.
  2312. * @returns {Number} Column width.
  2313. * @fires Hooks#modifyColWidth
  2314. */
  2315. this.getColWidth = function (col) {
  2316. var width = instance._getColWidthFromSettings(col);
  2317. width = instance.runHooks('modifyColWidth', width, col);
  2318. if (width === void 0) {
  2319. width = ViewportColumnsCalculator.DEFAULT_WIDTH;
  2320. }
  2321. return width;
  2322. };
  2323. /**
  2324. * Return row height from settings (no guessing). Private use intended.
  2325. *
  2326. * @private
  2327. * @memberof Core#
  2328. * @function _getRowHeightFromSettings
  2329. * @param {Number} row
  2330. * @returns {Number}
  2331. */
  2332. this._getRowHeightFromSettings = function (row) {
  2333. // let cellProperties = instance.getCellMeta(row, 0);
  2334. // let height = cellProperties.height;
  2335. //
  2336. // if (height === void 0 || height === priv.settings.height) {
  2337. // height = cellProperties.rowHeights;
  2338. // }
  2339. var height = priv.settings.rowHeights;
  2340. if (height !== void 0 && height !== null) {
  2341. switch (typeof height === 'undefined' ? 'undefined' : _typeof(height)) {
  2342. case 'object':
  2343. // array
  2344. height = height[row];
  2345. break;
  2346. case 'function':
  2347. height = height(row);
  2348. break;
  2349. default:
  2350. break;
  2351. }
  2352. if (typeof height === 'string') {
  2353. height = parseInt(height, 10);
  2354. }
  2355. }
  2356. return height;
  2357. };
  2358. /**
  2359. * Returns the row height.
  2360. *
  2361. * @memberof Core#
  2362. * @function getRowHeight
  2363. * @since 0.11
  2364. * @param {Number} row Row index.
  2365. * @returns {Number} The given row's height.
  2366. * @fires Hooks#modifyRowHeight
  2367. */
  2368. this.getRowHeight = function (row) {
  2369. var height = instance._getRowHeightFromSettings(row);
  2370. height = instance.runHooks('modifyRowHeight', height, row);
  2371. return height;
  2372. };
  2373. /**
  2374. * Returns the total number of rows in the data source.
  2375. *
  2376. * @memberof Core#
  2377. * @function countSourceRows
  2378. * @since 0.20.0
  2379. * @returns {Number} Total number in rows in data source.
  2380. */
  2381. this.countSourceRows = function () {
  2382. var sourceLength = instance.runHooks('modifySourceLength');
  2383. return sourceLength || (instance.getSourceData() ? instance.getSourceData().length : 0);
  2384. };
  2385. /**
  2386. * Returns the total number of columns in the data source.
  2387. *
  2388. * @memberof Core#
  2389. * @function countSourceCols
  2390. * @since 0.26.1
  2391. * @returns {Number} Total number in columns in data source.
  2392. */
  2393. this.countSourceCols = function () {
  2394. var len = 0;
  2395. var obj = instance.getSourceData() && instance.getSourceData()[0] ? instance.getSourceData()[0] : [];
  2396. if (isObject(obj)) {
  2397. len = deepObjectSize(obj);
  2398. } else {
  2399. len = obj.length || 0;
  2400. }
  2401. return len;
  2402. };
  2403. /**
  2404. * Returns the total number of rows in the grid.
  2405. *
  2406. * @memberof Core#
  2407. * @function countRows
  2408. * @returns {Number} Total number in rows the grid.
  2409. */
  2410. this.countRows = function () {
  2411. return datamap.getLength();
  2412. };
  2413. /**
  2414. * Returns the total number of columns in the grid.
  2415. *
  2416. * @memberof Core#
  2417. * @function countCols
  2418. * @returns {Number} Total number of columns.
  2419. */
  2420. this.countCols = function () {
  2421. var maxCols = this.getSettings().maxCols;
  2422. var dataHasLength = false;
  2423. var dataLen = 0;
  2424. if (instance.dataType === 'array') {
  2425. dataHasLength = priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length;
  2426. }
  2427. if (dataHasLength) {
  2428. dataLen = priv.settings.data[0].length;
  2429. }
  2430. if (priv.settings.columns) {
  2431. var columnsIsFunction = isFunction(priv.settings.columns);
  2432. if (columnsIsFunction) {
  2433. if (instance.dataType === 'array') {
  2434. var columnLen = 0;
  2435. for (var i = 0; i < dataLen; i++) {
  2436. if (priv.settings.columns(i)) {
  2437. columnLen++;
  2438. }
  2439. }
  2440. dataLen = columnLen;
  2441. } else if (instance.dataType === 'object' || instance.dataType === 'function') {
  2442. dataLen = datamap.colToPropCache.length;
  2443. }
  2444. } else {
  2445. dataLen = priv.settings.columns.length;
  2446. }
  2447. } else if (instance.dataType === 'object' || instance.dataType === 'function') {
  2448. dataLen = datamap.colToPropCache.length;
  2449. }
  2450. return Math.min(maxCols, dataLen);
  2451. };
  2452. /**
  2453. * Returns an index of the first rendered row.
  2454. *
  2455. * @memberof Core#
  2456. * @function rowOffset
  2457. * @returns {Number} Index of first rendered row.
  2458. */
  2459. this.rowOffset = function () {
  2460. return instance.view.wt.wtTable.getFirstRenderedRow();
  2461. };
  2462. /**
  2463. * Returns the index of the first rendered column.
  2464. *
  2465. * @memberof Core#
  2466. * @function colOffset
  2467. * @returns {Number} Index of the first visible column.
  2468. */
  2469. this.colOffset = function () {
  2470. return instance.view.wt.wtTable.getFirstRenderedColumn();
  2471. };
  2472. /**
  2473. * Returns the number of rendered rows (including rows partially or fully rendered outside viewport).
  2474. *
  2475. * @memberof Core#
  2476. * @function countRenderedRows
  2477. * @returns {Number} Returns -1 if table is not visible.
  2478. */
  2479. this.countRenderedRows = function () {
  2480. return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedRowsCount() : -1;
  2481. };
  2482. /**
  2483. * Returns the number of visible rows (rendered rows that fully fit inside viewport).
  2484. *
  2485. * @memberof Core#
  2486. * @function countVisibleRows
  2487. * @returns {Number} Number of visible rows or -1.
  2488. */
  2489. this.countVisibleRows = function () {
  2490. return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleRowsCount() : -1;
  2491. };
  2492. /**
  2493. * Returns the number of rendered columns (including columns partially or fully rendered outside viewport).
  2494. *
  2495. * @memberof Core#
  2496. * @function countRenderedCols
  2497. * @returns {Number} Returns -1 if table is not visible.
  2498. */
  2499. this.countRenderedCols = function () {
  2500. return instance.view.wt.drawn ? instance.view.wt.wtTable.getRenderedColumnsCount() : -1;
  2501. };
  2502. /**
  2503. * Returns the number of visible columns. Returns -1 if table is not visible
  2504. *
  2505. * @memberof Core#
  2506. * @function countVisibleCols
  2507. * @return {Number} Number of visible columns or -1.
  2508. */
  2509. this.countVisibleCols = function () {
  2510. return instance.view.wt.drawn ? instance.view.wt.wtTable.getVisibleColumnsCount() : -1;
  2511. };
  2512. /**
  2513. * Returns the number of empty rows. If the optional ending parameter is `true`, returns the
  2514. * number of empty rows at the bottom of the table.
  2515. *
  2516. * @memberof Core#
  2517. * @function countEmptyRows
  2518. * @param {Boolean} [ending] If `true`, will only count empty rows at the end of the data source.
  2519. * @returns {Number} Count empty rows
  2520. * @fires Hooks#modifyRow
  2521. */
  2522. this.countEmptyRows = function (ending) {
  2523. var i = instance.countRows() - 1,
  2524. empty = 0,
  2525. row;
  2526. while (i >= 0) {
  2527. row = instance.runHooks('modifyRow', i);
  2528. if (instance.isEmptyRow(row)) {
  2529. empty++;
  2530. } else if (ending) {
  2531. break;
  2532. }
  2533. i--;
  2534. }
  2535. return empty;
  2536. };
  2537. /**
  2538. * Returns the number of empty columns. If the optional ending parameter is `true`, returns the number of empty
  2539. * columns at right hand edge of the table.
  2540. *
  2541. * @memberof Core#
  2542. * @function countEmptyCols
  2543. * @param {Boolean} [ending] If `true`, will only count empty columns at the end of the data source row.
  2544. * @returns {Number} Count empty cols
  2545. */
  2546. this.countEmptyCols = function (ending) {
  2547. if (instance.countRows() < 1) {
  2548. return 0;
  2549. }
  2550. var i = instance.countCols() - 1,
  2551. empty = 0;
  2552. while (i >= 0) {
  2553. if (instance.isEmptyCol(i)) {
  2554. empty++;
  2555. } else if (ending) {
  2556. break;
  2557. }
  2558. i--;
  2559. }
  2560. return empty;
  2561. };
  2562. /**
  2563. * Check if all cells in the row declared by the `row` argument are empty.
  2564. *
  2565. * @memberof Core#
  2566. * @function isEmptyRow
  2567. * @param {Number} row Row index.
  2568. * @returns {Boolean} `true` if the row at the given `row` is empty, `false` otherwise.
  2569. */
  2570. this.isEmptyRow = function (row) {
  2571. return priv.settings.isEmptyRow.call(instance, row);
  2572. };
  2573. /**
  2574. * Check if all cells in the the column declared by the `col` argument are empty.
  2575. *
  2576. * @memberof Core#
  2577. * @function isEmptyCol
  2578. * @param {Number} col Column index.
  2579. * @returns {Boolean} `true` if the column at the given `col` is empty, `false` otherwise.
  2580. */
  2581. this.isEmptyCol = function (col) {
  2582. return priv.settings.isEmptyCol.call(instance, col);
  2583. };
  2584. /**
  2585. * Select cell specified by `row` and `col` values or a range of cells finishing at `endRow`, `endCol`.
  2586. * By default, viewport will be scrolled to selection.
  2587. * After the `selectCell` method had finished, the instance will be listening to keyboard input on the document.
  2588. *
  2589. * @memberof Core#
  2590. * @function selectCell
  2591. * @param {Number} row Row index.
  2592. * @param {Number} col Column index.
  2593. * @param {Number} [endRow] End row index (if selecting a range).
  2594. * @param {Number} [endCol] End column index (if selecting a range).
  2595. * @param {Boolean} [scrollToCell=true] If `true`, the viewport will be scrolled to the selection.
  2596. * @param {Boolean} [changeListener=true] If `false`, Handsontable will not change keyboard events listener to himself.
  2597. * @returns {Boolean} `true` if selection was successful, `false` otherwise.
  2598. */
  2599. this.selectCell = function (row, col, endRow, endCol, scrollToCell, changeListener) {
  2600. var coords;
  2601. changeListener = isUndefined(changeListener) || changeListener === true;
  2602. if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) {
  2603. return false;
  2604. }
  2605. if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
  2606. return false;
  2607. }
  2608. if (isDefined(endRow)) {
  2609. if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
  2610. return false;
  2611. }
  2612. if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
  2613. return false;
  2614. }
  2615. }
  2616. coords = new CellCoords(row, col);
  2617. priv.selRange = new CellRange(coords, coords, coords);
  2618. if (changeListener) {
  2619. instance.listen();
  2620. }
  2621. if (isUndefined(endRow)) {
  2622. selection.setRangeEnd(priv.selRange.from, scrollToCell);
  2623. } else {
  2624. selection.setRangeEnd(new CellCoords(endRow, endCol), scrollToCell);
  2625. }
  2626. instance.selection.finish();
  2627. return true;
  2628. };
  2629. /**
  2630. * Select the cell specified by the `row` and `prop` arguments, or a range finishing at `endRow`, `endProp`.
  2631. * By default, viewport will be scrolled to selection.
  2632. *
  2633. * @memberof Core#
  2634. * @function selectCellByProp
  2635. * @param {Number} row Row index.
  2636. * @param {String} prop Property name.
  2637. * @param {Number} [endRow] End row index (if selecting a range).
  2638. * @param {String} [endProp] End property name (if selecting a range).
  2639. * @param {Boolean} [scrollToCell=true] If `true`, viewport will be scrolled to the selection.
  2640. * @returns {Boolean} `true` if selection was successful, `false` otherwise.
  2641. */
  2642. this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) {
  2643. var _instance5;
  2644. arguments[1] = datamap.propToCol(arguments[1]);
  2645. if (isDefined(arguments[3])) {
  2646. arguments[3] = datamap.propToCol(arguments[3]);
  2647. }
  2648. return (_instance5 = instance).selectCell.apply(_instance5, arguments);
  2649. };
  2650. /**
  2651. * Deselects the current cell selection on grid.
  2652. *
  2653. * @memberof Core#
  2654. * @function deselectCell
  2655. */
  2656. this.deselectCell = function () {
  2657. selection.deselect();
  2658. };
  2659. /**
  2660. * Scroll viewport to coords specified by the `row` and `column` arguments.
  2661. *
  2662. * @since 0.24.3
  2663. * @memberof Core#
  2664. * @function scrollViewportTo
  2665. * @param {Number} [row] Row index.
  2666. * @param {Number} [column] Column index.
  2667. * @param {Boolean} [snapToBottom = false] If `true`, viewport is scrolled to show the cell on the bottom of the table.
  2668. * @param {Boolean} [snapToRight = false] If `true`, viewport is scrolled to show the cell on the right side of the table.
  2669. * @returns {Boolean} `true` if scroll was successful, `false` otherwise.
  2670. */
  2671. this.scrollViewportTo = function (row, column) {
  2672. var snapToBottom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  2673. var snapToRight = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  2674. if (row !== void 0 && (row < 0 || row >= instance.countRows())) {
  2675. return false;
  2676. }
  2677. if (column !== void 0 && (column < 0 || column >= instance.countCols())) {
  2678. return false;
  2679. }
  2680. var result = false;
  2681. if (row !== void 0 && column !== void 0) {
  2682. instance.view.wt.wtOverlays.topOverlay.scrollTo(row, snapToBottom);
  2683. instance.view.wt.wtOverlays.leftOverlay.scrollTo(column, snapToRight);
  2684. result = true;
  2685. }
  2686. if (typeof row === 'number' && typeof column !== 'number') {
  2687. instance.view.wt.wtOverlays.topOverlay.scrollTo(row, snapToBottom);
  2688. result = true;
  2689. }
  2690. if (typeof column === 'number' && typeof row !== 'number') {
  2691. instance.view.wt.wtOverlays.leftOverlay.scrollTo(column, snapToRight);
  2692. result = true;
  2693. }
  2694. return result;
  2695. };
  2696. /**
  2697. * Removes grid from the DOM.
  2698. *
  2699. * @memberof Core#
  2700. * @function destroy
  2701. * @fires Hooks#afterDestroy
  2702. */
  2703. this.destroy = function () {
  2704. instance._clearTimeouts();
  2705. if (instance.view) {
  2706. // in case HT is destroyed before initialization has finished
  2707. instance.view.destroy();
  2708. }
  2709. if (dataSource) {
  2710. dataSource.destroy();
  2711. }
  2712. dataSource = null;
  2713. empty(instance.rootElement);
  2714. eventManager.destroy();
  2715. instance.runHooks('afterDestroy');
  2716. Hooks.getSingleton().destroy(instance);
  2717. for (var i in instance) {
  2718. if (hasOwnProperty(instance, i)) {
  2719. // replace instance methods with post mortem
  2720. if (isFunction(instance[i])) {
  2721. instance[i] = postMortem;
  2722. } else if (i !== 'guid') {
  2723. // replace instance properties with null (restores memory)
  2724. // it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests
  2725. instance[i] = null;
  2726. }
  2727. }
  2728. }
  2729. // replace private properties with null (restores memory)
  2730. // it should not be necessary but this prevents a memory leak side effects that show itself in Jasmine tests
  2731. if (datamap) {
  2732. datamap.destroy();
  2733. }
  2734. datamap = null;
  2735. priv = null;
  2736. grid = null;
  2737. selection = null;
  2738. editorManager = null;
  2739. instance = null;
  2740. GridSettings = null;
  2741. };
  2742. /**
  2743. * Replacement for all methods after Handsotnable was destroyed.
  2744. *
  2745. * @private
  2746. */
  2747. function postMortem() {
  2748. throw new Error('This method cannot be called because this Handsontable instance has been destroyed');
  2749. }
  2750. /**
  2751. * Returns the active editor object.
  2752. *
  2753. * @memberof Core#
  2754. * @function getActiveEditor
  2755. * @returns {Object} The active editor object.
  2756. */
  2757. this.getActiveEditor = function () {
  2758. return editorManager.getActiveEditor();
  2759. };
  2760. /**
  2761. * Returns plugin instance using the plugin name provided.
  2762. *
  2763. * @memberof Core#
  2764. * @function getPlugin
  2765. * @param {String} pluginName The plugin name.
  2766. * @returns {*} The plugin instance.
  2767. * @since 0.15.0
  2768. */
  2769. this.getPlugin = function (pluginName) {
  2770. return getPlugin(this, pluginName);
  2771. };
  2772. /**
  2773. * Returns the Handsontable instance.
  2774. *
  2775. * @memberof Core#
  2776. * @function getInstance
  2777. * @returns {Handsontable} The Handsontable instance.
  2778. */
  2779. this.getInstance = function () {
  2780. return instance;
  2781. };
  2782. /**
  2783. * Adds listener to the specified hook name (only for this Handsontable instance).
  2784. *
  2785. * @memberof Core#
  2786. * @function addHook
  2787. * @see Hooks#add
  2788. * @param {String} key Hook name.
  2789. * @param {Function|Array} callback Function or array of Functions.
  2790. *
  2791. * @example
  2792. * ```js
  2793. * hot.addHook('beforeInit', myCallback);
  2794. * ```
  2795. */
  2796. this.addHook = function (key, callback) {
  2797. Hooks.getSingleton().add(key, callback, instance);
  2798. };
  2799. /**
  2800. * Check if for a specified hook name there are added listeners (only for this Handsontable instance).
  2801. *
  2802. * @memberof Core#
  2803. * @function hasHook
  2804. * @see Hooks#has
  2805. * @param {String} key Hook name
  2806. * @return {Boolean}
  2807. *
  2808. * @example
  2809. * ```js
  2810. * var hasBeforeInitListeners = hot.hasHook('beforeInit');
  2811. * ```
  2812. */
  2813. this.hasHook = function (key) {
  2814. return Hooks.getSingleton().has(key, instance);
  2815. };
  2816. /**
  2817. * Adds listener to specified hook name (only for this Handsontable instance).
  2818. * After the listener is triggered, it will be automatically removed.
  2819. *
  2820. * @memberof Core#
  2821. * @function addHookOnce
  2822. * @see Hooks#once
  2823. * @param {String} key Hook name.
  2824. * @param {Function|Array} callback Function or array of Functions.
  2825. *
  2826. * @example
  2827. * ```js
  2828. * hot.addHookOnce('beforeInit', myCallback);
  2829. * ```
  2830. */
  2831. this.addHookOnce = function (key, callback) {
  2832. Hooks.getSingleton().once(key, callback, instance);
  2833. };
  2834. /**
  2835. * Removes the hook listener previously registered with {@link Core#addHook}.
  2836. *
  2837. * @memberof Core#
  2838. * @function removeHook
  2839. * @see Hooks#remove
  2840. * @param {String} key Hook name.
  2841. * @param {Function} callback Function which have been registered via {@link Core#addHook}.
  2842. *
  2843. * @example
  2844. * ```js
  2845. * hot.removeHook('beforeInit', myCallback);
  2846. * ```
  2847. */
  2848. this.removeHook = function (key, callback) {
  2849. Hooks.getSingleton().remove(key, callback, instance);
  2850. };
  2851. /**
  2852. * Run the callbacks for the hook provided in the `key` argument using the parameters given in the other arguments.
  2853. *
  2854. * @memberof Core#
  2855. * @function runHooks
  2856. * @see Hooks#run
  2857. * @param {String} key Hook name.
  2858. * @param {*} [p1] Argument passed to the callback.
  2859. * @param {*} [p2] Argument passed to the callback.
  2860. * @param {*} [p3] Argument passed to the callback.
  2861. * @param {*} [p4] Argument passed to the callback.
  2862. * @param {*} [p5] Argument passed to the callback.
  2863. * @param {*} [p6] Argument passed to the callback.
  2864. * @returns {*}
  2865. *
  2866. * @example
  2867. * ```js
  2868. * hot.runHooks('beforeInit');
  2869. * ```
  2870. */
  2871. this.runHooks = function (key, p1, p2, p3, p4, p5, p6) {
  2872. return Hooks.getSingleton().run(instance, key, p1, p2, p3, p4, p5, p6);
  2873. };
  2874. this.timeouts = [];
  2875. /**
  2876. * Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called.
  2877. *
  2878. * @param {*} handle
  2879. * @private
  2880. */
  2881. this._registerTimeout = function (handle) {
  2882. this.timeouts.push(handle);
  2883. };
  2884. /**
  2885. * Clears all known timeouts.
  2886. *
  2887. * @private
  2888. */
  2889. this._clearTimeouts = function () {
  2890. for (var i = 0, ilen = this.timeouts.length; i < ilen; i++) {
  2891. clearTimeout(this.timeouts[i]);
  2892. }
  2893. };
  2894. /**
  2895. * Handsontable version
  2896. *
  2897. * @type {String}
  2898. */
  2899. // this.version = Handsontable.version;
  2900. Hooks.getSingleton().run(instance, 'construct');
  2901. };