Skip to Content
Grist Widgets

Helpers

The SDK's pure functions: cells, links, attachments, user actions, typed reads, page metadata.

Pure functions, exported from grist-widget-sdk (the user actions from grist-widget-sdk/actions). None needs React or Grist.

Cells

tableDataToRows(columnar)

Turns a column-oriented payload (fetchRows({ columnar: true }): { id: [1, 2], Name: ["a", "b"] }) into rows ([{ id: 1, Name: "a" }, …]), in the order of the id column.

import { tableDataToRows } from "grist-widget-sdk"

const rows = tableDataToRows<{ Name: string }>({ id: [1, 2], Name: ["Ada", "Grace"] })
// [{ id: 1, Name: "Ada" }, { id: 2, Name: "Grace" }]
console.log(rows[0]?.Name)

decodeGristValue(value, column?)

Decode a single cell from its wire format into a JS value.

import { decodeGristValue } from "grist-widget-sdk"

decodeGristValue(1717599600, { type: "DateTime:UTC" })
// → Date

decodeGristValue(["L", 1, 2], { type: "RefList:Tasks" })
// → marshalled list

decodeGristValue(["E", "TypeError", "expected number"], { type: "Numeric" })
// → { kind: "error", type: "TypeError", message: "expected number" }

If column is omitted, the codec applies type-inference based on the tag.

encodeGristValue(value, column)

Inverse — turn a JS value into the wire format Grist expects.

import { encodeGristValue } from "grist-widget-sdk"

encodeGristValue(new Date(), { type: "DateTime:UTC" }) // → epoch seconds
encodeGristValue([1, 2], { type: "RefList:Tasks" })    // → ["L", 1, 2]

isGristCellError(value)

True when value is a formula error in Grist's stored form, the ["E", type, message?] tuple that fetchRows(tableId) gives. In the section's decoded rows (w.record, w.records), a formula error is a RaisedException and a list can start with "E": use checkGristCell(type, value, { encoded: false }) there.

import { isGristCellError } from "grist-widget-sdk"

function Total({ value }: { value: unknown }) {
  return <span>{isGristCellError(value) ? "#ERROR" : String(value)}</span>
}

normalizeGristChoiceListEntries(widgetOptions)

A Choice or ChoiceList column's widgetOptions as a flat list for a dropdown: [{ value, label, fillColor?, textColor? }].

resolveGristFormulaKind(column)

A replica column's formula kind: "computed" (a formula column), "trigger" (a data column with a trigger formula), "empty_slot" or "none".

import { resolveGristFormulaKind } from "grist-widget-sdk"

resolveGristFormulaKind({ type: "Numeric", isFormula: true, formula: "$Price * $Qty" }) // "computed"
resolveGristFormulaKind({ type: "Text", isFormula: false })                              // "none"

httpUrl(value)

A link or a source from a document's data, as an absolute http: or https: URL, or undefined. Pass every URL that comes from a cell through it before it reaches an href or a src: it refuses javascript:, data: and other schemes, relative URLs, and credentials (https://bank.example@evil.example). It doesn't judge the host: an http(s) src from a cell can still load from any server the browser reaches.

<a href={httpUrl(row.Website)}>{row.Name}</a>
import { httpUrl } from "grist-widget-sdk"

httpUrl(" https://example.com/a b ") // "https://example.com/a%20b"
httpUrl("javascript:alert(1)")       // undefined

Attachments

SymbolPurpose
extractGristAttachmentIdsFromCell(cell)Every attachment id in an Attachments cell.
extractGristAttachmentId(cell)The first one.
gristAttachmentCellValue(id)The cell value for one file, ["L", id].
gristAttachmentCellValues(ids)The cell value for several, ["L", ...ids].
mergeGristAttachmentCellValue(cell, newIds)The cell with newIds added, without duplicates.
import {
  extractGristAttachmentId,
  extractGristAttachmentIdsFromCell,
  gristAttachmentCellValue,
  gristAttachmentCellValues,
  mergeGristAttachmentCellValue,
} from "grist-widget-sdk"

const cell = ["L", 12, 13]
const ids = extractGristAttachmentIdsFromCell(cell)  // ["12", "13"]
const cover = extractGristAttachmentId(cell)          // "12": the first file
const one = gristAttachmentCellValue(14)              // ["L", 14]
const both = gristAttachmentCellValues([12, 13])      // ["L", 12, 13], ready to write
const more = mergeGristAttachmentCellValue(cell, [13, 14]) // ["L", 12, 13, 14]
console.log(ids, cover, one, both, more)

Downloading and uploading need the document's REST API: useGrist()'s getAttachmentUrl, fetchAttachmentBlob and uploadAttachment.

User actions

Builders for useGrist().applyActions([...]), which applies them together, as one step of Grist's undo. They are exported from grist-widget-sdk/actions:

import { gristAddColumnAction } from "grist-widget-sdk/actions"
BuilderAction
gristAddRecordAction(tableId, values)["AddRecord", tableId, null, values]
gristUpdateRecordAction(tableId, rowId, patch)["UpdateRecord", tableId, rowId, patch]
gristRemoveRecordAction(tableId, rowId)["RemoveRecord", tableId, rowId]
gristBulkAddRecordAction(tableId, values, rowIds?)["BulkAddRecord", tableId, ids, { col: [...] }]: Grist allocates the ids unless given
gristBulkUpdateRecordAction(tableId, rowIds, values)["BulkUpdateRecord", tableId, rowIds, { col: [...] }]
gristBulkRemoveRecordAction(tableId, rowIds)["BulkRemoveRecord", tableId, rowIds]
gristAddTableAction(tableId, columns)["AddTable", tableId, columns], each column { id, type?, … }
gristAddColumnAction(tableId, colId, colInfo)["AddColumn", tableId, colId, colInfo]
gristAddVisibleColumnAction(tableId, colId, colInfo)["AddVisibleColumn", ...]: also shows it in the section
gristModifyColumnAction(tableId, colId, colInfo)["ModifyColumn", ...]
gristRenameColumnAction(tableId, colId, newColId)["RenameColumn", ...]
gristRemoveColumnAction(tableId, colId)["RemoveColumn", ...]
import type { UseGristResult } from "grist-widget-sdk"
import {
  gristAddRecordAction,
  gristAddTableAction,
  gristAddVisibleColumnAction,
  gristBulkAddRecordAction,
  gristModifyColumnAction,
  gristRemoveColumnAction,
  gristRemoveRecordAction,
  gristUpdateRecordAction,
} from "grist-widget-sdk/actions"

// One step of Grist's undo: the schema and the rows change together.
async function reorganise(w: UseGristResult) {
  await w.applyActions([
    gristAddTableAction("Archive", [{ id: "Title", type: "Text" }]),
    gristAddVisibleColumnAction("Tasks", "Owner", { type: "Text" }),
    gristModifyColumnAction("Tasks", "Due", { type: "Date" }),
    gristRemoveColumnAction("Tasks", "Legacy"),
    gristAddRecordAction("Tasks", { Title: "Write the brief" }),
    gristBulkAddRecordAction("Tasks", { Title: ["Review", "Ship"] }),
    gristUpdateRecordAction("Tasks", 1, { Done: true }),
    gristRemoveRecordAction("Tasks", 2),
  ])
}

For other actions, write the tuple: applyActions takes any GristUserActionTuple.

Typed reads

checkGristCell(type, value, options?)

{ ok: true, value }, the value a Grist type promises ("Numeric", "Ref:Tasks", "Text,Ref"…), or { ok: false, message }. useGrist() checks the mapped cells with it; use it for data read another way. See Typed reads.

options.encoded says which form a list is in, since a ChoiceList's first choice can be "L", the tag of an encoded list:

  • false: decoded, as w.record, w.records, fetchRows() and fetchRows(tableId, { columns }) give it. A formula error is then a RaisedException (or, with columns, { __error: true, type }), and a list starting with "E" is a list;
  • true: Grist's stored form, as fetchRows(tableId) gives it without columns;
  • omitted: a list starting with "L" is taken as encoded, and one starting with "E" as an encoded formula error.

In a type that accepts both a ChoiceList and a RefList, encodeGristCell wraps an empty ["L"]: it can't be told from the one choice "L".

encodeGristCell(type, value)

The reverse: a value as Grist stores it in a column of that type. Lists become ["L", ...], a Date for a Date or DateTime column becomes seconds, a Reference for a Ref column its row id; anything else, or a RefList or Attachments list already encoded, passes through. A ChoiceList value is always read as its choices, so a first choice "L" is kept: encodeGristCell("ChoiceList", ["L", "M"]) gives ["L", "L", "M"]. Give it the choices, never a list already encoded. mapBack encodes with it; use it for a write that doesn't go through mapBack, since Grist stores a bare list as an error cell. See Write data.

On this page