@atlaskit/editor-plugin-table
Version:
Table plugin for the @atlaskit/editor
86 lines (83 loc) • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createPlugin = exports.activeCellHighlightPluginKey = void 0;
var _safePlugin = require("@atlaskit/editor-common/safe-plugin");
var _state = require("@atlaskit/editor-prosemirror/state");
var _view = require("@atlaskit/editor-prosemirror/view");
var _cellSelection = require("@atlaskit/editor-tables/cell-selection");
var _utils = require("@atlaskit/editor-tables/utils");
var _types = require("../../types");
var EMPTY_STATE = {
cellPos: -1,
decorationSet: _view.DecorationSet.empty
};
var activeCellHighlightPluginKey = exports.activeCellHighlightPluginKey = new _state.PluginKey('tableActiveCellHighlight');
/**
* Returns the position of the cell containing the cursor, or -1 if the cursor
* is not in a table cell or the selection is a CellSelection.
*/
var getActiveCellPos = function getActiveCellPos(state) {
if (state.selection instanceof _cellSelection.CellSelection) {
return -1;
}
try {
var cell = (0, _utils.findCellClosestToPos)(state.selection.$from);
return cell ? cell.pos : -1;
} catch (_unused) {
return -1;
}
};
var buildState = function buildState(cellPos, state) {
if (cellPos === -1) {
return EMPTY_STATE;
}
try {
var cell = state.doc.nodeAt(cellPos);
if (!cell) {
return EMPTY_STATE;
}
var decoration = _view.Decoration.node(cellPos, cellPos + cell.nodeSize, {
class: _types.TableCssClassName.ACTIVE_CURSOR_CELL
});
return {
cellPos: cellPos,
decorationSet: _view.DecorationSet.create(state.doc, [decoration])
};
} catch (_unused2) {
return EMPTY_STATE;
}
};
var createPlugin = exports.createPlugin = function createPlugin() {
return new _safePlugin.SafePlugin({
key: activeCellHighlightPluginKey,
state: {
init: function init(_, state) {
return buildState(getActiveCellPos(state), state);
},
apply: function apply(tr, prev, _oldState, newState) {
if (tr.docChanged) {
// Doc changed — always rebuild since positions may have shifted
return buildState(getActiveCellPos(newState), newState);
}
if (!tr.selectionSet) {
// Neither doc nor selection changed — nothing to do
return prev;
}
// Selection changed — only rebuild if cursor moved to a different cell
var nextCellPos = getActiveCellPos(newState);
if (nextCellPos === prev.cellPos) {
return prev;
}
return buildState(nextCellPos, newState);
}
},
props: {
decorations: function decorations(state) {
var _activeCellHighlightP, _activeCellHighlightP2;
return (_activeCellHighlightP = (_activeCellHighlightP2 = activeCellHighlightPluginKey.getState(state)) === null || _activeCellHighlightP2 === void 0 ? void 0 : _activeCellHighlightP2.decorationSet) !== null && _activeCellHighlightP !== void 0 ? _activeCellHighlightP : _view.DecorationSet.empty;
}
}
});
};