sheet

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PropLink      = "link"      // http(s) or mailto URL
	PropNote      = "note"      // note text
	PropValidList = "validList" // allowed values, comma separated (Excel's list validation)
	PropCondFmt   = "cf"        // JSON array of CondRule
)

Props that are not formatting but belong to the cell, like Excel's hyperlinks, notes, data validation and conditional formatting. They live in the style props so they move, copy and undo with the cell.

View Source
const (
	// Limits count UTF-8 bytes, on the server (len) and in the browser
	// (TextEncoder), so both accept the same values.
	MaxLinkLength      = 2048
	MaxNoteLength      = 4000
	MaxValidListLength = 255 // Excel's limit for a list typed into the dialog
	MaxCondRules       = 8
	MaxCondValue       = 255
	// MaxCondJSON fits eight rules with two values of MaxCondValue bytes each,
	// even when JSON escapes every character of them.
	MaxCondJSON = 16384
)
View Source
const (
	MaxChartsPerSheet = 50
	MaxChartTitle     = 255
	// A chart shows at most MaxChartSeries series (plus a category column)
	// and MaxChartPoints points (plus a header row); its range may not be
	// taller than the grid.
	MaxChartSeries = 50
	MaxChartPoints = 500
)
View Source
const (
	MaxFrozenRows = 100
	MaxFrozenCols = 26
)

MaxFrozenRows and MaxFrozenCols bound setFreeze (the frozen part stays on screen, so more would leave nothing to scroll).

View Source
const (
	MaxFilterValues      = 1000
	MaxFilterValueLength = 1024
)
View Source
const MaxCidLength = 64

MaxCidLength bounds Op.Cid; clients send "<random>:<seq>".

Variables

View Source
var (
	ChartTypes = []string{"column", "bar", "line", "pie"}
)
View Source
var CondOps = map[string]int{
	"gt": 1, "lt": 1, "ge": 1, "le": 1, "eq": 1, "ne": 1,
	"between": 2, "notBetween": 2,
	"contains": 1, "notContains": 1, "beginsWith": 1, "endsWith": 1,
	"blank": 0, "notBlank": 0,
}

CondOps lists the rule operators and how many values they take.

MetaProps are kept by "Clear Formats" (Excel keeps notes, links and validation; it removes conditional formatting).

Functions

func ColumnName added in v0.7.0

func ColumnName(col int) string

ColumnName turns a zero-based column index into its letters (0 -> A).

func FilterKey added in v0.7.0

func FilterKey(v string) string

FilterKey is how filter values compare, in the server and the browser (cellFilter.ts): without case and surrounding space, and numbers by value, so Excel's "1,234.5" in an imported filter matches a cell showing 1234.5.

func ParseChartRange added in v0.7.0

func ParseChartRange(r string) (r0, c0, r1, c1 int, ok bool)

ParseChartRange reads "A1:C10" (or one cell) into zero-based bounds.

func QuoteSheetName added in v0.7.0

func QuoteSheetName(name string) string

QuoteSheetName writes a sheet name the way a formula needs it: plain when it is a simple word, otherwise in single quotes ('My Sheet', 'Q1”24').

func RewriteFormula added in v0.7.0

func RewriteFormula(raw string, e RefEdit) string

RewriteFormula returns raw with its references changed by e. Text that is not a reference (strings, function names, numbers) is kept as written, as are references the edit does not touch.

func ValidateProps added in v0.6.7

func ValidateProps(props map[string]string) error

ValidateProps allowlists style prop keys and values. Props come from arbitrary collaborators and end up as inline CSS on every viewer's DOM, so anything outside the known vocabulary is rejected (e.g. bg: "url(...)").

Types

type Cell

type Cell struct {
	Raw       string `json:"raw"`
	Value     string `json:"value,omitempty"`
	ValueType string `json:"valueType,omitempty"`
	StyleId   int    `json:"styleId"`
}

Cell is the atomic unit of a sheet. Raw is the source of truth (a literal value or a formula string like "=SUM(A1:A10)"). Value/ValueType are an optional client-reported cache of the computed result; the backend core never computes them. StyleId references the workbook StylePool.

func (Cell) IsEmpty

func (c Cell) IsEmpty() bool

IsEmpty reports whether the cell carries no content and default styling, i.e. it can be dropped from sparse storage.

func (Cell) Kind

func (c Cell) Kind() CellKind

Kind reports whether the raw content is a formula (leading '=') or a value.

type CellKind

type CellKind string

CellKind classifies a cell's raw content.

const (
	KindValue   CellKind = "value"
	KindFormula CellKind = "formula"
)

type CellRef

type CellRef struct {
	Row int
	Col int
}

CellRef is a zero-based (row, col) address within a single sheet. It is a comparable struct so it can be used directly as a map key.

type CellSnapshot

type CellSnapshot struct {
	Row       int    `json:"row"`
	Col       int    `json:"col"`
	Raw       string `json:"raw"`
	Value     string `json:"value,omitempty"`
	ValueType string `json:"valueType,omitempty"`
	StyleId   int    `json:"styleId,omitempty"`
}

CellSnapshot is the serializable form of one populated cell (map keys can't be JSON-encoded, so cells become a flat slice).

type Chart added in v0.7.0

type Chart struct {
	Id     string `json:"id"`
	Type   string `json:"type"`  // column, bar, line, pie
	Range  string `json:"range"` // e.g. A1:C10 on the same sheet, #REF! once deleted
	Title  string `json:"title,omitempty"`
	Row    int    `json:"row"`
	Col    int    `json:"col"`
	Width  int    `json:"width"`  // px
	Height int    `json:"height"` // px
}

Chart is a chart floating over a sheet, drawn by the browser from a range of the same sheet. Its top-left corner sits on cell (Row, Col); the op carries the anchor in Op.Row/Op.Col so Transform moves it like any cell.

type CondRule added in v0.7.0

type CondRule struct {
	Op    string `json:"op"`
	V1    string `json:"v1,omitempty"`
	V2    string `json:"v2,omitempty"`
	Bg    string `json:"bg,omitempty"`
	Color string `json:"color,omitempty"`
	Bold  string `json:"bold,omitempty"`
}

CondRule is one conditional-formatting rule of a cell. Op compares the cell's value with V1 (and V2 for between/notBetween); when it matches, the cell is shown with Bg, Color and Bold.

func ParseCondRules added in v0.7.0

func ParseCondRules(v string) []CondRule

ParseCondRules decodes a cf prop; nil when it is invalid.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document is the authoritative server-side state for one sheet document: the current Workbook, a monotonically growing op-log, and the head revision. It is NOT goroutine-safe; the per-document serialization goroutine (plan 2c) provides the total order, exactly as the text pad channel does.

func NewDocument

func NewDocument(wb *Workbook) *Document

func NewDocumentAt

func NewDocumentAt(wb *Workbook, log []Op) *Document

NewDocumentAt builds a Document whose workbook is already materialized to the end of log; head becomes len(log). Used when loading a persisted document (workbook from the snapshot, log from sheet_op) so stale-op rebasing keeps working after a server restart.

func (*Document) Head

func (d *Document) Head() int

func (*Document) Log

func (d *Document) Log() []Op

func (*Document) Submit

func (d *Document) Submit(op Op) (int, error)

Submit rebases an op composed against op.BaseRev past every op applied since then, applies it, appends the rebased op to the log, and returns the new head revision. The rebased op (not the original) is logged so replay is exact.

func (*Document) Workbook

func (d *Document) Workbook() *Workbook

type MergeSnapshot added in v0.6.7

type MergeSnapshot struct {
	Row  int `json:"row"`
	Col  int `json:"col"`
	Rows int `json:"rows"`
	Cols int `json:"cols"`
}

MergeSnapshot is one merged range: top-left anchor plus its span.

type Op

type Op struct {
	Type    OpType `json:"type"`
	Sheet   string `json:"sheet"`
	BaseRev int    `json:"baseRev"`

	// Cell ops (setCell, setStyle) and the top-left of a range (clearRange).
	Row int `json:"row,omitempty"`
	Col int `json:"col,omitempty"`
	// Range end (inclusive) for clearRange.
	EndRow int `json:"endRow,omitempty"`
	EndCol int `json:"endCol,omitempty"`

	// setCell payload (pointers so "unset" is distinguishable from empty).
	Raw       *string `json:"raw,omitempty"`
	Value     *string `json:"value,omitempty"`
	ValueType *string `json:"valueType,omitempty"`
	// setCell + setStyle payload.
	StyleId *int `json:"styleId,omitempty"`
	// setCell + setStyle: style properties to intern into the workbook StylePool.
	// When present, Apply interns them and sets the cell's StyleId to the result.
	Props map[string]string `json:"props,omitempty"`

	// Structural ops (insert/delete rows/cols). Index doubles as the insertion
	// position for addSheet.
	Index int `json:"index,omitempty"`
	Count int `json:"count,omitempty"`

	// Sheet-list ops. The server also fills Name on row/column inserts and
	// deletes and on deleteSheet with the sheet's name, and OldName on
	// renameSheet, so Transform can move formulas that name the sheet.
	Name    string `json:"name,omitempty"`    // addSheet, renameSheet
	OldName string `json:"oldName,omitempty"` // renameSheet (server-filled)
	ToIndex int    `json:"toIndex,omitempty"` // moveSheet

	// setDimension.
	Axis string `json:"axis,omitempty"` // "col" or "row"
	Size int    `json:"size,omitempty"` // px

	// setFreeze. 0 or 1 each (freeze first row / first col only for now).
	FrozenRows int `json:"frozenRows,omitempty"`
	FrozenCols int `json:"frozenCols,omitempty"`

	// setFilter.
	Values []string `json:"values,omitempty"`
	// Exclude: Values are the values whose rows are hidden (shorter than
	// listing what is kept when one value out of many is unchecked).
	Exclude bool `json:"exclude,omitempty"`

	// setChart / deleteChart (only Id). Order (1-based) puts a chart that is
	// not there yet at that drawing position (undo of a delete); 0 appends.
	Chart *Chart `json:"chart,omitempty"`
	Order int    `json:"order,omitempty"`
	Clear bool   `json:"clear,omitempty"`

	// Noop: Transform found nothing left to do (a filter on a column that
	// was deleted meanwhile); Apply skips the op, it only keeps the
	// revision numbering.
	Noop bool `json:"noop,omitempty"`

	// clearRange: empty the cells but keep their style props (Excel's
	// Delete / Clear Contents).
	KeepStyle bool `json:"keepStyle,omitempty"`

	// Cid is the sending client's id for the op. It is stored with the op,
	// so a client that lost the acknowledgement in a reconnect finds its op
	// in the missed ops, and a resent op is not applied twice.
	Cid string `json:"cid,omitempty"`
}

Op is one cell-based operation. BaseRev is the workbook revision the client composed it against (used by the server to rebase stale ops). Payload fields are optional per type.

func RestoreOps added in v0.7.0

func RestoreOps(cur, target *Workbook) []Op

RestoreOps returns the ops that turn cur into target: restoring an old version is ordinary ops on top of the history (which stays), live for everyone and undone like any edit.

func Transform

func Transform(in, applied Op) Op

Transform adjusts `in` so it applies cleanly after `applied`, where both were originally composed against the same base revision and `applied` was ordered first by the server. Only structural ops (row/col insert/delete) on the same sheet and axis move coordinates; everything else is returned unchanged.

func (Op) Validate

func (o Op) Validate() error

Validate checks structural invariants independent of any workbook state.

type OpType

type OpType string
const (
	OpSetCell    OpType = "setCell"
	OpSetStyle   OpType = "setStyle"
	OpClearRange OpType = "clearRange"
	OpInsertRows OpType = "insertRows"
	OpDeleteRows OpType = "deleteRows"
	OpInsertCols OpType = "insertCols"
	OpDeleteCols OpType = "deleteCols"
	// Sheet-list ops: Op.Sheet names the target sheet id.
	OpAddSheet    OpType = "addSheet"
	OpRenameSheet OpType = "renameSheet"
	OpDeleteSheet OpType = "deleteSheet"
	OpMoveSheet   OpType = "moveSheet"
	// Grid metadata ops.
	OpSetDimension OpType = "setDimension"
	OpSetFreeze    OpType = "setFreeze"
	// Merged cells: both carry the Row/Col..EndRow/EndCol rectangle.
	OpMergeCells   OpType = "mergeCells"
	OpUnmergeCells OpType = "unmergeCells"
	// setFilter shows only the rows whose value in column Col is one of
	// Values (rows up to the header row Row always show). No Values removes
	// the column's filter; Clear removes all filters of the sheet.
	OpSetFilter OpType = "setFilter"
	// setChart adds or replaces the chart Chart.Id, anchored at (Row, Col);
	// deleteChart removes the chart Chart.Id.
	OpSetChart    OpType = "setChart"
	OpDeleteChart OpType = "deleteChart"
)

type RefEdit added in v0.7.0

type RefEdit struct {
	// Target is the name of the sheet the op changes.
	Target string
	// OnTarget: the formula is on that sheet, so references without a sheet
	// name point into it.
	OnTarget bool
	// Axis is "row" or "col" for an insert/delete; Delta > 0 inserts Delta
	// rows/columns at Index, Delta < 0 deletes -Delta of them from Index on.
	Axis  string
	Index int
	Delta int
	// Rename is the sheet's new name (renameSheet).
	Rename string
	// Deleted: the sheet is deleted (deleteSheet).
	Deleted bool
}

RefEdit describes how an op changes the cell references in formulas: inserting or deleting rows/columns moves them, renaming a sheet renames them, deleting a sheet breaks them (#REF!), as in Excel.

formularefs.ts ports this exactly; both read testdata/formularefs.json.

type Sheet

type Sheet struct {
	Id    string           `json:"id"`
	Name  string           `json:"name"`
	Cells map[CellRef]Cell `json:"-"` // sparse; JSON handled by the snapshot/persistence layer
	// Sparse per-index pixel overrides; unset = view default.
	ColWidths  map[int]int `json:"-"`
	RowHeights map[int]int `json:"-"`
	// Number of frozen top rows / left columns (position: sticky in the view).
	FrozenRows int `json:"-"`
	FrozenCols int `json:"-"`
	// Merged-cell ranges keyed by top-left anchor. Non-anchor cells keep their
	// content (hidden by the view); unmerge reveals it again.
	Merges map[CellRef]Span `json:"-"`
	// Filters: column -> the values whose rows are shown. Rows up to
	// FilterRow (the header) always show.
	Filters   map[int][]string `json:"-"`
	FilterRow int              `json:"-"`
	// FilterHide marks the columns whose Filters list the hidden values
	// instead of the shown ones.
	FilterHide map[int]bool `json:"-"`
	// Charts in drawing order (later ones on top).
	Charts []Chart `json:"-"`
}

Sheet is a single tab: sparse cells plus structural metadata.

func NewSheet

func NewSheet(id, name string) *Sheet

func (*Sheet) FilterKeeps added in v0.7.0

func (s *Sheet) FilterKeeps(col int, value string) bool

FilterKeeps reports whether a column filter keeps a row with this value. Empty cells never hide a row.

func (*Sheet) GetCell

func (s *Sheet) GetCell(ref CellRef) Cell

GetCell returns the cell at ref, or the zero Cell if unset.

func (*Sheet) SetCell

func (s *Sheet) SetCell(ref CellRef, c Cell)

SetCell stores a cell, dropping it from storage if empty (keeps it sparse).

type SheetSnapshot

type SheetSnapshot struct {
	Id    string         `json:"id"`
	Name  string         `json:"name"`
	Cells []CellSnapshot `json:"cells"`
	// Sparse dimension overrides; JSON object keys are stringified indices.
	ColWidths  map[int]int     `json:"colWidths,omitempty"`
	RowHeights map[int]int     `json:"rowHeights,omitempty"`
	FrozenRows int             `json:"frozenRows,omitempty"`
	FrozenCols int             `json:"frozenCols,omitempty"`
	Merges     []MergeSnapshot `json:"merges,omitempty"`
	// Column filters; JSON object keys are stringified column indices.
	Filters   map[int][]string `json:"filters,omitempty"`
	FilterRow int              `json:"filterRow,omitempty"`
	// Columns whose filter lists the hidden values.
	FilterHide []int   `json:"filterHide,omitempty"`
	Charts     []Chart `json:"charts,omitempty"`
}

type Span added in v0.6.7

type Span struct {
	Rows int `json:"rows"`
	Cols int `json:"cols"`
}

Span is the extent of a merged-cell range, keyed by its top-left anchor. Rows/Cols >= 1; a 1x1 span is never stored.

type Style

type Style struct {
	Props map[string]string `json:"props"`
}

Style is a set of formatting properties (e.g. numFmt, bold, color, align, border). Kept as a string->string map so the pool stays format-agnostic.

type StylePool

type StylePool struct {
	IdToStyle map[int]Style `json:"idToStyle"`

	NextId int `json:"nextId"`
	// contains filtered or unexported fields
}

StylePool deduplicates styles per workbook. Id 0 is reserved for the empty style; cells default to it.

func NewStylePool

func NewStylePool() *StylePool

func (*StylePool) Get

func (p *StylePool) Get(id int) (Style, bool)

Get returns the style for an id. Id 0 is always the empty style.

func (*StylePool) Put

func (p *StylePool) Put(s Style) int

Put interns a style and returns its id (dedup by canonical key).

type Workbook

type Workbook struct {
	Sheets []*Sheet   `json:"sheets"`
	Styles *StylePool `json:"styles"`
}

Workbook is the full document: ordered sheets plus the shared StylePool.

func NewWorkbook

func NewWorkbook() *Workbook

func WorkbookFromSnapshot

func WorkbookFromSnapshot(snap WorkbookSnapshot) *Workbook

WorkbookFromSnapshot rebuilds a Workbook (and its StylePool dedup index) from a deserialized snapshot.

func (*Workbook) AddSheet

func (w *Workbook) AddSheet(id, name string) *Sheet

func (*Workbook) Apply

func (w *Workbook) Apply(op Op) error

Apply mutates the workbook by op. The op is assumed already rebased to the current revision (see reconcile.go). Cell ops are last-writer-wins; the caller's total ordering decides the winner.

func (*Workbook) Clone

func (w *Workbook) Clone() *Workbook

Clone returns a deep copy so callers can simulate clients independently.

func (*Workbook) FillSheetNames added in v0.7.0

func (w *Workbook) FillSheetNames(op *Op)

FillSheetNames records in op the sheet names Transform needs to move formulas typed concurrently: the sheet's name on row/column inserts and deletes and on deleteSheet, the old name on renameSheet. Called on the server before an op is applied and stored; what the client sent there is replaced.

func (*Workbook) SheetByID

func (w *Workbook) SheetByID(id string) *Sheet

func (*Workbook) Snapshot

func (w *Workbook) Snapshot() WorkbookSnapshot

Snapshot converts the workbook to its serializable form. Cells are emitted in (row, col) order for deterministic output.

type WorkbookSnapshot

type WorkbookSnapshot struct {
	Sheets []SheetSnapshot `json:"sheets"`
	Styles *StylePool      `json:"styles"`
}

WorkbookSnapshot is the JSON-serializable form of a Workbook for persistence.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL