core.js 120 KB

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