2022-02-19 09:46:49 +00:00
|
|
|
// Provide a way to access grist for iframe, web worker (which runs the main safeBrowser script) and
|
2020-07-21 13:20:51 +00:00
|
|
|
// unsafeNode. WebView should work the same way as iframe, grist is exposed just the same way and
|
|
|
|
// necessary api is exposed using preload script. Here we bootstrap from channel capabilities to key
|
|
|
|
// parts of the grist API.
|
|
|
|
|
|
|
|
// For iframe (and webview):
|
|
|
|
// user will add '<script src="/grist-api.js"></script>' and get a window.grist
|
|
|
|
|
|
|
|
// For web worker:
|
|
|
|
// use will add `self.importScripts('/grist-api.js');`
|
|
|
|
|
|
|
|
// For node, user will do something like:
|
|
|
|
// const {grist} = require('grist-api');
|
|
|
|
// grist.registerFunction();
|
|
|
|
// In TypeScript:
|
|
|
|
// import {grist} from 'grist-api';
|
|
|
|
// grist.registerFunction();
|
|
|
|
|
|
|
|
// tslint:disable:no-console
|
|
|
|
|
2022-02-08 15:23:14 +00:00
|
|
|
import { ColumnsToMap, CustomSectionAPI, InteractionOptions, InteractionOptionsRequest,
|
|
|
|
WidgetColumnMap } from './CustomSectionAPI';
|
2022-07-19 15:39:49 +00:00
|
|
|
import { AccessTokenOptions, AccessTokenResult, GristAPI, GristDocAPI,
|
|
|
|
GristView, RPC_GRISTAPI_INTERFACE } from './GristAPI';
|
2020-08-13 18:13:16 +00:00
|
|
|
import { RowRecord } from './GristData';
|
2020-07-21 13:20:51 +00:00
|
|
|
import { ImportSource, ImportSourceAPI, InternalImportSourceAPI } from './InternalImportSourceAPI';
|
2020-08-21 21:14:42 +00:00
|
|
|
import { decodeObject, mapValues } from './objtypes';
|
2020-07-21 13:20:51 +00:00
|
|
|
import { RenderOptions, RenderTarget } from './RenderOptions';
|
2022-03-15 14:35:15 +00:00
|
|
|
import { TableOperations } from './TableOperations';
|
|
|
|
import { TableOperationsImpl } from './TableOperationsImpl';
|
2020-07-21 13:20:51 +00:00
|
|
|
import { checkers } from './TypeCheckers';
|
2022-01-12 13:30:51 +00:00
|
|
|
import { WidgetAPI } from './WidgetAPI';
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
export * from './TypeCheckers';
|
|
|
|
export * from './FileParserAPI';
|
|
|
|
export * from './GristAPI';
|
2022-05-24 20:22:41 +00:00
|
|
|
export * from './GristData';
|
2020-07-21 13:20:51 +00:00
|
|
|
export * from './GristTable';
|
|
|
|
export * from './ImportSourceAPI';
|
|
|
|
export * from './StorageAPI';
|
|
|
|
export * from './RenderOptions';
|
2022-01-12 13:30:51 +00:00
|
|
|
export * from './WidgetAPI';
|
|
|
|
export * from './CustomSectionAPI';
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
import {IRpcLogger, Rpc} from 'grain-rpc';
|
2023-09-19 18:44:22 +00:00
|
|
|
import isEqual from 'lodash/isEqual';
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
export const rpc: Rpc = new Rpc({logger: createRpcLogger()});
|
|
|
|
|
|
|
|
export const api = rpc.getStub<GristAPI>(RPC_GRISTAPI_INTERFACE, checkers.GristAPI);
|
|
|
|
export const coreDocApi = rpc.getStub<GristDocAPI>('GristDocAPI@grist', checkers.GristDocAPI);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Interface for the records backing a custom widget.
|
|
|
|
*/
|
2020-07-21 13:20:51 +00:00
|
|
|
export const viewApi = rpc.getStub<GristView>('GristView', checkers.GristView);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Interface for the state of a custom widget.
|
|
|
|
*/
|
2022-01-12 13:30:51 +00:00
|
|
|
export const widgetApi = rpc.getStub<WidgetAPI>('WidgetAPI', checkers.WidgetAPI);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Interface for the mapping of a custom widget.
|
|
|
|
*/
|
2022-01-12 13:30:51 +00:00
|
|
|
export const sectionApi = rpc.getStub<CustomSectionAPI>('CustomSectionAPI', checkers.CustomSectionAPI);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
2023-09-26 20:37:27 +00:00
|
|
|
export const commandApi = rpc.getStub<any>('CommandAPI');
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* Shortcut for [[GristView.allowSelectBy]].
|
|
|
|
*/
|
2022-02-01 19:51:40 +00:00
|
|
|
export const allowSelectBy = viewApi.allowSelectBy;
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Shortcut for [[GristView.setSelectedRows]].
|
|
|
|
*/
|
2022-02-01 19:51:40 +00:00
|
|
|
export const setSelectedRows = viewApi.setSelectedRows;
|
2020-08-21 21:14:42 +00:00
|
|
|
|
2023-10-10 12:54:50 +00:00
|
|
|
/**
|
|
|
|
* Sets the cursor position in a linked section.
|
|
|
|
*/
|
2023-08-28 09:16:17 +00:00
|
|
|
export const setCursorPos = viewApi.setCursorPos;
|
|
|
|
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* Fetches data backing the widget as for [[GristView.fetchSelectedTable]],
|
|
|
|
* but decoding data by default, replacing e.g. ['D', timestamp] with
|
|
|
|
* a moment date. Option `keepEncoded` skips the decoding step.
|
|
|
|
*/
|
2022-05-24 20:22:41 +00:00
|
|
|
export async function fetchSelectedTable(options: {keepEncoded?: boolean} = {}) {
|
2022-03-23 13:41:34 +00:00
|
|
|
const table = await viewApi.fetchSelectedTable();
|
|
|
|
return options.keepEncoded ? table :
|
|
|
|
mapValues<any[], any[]>(table, (col) => col.map(decodeObject));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Fetches current selected record as for [[GristView.fetchSelectedRecord]],
|
|
|
|
* but decoding data by default, replacing e.g. ['D', timestamp] with
|
|
|
|
* a moment date. Option `keepEncoded` skips the decoding step.
|
|
|
|
*/
|
|
|
|
export async function fetchSelectedRecord(rowId: number, options: {keepEncoded?: boolean} = {}) {
|
|
|
|
const rec = await viewApi.fetchSelectedRecord(rowId);
|
|
|
|
return options.keepEncoded ? rec :
|
|
|
|
mapValues(rec, decodeObject);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A collection of methods for fetching document data. The
|
|
|
|
* fetchSelectedTable and fetchSelectedRecord methods are
|
|
|
|
* overridden to decode data by default.
|
|
|
|
*/
|
2020-08-21 21:14:42 +00:00
|
|
|
export const docApi: GristDocAPI & GristView = {
|
2020-07-21 13:20:51 +00:00
|
|
|
...coreDocApi,
|
|
|
|
...viewApi,
|
2022-03-23 13:41:34 +00:00
|
|
|
fetchSelectedTable,
|
|
|
|
fetchSelectedRecord,
|
2020-07-21 13:20:51 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const on = rpc.on.bind(rpc);
|
|
|
|
|
2022-02-16 11:27:06 +00:00
|
|
|
// Exposing widgetApi methods in a module scope.
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Shortcut for [[WidgetAPI.getOption]]
|
|
|
|
*/
|
2022-02-16 11:27:06 +00:00
|
|
|
export const getOption = widgetApi.getOption.bind(widgetApi);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Shortcut for [[WidgetAPI.setOption]]
|
|
|
|
*/
|
2022-02-16 11:27:06 +00:00
|
|
|
export const setOption = widgetApi.setOption.bind(widgetApi);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Shortcut for [[WidgetAPI.setOptions]]
|
|
|
|
*/
|
2022-02-16 11:27:06 +00:00
|
|
|
export const setOptions = widgetApi.setOptions.bind(widgetApi);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Shortcut for [[WidgetAPI.getOptions]]
|
|
|
|
*/
|
2022-02-16 11:27:06 +00:00
|
|
|
export const getOptions = widgetApi.getOptions.bind(widgetApi);
|
2022-03-23 13:41:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Shortcut for [[WidgetAPI.clearOptions]]
|
|
|
|
*/
|
2022-02-16 11:27:06 +00:00
|
|
|
export const clearOptions = widgetApi.clearOptions.bind(widgetApi);
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* Get access to a table in the document. If no tableId specified, this
|
|
|
|
* will use the current selected table (for custom widgets).
|
|
|
|
* If a table does not exist, there will be no error until an operation
|
|
|
|
* on the table is attempted.
|
|
|
|
*/
|
2022-03-16 18:33:48 +00:00
|
|
|
export function getTable(tableId?: string): TableOperations {
|
|
|
|
return new TableOperationsImpl({
|
|
|
|
async getTableId() {
|
|
|
|
return tableId || await getSelectedTableId();
|
|
|
|
},
|
|
|
|
throwError(verb, text, status) {
|
|
|
|
throw new Error(text);
|
|
|
|
},
|
|
|
|
applyUserActions(actions, opts) {
|
|
|
|
return docApi.applyUserActions(actions, opts);
|
|
|
|
},
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
|
2022-07-19 15:39:49 +00:00
|
|
|
/**
|
|
|
|
* Get an access token, for making API calls outside of the custom widget
|
2022-07-27 19:29:20 +00:00
|
|
|
* API. There is no caching of tokens. The returned token can
|
|
|
|
* be used to authorize regular REST API calls that access the content of the
|
|
|
|
* document. For example, in a custom widget for a table with a `Photos` column
|
|
|
|
* containing attachments, the following code will update the `src` of an
|
|
|
|
* image with id `the_image` to show the attachment:
|
|
|
|
* ```js
|
|
|
|
* grist.onRecord(async (record) => {
|
|
|
|
* const tokenInfo = await grist.docApi.getAccessToken({readOnly: true});
|
|
|
|
* const img = document.getElementById('the_image');
|
|
|
|
* const id = record.Photos[0]; // get an id of an attachment - there could be several
|
|
|
|
* // in a cell, for this example we just take the first.
|
|
|
|
* const src = `${tokenInfo.baseUrl}/attachments/${id}/download?auth=${tokenInfo.token}`;
|
|
|
|
* img.setAttribute('src', src);
|
|
|
|
* });
|
|
|
|
* ```
|
2022-07-19 15:39:49 +00:00
|
|
|
*/
|
|
|
|
export async function getAccessToken(options?: AccessTokenOptions): Promise<AccessTokenResult> {
|
|
|
|
return docApi.getAccessToken(options || {});
|
|
|
|
}
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* Get the current selected table (for custom widgets).
|
|
|
|
*/
|
2022-03-16 18:33:48 +00:00
|
|
|
export const selectedTable: TableOperations = getTable();
|
|
|
|
|
|
|
|
// Get the ID of the current selected table (for custom widgets).
|
|
|
|
// Will wait for the table ID to be set.
|
|
|
|
export async function getSelectedTableId(): Promise<string> {
|
|
|
|
await _initialization;
|
|
|
|
return _tableId!;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the ID of the current selected table if set (for custom widgets).
|
|
|
|
// The ID may take some time to be set, or may never be set if the widget
|
|
|
|
// is not linked to anything.
|
|
|
|
export function getSelectedTableIdSync(): string|undefined {
|
|
|
|
return _tableId;
|
|
|
|
}
|
2022-03-15 14:35:15 +00:00
|
|
|
|
2022-02-08 15:23:14 +00:00
|
|
|
// For custom widgets that support custom columns mappings store current configuration
|
|
|
|
// in a memory.
|
|
|
|
|
|
|
|
// Actual cached value. Undefined means that widget hasn't asked for configuration yet.
|
|
|
|
// Here we are storing serialized configuration instead of actual one, since widget can
|
|
|
|
// mutate returned value.
|
|
|
|
let _mappingsCache: WidgetColumnMap|null|undefined;
|
|
|
|
// Since widget needs to ask for mappings during onRecord and onRecords event, we will reuse
|
|
|
|
// current request if available;
|
|
|
|
let _activeRefreshReq: Promise<void>|null = null;
|
|
|
|
// Remember columns requested during ready call.
|
|
|
|
let _columnsToMap: ColumnsToMap|undefined;
|
2022-03-15 14:35:15 +00:00
|
|
|
let _tableId: string|undefined;
|
|
|
|
let _setInitialized: () => void;
|
|
|
|
const _initialization = new Promise<void>(resolve => _setInitialized = resolve);
|
|
|
|
let _readyCalled: boolean = false;
|
2022-02-08 15:23:14 +00:00
|
|
|
|
|
|
|
async function getMappingsIfChanged(data: any): Promise<WidgetColumnMap|null> {
|
|
|
|
const uninitialized = _mappingsCache === undefined;
|
|
|
|
if (data.mappingsChange || uninitialized) {
|
|
|
|
// If no active request.
|
|
|
|
if (!_activeRefreshReq) {
|
|
|
|
// Request for new mappings.
|
|
|
|
_activeRefreshReq = sectionApi
|
|
|
|
.mappings()
|
|
|
|
// Store it in global variable.
|
|
|
|
.then(mappings => void (_mappingsCache = mappings))
|
|
|
|
// Clear current request variable.
|
|
|
|
.finally(() => _activeRefreshReq = null);
|
|
|
|
}
|
|
|
|
await _activeRefreshReq;
|
|
|
|
}
|
|
|
|
return _mappingsCache ? JSON.parse(JSON.stringify(_mappingsCache)) : null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Renames columns in the result using columns mapping configuration passed in ready method.
|
|
|
|
* Returns null if not all required columns were mapped or not widget doesn't support
|
|
|
|
* custom column mapping.
|
|
|
|
*/
|
2022-05-05 11:42:50 +00:00
|
|
|
export function mapColumnNames(data: any, options?: {
|
2022-03-15 14:35:15 +00:00
|
|
|
columns?: ColumnsToMap
|
|
|
|
mappings?: WidgetColumnMap|null,
|
|
|
|
reverse?: boolean,
|
2022-02-08 15:23:14 +00:00
|
|
|
}) {
|
2022-03-15 14:35:15 +00:00
|
|
|
options = {columns: _columnsToMap, mappings: _mappingsCache, reverse: false, ...options};
|
2022-05-05 11:42:50 +00:00
|
|
|
// If no column configuration was requested or
|
2022-02-08 15:23:14 +00:00
|
|
|
// table has no rows, return original data.
|
|
|
|
if (!options.columns) {
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
// If we haven't received columns configuration return null.
|
|
|
|
if (!options.mappings) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
// If we are renaming names for whole table, but it is empty, don't do anything.
|
|
|
|
if (Array.isArray(data) && data.length === 0) {
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Prepare convert function - a function that will take record returned from Grist
|
|
|
|
// and convert it to a new record with mapped field names;
|
|
|
|
// Convert function will consists of several transformations:
|
|
|
|
const transformations: ((from: any, to: any) => void)[] = [];
|
|
|
|
// First transformation is for copying id field:
|
|
|
|
transformations.push((from, to) => to.id = from.id);
|
|
|
|
// Helper function to test if a column was configured as optional.
|
|
|
|
function isOptional(col: string) {
|
|
|
|
return Boolean(
|
|
|
|
// Columns passed as strings are required.
|
2022-05-05 11:42:50 +00:00
|
|
|
!options!.columns?.includes(col)
|
|
|
|
&& options!.columns?.find(c => typeof c === 'object' && c?.name === col && c.optional)
|
2022-02-08 15:23:14 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
// For each widget column in mapping.
|
2022-03-15 14:35:15 +00:00
|
|
|
// Keys are ordered for determinism in case of conflicts.
|
|
|
|
for(const widgetCol of Object.keys(options.mappings).sort()) {
|
2022-02-08 15:23:14 +00:00
|
|
|
// Get column from Grist.
|
|
|
|
const gristCol = options.mappings[widgetCol];
|
|
|
|
// Copy column as series (multiple values)
|
|
|
|
if (Array.isArray(gristCol) && gristCol.length) {
|
2022-03-15 14:35:15 +00:00
|
|
|
if (!options.reverse) {
|
|
|
|
transformations.push((from, to) => {
|
|
|
|
to[widgetCol] = gristCol.map(col => from[col]);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
transformations.push((from, to) => {
|
|
|
|
for (const [idx, col] of gristCol.entries()) {
|
|
|
|
to[col] = from[widgetCol]?.[idx];
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2022-02-08 15:23:14 +00:00
|
|
|
// Copy column directly under widget column name.
|
|
|
|
} else if (!Array.isArray(gristCol) && gristCol) {
|
2022-03-15 14:35:15 +00:00
|
|
|
if (!options.reverse) {
|
|
|
|
transformations.push((from, to) => to[widgetCol] = from[gristCol]);
|
|
|
|
} else {
|
|
|
|
transformations.push((from, to) => to[gristCol] = from[widgetCol]);
|
|
|
|
}
|
2022-02-08 15:23:14 +00:00
|
|
|
} else if (!isOptional(widgetCol)) {
|
|
|
|
// Column was not configured but was required.
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Finally assemble function to convert a single record.
|
|
|
|
const convert = (rec: any) => transformations.reduce((obj, tran) => { tran(rec, obj); return obj; }, {} as any);
|
|
|
|
// Transform all records (or a single one depending on the arguments).
|
|
|
|
return Array.isArray(data) ? data.map(convert) : convert(data);
|
|
|
|
}
|
|
|
|
|
2022-03-15 14:35:15 +00:00
|
|
|
/**
|
|
|
|
* Offer a convenient way to map data with renamed columns back into the
|
|
|
|
* form used in the original table. This is useful for making edits to the
|
|
|
|
* original table in a widget with column mappings. As for mapColumnNames(),
|
|
|
|
* we don't attempt to do these transformations automatically.
|
|
|
|
*/
|
2022-05-05 11:42:50 +00:00
|
|
|
export function mapColumnNamesBack(data: any, options?: {
|
2022-03-15 14:35:15 +00:00
|
|
|
columns?: ColumnsToMap
|
|
|
|
mappings?: WidgetColumnMap|null,
|
|
|
|
}) {
|
|
|
|
return mapColumnNames(data, {...options, reverse: true});
|
|
|
|
}
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* For custom widgets, add a handler that will be called whenever the
|
|
|
|
* row with the cursor changes - either by switching to a different row, or
|
|
|
|
* by some value within the row potentially changing. Handler may
|
|
|
|
* in the future be called with null if the cursor moves away from
|
|
|
|
* any row.
|
|
|
|
*/
|
2022-02-08 15:23:14 +00:00
|
|
|
export function onRecord(callback: (data: RowRecord | null, mappings: WidgetColumnMap | null) => unknown) {
|
2022-05-24 20:22:41 +00:00
|
|
|
// TODO: currently this will be called even if the content of a different row changes.
|
2020-08-13 18:13:16 +00:00
|
|
|
on('message', async function(msg) {
|
2022-04-11 19:33:26 +00:00
|
|
|
if (!msg.tableId || !msg.rowId || msg.rowId === 'new') { return; }
|
2020-08-13 18:13:16 +00:00
|
|
|
const rec = await docApi.fetchSelectedRecord(msg.rowId);
|
2022-02-08 15:23:14 +00:00
|
|
|
callback(rec, await getMappingsIfChanged(msg));
|
2020-08-13 18:13:16 +00:00
|
|
|
});
|
|
|
|
}
|
2022-03-23 13:41:34 +00:00
|
|
|
|
2022-04-11 19:33:26 +00:00
|
|
|
/**
|
|
|
|
* For custom widgets, add a handler that will be called whenever the
|
|
|
|
* new (blank) row is selected.
|
|
|
|
*/
|
2022-05-05 11:42:50 +00:00
|
|
|
export function onNewRecord(callback: (mappings: WidgetColumnMap | null) => unknown) {
|
2022-04-11 19:33:26 +00:00
|
|
|
on('message', async function(msg) {
|
|
|
|
if (msg.tableId && msg.rowId === 'new') {
|
2022-05-05 11:42:50 +00:00
|
|
|
callback(await getMappingsIfChanged(msg));
|
2022-04-11 19:33:26 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* For custom widgets, add a handler that will be called whenever the
|
|
|
|
* selected records change. Handler will be called with a list of records.
|
|
|
|
*/
|
2022-02-08 15:23:14 +00:00
|
|
|
export function onRecords(callback: (data: RowRecord[], mappings: WidgetColumnMap | null) => unknown) {
|
2020-08-13 18:13:16 +00:00
|
|
|
on('message', async function(msg) {
|
|
|
|
if (!msg.tableId || !msg.dataChange) { return; }
|
|
|
|
const data = await docApi.fetchSelectedTable();
|
|
|
|
if (!data.id) { return; }
|
|
|
|
const rows: RowRecord[] = [];
|
|
|
|
for (let i = 0; i < data.id.length; i++) {
|
|
|
|
const row: RowRecord = {id: data.id[i]};
|
|
|
|
for (const key of Object.keys(data)) {
|
|
|
|
row[key] = data[key][i];
|
|
|
|
}
|
|
|
|
rows.push(row);
|
|
|
|
}
|
2022-02-08 15:23:14 +00:00
|
|
|
callback(rows, await getMappingsIfChanged(msg));
|
2020-08-13 18:13:16 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* For custom widgets, add a handler that will be called whenever the
|
|
|
|
* widget options change (and on initial ready message). Handler will be
|
|
|
|
* called with an object containing saved json options, or null if no options were saved.
|
|
|
|
* The second parameter has information about the widgets relationship with
|
|
|
|
* the document that contains it.
|
|
|
|
*/
|
2022-01-12 13:30:51 +00:00
|
|
|
export function onOptions(callback: (options: any, settings: InteractionOptions) => unknown) {
|
2023-10-06 13:17:39 +00:00
|
|
|
on('message', function(msg) {
|
2022-01-12 13:30:51 +00:00
|
|
|
if (msg.settings) {
|
2023-10-06 13:17:39 +00:00
|
|
|
callback(msg.options || null, msg.settings);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Called whenever the Grist theme changes (and on initial ready message).
|
|
|
|
*/
|
|
|
|
function onThemeChange(callback: (theme: any) => unknown) {
|
|
|
|
on('message', function(msg) {
|
|
|
|
if (msg.theme) {
|
|
|
|
callback(msg.theme);
|
|
|
|
|
|
|
|
if (msg.fromReady) {
|
|
|
|
void (async function() {
|
|
|
|
await rpc.postMessage({message: 'themeInitialized'});
|
|
|
|
})();
|
|
|
|
}
|
2022-01-12 13:30:51 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Calling `addImporter(...)` adds a safeBrowser importer. It is a short-hand for forwarding calls
|
|
|
|
* to an `ImportSourceAPI` implementation registered in the file at `path`. It takes care of
|
|
|
|
* creating the stub, registering an implementation that renders the file, forward the call and
|
2022-01-12 13:30:51 +00:00
|
|
|
* dispose the view properly. If `mode` is `'inline'` embeds the view in the import modal, otherwise
|
2020-07-21 13:20:51 +00:00
|
|
|
* renders fullscreen.
|
|
|
|
*
|
|
|
|
* Notes: it assumes that file at `path` registers an `ImportSourceAPI` implementation under
|
|
|
|
* `name`. Calling `addImporter(...)` from another component than a `safeBrowser` component is not
|
|
|
|
* currently supported.
|
|
|
|
*
|
2022-03-23 13:41:34 +00:00
|
|
|
* @internal
|
2020-07-21 13:20:51 +00:00
|
|
|
*/
|
|
|
|
export async function addImporter(name: string, path: string, mode: 'fullscreen' | 'inline', options?: RenderOptions) {
|
2022-02-19 09:46:49 +00:00
|
|
|
// checker is omitted for implementation because call was already checked by grist.
|
2020-07-21 13:20:51 +00:00
|
|
|
rpc.registerImpl<InternalImportSourceAPI>(name, {
|
|
|
|
async getImportSource(target: RenderTarget): Promise<ImportSource|undefined> {
|
|
|
|
const procId = await api.render(path, mode === 'inline' ? target : 'fullscreen', options);
|
|
|
|
try {
|
|
|
|
// stubName for the interface `name` at forward destination `path`
|
|
|
|
const stubName = `${name}@${path}`;
|
|
|
|
// checker is omitted in stub because call will be checked just after in grist.
|
|
|
|
return await rpc.getStub<ImportSourceAPI>(stubName).getImportSource();
|
|
|
|
} finally {
|
|
|
|
await api.dispose(procId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-09-26 20:37:27 +00:00
|
|
|
export function enableKeyboardShortcuts() {
|
|
|
|
const Mousetrap = require('mousetrap');
|
|
|
|
Mousetrap.bind('mod+z', () => commandApi.run('undo'));
|
|
|
|
Mousetrap.bind(['mod+shift+z', 'ctrl+y'], () => commandApi.run('redo'));
|
|
|
|
}
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/**
|
|
|
|
* Options when initializing connection to Grist.
|
|
|
|
*/
|
|
|
|
export interface ReadyPayload extends Omit<InteractionOptionsRequest, "hasCustomOptions"> {
|
2022-02-08 15:23:14 +00:00
|
|
|
/**
|
|
|
|
* Handler that will be called by Grist to open additional configuration panel inside the Custom Widget.
|
|
|
|
*/
|
(core) Speed up and upgrade build.
Summary:
- Upgrades to build-related packages:
- Upgrade typescript, related libraries and typings.
- Upgrade webpack, eslint; add tsc-watch, node-dev, eslint_d.
- Build organization changes:
- Build webpack from original typescript, transpiling only; with errors still
reported by a background tsc watching process.
- Typescript-related changes:
- Reduce imports of AWS dependencies (very noticeable speedup)
- Avoid auto-loading global @types
- Client code is now built with isolatedModules flag (for safe transpilation)
- Use allowJs to avoid copying JS files manually.
- Linting changes
- Enhance Arcanist ESLintLinter to run before/after commands, and set up to use eslint_d
- Update eslint config, and include .eslintignore to avoid linting generated files.
- Include a bunch of eslint-prompted and eslint-generated fixes
- Add no-unused-expression rule to eslint, and fix a few warnings about it
- Other items:
- Refactor cssInput to avoid circular dependency
- Remove a bit of unused code, libraries, dependencies
Test Plan: No behavior changes, all existing tests pass. There are 30 tests fewer reported because `test_gpath.py` was removed (it's been unused for years)
Reviewers: paulfitz
Reviewed By: paulfitz
Subscribers: paulfitz
Differential Revision: https://phab.getgrist.com/D3498
2022-06-27 20:09:41 +00:00
|
|
|
onEditOptions?: () => unknown;
|
2022-02-08 15:23:14 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Declare that a component is prepared to receive messages from the outside world.
|
|
|
|
* Grist will not attempt to communicate with it until this method is called.
|
|
|
|
*/
|
2022-02-08 15:23:14 +00:00
|
|
|
export function ready(settings?: ReadyPayload): void {
|
2022-03-15 14:35:15 +00:00
|
|
|
// Make it safe for this method to be called multiple times.
|
|
|
|
if (_readyCalled) { return; }
|
|
|
|
_readyCalled = true;
|
|
|
|
|
2022-01-12 13:30:51 +00:00
|
|
|
if (settings && settings.onEditOptions) {
|
|
|
|
rpc.registerFunc('editOptions', settings.onEditOptions);
|
|
|
|
}
|
2022-03-15 14:35:15 +00:00
|
|
|
on('message', async function(msg) {
|
|
|
|
if (msg.tableId && msg.tableId !== _tableId) {
|
|
|
|
if (!_tableId) { _setInitialized(); }
|
|
|
|
_tableId = msg.tableId;
|
|
|
|
}
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
rpc.processIncoming();
|
2022-01-12 13:30:51 +00:00
|
|
|
void (async function() {
|
|
|
|
await rpc.sendReadyMessage();
|
|
|
|
if (settings) {
|
2022-02-08 15:23:14 +00:00
|
|
|
const options = {
|
|
|
|
...(settings),
|
|
|
|
hasCustomOptions: Boolean(settings.onEditOptions),
|
|
|
|
};
|
|
|
|
delete options.onEditOptions;
|
|
|
|
_columnsToMap = options.columns;
|
|
|
|
await sectionApi.configure(options).catch((err: unknown) => console.error(err));
|
2022-01-12 13:30:51 +00:00
|
|
|
}
|
|
|
|
})();
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/** @internal */
|
2020-07-21 13:20:51 +00:00
|
|
|
function getPluginPath(location: Location) {
|
|
|
|
return location.pathname.replace(/^\/plugins\//, '');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof window !== 'undefined') {
|
|
|
|
// Window or iframe.
|
|
|
|
const preloadWindow: any = window;
|
|
|
|
if (preloadWindow.isRunningUnderElectron) {
|
|
|
|
rpc.setSendMessage(msg => preloadWindow.sendToHost(msg));
|
|
|
|
preloadWindow.onGristMessage((data: any) => rpc.receiveMessage(data));
|
|
|
|
} else {
|
|
|
|
rpc.setSendMessage(msg => window.parent.postMessage(msg, "*"));
|
|
|
|
window.onmessage = (e: MessageEvent) => rpc.receiveMessage(e.data);
|
|
|
|
}
|
2020-10-09 21:39:13 +00:00
|
|
|
|
|
|
|
// Allow outer Grist application to trigger printing. This is similar to using
|
|
|
|
// iframe.contentWindow.print(), but that call does not work cross-domain.
|
|
|
|
rpc.registerFunc("print", () => window.print());
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
} else if (typeof process === 'undefined') {
|
|
|
|
// Web worker. We can't really bring in the types for WebWorker (available with --lib flag)
|
|
|
|
// without conflicting with a regular window, so use just use `self as any` here.
|
|
|
|
self.onmessage = (e: MessageEvent) => rpc.receiveMessage(e.data);
|
|
|
|
rpc.setSendMessage((mssg: any) => (self as any).postMessage(mssg));
|
|
|
|
} else if (typeof process.send !== 'undefined') {
|
|
|
|
// Forked ChildProcess of node or electron.
|
|
|
|
// sendMessage callback returns void 0 because rpc process.send returns a boolean and rpc
|
|
|
|
// expecting void|Promise interprets truthy values as Promise which cause failure.
|
|
|
|
rpc.setSendMessage((data) => { process.send!(data); });
|
|
|
|
process.on('message', (data: any) => rpc.receiveMessage(data));
|
|
|
|
process.on('disconnect', () => { process.exit(0); });
|
|
|
|
} else {
|
|
|
|
// Not a recognized environment, perhaps plain nodejs run independently of Grist, or tests
|
2022-02-19 09:46:49 +00:00
|
|
|
// running under mocha. For now, we only provide a dysfunctional implementation. It allows
|
2020-07-21 13:20:51 +00:00
|
|
|
// plugins to call methods like registerFunction() without failing, so that plugin code may be
|
|
|
|
// imported, but the methods don't do anything useful.
|
2021-05-23 17:43:11 +00:00
|
|
|
rpc.setSendMessage((data) => { return; });
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2022-03-23 13:41:34 +00:00
|
|
|
/** @internal */
|
2020-07-21 13:20:51 +00:00
|
|
|
function createRpcLogger(): IRpcLogger {
|
|
|
|
let prefix: string;
|
|
|
|
if (typeof window !== 'undefined') {
|
|
|
|
prefix = `PLUGIN VIEW ${getPluginPath(window.location)}:`;
|
|
|
|
} else if (typeof process === 'undefined') {
|
|
|
|
prefix = `PLUGIN VIEW ${getPluginPath(self.location)}:`;
|
|
|
|
} else if (typeof process.send !== 'undefined') {
|
|
|
|
prefix = `PLUGIN NODE ${process.env.GRIST_PLUGIN_PATH || "<unset-plugin-id>"}:`;
|
|
|
|
} else {
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
info(msg: string) { console.log("%s %s", prefix, msg); },
|
|
|
|
warn(msg: string) { console.warn("%s %s", prefix, msg); },
|
|
|
|
};
|
|
|
|
}
|
2023-09-19 18:44:22 +00:00
|
|
|
|
|
|
|
let _theme: any;
|
|
|
|
|
2023-10-06 13:17:39 +00:00
|
|
|
onThemeChange((newTheme) => {
|
|
|
|
if (isEqual(newTheme, _theme)) { return; }
|
|
|
|
|
|
|
|
_theme = newTheme;
|
|
|
|
attachCssThemeVars(_theme);
|
|
|
|
});
|
2023-09-19 18:44:22 +00:00
|
|
|
|
|
|
|
function attachCssThemeVars({appearance, colors}: any) {
|
|
|
|
// Prepare the custom properties needed for applying the theme.
|
|
|
|
const properties = Object.entries(colors)
|
|
|
|
.map(([name, value]) => `--grist-theme-${name}: ${value};`);
|
|
|
|
|
|
|
|
// Include properties for styling the scrollbar.
|
|
|
|
properties.push(...getCssScrollbarProperties(appearance));
|
|
|
|
|
|
|
|
// Apply the properties to the theme style element.
|
|
|
|
getOrCreateStyleElement('grist-theme').textContent = `:root {
|
|
|
|
${properties.join('\n')}
|
|
|
|
}`;
|
|
|
|
|
|
|
|
// Make the browser aware of the color scheme.
|
|
|
|
document.documentElement.style.setProperty(`color-scheme`, appearance);
|
|
|
|
}
|
|
|
|
|
|
|
|
function getCssScrollbarProperties(appearance: 'light' | 'dark') {
|
|
|
|
return [
|
|
|
|
'--scroll-bar-fg: ' +
|
|
|
|
(appearance === 'dark' ? '#6B6B6B;' : '#A8A8A8;'),
|
|
|
|
'--scroll-bar-hover-fg: ' +
|
|
|
|
(appearance === 'dark' ? '#7B7B7B;' : '#8F8F8F;'),
|
|
|
|
'--scroll-bar-active-fg: ' +
|
|
|
|
(appearance === 'dark' ? '#8B8B8B;' : '#7C7C7C;'),
|
|
|
|
'--scroll-bar-bg: ' +
|
|
|
|
(appearance === 'dark' ? '#2B2B2B;' : '#F0F0F0;'),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
function getOrCreateStyleElement(id: string) {
|
|
|
|
let style = document.head.querySelector(`#${id}`);
|
|
|
|
if (style) { return style; }
|
|
|
|
style = document.createElement('style');
|
|
|
|
style.setAttribute('id', id);
|
|
|
|
document.head.append(style);
|
|
|
|
return style;
|
|
|
|
}
|