UNPKG

@odoo/o-spreadsheet

Version:
1,579 lines (1,541 loc) 506 kB
import * as chart_js from 'chart.js'; import { ChartConfiguration, ChartDataset, CoreChartOptions, Scriptable, Color as Color$1, ScriptableContext, FontSpec, Point, ChartType as ChartType$1, ChartMeta } from 'chart.js'; import * as ChartGeo from 'chartjs-chart-geo'; import * as GeoJSON$1 from 'geojson'; import * as _odoo_owl from '@odoo/owl'; import { ComponentConstructor, Component } from '@odoo/owl'; import * as chart_js_dist_types_utils from 'chart.js/dist/types/utils'; import * as chart_js_dist_types_geometric from 'chart.js/dist/types/geometric'; interface FigureInfo { id: UID; width: Pixel; height: Pixel; tag: string; } interface Figure extends FigureInfo, AnchorOffset { } interface FigureUI extends DOMCoordinates, Figure { } interface AnchorOffset { col: HeaderIndex; row: HeaderIndex; offset: PixelPosition; } interface FigureSize { width: Pixel; height: Pixel; } interface ExcelFigureSize { cx: number; cy: number; } type ResizeDirection = -1 | 0 | 1; type ImageSVG = { name: string; width: number; height: number; paths: { path: string; fillColor: Color; }[]; }; interface Image$1 { path: string; size: FigureSize; mimetype?: string; } declare const AllowedImageMimeTypes: readonly ["image/avif", "image/bmp", "image/gif", "image/vnd.microsoft.icon", "image/jpeg", "image/png", "image/tiff", "image/webp"]; type XLSXExportFile = XLSXExportImageFile | XLSXExportXMLFile; interface XLSXExportXMLFile { path: string; content: string; contentType?: string; } interface XLSXExportImageFile { path: string; imageSrc: string; } interface XLSXExport { name: string; files: XLSXExportFile[]; } /** * Standardized XLSX hexadecimal color (with or without alpha channel). * Note that the alpha channel goes first! AARRGGBB * e.g. "1E5010" or "331E5010" */ type XlsxHexColor = string & Alias; type VerticalAxisPosition = "left" | "right"; type LegendPosition = "top" | "bottom" | "left" | "right" | "none"; interface CommonChartDefinition { readonly dataSets: CustomizedDataSet[]; readonly dataSetsHaveTitle: boolean; readonly labelRange?: string; readonly title: TitleDesign; readonly background?: Color; readonly legendPosition: LegendPosition; readonly aggregated?: boolean; readonly axesDesign?: AxesDesign; readonly showValues?: boolean; } interface ComboBarChartDefinition extends CommonChartDefinition { } interface BarChartDefinition extends ComboBarChartDefinition { readonly type: "bar"; readonly stacked: boolean; readonly horizontal?: boolean; } type BarChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; interface ComboChartDefinition extends ComboBarChartDefinition { readonly dataSets: ComboChartDataSet[]; readonly type: "combo"; readonly hideDataMarkers?: boolean; } type ComboChartDataSet = CustomizedDataSet & { type?: "bar" | "line"; }; type ComboChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; interface FunnelChartDefinition { readonly type: "funnel"; readonly dataSets: CustomizedDataSet[]; readonly dataSetsHaveTitle: boolean; readonly labelRange?: string; readonly title: TitleDesign; readonly background?: Color; readonly legendPosition: LegendPosition; readonly horizontal?: boolean; readonly axesDesign?: AxesDesign; readonly aggregated?: boolean; readonly showValues?: boolean; readonly funnelColors?: FunnelChartColors; readonly cumulative?: boolean; } type FunnelChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; type FunnelChartColors = (Color | undefined)[]; interface GaugeChartDefinition { readonly type: "gauge"; readonly title: TitleDesign; readonly dataRange?: string; readonly sectionRule: SectionRule; readonly background?: Color; } interface SectionRule { readonly colors: ColorSet; readonly rangeMin: string; readonly rangeMax: string; readonly lowerInflectionPoint: SectionThreshold; readonly upperInflectionPoint: SectionThreshold; } interface ColorSet { readonly lowerColor: Color; readonly middleColor: Color; readonly upperColor: Color; } interface SectionThreshold { readonly type: "number" | "percentage"; readonly value: string; readonly operator: "<" | "<="; } interface GaugeValue { value: number; label: string; } interface GaugeInflectionValue extends GaugeValue { operator: "<" | "<="; } interface GaugeChartRuntime { background: Color; title: TitleDesign; minValue: GaugeValue; maxValue: GaugeValue; gaugeValue?: GaugeValue; inflectionValues: GaugeInflectionValue[]; colors: Color[]; } interface GeoChartDefinition { readonly type: "geo"; readonly dataSets: CustomizedDataSet[]; readonly dataSetsHaveTitle: boolean; readonly labelRange?: string; readonly title: TitleDesign; readonly background?: Color; readonly legendPosition: LegendPosition; readonly colorScale?: GeoChartColorScale; readonly missingValueColor?: Color; readonly region?: string; } type GeoChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; interface GeoChartCustomColorScale { minColor: Color; midColor?: Color; maxColor: Color; } type GeoChartColorScale = GeoChartCustomColorScale | "blues" | "cividis" | "greens" | "greys" | "oranges" | "purples" | "rainbow" | "reds" | "viridis"; type GeoChartProjection = "azimuthalEqualArea" | "azimuthalEquidistant" | "gnomonic" | "orthographic" | "stereographic" | "equalEarth" | "albers" | "albersUsa" | "conicConformal" | "conicEqualArea" | "conicEquidistant" | "equirectangular" | "mercator" | "transverseMercator" | "naturalEarth1"; interface GeoChartRegion { id: string; label: string; defaultProjection: GeoChartProjection; } interface GeoChartRuntimeGenerationArgs extends ChartRuntimeGenerationArgs { availableRegions: GeoChartRegion[]; getGeoJsonFeatures: (region: string) => GeoJSON.Feature[] | undefined; geoFeatureNameToId: (region: string, featureName: string) => string | undefined; } interface LineChartDefinition extends CommonChartDefinition { readonly type: "line"; readonly labelsAsText: boolean; readonly stacked: boolean; readonly aggregated?: boolean; readonly cumulative: boolean; readonly fillArea?: boolean; readonly hideDataMarkers?: boolean; } type LineChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; interface PieChartDefinition extends CommonChartDefinition { readonly type: "pie"; readonly aggregated?: boolean; readonly isDoughnut?: boolean; readonly showValues?: boolean; readonly pieHolePercentage?: number; } type PieChartRuntime = { chartJsConfig: ChartConfiguration<"pie" | "doughnut">; background: Color; }; interface PyramidChartDefinition extends Omit<BarChartDefinition, "type"> { readonly type: "pyramid"; } type PyramidChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; interface RadarChartDefinition extends CommonChartDefinition { readonly type: "radar"; readonly aggregated?: boolean; readonly stacked: boolean; readonly fillArea?: boolean; readonly hideDataMarkers?: boolean; } type RadarChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; interface ScatterChartDefinition extends Omit<LineChartDefinition, "type" | "stacked" | "cumulative"> { readonly type: "scatter"; } type ScatterChartRuntime = LineChartRuntime; interface ScorecardChartDefinition { readonly type: "scorecard"; readonly title: TitleDesign; readonly keyValue?: string; readonly keyDescr?: TitleDesign; readonly baseline?: string; readonly baselineMode: BaselineMode; readonly baselineDescr?: TitleDesign; readonly background?: Color; readonly baselineColorUp: Color; readonly baselineColorDown: Color; readonly humanize?: boolean; } type BaselineMode = "text" | "difference" | "percentage" | "progress"; type BaselineArrowDirection = "neutral" | "up" | "down"; interface ProgressBar { readonly value: number; readonly color: Color; } interface ScorecardChartRuntime { readonly title: TitleDesign; readonly keyValue: string; readonly keyDescr: string; readonly baselineDisplay: string; readonly baselineColor?: string; readonly baselineArrow: BaselineArrowDirection; readonly baselineDescr?: string; readonly background: Color; readonly fontColor: Color; readonly keyValueStyle?: Style; readonly keyValueDescrStyle?: Style; readonly baselineStyle?: Style; readonly baselineDescrStyle?: Style; readonly progressBar?: ProgressBar; } interface SunburstChartDefinition { readonly type: "sunburst"; readonly dataSets: CustomizedDataSet[]; readonly dataSetsHaveTitle: boolean; readonly labelRange?: string; readonly title: TitleDesign; readonly background?: Color; readonly legendPosition: LegendPosition; readonly showValues?: boolean; readonly showLabels?: boolean; readonly valuesDesign?: ChartStyle; readonly groupColors?: (Color | undefined | null)[]; readonly pieHolePercentage?: number; } type SunburstChartRuntime = { chartJsConfig: ChartConfiguration<"doughnut">; background: Color; }; interface SunburstChartJSDataset extends ChartDataset<"doughnut"> { groupColors: { label: string; color: Color; }[]; } /*! * chartjs-chart-treemap v3.1.0 * https://chartjs-chart-treemap.pages.dev/ * (c) 2024 Jukka Kurkela * Released under the MIT license */ type AnyObject = Record<string, unknown>; type TreemapScriptableContext = ScriptableContext<"treemap"> & { raw: TreemapDataPoint; }; type TreemapControllerDatasetCaptionsOptions = { align?: Scriptable<LabelAlign, TreemapScriptableContext>; color?: Scriptable<Color$1, TreemapScriptableContext>; display?: boolean; formatter?: Scriptable<string, TreemapScriptableContext>; font?: FontSpec; hoverColor?: Scriptable<Color$1, TreemapScriptableContext>; hoverFont?: FontSpec; padding?: number; }; type TreemapControllerDatasetLabelsOptions = { align?: Scriptable<LabelAlign, TreemapScriptableContext>; color?: Scriptable<Color$1 | Color$1[], TreemapScriptableContext>; display?: boolean; formatter?: Scriptable<string | Array<string>, TreemapScriptableContext>; font?: Scriptable<FontSpec | FontSpec[], TreemapScriptableContext>; hoverColor?: Scriptable<Color$1 | Color$1[], TreemapScriptableContext>; hoverFont?: Scriptable<FontSpec | FontSpec[], TreemapScriptableContext>; overflow?: Scriptable<LabelOverflow, TreemapScriptableContext>; padding?: number; position?: Scriptable<LabelPosition, TreemapScriptableContext>; }; type LabelPosition = "top" | "middle" | "bottom"; type LabelAlign = "left" | "center" | "right"; type LabelOverflow = "cut" | "hidden" | "fit"; type TreemapControllerDatasetDividersOptions = { display?: boolean; lineCapStyle?: string; lineColor?: string; lineDash?: number[]; lineDashOffset?: number; lineWidth?: number; }; interface TreemapControllerDatasetOptions<DType> { spacing?: number; rtl?: boolean; backgroundColor?: Scriptable<Color$1, TreemapScriptableContext>; borderColor?: Scriptable<Color$1, TreemapScriptableContext>; borderWidth?: number; hoverBackgroundColor?: Scriptable<Color$1, TreemapScriptableContext>; hoverBorderColor?: Scriptable<Color$1, TreemapScriptableContext>; hoverBorderWidth?: number; captions?: TreemapControllerDatasetCaptionsOptions; dividers?: TreemapControllerDatasetDividersOptions; labels?: TreemapControllerDatasetLabelsOptions; label?: string; data: TreemapDataPoint[]; groups?: Array<keyof DType>; sumKeys?: Array<keyof DType>; tree: number[] | DType[] | AnyObject; treeLeafKey?: keyof DType; key?: keyof DType; hidden?: boolean; displayMode?: "containerBoxes" | "headerBoxes"; groupColors?: TreeMapGroupColor[]; } interface TreemapDataPoint { x: number; y: number; w: number; h: number; /** * Value */ v: number; /** * Sum */ s: number; /** * Depth, only available if grouping */ l?: number; /** * Group name, only available if grouping */ g?: string; /** * Group Sum, only available if grouping */ gs?: number; /** * additonal keys sums, only available if grouping */ vs?: AnyObject; isLeaf?: boolean; } declare module "chart.js" { interface ChartTypeRegistry { treemap: { chartOptions: CoreChartOptions<"treemap">; datasetOptions: TreemapControllerDatasetOptions<Record<string, unknown>>; defaultDataPoint: TreemapDataPoint; metaExtensions: AnyObject; parsedDataType: unknown; scales: never; }; } } interface TreeMapChartDefinition { readonly type: "treemap"; readonly dataSets: CustomizedDataSet[]; readonly dataSetsHaveTitle: boolean; readonly labelRange?: string; readonly title: TitleDesign; readonly background?: Color; readonly legendPosition: LegendPosition; readonly showHeaders?: boolean; readonly headerDesign?: TitleDesign; readonly showValues?: boolean; readonly showLabels?: boolean; readonly valuesDesign?: TitleDesign; readonly coloringOptions?: TreeMapColoringOptions; } type TreeMapCategoryColorOptions = { type: "categoryColor"; colors: (Color | undefined | null)[]; useValueBasedGradient: boolean; }; type TreeMapColorScaleOptions = { type: "colorScale"; minColor: Color; midColor?: Color; maxColor: Color; }; interface TreeMapGroupColor { label: string; color: Color; } type TreeMapColoringOptions = TreeMapCategoryColorOptions | TreeMapColorScaleOptions; type TreeMapChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; interface WaterfallChartDefinition extends CommonChartDefinition { readonly type: "waterfall"; readonly verticalAxisPosition: VerticalAxisPosition; readonly aggregated?: boolean; readonly showSubTotals: boolean; readonly showConnectorLines: boolean; readonly firstValueAsSubtotal?: boolean; readonly positiveValuesColor?: Color; readonly negativeValuesColor?: Color; readonly subTotalValuesColor?: Color; } type WaterfallChartRuntime = { chartJsConfig: ChartConfiguration; background: Color; }; declare const CHART_TYPES: readonly ["line", "bar", "pie", "scorecard", "gauge", "scatter", "combo", "waterfall", "pyramid", "radar", "geo", "funnel", "sunburst", "treemap"]; type ChartType = (typeof CHART_TYPES)[number]; type ChartDefinition = LineChartDefinition | PieChartDefinition | BarChartDefinition | ScorecardChartDefinition | GaugeChartDefinition | ScatterChartDefinition | ComboChartDefinition | WaterfallChartDefinition | PyramidChartDefinition | RadarChartDefinition | GeoChartDefinition | FunnelChartDefinition | SunburstChartDefinition | TreeMapChartDefinition; type ChartWithDataSetDefinition = Extract<ChartDefinition, { dataSets: CustomizedDataSet[]; labelRange?: string; }>; type ChartWithAxisDefinition = Extract<ChartWithDataSetDefinition, { axesDesign?: AxesDesign; }>; type ChartJSRuntime = LineChartRuntime | PieChartRuntime | BarChartRuntime | ComboChartRuntime | ScatterChartRuntime | WaterfallChartRuntime | PyramidChartRuntime | RadarChartRuntime | GeoChartRuntime | FunnelChartRuntime | SunburstChartRuntime | TreeMapChartRuntime; type ChartRuntime = ChartJSRuntime | ScorecardChartRuntime | GaugeChartRuntime; interface LabelValues { readonly values: string[]; readonly formattedValues: string[]; } interface DatasetValues { readonly label?: string; readonly data: any[]; readonly hidden?: boolean; } interface DatasetDesign { readonly backgroundColor?: string; readonly yAxisId?: string; readonly label?: string; } interface AxisDesign { readonly title?: TitleDesign; } interface AxesDesign { readonly x?: AxisDesign; readonly y?: AxisDesign; readonly y1?: AxisDesign; } interface ChartStyle { readonly bold?: boolean; readonly italic?: boolean; readonly align?: Align; readonly verticalAlign?: VerticalAlign; readonly color?: Color; readonly fontSize?: number; readonly fillColor?: Color; } interface TitleDesign extends ChartStyle { readonly text?: string; } type TrendType = "polynomial" | "exponential" | "logarithmic" | "trailingMovingAverage"; interface TrendConfiguration { type?: TrendType; order?: number; color?: Color; display?: boolean; window?: number; } type CustomizedDataSet = { readonly dataRange: string; readonly trend?: TrendConfiguration; } & DatasetDesign; type AxisType = "category" | "linear" | "time"; type ChartDatasetOrientation = "rows" | "columns"; interface DataSet { readonly labelCell?: Range; readonly dataRange: Range; readonly rightYAxis?: boolean; readonly backgroundColor?: Color; readonly customLabel?: string; readonly trend?: TrendConfiguration; } interface ExcelChartDataset { readonly label?: { text?: string; } | { reference?: string; }; readonly range: string; readonly backgroundColor?: Color; readonly rightYAxis?: boolean; readonly trend?: ExcelChartTrendConfiguration; } interface ExcelChartTrendConfiguration { readonly type?: ExcelTrendlineType; readonly order?: number; readonly color?: Color; readonly window?: number; } type ExcelTrendlineType = "poly" | "exp" | "log" | "movingAvg" | "linear"; type ExcelChartType = "line" | "bar" | "pie" | "combo" | "scatter" | "radar"; interface ExcelChartDefinition { readonly title?: TitleDesign; readonly type: ExcelChartType; readonly dataSets: ExcelChartDataset[]; readonly labelRange?: string; readonly backgroundColor: XlsxHexColor; readonly fontColor: XlsxHexColor; readonly legendPosition: LegendPosition; readonly stacked?: boolean; readonly cumulative?: boolean; readonly verticalAxis?: { useLeftAxis?: boolean; useRightAxis?: boolean; }; readonly axesDesign?: AxesDesign; } interface ChartCreationContext { readonly range?: CustomizedDataSet[]; readonly hierarchicalRanges?: CustomizedDataSet[]; readonly title?: TitleDesign; readonly background?: Color; readonly auxiliaryRange?: string; readonly aggregated?: boolean; readonly stacked?: boolean; readonly cumulative?: boolean; readonly dataSetsHaveTitle?: boolean; readonly labelsAsText?: boolean; readonly showSubTotals?: boolean; readonly showConnectorLines?: boolean; readonly firstValueAsSubtotal?: boolean; readonly legendPosition?: LegendPosition; readonly axesDesign?: AxesDesign; readonly fillArea?: boolean; readonly showValues?: boolean; readonly funnelColors?: FunnelChartColors; readonly showLabels?: boolean; readonly hideDataMarkers?: boolean; readonly valuesDesign?: ChartStyle; readonly groupColors?: (Color | undefined | null)[]; readonly showHeaders?: boolean; readonly headerDesign?: TitleDesign; readonly treemapColoringOptions?: TreeMapColoringOptions; } type ChartAxisFormats = { [axisId: string]: Format | undefined; } | undefined; interface ChartRuntimeGenerationArgs { dataSetsValues: DatasetValues[]; axisFormats: ChartAxisFormats; labels: string[]; locale: Locale; trendDataSetsValues?: (Point[] | undefined)[]; axisType?: AxisType; topPadding?: number; } /** Generic definition of chart to create a runtime: omit the chart type and the dataRange of the dataSets*/ type GenericDefinition<T extends ChartWithDataSetDefinition> = Partial<Omit<T, "dataSets" | "type">> & { dataSets?: Omit<T["dataSets"][number], "dataRange">[]; }; /** * This is a generic event bus based on the Owl event bus. * This bus however ensures type safety across events and subscription callbacks. */ declare class EventBus<Event extends { type: string; }> { subscriptions: { [eventType: string]: Subscription[]; }; /** * Add a listener for the 'eventType' events. * * Note that the 'owner' of this event can be anything, but will more likely * be a component or a class. The idea is that the callback will be called with * the proper owner bound. * * Also, the owner should be kind of unique. This will be used to remove the * listener. */ on<T extends Event["type"], E extends Extract<Event, { type: T; }>>(type: T, owner: any, callback: (r: Omit<E, "type">) => void): void; /** * Emit an event of type 'eventType'. Any extra arguments will be passed to * the listeners callback. */ trigger<T extends Event["type"], E extends Extract<Event, { type: T; }>>(type: T, payload?: Omit<E, "type">): void; /** * Remove a listener */ off<T extends Event["type"]>(eventType: T, owner: any): void; /** * Remove all subscriptions. */ clear(): void; } type Callback = (...args: any[]) => void; interface Subscription { owner: any; callback: Callback; } declare class SelectiveHistory<T = unknown> { private HEAD_BRANCH; private HEAD_OPERATION; private tree; private readonly applyOperation; private readonly revertOperation; private readonly buildEmpty; private readonly buildTransformation; /** * The selective history is a data structure used to register changes/updates of a state. * Each change/update is called an "operation". * The data structure allows to easily cancel (and redo) any operation individually. * An operation can be represented by any data structure. It can be a "command", a "diff", etc. * However it must have the following properties: * - it can be applied to modify the state * - it can be reverted on the state such that it was never executed. * - it can be transformed given other operation (Operational Transformation) * * Since this data structure doesn't know anything about the state nor the structure of * operations, the actual work must be performed by external functions given as parameters. * @param initialOperationId * @param applyOperation a function which can apply an operation to the state * @param revertOperation a function which can revert an operation from the state * @param buildEmpty a function returning an "empty" operation. * i.e an operation that leaves the state unmodified once applied or reverted * (used for internal implementation) * @param buildTransformation Factory used to build transformations */ constructor(args: { initialOperationId: UID; applyOperation: (data: T) => void; revertOperation: (data: T) => void; buildEmpty: (id: UID) => T; buildTransformation: TransformationFactory<T>; }); /** * Return the operation identified by its id. */ get(operationId: UID): T; /** * Append a new operation as the last one */ append(operationId: UID, data: T): void; /** * Insert a new operation after a specific operation (may not be the last operation). * Following operations will be transformed according * to the new operation. */ insert(operationId: UID, data: T, insertAfter: UID): void; /** * @param operationId operation to undo * @param undoId the id of the "undo operation" * @param insertAfter the id of the operation after which to insert the undo */ undo(operationId: UID, undoId: UID, insertAfter: UID): void; /** * @param operationId operation to redo * @param redoId the if of the "redo operation" * @param insertAfter the id of the operation after which to insert the redo */ redo(operationId: UID, redoId: UID, insertAfter: UID): void; rebase(operationId: UID): void; /** * Revert the state as it was *before* the given operation was executed. */ private revertBefore; /** * Revert the state as it was *after* the given operation was executed. */ private revertTo; /** * Revert an execution */ private revert; /** * Replay the operations between the current HEAD_BRANCH and the end of the tree */ private fastForward; } type ClientId = string; interface Client { id: ClientId; name: string; position?: ClientPosition; color?: Color; } interface ClientWithPosition extends Client { position: ClientPosition; } interface ClientWithColor extends Client { color: Color; } interface ClientPosition { sheetId: UID; col: HeaderIndex; row: HeaderIndex; } interface RemoteRevisionReceivedEvent { type: "remote-revision-received"; commands: readonly CoreCommand[]; } interface RevisionAcknowledgedEvent { type: "revision-acknowledged"; revisionId: UID; } interface RevisionUndone { type: "revision-undone"; revisionId: UID; commands: readonly CoreCommand[]; } interface RevisionRedone { type: "revision-redone"; revisionId: UID; commands: readonly CoreCommand[]; } interface CollaborativeEventReceived { type: "collaborative-event-received"; } interface UnexpectedRevisionIdEvent { type: "unexpected-revision-id"; } interface NewLocalStateUpdateEvent { type: "new-local-state-update"; id: UID; } interface SnapshotEvent { type: "snapshot"; } type CollaborativeEvent = NewLocalStateUpdateEvent | UnexpectedRevisionIdEvent | RemoteRevisionReceivedEvent | RevisionAcknowledgedEvent | RevisionUndone | RevisionRedone | SnapshotEvent | CollaborativeEventReceived; type CollaborativeEventTypes = CollaborativeEvent["type"]; interface RangePart { readonly colFixed: boolean; readonly rowFixed: boolean; } interface Range { readonly zone: Readonly<Zone>; readonly unboundedZone: Readonly<UnboundedZone>; readonly parts: readonly RangePart[]; readonly invalidXc?: string; /** true if the user provided the range with the sheet name */ readonly prefixSheet: boolean; /** the name of any sheet that is invalid */ readonly invalidSheetName?: string; /** the sheet on which the range is defined */ readonly sheetId: UID; } interface RangeStringOptions { useBoundedReference?: boolean; useFixedReference?: boolean; } interface RangeData { _zone: Zone | UnboundedZone; _sheetId: UID; } /** * https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/025ea6e4-ad42-43ea-a016-16f4e4688ac8 */ interface ConditionalFormat { id: UID; rule: ConditionalFormatRule; stopIfTrue?: boolean; ranges: string[]; } interface ConditionalFormatInternal extends Omit<ConditionalFormat, "ranges" | "rule"> { ranges: Range[]; rule: ConditionalFormatRuleInternal; } type ConditionalFormatRule = SingleColorRules | ColorScaleRule | IconSetRule | DataBarRule; type ConditionalFormatRuleInternal = SingleColorRules | ColorScaleRule | IconSetRule | DataBarRuleInternal; type SingleColorRules = CellIsRule; interface SingleColorRule { style: Style; } interface TextRule extends SingleColorRule { text: string; } interface CellIsRule extends SingleColorRule { type: "CellIsRule"; operator: ConditionalFormattingOperatorValues; values: string[]; } interface ExpressionRule extends SingleColorRule { type: "ExpressionRule"; } type ThresholdType = "value" | "number" | "percentage" | "percentile" | "formula"; type ColorScaleThreshold = { color: number; type: ThresholdType; value?: string; }; type ColorScaleMidPointThreshold = { color: number; type: Exclude<ThresholdType, "value">; value: string; }; type IconThreshold = { type: Exclude<ThresholdType, "value">; operator: "gt" | "ge"; value: string; }; interface ColorScaleRule { type: "ColorScaleRule"; minimum: ColorScaleThreshold; maximum: ColorScaleThreshold; midpoint?: ColorScaleMidPointThreshold; } interface DataBarRule { type: "DataBarRule"; color: number; rangeValues?: string; } interface DataBarRuleInternal extends Omit<DataBarRule, "rangeValues"> { rangeValues?: Range; } interface IconSet { upper: string; middle: string; lower: string; } interface IconSetRule { type: "IconSetRule"; icons: IconSet; upperInflectionPoint: IconThreshold; lowerInflectionPoint: IconThreshold; } interface ContainsTextRule extends TextRule { type: "ContainsTextRule"; } interface NotContainsTextRule extends TextRule { type: "NotContainsTextRule"; } interface BeginsWithRule extends TextRule { type: "BeginsWithRule"; } interface EndsWithRule extends TextRule { type: "EndsWithRule"; } interface containsBlanksRule extends TextRule { type: "containsBlanksRule"; } interface notContainsBlanksRule extends TextRule { type: "notContainsBlanksRule"; } interface containsErrorsRule extends SingleColorRule { type: "containsErrorsRule"; } interface notContainsErrorsRule extends SingleColorRule { type: "notContainsErrorsRule"; } interface TimePeriodRule extends SingleColorRule { type: "TimePeriodRule"; timePeriod: string; } interface AboveAverageRule extends SingleColorRule { type: "AboveAverageRule"; aboveAverage: boolean; equalAverage: boolean; } interface Top10Rule extends SingleColorRule { type: "Top10Rule"; percent: boolean; bottom: boolean; rank: number; } type ConditionalFormattingOperatorValues = "beginsWithText" | "isBetween" | "containsText" | "isEmpty" | "isNotEmpty" | "endsWithText" | "isEqual" | "isGreaterThan" | "isGreaterOrEqualTo" | "isLessThan" | "isLessOrEqualTo" | "isNotBetween" | "notContainsText" | "isNotEqual"; declare const availableConditionalFormatOperators: Set<ConditionalFormattingOperatorValues>; declare const PREVIOUS_VALUE = "(previous)"; declare const NEXT_VALUE = "(next)"; type Aggregator = "array_agg" | "count" | "count_distinct" | "bool_and" | "bool_or" | "max" | "min" | "avg" | "sum"; type Granularity = "day" | "week" | "month" | "quarter" | "year" | "second_number" | "minute_number" | "hour_number" | "day_of_week" | "day_of_month" | "iso_week_number" | "month_number" | "quarter_number"; interface PivotCoreDimension { fieldName: string; order?: SortDirection; granularity?: Granularity | string; } interface PivotCoreMeasure { /** * Identifier of the measure, `technicalName:aggregator{:autoIncrementedNumber}`. * It's used to identify the measure in the pivot formula. */ id: string; userDefinedName?: string; fieldName: string; aggregator: Aggregator | string; isHidden?: boolean; format?: Format; computedBy?: { sheetId: UID; formula: string; }; display?: PivotMeasureDisplay; } interface CommonPivotCoreDefinition { columns: PivotCoreDimension[]; rows: PivotCoreDimension[]; measures: PivotCoreMeasure[]; name: string; deferUpdates?: boolean; sortedColumn?: PivotSortedColumn; collapsedDomains?: PivotCollapsedDomains; } interface PivotSortedColumn { order: SortDirection; domain: PivotDomain; measure: string; } interface PivotCollapsedDomains { COL: PivotDomain[]; ROW: PivotDomain[]; } interface SpreadsheetPivotCoreDefinition extends CommonPivotCoreDefinition { type: "SPREADSHEET"; dataSet?: { sheetId: UID; zone: Zone; }; } interface FakePivotDefinition extends CommonPivotCoreDefinition { type: "FAKE"; } type PivotCoreDefinition = SpreadsheetPivotCoreDefinition | FakePivotDefinition; type TechnicalName = string; interface PivotField { name: TechnicalName; type: string; string: string; aggregator?: string; help?: string; } type PivotFields = Record<TechnicalName, PivotField | undefined>; interface PivotMeasure extends PivotCoreMeasure { displayName: string; type: string; isValid: boolean; } interface PivotDimension$1 extends PivotCoreDimension { nameWithGranularity: string; displayName: string; type: string; isValid: boolean; } interface PivotTableColumn { fields: string[]; values: CellValue[]; width: number; offset: number; } interface PivotTableRow { fields: string[]; values: CellValue[]; indent: number; } interface PivotTableData { cols: PivotTableColumn[][]; rows: PivotTableRow[]; measures: string[]; fieldsType?: Record<string, string | undefined>; } interface PivotHeaderCell { type: "HEADER"; domain: PivotDomain; dimension: Dimension; } interface PivotMeasureHeaderCell { type: "MEASURE_HEADER"; domain: PivotDomain; measure: string; } interface PivotValueCell { type: "VALUE"; domain: PivotDomain; measure: string; } interface PivotEmptyCell { type: "EMPTY"; } type PivotTableCell = PivotHeaderCell | PivotMeasureHeaderCell | PivotValueCell | PivotEmptyCell; interface PivotTimeAdapterNotNull<T> { normalizeFunctionValue: (value: Exclude<CellValue, null>) => T; toValueAndFormat: (normalizedValue: T, locale?: Locale) => FunctionResultObject; toFunctionValue: (normalizedValue: T) => string; } interface PivotTimeAdapter<T> { normalizeFunctionValue: (value: CellValue) => T | null; toValueAndFormat: (normalizedValue: T, locale?: Locale) => FunctionResultObject; toFunctionValue: (normalizedValue: T) => string; } interface PivotNode { field: string; type: string; value: CellValue; } type PivotDomain = PivotNode[]; /** Pivot domain splitted for the domain related to the pivot's rows and columns */ interface PivotColRowDomain { colDomain: PivotDomain; rowDomain: PivotDomain; } interface PivotMeasureDisplay { type: PivotMeasureDisplayType; fieldNameWithGranularity?: string; value?: string | boolean | number | typeof PREVIOUS_VALUE | typeof NEXT_VALUE; } type PivotMeasureDisplayType = "no_calculations" | "%_of_grand_total" | "%_of_col_total" | "%_of_row_total" | "%_of_parent_row_total" | "%_of_parent_col_total" | "index" | "%_of_parent_total" | "running_total" | "%_running_total" | "rank_asc" | "rank_desc" | "%_of" | "difference_from" | "%_difference_from"; interface DimensionTreeNode { value: CellValue; field: string; type: string; children: DimensionTree; width: number; } type DimensionTree = DimensionTreeNode[]; interface PivotVisibilityOptions { displayColumnHeaders: boolean; displayTotals: boolean; displayMeasuresRow: boolean; } interface GenericCriterion { type: GenericCriterionType; values: string[]; } type GenericDateCriterion = GenericCriterion & { dateValue: DateCriterionValue; }; type GenericCriterionType = "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" | "beginsWithText" | "endsWithText" | "isNotEmpty" | "isEmpty"; type DateCriterionValue = "today" | "tomorrow" | "yesterday" | "lastWeek" | "lastMonth" | "lastYear" | "exactDate"; type EvaluatedCriterion<T extends GenericCriterion = GenericCriterion> = Omit<T, "values"> & { values: CellValue[]; }; type EvaluatedDateCriterion = EvaluatedCriterion<GenericDateCriterion>; interface Table { readonly id: TableId; readonly range: Range; readonly filters: Filter[]; readonly config: TableConfig; } interface StaticTable extends Table { readonly type: "static" | "forceStatic"; } interface DynamicTable extends Omit<Table, "filters"> { readonly type: "dynamic"; } type CoreTable = StaticTable | DynamicTable; type CoreTableType = Extract<CoreTable, { type: string; }>["type"]; interface Filter { readonly id: UID; readonly rangeWithHeaders: Range; readonly col: number; /** The filtered zone doesn't includes the headers of the table */ readonly filteredRange: Range | undefined; } interface TableConfig { hasFilters: boolean; totalRow: boolean; firstColumn: boolean; lastColumn: boolean; numberOfHeaders: number; bandedRows: boolean; bandedColumns: boolean; automaticAutofill?: boolean; styleId: string; } interface ComputedTableStyle { borders: Border$1[][]; styles: Style[][]; } interface TableElementStyle { border?: TableBorder; style?: Style; size?: number; } interface TableBorder extends Border$1 { horizontal?: BorderDescr; vertical?: BorderDescr; } interface TableStyle { category: string; displayName: string; templateName: TableStyleTemplateName; primaryColor: string; wholeTable?: TableElementStyle; firstColumnStripe?: TableElementStyle; secondColumnStripe?: TableElementStyle; firstRowStripe?: TableElementStyle; secondRowStripe?: TableElementStyle; firstColumn?: TableElementStyle; lastColumn?: TableElementStyle; headerRow?: TableElementStyle; totalRow?: TableElementStyle; } type TableStyleTemplateName = "none" | "lightColoredText" | "lightAllBorders" | "mediumAllBorders" | "lightWithHeader" | "mediumBandedBorders" | "mediumMinimalBorders" | "darkNoBorders" | "mediumWhiteBorders" | "dark"; declare const filterCriterions: GenericCriterionType[]; type FilterCriterionType = (typeof filterCriterions)[number]; declare const availableFiltersOperators: Set<FilterCriterionType>; declare const filterTextCriterionOperators: FilterCriterionType[]; declare const filterNumberCriterionOperators: FilterCriterionType[]; declare const filterDateCriterionOperators: FilterCriterionType[]; interface ValuesFilter { filterType: "values"; hiddenValues: string[]; } interface CriterionFilter { filterType: "criterion"; type: FilterCriterionType | "none"; values: string[]; dateValue?: DateCriterionValue; } type DataFilterValue = ValuesFilter | CriterionFilter; interface Dependencies { references: string[]; numbers: number[]; strings: string[]; } interface HeaderData { size?: number; isHidden?: boolean; } interface FigureData<T> { id: UID; col: HeaderIndex; row: HeaderIndex; offset: PixelPosition; width: Pixel; height: Pixel; tag: string; data: T; } interface SheetData { id: string; name: string; colNumber: number; rowNumber: number; cells: { [key: string]: string | undefined; }; styles: { [zone: string]: number; }; formats: { [zone: string]: number; }; borders: { [zone: string]: number; }; merges: string[]; figures: FigureData<any>[]; cols: { [key: number]: HeaderData; }; rows: { [key: number]: HeaderData; }; conditionalFormats: ConditionalFormat[]; dataValidationRules: DataValidationRuleData[]; tables: TableData$1[]; areGridLinesVisible?: boolean; isVisible: boolean; panes?: PaneDivision; headerGroups?: Record<Dimension, HeaderGroup[]>; color?: Color; } interface WorkbookSettings { locale: Locale; disableCellAnimations?: boolean; } type PivotData = { formulaId: string; } & PivotCoreDefinition; interface WorkbookData { version: string; sheets: SheetData[]; styles: { [key: number]: Style; }; formats: { [key: number]: Format; }; borders: { [key: number]: Border$1; }; pivots: { [key: string]: PivotData; }; pivotNextId: number; revisionId: UID; uniqueFigureIds: boolean; settings: WorkbookSettings; customTableStyles: { [key: string]: TableStyleData; }; } interface ExcelWorkbookData extends WorkbookData { sheets: ExcelSheetData[]; } interface ExcelSheetData extends Omit<SheetData, "figureTables" | "cols" | "rows"> { cellValues: { [xc: string]: CellValue | undefined; }; formulaSpillRanges: { [xc: string]: string; }; charts: FigureData<ExcelChartDefinition>[]; images: FigureData<Image$1>[]; tables: ExcelTableData[]; cols: { [key: number]: ExcelHeaderData; }; rows: { [key: number]: ExcelHeaderData; }; } interface ExcelHeaderData extends HeaderData { outlineLevel?: number; collapsed?: boolean; } interface TableData$1 { range: string; config?: TableConfig; type?: CoreTableType; } interface DataValidationRuleData extends Omit<DataValidationRule, "ranges"> { ranges: string[]; } interface ExcelTableData { range: string; filters: ExcelFilterData[]; config: TableConfig; } interface ExcelFilterData { colId: number; displayedValues: string[]; displayBlanks?: boolean; } interface TableStyleData { templateName: TableStyleTemplateName; primaryColor: string; displayName: string; } interface AbstractMessage { version: number; } interface RemoteRevisionMessage extends AbstractMessage { type: "REMOTE_REVISION"; clientId: ClientId; commands: readonly CoreCommand[]; nextRevisionId: UID; serverRevisionId: UID; timestamp?: number; } interface RevisionUndoneMessage extends AbstractMessage { type: "REVISION_UNDONE"; undoneRevisionId: UID; nextRevisionId: UID; serverRevisionId: UID; } interface RevisionRedoneMessage extends AbstractMessage { type: "REVISION_REDONE"; redoneRevisionId: UID; nextRevisionId: UID; serverRevisionId: UID; } interface ClientJoinedMessage extends AbstractMessage { type: "CLIENT_JOINED"; client: ClientWithPosition; } interface ClientLeftMessage extends AbstractMessage { type: "CLIENT_LEFT"; clientId: ClientId; } interface ClientMovedMessage extends AbstractMessage { type: "CLIENT_MOVED"; client: ClientWithPosition; } /** * Send a snapshot of the spreadsheet to the collaborative server */ interface SnapshotMessage extends AbstractMessage { type: "SNAPSHOT"; data: WorkbookData; serverRevisionId: UID; nextRevisionId: UID; } /** * Notify all clients that the server has a new snapshot of the * spreadsheet and that the previous history may be lost. */ interface SnapshotCreatedMessage extends AbstractMessage { type: "SNAPSHOT_CREATED"; serverRevisionId: UID; nextRevisionId: UID; } type CollaborationMessage = RevisionUndoneMessage | RevisionRedoneMessage | RemoteRevisionMessage | SnapshotMessage | SnapshotCreatedMessage | ClientMovedMessage | ClientJoinedMessage | ClientLeftMessage; type StateUpdateMessage = Extract<CollaborationMessage, { nextRevisionId: UID; }>; type NewMessageCallback<T = any> = (message: T) => void; /** * The transport service allows to communicate between multiple clients. * A client can send any message to others. * The service will handle all networking details internally. */ interface TransportService<T = any> { /** * Send a message to all clients */ sendMessage: (message: T) => Promise<void>; /** * Register a callback function which will be called each time * a new message is received. * The new message is given to the callback. * * ```js * transportService.onNewMessage(id, (message) => { * // ... handle the new message * }) * ``` * The `id` is used to unregister this callback when the session is closed. */ onNewMessage: (id: UID, callback: NewMessageCallback<T>) => void; /** * Unregister a callback linked to the given id */ leave: (id: UID) => void; } declare class Revision implements RevisionData { readonly rootCommand?: Command | undefined; readonly timestamp?: number | undefined; readonly id: UID; readonly clientId: ClientId; private _commands; private _changes; /** * A revision represents a whole client action (Create a sheet, merge a Zone, Undo, ...). * A revision contains the following information: * - id: ID of the revision * - commands: CoreCommands that are linked to the action, and should be * dispatched in other clients * - clientId: Client who initiated the action * - changes: List of changes applied on the state. */ constructor(id: UID, clientId: ClientId, commands: readonly CoreCommand[], rootCommand?: Command | undefined, changes?: readonly HistoryChange[], timestamp?: number | undefined); setChanges(changes: readonly HistoryChange[]): void; get commands(): readonly CoreCommand[]; get changes(): readonly HistoryChange[]; } declare class ClientDisconnectedError extends Error { } declare class Session extends EventBus<CollaborativeEvent> { private revisions; private transportService; private serverRevisionId; /** * Positions of the others client. */ private clients; private clientId; /** * Id of the server revision */ private debouncedMove; private pendingMessages; /** * Stored position of the client, if session.move is called while the client is not in a session. * Will be used to send the position to the server when the client joins. */ private awaitingClientPosition; private waitingAck; /** * Flag used to block all commands when an undo or redo is triggered, until * it is accepted on the server */ private waitingUndoRedoAck; private isReplayingInitialRevisions; private processedRevisions; private lastRevisionMessage; private uuidGenerator; private lastLocalOperation; /** * Manages the collaboration between multiple users on the same spreadsheet. * It can forward local state changes to other users to ensure they all eventually * reach the same state. * It also manages the positions of each clients in the spreadsheet to provide * a visual indication of what other users are doing in the spreadsheet. * * @param revisions * @param transportService communication channel used to send and receive messages * between all connected clients * @param client the client connected locally * @param serverRevisionId */ constructor(revisions: SelectiveHistory<Revision>, transportService: TransportService<CollaborationMessage>, serverRevisionId?: UID); canApplyOptimisticUpdate(): boolean; /** * Add a new revision to the collaborative session. * It will be transmitted to all other connected clients. */ save(rootCommand: Command, commands: CoreCommand[], changes: HistoryChange[]): void; undo(revisionId: UID): void; redo(revisionId: UID): void; /** * Notify that the position of the client has changed */ move(position: ClientPosition): void; join(client?: Client): void; loadInitialMessages(messages: StateUpdateMessage[]): void; /** * Notify the server that the user client left the collaborative session */ leave(data?: Lazy<WorkbookData>): Promise<void>; /** * Send a snapshot of the spreadsheet to the collaboration server */ snapshot(data: WorkbookData): Promise<void>; getCurrentClient(): Client; getClient(clientId: ClientId): Client; getConnectedClients(): Set<Client>; getRevisionId(): UID; isFullySynchronized(): boolean; /** * Get the last local revision * */ getLastLocalNonEmptyRevision(): Revision | undefined; private _move; /** * Handles messages received from other clients in the collaborative * session. */ private onMessageReceived; private onClientMoved; /** * Register the new client and send your * own position back. */ private onClientJoined; private onClientLeft; private sendUpdateMessage; /** * Send the next pending message */ private sendPendingMessage; private acknowledge; private isAlreadyProcessed; isWrongServerRevisionId(message: CollaborationMessage): boolean; private dropPendingHistoryMessages; } /** * RGBA to HEX representation (#RRGGBBAA). * * https://css-tricks.com/converting-color-spaces-in-javascript/ */ declare function rgbaToHex(rgba: RGBA): Color; /** * Color string to RGBA representation */ declare function colorToRGBA(color: Color): RGBA; declare class ColorGenerator { private preferredColors; private currentColorIndex; protected palette: Color[]; constructor(paletteSize: number, preferredColors?: (Color | undefined | null)[]); next(): string; } interface SearchOptions { matchCase: boolean; exactMatch: boolean; searchFormulas: boolean; searchScope: "allSheets" | "activeSheet" | "specificRange"; specificRange?: Range; } /** * Deep copy arrays, plain objects and primitive values. * Throws an error for other types such as class instances. * Sparse arrays remain sparse. */ declare function deepCopy<T>(obj: T): T; declare function unquote(string: string, quoteChar?: "'" | '"'): string; /** Replace the excel-excluded characters of a sheetName */ declare function sanitizeSheetName(sheetName: string, replacementChar?: string): string; declare function isMarkdownLink(str: string): boolean; /** * Build a markdown link from a label and an url */ declare function markdownLink(label: string, url: string): string; declare function parseMarkdownLink(str: string): { url: string; label: string; }; /** * Th