@odoo/o-spreadsheet
Version:
A spreadsheet component
1,581 lines (1,565 loc) • 3.44 MB
JavaScript
/**
* This file is generated by o-spreadsheet build tools. Do not edit it.
* @see https://github.com/odoo/o-spreadsheet
* @version 19.0.4
* @date 2025-09-23T12:37:28.362Z
* @hash 87b774d
*/
'use strict';
var owl = require('@odoo/owl');
function createActions(menuItems) {
return menuItems.map(createAction).sort((a, b) => a.sequence - b.sequence);
}
let nextItemId = 1;
function createAction(item) {
const name = item.name;
const children = item.children;
const description = item.description;
const icon = item.icon;
const secondaryIcon = item.secondaryIcon;
const itemId = item.id || nextItemId++;
const isEnabled = item.isEnabled ? item.isEnabled : () => true;
return {
id: itemId.toString(),
name: typeof name === "function" ? name : () => name,
isVisible: item.isVisible ? item.isVisible : () => true,
isEnabled: isEnabled,
isActive: item.isActive,
execute: item.execute
? (env, isMiddleClick) => {
if (isEnabled(env)) {
return item.execute(env, isMiddleClick);
}
return undefined;
}
: undefined,
children: children
? (env) => {
return children
.map((child) => (typeof child === "function" ? child(env) : child))
.flat()
.map(createAction);
}
: () => [],
isReadonlyAllowed: item.isReadonlyAllowed || false,
separator: item.separator || false,
icon: typeof icon === "function" ? icon : () => icon || "",
iconColor: item.iconColor,
secondaryIcon: typeof secondaryIcon === "function" ? secondaryIcon : () => secondaryIcon || "",
description: typeof description === "function" ? description : () => description || "",
textColor: item.textColor,
sequence: item.sequence || 0,
onStartHover: item.onStartHover,
onStopHover: item.onStopHover,
};
}
/**
* Registry
*
* The Registry class is basically just a mapping from a string key to an object.
* It is really not much more than an object. It is however useful for the
* following reasons:
*
* 1. it let us react and execute code when someone add something to the registry
* (for example, the FunctionRegistry subclass this for this purpose)
* 2. it throws an error when the get operation fails
* 3. it provides a chained API to add items to the registry.
*/
class Registry {
content = {};
/**
* Add an item to the registry, you can only add if there is no item
* already present in the registery with the given key
*
* Note that this also returns the registry, so another add method call can
* be chained
*/
add(key, value) {
if (key in this.content) {
throw new Error(`${key} is already present in this registry!`);
}
return this.replace(key, value);
}
/**
* Replace (or add) an item to the registry
*
* Note that this also returns the registry, so another add method call can
* be chained
*/
replace(key, value) {
this.content[key] = value;
return this;
}
/**
* Get an item from the registry
*/
get(key) {
/**
* Note: key in {} is ~12 times slower than {}[key].
* So, we check the absence of key only when the direct access returns
* a falsy value. It's done to ensure that the registry can contains falsy values
*/
const content = this.content[key];
if (!content) {
if (!(key in this.content)) {
throw new Error(`Cannot find ${key} in this registry!`);
}
}
return content;
}
/**
* Check if the key is already in the registry
*/
contains(key) {
return key in this.content;
}
/**
* Get a list of all elements in the registry
*/
getAll() {
return Object.values(this.content);
}
/**
* Get a list of all keys in the registry
*/
getKeys() {
return Object.keys(this.content);
}
/**
* Remove an item from the registry
*/
remove(key) {
delete this.content[key];
}
}
var CellValueType;
(function (CellValueType) {
CellValueType["boolean"] = "boolean";
CellValueType["number"] = "number";
CellValueType["text"] = "text";
CellValueType["empty"] = "empty";
CellValueType["error"] = "error";
})(CellValueType || (CellValueType = {}));
var ClipboardMIMEType;
(function (ClipboardMIMEType) {
ClipboardMIMEType["PlainText"] = "text/plain";
ClipboardMIMEType["Html"] = "text/html";
ClipboardMIMEType["Image"] = "image";
})(ClipboardMIMEType || (ClipboardMIMEType = {}));
function isSheetDependent(cmd) {
return "sheetId" in cmd;
}
function isHeadersDependant(cmd) {
return "dimension" in cmd && "sheetId" in cmd && "elements" in cmd;
}
function isTargetDependent(cmd) {
return "target" in cmd && "sheetId" in cmd;
}
function isRangeDependant(cmd) {
return "ranges" in cmd;
}
function isPositionDependent(cmd) {
return "col" in cmd && "row" in cmd && "sheetId" in cmd;
}
function isZoneDependent(cmd) {
return "sheetId" in cmd && "zone" in cmd;
}
const invalidateEvaluationCommands = new Set([
"RENAME_SHEET",
"DELETE_SHEET",
"CREATE_SHEET",
"DUPLICATE_SHEET",
"ADD_COLUMNS_ROWS",
"REMOVE_COLUMNS_ROWS",
"UNDO",
"REDO",
"ADD_MERGE",
"REMOVE_MERGE",
"DUPLICATE_SHEET",
"UPDATE_LOCALE",
"ADD_PIVOT",
"UPDATE_PIVOT",
"INSERT_PIVOT",
"RENAME_PIVOT",
"REMOVE_PIVOT",
"DUPLICATE_PIVOT",
]);
const invalidateChartEvaluationCommands = new Set([
"EVALUATE_CELLS",
"EVALUATE_CHARTS",
"UPDATE_CELL",
"UNHIDE_COLUMNS_ROWS",
"HIDE_COLUMNS_ROWS",
"GROUP_HEADERS",
"UNGROUP_HEADERS",
"FOLD_ALL_HEADER_GROUPS",
"FOLD_HEADER_GROUP",
"FOLD_HEADER_GROUPS_IN_ZONE",
"UNFOLD_ALL_HEADER_GROUPS",
"UNFOLD_HEADER_GROUP",
"UNFOLD_HEADER_GROUPS_IN_ZONE",
"UPDATE_TABLE",
"UPDATE_FILTER",
"UNDO",
"REDO",
]);
const invalidateDependenciesCommands = new Set(["MOVE_RANGES"]);
const invalidateCFEvaluationCommands = new Set([
"EVALUATE_CELLS",
"ADD_CONDITIONAL_FORMAT",
"REMOVE_CONDITIONAL_FORMAT",
"CHANGE_CONDITIONAL_FORMAT_PRIORITY",
]);
const invalidateBordersCommands = new Set([
"AUTOFILL_CELL",
"SET_BORDER",
"SET_ZONE_BORDERS",
"SET_BORDERS_ON_TARGET",
]);
const invalidSubtotalFormulasCommands = new Set([
"UNHIDE_COLUMNS_ROWS",
"HIDE_COLUMNS_ROWS",
"GROUP_HEADERS",
"UNGROUP_HEADERS",
"FOLD_ALL_HEADER_GROUPS",
"FOLD_HEADER_GROUP",
"FOLD_HEADER_GROUPS_IN_ZONE",
"UNFOLD_ALL_HEADER_GROUPS",
"UNFOLD_HEADER_GROUP",
"UNFOLD_HEADER_GROUPS_IN_ZONE",
"UPDATE_TABLE",
"UPDATE_FILTER",
]);
const readonlyAllowedCommands = new Set([
"START",
"ACTIVATE_SHEET",
"COPY",
"RESIZE_SHEETVIEW",
"SET_VIEWPORT_OFFSET",
"EVALUATE_CELLS",
"EVALUATE_CHARTS",
"SET_FORMULA_VISIBILITY",
"UPDATE_FILTER",
"UPDATE_CHART",
"UPDATE_CAROUSEL_ACTIVE_ITEM",
"UPDATE_PIVOT",
]);
const coreTypes = new Set([
/** CELLS */
"UPDATE_CELL",
"UPDATE_CELL_POSITION",
"CLEAR_CELL",
"CLEAR_CELLS",
"DELETE_CONTENT",
/** GRID SHAPE */
"ADD_COLUMNS_ROWS",
"REMOVE_COLUMNS_ROWS",
"RESIZE_COLUMNS_ROWS",
"HIDE_COLUMNS_ROWS",
"UNHIDE_COLUMNS_ROWS",
"SET_GRID_LINES_VISIBILITY",
"UNFREEZE_COLUMNS",
"UNFREEZE_ROWS",
"FREEZE_COLUMNS",
"FREEZE_ROWS",
"UNFREEZE_COLUMNS_ROWS",
/** MERGE */
"ADD_MERGE",
"REMOVE_MERGE",
/** SHEETS MANIPULATION */
"CREATE_SHEET",
"DELETE_SHEET",
"DUPLICATE_SHEET",
"MOVE_SHEET",
"RENAME_SHEET",
"COLOR_SHEET",
"HIDE_SHEET",
"SHOW_SHEET",
/** RANGES MANIPULATION */
"MOVE_RANGES",
/** CONDITIONAL FORMAT */
"ADD_CONDITIONAL_FORMAT",
"REMOVE_CONDITIONAL_FORMAT",
"CHANGE_CONDITIONAL_FORMAT_PRIORITY",
/** FIGURES */
"CREATE_FIGURE",
"DELETE_FIGURE",
"UPDATE_FIGURE",
"CREATE_CAROUSEL",
"UPDATE_CAROUSEL",
/** FORMATTING */
"SET_FORMATTING",
"CLEAR_FORMATTING",
"SET_BORDER",
"SET_ZONE_BORDERS",
"SET_BORDERS_ON_TARGET",
/** CHART */
"CREATE_CHART",
"UPDATE_CHART",
"DELETE_CHART",
/** FILTERS */
"CREATE_TABLE",
"REMOVE_TABLE",
"UPDATE_TABLE",
"CREATE_TABLE_STYLE",
"REMOVE_TABLE_STYLE",
/** IMAGE */
"CREATE_IMAGE",
/** HEADER GROUP */
"GROUP_HEADERS",
"UNGROUP_HEADERS",
"UNFOLD_HEADER_GROUP",
"FOLD_HEADER_GROUP",
"FOLD_ALL_HEADER_GROUPS",
"UNFOLD_ALL_HEADER_GROUPS",
"UNFOLD_HEADER_GROUPS_IN_ZONE",
"FOLD_HEADER_GROUPS_IN_ZONE",
/** DATA VALIDATION */
"ADD_DATA_VALIDATION_RULE",
"REMOVE_DATA_VALIDATION_RULE",
/** MISC */
"UPDATE_LOCALE",
/** PIVOT */
"ADD_PIVOT",
"UPDATE_PIVOT",
"INSERT_PIVOT",
"RENAME_PIVOT",
"REMOVE_PIVOT",
"DUPLICATE_PIVOT",
]);
function isCoreCommand(cmd) {
return coreTypes.has(cmd.type);
}
function canExecuteInReadonly(cmd) {
return readonlyAllowedCommands.has(cmd.type);
}
/**
* Holds the result of a command dispatch.
* The command may have been successfully dispatched or cancelled
* for one or more reasons.
*/
class DispatchResult {
reasons;
constructor(results = []) {
if (!Array.isArray(results)) {
results = [results];
}
results = [...new Set(results)];
this.reasons = results.filter((result) => result !== "Success" /* CommandResult.Success */);
}
/**
* Static helper which returns a successful DispatchResult
*/
static get Success() {
return SUCCESS;
}
get isSuccessful() {
return this.reasons.length === 0;
}
/**
* Check if the dispatch has been cancelled because of
* the given reason.
*/
isCancelledBecause(reason) {
return this.reasons.includes(reason);
}
}
const SUCCESS = new DispatchResult();
exports.CommandResult = void 0;
(function (CommandResult) {
CommandResult["Success"] = "Success";
CommandResult["CancelledForUnknownReason"] = "CancelledForUnknownReason";
CommandResult["WillRemoveExistingMerge"] = "WillRemoveExistingMerge";
CommandResult["CannotMoveTableHeader"] = "CannotMoveTableHeader";
CommandResult["MergeIsDestructive"] = "MergeIsDestructive";
CommandResult["CellIsMerged"] = "CellIsMerged";
CommandResult["InvalidTarget"] = "InvalidTarget";
CommandResult["EmptyUndoStack"] = "EmptyUndoStack";
CommandResult["EmptyRedoStack"] = "EmptyRedoStack";
CommandResult["NotEnoughElements"] = "NotEnoughElements";
CommandResult["NotEnoughSheets"] = "NotEnoughSheets";
CommandResult["MissingSheetName"] = "MissingSheetName";
CommandResult["UnchangedSheetName"] = "UnchangedSheetName";
CommandResult["DuplicatedSheetName"] = "DuplicatedSheetName";
CommandResult["DuplicatedSheetId"] = "DuplicatedSheetId";
CommandResult["ForbiddenCharactersInSheetName"] = "ForbiddenCharactersInSheetName";
CommandResult["WrongSheetMove"] = "WrongSheetMove";
CommandResult["WrongSheetPosition"] = "WrongSheetPosition";
CommandResult["InvalidAnchorZone"] = "InvalidAnchorZone";
CommandResult["SelectionOutOfBound"] = "SelectionOutOfBound";
CommandResult["TargetOutOfSheet"] = "TargetOutOfSheet";
CommandResult["WrongCutSelection"] = "WrongCutSelection";
CommandResult["WrongPasteSelection"] = "WrongPasteSelection";
CommandResult["WrongPasteOption"] = "WrongPasteOption";
CommandResult["WrongFigurePasteOption"] = "WrongFigurePasteOption";
CommandResult["EmptyClipboard"] = "EmptyClipboard";
CommandResult["EmptyRange"] = "EmptyRange";
CommandResult["InvalidRange"] = "InvalidRange";
CommandResult["InvalidZones"] = "InvalidZones";
CommandResult["InvalidSheetId"] = "InvalidSheetId";
CommandResult["InvalidCellId"] = "InvalidCellId";
CommandResult["InvalidFigureId"] = "InvalidFigureId";
CommandResult["InputAlreadyFocused"] = "InputAlreadyFocused";
CommandResult["MaximumRangesReached"] = "MaximumRangesReached";
CommandResult["MinimumRangesReached"] = "MinimumRangesReached";
CommandResult["InvalidChartDefinition"] = "InvalidChartDefinition";
CommandResult["InvalidDataSet"] = "InvalidDataSet";
CommandResult["InvalidLabelRange"] = "InvalidLabelRange";
CommandResult["InvalidScorecardKeyValue"] = "InvalidScorecardKeyValue";
CommandResult["InvalidScorecardBaseline"] = "InvalidScorecardBaseline";
CommandResult["InvalidGaugeDataRange"] = "InvalidGaugeDataRange";
CommandResult["EmptyGaugeRangeMin"] = "EmptyGaugeRangeMin";
CommandResult["GaugeRangeMinNaN"] = "GaugeRangeMinNaN";
CommandResult["EmptyGaugeRangeMax"] = "EmptyGaugeRangeMax";
CommandResult["GaugeRangeMaxNaN"] = "GaugeRangeMaxNaN";
CommandResult["GaugeLowerInflectionPointNaN"] = "GaugeLowerInflectionPointNaN";
CommandResult["GaugeUpperInflectionPointNaN"] = "GaugeUpperInflectionPointNaN";
CommandResult["InvalidAutofillSelection"] = "InvalidAutofillSelection";
CommandResult["MinBiggerThanMax"] = "MinBiggerThanMax";
CommandResult["LowerBiggerThanUpper"] = "LowerBiggerThanUpper";
CommandResult["MidBiggerThanMax"] = "MidBiggerThanMax";
CommandResult["MinBiggerThanMid"] = "MinBiggerThanMid";
CommandResult["FirstArgMissing"] = "FirstArgMissing";
CommandResult["SecondArgMissing"] = "SecondArgMissing";
CommandResult["MinNaN"] = "MinNaN";
CommandResult["MidNaN"] = "MidNaN";
CommandResult["MaxNaN"] = "MaxNaN";
CommandResult["ValueUpperInflectionNaN"] = "ValueUpperInflectionNaN";
CommandResult["ValueLowerInflectionNaN"] = "ValueLowerInflectionNaN";
CommandResult["MinInvalidFormula"] = "MinInvalidFormula";
CommandResult["MidInvalidFormula"] = "MidInvalidFormula";
CommandResult["MaxInvalidFormula"] = "MaxInvalidFormula";
CommandResult["ValueUpperInvalidFormula"] = "ValueUpperInvalidFormula";
CommandResult["ValueLowerInvalidFormula"] = "ValueLowerInvalidFormula";
CommandResult["InvalidSortAnchor"] = "InvalidSortAnchor";
CommandResult["InvalidSortZone"] = "InvalidSortZone";
CommandResult["SortZoneWithArrayFormulas"] = "SortZoneWithArrayFormulas";
CommandResult["WaitingSessionConfirmation"] = "WaitingSessionConfirmation";
CommandResult["MergeOverlap"] = "MergeOverlap";
CommandResult["TooManyHiddenElements"] = "TooManyHiddenElements";
CommandResult["Readonly"] = "Readonly";
CommandResult["InvalidViewportSize"] = "InvalidViewportSize";
CommandResult["InvalidScrollingDirection"] = "InvalidScrollingDirection";
CommandResult["ViewportScrollLimitsReached"] = "ViewportScrollLimitsReached";
CommandResult["FigureDoesNotExist"] = "FigureDoesNotExist";
CommandResult["InvalidConditionalFormatId"] = "InvalidConditionalFormatId";
CommandResult["InvalidCellPopover"] = "InvalidCellPopover";
CommandResult["EmptyTarget"] = "EmptyTarget";
CommandResult["InvalidFreezeQuantity"] = "InvalidFreezeQuantity";
CommandResult["FrozenPaneOverlap"] = "FrozenPaneOverlap";
CommandResult["ValuesNotChanged"] = "ValuesNotChanged";
CommandResult["InvalidFilterZone"] = "InvalidFilterZone";
CommandResult["TableNotFound"] = "TableNotFound";
CommandResult["TableOverlap"] = "TableOverlap";
CommandResult["InvalidTableConfig"] = "InvalidTableConfig";
CommandResult["InvalidTableStyle"] = "InvalidTableStyle";
CommandResult["FilterNotFound"] = "FilterNotFound";
CommandResult["MergeInTable"] = "MergeInTable";
CommandResult["NonContinuousTargets"] = "NonContinuousTargets";
CommandResult["DuplicatedFigureId"] = "DuplicatedFigureId";
CommandResult["InvalidSelectionStep"] = "InvalidSelectionStep";
CommandResult["DuplicatedChartId"] = "DuplicatedChartId";
CommandResult["ChartDoesNotExist"] = "ChartDoesNotExist";
CommandResult["InvalidHeaderIndex"] = "InvalidHeaderIndex";
CommandResult["InvalidQuantity"] = "InvalidQuantity";
CommandResult["MoreThanOneColumnSelected"] = "MoreThanOneColumnSelected";
CommandResult["EmptySplitSeparator"] = "EmptySplitSeparator";
CommandResult["SplitWillOverwriteContent"] = "SplitWillOverwriteContent";
CommandResult["NoSplitSeparatorInSelection"] = "NoSplitSeparatorInSelection";
CommandResult["NoActiveSheet"] = "NoActiveSheet";
CommandResult["InvalidLocale"] = "InvalidLocale";
CommandResult["MoreThanOneRangeSelected"] = "MoreThanOneRangeSelected";
CommandResult["NoColumnsProvided"] = "NoColumnsProvided";
CommandResult["ColumnsNotIncludedInZone"] = "ColumnsNotIncludedInZone";
CommandResult["DuplicatesColumnsSelected"] = "DuplicatesColumnsSelected";
CommandResult["InvalidHeaderGroupStartEnd"] = "InvalidHeaderGroupStartEnd";
CommandResult["HeaderGroupAlreadyExists"] = "HeaderGroupAlreadyExists";
CommandResult["UnknownHeaderGroup"] = "UnknownHeaderGroup";
CommandResult["UnknownDataValidationRule"] = "UnknownDataValidationRule";
CommandResult["UnknownDataValidationCriterionType"] = "UnknownDataValidationCriterionType";
CommandResult["InvalidDataValidationCriterionValue"] = "InvalidDataValidationCriterionValue";
CommandResult["InvalidNumberOfCriterionValues"] = "InvalidNumberOfCriterionValues";
CommandResult["InvalidCopyPasteSelection"] = "InvalidCopyPasteSelection";
CommandResult["NoChanges"] = "NoChanges";
CommandResult["InvalidInputId"] = "InvalidInputId";
CommandResult["SheetIsHidden"] = "SheetIsHidden";
CommandResult["InvalidTableResize"] = "InvalidTableResize";
CommandResult["PivotIdNotFound"] = "PivotIdNotFound";
CommandResult["PivotInError"] = "PivotInError";
CommandResult["EmptyName"] = "EmptyName";
CommandResult["ValueCellIsInvalidFormula"] = "ValueCellIsInvalidFormula";
CommandResult["InvalidDefinition"] = "InvalidDefinition";
CommandResult["InvalidColor"] = "InvalidColor";
CommandResult["InvalidPivotDataSet"] = "InvalidPivotDataSet";
CommandResult["InvalidPivotCustomField"] = "InvalidPivotCustomField";
CommandResult["MissingFigureArguments"] = "MissingFigureArguments";
CommandResult["InvalidCarouselItem"] = "InvalidCarouselItem";
})(exports.CommandResult || (exports.CommandResult = {}));
const availableConditionalFormatOperators = new Set([
"containsText",
"notContainsText",
"isGreaterThan",
"isGreaterOrEqualTo",
"isLessThan",
"isLessOrEqualTo",
"isBetween",
"isNotBetween",
"beginsWithText",
"endsWithText",
"isNotEmpty",
"isEmpty",
"isNotEqual",
"isEqual",
"customFormula",
]);
const availableDataValidationOperators = new Set([
"containsText",
"notContainsText",
"isEqualText",
"isEmail",
"isLink",
"dateIs",
"dateIsBefore",
"dateIsOnOrBefore",
"dateIsAfter",
"dateIsOnOrAfter",
"dateIsBetween",
"dateIsNotBetween",
"dateIsValid",
"isEqual",
"isNotEqual",
"isGreaterThan",
"isGreaterOrEqualTo",
"isLessThan",
"isLessOrEqualTo",
"isBetween",
"isNotBetween",
"isBoolean",
"isValueInList",
"isValueInRange",
"customFormula",
]);
const DEFAULT_LOCALES = [
{
name: "English (US)",
code: "en_US",
thousandsSeparator: ",",
decimalSeparator: ".",
weekStart: 7, // Sunday
dateFormat: "m/d/yyyy",
timeFormat: "hh:mm:ss a",
formulaArgSeparator: ",",
},
{
name: "French",
code: "fr_FR",
thousandsSeparator: " ",
decimalSeparator: ",",
weekStart: 1, // Monday
dateFormat: "dd/mm/yyyy",
timeFormat: "hh:mm:ss",
formulaArgSeparator: ";",
},
];
const DEFAULT_LOCALE = DEFAULT_LOCALES[0];
const borderStyles = ["thin", "medium", "thick", "dashed", "dotted"];
function isMatrix(x) {
return Array.isArray(x) && Array.isArray(x[0]);
}
var DIRECTION;
(function (DIRECTION) {
DIRECTION["UP"] = "up";
DIRECTION["DOWN"] = "down";
DIRECTION["LEFT"] = "left";
DIRECTION["RIGHT"] = "right";
})(DIRECTION || (DIRECTION = {}));
const CANVAS_SHIFT = 0.5;
// Colors
const HIGHLIGHT_COLOR = "#017E84";
const BACKGROUND_GRAY_COLOR = "#f5f5f5";
const BACKGROUND_HEADER_COLOR = "#F8F9FA";
const BACKGROUND_HEADER_SELECTED_COLOR = "#E8EAED";
const BACKGROUND_HEADER_ACTIVE_COLOR = "#595959";
const TEXT_HEADER_COLOR = "#666666";
const FIGURE_BORDER_COLOR = "#c9ccd2";
const SELECTION_BORDER_COLOR = "#3266ca";
const HEADER_BORDER_COLOR = "#C0C0C0";
const CELL_BORDER_COLOR = "#E2E3E3";
const BACKGROUND_CHART_COLOR = "#FFFFFF";
const DISABLED_TEXT_COLOR = "#CACACA";
const DEFAULT_COLOR_SCALE_MIDPOINT_COLOR = 0xb6d7a8;
const LINK_COLOR = HIGHLIGHT_COLOR;
const FILTERS_COLOR = "#188038";
const SEPARATOR_COLOR = "#E0E2E4";
const ICONS_COLOR = "#4A4F59";
const HEADER_GROUPING_BACKGROUND_COLOR = "#F5F5F5";
const HEADER_GROUPING_BORDER_COLOR = "#999";
const GRID_BORDER_COLOR = "#E2E3E3";
const FROZEN_PANE_HEADER_BORDER_COLOR = "#BCBCBC";
const FROZEN_PANE_BORDER_COLOR = "#DADFE8";
const COMPOSER_ASSISTANT_COLOR = "#9B359B";
const COLOR_TRANSPARENT = "#00000000";
const TABLE_HOVER_BACKGROUND_COLOR = "#017E8414";
const CHART_WATERFALL_POSITIVE_COLOR = "#4EA7F2";
const CHART_WATERFALL_NEGATIVE_COLOR = "#EA6175";
const CHART_WATERFALL_SUBTOTAL_COLOR = "#AAAAAA";
const GRAY_900 = "#111827";
const GRAY_300 = "#D8DADD";
const GRAY_200 = "#E7E9ED";
const GRAY_100 = "#F9FAFB";
const TEXT_BODY = "#374151";
const TEXT_BODY_MUTED = TEXT_BODY + "C2";
const TEXT_HEADING = "#111827";
const PRIMARY_BUTTON_BG = "#714B67";
const PRIMARY_BUTTON_HOVER_BG = "#624159";
const PRIMARY_BUTTON_ACTIVE_BG = "#f1edf0";
const BUTTON_BG = GRAY_200;
const BUTTON_HOVER_BG = GRAY_300;
const BUTTON_HOVER_TEXT_COLOR = "#111827";
const BUTTON_ACTIVE_BG = "#e6f2f3";
const BUTTON_ACTIVE_TEXT_COLOR = "#111827";
const ACTION_COLOR = HIGHLIGHT_COLOR;
const ACTION_COLOR_HOVER = "#01585c";
const ALERT_WARNING_BG = "#FBEBCC";
const ALERT_WARNING_BORDER = "#F8E2B3";
const ALERT_WARNING_TEXT_COLOR = "#946D23";
const ALERT_DANGER_BG = "#D44C591A";
const ALERT_DANGER_BORDER = "#C34A41";
const ALERT_DANGER_TEXT_COLOR = "#C34A41";
const ALERT_INFO_BG = "#CDEDF1";
const ALERT_INFO_BORDER = "#98DBE2";
const ALERT_INFO_TEXT_COLOR = "#09414A";
const BADGE_SELECTED_COLOR = "#E6F2F3";
const CHART_PADDING = 20;
const CHART_PADDING_BOTTOM = 10;
const CHART_PADDING_TOP = 15;
const CHART_TITLE_FONT_SIZE = 16;
const CHART_AXIS_TITLE_FONT_SIZE = 12;
const MASTER_CHART_HEIGHT = 60;
const SCORECARD_CHART_TITLE_FONT_SIZE = 14;
const PIVOT_TOKEN_COLOR = "#F28C28";
// Color picker defaults as upper case HEX to match `toHex`helper
const COLOR_PICKER_DEFAULTS = [
"#000000",
"#434343",
"#666666",
"#999999",
"#B7B7B7",
"#CCCCCC",
"#D9D9D9",
"#EFEFEF",
"#F3F3F3",
"#FFFFFF",
"#980000",
"#FF0000",
"#FF9900",
"#FFFF00",
"#00FF00",
"#00FFFF",
"#4A86E8",
"#0000FF",
"#9900FF",
"#FF00FF",
"#E6B8AF",
"#F4CCCC",
"#FCE5CD",
"#FFF2CC",
"#D9EAD3",
"#D0E0E3",
"#C9DAF8",
"#CFE2F3",
"#D9D2E9",
"#EAD1DC",
"#DD7E6B",
"#EA9999",
"#F9CB9C",
"#FFE599",
"#B6D7A8",
"#A2C4C9",
"#A4C2F4",
"#9FC5E8",
"#B4A7D6",
"#D5A6BD",
"#CC4125",
"#E06666",
"#F6B26B",
"#FFD966",
"#93C47D",
"#76A5AF",
"#6D9EEB",
"#6FA8DC",
"#8E7CC3",
"#C27BA0",
"#A61C00",
"#CC0000",
"#E69138",
"#F1C232",
"#6AA84F",
"#45818E",
"#3C78D8",
"#3D85C6",
"#674EA7",
"#A64D79",
"#85200C",
"#990000",
"#B45F06",
"#BF9000",
"#38761D",
"#134F5C",
"#1155CC",
"#0B5394",
"#351C75",
"#741B47",
"#5B0F00",
"#660000",
"#783F04",
"#7F6000",
"#274E13",
"#0C343D",
"#1C4587",
"#073763",
"#20124D",
"#4C1130",
];
// Dimensions
const MIN_ROW_HEIGHT = 10;
const MIN_COL_WIDTH = 5;
const HEADER_HEIGHT = 26;
const HEADER_WIDTH = 48;
const DESKTOP_TOPBAR_TOOLBAR_HEIGHT = 34;
const MOBILE_TOPBAR_TOOLBAR_HEIGHT = 44;
const DESKTOP_BOTTOMBAR_HEIGHT = 36;
const MOBILE_BOTTOMBAR_HEIGHT = 44;
const DEFAULT_CELL_WIDTH = 96;
const DEFAULT_CELL_HEIGHT = 23;
const SCROLLBAR_WIDTH = 15;
const AUTOFILL_EDGE_LENGTH = 8;
const ICON_EDGE_LENGTH = 18;
const MIN_CF_ICON_MARGIN = 4;
const MIN_CELL_TEXT_MARGIN = 4;
const CF_ICON_EDGE_LENGTH = 15;
const PADDING_AUTORESIZE_VERTICAL = 3;
const PADDING_AUTORESIZE_HORIZONTAL = MIN_CELL_TEXT_MARGIN;
const GROUP_LAYER_WIDTH = 21;
const GRID_ICON_MARGIN = 2;
const GRID_ICON_EDGE_LENGTH = 17;
const FOOTER_HEIGHT = 2 * DEFAULT_CELL_HEIGHT;
const DATA_VALIDATION_CHIP_MARGIN = 5;
// 768px is a common breakpoint for small screens
// Typically inside Odoo, it is the threshold for switching to mobile view
const MOBILE_WIDTH_BREAKPOINT = 768;
// Menus
const MENU_WIDTH = 250;
const MENU_VERTICAL_PADDING = 6;
const DESKTOP_MENU_ITEM_HEIGHT = 26;
const MOBILE_MENU_ITEM_HEIGHT = 35;
const MENU_ITEM_PADDING_HORIZONTAL = 11;
const MENU_ITEM_PADDING_VERTICAL = 4;
const MENU_SEPARATOR_BORDER_WIDTH = 1;
const MENU_SEPARATOR_PADDING = 5;
// Style
const DEFAULT_STYLE = {
align: "left",
verticalAlign: "bottom",
wrapping: "overflow",
bold: false,
italic: false,
strikethrough: false,
underline: false,
fontSize: 10,
fillColor: "",
textColor: "",
};
const DEFAULT_VERTICAL_ALIGN = DEFAULT_STYLE.verticalAlign;
const DEFAULT_WRAPPING_MODE = DEFAULT_STYLE.wrapping;
// Fonts
const DEFAULT_FONT_WEIGHT = "400";
const DEFAULT_FONT_SIZE = DEFAULT_STYLE.fontSize;
const HEADER_FONT_SIZE = 11;
const DEFAULT_FONT = "'Roboto', arial";
// Borders
const DEFAULT_BORDER_DESC = { style: "thin", color: "#000000" };
// Max Number of history steps kept in memory
const MAX_HISTORY_STEPS = 99;
// Id of the first revision
const DEFAULT_REVISION_ID = "START_REVISION";
// Figure
const DEFAULT_FIGURE_HEIGHT = 335;
const DEFAULT_FIGURE_WIDTH = 536;
const FIGURE_BORDER_WIDTH = 1;
const MIN_FIG_SIZE = 80;
// Chart
const MAX_CHAR_LABEL = 20;
const FIGURE_ID_SPLITTER = "??";
const DEFAULT_GAUGE_LOWER_COLOR = "#EA6175";
const DEFAULT_GAUGE_MIDDLE_COLOR = "#FFD86D";
const DEFAULT_GAUGE_UPPER_COLOR = "#43C5B1";
const DEFAULT_SCORECARD_BASELINE_MODE = "difference";
const DEFAULT_SCORECARD_BASELINE_COLOR_UP = "#43C5B1";
const DEFAULT_SCORECARD_BASELINE_COLOR_DOWN = "#EA6175";
const DEFAULT_SCORECARD_KEY_VALUE_FONT_SIZE = 32;
const DEFAULT_SCORECARD_BASELINE_FONT_SIZE = 16;
const LINE_FILL_TRANSPARENCY = 0.4;
const LINE_DATA_POINT_RADIUS = 3;
const DEFAULT_WINDOW_SIZE = 2;
// session
const DEBOUNCE_TIME = 200;
const MESSAGE_VERSION = 1;
// Sheets
const FORBIDDEN_SHEETNAME_CHARS = ["'", "*", "?", "/", "\\", "[", "]"];
const FORBIDDEN_SHEETNAME_CHARS_IN_EXCEL_REGEX = /'|\*|\?|\/|\\|\[|\]/;
// Cells
const FORMULA_REF_IDENTIFIER = "|";
// Components
var ComponentsImportance;
(function (ComponentsImportance) {
ComponentsImportance[ComponentsImportance["Grid"] = 0] = "Grid";
ComponentsImportance[ComponentsImportance["Highlight"] = 5] = "Highlight";
ComponentsImportance[ComponentsImportance["HeaderGroupingButton"] = 6] = "HeaderGroupingButton";
ComponentsImportance[ComponentsImportance["Figure"] = 10] = "Figure";
ComponentsImportance[ComponentsImportance["ScrollBar"] = 15] = "ScrollBar";
ComponentsImportance[ComponentsImportance["GridPopover"] = 19] = "GridPopover";
ComponentsImportance[ComponentsImportance["GridComposer"] = 20] = "GridComposer";
ComponentsImportance[ComponentsImportance["IconPicker"] = 25] = "IconPicker";
ComponentsImportance[ComponentsImportance["TopBarComposer"] = 30] = "TopBarComposer";
ComponentsImportance[ComponentsImportance["Popover"] = 35] = "Popover";
ComponentsImportance[ComponentsImportance["FigureAnchor"] = 1000] = "FigureAnchor";
ComponentsImportance[ComponentsImportance["FigureSnapLine"] = 1001] = "FigureSnapLine";
ComponentsImportance[ComponentsImportance["FigureTooltip"] = 1002] = "FigureTooltip";
})(ComponentsImportance || (ComponentsImportance = {}));
let DEFAULT_SHEETVIEW_SIZE = 0;
function getDefaultSheetViewSize() {
return DEFAULT_SHEETVIEW_SIZE;
}
function setDefaultSheetViewSize(size) {
DEFAULT_SHEETVIEW_SIZE = size;
}
const MAXIMAL_FREEZABLE_RATIO = 0.85;
const NEWLINE = "\n";
const FONT_SIZES = [6, 7, 8, 9, 10, 11, 12, 14, 18, 24, 36];
// Pivot
const PIVOT_TABLE_CONFIG = {
hasFilters: false,
totalRow: false,
firstColumn: true,
lastColumn: false,
numberOfHeaders: 1,
bandedRows: true,
bandedColumns: false,
styleId: "TableStyleMedium5",
automaticAutofill: false,
};
const PIVOT_INDENT = 15;
const PIVOT_COLLAPSE_ICON_SIZE = 12;
const PIVOT_MAX_NUMBER_OF_CELLS = 1e5;
const DEFAULT_CURRENCY = {
symbol: "$",
position: "before",
decimalPlaces: 2,
code: "",
name: "Dollar",
};
const DEFAULT_CAROUSEL_TITLE_STYLE = {
fontSize: CHART_TITLE_FONT_SIZE,
color: TEXT_BODY,
};
const DEFAULT_TOKEN_COLOR = "#000000";
const functionColor = DEFAULT_TOKEN_COLOR;
const operatorColor = "#3da4ab";
const tokenColors = {
OPERATOR: operatorColor,
NUMBER: "#02c39a",
STRING: "#00a82d",
FUNCTION: functionColor,
DEBUGGER: operatorColor,
LEFT_PAREN: functionColor,
RIGHT_PAREN: functionColor,
ARG_SEPARATOR: functionColor,
ORPHAN_RIGHT_PAREN: "#ff0000",
};
const DRAG_THRESHOLD = 5; // in pixels, to avoid unwanted drag when clicking
//------------------------------------------------------------------------------
// Miscellaneous
//------------------------------------------------------------------------------
const sanitizeSheetNameRegex = new RegExp(FORBIDDEN_SHEETNAME_CHARS_IN_EXCEL_REGEX, "g");
/**
* Remove quotes from a quoted string
* ```js
* removeStringQuotes('"Hello"')
* > 'Hello'
* ```
*/
function removeStringQuotes(str) {
if (str[0] === '"') {
str = str.slice(1);
}
if (str[str.length - 1] === '"' && str[str.length - 2] !== "\\") {
return str.slice(0, str.length - 1);
}
return str;
}
function isCloneable(obj) {
return "clone" in obj && obj.clone instanceof Function;
}
/**
* Escapes a string to use as a literal string in a RegExp.
* @url https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
*/
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Deep copy arrays, plain objects and primitive values.
* Throws an error for other types such as class instances.
* Sparse arrays remain sparse.
*/
function deepCopy(obj) {
switch (typeof obj) {
case "object": {
if (obj === null) {
return obj;
}
else if (isCloneable(obj)) {
return obj.clone();
}
else if (!(isPlainObject(obj) || obj instanceof Array)) {
throw new Error("Unsupported type: only objects and arrays are supported");
}
const result = Array.isArray(obj) ? new Array(obj.length) : {};
if (Array.isArray(obj)) {
for (let i = 0, len = obj.length; i < len; i++) {
if (i in obj) {
result[i] = deepCopy(obj[i]);
}
}
}
else {
for (const key in obj) {
result[key] = deepCopy(obj[key]);
}
}
return result;
}
case "number":
case "string":
case "boolean":
case "function":
case "undefined":
return obj;
default:
throw new Error(`Unsupported type: ${typeof obj}`);
}
}
/**
* Check if the object is a plain old javascript object.
*/
function isPlainObject(obj) {
return (typeof obj === "object" &&
obj !== null &&
// obj.constructor can be undefined when there's no prototype (`Object.create(null, {})`)
(obj?.constructor === Object || obj?.constructor === undefined));
}
/**
* Sanitize the name of a sheet, by eventually removing quotes
* @param sheetName name of the sheet, potentially quoted with single quotes
*/
function getUnquotedSheetName(sheetName) {
return unquote(sheetName, "'");
}
function unquote(string, quoteChar = '"') {
if (string.startsWith(quoteChar)) {
string = string.slice(1);
}
if (string.endsWith(quoteChar)) {
string = string.slice(0, -1);
}
return string;
}
/**
* Add quotes around the sheet name or any symbol name if it contains at least one non alphanumeric character
* '\w' captures [0-9][a-z][A-Z] and _.
* @param symbolName Name of the sheet or symbol
*/
function getCanonicalSymbolName(symbolName) {
if (symbolName.match(/\w/g)?.length !== symbolName.length) {
symbolName = `'${symbolName}'`;
}
return symbolName;
}
/** Replace the excel-excluded characters of a sheetName */
function sanitizeSheetName(sheetName, replacementChar = " ") {
return sheetName.replace(sanitizeSheetNameRegex, replacementChar);
}
function clip(val, min, max) {
return val < min ? min : val > max ? max : val;
}
/**
* Create a range from start (included) to end (excluded).
* range(10, 13) => [10, 11, 12]
* range(2, 8, 2) => [2, 4, 6]
*/
function range(start, end, step = 1) {
if (end <= start && step > 0) {
return [];
}
if (step === 0) {
throw new Error("range() step must not be zero");
}
const length = Math.ceil(Math.abs((end - start) / step));
const array = Array(length);
for (let i = 0; i < length; i++) {
array[i] = start + i * step;
}
return array;
}
/**
* Groups consecutive numbers.
* The input array is assumed to be sorted
* @param numbers
*/
function groupConsecutive(numbers) {
return numbers.reduce((groups, currentRow, index, rows) => {
if (Math.abs(currentRow - rows[index - 1]) === 1) {
const lastGroup = groups[groups.length - 1];
lastGroup.push(currentRow);
}
else {
groups.push([currentRow]);
}
return groups;
}, []);
}
/**
* Create one generator from two generators by linking
* each item of the first generator to the next item of
* the second generator.
*
* Let's say generator G1 yields A, B, C and generator G2 yields X, Y, Z.
* The resulting generator of `linkNext(G1, G2)` will yield A', B', C'
* where `A' = A & {next: Y}`, `B' = B & {next: Z}` and `C' = C & {next: undefined}`
* @param generator
* @param nextGenerator
*/
function* linkNext(generator, nextGenerator) {
nextGenerator.next();
for (const item of generator) {
const nextItem = nextGenerator.next();
yield {
...item,
next: nextItem.done ? undefined : nextItem.value,
};
}
}
function isBoolean(str) {
const upperCased = str.toUpperCase();
return upperCased === "TRUE" || upperCased === "FALSE";
}
const MARKDOWN_LINK_REGEX = /^\[(.+)\]\((.+)\)$/;
//link must start with http or https
//https://stackoverflow.com/a/3809435/4760614
const WEB_LINK_REGEX = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;
function isMarkdownLink(str) {
return MARKDOWN_LINK_REGEX.test(str);
}
/**
* Check if the string is a web link.
* e.g. http://odoo.com
*/
function isWebLink(str) {
return WEB_LINK_REGEX.test(str);
}
/**
* Build a markdown link from a label and an url
*/
function markdownLink(label, url) {
return `[${label}](${url})`;
}
function parseMarkdownLink(str) {
const matches = str.match(MARKDOWN_LINK_REGEX) || [];
const label = matches[1];
const url = matches[2];
if (!label || !url) {
throw new Error(`Could not parse markdown link ${str}.`);
}
return {
label,
url,
};
}
const O_SPREADSHEET_LINK_PREFIX = "o-spreadsheet://";
function isSheetUrl(url) {
return url.startsWith(O_SPREADSHEET_LINK_PREFIX);
}
function buildSheetLink(sheetId) {
return `${O_SPREADSHEET_LINK_PREFIX}${sheetId}`;
}
/**
* Parse a sheet link and return the sheet id
*/
function parseSheetUrl(sheetLink) {
if (sheetLink.startsWith(O_SPREADSHEET_LINK_PREFIX)) {
return sheetLink.slice(O_SPREADSHEET_LINK_PREFIX.length);
}
throw new Error(`${sheetLink} is not a valid sheet link`);
}
/**
* This helper function can be used as a type guard when filtering arrays.
* const foo: number[] = [1, 2, undefined, 4].filter(isDefined)
*/
function isDefined(argument) {
return argument !== undefined;
}
/**
* Check if all the values of an object, and all the values of the objects inside of it, are undefined.
*/
function isObjectEmptyRecursive(argument) {
if (argument === undefined)
return true;
return Object.values(argument).every((value) => typeof value === "object" ? isObjectEmptyRecursive(value) : !value);
}
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
*
* Also decorate the argument function with two methods: stopDebounce and isDebouncePending.
*
* Inspired by https://davidwalsh.name/javascript-debounce-function
*/
function debounce(func, wait, immediate) {
let timeout = undefined;
const debounced = function () {
const context = this;
const args = Array.from(arguments);
function later() {
timeout = undefined;
if (!immediate) {
func.apply(context, args);
}
}
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
debounced.isDebouncePending = () => timeout !== undefined;
debounced.stopDebounce = () => {
clearTimeout(timeout);
};
return debounced;
}
/**
* Creates a batched version of a callback so that all calls to it in the same
* microtick will only call the original callback once.
*
* @param callback the callback to batch
* @returns a batched version of the original callback
*
* Copied from odoo/owl repo.
*/
function batched(callback) {
let scheduled = false;
return async (...args) => {
if (!scheduled) {
scheduled = true;
await Promise.resolve();
scheduled = false;
callback(...args);
}
};
}
/*
* Concatenate an array of strings.
*/
function concat$1(chars) {
// ~40% faster than chars.join("")
let output = "";
for (let i = 0, len = chars.length; i < len; i++) {
output += chars[i];
}
return output;
}
/**
* Lazy value computed by the provided function.
*/
function lazy(fn) {
let isMemoized = false;
let memo;
const lazyValue = () => {
if (!isMemoized) {
memo = fn instanceof Function ? fn() : fn;
isMemoized = true;
}
return memo;
};
lazyValue.map = (callback) => lazy(() => callback(lazyValue()));
return lazyValue;
}
/**
* Find the next defined value after the given index in an array of strings. If there is no defined value
* after the index, return the closest defined value before the index. Return an empty string if no
* defined value was found.
*
*/
function findNextDefinedValue(arr, index) {
let value = arr.slice(index).find((val) => val);
if (!value) {
value = arr
.slice(0, index)
.reverse()
.find((val) => val);
}
return value || "";
}
/** Get index of first header added by an ADD_COLUMNS_ROWS command */
function getAddHeaderStartIndex(position, base) {
return position === "after" ? base + 1 : base;
}
/**
* Compares n objects.
*/
function deepEquals(...o) {
if (o.length <= 1)
return true;
for (let index = 1; index < o.length; index++) {
if (!_deepEquals(o[0], o[index]))
return false;
}
return true;
}
function _deepEquals(o1, o2) {
if (o1 === o2)
return true;
if ((o1 && !o2) || (o2 && !o1))
return false;
if (typeof o1 !== typeof o2)
return false;
if (typeof o1 !== "object")
return false;
// Objects can have different keys if the values are undefined
for (const key in o2) {
if (!(key in o1) && o2[key] !== undefined) {
return false;
}
}
for (const key in o1) {
if (typeof o1[key] !== typeof o2[key])
return false;
if (typeof o1[key] === "object") {
if (!_deepEquals(o1[key], o2[key]))
return false;
}
else {
if (o1[key] !== o2[key])
return false;
}
}
return true;
}
/**
* Compares two arrays.
* For performance reasons, this function is to be preferred
* to 'deepEquals' in the case we know that the inputs are arrays.
*/
function deepEqualsArray(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (!deepEquals(arr1[i], arr2[i])) {
return false;
}
}
return true;
}
/**
* Check if the given array contains all the values of the other array.
* It makes the assumption that both array do not contain duplicates.
*/
function includesAll(arr, values) {
if (arr.length < values.length) {
return false;
}
const set = new Set(arr);
return values.every((value) => set.has(value));
}
/**
* Return an object with all the keys in the object that have a falsy value removed.
*/
function removeFalsyAttributes(obj) {
if (!obj)
return obj;
const cleanObject = { ...obj };
Object.keys(cleanObject).forEach((key) => !cleanObject[key] && delete cleanObject[key]);
return cleanObject;
}
/**
* Equivalent to "\s" in regexp, minus the new lines characters
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes
*/
const specialWhiteSpaceSpecialCharacters = [
"\t",
"\f",
"\v",
String.fromCharCode(parseInt("00a0", 16)),
String.fromCharCode(parseInt("1680", 16)),
String.fromCharCode(parseInt("2000", 16)),
String.fromCharCode(parseInt("200a", 16)),
String.fromCharCode(parseInt("2028", 16)),
String.fromCharCode(parseInt("2029", 16)),
String.fromCharCode(parseInt("202f", 16)),
String.fromCharCode(parseInt("205f", 16)),
String.fromCharCode(parseInt("3000", 16)),
String.fromCharCode(parseInt("feff", 16)),
];
const specialWhiteSpaceRegexp = new RegExp(specialWhiteSpaceSpecialCharacters.join("|"), "g");
const newLineRegexp = /(\r\n|\r)/g;
const whiteSpaceCharacters = specialWhiteSpaceSpecialCharacters.concat([" "]);
/**
* Replace all different newlines characters by \n
*/
function replaceNewLines(text) {
if (!text)
return "";
return text.replace(newLineRegexp, NEWLINE);
}
/**
* Determine if the numbers are consecutive.
*/
function isConsecutive(iterable) {
const array = Array.from(iterable).sort((a, b) => a - b); // sort numerically rather than lexicographically
for (let i = 1; i < array.length; i++) {
if (array[i] - array[i - 1] !== 1) {
return false;
}
}
return true;
}
/**
* Creates a version of the function that's memoized on the value of its first
* argument, if any.
*/
function memoize(func) {
const cache = new Map();
const funcName = func.name ? func.name + " (memoized)" : "memoized";
return {
[funcName](...args) {
if (!cache.has(args[0])) {
cache.set(args[0], func(...args));
}
return cache.get(args[0]);
},
}[funcName];
}
/**
* Removes the specified indexes from the array.
* Sparse (empty) elements are transformed to undefined (unless their index is explicitly removed).
*/
function removeIndexesFromArray(array, indexes) {
const toRemove = new Set(indexes);
const newArray = [];
for (let i = 0; i < array.length; i++) {
if (!toRemove.has(i)) {
newArray.push(array[i]);
}
}
return newArray;
}
function insertItemsAtIndex(array, items, index) {
const newArray = [...array];
newArray.splice(index, 0, ...items);
return newArray;
}
function replaceItemAtIndex(array, newItem, index) {
const newArray = [...array];
newArray[index] = newItem;
return newArray;
}
function trimContent(content) {
const contentLines = content.split("\n");
return contentLines.map((line) => line.replace(/\s+/g, " ").trim()).join("\n");
}
function isNumberBetween(value, min, max) {
if (min > max) {
return isNumberBetween(value, max, min);
}
return value >= min && value <= max;
}
/**
* Get a Regex for the find & replace that matches the given search string and options.
*/
function getSearchRegex(searchStr, searchOptions) {
let searchValue = escapeRegExp(searchStr);
const flags = !searchOptions.matchCase ? "i" : "";
if (searchOptions.exactMatch) {
searchValue = `^${searchValue}$`;
}
return RegExp(searchValue, flags);
}
/**
* Alternative to Math.max that works with large arrays.
* Typically useful for arrays bigger than 100k elements.
*/
function largeMax(array) {
let len = array.length;
if (len < 100_000)
return Math.max(...array);
let max = -Infinity;
while (len--) {
max = array[len] > max ? array[len] : max;
}
return max;
}
/**
* Alternative to Math.min that works with large arrays.
* Typically useful for arrays bigger than 100k elements.
*/
function largeMin(array) {
let len = array.length;
if (len < 100_000)
return Math.min(...array);
let min = +Infinity;
while (len--) {
min = array[len] < min ? array[len] : min;
}
return min;
}
class TokenizingChars {
text;
currentIndex = 0;
current;
constructor(text) {
this.text = text;
this.current = text[0];
}
shift() {
const current = this.current;
const next = this.text[++this.currentIndex];
this.current = next;
return current;
}
advanceBy(length) {
this.currentIndex += length;
this.current = this.text[this.currentIndex];
}
isOver() {
return this.currentIndex >= this.text.length;
}
remaining() {
return this.text.substring(this.currentIndex);
}
currentStartsWith(str) {
if (this.current !== str[0]) {
return false;
}
for (let j = 1; j < str.length; j++) {
if (this.text[this.currentIndex + j] !== str[j]) {
return false;
}
}
return true;
}
}
/**
* Remove duplicates from an array.
*
* @param array The array to remove duplicates from.
* @param cb A callback to get an element value.
*/
function removeDuplicates$1(array, cb = (a) => a) {
const set = new Set();
return array.filter((item) => {
const key = cb(item);
if (set.has(key)) {
return false;
}
set.add(key);
return true;
});
}
/**
* Similar to transposing and array, but with POJOs instead of arrays. Useful, for example, when manipulating
* a POJO grid[col][row] and you want to transpose it to grid[row][col].
*
* The resulting object is created such as result[key1][key2] = pojo[key2][key1]
*/
function transpose2dPOJO(pojo) {
const result = {};
for (const key in pojo) {
for (const subKey in pojo[key]) {
if (!result[subKey]) {
result[subKey] = {};
}
result[subKey][key] = pojo[key][subKey];
}
}
return result;
}
function getUniqueText(text, texts, options = {}) {
const compute = options.compute ?? ((text, i) => `${text} (${i})`);
const computeFirstOne = options.computeFirstOne ?? false;
let i = options.start ?? 1;
let newText = computeFirstOne ? compute(text, i) : text;
while (texts.includes(newText)) {
newText = compute(text, i++);
}
return newText;
}
function isFormula(content) {
return content.startsWith("=") || content.startsWith("+");
}
// TODO: we should make make ChartStyle be the same as Style sometime ...
function chartStyleToCellStyle(style) {
return {
bold: style.bold,
italic: style.italic,
fontSize: style.fontSize,
textColor: style.color,
align: style.align,
};
}
const LAYERS = {
Background: 0,
Highlights: 1,
Clipboard: 2,
Chart: 4,
Autofill: 5,
Selection: 6,
Headers: 100, // ensure that we end up on top
};
const OrderedLayers = memoize(() => Object.keys(LAYERS).sort((a, b) => LAYERS[a] - LAYERS[b]));
/**
*
* @param layer New layer name
* @param priority The lower priorities are rendered first
*/
function addRenderingLayer(layer, priority) {
if (LAYERS[layer]) {
throw new Error(`Layer ${layer} already exists`);
}
LAYERS[layer] = priority;
}
const filterCriterions = [
"containsText",
"notContainsText",
"isEqualText",
"dateIs",
"dateIsBefore",
"dateIsOnOrBefore",
"dateIsAfter",
"dateIsOnOrAfter",
"dateIsBetween",
"dateIsNotBetween",
"isEqual",
"isNotEqual",
"isGreaterThan",
"isGreaterOrEqualTo",
"isLessThan",
"isLessOrEqualTo",
"isBetween",
"isNotBetween",
"customFormula