-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathHyperFormula.ts
More file actions
4660 lines (4484 loc) · 169 KB
/
HyperFormula.ts
File metadata and controls
4660 lines (4484 loc) · 169 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright (c) 2025 Handsoncode. All rights reserved.
*/
import {AbsoluteCellRange, isSimpleCellRange, SimpleCellRange} from './AbsoluteCellRange'
import {validateArgToType} from './ArgumentSanitization'
import {BuildEngineFactory, EngineState} from './BuildEngineFactory'
import {
CellType,
CellValueDetailedType,
CellValueType,
getCellType,
getCellValueDetailedType,
getCellValueFormat,
getCellValueType,
isSimpleCellAddress,
SimpleCellAddress
} from './Cell'
import {CellContent, CellContentParser, RawCellContent} from './CellContentParser'
import {CellValue} from './CellValue'
import {Config, getDefaultConfig} from './Config'
import {ColumnRowIndex, CrudOperations} from './CrudOperations'
import {DateTime, numberToSimpleTime} from './DateTimeHelper'
import {
AddressMapping,
ArrayMapping,
DependencyGraph,
Graph,
RangeMapping,
SheetMapping,
Vertex,
} from './DependencyGraph'
import {objectDestroy} from './Destroy'
import {Emitter, Events, Listeners, TypedEmitter} from './Emitter'
import {
EvaluationSuspendedError,
ExpectedValueOfTypeError,
LanguageAlreadyRegisteredError,
LanguageNotRegisteredError,
NotAFormulaError,
} from './errors'
import {Evaluator} from './Evaluator'
import {ExportedChange, Exporter} from './Exporter'
import {LicenseKeyValidityState} from './helpers/licenseKeyValidator'
import {buildTranslationPackage, RawTranslationPackage, TranslationPackage} from './i18n'
import {FunctionPluginDefinition} from './interpreter'
import {FunctionRegistry, FunctionTranslationsPackage} from './interpreter/FunctionRegistry'
import {FormatInfo} from './interpreter/InterpreterValue'
import {LazilyTransformingAstService} from './LazilyTransformingAstService'
import {ColumnSearchStrategy} from './Lookup/SearchStrategy'
import {NamedExpression, NamedExpressionOptions, NamedExpressions} from './NamedExpressions'
import {normalizeAddedIndexes, normalizeRemovedIndexes} from './Operations'
import {
Ast,
NamedExpressionDependency,
ParserWithCaching,
RelativeDependency,
simpleCellAddressFromString,
simpleCellAddressToString,
simpleCellRangeFromString,
simpleCellRangeToString,
Unparser,
} from './parser'
import {Serialization, SerializedNamedExpression} from './Serialization'
import {Sheet, SheetDimensions, Sheets} from './Sheet'
import {Statistics, StatType} from './statistics'
import {ConfigParams} from './ConfigParams'
/**
* This is a class for creating HyperFormula instance, all the following public methods
* are related to this class.
*
* The instance can be created only by calling one of the static methods
* `buildFromArray`, `buildFromSheets` or `buildEmpty` and should be disposed of with the
* `destroy` method when it's no longer needed to free the resources.
*
* The instance can be seen as a workbook where worksheets can be created and
* manipulated. They are organized within a widely known structure of columns and rows
* which can be manipulated as well. The smallest possible data unit are the cells, which
* may contain simple values or formulas to be calculated.
*
* All CRUD methods are called directly on HyperFormula instance and will trigger
* corresponding lifecycle events. The events are marked accordingly, as well as thrown
* errors, so they can be correctly handled.
*/
export class HyperFormula implements TypedEmitter {
/**
* Version of the HyperFormula.
*
* @category Static Properties
*/
public static version = process.env.HT_VERSION as string
/**
* Latest build date.
*
* @category Static Properties
*/
public static buildDate = process.env.HT_BUILD_DATE as string
/**
* A release date.
*
* @category Static Properties
*/
public static releaseDate = process.env.HT_RELEASE_DATE as string
/**
* When using the UMD build, this property contains all available languages to use with the [registerLanguage](#registerlanguage) method.
*
* For more information, see the [Localizing functions](/guide/localizing-functions.md) guide.
*
* @category Static Properties
*/
public static languages: Record<string, RawTranslationPackage> = {}
private static registeredLanguages: Map<string, TranslationPackage> = new Map()
private readonly _emitter: Emitter = new Emitter()
private _evaluationSuspended: boolean = false
/**
* Constructor
*
* @internal
*/
protected constructor(
private _config: Config,
private _stats: Statistics,
private _dependencyGraph: DependencyGraph,
private _columnSearch: ColumnSearchStrategy,
private _parser: ParserWithCaching,
private _unparser: Unparser,
private _cellContentParser: CellContentParser,
private _evaluator: Evaluator,
private _lazilyTransformingAstService: LazilyTransformingAstService,
private _crudOperations: CrudOperations,
private _exporter: Exporter,
private _namedExpressions: NamedExpressions,
private _serialization: Serialization,
private _functionRegistry: FunctionRegistry,
) {
}
/**
* Returns all of HyperFormula's default [configuration options](/guide/configuration-options.md).
*
* @example
* ```js
* // returns all default configuration options
* const defaultConfig = HyperFormula.defaultConfig;
* ```
*
* @category Static Accessors
*/
public static get defaultConfig(): ConfigParams {
return getDefaultConfig()
}
/**
* Calls the `graph` method on the dependency graph.
* Allows for executing `graph` directly, without a need to refer to `dependencyGraph`.
*
* @internal
*/
public get graph(): Graph<Vertex> {
return this.dependencyGraph.graph
}
/**
* Calls the `rangeMapping` method on the dependency graph.
* Allows for executing `rangeMapping` directly, without a need to refer to `dependencyGraph`.
*
* @internal
*/
public get rangeMapping(): RangeMapping {
return this.dependencyGraph.rangeMapping
}
/**
* Calls the `arrayMapping` method on the dependency graph.
* Allows for executing `arrayMapping` directly, without a need to refer to `dependencyGraph`.
*
* @internal
*/
public get arrayMapping(): ArrayMapping {
return this.dependencyGraph.arrayMapping
}
/**
* Calls the `sheetMapping` method on the dependency graph.
* Allows for executing `sheetMapping` directly, without a need to refer to `dependencyGraph`.
*
* @internal
*/
public get sheetMapping(): SheetMapping {
return this.dependencyGraph.sheetMapping
}
/**
* Calls the `addressMapping` method on the dependency graph.
* Allows for executing `addressMapping` directly, without a need to refer to `dependencyGraph`.
*
* @internal
*/
public get addressMapping(): AddressMapping {
return this.dependencyGraph.addressMapping
}
/** @internal */
public get dependencyGraph(): DependencyGraph {
return this._dependencyGraph
}
/** @internal */
public get evaluator(): Evaluator {
return this._evaluator
}
/** @internal */
public get columnSearch(): ColumnSearchStrategy {
return this._columnSearch
}
/** @internal */
public get lazilyTransformingAstService(): LazilyTransformingAstService {
return this._lazilyTransformingAstService
}
/**
* Returns state of the validity of the license key.
*
* @internal
*/
public get licenseKeyValidityState(): LicenseKeyValidityState {
return this._config.licenseKeyValidityState
}
/**
* Builds the engine for a sheet from a two-dimensional array representation.
* The engine is created with a single sheet.
* Can be configured with the optional second parameter that represents a [[ConfigParams]].
* If not specified, the engine will be built with the default configuration.
*
* @param {Sheet} sheet - two-dimensional array representation of sheet
* @param {Partial<ConfigParams>} configInput - engine configuration
* @param {SerializedNamedExpression[]} namedExpressions - starting named expressions
*
* @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits
* @throws [[InvalidArgumentsError]] when sheet is not an array of arrays
* @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata
*
* @example
* ```js
* // data represented as an array
* const sheetData = [
* ['0', '=SUM(1, 2, 3)', '52'],
* ['=SUM(A1:C1)', '', '=A1'],
* ['2', '=SUM(A1:C1)', '=theUltimateQuestionOfLife'],
* ];
*
* const namedExpressions = [
* {
* name: 'theUltimateQuestionOfLife',
* expression: '=42',
* },
* ];
*
* // method with optional config parameter maxColumns
* const hfInstance = HyperFormula.buildFromArray(sheetData, { maxColumns: 1000 }, namedExpressions);
* ```
*
* @category Factories
*/
public static buildFromArray(sheet: Sheet, configInput: Partial<ConfigParams> = {}, namedExpressions: SerializedNamedExpression[] = []): HyperFormula {
return this.buildFromEngineState(BuildEngineFactory.buildFromSheet(sheet, configInput, namedExpressions))
}
/**
* Builds the engine from an object containing multiple sheets with names.
* The engine is created with one or more sheets.
* Can be configured with the optional second parameter that represents a [[ConfigParams]].
* If not specified the engine will be built with the default configuration.
*
* @param {Sheet} sheets - object with sheets definition
* @param {Partial<ConfigParams>} configInput - engine configuration
* @param {SerializedNamedExpression[]} namedExpressions - starting named expressions
*
* @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits
* @throws [[InvalidArgumentsError]] when any sheet is not an array of arrays
* @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata
*
* @example
* ```js
* // data represented as an object with sheets: Sheet1 and Sheet2
* const sheetData = {
* 'Sheet1': [
* ['1', '', '=Sheet2!$A1'],
* ['', '2', '=SUM(1, 2, 3)'],
* ['=Sheet2!$A2', '2', ''],
* ],
* 'Sheet2': [
* ['', '4', '=Sheet1!$B1'],
* ['', '8', '=SUM(9, 3, 3)'],
* ['=Sheet1!$B1', '2', '=theUltimateQuestionOfLife'],
* ],
* };
*
* const namedExpressions = [
* {
* name: 'theUltimateQuestionOfLife',
* expression: '=42',
* },
* ];
*
* // method with optional config parameter useColumnIndex
* const hfInstance = HyperFormula.buildFromSheets(sheetData, { useColumnIndex: true }, namedExpressions);
* ```
*
* @category Factories
*/
public static buildFromSheets(sheets: Sheets, configInput: Partial<ConfigParams> = {}, namedExpressions: SerializedNamedExpression[] = []): HyperFormula {
return this.buildFromEngineState(BuildEngineFactory.buildFromSheets(sheets, configInput, namedExpressions))
}
/**
* Builds an empty engine instance.
* Can be configured with the optional parameter that represents a [[ConfigParams]].
* If not specified the engine will be built with the default configuration.
*
* @param {Partial<ConfigParams>} configInput - engine configuration
* @param {SerializedNamedExpression[]} namedExpressions - starting named expressions
*
* @example
* ```js
* const namedExpressions = [
* {
* name: 'theUltimateQuestionOfLife',
* expression: '=42',
* },
* ];
*
* // build with no initial data and with optional config parameter maxColumns
* const hfInstance = HyperFormula.buildEmpty({ maxColumns: 1000 }, namedExpressions);
* ```
*
* @category Factories
*/
public static buildEmpty(configInput: Partial<ConfigParams> = {}, namedExpressions: SerializedNamedExpression[] = []): HyperFormula {
return this.buildFromEngineState(BuildEngineFactory.buildEmpty(configInput, namedExpressions))
}
/**
* Returns registered language from its code string.
*
* For more information, see the [Localizing functions guide](/guide/localizing-functions.md).
*
* @param {string} languageCode - code string of the translation package
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[LanguageNotRegisteredError]] when trying to retrieve not registered language
*
* @example
* ```js
* // return registered language
* const language = HyperFormula.getLanguage('enGB');
* ```
*
* @category Static Methods
*/
public static getLanguage(languageCode: string): TranslationPackage {
validateArgToType(languageCode, 'string', 'languageCode')
const val = this.registeredLanguages.get(languageCode)
if (val === undefined) {
throw new LanguageNotRegisteredError()
} else {
return val
}
}
/**
* Registers language under given code string.
*
* For more information, see the [Localizing functions guide](/guide/localizing-functions.md).
*
* @param {string} languageCode - code string of the translation package
* @param {RawTranslationPackage} languagePackage - translation package to be registered
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[ProtectedFunctionTranslationError]] when trying to register translation for protected function
* @throws [[LanguageAlreadyRegisteredError]] when given language is already registered
*
* @example
* ```js
* // return registered language
* HyperFormula.registerLanguage('enUS', enUS);
* const engine = HyperFormula.buildEmpty({language: 'enUS'});
* ```
*
* @category Static Methods
*/
public static registerLanguage(languageCode: string, languagePackage: RawTranslationPackage): void {
validateArgToType(languageCode, 'string', 'languageCode')
if (this.registeredLanguages.has(languageCode)) {
throw new LanguageAlreadyRegisteredError()
} else {
this.registeredLanguages.set(languageCode, buildTranslationPackage(languagePackage))
}
}
/**
* Unregisters language that is registered under given code string.
*
* For more information, see the [Localizing functions guide](/guide/localizing-functions.md).
*
* @param {string} languageCode - code string of the translation package
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[LanguageNotRegisteredError]] when given language is not registered
*
* @example
* ```js
* // register the language for the instance
* HyperFormula.registerLanguage('plPL', plPL);
*
* // unregister plPL
* HyperFormula.unregisterLanguage('plPL');
* ```
*
* @category Static Methods
*/
public static unregisterLanguage(languageCode: string): void {
validateArgToType(languageCode, 'string', 'languageCode')
if (this.registeredLanguages.has(languageCode)) {
this.registeredLanguages.delete(languageCode)
} else {
throw new LanguageNotRegisteredError()
}
}
/**
* Returns all registered languages codes.
*
* @example
* ```js
* // should return all registered language codes: ['enGB', 'plPL']
* const registeredLanguages = HyperFormula.getRegisteredLanguagesCodes();
* ```
*
* @category Static Methods
*/
public static getRegisteredLanguagesCodes(): string[] {
return Array.from(this.registeredLanguages.keys())
}
/**
* Registers all functions in a given plugin with optional translations.
*
* For more information, see the [Custom functions guide](/guide/custom-functions.md).
*
* Note: FunctionPlugins must be registered prior to the creation of HyperFormula instances in which they are used.
* HyperFormula instances created prior to the registration of a FunctionPlugin are unable to access the FunctionPlugin.
* Registering a FunctionPlugin with [[custom-functions]] requires the translations parameter.
*
* @param {FunctionPluginDefinition} plugin - plugin class
* @param {FunctionTranslationsPackage} translations - optional package of function names translations
*
* @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata
* @throws [[ProtectedFunctionTranslationError]] when trying to register translation for protected function
*
* @example
* ```js
* // import your own plugin
* import { MyExamplePlugin } from './file_with_your_plugin';
*
* // register the plugin
* HyperFormula.registerFunctionPlugin(MyExamplePlugin);
* ```
*
* @category Static Methods
*/
public static registerFunctionPlugin(plugin: FunctionPluginDefinition, translations?: FunctionTranslationsPackage): void {
FunctionRegistry.registerFunctionPlugin(plugin, translations)
}
/**
* Unregisters all functions defined in given plugin.
*
* For more information, see the [Custom functions guide](/guide/custom-functions.md).
*
* Note: This method does not affect the existing HyperFormula instances.
*
* @param {FunctionPluginDefinition} plugin - plugin class
*
* @example
* ```js
* // get the class of a plugin
* const registeredPluginClass = HyperFormula.getFunctionPlugin('EXAMPLE');
*
* // unregister all functions defined in a plugin of ID 'EXAMPLE'
* HyperFormula.unregisterFunctionPlugin(registeredPluginClass);
* ```
*
* @category Static Methods
*/
public static unregisterFunctionPlugin(plugin: FunctionPluginDefinition): void {
FunctionRegistry.unregisterFunctionPlugin(plugin)
}
/**
* Registers a function with a given id if such exists in a plugin.
*
* For more information, see the [Custom functions guide](/guide/custom-functions.md).
*
* Note: This method does not affect the existing HyperFormula instances.
*
* @param {string} functionId - function id, e.g., 'SUMIF'
* @param {FunctionPluginDefinition} plugin - plugin class
* @param {FunctionTranslationsPackage} translations - translations for the function name
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[FunctionPluginValidationError]] when function with a given id does not exist in plugin or plugin class definition is not consistent with metadata
* @throws [[ProtectedFunctionTranslationError]] when trying to register translation for protected function
*
* @example
* ```js
* // import your own plugin
* import { MyExamplePlugin } from './file_with_your_plugin';
*
* // register a function
* HyperFormula.registerFunction('EXAMPLE', MyExamplePlugin);
* ```
*
* @category Static Methods
*/
public static registerFunction(functionId: string, plugin: FunctionPluginDefinition, translations?: FunctionTranslationsPackage): void {
validateArgToType(functionId, 'string', 'functionId')
FunctionRegistry.registerFunction(functionId, plugin, translations)
}
/**
* Unregisters a function with a given id.
*
* For more information, see the [Custom functions guide](/guide/custom-functions.md).
*
* Note: This method does not affect the existing HyperFormula instances.
*
* @param {string} functionId - function id, e.g., 'SUMIF'
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
*
* @example
* ```js
* // import your own plugin
* import { MyExamplePlugin } from './file_with_your_plugin';
*
* // register a function
* HyperFormula.registerFunction('EXAMPLE', MyExamplePlugin);
*
* // unregister a function
* HyperFormula.unregisterFunction('EXAMPLE');
* ```
*
* @category Static Methods
*/
public static unregisterFunction(functionId: string): void {
validateArgToType(functionId, 'string', 'functionId')
FunctionRegistry.unregisterFunction(functionId)
}
/**
* Clears function registry.
*
* Note: This method does not affect the existing HyperFormula instances.
*
* @example
* ```js
* HyperFormula.unregisterAllFunctions();
* ```
*
* @category Static Methods
*/
public static unregisterAllFunctions(): void {
FunctionRegistry.unregisterAll()
}
/**
* Returns translated names of all registered functions for a given language
*
* @param {string} code - language code
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
*
* @example
* ```js
* // return a list of function names registered for enGB
* const allNames = HyperFormula.getRegisteredFunctionNames('enGB');
* ```
*
* @category Static Methods
*/
public static getRegisteredFunctionNames(code: string): string[] {
validateArgToType(code, 'string', 'code')
const functionIds = FunctionRegistry.getRegisteredFunctionIds()
const language = this.getLanguage(code)
return language.getFunctionTranslations(functionIds)
}
/**
* Returns class of a plugin used by function with given id
*
* For more information, see the [Custom functions guide](/guide/custom-functions.md).
*
* @param {string} functionId - id of a function, e.g., 'SUMIF'
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
*
* @example
* ```js
* // import your own plugin
* import { MyExamplePlugin } from './file_with_your_plugin';
*
* // register a plugin
* HyperFormula.registerFunctionPlugin(MyExamplePlugin);
*
* // return the class of a given plugin
* const myFunctionClass = HyperFormula.getFunctionPlugin('EXAMPLE');
* ```
*
* @category Static Methods
*/
public static getFunctionPlugin(functionId: string): FunctionPluginDefinition | undefined {
validateArgToType(functionId, 'string', 'functionId')
return FunctionRegistry.getFunctionPlugin(functionId)
}
/**
* Returns classes of all plugins registered in HyperFormula.
*
* @example
* ```js
* // return classes of all plugins
* const allClasses = HyperFormula.getAllFunctionPlugins();
* ```
*
* @category Static Methods
*/
public static getAllFunctionPlugins(): FunctionPluginDefinition[] {
return FunctionRegistry.getPlugins()
}
/**
* @internal
*/
private static buildFromEngineState(engine: EngineState): HyperFormula {
return new HyperFormula(
engine.config,
engine.stats,
engine.dependencyGraph,
engine.columnSearch,
engine.parser,
engine.unparser,
engine.cellContentParser,
engine.evaluator,
engine.lazilyTransformingAstService,
engine.crudOperations,
engine.exporter,
engine.namedExpressions,
engine.serialization,
engine.functionRegistry,
)
}
/**
* Returns the cell value of a given address.
* Applies rounding and post-processing.
*
* @param {SimpleCellAddress} cellAddress - cell coordinates
*
* @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
* @throws [[EvaluationSuspendedError]] when the evaluation is suspended
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['=SUM(1, 2, 3)', '2'],
* ]);
*
* // get value of A1 cell, should be '6'
* const A1Value = hfInstance.getCellValue({ sheet: 0, col: 0, row: 0 });
*
* // get value of B1 cell, should be '2'
* const B1Value = hfInstance.getCellValue({ sheet: 0, col: 1, row: 0 });
* ```
*
* @category Cells
*/
public getCellValue(cellAddress: SimpleCellAddress): CellValue {
if (!isSimpleCellAddress(cellAddress)) {
throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress')
}
this.ensureEvaluationIsNotSuspended()
return this._serialization.getCellValue(cellAddress)
}
/**
* Returns a normalized formula string from the cell of a given address or `undefined` for an address that does not exist and empty values.
*
* @param {SimpleCellAddress} cellAddress - cell coordinates
*
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
* @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['=SUM(1, 2, 3)', '0'],
* ]);
*
* // should return a normalized A1 cell formula: '=SUM(1, 2, 3)'
* const A1Formula = hfInstance.getCellFormula({ sheet: 0, col: 0, row: 0 });
*
* // should return a normalized B1 cell formula: 'undefined'
* const B1Formula = hfInstance.getCellFormula({ sheet: 0, col: 1, row: 0 });
* ```
*
* @category Cells
*/
public getCellFormula(cellAddress: SimpleCellAddress): string | undefined {
if (!isSimpleCellAddress(cellAddress)) {
throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress')
}
return this._serialization.getCellFormula(cellAddress)
}
/**
* Returns the `HYPERLINK` url for a cell of a given address or `undefined` for an address that does not exist or a cell that is not `HYPERLINK`
*
* @param {SimpleCellAddress} cellAddress - cell coordinates
*
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
* @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['=HYPERLINK("https://hyperformula.handsontable.com/", "HyperFormula")', '0'],
* ]);
*
* // should return url of 'HYPERLINK': https://hyperformula.handsontable.com/
* const A1Hyperlink = hfInstance.getCellHyperlink({ sheet: 0, col: 0, row: 0 });
*
* // should return 'undefined' for a cell that is not 'HYPERLINK'
* const B1Hyperlink = hfInstance.getCellHyperlink({ sheet: 0, col: 1, row: 0 });
* ```
*
* @category Cells
*/
public getCellHyperlink(cellAddress: SimpleCellAddress): string | undefined {
if (!isSimpleCellAddress(cellAddress)) {
throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress')
}
this.ensureEvaluationIsNotSuspended()
return this._serialization.getCellHyperlink(cellAddress)
}
/**
* Returns [[RawCellContent]] with a serialized content of the cell of a given address: either a cell formula, an explicit value, or an error.
*
* @param {SimpleCellAddress} cellAddress - cell coordinates
*
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
* @throws [[EvaluationSuspendedError]] when the evaluation is suspended
* @throws [[ExpectedValueOfTypeError]] when cellAddress is of incorrect type
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['=SUM(1, 2, 3)', '0'],
* ]);
*
* // should return serialized content of A1 cell: '=SUM(1, 2, 3)'
* const cellA1Serialized = hfInstance.getCellSerialized({ sheet: 0, col: 0, row: 0 });
*
* // should return serialized content of B1 cell: '0'
* const cellB1Serialized = hfInstance.getCellSerialized({ sheet: 0, col: 1, row: 0 });
* ```
*
* @category Cells
*/
public getCellSerialized(cellAddress: SimpleCellAddress): RawCellContent {
if (!isSimpleCellAddress(cellAddress)) {
throw new ExpectedValueOfTypeError('SimpleCellAddress', 'cellAddress')
}
this.ensureEvaluationIsNotSuspended()
return this._serialization.getCellSerialized(cellAddress)
}
/**
* Returns an array of arrays of [[CellValue]] with values of all cells from [[Sheet]].
* Applies rounding and post-processing.
*
* @param {number} sheetId - sheet ID number
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
* @throws [[EvaluationSuspendedError]] when the evaluation is suspended
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['0', '=SUM(1, 2, 3)', '=A1'],
* ['1', '=TEXT(A2, "0.0%")', '=C1'],
* ['2', '=SUM(A1:C1)', '=C1'],
* ]);
*
* // should return all values of a sheet: [[0, 6, 0], [1, '1.0%', 0], [2, 6, 0]]
* const sheetValues = hfInstance.getSheetValues(0);
* ```
*
* @category Sheets
*/
public getSheetValues(sheetId: number): CellValue[][] {
validateArgToType(sheetId, 'number', 'sheetId')
this.ensureEvaluationIsNotSuspended()
return this._serialization.getSheetValues(sheetId)
}
/**
* Returns an array with normalized formula strings from [[Sheet]] or `undefined` for a cells that have no value.
*
* @param {SimpleCellAddress} sheetId - sheet ID number
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['0', '=SUM(1, 2, 3)', '=A1'],
* ['1', '=TEXT(A2, "0.0%")', '=C1'],
* ['2', '=SUM(A1:C1)', '=C1'],
* ]);
*
* // should return all formulas of a sheet:
* // [
* // [undefined, '=SUM(1, 2, 3)', '=A1'],
* // [undefined, '=TEXT(A2, "0.0%")', '=C1'],
* // [undefined, '=SUM(A1:C1)', '=C1'],
* // ];
* const sheetFormulas = hfInstance.getSheetFormulas(0);
* ```
*
* @category Sheets
*/
public getSheetFormulas(sheetId: number): (string | undefined)[][] {
validateArgToType(sheetId, 'number', 'sheetId')
return this._serialization.getSheetFormulas(sheetId)
}
/**
* Returns an array of arrays of [[RawCellContent]] with serialized content of cells from [[Sheet]], either a cell formula or an explicit value.
*
* @param {SimpleCellAddress} sheetId - sheet ID number
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[EvaluationSuspendedError]] when the evaluation is suspended
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['0', '=SUM(1, 2, 3)', '=A1'],
* ['1', '=TEXT(A2, "0.0%")', '=C1'],
* ['2', '=SUM(A1:C1)', '=C1'],
* ]);
*
* // should return:
* // [
* // ['0', '=SUM(1, 2, 3)', '=A1'],
* // ['1', '=TEXT(A2, "0.0%")', '=C1'],
* // ['2', '=SUM(A1:C1)', '=C1'],
* // ];
* const serializedContent = hfInstance.getSheetSerialized(0);
* ```
*
* @category Sheets
*/
public getSheetSerialized(sheetId: number): RawCellContent[][] {
validateArgToType(sheetId, 'number', 'sheetId')
this.ensureEvaluationIsNotSuspended()
return this._serialization.getSheetSerialized(sheetId)
}
/**
* Returns a map containing dimensions of all sheets for the engine instance represented as a key-value pairs where keys are sheet IDs and dimensions are returned as numbers, width and height respectively.
*
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromSheets({
* Sheet1: [
* ['1', '2', '=Sheet2!$A1'],
* ],
* Sheet2: [
* ['3'],
* ['4'],
* ],
* });
*
* // should return the dimensions of all sheets:
* // { Sheet1: { width: 3, height: 1 }, Sheet2: { width: 1, height: 2 } }
* const allSheetsDimensions = hfInstance.getAllSheetsDimensions();
* ```
*
* @category Sheets
*/
public getAllSheetsDimensions(): Record<string, SheetDimensions> {
return this._serialization.genericAllSheetsGetter((arg) => this.getSheetDimensions(arg))
}
/**
* Returns dimensions of a specified sheet.
* The sheet dimensions is represented with numbers: width and height.
*
* Note: Due to the memory optimizations, some of the empty bottom rows and rightmost columns are not counted to the dimensions.
*
* @param {number} sheetId - sheet ID number
*
* @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type
* @throws [[NoSheetWithIdError]] when the given sheet ID does not exist
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['1', '2', '=Sheet2!$A1'],
* ]);
*
* // should return provided sheet's dimensions: { width: 3, height: 1 }
* const sheetDimensions = hfInstance.getSheetDimensions(0);
* ```
*
* @category Sheets
*/
public getSheetDimensions(sheetId: number): SheetDimensions {
validateArgToType(sheetId, 'number', 'sheetId')
return {
width: this.dependencyGraph.getSheetWidth(sheetId),
height: this.dependencyGraph.getSheetHeight(sheetId),
}
}
/**
* Returns values of all sheets in a form of an object which property keys are strings and values are 2D arrays of [[CellValue]].
*
* @throws [[EvaluationSuspendedError]] when the evaluation is suspended
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['1', '=A1+10', '3'],
* ]);
*
* // should return all sheets values: { Sheet1: [ [ 1, 11, 3 ] ] }
* const allSheetsValues = hfInstance.getAllSheetsValues();
* ```
*
* @category Sheets
*/
public getAllSheetsValues(): Record<string, CellValue[][]> {
this.ensureEvaluationIsNotSuspended()
return this._serialization.getAllSheetsValues()
}
/**
* Returns formulas of all sheets in a form of an object which property keys are strings and values are 2D arrays of strings or possibly `undefined` when the call does not contain a formula.
*
* @example
* ```js
* const hfInstance = HyperFormula.buildFromArray([
* ['1', '2', '=A1+10'],
* ]);
*
* // should return only formulas: { Sheet1: [ [ undefined, undefined, '=A1+10' ] ] }
* const allSheetsFormulas = hfInstance.getAllSheetsFormulas();
* ```
* @category Sheets
*/
public getAllSheetsFormulas(): Record<string, (string | undefined)[][]> {
return this._serialization.getAllSheetsFormulas()
}
/**
* Returns formulas or values of all sheets in a form of an object which property keys are strings and values are 2D arrays of [[RawCellContent]].
*
* @throws [[EvaluationSuspendedError]] when the evaluation is suspended
*
* @example