@odoo/o-spreadsheet 14.0.0 → 14.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/.eslintrc.json +20 -0
  2. package/.husky/post-checkout +9 -0
  3. package/.husky/pre-commit +39 -0
  4. package/.prettierignore +1 -0
  5. package/astToFormula.patch +0 -0
  6. package/demo/data.js +255 -0
  7. package/demo/index.html +9 -0
  8. package/demo/libs/Chart.bundle.js +20755 -0
  9. package/demo/main.js +101 -0
  10. package/doc/readme.md +46 -0
  11. package/package.json +3 -17
  12. package/rollup.config.js +23 -0
  13. package/src/base_plugin.ts +102 -0
  14. package/src/components/autofill.ts +146 -0
  15. package/src/components/bottom_bar.ts +199 -0
  16. package/src/components/color_picker.ts +150 -0
  17. package/src/components/composer/autocomplete_dropdown.ts +135 -0
  18. package/src/components/composer/composer.ts +487 -0
  19. package/src/components/composer/content_editable_helper.ts +146 -0
  20. package/src/components/figures/chart.ts +70 -0
  21. package/src/components/figures/container.ts +268 -0
  22. package/src/components/figures/text_figure.ts +36 -0
  23. package/src/components/grid.ts +635 -0
  24. package/src/components/helpers/dom_helpers.ts +7 -0
  25. package/src/components/helpers/drag_and_drop.ts +17 -0
  26. package/src/components/icons.ts +36 -0
  27. package/src/components/index.ts +1 -0
  28. package/src/components/menu.ts +288 -0
  29. package/src/components/overlay.ts +457 -0
  30. package/src/components/scrollbar.ts +22 -0
  31. package/src/components/selection_input.ts +168 -0
  32. package/src/components/side_panel/cell_is_rule_editor.ts +169 -0
  33. package/src/components/side_panel/chart_panel.ts +104 -0
  34. package/src/components/side_panel/color_scale_rule_editor.ts +145 -0
  35. package/src/components/side_panel/conditional_formatting.ts +396 -0
  36. package/src/components/side_panel/side_panel.ts +127 -0
  37. package/src/components/side_panel/translations_terms.ts +45 -0
  38. package/src/components/spreadsheet.ts +198 -0
  39. package/src/components/top_bar.ts +535 -0
  40. package/src/constants.ts +26 -0
  41. package/src/data.ts +149 -0
  42. package/src/fonts.ts +41 -0
  43. package/src/formulas/compiler.ts +258 -0
  44. package/src/formulas/composer_tokenizer.ts +70 -0
  45. package/src/formulas/index.ts +15 -0
  46. package/src/formulas/normalize.ts +52 -0
  47. package/src/formulas/parser.ts +280 -0
  48. package/src/formulas/range_tokenizer.ts +97 -0
  49. package/src/formulas/tokenizer.ts +242 -0
  50. package/src/functions/arguments.ts +114 -0
  51. package/src/functions/dates.ts +302 -0
  52. package/src/functions/helpers.ts +592 -0
  53. package/src/functions/index.ts +52 -0
  54. package/src/functions/module_database.ts +282 -0
  55. package/src/functions/module_date.ts +743 -0
  56. package/src/functions/module_info.ts +69 -0
  57. package/src/functions/module_logical.ts +208 -0
  58. package/src/functions/module_lookup.ts +185 -0
  59. package/src/functions/module_math.ts +1252 -0
  60. package/src/functions/module_operators.ts +291 -0
  61. package/src/functions/module_statistical.ts +882 -0
  62. package/src/functions/module_text.ts +370 -0
  63. package/src/helpers/color.ts +30 -0
  64. package/src/helpers/coordinates.ts +71 -0
  65. package/src/helpers/grid_manipulation.ts +68 -0
  66. package/src/helpers/index.ts +7 -0
  67. package/src/helpers/misc.ts +76 -0
  68. package/src/helpers/numbers.ts +117 -0
  69. package/src/helpers/uuid.ts +19 -0
  70. package/src/helpers/zones.ts +263 -0
  71. package/src/history.ts +186 -0
  72. package/src/index.ts +84 -0
  73. package/src/model.ts +261 -0
  74. package/src/plugins/autofill.ts +412 -0
  75. package/src/plugins/chart.ts +404 -0
  76. package/src/plugins/clipboard.ts +461 -0
  77. package/src/plugins/conditional_format.ts +445 -0
  78. package/src/plugins/core.ts +1502 -0
  79. package/src/plugins/edition.ts +157 -0
  80. package/src/plugins/evaluation.ts +428 -0
  81. package/src/plugins/figures.ts +123 -0
  82. package/src/plugins/formatting.ts +630 -0
  83. package/src/plugins/highlight.ts +187 -0
  84. package/src/plugins/index.ts +32 -0
  85. package/src/plugins/merge.ts +524 -0
  86. package/src/plugins/renderer.ts +571 -0
  87. package/src/plugins/selection.ts +562 -0
  88. package/src/plugins/selection_inputs.ts +326 -0
  89. package/src/registries/autofill_modifiers.ts +76 -0
  90. package/src/registries/autofill_rules.ts +98 -0
  91. package/src/registries/figure_registry.ts +30 -0
  92. package/src/registries/index.ts +7 -0
  93. package/src/registries/menu_items_registry.ts +110 -0
  94. package/src/registries/menus/cell_menu_registry.ts +79 -0
  95. package/src/registries/menus/col_menu_registry.ts +63 -0
  96. package/src/registries/menus/index.ts +6 -0
  97. package/src/registries/menus/menu_items_actions.ts +425 -0
  98. package/src/registries/menus/row_menu_registry.ts +63 -0
  99. package/src/registries/menus/sheet_menu_registry.ts +75 -0
  100. package/src/registries/menus/topbar_menu_registry.ts +204 -0
  101. package/src/registries/side_panel_registry.ts +26 -0
  102. package/src/registries/topbar_component_registry.ts +12 -0
  103. package/src/registry.ts +51 -0
  104. package/src/translation.ts +44 -0
  105. package/src/types/autofill.ts +48 -0
  106. package/src/types/chart.ts +26 -0
  107. package/src/types/commands.ts +716 -0
  108. package/src/types/conditional_formatting.ts +124 -0
  109. package/src/types/env.ts +13 -0
  110. package/src/types/functions.ts +35 -0
  111. package/src/types/getters.ts +103 -0
  112. package/src/types/index.ts +20 -0
  113. package/src/types/misc.ts +143 -0
  114. package/src/types/rendering.ts +41 -0
  115. package/src/types/workbook_data.ts +62 -0
  116. package/tests/__mocks__/uuid.ts +7 -0
  117. package/tests/canvas.mock.ts +34 -0
  118. package/tests/components/__mocks__/content_editable_helper.ts +79 -0
  119. package/tests/components/__mocks__/scrollbar.ts +18 -0
  120. package/tests/components/__snapshots__/autocomplete_dropdown_test.ts.snap +29 -0
  121. package/tests/components/__snapshots__/bottom_bar_test.ts.snap +75 -0
  122. package/tests/components/__snapshots__/context_menu_test.ts.snap +88 -0
  123. package/tests/components/__snapshots__/grid_test.ts.snap +60 -0
  124. package/tests/components/__snapshots__/spreadsheet_test.ts.snap +455 -0
  125. package/tests/components/__snapshots__/top_bar_test.ts.snap +705 -0
  126. package/tests/components/autocomplete_dropdown_test.ts +315 -0
  127. package/tests/components/autofill_test.ts +167 -0
  128. package/tests/components/bottom_bar_test.ts +262 -0
  129. package/tests/components/chart_side_panel_test.ts +123 -0
  130. package/tests/components/composer_test.ts +400 -0
  131. package/tests/components/context_menu_test.ts +825 -0
  132. package/tests/components/grid_manipulation_test.ts +163 -0
  133. package/tests/components/grid_test.ts +581 -0
  134. package/tests/components/overlay_test.ts +541 -0
  135. package/tests/components/selection_input_test.ts +259 -0
  136. package/tests/components/side_panel_test.ts +148 -0
  137. package/tests/components/spreadsheet_test.ts +194 -0
  138. package/tests/components/top_bar_test.ts +427 -0
  139. package/tests/data_test.ts +175 -0
  140. package/tests/dom_helper.ts +42 -0
  141. package/tests/formulas/__snapshots__/compiler_test.ts.snap +302 -0
  142. package/tests/formulas/compiler_test.ts +266 -0
  143. package/tests/formulas/composer_tokenizer_test.ts +137 -0
  144. package/tests/formulas/expressions_test.ts +57 -0
  145. package/tests/formulas/formulas_test.ts +80 -0
  146. package/tests/formulas/normalize_test.ts +82 -0
  147. package/tests/formulas/parser_test.ts +224 -0
  148. package/tests/formulas/range_tokenizer_test.ts +187 -0
  149. package/tests/formulas/tokenizer_test.ts +164 -0
  150. package/tests/functions/arguments_test.ts +141 -0
  151. package/tests/functions/dates_test.ts +1081 -0
  152. package/tests/functions/functions_test.ts +53 -0
  153. package/tests/functions/helper_test.ts +98 -0
  154. package/tests/functions/module_database_test.ts +311 -0
  155. package/tests/functions/module_date_test.ts +941 -0
  156. package/tests/functions/module_info_test.ts +139 -0
  157. package/tests/functions/module_logical_test.ts +369 -0
  158. package/tests/functions/module_lookup_test.ts +541 -0
  159. package/tests/functions/module_math_test.ts +2482 -0
  160. package/tests/functions/module_operators_test.ts +955 -0
  161. package/tests/functions/module_statistical_test.ts +2014 -0
  162. package/tests/functions/module_text_test.ts +667 -0
  163. package/tests/helpers/coordinates_test.ts +25 -0
  164. package/tests/helpers/misc_test.ts +95 -0
  165. package/tests/helpers/numbers_test.ts +196 -0
  166. package/tests/helpers/zones_test.ts +97 -0
  167. package/tests/helpers.ts +384 -0
  168. package/tests/menu_items_registry_test.ts +540 -0
  169. package/tests/model/plugins/__snapshots__/chart_test.ts.snap +90 -0
  170. package/tests/model/plugins/chart_test.ts +562 -0
  171. package/tests/model_test.ts +82 -0
  172. package/tests/plugins/__snapshots__/conditional_formatting_test.ts.snap +131 -0
  173. package/tests/plugins/__snapshots__/renderer_test.ts.snap +371 -0
  174. package/tests/plugins/autofill_test.ts +457 -0
  175. package/tests/plugins/borders_test.ts +295 -0
  176. package/tests/plugins/clipboard_test.ts +1180 -0
  177. package/tests/plugins/conditional_formatting_test.ts +1253 -0
  178. package/tests/plugins/core_test.ts +614 -0
  179. package/tests/plugins/edition_test.ts +100 -0
  180. package/tests/plugins/evaluation_async_test.ts +332 -0
  181. package/tests/plugins/evaluation_dates_test.ts +79 -0
  182. package/tests/plugins/evaluation_test.ts +901 -0
  183. package/tests/plugins/figures_test.ts +327 -0
  184. package/tests/plugins/formatting_test.ts +391 -0
  185. package/tests/plugins/grid_manipulation_test.ts +1366 -0
  186. package/tests/plugins/highlight_test.ts +413 -0
  187. package/tests/plugins/history_test.ts +142 -0
  188. package/tests/plugins/import_export_test.ts +276 -0
  189. package/tests/plugins/merges_test.ts +490 -0
  190. package/tests/plugins/navigation_test.ts +181 -0
  191. package/tests/plugins/plugins/evaluation_test.ts +111 -0
  192. package/tests/plugins/renderer_test.ts +598 -0
  193. package/tests/plugins/resizing_test.ts +152 -0
  194. package/tests/plugins/selection_input_test.ts +409 -0
  195. package/tests/plugins/selection_test.ts +442 -0
  196. package/tests/plugins/sheets_test.ts +643 -0
  197. package/tests/plugins/style_test.ts +90 -0
  198. package/tsconfig.json +22 -0
@@ -0,0 +1,117 @@
1
+ /**
2
+ * This regexp is supposed to be as close as possible as the numberRegexp, but
3
+ * its purpose is to be used by the tokenizer.
4
+ *
5
+ * - it tolerates extra characters at the end. This is useful because the tokenizer
6
+ * only needs to find the number at the start of a string
7
+ * - it does not accept "," as thousand separator, because when we tokenize a
8
+ * formula, commas are used to separate arguments
9
+ */
10
+ export const formulaNumberRegexp = /^-?\d+(\.?\d*(e\d+)?)?(\s*%)?|^-?\.\d+(\s*%)?/;
11
+
12
+ export const numberRegexp = /^-?\d+(,\d+)*(\.?\d*(e\d+)?)?(\s*%)?$|^-?\.\d+(\s*%)?$/;
13
+
14
+ /**
15
+ * Return true if the argument is a "number string".
16
+ *
17
+ * Note that "" (empty string) does not count as a number string
18
+ */
19
+ export function isNumber(value: string): boolean {
20
+ // TO DO: add regexp for DATE string format (ex match: "28 02 2020")
21
+ return numberRegexp.test(value.trim());
22
+ }
23
+
24
+ const commaRegexp = /,/g;
25
+ /**
26
+ * Convert a string into a number. It assumes that the string actually represents
27
+ * a number (as determined by the isNumber function)
28
+ *
29
+ * Note that it accepts "" (empty string), even though it does not count as a
30
+ * number from the point of view of the isNumber function.
31
+ */
32
+ export function parseNumber(str: string): number {
33
+ let n = Number(str.replace(commaRegexp, ""));
34
+ if (isNaN(n) && str.includes("%")) {
35
+ n = Number(str.split("%")[0]);
36
+ if (!isNaN(n)) {
37
+ return n / 100;
38
+ }
39
+ }
40
+ return n;
41
+ }
42
+
43
+ const decimalStandardRepresentation = new Intl.NumberFormat("en-US", {
44
+ useGrouping: false,
45
+ maximumFractionDigits: 10,
46
+ });
47
+
48
+ export function formatStandardNumber(n: number): string {
49
+ if (Number.isInteger(n)) {
50
+ return n.toString();
51
+ }
52
+ return decimalStandardRepresentation.format(n);
53
+ }
54
+
55
+ // this is a cache than can contains decimal representation formats
56
+ // from 0 (minimum) to 20 (maximum) digits after the decimal point
57
+ let decimalRepresentations: Intl.NumberFormat[] = [];
58
+
59
+ export const maximumDecimalPlaces = 20;
60
+
61
+ export function formatDecimal(n: number, decimals: number, sep: string = ""): string {
62
+ if (n < 0) {
63
+ return "-" + formatDecimal(-n, decimals);
64
+ }
65
+ const maxDecimals = decimals >= maximumDecimalPlaces ? maximumDecimalPlaces : decimals;
66
+
67
+ let formatter = decimalRepresentations[maxDecimals];
68
+ if (!formatter) {
69
+ formatter = new Intl.NumberFormat("en-US", {
70
+ minimumFractionDigits: maxDecimals,
71
+ maximumFractionDigits: maxDecimals,
72
+ useGrouping: false,
73
+ });
74
+ decimalRepresentations[maxDecimals] = formatter;
75
+ }
76
+ let result = formatter.format(n);
77
+ if (sep) {
78
+ let p: number = result.indexOf(".")!;
79
+ result = result.replace(/\d(?=(?:\d{3})+(?:\.|$))/g, (m, i) =>
80
+ p < 0 || i < p ? `${m}${sep}` : m
81
+ );
82
+ }
83
+ return result;
84
+ }
85
+
86
+ export function formatPercent(n: number): string {
87
+ return formatDecimal(100 * n, 2) + "%";
88
+ }
89
+
90
+ export function formatNumber(value: any, format: string): string {
91
+ const parts = format.split(";");
92
+ const l = parts.length;
93
+ if (value < 0) {
94
+ if (l > 1) {
95
+ return _formatValue(-value, parts[1]);
96
+ } else {
97
+ return "-" + _formatValue(-value, parts[0]);
98
+ }
99
+ }
100
+ const index = l === 3 && value === 0 ? 2 : 0;
101
+ return _formatValue(value, parts[index]);
102
+ }
103
+
104
+ function _formatValue(value: any, format: string): string {
105
+ const parts = format.split(".");
106
+ const decimals = parts.length === 1 ? 0 : parts[1].match(/0/g)!.length;
107
+ const separator = parts[0].includes(",") ? "," : "";
108
+ const isPercent = format.includes("%");
109
+ if (isPercent) {
110
+ value = value * 100;
111
+ }
112
+ const rawNumber = formatDecimal(value, decimals, separator);
113
+ if (isPercent) {
114
+ return rawNumber + "%";
115
+ }
116
+ return rawNumber;
117
+ }
@@ -0,0 +1,19 @@
1
+ /*
2
+ * https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
3
+ * */
4
+ export function uuidv4(): string {
5
+ //@ts-ignore
6
+ if (window.crypto && window.crypto.getRandomValues) {
7
+ //@ts-ignore
8
+ return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
9
+ (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
10
+ );
11
+ } else {
12
+ // mainly for jest and other browsers that do not have the crypto functionality
13
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
14
+ var r = (Math.random() * 16) | 0,
15
+ v = c == "x" ? r : (r & 0x3) | 0x8;
16
+ return v.toString(16);
17
+ });
18
+ }
19
+ }
@@ -0,0 +1,263 @@
1
+ import { Cell, Sheet, Zone } from "../types";
2
+ import { toCartesian, toXC } from "./coordinates";
3
+
4
+ /**
5
+ * Convert from a cartesian reference to a Zone
6
+ *
7
+ * Examples:
8
+ * "A1" ==> Top 0, Bottom 0, Left: 0, Right: 0
9
+ * "B1:B3" ==> Top 0, Bottom 3, Left: 1, Right: 1
10
+ * "Sheet1!A1" ==> Top 0, Bottom 0, Left: 0, Right: 0
11
+ * "Sheet1!B1:B3" ==> Top 0, Bottom 3, Left: 1, Right: 1
12
+ *
13
+ */
14
+ export function toZone(xc: string): Zone {
15
+ xc = xc.split("!").pop()!;
16
+ const ranges = xc.replace("$", "").split(":");
17
+ let top: number, bottom: number, left: number, right: number;
18
+
19
+ let c = toCartesian(ranges[0].trim());
20
+ left = right = c[0];
21
+ top = bottom = c[1];
22
+ if (ranges.length === 2) {
23
+ let d = toCartesian(ranges[1].trim());
24
+ right = d[0];
25
+ bottom = d[1];
26
+ if (right < left) {
27
+ [right, left] = [left, right];
28
+ }
29
+ if (bottom < top) {
30
+ [bottom, top] = [top, bottom];
31
+ }
32
+ }
33
+
34
+ return { top, bottom, left, right };
35
+ }
36
+
37
+ /**
38
+ * Convert from zone to a cartesian reference
39
+ *
40
+ */
41
+ export function zoneToXc(zone: Zone): string {
42
+ const { top, bottom, left, right } = zone;
43
+ const isOneCell = top === bottom && left === right;
44
+ return isOneCell ? toXC(left, top) : `${toXC(left, top)}:${toXC(right, bottom)}`;
45
+ }
46
+
47
+ /**
48
+ * Compute the union of two zones. It is the smallest zone which contains the
49
+ * two arguments.
50
+ */
51
+ export function union(z1: Zone, z2: Zone): Zone {
52
+ return {
53
+ top: Math.min(z1.top, z2.top),
54
+ left: Math.min(z1.left, z2.left),
55
+ bottom: Math.max(z1.bottom, z2.bottom),
56
+ right: Math.max(z1.right, z2.right),
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Two zones are equal if they represent the same area, so we clearly cannot use
62
+ * reference equality.
63
+ */
64
+ export function isEqual(z1: Zone, z2: Zone): boolean {
65
+ return (
66
+ z1.left === z2.left && z1.right === z2.right && z1.top === z2.top && z1.bottom === z2.bottom
67
+ );
68
+ }
69
+
70
+ /**
71
+ * Return true if two zones overlap, false otherwise.
72
+ */
73
+ export function overlap(z1: Zone, z2: Zone): boolean {
74
+ if (z1.bottom < z2.top || z2.bottom < z1.top) {
75
+ return false;
76
+ }
77
+ if (z1.right < z2.left || z2.right < z1.left) {
78
+ return false;
79
+ }
80
+ return true;
81
+ }
82
+
83
+ export function isInside(col: number, row: number, zone: Zone): boolean {
84
+ const { left, right, top, bottom } = zone;
85
+ return col >= left && col <= right && row >= top && row <= bottom;
86
+ }
87
+
88
+ /**
89
+ * Recompute the ranges of the zone to contain all the cells in zones, without the cells in toRemoveZones
90
+ * Also regroup zones together to shorten the string
91
+ * (A1, A2, B1, B2, [C1:C2], C3 => [A1:B2],[C1:C3])
92
+ * To do so, the cells are separated and remerged in zones by columns, and then
93
+ * if possible zones in adjacent columns are merged together.
94
+ */
95
+ export function recomputeZones(zones: string[], toRemoveZones: string[]): string[] {
96
+ const zonesPerColumn: {
97
+ [col: string]: { top: number; bottom: number; remove: boolean }[];
98
+ } = {};
99
+ //separate the existing zones per column
100
+ for (let z of zones) {
101
+ const zone = toZone(z);
102
+ for (let col = zone.left; col <= zone.right; col++) {
103
+ if (zonesPerColumn[col] === undefined) {
104
+ zonesPerColumn[col] = [];
105
+ }
106
+ zonesPerColumn[col].push({
107
+ top: zone.top,
108
+ bottom: zone.bottom,
109
+ remove: false,
110
+ });
111
+ }
112
+ }
113
+
114
+ //separate the to deleted zones per column
115
+ for (let z of toRemoveZones) {
116
+ const zone = toZone(z);
117
+ for (let col = zone.left; col <= zone.right; col++) {
118
+ if (zonesPerColumn[col] === undefined) {
119
+ zonesPerColumn[col] = [];
120
+ }
121
+ zonesPerColumn[col].push({
122
+ top: zone.top,
123
+ bottom: zone.bottom,
124
+ remove: true,
125
+ });
126
+ }
127
+ }
128
+ const OptimizedZonePerColumn: {
129
+ col: number;
130
+ ranges: { top: number; bottom: number }[];
131
+ }[] = [];
132
+
133
+ //regroup zones per column
134
+ for (let [col, zones] of Object.entries(zonesPerColumn)) {
135
+ OptimizedZonePerColumn.push({
136
+ col: parseInt(col),
137
+ ranges: optimiseColumn(zones),
138
+ });
139
+ }
140
+ //merge zones that spread over multiple columns that can be merged
141
+ const result = mergeColumns(OptimizedZonePerColumn);
142
+ return result.map(zoneToXc);
143
+ }
144
+
145
+ /**
146
+ * Recompute the ranges of a column, without the remove cells.
147
+ * takes as input a array of {top, bottom, remove} where top and bottom
148
+ * are the start and end of ranges in the column and remove expresses if the
149
+ * cell should be kept or not.
150
+ */
151
+ function optimiseColumn(
152
+ zones: { top: number; bottom: number; remove: boolean }[]
153
+ ): { top: number; bottom: number }[] {
154
+ const toKeep: Set<number> = new Set();
155
+ const toRemove: Set<number> = new Set();
156
+
157
+ for (let zone of zones) {
158
+ for (let x = zone.top; x <= zone.bottom; x++) {
159
+ zone.remove ? toRemove.add(x) : toKeep.add(x);
160
+ }
161
+ }
162
+ const finalElements: number[] = [...toKeep]
163
+ .filter((x) => !toRemove.has(x))
164
+ .sort((a, b) => {
165
+ return a - b;
166
+ });
167
+ const newZones: { top: number; bottom: number }[] = [];
168
+ let currentZone: { top: number; bottom: number } | undefined;
169
+ for (let x of finalElements) {
170
+ if (!currentZone) {
171
+ currentZone = { top: x, bottom: x };
172
+ } else if (x === currentZone.bottom + 1) {
173
+ currentZone.bottom = x;
174
+ } else {
175
+ newZones.push({ top: currentZone.top, bottom: currentZone.bottom });
176
+ currentZone = { top: x, bottom: x };
177
+ }
178
+ }
179
+ if (currentZone) {
180
+ newZones.push({ top: currentZone.top, bottom: currentZone.bottom });
181
+ }
182
+ return newZones;
183
+ }
184
+
185
+ /**
186
+ * Verify if ranges in two adjacent columns can be merged in one in one range,
187
+ * and if they can, merge them in the same range.
188
+ */
189
+ function mergeColumns(
190
+ zonePerCol: {
191
+ col: number;
192
+ ranges: { top: number; bottom: number }[];
193
+ }[]
194
+ ) {
195
+ const orderedZones = zonePerCol.sort((a, b) => {
196
+ return a.col - b.col;
197
+ });
198
+ const finalZones: { top: number; left: number; right: number; bottom: number }[] = [];
199
+ let inProgressZones: { top: number; bottom: number; startCol: number }[] = [];
200
+ let currentCol = 0;
201
+ for (let index = 0; index <= orderedZones.length - 1; index++) {
202
+ let newInProgress: { top: number; bottom: number; startCol: number }[] = [];
203
+ if (currentCol + 1 === orderedZones[index].col) {
204
+ for (let z1 of orderedZones[index].ranges) {
205
+ let merged = false;
206
+ for (let z2 of inProgressZones) {
207
+ //extend existing zone with the adjacent col
208
+ if (z1.top == z2.top && z1.bottom == z2.bottom) {
209
+ newInProgress.push(z2);
210
+ merged = true;
211
+ }
212
+ }
213
+ // create new zone as it could not be merged with a previous one
214
+ if (!merged) {
215
+ newInProgress.push({ top: z1.top, bottom: z1.bottom, startCol: orderedZones[index].col });
216
+ }
217
+ }
218
+ } else {
219
+ // create new zone as it was not adjacent to the previous zones
220
+ newInProgress = orderedZones[index].ranges.map((zone) => {
221
+ return {
222
+ top: zone.top,
223
+ bottom: zone.bottom,
224
+ startCol: orderedZones[index].col,
225
+ };
226
+ });
227
+ }
228
+
229
+ //All the zones from inProgressZones that are not transferred in newInprogress
230
+ //are zones that were not extended and are therefore final.
231
+ const difference = inProgressZones.filter((x) => !newInProgress.includes(x));
232
+ for (let x of difference) {
233
+ finalZones.push({ top: x.top, bottom: x.bottom, left: x.startCol, right: currentCol });
234
+ }
235
+ currentCol = orderedZones[index].col;
236
+ inProgressZones = newInProgress;
237
+ }
238
+ //after the last iteration, the unfinished zones need to be finalized to.
239
+ for (let x of inProgressZones) {
240
+ finalZones.push({ top: x.top, bottom: x.bottom, left: x.startCol, right: currentCol });
241
+ }
242
+
243
+ return finalZones;
244
+ }
245
+
246
+ export function mapCellsInZone<T, U>(
247
+ zone: Zone,
248
+ sheet: Sheet,
249
+ callback: (cell: Cell) => T,
250
+ emptyCellValue: U = undefined as unknown as U
251
+ ): (T | U)[][] {
252
+ const { top, bottom, left, right } = zone;
253
+ const result: any[] = new Array(right - left + 1);
254
+ for (let c = left; c <= right; c++) {
255
+ let col: any[] = new Array(bottom - top + 1);
256
+ result[c - left] = col;
257
+ for (let r = top; r <= bottom; r++) {
258
+ let cell = sheet.rows[r].cells[c];
259
+ col[r - top] = cell ? callback(cell) : emptyCellValue;
260
+ }
261
+ }
262
+ return result;
263
+ }
package/src/history.ts ADDED
@@ -0,0 +1,186 @@
1
+ import {
2
+ CancelledReason,
3
+ Cell,
4
+ Command,
5
+ CommandHandler,
6
+ CommandResult,
7
+ Sheet,
8
+ Workbook,
9
+ } from "./types/index";
10
+
11
+ /**
12
+ * History Management System
13
+ *
14
+ * This file contains the code necessary to make the undo/redo feature work
15
+ * as expected.
16
+ */
17
+
18
+ interface HistoryChange {
19
+ root: any;
20
+ path: (string | number)[];
21
+ before: any;
22
+ after: any;
23
+ }
24
+
25
+ type Step = HistoryChange[];
26
+
27
+ /**
28
+ * Max Number of history steps kept in memory
29
+ */
30
+ export const MAX_HISTORY_STEPS = 99;
31
+
32
+ export interface WorkbookHistory {
33
+ updateState(path: (string | number)[], val: any): void;
34
+ updateLocalState(path: (string | number)[], val: any): void;
35
+ updateCell<T extends keyof Cell>(cell: Cell, key: T, value: Cell[T]): void;
36
+ updateSheet(sheet: Sheet, path: (string | number)[], value: any): void;
37
+ }
38
+
39
+ type WorkbookHistoryNonLocal = Omit<WorkbookHistory, "updateLocalState">;
40
+
41
+ export class WHistory implements WorkbookHistoryNonLocal, CommandHandler {
42
+ private workbook: Workbook;
43
+ private current: Step | null = null;
44
+ private undoStack: Step[] = [];
45
+ private redoStack: Step[] = [];
46
+
47
+ constructor(workbook: Workbook) {
48
+ this.workbook = workbook;
49
+ }
50
+
51
+ // getters
52
+ canUndo(): boolean {
53
+ return this.undoStack.length > 0;
54
+ }
55
+
56
+ canRedo(): boolean {
57
+ return this.redoStack.length > 0;
58
+ }
59
+
60
+ allowDispatch(cmd: Command): CommandResult {
61
+ switch (cmd.type) {
62
+ case "UNDO":
63
+ return this.canUndo()
64
+ ? { status: "SUCCESS" }
65
+ : { status: "CANCELLED", reason: CancelledReason.EmptyUndoStack };
66
+ case "REDO":
67
+ return this.canRedo()
68
+ ? { status: "SUCCESS" }
69
+ : { status: "CANCELLED", reason: CancelledReason.EmptyRedoStack };
70
+ }
71
+ return { status: "SUCCESS" };
72
+ }
73
+
74
+ beforeHandle(cmd: Command) {
75
+ if (!this.current && cmd.type !== "REDO" && cmd.type !== "UNDO") {
76
+ this.current = [];
77
+ }
78
+ }
79
+
80
+ handle(cmd: Command) {
81
+ switch (cmd.type) {
82
+ case "UNDO":
83
+ this.undo();
84
+ break;
85
+ case "REDO":
86
+ this.redo();
87
+ break;
88
+ }
89
+ }
90
+
91
+ finalize() {
92
+ if (this.current && this.current.length) {
93
+ if (!this.isActiveSheet()) {
94
+ // We do not want to save the ACTIVATE_SHEET command if triggered
95
+ // standalone
96
+ this.undoStack.push(this.current);
97
+ }
98
+ this.redoStack = [];
99
+ this.current = null;
100
+ if (this.undoStack.length > MAX_HISTORY_STEPS) {
101
+ this.undoStack.shift();
102
+ }
103
+ }
104
+ }
105
+
106
+ isActiveSheet() {
107
+ return (
108
+ this.current &&
109
+ this.current.length === 1 &&
110
+ this.current[0].path.length === 1 &&
111
+ this.current[0].path[0] === "activeSheet"
112
+ );
113
+ }
114
+
115
+ undo() {
116
+ const step = this.undoStack.pop();
117
+ if (!step) {
118
+ return;
119
+ }
120
+ this.redoStack.push(step);
121
+ for (let i = step.length - 1; i >= 0; i--) {
122
+ let change = step[i];
123
+ this.applyChange(change, "before");
124
+ }
125
+ }
126
+
127
+ redo() {
128
+ const step = this.redoStack.pop();
129
+ if (!step) {
130
+ return;
131
+ }
132
+ this.undoStack.push(step);
133
+ for (let change of step) {
134
+ this.applyChange(change, "after");
135
+ }
136
+ }
137
+
138
+ private applyChange(change: HistoryChange, target: "before" | "after") {
139
+ let val = change.root as any;
140
+ let key = change.path[change.path.length - 1];
141
+ for (let p of change.path.slice(0, -1)) {
142
+ val = val[p];
143
+ }
144
+ if (change[target] === undefined) {
145
+ delete val[key];
146
+ } else {
147
+ val[key] = change[target];
148
+ }
149
+ }
150
+
151
+ updateStateFromRoot(root: any, path: (string | number)[], val: any) {
152
+ let value = root as any;
153
+ let key = path[path.length - 1];
154
+ for (let p of path.slice(0, -1)) {
155
+ value = value[p];
156
+ }
157
+ if (value[key] === val) {
158
+ return;
159
+ }
160
+ if (this.current) {
161
+ this.current.push({
162
+ root,
163
+ path,
164
+ before: value[key],
165
+ after: val,
166
+ });
167
+ }
168
+ if (val === undefined) {
169
+ delete value[key];
170
+ } else {
171
+ value[key] = val;
172
+ }
173
+ }
174
+
175
+ updateState(path: (string | number)[], val: any): void {
176
+ this.updateStateFromRoot(this.workbook, path, val);
177
+ }
178
+
179
+ updateCell<T extends keyof Cell>(cell: Cell, key: T, value: Cell[T]): void {
180
+ this.updateStateFromRoot(cell, [key], value);
181
+ }
182
+
183
+ updateSheet(sheet: Sheet, path: (string | number)[], value: any): void {
184
+ this.updateStateFromRoot(sheet, path, value);
185
+ }
186
+ }
package/src/index.ts ADDED
@@ -0,0 +1,84 @@
1
+ import {
2
+ BOTTOMBAR_HEIGHT,
3
+ DEFAULT_CELL_HEIGHT,
4
+ DEFAULT_CELL_WIDTH,
5
+ HEADER_HEIGHT,
6
+ HEADER_WIDTH,
7
+ MIN_COL_WIDTH,
8
+ MIN_ROW_HEIGHT,
9
+ SCROLLBAR_WIDTH,
10
+ TOPBAR_HEIGHT,
11
+ } from "./constants";
12
+ import { toBoolean, toNumber, toString } from "./functions/helpers";
13
+ import { args, functionRegistry } from "./functions/index";
14
+ import { formatDecimal, numberToLetters, toCartesian, toXC, toZone, uuidv4 } from "./helpers/index";
15
+ import { pluginRegistry } from "./plugins/index";
16
+ import {
17
+ autofillModifiersRegistry,
18
+ autofillRulesRegistry,
19
+ cellMenuRegistry,
20
+ colMenuRegistry,
21
+ createFullMenuItem,
22
+ rowMenuRegistry,
23
+ sheetMenuRegistry,
24
+ sidePanelRegistry,
25
+ topbarComponentRegistry,
26
+ topbarMenuRegistry,
27
+ } from "./registries/index";
28
+
29
+ /**
30
+ * We export here all entities that needs to be accessed publicly by Odoo.
31
+ *
32
+ * Note that the __info__ key is actually completed by the build process (see
33
+ * the rollup.config.js file)
34
+ */
35
+
36
+ export const __info__ = {};
37
+ export { BasePlugin } from "./base_plugin";
38
+ export { Spreadsheet } from "./components/index";
39
+ export { functionCache } from "./formulas/compiler";
40
+ export { normalize } from "./formulas/index";
41
+ export { astToFormula, parse } from "./formulas/parser";
42
+ export { DEBUG as __DEBUG__ } from "./helpers/index";
43
+ export { Model } from "./model";
44
+ export { setTranslationMethod } from "./translation";
45
+
46
+ export const SPREADSHEET_DIMENSIONS = {
47
+ MIN_ROW_HEIGHT,
48
+ MIN_COL_WIDTH,
49
+ HEADER_HEIGHT,
50
+ HEADER_WIDTH,
51
+ TOPBAR_HEIGHT,
52
+ BOTTOMBAR_HEIGHT,
53
+ DEFAULT_CELL_WIDTH,
54
+ DEFAULT_CELL_HEIGHT,
55
+ SCROLLBAR_WIDTH,
56
+ };
57
+
58
+ export const registries = {
59
+ autofillModifiersRegistry,
60
+ autofillRulesRegistry,
61
+ cellMenuRegistry,
62
+ colMenuRegistry,
63
+ functionRegistry,
64
+ pluginRegistry,
65
+ rowMenuRegistry,
66
+ sidePanelRegistry,
67
+ sheetMenuRegistry,
68
+ topbarMenuRegistry,
69
+ topbarComponentRegistry,
70
+ };
71
+
72
+ export const helpers = {
73
+ args,
74
+ toBoolean,
75
+ toNumber,
76
+ toString,
77
+ toXC,
78
+ toZone,
79
+ toCartesian,
80
+ numberToLetters,
81
+ createFullMenuItem,
82
+ uuidv4,
83
+ formatDecimal,
84
+ };