core.js 121 KB

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