2021-05-25 09:24:00 +00:00
|
|
|
import { DocModel, ViewFieldRec } from "app/client/models/DocModel";
|
2023-08-28 09:16:17 +00:00
|
|
|
import { CursorPos } from 'app/plugin/GristAPI';
|
2021-05-25 09:24:00 +00:00
|
|
|
import BaseRowModel = require("app/client/models/BaseRowModel");
|
2021-05-17 14:05:49 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Absolute position of a cell in a document
|
|
|
|
*/
|
2021-05-25 09:24:00 +00:00
|
|
|
export abstract class CellPosition {
|
|
|
|
public static equals(a: CellPosition, b: CellPosition) {
|
|
|
|
return a && b && a.colRef == b.colRef &&
|
|
|
|
a.sectionId == b.sectionId &&
|
|
|
|
a.rowId == b.rowId;
|
|
|
|
}
|
|
|
|
public static create(row: BaseRowModel, field: ViewFieldRec): CellPosition {
|
|
|
|
const rowId = row.id.peek();
|
|
|
|
const colRef = field.colRef.peek();
|
|
|
|
const sectionId = field.viewSection.peek().id.peek();
|
|
|
|
return { rowId, colRef, sectionId };
|
|
|
|
}
|
|
|
|
public sectionId: number;
|
|
|
|
public rowId: number | string;
|
|
|
|
public colRef: number;
|
2021-05-17 14:05:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Converts cursor position to cell absolute positions. Return null if the conversion is not
|
|
|
|
* possible (if cursor position doesn't have enough information)
|
|
|
|
* @param position Cursor position
|
|
|
|
* @param docModel Document model
|
|
|
|
*/
|
|
|
|
export function fromCursor(position: CursorPos, docModel: DocModel): CellPosition | null {
|
2021-05-23 17:43:11 +00:00
|
|
|
if (!position.sectionId || !position.rowId || position.fieldIndex == null) {
|
2021-05-17 14:05:49 +00:00
|
|
|
return null;
|
2021-05-23 17:43:11 +00:00
|
|
|
}
|
2021-05-17 14:05:49 +00:00
|
|
|
|
|
|
|
const section = docModel.viewSections.getRowModel(position.sectionId);
|
|
|
|
const colRef = section.viewFields().peek()[position.fieldIndex]?.colRef.peek();
|
|
|
|
|
|
|
|
const cursorPosition = {
|
2021-05-25 09:24:00 +00:00
|
|
|
rowId: position.rowId as (string | number), // TODO: cursor position is wrongly typed
|
2021-05-17 14:05:49 +00:00
|
|
|
colRef,
|
|
|
|
sectionId: position.sectionId,
|
|
|
|
};
|
|
|
|
|
|
|
|
return cursorPosition;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Converts cell's absolute position to current cursor position.
|
|
|
|
* @param position Cell's absolute position
|
|
|
|
* @param docModel DocModel
|
|
|
|
*/
|
|
|
|
export function toCursor(position: CellPosition, docModel: DocModel): CursorPos {
|
|
|
|
|
|
|
|
// translate colRef to fieldIndex
|
|
|
|
const fieldIndex = docModel.viewSections.getRowModel(position.sectionId)
|
|
|
|
.viewFields().peek()
|
|
|
|
.findIndex(x => x.colRef.peek() == position.colRef);
|
|
|
|
|
|
|
|
const cursorPosition = {
|
2021-05-25 09:24:00 +00:00
|
|
|
rowId: position.rowId as number, // this is hack, as cursor position can accept string
|
2021-05-17 14:05:49 +00:00
|
|
|
fieldIndex,
|
|
|
|
sectionId: position.sectionId
|
|
|
|
};
|
|
|
|
|
|
|
|
return cursorPosition;
|
|
|
|
}
|