spreadjs_zh.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. /**
  2. * Spreadjs 通用方法集
  3. *
  4. * @author Mai
  5. * @date 2018/02/06
  6. * @version
  7. */
  8. const spreadNS = GC.Spread.Sheets;
  9. const SpreadJsObj = {
  10. DataType: {
  11. Data: 'data',
  12. Tree: 'tree',
  13. },
  14. /**
  15. * 创建Spread(默认1张表,3行数据)
  16. * @param obj 用于创建spreadjs的Dom元素
  17. * @returns {GC.Spread.Sheets.Workbook}
  18. */
  19. createNewSpread: function (obj) {
  20. const spread = new spreadNS.Workbook(obj, {sheetCount: 1});
  21. spread.options.tabStripVisible = false;
  22. spread.options.scrollbarMaxAlign = true;
  23. spread.options.cutCopyIndicatorVisible = false;
  24. spread.options.allowCopyPasteExcelStyle = false;
  25. spread.options.allowUserDragDrop = false;
  26. spread.options.allowUserEditFormula = false;
  27. spread.getActiveSheet().options.clipBoardOptions = GC.Spread.Sheets.ClipboardPasteOptions.values;//设置粘贴时只粘贴值
  28. spread.getActiveSheet().setRowCount(3);
  29. return spread;
  30. },
  31. /**
  32. * 保护sheet(需设置保护后, 单元格的locked等属性方可生效)
  33. * @param {GC.Spread.Sheets.Worksheet} sheet
  34. */
  35. protectedSheet: function (sheet) {
  36. const option = {
  37. allowSelectLockedCells: true,
  38. allowSelectUnlockedCells: true,
  39. allowResizeRows: true,
  40. allowResizeColumns: true
  41. };
  42. sheet.options.protectionOptions = option;
  43. sheet.options.isProtected = true;
  44. sheet.options.allowCellOverflow = false;
  45. },
  46. /**
  47. * sheet批量操作优化(sheet操作大批量数据时, 屏蔽数据刷新, 可优化大量时间)
  48. * @param {GC.Spread.Sheets.Worksheet} sheet
  49. * @param {function} operation
  50. */
  51. beginMassOperation: function (sheet) {
  52. sheet.suspendPaint();
  53. sheet.suspendEvent();
  54. },
  55. endMassOperation: function (sheet) {
  56. sheet.resumeEvent();
  57. sheet.resumePaint();
  58. },
  59. massOperationSheet: function (sheet, operation) {
  60. this.beginMassOperation(sheet);
  61. operation();
  62. this.endMassOperation(sheet);
  63. },
  64. /**
  65. * 获取Obj左顶点位置(部分功能需通过spreadjs左顶点位置计算)
  66. * @param obj
  67. * @returns {{x: number, y: number}}
  68. */
  69. getObjPos: function (obj) {
  70. let target = obj;
  71. let pos = {x: obj.offsetLeft, y: obj.offsetTop};
  72. target = obj.offsetParent;
  73. while (target) {
  74. pos.x += target.offsetLeft;
  75. pos.y += target.offsetTop;
  76. target = target.offsetParent;
  77. }
  78. return pos;
  79. },
  80. /**
  81. * 以下四个方法来自Spread示例, 参见官网或文档
  82. */
  83. getHitTest: function (obj, e, sheet) {
  84. var offset = obj.offset(),
  85. x = e.pageX - offset.left,
  86. y = e.pageY - offset.top;
  87. return sheet.hitTest(x, y);
  88. },
  89. getTargetSelection: function (sheet, target) {
  90. if (target.hitTestType === spreadNS.SheetArea.colHeader) {
  91. return sheet.getRange(-1, target.col, sheet.getRowCount(), 1);
  92. } else if (target.hitTestType === spreadNS.SheetArea.rowHeader) {
  93. return sheet.getRange(target.row, -1, 1, sheet.getColumnCount());
  94. } else if (target.hitTestType === spreadNS.SheetArea.viewport) {
  95. return sheet.getRange(target.row, target.col, 1, 1);
  96. } else if (target.hitTestType === spreadNS.SheetArea.corner) {
  97. return sheet.getRange(-1, -1, sheet.getRowCount(), sheet.getColumnCount());
  98. };
  99. },
  100. getCellInSelections: function (selections, row, col) {
  101. const count = selections.length;
  102. let range;
  103. for (var i = 0; i < count; i++) {
  104. range = selections[i];
  105. if (range.contains(row, col)) {
  106. return range;
  107. }
  108. }
  109. return null;
  110. },
  111. checkTargetInSelection: function (selections, range) {
  112. var count = selections.length, sel;
  113. for (var i = 0; i < count; i++) {
  114. sel = selections[i];
  115. if (sel.containsRange(range)) {
  116. return true;
  117. }
  118. }
  119. return false;
  120. },
  121. /**
  122. * 获取 spread 在鼠标右键时, spread的选中区域
  123. * viewport, 选中鼠标点击单元格X, X不在原选中区域内, 则选中X
  124. * colHeader, 选中整列
  125. * rowHeader, 选中整行
  126. * corner, 全选
  127. * 该方法返回不符合需求时,可通过getHitTest/getTargetSelection/getCellInSelections/checkTargetInSelection来确定鼠标右键点击时,spread当前Sheet应选中的单元格
  128. * @param obj: 创建Spread的Dom元素(jquery-contextmenu.build方法的第一个变量可读取)
  129. * @param e: jquery-contextmenu.build方法的第二个变量
  130. * @param {GC.Spread.Sheets.Workbook} spread
  131. * @returns {*}
  132. */
  133. safeRightClickSelection: function (obj, e, spread) {
  134. const sheet = spread.getActiveSheet();
  135. const selections = sheet.getSelections(), target = this.getHitTest(obj, e, sheet), range = this.getTargetSelection(sheet, target);
  136. if (!this.checkTargetInSelection(selections, range)) {
  137. sheet.setSelection(range.row, range.col, range.rowCount, range.colCount);
  138. }
  139. return target;
  140. },
  141. /**
  142. * sheet中 使用delete键,触发EndEdited事件
  143. * @param {GC.Spreads.Sheets.Workbook} spread
  144. * @param {function} fun
  145. */
  146. addDeleteBind: function (spread, fun) {
  147. spread.commandManager().register('deleteEvent', function () {
  148. fun(spread.getActiveSheet());
  149. });
  150. spread.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
  151. spread.commandManager().setShortcutKey('deleteEvent', GC.Spread.Commands.Key.del, false, false, false, false);
  152. },
  153. /**
  154. * 根据sheet.zh_setting初始化sheet表头
  155. * @param {GC.Spread.Sheets.Worksheet} sheet
  156. */
  157. _initSheetHeader: function (sheet) {
  158. if (!sheet.zh_setting) { return; }
  159. sheet.setColumnCount(sheet.zh_setting.cols.length);
  160. sheet.setRowCount(sheet.zh_setting.headRows, spreadNS.SheetArea.colHeader);
  161. for (let iRow = 0; iRow < sheet.zh_setting.headRowHeight.length; iRow ++) {
  162. sheet.setRowHeight(iRow, sheet.zh_setting.headRowHeight[iRow], spreadNS.SheetArea.colHeader);
  163. }
  164. for (let iCol = 0; iCol < sheet.zh_setting.cols.length; iCol++) {
  165. const col = sheet.zh_setting.cols[iCol];
  166. const title = col.title.split('|');
  167. const colSpan = col.colSpan ? col.colSpan.split('|'): ['1'], rowSpan = col.rowSpan ? col.rowSpan.split('|'): ['1'];
  168. for (let i = 0; i < title.length; i++) {
  169. const cell = sheet.getCell(i, iCol, spreadNS.SheetArea.colHeader);
  170. cell.text(title[i]).wordWrap(true);
  171. if ((colSpan[i] !== '' && colSpan[i] !== '1') || (rowSpan[i] !== '' && rowSpan[i] !== '1')) {
  172. sheet.addSpan(i, iCol, parseInt(rowSpan[i]), parseInt(colSpan[i]), spreadNS.SheetArea.colHeader);
  173. }
  174. }
  175. sheet.setColumnWidth(iCol, col.width);
  176. if (col.visible !== undefined && col.visible !== null) {
  177. sheet.setColumnVisible(iCol, col.visible);
  178. }
  179. }
  180. sheet.rowOutlines.direction(spreadNS.Outlines.OutlineDirection.backward);
  181. sheet.showRowOutline(false);
  182. if (sheet.zh_setting.defaultRowHeight) {
  183. sheet.defaults.rowHeight = sheet.zh_setting.defaultRowHeight;
  184. }
  185. },
  186. /**
  187. * 初始化sheet, 设置sheet.zh_setting, 并初始化表头
  188. * @param {GC.Spread.Sheets.Worksheet} sheet
  189. * @param setting
  190. */
  191. initSheet: function (sheet, setting) {
  192. this.beginMassOperation(sheet);
  193. sheet.zh_setting = setting;
  194. this._initSheetHeader(sheet);
  195. sheet.setRowCount(sheet.zh_setting.emptyRows);
  196. sheet.extendCellType = {};
  197. sheet.getRange(0, 0, sheet.getRowCount(), sheet.getColumnCount()).locked(setting.readOnly);
  198. this.endMassOperation(sheet);
  199. },
  200. /**
  201. * 整个sheet重新加载数据
  202. * @param {GC.Spread.Sheets.Worksheet} sheet
  203. */
  204. reLoadSheetData: function (sheet) {
  205. const self = this;
  206. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  207. this.beginMassOperation(sheet);
  208. try {
  209. sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount(), spreadNS.SheetArea.viewport, spreadNS.StorageType.data)
  210. // 设置总行数
  211. const totalRow = sortData.length + sheet.zh_setting.emptyRows;
  212. sheet.setRowCount(totalRow, spreadNS.SheetArea.viewport);
  213. // 控制空白行
  214. const emptyRows = sheet.getRange(sortData.length, -1, sheet.zh_setting.emptyRows, -1);
  215. emptyRows.locked(sheet.zh_dataType === 'tree');
  216. // 单元格写入数据
  217. sortData.forEach(function (data, i) {
  218. sheet.zh_setting.cols.forEach(function (col, j) {
  219. const cell = sheet.getCell(i, j);
  220. if (col.field !== '' && data[col.field]) {
  221. cell.value(data[col.field]).locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  222. } else {
  223. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  224. }
  225. });
  226. });
  227. // 设置列单元格格式
  228. sheet.zh_setting.cols.forEach(function (col, j) {
  229. //if (!col.cellType) { return; }
  230. if (col.cellType === 'tree') {
  231. if (!sheet.extendCellType.tree) {
  232. sheet.extendCellType.tree = self.CellType.getTreeNodeCellType();
  233. }
  234. sheet.getRange(-1, j, -1, 1).cellType(sheet.extendCellType.tree);
  235. } else if (col.cellType === 'tip') {
  236. if (!sheet.extendCellType.tip) {
  237. sheet.extendCellType.tip = self.CellType.getTipCellType();
  238. }
  239. sheet.getRange(-1, j, -1, 1).cellType(sheet.extendCellType.tip);
  240. } else if (col.cellType === 'checkbox') {
  241. if (!sheet.extendCellType.checkbox) {
  242. sheet.extendCellType.checkbox = new spreadNS.CellTypes.CheckBox();
  243. }
  244. sheet.getRange(-1, j, -1, 1).cellType(sheet.extendCellType.checkbox);
  245. }
  246. if (col.formatter) {
  247. sheet.getRange(-1, j, -1, 1).formatter(col.formatter);
  248. }
  249. });
  250. this.endMassOperation(sheet);
  251. } catch (err) {
  252. this.endMassOperation(sheet);
  253. }
  254. },
  255. _loadRowData: function (sheet, data, row) {
  256. // 单元格重新写入数据
  257. if (!data) { return }
  258. sheet.zh_setting.cols.forEach(function (col, j) {
  259. const cell = sheet.getCell(row, j);
  260. if (col.field !== '' && data[col.field]) {
  261. cell.value(data[col.field]).locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  262. } else {
  263. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  264. }
  265. if (col.formatter) {
  266. cell.formatter(col.formatter);
  267. }
  268. });
  269. },
  270. /**
  271. * 重新加载部分数据行
  272. * @param {GC.Spread.Sheets.Worksheet} sheet
  273. * @param {Number} row
  274. * @param {Number} count
  275. */
  276. reLoadRowData: function (sheet, row, count) {
  277. const self = this;
  278. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  279. this.beginMassOperation(sheet);
  280. try {
  281. // 清空原单元格数据
  282. sheet.clear(row, -1, count, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  283. // 单元格重新写入数据
  284. for (let i = row; i < row + count; i++) {
  285. const data = sortData[i];
  286. if (!data) { continue; }
  287. sheet.zh_setting.cols.forEach(function (col, j) {
  288. const cell = sheet.getCell(i, j);
  289. if (col.field !== '' && data[col.field]) {
  290. cell.value(data[col.field]).locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  291. } else {
  292. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  293. }
  294. if (col.formatter) {
  295. cell.formatter(col.formatter);
  296. }
  297. });
  298. }
  299. this.endMassOperation(sheet);
  300. } catch (err) {
  301. this.endMassOperation(sheet);
  302. }
  303. },
  304. /**
  305. * 重新加载部分行数据
  306. * @param {GC.Spread.Sheets.Worksheet} sheet
  307. * @param {Array} rows
  308. */
  309. reLoadRowsData: function (sheet, rows) {
  310. const self = this;
  311. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  312. this.beginMassOperation(sheet);
  313. try {
  314. for (const row of rows) {
  315. // 清空原单元格数据
  316. sheet.clear(row, -1, 1, -1, spreadNS.SheetArea.viewport, spreadNS.StorageType.data);
  317. const data = sortData[row];
  318. // 单元格重新写入数据
  319. sheet.zh_setting.cols.forEach(function (col, j) {
  320. // 设置值
  321. const cell = sheet.getCell(row, j);
  322. if (col.field !== '' && data[col.field]) {
  323. cell.value(data[col.field]).locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  324. } else {
  325. cell.locked(col.readOnly || sheet.zh_setting.readOnly || false).vAlign(1).hAlign(col.hAlign);
  326. }
  327. // 设置单元格格式
  328. if (col.formatter) {
  329. cell.formatter(col.formatter);
  330. }
  331. });
  332. };
  333. this.endMassOperation(sheet);
  334. } catch (err) {
  335. this.endMassOperation(sheet);
  336. }
  337. },
  338. reLoadNodesData: function (sheet, nodes) {
  339. this.beginMassOperation(sheet);
  340. nodes = nodes instanceof Array ? nodes : [nodes];
  341. for (const node of nodes) {
  342. const sortData = sheet.zh_dataType === 'tree' ? sheet.zh_tree.nodes : sheet.zh_data;
  343. this._loadRowData(sheet, node, sortData.indexOf(node));
  344. }
  345. this.endMassOperation(sheet);
  346. },
  347. /**
  348. * 根据data加载sheet数据,合并了一般数据和树结构数据的加载
  349. * @param {GC.Spread.Sheets.Worksheet} sheet
  350. * @param {String} dataType - 1.'zh_data' 2.'zh_tree'
  351. * @param {Array|PathTree} data - 对dataType对应
  352. */
  353. loadSheetData: function (sheet, dataType, data){
  354. sheet.zh_dataType = dataType;
  355. if (dataType === 'tree') {
  356. sheet.zh_tree = data;
  357. } else {
  358. sheet.zh_data = data;
  359. }
  360. this.protectedSheet(sheet);
  361. this.reLoadSheetData(sheet);
  362. },
  363. /**
  364. * 获取复制数据HTML格式(过滤不可见单元格)
  365. * @param {GC.Spread.Sheets.Worksheet} sheet
  366. * @returns {string}
  367. */
  368. getFilterCopyHTML: function (sheet) {
  369. const sel = sheet.getSelections()[0];
  370. const html = [];
  371. html.push('<table>');
  372. for (let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  373. // 跳过隐藏行
  374. if (!sheet.getCell(i, -1).visible()) { continue; }
  375. const rowHtml = [];
  376. rowHtml.push('<tr>');
  377. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  378. const data = sheet.getText(i, j);
  379. rowHtml.push('<td>' + data + '</td>');
  380. }
  381. rowHtml.push('</tr>');
  382. html.push(rowHtml.join(''));
  383. }
  384. html.push('</table>');
  385. return html.join('');
  386. },
  387. /**
  388. * 获取复制数据Text格式(过滤不可见单元格)
  389. * @param {GC.Spread.Sheets.Worksheet} sheet
  390. * @returns {string}
  391. */
  392. getFilterCopyText: function (sheet) {
  393. const copyData = [];
  394. const sel = sheet.getSelections()[0];
  395. for(let i = sel.row, iLen = sel.row + sel.rowCount; i < iLen; i++) {
  396. // 跳过隐藏行
  397. if (!sheet.getCell(i, -1).visible()) { continue; }
  398. const rowText = [];
  399. for (let j = sel.col, jLen = sel.col + sel.colCount; j < jLen; j++) {
  400. const data = sheet.getText(i, j);
  401. rowText.push(data);
  402. }
  403. copyData.push(rowText.join('\t'));
  404. }
  405. return copyData.join('\n');
  406. },
  407. /**
  408. * 树表结构,定位至指定的节点
  409. * @param {GC.Spread.Sheets.Worksheet} sheet - 需要定位的sheet
  410. * @param {Number} id - 定位节点的id
  411. */
  412. locateTreeNode: function (sheet, id) {
  413. const tree = sheet.zh_tree;
  414. if (!tree) { return }
  415. const node = tree.getItems(id);
  416. if (!node) { return }
  417. const index = tree.nodes.indexOf(node);
  418. const sels = sheet.getSelections();
  419. sheet.setSelection(index, sels[0].col, 1, 1);
  420. sheet.showRow(index, spreadNS.VerticalPosition.center);
  421. },
  422. /**
  423. * 获取当前选行的数据对象
  424. * @param {GC.Spread.Sheets.Worksheet} sheet
  425. * @returns {Object}
  426. */
  427. getSelectObject: function (sheet) {
  428. if (!sheet) {
  429. return null;
  430. } else if (sheet.zh_dataType) {
  431. const sel = sheet.getSelections()[0];
  432. if (sheet.zh_dataType === this.DataType.Tree) {
  433. return sheet.zh_tree.nodes[sel.row];
  434. } else if (sheet.zh_dataType === this.DataType.Data) {
  435. return sheet.zh_data[sel.row];
  436. } else {
  437. return null;
  438. }
  439. }
  440. },
  441. /**
  442. * 刷新列显示
  443. * @param sheet
  444. */
  445. refreshColumnVisible: function (sheet) {
  446. if(sheet.zh_setting) {
  447. sheet.zh_setting.cols.forEach(function (col, index) {
  448. if (col.visible !== undefined && col.visible !== null) {
  449. sheet.setColumnVisible(index, col.visible);
  450. }
  451. });
  452. }
  453. },
  454. resetFieldReadOnly: function (sheet, field, readonly) {
  455. const fields = field instanceof Array ? field : [field];
  456. if (sheet.zh_setting) {
  457. sheet.zh_setting.cols.forEach(function (col, i) {
  458. if (fields.indexOf(col.field) !== -1) {
  459. col.readOnly = readonly;
  460. sheet.getRange(-1, i, -1, 1).locked(col.readOnly || sheet.zh_setting.readOnly || false);
  461. console.log(sheet.getCell(1, 0).locked());
  462. console.log(sheet.getCell(1, 0).text());
  463. console.log(sheet.getCell(1, 1).text());
  464. }
  465. });
  466. }
  467. },
  468. CellType: {
  469. /**
  470. * 获取树结构CellType
  471. * 通过SpreadJsObj.loadSheetData(sheet, 'tree', tree)加载树结构数据
  472. * 要求tree类型为PathTree, 节点必须含有{id, pid, level, order, is_leaf}数据
  473. * @returns {TreeNodeCellType}
  474. */
  475. getTreeNodeCellType: function () {
  476. const indent = 20;
  477. const levelIndent = -5;
  478. const halfBoxLength = 5;
  479. const halfExpandLength = 3;
  480. /**
  481. * 画一条线段
  482. * @param canvas - 画布
  483. * @param x1 - 线段起点 x
  484. * @param y1 - 线段起点 y
  485. * @param x2 - 线段终点 x
  486. * @param y2 - 线段终点 y
  487. * @param color - 线段颜色
  488. */
  489. const drawLine = function (canvas, x1, y1, x2, y2, color) {
  490. canvas.save();
  491. // 设置偏移量
  492. canvas.translate(0.5, 0.5);
  493. canvas.beginPath();
  494. canvas.moveTo(x1, y1);
  495. canvas.lineTo(x2, y2);
  496. canvas.strokeStyle = color;
  497. canvas.stroke();
  498. canvas.restore();
  499. };
  500. /**
  501. * 画一个方框
  502. * @param {Object} canvas - 画布
  503. * @param {Object} rect - 方框区域
  504. * @param {String} lineColor - 画线颜色
  505. * @param {String} fillColor - 填充颜色
  506. */
  507. const drawBox = function (canvas, rect, lineColor, fillColor) {
  508. canvas.save();
  509. // 设置偏移量
  510. canvas.translate(0.5, 0.5);
  511. canvas.strokeStyle = lineColor;
  512. canvas.beginPath();
  513. canvas.moveTo(rect.left, rect.top);
  514. canvas.lineTo(rect.left, rect.bottom);
  515. canvas.lineTo(rect.right, rect.bottom);
  516. canvas.lineTo(rect.right, rect.top);
  517. canvas.lineTo(rect.left, rect.top);
  518. canvas.stroke();
  519. canvas.fillStyle = fillColor;
  520. canvas.fill();
  521. canvas.restore();
  522. };
  523. /**
  524. * 画树结构-展开收起按钮
  525. * @param {Object} canvas - 画布
  526. * @param {Number} x - 单元格左顶点坐标 x
  527. * @param {Number} y - 单元格左顶点坐标 y
  528. * @param {Number} w - 单元格宽度
  529. * @param {Number} h - 单元格高度
  530. * @param {Number} centerX - 按钮中央坐标
  531. * @param {Number} centerY - 按钮中央坐标
  532. * @param {Boolean} expanded - 当前节点展开收起状态
  533. */
  534. const drawExpandBox = function (canvas, x, y, w, h, centerX, centerY, expanded) {
  535. let rect = {
  536. top: centerY - halfBoxLength,
  537. bottom: centerY + halfBoxLength,
  538. left: centerX - halfBoxLength,
  539. right: centerX + halfBoxLength
  540. };
  541. let h1, h2, offset = 1;
  542. if (rect.left < x + w) {
  543. // 方框超出单元格宽度时,超出部分不画。
  544. rect.right = Math.min(rect.right, x + w);
  545. drawBox(canvas, rect, 'black', 'white');
  546. // 画中心十字
  547. // 画十字横线
  548. h1 = centerX - halfExpandLength;
  549. h2 = Math.min(centerX + halfExpandLength, x + w);
  550. if (h2 > h1) {
  551. drawLine(canvas, h1, centerY, h2, centerY, 'black');
  552. }
  553. // 画十字竖线
  554. if (!expanded && (centerX < x + w)) {
  555. drawLine(canvas, centerX, centerY - halfExpandLength, centerX, centerY + halfExpandLength, 'black');
  556. }
  557. }
  558. };
  559. let TreeNodeCellType = function (){};
  560. TreeNodeCellType.prototype = new spreadNS.CellTypes.Text();
  561. const proto = TreeNodeCellType.prototype;
  562. /**
  563. * 绘制方法
  564. * @param {Object} canvas - 画布
  565. * @param value - cell.value
  566. * @param {Number} x - 单元格左顶点坐标 x
  567. * @param {Number} y - 单元格左顶点坐标 y
  568. * @param {Number} w - 单元格宽度
  569. * @param {Number} h - 单元格高度
  570. * @param {Object} style - cell.style
  571. * @param {Object} options
  572. */
  573. proto.paint = function (canvas, value, x, y, w, h, style, options) {
  574. // 清理 画布--单元格范围 旧数据
  575. if (style.backColor) {
  576. canvas.save();
  577. canvas.fillStyle = style.backColor;
  578. canvas.fillRect(x, y, w, h);
  579. canvas.restore();
  580. } else {
  581. canvas.clearRect(x, y, w, h);
  582. }
  583. const tree = options.sheet.zh_tree;
  584. // 使用TreeCellType前,需定义sheet.tree
  585. if (tree) {
  586. const node = options.row < tree.nodes.length ? tree.nodes[options.row] : null;
  587. if (node) {
  588. const showTreeLine = true;
  589. const centerX = Math.floor(x) + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  590. const centerY = Math.floor((y + (y + h)) / 2);
  591. // Draw Sibling Line
  592. if (showTreeLine) {
  593. // Draw Horizontal Line
  594. if (centerX < x + w) {
  595. const x1 = centerX + indent / 2;
  596. drawLine(canvas, centerX, centerY, Math.min(x1, x + w), centerY, 'gray');
  597. }
  598. // Draw Vertical Line
  599. if (centerX < x + w) {
  600. const y1 = tree.isLastSibling(node) ? centerY : y + h;
  601. const parent = tree.getParent(node);
  602. const y2 = y1 - centerY;
  603. if (node.order === 1 && !parent) {
  604. drawLine(canvas, centerX, centerY, centerX, y1, 'gray');
  605. } else {
  606. drawLine(canvas, centerX, y, centerX, y1, 'gray');
  607. }
  608. }
  609. }
  610. // Draw Expand Box
  611. if (!node.is_leaf) {
  612. drawExpandBox(canvas, x, y, w, h, centerX, centerY, node.expanded);
  613. }
  614. // Draw Parent Line
  615. if (showTreeLine) {
  616. let parent = tree.getParent(node), parentCenterX = centerX - indent - levelIndent;
  617. while (parent) {
  618. if (!tree.isLastSibling(parent)) {
  619. if (parentCenterX < x + w) {
  620. drawLine(canvas, parentCenterX, y, parentCenterX, y + h, 'gray');
  621. }
  622. }
  623. parent = tree.getParent(parent);
  624. parentCenterX -= (indent + levelIndent);
  625. }
  626. };
  627. // 重定位x
  628. x = x + (node.level + 1) * indent + (node.level) * levelIndent;
  629. w = w - (node.level - 1) * indent - (node.level) * levelIndent;
  630. }
  631. }
  632. // Drawing Text
  633. spreadNS.CellTypes.Text.prototype.paint.apply(this, arguments);
  634. };
  635. /**
  636. * 获取点击信息
  637. * @param {Number} x
  638. * @param {Number} y
  639. * @param {Object} cellStyle
  640. * @param {Object} cellRect
  641. * @param {Object} context
  642. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  643. */
  644. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  645. return {
  646. x: x,
  647. y: y,
  648. row: context.row,
  649. col: context.col,
  650. cellStyle: cellStyle,
  651. cellRect: cellRect,
  652. sheet: context.sheet,
  653. sheetArea: context.sheetArea
  654. };
  655. };
  656. /**
  657. * 鼠标点击 树结构按钮 响应展开收起(未加载子节点时,先加载子节点)
  658. * @param {Object} hitinfo - 见getHitInfo
  659. */
  660. proto.processMouseDown = function (hitinfo) {
  661. const offset = -1;
  662. const tree = hitinfo.sheet.zh_tree;
  663. if (!tree) { return; }
  664. const node = tree.nodes[hitinfo.row];
  665. if (!node) { return; }
  666. let centerX = hitinfo.cellRect.x + offset + (node.level) * indent + (node.level) * levelIndent + indent / 2;
  667. let centerY = (hitinfo.cellRect.y + offset + (hitinfo.cellRect.y + offset + hitinfo.cellRect.height)) / 2;
  668. // 点击展开节点时,如果已加载子项,则展开,反之这加载子项,展开
  669. if (Math.abs(hitinfo.x - centerX) < halfBoxLength && Math.abs(hitinfo.y - centerY) < halfBoxLength) {
  670. const children = tree.getChildren(node);
  671. if (!node.expanded && !node.is_leaf && children.length === 0 && tree.loadChildren) {
  672. tree.loadChildren(node, function () {
  673. node.expanded = true;
  674. const children = tree.getChildren(node);
  675. hitinfo.sheet.addRows(hitinfo.row + 1, children.length);
  676. SpreadJsObj.reLoadRowData(hitinfo.sheet, hitinfo.row + 1, children.length);
  677. });
  678. } else {
  679. tree.setExpanded(node, !node.expanded);
  680. SpreadJsObj.massOperationSheet(hitinfo.sheet, function () {
  681. const posterity = tree.getPosterity(node);
  682. for (const child of posterity) {
  683. hitinfo.sheet.setRowVisible(tree.nodes.indexOf(child), child.visible, hitinfo.sheetArea);
  684. }
  685. });
  686. hitinfo.sheet.repaint();
  687. }
  688. }
  689. };
  690. return new TreeNodeCellType();
  691. },
  692. /**
  693. * 获取带悬浮提示CellType
  694. * @returns {TipCellType}
  695. */
  696. getTipCellType: function () {
  697. const TipCellType = function () {};
  698. // 继承 SpreadJs定义的 普通的TextCellType
  699. TipCellType.prototype = new spreadNS.CellTypes.Text();
  700. const proto = TipCellType.prototype;
  701. /**
  702. * 获取点击信息
  703. * @param {Number} x
  704. * @param {Number} y
  705. * @param {Object} cellStyle
  706. * @param {Object} cellRect
  707. * @param {Object} context
  708. * @returns {{x: *, y: *, row: *, col: *|boolean|*[]|number|{}|UE.dom.dtd.col, cellStyle: *, cellRect: *, sheet: *|StyleSheet, sheetArea: *}}
  709. */
  710. proto.getHitInfo = function (x, y, cellStyle, cellRect, context) {
  711. return {
  712. x: x,
  713. y: y,
  714. row: context.row,
  715. col: context.col,
  716. cellStyle: cellStyle,
  717. cellRect: cellRect,
  718. sheet: context.sheet,
  719. sheetArea: context.sheetArea
  720. };
  721. };
  722. /**
  723. * 鼠标进入单元格事件 - 显示悬浮提示
  724. * @param {Object} hitinfo - 见getHitInfo返回值
  725. */
  726. proto.processMouseEnter = function (hitinfo) {
  727. const text = hitinfo.sheet.getText(hitinfo.row, hitinfo.col);
  728. const setting = hitinfo.sheet.setting;
  729. if (setting.pos && text && text !== '') {
  730. if (!this._toolTipElement) {
  731. let div = $('#autoTip')[0];
  732. if (!div) {
  733. div = document.createElement("div");
  734. $(div).css("position", "absolute")
  735. .css("border", "1px #C0C0C0 solid")
  736. .css("box-shadow", "1px 2px 5px rgba(0,0,0,0.4)")
  737. .css("font", "9pt Arial")
  738. .css("background", "white")
  739. .css("padding", 5)
  740. .attr("id", 'autoTip');
  741. $(div).hide();
  742. document.body.insertBefore(div, null);
  743. }
  744. this._toolTipElement = div;
  745. $(this._toolTipElement).text(text).css("top", setting.pos.y + hitinfo.y + 15).css("left", setting.pos.x + hitinfo.x + 15);
  746. $(this._toolTipElement).show("fast");
  747. }
  748. }
  749. };
  750. /**
  751. * 鼠标移出单元格事件 - 隐藏悬浮提示
  752. * @param {Object} hitinfo - 见getHitInfo返回值
  753. */
  754. proto.processMouseLeave = function (hitinfo) {
  755. if (this._toolTipElement) {
  756. $(this._toolTipElement).hide();
  757. this._toolTipElement = null;
  758. }
  759. };
  760. return new TipCellType();
  761. }
  762. }
  763. };