b062237dfa166a976d3fb0b70bf11182d9efd7c85da8a3e24602883fc1539af2360c35f59287ed5671088a23e792239c9db1ba8ac0a20ab8eed4fd37ea9bbc 105 KB

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