index.js 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430
  1. // src/index.ts
  2. import { Plugin as Plugin2 } from "prosemirror-state";
  3. // src/cellselection.ts
  4. import { Fragment, Slice } from "prosemirror-model";
  5. import {
  6. NodeSelection as NodeSelection2,
  7. Selection,
  8. SelectionRange,
  9. TextSelection
  10. } from "prosemirror-state";
  11. import { Decoration, DecorationSet } from "prosemirror-view";
  12. // src/tablemap.ts
  13. var readFromCache;
  14. var addToCache;
  15. if (typeof WeakMap != "undefined") {
  16. let cache = /* @__PURE__ */ new WeakMap();
  17. readFromCache = (key) => cache.get(key);
  18. addToCache = (key, value) => {
  19. cache.set(key, value);
  20. return value;
  21. };
  22. } else {
  23. const cache = [];
  24. const cacheSize = 10;
  25. let cachePos = 0;
  26. readFromCache = (key) => {
  27. for (let i = 0; i < cache.length; i += 2)
  28. if (cache[i] == key)
  29. return cache[i + 1];
  30. };
  31. addToCache = (key, value) => {
  32. if (cachePos == cacheSize)
  33. cachePos = 0;
  34. cache[cachePos++] = key;
  35. return cache[cachePos++] = value;
  36. };
  37. }
  38. var TableMap = class {
  39. constructor(width, height, map, problems) {
  40. this.width = width;
  41. this.height = height;
  42. this.map = map;
  43. this.problems = problems;
  44. }
  45. // Find the dimensions of the cell at the given position.
  46. findCell(pos) {
  47. for (let i = 0; i < this.map.length; i++) {
  48. const curPos = this.map[i];
  49. if (curPos != pos)
  50. continue;
  51. const left = i % this.width;
  52. const top = i / this.width | 0;
  53. let right = left + 1;
  54. let bottom = top + 1;
  55. for (let j = 1; right < this.width && this.map[i + j] == curPos; j++) {
  56. right++;
  57. }
  58. for (let j = 1; bottom < this.height && this.map[i + this.width * j] == curPos; j++) {
  59. bottom++;
  60. }
  61. return { left, top, right, bottom };
  62. }
  63. throw new RangeError(`No cell with offset ${pos} found`);
  64. }
  65. // Find the left side of the cell at the given position.
  66. colCount(pos) {
  67. for (let i = 0; i < this.map.length; i++) {
  68. if (this.map[i] == pos) {
  69. return i % this.width;
  70. }
  71. }
  72. throw new RangeError(`No cell with offset ${pos} found`);
  73. }
  74. // Find the next cell in the given direction, starting from the cell
  75. // at `pos`, if any.
  76. nextCell(pos, axis, dir) {
  77. const { left, right, top, bottom } = this.findCell(pos);
  78. if (axis == "horiz") {
  79. if (dir < 0 ? left == 0 : right == this.width)
  80. return null;
  81. return this.map[top * this.width + (dir < 0 ? left - 1 : right)];
  82. } else {
  83. if (dir < 0 ? top == 0 : bottom == this.height)
  84. return null;
  85. return this.map[left + this.width * (dir < 0 ? top - 1 : bottom)];
  86. }
  87. }
  88. // Get the rectangle spanning the two given cells.
  89. rectBetween(a, b) {
  90. const {
  91. left: leftA,
  92. right: rightA,
  93. top: topA,
  94. bottom: bottomA
  95. } = this.findCell(a);
  96. const {
  97. left: leftB,
  98. right: rightB,
  99. top: topB,
  100. bottom: bottomB
  101. } = this.findCell(b);
  102. return {
  103. left: Math.min(leftA, leftB),
  104. top: Math.min(topA, topB),
  105. right: Math.max(rightA, rightB),
  106. bottom: Math.max(bottomA, bottomB)
  107. };
  108. }
  109. // Return the position of all cells that have the top left corner in
  110. // the given rectangle.
  111. cellsInRect(rect) {
  112. const result = [];
  113. const seen = {};
  114. for (let row = rect.top; row < rect.bottom; row++) {
  115. for (let col = rect.left; col < rect.right; col++) {
  116. const index = row * this.width + col;
  117. const pos = this.map[index];
  118. if (seen[pos])
  119. continue;
  120. seen[pos] = true;
  121. if (col == rect.left && col && this.map[index - 1] == pos || row == rect.top && row && this.map[index - this.width] == pos) {
  122. continue;
  123. }
  124. result.push(pos);
  125. }
  126. }
  127. return result;
  128. }
  129. // Return the position at which the cell at the given row and column
  130. // starts, or would start, if a cell started there.
  131. positionAt(row, col, table) {
  132. for (let i = 0, rowStart = 0; ; i++) {
  133. const rowEnd = rowStart + table.child(i).nodeSize;
  134. if (i == row) {
  135. let index = col + row * this.width;
  136. const rowEndIndex = (row + 1) * this.width;
  137. while (index < rowEndIndex && this.map[index] < rowStart)
  138. index++;
  139. return index == rowEndIndex ? rowEnd - 1 : this.map[index];
  140. }
  141. rowStart = rowEnd;
  142. }
  143. }
  144. // Find the table map for the given table node.
  145. static get(table) {
  146. return readFromCache(table) || addToCache(table, computeMap(table));
  147. }
  148. };
  149. function computeMap(table) {
  150. if (table.type.spec.tableRole != "table")
  151. throw new RangeError("Not a table node: " + table.type.name);
  152. const width = findWidth(table), height = table.childCount;
  153. const map = [];
  154. let mapPos = 0;
  155. let problems = null;
  156. const colWidths = [];
  157. for (let i = 0, e = width * height; i < e; i++)
  158. map[i] = 0;
  159. for (let row = 0, pos = 0; row < height; row++) {
  160. const rowNode = table.child(row);
  161. pos++;
  162. for (let i = 0; ; i++) {
  163. while (mapPos < map.length && map[mapPos] != 0)
  164. mapPos++;
  165. if (i == rowNode.childCount)
  166. break;
  167. const cellNode = rowNode.child(i);
  168. const { colspan, rowspan, colwidth } = cellNode.attrs;
  169. for (let h = 0; h < rowspan; h++) {
  170. if (h + row >= height) {
  171. (problems || (problems = [])).push({
  172. type: "overlong_rowspan",
  173. pos,
  174. n: rowspan - h
  175. });
  176. break;
  177. }
  178. const start = mapPos + h * width;
  179. for (let w = 0; w < colspan; w++) {
  180. if (map[start + w] == 0)
  181. map[start + w] = pos;
  182. else
  183. (problems || (problems = [])).push({
  184. type: "collision",
  185. row,
  186. pos,
  187. n: colspan - w
  188. });
  189. const colW = colwidth && colwidth[w];
  190. if (colW) {
  191. const widthIndex = (start + w) % width * 2, prev = colWidths[widthIndex];
  192. if (prev == null || prev != colW && colWidths[widthIndex + 1] == 1) {
  193. colWidths[widthIndex] = colW;
  194. colWidths[widthIndex + 1] = 1;
  195. } else if (prev == colW) {
  196. colWidths[widthIndex + 1]++;
  197. }
  198. }
  199. }
  200. }
  201. mapPos += colspan;
  202. pos += cellNode.nodeSize;
  203. }
  204. const expectedPos = (row + 1) * width;
  205. let missing = 0;
  206. while (mapPos < expectedPos)
  207. if (map[mapPos++] == 0)
  208. missing++;
  209. if (missing)
  210. (problems || (problems = [])).push({ type: "missing", row, n: missing });
  211. pos++;
  212. }
  213. const tableMap = new TableMap(width, height, map, problems);
  214. let badWidths = false;
  215. for (let i = 0; !badWidths && i < colWidths.length; i += 2)
  216. if (colWidths[i] != null && colWidths[i + 1] < height)
  217. badWidths = true;
  218. if (badWidths)
  219. findBadColWidths(tableMap, colWidths, table);
  220. return tableMap;
  221. }
  222. function findWidth(table) {
  223. let width = -1;
  224. let hasRowSpan = false;
  225. for (let row = 0; row < table.childCount; row++) {
  226. const rowNode = table.child(row);
  227. let rowWidth = 0;
  228. if (hasRowSpan)
  229. for (let j = 0; j < row; j++) {
  230. const prevRow = table.child(j);
  231. for (let i = 0; i < prevRow.childCount; i++) {
  232. const cell = prevRow.child(i);
  233. if (j + cell.attrs.rowspan > row)
  234. rowWidth += cell.attrs.colspan;
  235. }
  236. }
  237. for (let i = 0; i < rowNode.childCount; i++) {
  238. const cell = rowNode.child(i);
  239. rowWidth += cell.attrs.colspan;
  240. if (cell.attrs.rowspan > 1)
  241. hasRowSpan = true;
  242. }
  243. if (width == -1)
  244. width = rowWidth;
  245. else if (width != rowWidth)
  246. width = Math.max(width, rowWidth);
  247. }
  248. return width;
  249. }
  250. function findBadColWidths(map, colWidths, table) {
  251. if (!map.problems)
  252. map.problems = [];
  253. const seen = {};
  254. for (let i = 0; i < map.map.length; i++) {
  255. const pos = map.map[i];
  256. if (seen[pos])
  257. continue;
  258. seen[pos] = true;
  259. const node = table.nodeAt(pos);
  260. if (!node) {
  261. throw new RangeError(`No cell with offset ${pos} found`);
  262. }
  263. let updated = null;
  264. const attrs = node.attrs;
  265. for (let j = 0; j < attrs.colspan; j++) {
  266. const col = (i + j) % map.width;
  267. const colWidth = colWidths[col * 2];
  268. if (colWidth != null && (!attrs.colwidth || attrs.colwidth[j] != colWidth))
  269. (updated || (updated = freshColWidth(attrs)))[j] = colWidth;
  270. }
  271. if (updated)
  272. map.problems.unshift({
  273. type: "colwidth mismatch",
  274. pos,
  275. colwidth: updated
  276. });
  277. }
  278. }
  279. function freshColWidth(attrs) {
  280. if (attrs.colwidth)
  281. return attrs.colwidth.slice();
  282. const result = [];
  283. for (let i = 0; i < attrs.colspan; i++)
  284. result.push(0);
  285. return result;
  286. }
  287. // src/util.ts
  288. import { PluginKey } from "prosemirror-state";
  289. // src/schema.ts
  290. function getCellAttrs(dom, extraAttrs) {
  291. if (typeof dom === "string") {
  292. return {};
  293. }
  294. const widthAttr = dom.getAttribute("data-colwidth");
  295. const widths = widthAttr && /^\d+(,\d+)*$/.test(widthAttr) ? widthAttr.split(",").map((s) => Number(s)) : null;
  296. const colspan = Number(dom.getAttribute("colspan") || 1);
  297. const result = {
  298. colspan,
  299. rowspan: Number(dom.getAttribute("rowspan") || 1),
  300. colwidth: widths && widths.length == colspan ? widths : null
  301. };
  302. for (const prop in extraAttrs) {
  303. const getter = extraAttrs[prop].getFromDOM;
  304. const value = getter && getter(dom);
  305. if (value != null) {
  306. result[prop] = value;
  307. }
  308. }
  309. return result;
  310. }
  311. function setCellAttrs(node, extraAttrs) {
  312. const attrs = {};
  313. if (node.attrs.colspan != 1)
  314. attrs.colspan = node.attrs.colspan;
  315. if (node.attrs.rowspan != 1)
  316. attrs.rowspan = node.attrs.rowspan;
  317. if (node.attrs.colwidth)
  318. attrs["data-colwidth"] = node.attrs.colwidth.join(",");
  319. for (const prop in extraAttrs) {
  320. const setter = extraAttrs[prop].setDOMAttr;
  321. if (setter)
  322. setter(node.attrs[prop], attrs);
  323. }
  324. return attrs;
  325. }
  326. function tableNodes(options) {
  327. const extraAttrs = options.cellAttributes || {};
  328. const cellAttrs = {
  329. colspan: { default: 1 },
  330. rowspan: { default: 1 },
  331. colwidth: { default: null }
  332. };
  333. for (const prop in extraAttrs)
  334. cellAttrs[prop] = { default: extraAttrs[prop].default };
  335. return {
  336. table: {
  337. content: "table_row+",
  338. tableRole: "table",
  339. isolating: true,
  340. group: options.tableGroup,
  341. parseDOM: [{ tag: "table" }],
  342. toDOM() {
  343. return ["table", ["tbody", 0]];
  344. }
  345. },
  346. table_row: {
  347. content: "(table_cell | table_header)*",
  348. tableRole: "row",
  349. parseDOM: [{ tag: "tr" }],
  350. toDOM() {
  351. return ["tr", 0];
  352. }
  353. },
  354. table_cell: {
  355. content: options.cellContent,
  356. attrs: cellAttrs,
  357. tableRole: "cell",
  358. isolating: true,
  359. parseDOM: [
  360. { tag: "td", getAttrs: (dom) => getCellAttrs(dom, extraAttrs) }
  361. ],
  362. toDOM(node) {
  363. return ["td", setCellAttrs(node, extraAttrs), 0];
  364. }
  365. },
  366. table_header: {
  367. content: options.cellContent,
  368. attrs: cellAttrs,
  369. tableRole: "header_cell",
  370. isolating: true,
  371. parseDOM: [
  372. { tag: "th", getAttrs: (dom) => getCellAttrs(dom, extraAttrs) }
  373. ],
  374. toDOM(node) {
  375. return ["th", setCellAttrs(node, extraAttrs), 0];
  376. }
  377. }
  378. };
  379. }
  380. function tableNodeTypes(schema) {
  381. let result = schema.cached.tableNodeTypes;
  382. if (!result) {
  383. result = schema.cached.tableNodeTypes = {};
  384. for (const name in schema.nodes) {
  385. const type = schema.nodes[name], role = type.spec.tableRole;
  386. if (role)
  387. result[role] = type;
  388. }
  389. }
  390. return result;
  391. }
  392. // src/util.ts
  393. var tableEditingKey = new PluginKey("selectingCells");
  394. function cellAround($pos) {
  395. for (let d = $pos.depth - 1; d > 0; d--)
  396. if ($pos.node(d).type.spec.tableRole == "row")
  397. return $pos.node(0).resolve($pos.before(d + 1));
  398. return null;
  399. }
  400. function cellWrapping($pos) {
  401. for (let d = $pos.depth; d > 0; d--) {
  402. const role = $pos.node(d).type.spec.tableRole;
  403. if (role === "cell" || role === "header_cell")
  404. return $pos.node(d);
  405. }
  406. return null;
  407. }
  408. function isInTable(state) {
  409. const $head = state.selection.$head;
  410. for (let d = $head.depth; d > 0; d--)
  411. if ($head.node(d).type.spec.tableRole == "row")
  412. return true;
  413. return false;
  414. }
  415. function selectionCell(state) {
  416. const sel = state.selection;
  417. if ("$anchorCell" in sel && sel.$anchorCell) {
  418. return sel.$anchorCell.pos > sel.$headCell.pos ? sel.$anchorCell : sel.$headCell;
  419. } else if ("node" in sel && sel.node && sel.node.type.spec.tableRole == "cell") {
  420. return sel.$anchor;
  421. }
  422. const $cell = cellAround(sel.$head) || cellNear(sel.$head);
  423. if ($cell) {
  424. return $cell;
  425. }
  426. throw new RangeError(`No cell found around position ${sel.head}`);
  427. }
  428. function cellNear($pos) {
  429. for (let after = $pos.nodeAfter, pos = $pos.pos; after; after = after.firstChild, pos++) {
  430. const role = after.type.spec.tableRole;
  431. if (role == "cell" || role == "header_cell")
  432. return $pos.doc.resolve(pos);
  433. }
  434. for (let before = $pos.nodeBefore, pos = $pos.pos; before; before = before.lastChild, pos--) {
  435. const role = before.type.spec.tableRole;
  436. if (role == "cell" || role == "header_cell")
  437. return $pos.doc.resolve(pos - before.nodeSize);
  438. }
  439. }
  440. function pointsAtCell($pos) {
  441. return $pos.parent.type.spec.tableRole == "row" && !!$pos.nodeAfter;
  442. }
  443. function moveCellForward($pos) {
  444. return $pos.node(0).resolve($pos.pos + $pos.nodeAfter.nodeSize);
  445. }
  446. function inSameTable($cellA, $cellB) {
  447. return $cellA.depth == $cellB.depth && $cellA.pos >= $cellB.start(-1) && $cellA.pos <= $cellB.end(-1);
  448. }
  449. function findCell($pos) {
  450. return TableMap.get($pos.node(-1)).findCell($pos.pos - $pos.start(-1));
  451. }
  452. function colCount($pos) {
  453. return TableMap.get($pos.node(-1)).colCount($pos.pos - $pos.start(-1));
  454. }
  455. function nextCell($pos, axis, dir) {
  456. const table = $pos.node(-1);
  457. const map = TableMap.get(table);
  458. const tableStart = $pos.start(-1);
  459. const moved = map.nextCell($pos.pos - tableStart, axis, dir);
  460. return moved == null ? null : $pos.node(0).resolve(tableStart + moved);
  461. }
  462. function removeColSpan(attrs, pos, n = 1) {
  463. const result = { ...attrs, colspan: attrs.colspan - n };
  464. if (result.colwidth) {
  465. result.colwidth = result.colwidth.slice();
  466. result.colwidth.splice(pos, n);
  467. if (!result.colwidth.some((w) => w > 0))
  468. result.colwidth = null;
  469. }
  470. return result;
  471. }
  472. function addColSpan(attrs, pos, n = 1) {
  473. const result = { ...attrs, colspan: attrs.colspan + n };
  474. if (result.colwidth) {
  475. result.colwidth = result.colwidth.slice();
  476. for (let i = 0; i < n; i++)
  477. result.colwidth.splice(pos, 0, 0);
  478. }
  479. return result;
  480. }
  481. function columnIsHeader(map, table, col) {
  482. const headerCell = tableNodeTypes(table.type.schema).header_cell;
  483. for (let row = 0; row < map.height; row++)
  484. if (table.nodeAt(map.map[col + row * map.width]).type != headerCell)
  485. return false;
  486. return true;
  487. }
  488. // src/cellselection.ts
  489. var CellSelection = class _CellSelection extends Selection {
  490. // A table selection is identified by its anchor and head cells. The
  491. // positions given to this constructor should point _before_ two
  492. // cells in the same table. They may be the same, to select a single
  493. // cell.
  494. constructor($anchorCell, $headCell = $anchorCell) {
  495. const table = $anchorCell.node(-1);
  496. const map = TableMap.get(table);
  497. const tableStart = $anchorCell.start(-1);
  498. const rect = map.rectBetween(
  499. $anchorCell.pos - tableStart,
  500. $headCell.pos - tableStart
  501. );
  502. const doc = $anchorCell.node(0);
  503. const cells = map.cellsInRect(rect).filter((p) => p != $headCell.pos - tableStart);
  504. cells.unshift($headCell.pos - tableStart);
  505. const ranges = cells.map((pos) => {
  506. const cell = table.nodeAt(pos);
  507. if (!cell) {
  508. throw RangeError(`No cell with offset ${pos} found`);
  509. }
  510. const from = tableStart + pos + 1;
  511. return new SelectionRange(
  512. doc.resolve(from),
  513. doc.resolve(from + cell.content.size)
  514. );
  515. });
  516. super(ranges[0].$from, ranges[0].$to, ranges);
  517. this.$anchorCell = $anchorCell;
  518. this.$headCell = $headCell;
  519. }
  520. map(doc, mapping) {
  521. const $anchorCell = doc.resolve(mapping.map(this.$anchorCell.pos));
  522. const $headCell = doc.resolve(mapping.map(this.$headCell.pos));
  523. if (pointsAtCell($anchorCell) && pointsAtCell($headCell) && inSameTable($anchorCell, $headCell)) {
  524. const tableChanged = this.$anchorCell.node(-1) != $anchorCell.node(-1);
  525. if (tableChanged && this.isRowSelection())
  526. return _CellSelection.rowSelection($anchorCell, $headCell);
  527. else if (tableChanged && this.isColSelection())
  528. return _CellSelection.colSelection($anchorCell, $headCell);
  529. else
  530. return new _CellSelection($anchorCell, $headCell);
  531. }
  532. return TextSelection.between($anchorCell, $headCell);
  533. }
  534. // Returns a rectangular slice of table rows containing the selected
  535. // cells.
  536. content() {
  537. const table = this.$anchorCell.node(-1);
  538. const map = TableMap.get(table);
  539. const tableStart = this.$anchorCell.start(-1);
  540. const rect = map.rectBetween(
  541. this.$anchorCell.pos - tableStart,
  542. this.$headCell.pos - tableStart
  543. );
  544. const seen = {};
  545. const rows = [];
  546. for (let row = rect.top; row < rect.bottom; row++) {
  547. const rowContent = [];
  548. for (let index = row * map.width + rect.left, col = rect.left; col < rect.right; col++, index++) {
  549. const pos = map.map[index];
  550. if (seen[pos])
  551. continue;
  552. seen[pos] = true;
  553. const cellRect = map.findCell(pos);
  554. let cell = table.nodeAt(pos);
  555. if (!cell) {
  556. throw RangeError(`No cell with offset ${pos} found`);
  557. }
  558. const extraLeft = rect.left - cellRect.left;
  559. const extraRight = cellRect.right - rect.right;
  560. if (extraLeft > 0 || extraRight > 0) {
  561. let attrs = cell.attrs;
  562. if (extraLeft > 0) {
  563. attrs = removeColSpan(attrs, 0, extraLeft);
  564. }
  565. if (extraRight > 0) {
  566. attrs = removeColSpan(
  567. attrs,
  568. attrs.colspan - extraRight,
  569. extraRight
  570. );
  571. }
  572. if (cellRect.left < rect.left) {
  573. cell = cell.type.createAndFill(attrs);
  574. if (!cell) {
  575. throw RangeError(
  576. `Could not create cell with attrs ${JSON.stringify(attrs)}`
  577. );
  578. }
  579. } else {
  580. cell = cell.type.create(attrs, cell.content);
  581. }
  582. }
  583. if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) {
  584. const attrs = {
  585. ...cell.attrs,
  586. rowspan: Math.min(cellRect.bottom, rect.bottom) - Math.max(cellRect.top, rect.top)
  587. };
  588. if (cellRect.top < rect.top) {
  589. cell = cell.type.createAndFill(attrs);
  590. } else {
  591. cell = cell.type.create(attrs, cell.content);
  592. }
  593. }
  594. rowContent.push(cell);
  595. }
  596. rows.push(table.child(row).copy(Fragment.from(rowContent)));
  597. }
  598. const fragment = this.isColSelection() && this.isRowSelection() ? table : rows;
  599. return new Slice(Fragment.from(fragment), 1, 1);
  600. }
  601. replace(tr, content = Slice.empty) {
  602. const mapFrom = tr.steps.length, ranges = this.ranges;
  603. for (let i = 0; i < ranges.length; i++) {
  604. const { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);
  605. tr.replace(
  606. mapping.map($from.pos),
  607. mapping.map($to.pos),
  608. i ? Slice.empty : content
  609. );
  610. }
  611. const sel = Selection.findFrom(
  612. tr.doc.resolve(tr.mapping.slice(mapFrom).map(this.to)),
  613. -1
  614. );
  615. if (sel)
  616. tr.setSelection(sel);
  617. }
  618. replaceWith(tr, node) {
  619. this.replace(tr, new Slice(Fragment.from(node), 0, 0));
  620. }
  621. forEachCell(f) {
  622. const table = this.$anchorCell.node(-1);
  623. const map = TableMap.get(table);
  624. const tableStart = this.$anchorCell.start(-1);
  625. const cells = map.cellsInRect(
  626. map.rectBetween(
  627. this.$anchorCell.pos - tableStart,
  628. this.$headCell.pos - tableStart
  629. )
  630. );
  631. for (let i = 0; i < cells.length; i++) {
  632. f(table.nodeAt(cells[i]), tableStart + cells[i]);
  633. }
  634. }
  635. // True if this selection goes all the way from the top to the
  636. // bottom of the table.
  637. isColSelection() {
  638. const anchorTop = this.$anchorCell.index(-1);
  639. const headTop = this.$headCell.index(-1);
  640. if (Math.min(anchorTop, headTop) > 0)
  641. return false;
  642. const anchorBottom = anchorTop + this.$anchorCell.nodeAfter.attrs.rowspan;
  643. const headBottom = headTop + this.$headCell.nodeAfter.attrs.rowspan;
  644. return Math.max(anchorBottom, headBottom) == this.$headCell.node(-1).childCount;
  645. }
  646. // Returns the smallest column selection that covers the given anchor
  647. // and head cell.
  648. static colSelection($anchorCell, $headCell = $anchorCell) {
  649. const table = $anchorCell.node(-1);
  650. const map = TableMap.get(table);
  651. const tableStart = $anchorCell.start(-1);
  652. const anchorRect = map.findCell($anchorCell.pos - tableStart);
  653. const headRect = map.findCell($headCell.pos - tableStart);
  654. const doc = $anchorCell.node(0);
  655. if (anchorRect.top <= headRect.top) {
  656. if (anchorRect.top > 0)
  657. $anchorCell = doc.resolve(tableStart + map.map[anchorRect.left]);
  658. if (headRect.bottom < map.height)
  659. $headCell = doc.resolve(
  660. tableStart + map.map[map.width * (map.height - 1) + headRect.right - 1]
  661. );
  662. } else {
  663. if (headRect.top > 0)
  664. $headCell = doc.resolve(tableStart + map.map[headRect.left]);
  665. if (anchorRect.bottom < map.height)
  666. $anchorCell = doc.resolve(
  667. tableStart + map.map[map.width * (map.height - 1) + anchorRect.right - 1]
  668. );
  669. }
  670. return new _CellSelection($anchorCell, $headCell);
  671. }
  672. // True if this selection goes all the way from the left to the
  673. // right of the table.
  674. isRowSelection() {
  675. const table = this.$anchorCell.node(-1);
  676. const map = TableMap.get(table);
  677. const tableStart = this.$anchorCell.start(-1);
  678. const anchorLeft = map.colCount(this.$anchorCell.pos - tableStart);
  679. const headLeft = map.colCount(this.$headCell.pos - tableStart);
  680. if (Math.min(anchorLeft, headLeft) > 0)
  681. return false;
  682. const anchorRight = anchorLeft + this.$anchorCell.nodeAfter.attrs.colspan;
  683. const headRight = headLeft + this.$headCell.nodeAfter.attrs.colspan;
  684. return Math.max(anchorRight, headRight) == map.width;
  685. }
  686. eq(other) {
  687. return other instanceof _CellSelection && other.$anchorCell.pos == this.$anchorCell.pos && other.$headCell.pos == this.$headCell.pos;
  688. }
  689. // Returns the smallest row selection that covers the given anchor
  690. // and head cell.
  691. static rowSelection($anchorCell, $headCell = $anchorCell) {
  692. const table = $anchorCell.node(-1);
  693. const map = TableMap.get(table);
  694. const tableStart = $anchorCell.start(-1);
  695. const anchorRect = map.findCell($anchorCell.pos - tableStart);
  696. const headRect = map.findCell($headCell.pos - tableStart);
  697. const doc = $anchorCell.node(0);
  698. if (anchorRect.left <= headRect.left) {
  699. if (anchorRect.left > 0)
  700. $anchorCell = doc.resolve(
  701. tableStart + map.map[anchorRect.top * map.width]
  702. );
  703. if (headRect.right < map.width)
  704. $headCell = doc.resolve(
  705. tableStart + map.map[map.width * (headRect.top + 1) - 1]
  706. );
  707. } else {
  708. if (headRect.left > 0)
  709. $headCell = doc.resolve(tableStart + map.map[headRect.top * map.width]);
  710. if (anchorRect.right < map.width)
  711. $anchorCell = doc.resolve(
  712. tableStart + map.map[map.width * (anchorRect.top + 1) - 1]
  713. );
  714. }
  715. return new _CellSelection($anchorCell, $headCell);
  716. }
  717. toJSON() {
  718. return {
  719. type: "cell",
  720. anchor: this.$anchorCell.pos,
  721. head: this.$headCell.pos
  722. };
  723. }
  724. static fromJSON(doc, json) {
  725. return new _CellSelection(doc.resolve(json.anchor), doc.resolve(json.head));
  726. }
  727. static create(doc, anchorCell, headCell = anchorCell) {
  728. return new _CellSelection(doc.resolve(anchorCell), doc.resolve(headCell));
  729. }
  730. getBookmark() {
  731. return new CellBookmark(this.$anchorCell.pos, this.$headCell.pos);
  732. }
  733. };
  734. CellSelection.prototype.visible = false;
  735. Selection.jsonID("cell", CellSelection);
  736. var CellBookmark = class _CellBookmark {
  737. constructor(anchor, head) {
  738. this.anchor = anchor;
  739. this.head = head;
  740. }
  741. map(mapping) {
  742. return new _CellBookmark(mapping.map(this.anchor), mapping.map(this.head));
  743. }
  744. resolve(doc) {
  745. const $anchorCell = doc.resolve(this.anchor), $headCell = doc.resolve(this.head);
  746. if ($anchorCell.parent.type.spec.tableRole == "row" && $headCell.parent.type.spec.tableRole == "row" && $anchorCell.index() < $anchorCell.parent.childCount && $headCell.index() < $headCell.parent.childCount && inSameTable($anchorCell, $headCell))
  747. return new CellSelection($anchorCell, $headCell);
  748. else
  749. return Selection.near($headCell, 1);
  750. }
  751. };
  752. function drawCellSelection(state) {
  753. if (!(state.selection instanceof CellSelection))
  754. return null;
  755. const cells = [];
  756. state.selection.forEachCell((node, pos) => {
  757. cells.push(
  758. Decoration.node(pos, pos + node.nodeSize, { class: "selectedCell" })
  759. );
  760. });
  761. return DecorationSet.create(state.doc, cells);
  762. }
  763. function isCellBoundarySelection({ $from, $to }) {
  764. if ($from.pos == $to.pos || $from.pos < $from.pos - 6)
  765. return false;
  766. let afterFrom = $from.pos;
  767. let beforeTo = $to.pos;
  768. let depth = $from.depth;
  769. for (; depth >= 0; depth--, afterFrom++)
  770. if ($from.after(depth + 1) < $from.end(depth))
  771. break;
  772. for (let d = $to.depth; d >= 0; d--, beforeTo--)
  773. if ($to.before(d + 1) > $to.start(d))
  774. break;
  775. return afterFrom == beforeTo && /row|table/.test($from.node(depth).type.spec.tableRole);
  776. }
  777. function isTextSelectionAcrossCells({ $from, $to }) {
  778. let fromCellBoundaryNode;
  779. let toCellBoundaryNode;
  780. for (let i = $from.depth; i > 0; i--) {
  781. const node = $from.node(i);
  782. if (node.type.spec.tableRole === "cell" || node.type.spec.tableRole === "header_cell") {
  783. fromCellBoundaryNode = node;
  784. break;
  785. }
  786. }
  787. for (let i = $to.depth; i > 0; i--) {
  788. const node = $to.node(i);
  789. if (node.type.spec.tableRole === "cell" || node.type.spec.tableRole === "header_cell") {
  790. toCellBoundaryNode = node;
  791. break;
  792. }
  793. }
  794. return fromCellBoundaryNode !== toCellBoundaryNode && $to.parentOffset === 0;
  795. }
  796. function normalizeSelection(state, tr, allowTableNodeSelection) {
  797. const sel = (tr || state).selection;
  798. const doc = (tr || state).doc;
  799. let normalize;
  800. let role;
  801. if (sel instanceof NodeSelection2 && (role = sel.node.type.spec.tableRole)) {
  802. if (role == "cell" || role == "header_cell") {
  803. normalize = CellSelection.create(doc, sel.from);
  804. } else if (role == "row") {
  805. const $cell = doc.resolve(sel.from + 1);
  806. normalize = CellSelection.rowSelection($cell, $cell);
  807. } else if (!allowTableNodeSelection) {
  808. const map = TableMap.get(sel.node);
  809. const start = sel.from + 1;
  810. const lastCell = start + map.map[map.width * map.height - 1];
  811. normalize = CellSelection.create(doc, start + 1, lastCell);
  812. }
  813. } else if (sel instanceof TextSelection && isCellBoundarySelection(sel)) {
  814. normalize = TextSelection.create(doc, sel.from);
  815. } else if (sel instanceof TextSelection && isTextSelectionAcrossCells(sel)) {
  816. normalize = TextSelection.create(doc, sel.$from.start(), sel.$from.end());
  817. }
  818. if (normalize)
  819. (tr || (tr = state.tr)).setSelection(normalize);
  820. return tr;
  821. }
  822. // src/fixtables.ts
  823. import { PluginKey as PluginKey2 } from "prosemirror-state";
  824. var fixTablesKey = new PluginKey2("fix-tables");
  825. function changedDescendants(old, cur, offset, f) {
  826. const oldSize = old.childCount, curSize = cur.childCount;
  827. outer:
  828. for (let i = 0, j = 0; i < curSize; i++) {
  829. const child = cur.child(i);
  830. for (let scan = j, e = Math.min(oldSize, i + 3); scan < e; scan++) {
  831. if (old.child(scan) == child) {
  832. j = scan + 1;
  833. offset += child.nodeSize;
  834. continue outer;
  835. }
  836. }
  837. f(child, offset);
  838. if (j < oldSize && old.child(j).sameMarkup(child))
  839. changedDescendants(old.child(j), child, offset + 1, f);
  840. else
  841. child.nodesBetween(0, child.content.size, f, offset + 1);
  842. offset += child.nodeSize;
  843. }
  844. }
  845. function fixTables(state, oldState) {
  846. let tr;
  847. const check = (node, pos) => {
  848. if (node.type.spec.tableRole == "table")
  849. tr = fixTable(state, node, pos, tr);
  850. };
  851. if (!oldState)
  852. state.doc.descendants(check);
  853. else if (oldState.doc != state.doc)
  854. changedDescendants(oldState.doc, state.doc, 0, check);
  855. return tr;
  856. }
  857. function fixTable(state, table, tablePos, tr) {
  858. const map = TableMap.get(table);
  859. if (!map.problems)
  860. return tr;
  861. if (!tr)
  862. tr = state.tr;
  863. const mustAdd = [];
  864. for (let i = 0; i < map.height; i++)
  865. mustAdd.push(0);
  866. for (let i = 0; i < map.problems.length; i++) {
  867. const prob = map.problems[i];
  868. if (prob.type == "collision") {
  869. const cell = table.nodeAt(prob.pos);
  870. if (!cell)
  871. continue;
  872. const attrs = cell.attrs;
  873. for (let j = 0; j < attrs.rowspan; j++)
  874. mustAdd[prob.row + j] += prob.n;
  875. tr.setNodeMarkup(
  876. tr.mapping.map(tablePos + 1 + prob.pos),
  877. null,
  878. removeColSpan(attrs, attrs.colspan - prob.n, prob.n)
  879. );
  880. } else if (prob.type == "missing") {
  881. mustAdd[prob.row] += prob.n;
  882. } else if (prob.type == "overlong_rowspan") {
  883. const cell = table.nodeAt(prob.pos);
  884. if (!cell)
  885. continue;
  886. tr.setNodeMarkup(tr.mapping.map(tablePos + 1 + prob.pos), null, {
  887. ...cell.attrs,
  888. rowspan: cell.attrs.rowspan - prob.n
  889. });
  890. } else if (prob.type == "colwidth mismatch") {
  891. const cell = table.nodeAt(prob.pos);
  892. if (!cell)
  893. continue;
  894. tr.setNodeMarkup(tr.mapping.map(tablePos + 1 + prob.pos), null, {
  895. ...cell.attrs,
  896. colwidth: prob.colwidth
  897. });
  898. }
  899. }
  900. let first, last;
  901. for (let i = 0; i < mustAdd.length; i++)
  902. if (mustAdd[i]) {
  903. if (first == null)
  904. first = i;
  905. last = i;
  906. }
  907. for (let i = 0, pos = tablePos + 1; i < map.height; i++) {
  908. const row = table.child(i);
  909. const end = pos + row.nodeSize;
  910. const add = mustAdd[i];
  911. if (add > 0) {
  912. let role = "cell";
  913. if (row.firstChild) {
  914. role = row.firstChild.type.spec.tableRole;
  915. }
  916. const nodes = [];
  917. for (let j = 0; j < add; j++) {
  918. const node = tableNodeTypes(state.schema)[role].createAndFill();
  919. if (node)
  920. nodes.push(node);
  921. }
  922. const side = (i == 0 || first == i - 1) && last == i ? pos + 1 : end - 1;
  923. tr.insert(tr.mapping.map(side), nodes);
  924. }
  925. pos = end;
  926. }
  927. return tr.setMeta(fixTablesKey, { fixTables: true });
  928. }
  929. // src/input.ts
  930. import { Fragment as Fragment3, Slice as Slice3 } from "prosemirror-model";
  931. import {
  932. Selection as Selection2,
  933. TextSelection as TextSelection2
  934. } from "prosemirror-state";
  935. import { keydownHandler } from "prosemirror-keymap";
  936. // src/copypaste.ts
  937. import { Fragment as Fragment2, Slice as Slice2 } from "prosemirror-model";
  938. import { Transform } from "prosemirror-transform";
  939. function pastedCells(slice) {
  940. if (!slice.size)
  941. return null;
  942. let { content, openStart, openEnd } = slice;
  943. while (content.childCount == 1 && (openStart > 0 && openEnd > 0 || content.child(0).type.spec.tableRole == "table")) {
  944. openStart--;
  945. openEnd--;
  946. content = content.child(0).content;
  947. }
  948. const first = content.child(0);
  949. const role = first.type.spec.tableRole;
  950. const schema = first.type.schema, rows = [];
  951. if (role == "row") {
  952. for (let i = 0; i < content.childCount; i++) {
  953. let cells = content.child(i).content;
  954. const left = i ? 0 : Math.max(0, openStart - 1);
  955. const right = i < content.childCount - 1 ? 0 : Math.max(0, openEnd - 1);
  956. if (left || right)
  957. cells = fitSlice(
  958. tableNodeTypes(schema).row,
  959. new Slice2(cells, left, right)
  960. ).content;
  961. rows.push(cells);
  962. }
  963. } else if (role == "cell" || role == "header_cell") {
  964. rows.push(
  965. openStart || openEnd ? fitSlice(
  966. tableNodeTypes(schema).row,
  967. new Slice2(content, openStart, openEnd)
  968. ).content : content
  969. );
  970. } else {
  971. return null;
  972. }
  973. return ensureRectangular(schema, rows);
  974. }
  975. function ensureRectangular(schema, rows) {
  976. const widths = [];
  977. for (let i = 0; i < rows.length; i++) {
  978. const row = rows[i];
  979. for (let j = row.childCount - 1; j >= 0; j--) {
  980. const { rowspan, colspan } = row.child(j).attrs;
  981. for (let r = i; r < i + rowspan; r++)
  982. widths[r] = (widths[r] || 0) + colspan;
  983. }
  984. }
  985. let width = 0;
  986. for (let r = 0; r < widths.length; r++)
  987. width = Math.max(width, widths[r]);
  988. for (let r = 0; r < widths.length; r++) {
  989. if (r >= rows.length)
  990. rows.push(Fragment2.empty);
  991. if (widths[r] < width) {
  992. const empty = tableNodeTypes(schema).cell.createAndFill();
  993. const cells = [];
  994. for (let i = widths[r]; i < width; i++) {
  995. cells.push(empty);
  996. }
  997. rows[r] = rows[r].append(Fragment2.from(cells));
  998. }
  999. }
  1000. return { height: rows.length, width, rows };
  1001. }
  1002. function fitSlice(nodeType, slice) {
  1003. const node = nodeType.createAndFill();
  1004. const tr = new Transform(node).replace(0, node.content.size, slice);
  1005. return tr.doc;
  1006. }
  1007. function clipCells({ width, height, rows }, newWidth, newHeight) {
  1008. if (width != newWidth) {
  1009. const added = [];
  1010. const newRows = [];
  1011. for (let row = 0; row < rows.length; row++) {
  1012. const frag = rows[row], cells = [];
  1013. for (let col = added[row] || 0, i = 0; col < newWidth; i++) {
  1014. let cell = frag.child(i % frag.childCount);
  1015. if (col + cell.attrs.colspan > newWidth)
  1016. cell = cell.type.createChecked(
  1017. removeColSpan(
  1018. cell.attrs,
  1019. cell.attrs.colspan,
  1020. col + cell.attrs.colspan - newWidth
  1021. ),
  1022. cell.content
  1023. );
  1024. cells.push(cell);
  1025. col += cell.attrs.colspan;
  1026. for (let j = 1; j < cell.attrs.rowspan; j++)
  1027. added[row + j] = (added[row + j] || 0) + cell.attrs.colspan;
  1028. }
  1029. newRows.push(Fragment2.from(cells));
  1030. }
  1031. rows = newRows;
  1032. width = newWidth;
  1033. }
  1034. if (height != newHeight) {
  1035. const newRows = [];
  1036. for (let row = 0, i = 0; row < newHeight; row++, i++) {
  1037. const cells = [], source = rows[i % height];
  1038. for (let j = 0; j < source.childCount; j++) {
  1039. let cell = source.child(j);
  1040. if (row + cell.attrs.rowspan > newHeight)
  1041. cell = cell.type.create(
  1042. {
  1043. ...cell.attrs,
  1044. rowspan: Math.max(1, newHeight - cell.attrs.rowspan)
  1045. },
  1046. cell.content
  1047. );
  1048. cells.push(cell);
  1049. }
  1050. newRows.push(Fragment2.from(cells));
  1051. }
  1052. rows = newRows;
  1053. height = newHeight;
  1054. }
  1055. return { width, height, rows };
  1056. }
  1057. function growTable(tr, map, table, start, width, height, mapFrom) {
  1058. const schema = tr.doc.type.schema;
  1059. const types = tableNodeTypes(schema);
  1060. let empty;
  1061. let emptyHead;
  1062. if (width > map.width) {
  1063. for (let row = 0, rowEnd = 0; row < map.height; row++) {
  1064. const rowNode = table.child(row);
  1065. rowEnd += rowNode.nodeSize;
  1066. const cells = [];
  1067. let add;
  1068. if (rowNode.lastChild == null || rowNode.lastChild.type == types.cell)
  1069. add = empty || (empty = types.cell.createAndFill());
  1070. else
  1071. add = emptyHead || (emptyHead = types.header_cell.createAndFill());
  1072. for (let i = map.width; i < width; i++)
  1073. cells.push(add);
  1074. tr.insert(tr.mapping.slice(mapFrom).map(rowEnd - 1 + start), cells);
  1075. }
  1076. }
  1077. if (height > map.height) {
  1078. const cells = [];
  1079. for (let i = 0, start2 = (map.height - 1) * map.width; i < Math.max(map.width, width); i++) {
  1080. const header = i >= map.width ? false : table.nodeAt(map.map[start2 + i]).type == types.header_cell;
  1081. cells.push(
  1082. header ? emptyHead || (emptyHead = types.header_cell.createAndFill()) : empty || (empty = types.cell.createAndFill())
  1083. );
  1084. }
  1085. const emptyRow = types.row.create(null, Fragment2.from(cells)), rows = [];
  1086. for (let i = map.height; i < height; i++)
  1087. rows.push(emptyRow);
  1088. tr.insert(tr.mapping.slice(mapFrom).map(start + table.nodeSize - 2), rows);
  1089. }
  1090. return !!(empty || emptyHead);
  1091. }
  1092. function isolateHorizontal(tr, map, table, start, left, right, top, mapFrom) {
  1093. if (top == 0 || top == map.height)
  1094. return false;
  1095. let found = false;
  1096. for (let col = left; col < right; col++) {
  1097. const index = top * map.width + col, pos = map.map[index];
  1098. if (map.map[index - map.width] == pos) {
  1099. found = true;
  1100. const cell = table.nodeAt(pos);
  1101. const { top: cellTop, left: cellLeft } = map.findCell(pos);
  1102. tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(pos + start), null, {
  1103. ...cell.attrs,
  1104. rowspan: top - cellTop
  1105. });
  1106. tr.insert(
  1107. tr.mapping.slice(mapFrom).map(map.positionAt(top, cellLeft, table)),
  1108. cell.type.createAndFill({
  1109. ...cell.attrs,
  1110. rowspan: cellTop + cell.attrs.rowspan - top
  1111. })
  1112. );
  1113. col += cell.attrs.colspan - 1;
  1114. }
  1115. }
  1116. return found;
  1117. }
  1118. function isolateVertical(tr, map, table, start, top, bottom, left, mapFrom) {
  1119. if (left == 0 || left == map.width)
  1120. return false;
  1121. let found = false;
  1122. for (let row = top; row < bottom; row++) {
  1123. const index = row * map.width + left, pos = map.map[index];
  1124. if (map.map[index - 1] == pos) {
  1125. found = true;
  1126. const cell = table.nodeAt(pos);
  1127. const cellLeft = map.colCount(pos);
  1128. const updatePos = tr.mapping.slice(mapFrom).map(pos + start);
  1129. tr.setNodeMarkup(
  1130. updatePos,
  1131. null,
  1132. removeColSpan(
  1133. cell.attrs,
  1134. left - cellLeft,
  1135. cell.attrs.colspan - (left - cellLeft)
  1136. )
  1137. );
  1138. tr.insert(
  1139. updatePos + cell.nodeSize,
  1140. cell.type.createAndFill(
  1141. removeColSpan(cell.attrs, 0, left - cellLeft)
  1142. )
  1143. );
  1144. row += cell.attrs.rowspan - 1;
  1145. }
  1146. }
  1147. return found;
  1148. }
  1149. function insertCells(state, dispatch, tableStart, rect, cells) {
  1150. let table = tableStart ? state.doc.nodeAt(tableStart - 1) : state.doc;
  1151. if (!table) {
  1152. throw new Error("No table found");
  1153. }
  1154. let map = TableMap.get(table);
  1155. const { top, left } = rect;
  1156. const right = left + cells.width, bottom = top + cells.height;
  1157. const tr = state.tr;
  1158. let mapFrom = 0;
  1159. function recomp() {
  1160. table = tableStart ? tr.doc.nodeAt(tableStart - 1) : tr.doc;
  1161. if (!table) {
  1162. throw new Error("No table found");
  1163. }
  1164. map = TableMap.get(table);
  1165. mapFrom = tr.mapping.maps.length;
  1166. }
  1167. if (growTable(tr, map, table, tableStart, right, bottom, mapFrom))
  1168. recomp();
  1169. if (isolateHorizontal(tr, map, table, tableStart, left, right, top, mapFrom))
  1170. recomp();
  1171. if (isolateHorizontal(tr, map, table, tableStart, left, right, bottom, mapFrom))
  1172. recomp();
  1173. if (isolateVertical(tr, map, table, tableStart, top, bottom, left, mapFrom))
  1174. recomp();
  1175. if (isolateVertical(tr, map, table, tableStart, top, bottom, right, mapFrom))
  1176. recomp();
  1177. for (let row = top; row < bottom; row++) {
  1178. const from = map.positionAt(row, left, table), to = map.positionAt(row, right, table);
  1179. tr.replace(
  1180. tr.mapping.slice(mapFrom).map(from + tableStart),
  1181. tr.mapping.slice(mapFrom).map(to + tableStart),
  1182. new Slice2(cells.rows[row - top], 0, 0)
  1183. );
  1184. }
  1185. recomp();
  1186. tr.setSelection(
  1187. new CellSelection(
  1188. tr.doc.resolve(tableStart + map.positionAt(top, left, table)),
  1189. tr.doc.resolve(tableStart + map.positionAt(bottom - 1, right - 1, table))
  1190. )
  1191. );
  1192. dispatch(tr);
  1193. }
  1194. // src/input.ts
  1195. var handleKeyDown = keydownHandler({
  1196. ArrowLeft: arrow("horiz", -1),
  1197. ArrowRight: arrow("horiz", 1),
  1198. ArrowUp: arrow("vert", -1),
  1199. ArrowDown: arrow("vert", 1),
  1200. "Shift-ArrowLeft": shiftArrow("horiz", -1),
  1201. "Shift-ArrowRight": shiftArrow("horiz", 1),
  1202. "Shift-ArrowUp": shiftArrow("vert", -1),
  1203. "Shift-ArrowDown": shiftArrow("vert", 1),
  1204. Backspace: deleteCellSelection,
  1205. "Mod-Backspace": deleteCellSelection,
  1206. Delete: deleteCellSelection,
  1207. "Mod-Delete": deleteCellSelection
  1208. });
  1209. function maybeSetSelection(state, dispatch, selection) {
  1210. if (selection.eq(state.selection))
  1211. return false;
  1212. if (dispatch)
  1213. dispatch(state.tr.setSelection(selection).scrollIntoView());
  1214. return true;
  1215. }
  1216. function arrow(axis, dir) {
  1217. return (state, dispatch, view) => {
  1218. if (!view)
  1219. return false;
  1220. const sel = state.selection;
  1221. if (sel instanceof CellSelection) {
  1222. return maybeSetSelection(
  1223. state,
  1224. dispatch,
  1225. Selection2.near(sel.$headCell, dir)
  1226. );
  1227. }
  1228. if (axis != "horiz" && !sel.empty)
  1229. return false;
  1230. const end = atEndOfCell(view, axis, dir);
  1231. if (end == null)
  1232. return false;
  1233. if (axis == "horiz") {
  1234. return maybeSetSelection(
  1235. state,
  1236. dispatch,
  1237. Selection2.near(state.doc.resolve(sel.head + dir), dir)
  1238. );
  1239. } else {
  1240. const $cell = state.doc.resolve(end);
  1241. const $next = nextCell($cell, axis, dir);
  1242. let newSel;
  1243. if ($next)
  1244. newSel = Selection2.near($next, 1);
  1245. else if (dir < 0)
  1246. newSel = Selection2.near(state.doc.resolve($cell.before(-1)), -1);
  1247. else
  1248. newSel = Selection2.near(state.doc.resolve($cell.after(-1)), 1);
  1249. return maybeSetSelection(state, dispatch, newSel);
  1250. }
  1251. };
  1252. }
  1253. function shiftArrow(axis, dir) {
  1254. return (state, dispatch, view) => {
  1255. if (!view)
  1256. return false;
  1257. const sel = state.selection;
  1258. let cellSel;
  1259. if (sel instanceof CellSelection) {
  1260. cellSel = sel;
  1261. } else {
  1262. const end = atEndOfCell(view, axis, dir);
  1263. if (end == null)
  1264. return false;
  1265. cellSel = new CellSelection(state.doc.resolve(end));
  1266. }
  1267. const $head = nextCell(cellSel.$headCell, axis, dir);
  1268. if (!$head)
  1269. return false;
  1270. return maybeSetSelection(
  1271. state,
  1272. dispatch,
  1273. new CellSelection(cellSel.$anchorCell, $head)
  1274. );
  1275. };
  1276. }
  1277. function deleteCellSelection(state, dispatch) {
  1278. const sel = state.selection;
  1279. if (!(sel instanceof CellSelection))
  1280. return false;
  1281. if (dispatch) {
  1282. const tr = state.tr;
  1283. const baseContent = tableNodeTypes(state.schema).cell.createAndFill().content;
  1284. sel.forEachCell((cell, pos) => {
  1285. if (!cell.content.eq(baseContent))
  1286. tr.replace(
  1287. tr.mapping.map(pos + 1),
  1288. tr.mapping.map(pos + cell.nodeSize - 1),
  1289. new Slice3(baseContent, 0, 0)
  1290. );
  1291. });
  1292. if (tr.docChanged)
  1293. dispatch(tr);
  1294. }
  1295. return true;
  1296. }
  1297. function handleTripleClick(view, pos) {
  1298. const doc = view.state.doc, $cell = cellAround(doc.resolve(pos));
  1299. if (!$cell)
  1300. return false;
  1301. view.dispatch(view.state.tr.setSelection(new CellSelection($cell)));
  1302. return true;
  1303. }
  1304. function handlePaste(view, _, slice) {
  1305. if (!isInTable(view.state))
  1306. return false;
  1307. let cells = pastedCells(slice);
  1308. const sel = view.state.selection;
  1309. if (sel instanceof CellSelection) {
  1310. if (!cells)
  1311. cells = {
  1312. width: 1,
  1313. height: 1,
  1314. rows: [
  1315. Fragment3.from(
  1316. fitSlice(tableNodeTypes(view.state.schema).cell, slice)
  1317. )
  1318. ]
  1319. };
  1320. const table = sel.$anchorCell.node(-1);
  1321. const start = sel.$anchorCell.start(-1);
  1322. const rect = TableMap.get(table).rectBetween(
  1323. sel.$anchorCell.pos - start,
  1324. sel.$headCell.pos - start
  1325. );
  1326. cells = clipCells(cells, rect.right - rect.left, rect.bottom - rect.top);
  1327. insertCells(view.state, view.dispatch, start, rect, cells);
  1328. return true;
  1329. } else if (cells) {
  1330. const $cell = selectionCell(view.state);
  1331. const start = $cell.start(-1);
  1332. insertCells(
  1333. view.state,
  1334. view.dispatch,
  1335. start,
  1336. TableMap.get($cell.node(-1)).findCell($cell.pos - start),
  1337. cells
  1338. );
  1339. return true;
  1340. } else {
  1341. return false;
  1342. }
  1343. }
  1344. function handleMouseDown(view, startEvent) {
  1345. var _a;
  1346. if (startEvent.ctrlKey || startEvent.metaKey)
  1347. return;
  1348. const startDOMCell = domInCell(view, startEvent.target);
  1349. let $anchor;
  1350. if (startEvent.shiftKey && view.state.selection instanceof CellSelection) {
  1351. setCellSelection(view.state.selection.$anchorCell, startEvent);
  1352. startEvent.preventDefault();
  1353. } else if (startEvent.shiftKey && startDOMCell && ($anchor = cellAround(view.state.selection.$anchor)) != null && ((_a = cellUnderMouse(view, startEvent)) == null ? void 0 : _a.pos) != $anchor.pos) {
  1354. setCellSelection($anchor, startEvent);
  1355. startEvent.preventDefault();
  1356. } else if (!startDOMCell) {
  1357. return;
  1358. }
  1359. function setCellSelection($anchor2, event) {
  1360. let $head = cellUnderMouse(view, event);
  1361. const starting = tableEditingKey.getState(view.state) == null;
  1362. if (!$head || !inSameTable($anchor2, $head)) {
  1363. if (starting)
  1364. $head = $anchor2;
  1365. else
  1366. return;
  1367. }
  1368. const selection = new CellSelection($anchor2, $head);
  1369. if (starting || !view.state.selection.eq(selection)) {
  1370. const tr = view.state.tr.setSelection(selection);
  1371. if (starting)
  1372. tr.setMeta(tableEditingKey, $anchor2.pos);
  1373. view.dispatch(tr);
  1374. }
  1375. }
  1376. function stop() {
  1377. view.root.removeEventListener("mouseup", stop);
  1378. view.root.removeEventListener("dragstart", stop);
  1379. view.root.removeEventListener("mousemove", move);
  1380. if (tableEditingKey.getState(view.state) != null)
  1381. view.dispatch(view.state.tr.setMeta(tableEditingKey, -1));
  1382. }
  1383. function move(_event) {
  1384. const event = _event;
  1385. const anchor = tableEditingKey.getState(view.state);
  1386. let $anchor2;
  1387. if (anchor != null) {
  1388. $anchor2 = view.state.doc.resolve(anchor);
  1389. } else if (domInCell(view, event.target) != startDOMCell) {
  1390. $anchor2 = cellUnderMouse(view, startEvent);
  1391. if (!$anchor2)
  1392. return stop();
  1393. }
  1394. if ($anchor2)
  1395. setCellSelection($anchor2, event);
  1396. }
  1397. view.root.addEventListener("mouseup", stop);
  1398. view.root.addEventListener("dragstart", stop);
  1399. view.root.addEventListener("mousemove", move);
  1400. }
  1401. function atEndOfCell(view, axis, dir) {
  1402. if (!(view.state.selection instanceof TextSelection2))
  1403. return null;
  1404. const { $head } = view.state.selection;
  1405. for (let d = $head.depth - 1; d >= 0; d--) {
  1406. const parent = $head.node(d), index = dir < 0 ? $head.index(d) : $head.indexAfter(d);
  1407. if (index != (dir < 0 ? 0 : parent.childCount))
  1408. return null;
  1409. if (parent.type.spec.tableRole == "cell" || parent.type.spec.tableRole == "header_cell") {
  1410. const cellPos = $head.before(d);
  1411. const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
  1412. return view.endOfTextblock(dirStr) ? cellPos : null;
  1413. }
  1414. }
  1415. return null;
  1416. }
  1417. function domInCell(view, dom) {
  1418. for (; dom && dom != view.dom; dom = dom.parentNode) {
  1419. if (dom.nodeName == "TD" || dom.nodeName == "TH") {
  1420. return dom;
  1421. }
  1422. }
  1423. return null;
  1424. }
  1425. function cellUnderMouse(view, event) {
  1426. const mousePos = view.posAtCoords({
  1427. left: event.clientX,
  1428. top: event.clientY
  1429. });
  1430. if (!mousePos)
  1431. return null;
  1432. return mousePos ? cellAround(view.state.doc.resolve(mousePos.pos)) : null;
  1433. }
  1434. // src/columnresizing.ts
  1435. import { Plugin, PluginKey as PluginKey3 } from "prosemirror-state";
  1436. import {
  1437. Decoration as Decoration2,
  1438. DecorationSet as DecorationSet2
  1439. } from "prosemirror-view";
  1440. // src/tableview.ts
  1441. var TableView = class {
  1442. constructor(node, cellMinWidth) {
  1443. this.node = node;
  1444. this.cellMinWidth = cellMinWidth;
  1445. this.dom = document.createElement("div");
  1446. this.dom.className = "tableWrapper";
  1447. this.table = this.dom.appendChild(document.createElement("table"));
  1448. this.colgroup = this.table.appendChild(document.createElement("colgroup"));
  1449. updateColumnsOnResize(node, this.colgroup, this.table, cellMinWidth);
  1450. this.contentDOM = this.table.appendChild(document.createElement("tbody"));
  1451. }
  1452. update(node) {
  1453. if (node.type != this.node.type)
  1454. return false;
  1455. this.node = node;
  1456. updateColumnsOnResize(node, this.colgroup, this.table, this.cellMinWidth);
  1457. return true;
  1458. }
  1459. ignoreMutation(record) {
  1460. return record.type == "attributes" && (record.target == this.table || this.colgroup.contains(record.target));
  1461. }
  1462. };
  1463. function updateColumnsOnResize(node, colgroup, table, cellMinWidth, overrideCol, overrideValue) {
  1464. var _a;
  1465. let totalWidth = 0;
  1466. let fixedWidth = true;
  1467. let nextDOM = colgroup.firstChild;
  1468. const row = node.firstChild;
  1469. if (!row)
  1470. return;
  1471. for (let i = 0, col = 0; i < row.childCount; i++) {
  1472. const { colspan, colwidth } = row.child(i).attrs;
  1473. for (let j = 0; j < colspan; j++, col++) {
  1474. const hasWidth = overrideCol == col ? overrideValue : colwidth && colwidth[j];
  1475. const cssWidth = hasWidth ? hasWidth + "px" : "";
  1476. totalWidth += hasWidth || cellMinWidth;
  1477. if (!hasWidth)
  1478. fixedWidth = false;
  1479. if (!nextDOM) {
  1480. colgroup.appendChild(document.createElement("col")).style.width = cssWidth;
  1481. } else {
  1482. if (nextDOM.style.width != cssWidth)
  1483. nextDOM.style.width = cssWidth;
  1484. nextDOM = nextDOM.nextSibling;
  1485. }
  1486. }
  1487. }
  1488. while (nextDOM) {
  1489. const after = nextDOM.nextSibling;
  1490. (_a = nextDOM.parentNode) == null ? void 0 : _a.removeChild(nextDOM);
  1491. nextDOM = after;
  1492. }
  1493. if (fixedWidth) {
  1494. table.style.width = totalWidth + "px";
  1495. table.style.minWidth = "";
  1496. } else {
  1497. table.style.width = "";
  1498. table.style.minWidth = totalWidth + "px";
  1499. }
  1500. }
  1501. // src/columnresizing.ts
  1502. var columnResizingPluginKey = new PluginKey3(
  1503. "tableColumnResizing"
  1504. );
  1505. function columnResizing({
  1506. handleWidth = 5,
  1507. cellMinWidth = 25,
  1508. View = TableView,
  1509. lastColumnResizable = true
  1510. } = {}) {
  1511. const plugin = new Plugin({
  1512. key: columnResizingPluginKey,
  1513. state: {
  1514. init(_, state) {
  1515. plugin.spec.props.nodeViews[tableNodeTypes(state.schema).table.name] = (node, view) => new View(node, cellMinWidth, view);
  1516. return new ResizeState(-1, false);
  1517. },
  1518. apply(tr, prev) {
  1519. return prev.apply(tr);
  1520. }
  1521. },
  1522. props: {
  1523. attributes: (state) => {
  1524. const pluginState = columnResizingPluginKey.getState(state);
  1525. return pluginState && pluginState.activeHandle > -1 ? { class: "resize-cursor" } : {};
  1526. },
  1527. handleDOMEvents: {
  1528. mousemove: (view, event) => {
  1529. handleMouseMove(
  1530. view,
  1531. event,
  1532. handleWidth,
  1533. cellMinWidth,
  1534. lastColumnResizable
  1535. );
  1536. },
  1537. mouseleave: (view) => {
  1538. handleMouseLeave(view);
  1539. },
  1540. mousedown: (view, event) => {
  1541. handleMouseDown2(view, event, cellMinWidth);
  1542. }
  1543. },
  1544. decorations: (state) => {
  1545. const pluginState = columnResizingPluginKey.getState(state);
  1546. if (pluginState && pluginState.activeHandle > -1) {
  1547. return handleDecorations(state, pluginState.activeHandle);
  1548. }
  1549. },
  1550. nodeViews: {}
  1551. }
  1552. });
  1553. return plugin;
  1554. }
  1555. var ResizeState = class _ResizeState {
  1556. constructor(activeHandle, dragging) {
  1557. this.activeHandle = activeHandle;
  1558. this.dragging = dragging;
  1559. }
  1560. apply(tr) {
  1561. const state = this;
  1562. const action = tr.getMeta(columnResizingPluginKey);
  1563. if (action && action.setHandle != null)
  1564. return new _ResizeState(action.setHandle, false);
  1565. if (action && action.setDragging !== void 0)
  1566. return new _ResizeState(state.activeHandle, action.setDragging);
  1567. if (state.activeHandle > -1 && tr.docChanged) {
  1568. let handle = tr.mapping.map(state.activeHandle, -1);
  1569. if (!pointsAtCell(tr.doc.resolve(handle))) {
  1570. handle = -1;
  1571. }
  1572. return new _ResizeState(handle, state.dragging);
  1573. }
  1574. return state;
  1575. }
  1576. };
  1577. function handleMouseMove(view, event, handleWidth, cellMinWidth, lastColumnResizable) {
  1578. const pluginState = columnResizingPluginKey.getState(view.state);
  1579. if (!pluginState)
  1580. return;
  1581. if (!pluginState.dragging) {
  1582. const target = domCellAround(event.target);
  1583. let cell = -1;
  1584. if (target) {
  1585. const { left, right } = target.getBoundingClientRect();
  1586. if (event.clientX - left <= handleWidth)
  1587. cell = edgeCell(view, event, "left", handleWidth);
  1588. else if (right - event.clientX <= handleWidth)
  1589. cell = edgeCell(view, event, "right", handleWidth);
  1590. }
  1591. if (cell != pluginState.activeHandle) {
  1592. if (!lastColumnResizable && cell !== -1) {
  1593. const $cell = view.state.doc.resolve(cell);
  1594. const table = $cell.node(-1);
  1595. const map = TableMap.get(table);
  1596. const tableStart = $cell.start(-1);
  1597. const col = map.colCount($cell.pos - tableStart) + $cell.nodeAfter.attrs.colspan - 1;
  1598. if (col == map.width - 1) {
  1599. return;
  1600. }
  1601. }
  1602. updateHandle(view, cell);
  1603. }
  1604. }
  1605. }
  1606. function handleMouseLeave(view) {
  1607. const pluginState = columnResizingPluginKey.getState(view.state);
  1608. if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging)
  1609. updateHandle(view, -1);
  1610. }
  1611. function handleMouseDown2(view, event, cellMinWidth) {
  1612. const pluginState = columnResizingPluginKey.getState(view.state);
  1613. if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging)
  1614. return false;
  1615. const cell = view.state.doc.nodeAt(pluginState.activeHandle);
  1616. const width = currentColWidth(view, pluginState.activeHandle, cell.attrs);
  1617. view.dispatch(
  1618. view.state.tr.setMeta(columnResizingPluginKey, {
  1619. setDragging: { startX: event.clientX, startWidth: width }
  1620. })
  1621. );
  1622. function finish(event2) {
  1623. window.removeEventListener("mouseup", finish);
  1624. window.removeEventListener("mousemove", move);
  1625. const pluginState2 = columnResizingPluginKey.getState(view.state);
  1626. if (pluginState2 == null ? void 0 : pluginState2.dragging) {
  1627. updateColumnWidth(
  1628. view,
  1629. pluginState2.activeHandle,
  1630. draggedWidth(pluginState2.dragging, event2, cellMinWidth)
  1631. );
  1632. view.dispatch(
  1633. view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null })
  1634. );
  1635. }
  1636. }
  1637. function move(event2) {
  1638. if (!event2.which)
  1639. return finish(event2);
  1640. const pluginState2 = columnResizingPluginKey.getState(view.state);
  1641. if (!pluginState2)
  1642. return;
  1643. if (pluginState2.dragging) {
  1644. const dragged = draggedWidth(pluginState2.dragging, event2, cellMinWidth);
  1645. displayColumnWidth(view, pluginState2.activeHandle, dragged, cellMinWidth);
  1646. }
  1647. }
  1648. window.addEventListener("mouseup", finish);
  1649. window.addEventListener("mousemove", move);
  1650. event.preventDefault();
  1651. return true;
  1652. }
  1653. function currentColWidth(view, cellPos, { colspan, colwidth }) {
  1654. const width = colwidth && colwidth[colwidth.length - 1];
  1655. if (width)
  1656. return width;
  1657. const dom = view.domAtPos(cellPos);
  1658. const node = dom.node.childNodes[dom.offset];
  1659. let domWidth = node.offsetWidth, parts = colspan;
  1660. if (colwidth) {
  1661. for (let i = 0; i < colspan; i++)
  1662. if (colwidth[i]) {
  1663. domWidth -= colwidth[i];
  1664. parts--;
  1665. }
  1666. }
  1667. return domWidth / parts;
  1668. }
  1669. function domCellAround(target) {
  1670. while (target && target.nodeName != "TD" && target.nodeName != "TH")
  1671. target = target.classList && target.classList.contains("ProseMirror") ? null : target.parentNode;
  1672. return target;
  1673. }
  1674. function edgeCell(view, event, side, handleWidth) {
  1675. const offset = side == "right" ? -handleWidth : handleWidth;
  1676. const found = view.posAtCoords({
  1677. left: event.clientX + offset,
  1678. top: event.clientY
  1679. });
  1680. if (!found)
  1681. return -1;
  1682. const { pos } = found;
  1683. const $cell = cellAround(view.state.doc.resolve(pos));
  1684. if (!$cell)
  1685. return -1;
  1686. if (side == "right")
  1687. return $cell.pos;
  1688. const map = TableMap.get($cell.node(-1)), start = $cell.start(-1);
  1689. const index = map.map.indexOf($cell.pos - start);
  1690. return index % map.width == 0 ? -1 : start + map.map[index - 1];
  1691. }
  1692. function draggedWidth(dragging, event, cellMinWidth) {
  1693. const offset = event.clientX - dragging.startX;
  1694. return Math.max(cellMinWidth, dragging.startWidth + offset);
  1695. }
  1696. function updateHandle(view, value) {
  1697. view.dispatch(
  1698. view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value })
  1699. );
  1700. }
  1701. function updateColumnWidth(view, cell, width) {
  1702. const $cell = view.state.doc.resolve(cell);
  1703. const table = $cell.node(-1), map = TableMap.get(table), start = $cell.start(-1);
  1704. const col = map.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
  1705. const tr = view.state.tr;
  1706. for (let row = 0; row < map.height; row++) {
  1707. const mapIndex = row * map.width + col;
  1708. if (row && map.map[mapIndex] == map.map[mapIndex - map.width])
  1709. continue;
  1710. const pos = map.map[mapIndex];
  1711. const attrs = table.nodeAt(pos).attrs;
  1712. const index = attrs.colspan == 1 ? 0 : col - map.colCount(pos);
  1713. if (attrs.colwidth && attrs.colwidth[index] == width)
  1714. continue;
  1715. const colwidth = attrs.colwidth ? attrs.colwidth.slice() : zeroes(attrs.colspan);
  1716. colwidth[index] = width;
  1717. tr.setNodeMarkup(start + pos, null, { ...attrs, colwidth });
  1718. }
  1719. if (tr.docChanged)
  1720. view.dispatch(tr);
  1721. }
  1722. function displayColumnWidth(view, cell, width, cellMinWidth) {
  1723. const $cell = view.state.doc.resolve(cell);
  1724. const table = $cell.node(-1), start = $cell.start(-1);
  1725. const col = TableMap.get(table).colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
  1726. let dom = view.domAtPos($cell.start(-1)).node;
  1727. while (dom && dom.nodeName != "TABLE") {
  1728. dom = dom.parentNode;
  1729. }
  1730. if (!dom)
  1731. return;
  1732. updateColumnsOnResize(
  1733. table,
  1734. dom.firstChild,
  1735. dom,
  1736. cellMinWidth,
  1737. col,
  1738. width
  1739. );
  1740. }
  1741. function zeroes(n) {
  1742. return Array(n).fill(0);
  1743. }
  1744. function handleDecorations(state, cell) {
  1745. const decorations = [];
  1746. const $cell = state.doc.resolve(cell);
  1747. const table = $cell.node(-1);
  1748. if (!table) {
  1749. return DecorationSet2.empty;
  1750. }
  1751. const map = TableMap.get(table);
  1752. const start = $cell.start(-1);
  1753. const col = map.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan;
  1754. for (let row = 0; row < map.height; row++) {
  1755. const index = col + row * map.width - 1;
  1756. if ((col == map.width || map.map[index] != map.map[index + 1]) && (row == 0 || map.map[index] != map.map[index - map.width])) {
  1757. const cellPos = map.map[index];
  1758. const pos = start + cellPos + table.nodeAt(cellPos).nodeSize - 1;
  1759. const dom = document.createElement("div");
  1760. dom.className = "column-resize-handle";
  1761. decorations.push(Decoration2.widget(pos, dom));
  1762. }
  1763. }
  1764. return DecorationSet2.create(state.doc, decorations);
  1765. }
  1766. // src/commands.ts
  1767. import { Fragment as Fragment4 } from "prosemirror-model";
  1768. import {
  1769. TextSelection as TextSelection3
  1770. } from "prosemirror-state";
  1771. function selectedRect(state) {
  1772. const sel = state.selection;
  1773. const $pos = selectionCell(state);
  1774. const table = $pos.node(-1);
  1775. const tableStart = $pos.start(-1);
  1776. const map = TableMap.get(table);
  1777. const rect = sel instanceof CellSelection ? map.rectBetween(
  1778. sel.$anchorCell.pos - tableStart,
  1779. sel.$headCell.pos - tableStart
  1780. ) : map.findCell($pos.pos - tableStart);
  1781. return { ...rect, tableStart, map, table };
  1782. }
  1783. function addColumn(tr, { map, tableStart, table }, col) {
  1784. let refColumn = col > 0 ? -1 : 0;
  1785. if (columnIsHeader(map, table, col + refColumn)) {
  1786. refColumn = col == 0 || col == map.width ? null : 0;
  1787. }
  1788. for (let row = 0; row < map.height; row++) {
  1789. const index = row * map.width + col;
  1790. if (col > 0 && col < map.width && map.map[index - 1] == map.map[index]) {
  1791. const pos = map.map[index];
  1792. const cell = table.nodeAt(pos);
  1793. tr.setNodeMarkup(
  1794. tr.mapping.map(tableStart + pos),
  1795. null,
  1796. addColSpan(cell.attrs, col - map.colCount(pos))
  1797. );
  1798. row += cell.attrs.rowspan - 1;
  1799. } else {
  1800. const type = refColumn == null ? tableNodeTypes(table.type.schema).cell : table.nodeAt(map.map[index + refColumn]).type;
  1801. const pos = map.positionAt(row, col, table);
  1802. tr.insert(tr.mapping.map(tableStart + pos), type.createAndFill());
  1803. }
  1804. }
  1805. return tr;
  1806. }
  1807. function addColumnBefore(state, dispatch) {
  1808. if (!isInTable(state))
  1809. return false;
  1810. if (dispatch) {
  1811. const rect = selectedRect(state);
  1812. dispatch(addColumn(state.tr, rect, rect.left));
  1813. }
  1814. return true;
  1815. }
  1816. function addColumnAfter(state, dispatch) {
  1817. if (!isInTable(state))
  1818. return false;
  1819. if (dispatch) {
  1820. const rect = selectedRect(state);
  1821. dispatch(addColumn(state.tr, rect, rect.right));
  1822. }
  1823. return true;
  1824. }
  1825. function removeColumn(tr, { map, table, tableStart }, col) {
  1826. const mapStart = tr.mapping.maps.length;
  1827. for (let row = 0; row < map.height; ) {
  1828. const index = row * map.width + col;
  1829. const pos = map.map[index];
  1830. const cell = table.nodeAt(pos);
  1831. const attrs = cell.attrs;
  1832. if (col > 0 && map.map[index - 1] == pos || col < map.width - 1 && map.map[index + 1] == pos) {
  1833. tr.setNodeMarkup(
  1834. tr.mapping.slice(mapStart).map(tableStart + pos),
  1835. null,
  1836. removeColSpan(attrs, col - map.colCount(pos))
  1837. );
  1838. } else {
  1839. const start = tr.mapping.slice(mapStart).map(tableStart + pos);
  1840. tr.delete(start, start + cell.nodeSize);
  1841. }
  1842. row += attrs.rowspan;
  1843. }
  1844. }
  1845. function deleteColumn(state, dispatch) {
  1846. if (!isInTable(state))
  1847. return false;
  1848. if (dispatch) {
  1849. const rect = selectedRect(state);
  1850. const tr = state.tr;
  1851. if (rect.left == 0 && rect.right == rect.map.width)
  1852. return false;
  1853. for (let i = rect.right - 1; ; i--) {
  1854. removeColumn(tr, rect, i);
  1855. if (i == rect.left)
  1856. break;
  1857. const table = rect.tableStart ? tr.doc.nodeAt(rect.tableStart - 1) : tr.doc;
  1858. if (!table) {
  1859. throw RangeError("No table found");
  1860. }
  1861. rect.table = table;
  1862. rect.map = TableMap.get(table);
  1863. }
  1864. dispatch(tr);
  1865. }
  1866. return true;
  1867. }
  1868. function rowIsHeader(map, table, row) {
  1869. var _a;
  1870. const headerCell = tableNodeTypes(table.type.schema).header_cell;
  1871. for (let col = 0; col < map.width; col++)
  1872. if (((_a = table.nodeAt(map.map[col + row * map.width])) == null ? void 0 : _a.type) != headerCell)
  1873. return false;
  1874. return true;
  1875. }
  1876. function addRow(tr, { map, tableStart, table }, row) {
  1877. var _a;
  1878. let rowPos = tableStart;
  1879. for (let i = 0; i < row; i++)
  1880. rowPos += table.child(i).nodeSize;
  1881. const cells = [];
  1882. let refRow = row > 0 ? -1 : 0;
  1883. if (rowIsHeader(map, table, row + refRow))
  1884. refRow = row == 0 || row == map.height ? null : 0;
  1885. for (let col = 0, index = map.width * row; col < map.width; col++, index++) {
  1886. if (row > 0 && row < map.height && map.map[index] == map.map[index - map.width]) {
  1887. const pos = map.map[index];
  1888. const attrs = table.nodeAt(pos).attrs;
  1889. tr.setNodeMarkup(tableStart + pos, null, {
  1890. ...attrs,
  1891. rowspan: attrs.rowspan + 1
  1892. });
  1893. col += attrs.colspan - 1;
  1894. } else {
  1895. const type = refRow == null ? tableNodeTypes(table.type.schema).cell : (_a = table.nodeAt(map.map[index + refRow * map.width])) == null ? void 0 : _a.type;
  1896. const node = type == null ? void 0 : type.createAndFill();
  1897. if (node)
  1898. cells.push(node);
  1899. }
  1900. }
  1901. tr.insert(rowPos, tableNodeTypes(table.type.schema).row.create(null, cells));
  1902. return tr;
  1903. }
  1904. function addRowBefore(state, dispatch) {
  1905. if (!isInTable(state))
  1906. return false;
  1907. if (dispatch) {
  1908. const rect = selectedRect(state);
  1909. dispatch(addRow(state.tr, rect, rect.top));
  1910. }
  1911. return true;
  1912. }
  1913. function addRowAfter(state, dispatch) {
  1914. if (!isInTable(state))
  1915. return false;
  1916. if (dispatch) {
  1917. const rect = selectedRect(state);
  1918. dispatch(addRow(state.tr, rect, rect.bottom));
  1919. }
  1920. return true;
  1921. }
  1922. function removeRow(tr, { map, table, tableStart }, row) {
  1923. let rowPos = 0;
  1924. for (let i = 0; i < row; i++)
  1925. rowPos += table.child(i).nodeSize;
  1926. const nextRow = rowPos + table.child(row).nodeSize;
  1927. const mapFrom = tr.mapping.maps.length;
  1928. tr.delete(rowPos + tableStart, nextRow + tableStart);
  1929. const seen = /* @__PURE__ */ new Set();
  1930. for (let col = 0, index = row * map.width; col < map.width; col++, index++) {
  1931. const pos = map.map[index];
  1932. if (seen.has(pos))
  1933. continue;
  1934. seen.add(pos);
  1935. if (row > 0 && pos == map.map[index - map.width]) {
  1936. const attrs = table.nodeAt(pos).attrs;
  1937. tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(pos + tableStart), null, {
  1938. ...attrs,
  1939. rowspan: attrs.rowspan - 1
  1940. });
  1941. col += attrs.colspan - 1;
  1942. } else if (row < map.height && pos == map.map[index + map.width]) {
  1943. const cell = table.nodeAt(pos);
  1944. const attrs = cell.attrs;
  1945. const copy = cell.type.create(
  1946. { ...attrs, rowspan: cell.attrs.rowspan - 1 },
  1947. cell.content
  1948. );
  1949. const newPos = map.positionAt(row + 1, col, table);
  1950. tr.insert(tr.mapping.slice(mapFrom).map(tableStart + newPos), copy);
  1951. col += attrs.colspan - 1;
  1952. }
  1953. }
  1954. }
  1955. function deleteRow(state, dispatch) {
  1956. if (!isInTable(state))
  1957. return false;
  1958. if (dispatch) {
  1959. const rect = selectedRect(state), tr = state.tr;
  1960. if (rect.top == 0 && rect.bottom == rect.map.height)
  1961. return false;
  1962. for (let i = rect.bottom - 1; ; i--) {
  1963. removeRow(tr, rect, i);
  1964. if (i == rect.top)
  1965. break;
  1966. const table = rect.tableStart ? tr.doc.nodeAt(rect.tableStart - 1) : tr.doc;
  1967. if (!table) {
  1968. throw RangeError("No table found");
  1969. }
  1970. rect.table = table;
  1971. rect.map = TableMap.get(rect.table);
  1972. }
  1973. dispatch(tr);
  1974. }
  1975. return true;
  1976. }
  1977. function isEmpty(cell) {
  1978. const c = cell.content;
  1979. return c.childCount == 1 && c.child(0).isTextblock && c.child(0).childCount == 0;
  1980. }
  1981. function cellsOverlapRectangle({ width, height, map }, rect) {
  1982. let indexTop = rect.top * width + rect.left, indexLeft = indexTop;
  1983. let indexBottom = (rect.bottom - 1) * width + rect.left, indexRight = indexTop + (rect.right - rect.left - 1);
  1984. for (let i = rect.top; i < rect.bottom; i++) {
  1985. if (rect.left > 0 && map[indexLeft] == map[indexLeft - 1] || rect.right < width && map[indexRight] == map[indexRight + 1])
  1986. return true;
  1987. indexLeft += width;
  1988. indexRight += width;
  1989. }
  1990. for (let i = rect.left; i < rect.right; i++) {
  1991. if (rect.top > 0 && map[indexTop] == map[indexTop - width] || rect.bottom < height && map[indexBottom] == map[indexBottom + width])
  1992. return true;
  1993. indexTop++;
  1994. indexBottom++;
  1995. }
  1996. return false;
  1997. }
  1998. function mergeCells(state, dispatch) {
  1999. const sel = state.selection;
  2000. if (!(sel instanceof CellSelection) || sel.$anchorCell.pos == sel.$headCell.pos)
  2001. return false;
  2002. const rect = selectedRect(state), { map } = rect;
  2003. if (cellsOverlapRectangle(map, rect))
  2004. return false;
  2005. if (dispatch) {
  2006. const tr = state.tr;
  2007. const seen = {};
  2008. let content = Fragment4.empty;
  2009. let mergedPos;
  2010. let mergedCell;
  2011. for (let row = rect.top; row < rect.bottom; row++) {
  2012. for (let col = rect.left; col < rect.right; col++) {
  2013. const cellPos = map.map[row * map.width + col];
  2014. const cell = rect.table.nodeAt(cellPos);
  2015. if (seen[cellPos] || !cell)
  2016. continue;
  2017. seen[cellPos] = true;
  2018. if (mergedPos == null) {
  2019. mergedPos = cellPos;
  2020. mergedCell = cell;
  2021. } else {
  2022. if (!isEmpty(cell))
  2023. content = content.append(cell.content);
  2024. const mapped = tr.mapping.map(cellPos + rect.tableStart);
  2025. tr.delete(mapped, mapped + cell.nodeSize);
  2026. }
  2027. }
  2028. }
  2029. if (mergedPos == null || mergedCell == null) {
  2030. return true;
  2031. }
  2032. tr.setNodeMarkup(mergedPos + rect.tableStart, null, {
  2033. ...addColSpan(
  2034. mergedCell.attrs,
  2035. mergedCell.attrs.colspan,
  2036. rect.right - rect.left - mergedCell.attrs.colspan
  2037. ),
  2038. rowspan: rect.bottom - rect.top
  2039. });
  2040. if (content.size) {
  2041. const end = mergedPos + 1 + mergedCell.content.size;
  2042. const start = isEmpty(mergedCell) ? mergedPos + 1 : end;
  2043. tr.replaceWith(start + rect.tableStart, end + rect.tableStart, content);
  2044. }
  2045. tr.setSelection(
  2046. new CellSelection(tr.doc.resolve(mergedPos + rect.tableStart))
  2047. );
  2048. dispatch(tr);
  2049. }
  2050. return true;
  2051. }
  2052. function splitCell(state, dispatch) {
  2053. const nodeTypes = tableNodeTypes(state.schema);
  2054. return splitCellWithType(({ node }) => {
  2055. return nodeTypes[node.type.spec.tableRole];
  2056. })(state, dispatch);
  2057. }
  2058. function splitCellWithType(getCellType) {
  2059. return (state, dispatch) => {
  2060. var _a;
  2061. const sel = state.selection;
  2062. let cellNode;
  2063. let cellPos;
  2064. if (!(sel instanceof CellSelection)) {
  2065. cellNode = cellWrapping(sel.$from);
  2066. if (!cellNode)
  2067. return false;
  2068. cellPos = (_a = cellAround(sel.$from)) == null ? void 0 : _a.pos;
  2069. } else {
  2070. if (sel.$anchorCell.pos != sel.$headCell.pos)
  2071. return false;
  2072. cellNode = sel.$anchorCell.nodeAfter;
  2073. cellPos = sel.$anchorCell.pos;
  2074. }
  2075. if (cellNode == null || cellPos == null) {
  2076. return false;
  2077. }
  2078. if (cellNode.attrs.colspan == 1 && cellNode.attrs.rowspan == 1) {
  2079. return false;
  2080. }
  2081. if (dispatch) {
  2082. let baseAttrs = cellNode.attrs;
  2083. const attrs = [];
  2084. const colwidth = baseAttrs.colwidth;
  2085. if (baseAttrs.rowspan > 1)
  2086. baseAttrs = { ...baseAttrs, rowspan: 1 };
  2087. if (baseAttrs.colspan > 1)
  2088. baseAttrs = { ...baseAttrs, colspan: 1 };
  2089. const rect = selectedRect(state), tr = state.tr;
  2090. for (let i = 0; i < rect.right - rect.left; i++)
  2091. attrs.push(
  2092. colwidth ? {
  2093. ...baseAttrs,
  2094. colwidth: colwidth && colwidth[i] ? [colwidth[i]] : null
  2095. } : baseAttrs
  2096. );
  2097. let lastCell;
  2098. for (let row = rect.top; row < rect.bottom; row++) {
  2099. let pos = rect.map.positionAt(row, rect.left, rect.table);
  2100. if (row == rect.top)
  2101. pos += cellNode.nodeSize;
  2102. for (let col = rect.left, i = 0; col < rect.right; col++, i++) {
  2103. if (col == rect.left && row == rect.top)
  2104. continue;
  2105. tr.insert(
  2106. lastCell = tr.mapping.map(pos + rect.tableStart, 1),
  2107. getCellType({ node: cellNode, row, col }).createAndFill(attrs[i])
  2108. );
  2109. }
  2110. }
  2111. tr.setNodeMarkup(
  2112. cellPos,
  2113. getCellType({ node: cellNode, row: rect.top, col: rect.left }),
  2114. attrs[0]
  2115. );
  2116. if (sel instanceof CellSelection)
  2117. tr.setSelection(
  2118. new CellSelection(
  2119. tr.doc.resolve(sel.$anchorCell.pos),
  2120. lastCell ? tr.doc.resolve(lastCell) : void 0
  2121. )
  2122. );
  2123. dispatch(tr);
  2124. }
  2125. return true;
  2126. };
  2127. }
  2128. function setCellAttr(name, value) {
  2129. return function(state, dispatch) {
  2130. if (!isInTable(state))
  2131. return false;
  2132. const $cell = selectionCell(state);
  2133. if ($cell.nodeAfter.attrs[name] === value)
  2134. return false;
  2135. if (dispatch) {
  2136. const tr = state.tr;
  2137. if (state.selection instanceof CellSelection)
  2138. state.selection.forEachCell((node, pos) => {
  2139. if (node.attrs[name] !== value)
  2140. tr.setNodeMarkup(pos, null, {
  2141. ...node.attrs,
  2142. [name]: value
  2143. });
  2144. });
  2145. else
  2146. tr.setNodeMarkup($cell.pos, null, {
  2147. ...$cell.nodeAfter.attrs,
  2148. [name]: value
  2149. });
  2150. dispatch(tr);
  2151. }
  2152. return true;
  2153. };
  2154. }
  2155. function deprecated_toggleHeader(type) {
  2156. return function(state, dispatch) {
  2157. if (!isInTable(state))
  2158. return false;
  2159. if (dispatch) {
  2160. const types = tableNodeTypes(state.schema);
  2161. const rect = selectedRect(state), tr = state.tr;
  2162. const cells = rect.map.cellsInRect(
  2163. type == "column" ? {
  2164. left: rect.left,
  2165. top: 0,
  2166. right: rect.right,
  2167. bottom: rect.map.height
  2168. } : type == "row" ? {
  2169. left: 0,
  2170. top: rect.top,
  2171. right: rect.map.width,
  2172. bottom: rect.bottom
  2173. } : rect
  2174. );
  2175. const nodes = cells.map((pos) => rect.table.nodeAt(pos));
  2176. for (let i = 0; i < cells.length; i++)
  2177. if (nodes[i].type == types.header_cell)
  2178. tr.setNodeMarkup(
  2179. rect.tableStart + cells[i],
  2180. types.cell,
  2181. nodes[i].attrs
  2182. );
  2183. if (tr.steps.length == 0)
  2184. for (let i = 0; i < cells.length; i++)
  2185. tr.setNodeMarkup(
  2186. rect.tableStart + cells[i],
  2187. types.header_cell,
  2188. nodes[i].attrs
  2189. );
  2190. dispatch(tr);
  2191. }
  2192. return true;
  2193. };
  2194. }
  2195. function isHeaderEnabledByType(type, rect, types) {
  2196. const cellPositions = rect.map.cellsInRect({
  2197. left: 0,
  2198. top: 0,
  2199. right: type == "row" ? rect.map.width : 1,
  2200. bottom: type == "column" ? rect.map.height : 1
  2201. });
  2202. for (let i = 0; i < cellPositions.length; i++) {
  2203. const cell = rect.table.nodeAt(cellPositions[i]);
  2204. if (cell && cell.type !== types.header_cell) {
  2205. return false;
  2206. }
  2207. }
  2208. return true;
  2209. }
  2210. function toggleHeader(type, options) {
  2211. options = options || { useDeprecatedLogic: false };
  2212. if (options.useDeprecatedLogic)
  2213. return deprecated_toggleHeader(type);
  2214. return function(state, dispatch) {
  2215. if (!isInTable(state))
  2216. return false;
  2217. if (dispatch) {
  2218. const types = tableNodeTypes(state.schema);
  2219. const rect = selectedRect(state), tr = state.tr;
  2220. const isHeaderRowEnabled = isHeaderEnabledByType("row", rect, types);
  2221. const isHeaderColumnEnabled = isHeaderEnabledByType(
  2222. "column",
  2223. rect,
  2224. types
  2225. );
  2226. const isHeaderEnabled = type === "column" ? isHeaderRowEnabled : type === "row" ? isHeaderColumnEnabled : false;
  2227. const selectionStartsAt = isHeaderEnabled ? 1 : 0;
  2228. const cellsRect = type == "column" ? {
  2229. left: 0,
  2230. top: selectionStartsAt,
  2231. right: 1,
  2232. bottom: rect.map.height
  2233. } : type == "row" ? {
  2234. left: selectionStartsAt,
  2235. top: 0,
  2236. right: rect.map.width,
  2237. bottom: 1
  2238. } : rect;
  2239. const newType = type == "column" ? isHeaderColumnEnabled ? types.cell : types.header_cell : type == "row" ? isHeaderRowEnabled ? types.cell : types.header_cell : types.cell;
  2240. rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => {
  2241. const cellPos = relativeCellPos + rect.tableStart;
  2242. const cell = tr.doc.nodeAt(cellPos);
  2243. if (cell) {
  2244. tr.setNodeMarkup(cellPos, newType, cell.attrs);
  2245. }
  2246. });
  2247. dispatch(tr);
  2248. }
  2249. return true;
  2250. };
  2251. }
  2252. var toggleHeaderRow = toggleHeader("row", {
  2253. useDeprecatedLogic: true
  2254. });
  2255. var toggleHeaderColumn = toggleHeader("column", {
  2256. useDeprecatedLogic: true
  2257. });
  2258. var toggleHeaderCell = toggleHeader("cell", {
  2259. useDeprecatedLogic: true
  2260. });
  2261. function findNextCell($cell, dir) {
  2262. if (dir < 0) {
  2263. const before = $cell.nodeBefore;
  2264. if (before)
  2265. return $cell.pos - before.nodeSize;
  2266. for (let row = $cell.index(-1) - 1, rowEnd = $cell.before(); row >= 0; row--) {
  2267. const rowNode = $cell.node(-1).child(row);
  2268. const lastChild = rowNode.lastChild;
  2269. if (lastChild) {
  2270. return rowEnd - 1 - lastChild.nodeSize;
  2271. }
  2272. rowEnd -= rowNode.nodeSize;
  2273. }
  2274. } else {
  2275. if ($cell.index() < $cell.parent.childCount - 1) {
  2276. return $cell.pos + $cell.nodeAfter.nodeSize;
  2277. }
  2278. const table = $cell.node(-1);
  2279. for (let row = $cell.indexAfter(-1), rowStart = $cell.after(); row < table.childCount; row++) {
  2280. const rowNode = table.child(row);
  2281. if (rowNode.childCount)
  2282. return rowStart + 1;
  2283. rowStart += rowNode.nodeSize;
  2284. }
  2285. }
  2286. return null;
  2287. }
  2288. function goToNextCell(direction) {
  2289. return function(state, dispatch) {
  2290. if (!isInTable(state))
  2291. return false;
  2292. const cell = findNextCell(selectionCell(state), direction);
  2293. if (cell == null)
  2294. return false;
  2295. if (dispatch) {
  2296. const $cell = state.doc.resolve(cell);
  2297. dispatch(
  2298. state.tr.setSelection(TextSelection3.between($cell, moveCellForward($cell))).scrollIntoView()
  2299. );
  2300. }
  2301. return true;
  2302. };
  2303. }
  2304. function deleteTable(state, dispatch) {
  2305. const $pos = state.selection.$anchor;
  2306. for (let d = $pos.depth; d > 0; d--) {
  2307. const node = $pos.node(d);
  2308. if (node.type.spec.tableRole == "table") {
  2309. if (dispatch)
  2310. dispatch(
  2311. state.tr.delete($pos.before(d), $pos.after(d)).scrollIntoView()
  2312. );
  2313. return true;
  2314. }
  2315. }
  2316. return false;
  2317. }
  2318. // src/index.ts
  2319. function tableEditing({
  2320. allowTableNodeSelection = false
  2321. } = {}) {
  2322. return new Plugin2({
  2323. key: tableEditingKey,
  2324. // This piece of state is used to remember when a mouse-drag
  2325. // cell-selection is happening, so that it can continue even as
  2326. // transactions (which might move its anchor cell) come in.
  2327. state: {
  2328. init() {
  2329. return null;
  2330. },
  2331. apply(tr, cur) {
  2332. const set = tr.getMeta(tableEditingKey);
  2333. if (set != null)
  2334. return set == -1 ? null : set;
  2335. if (cur == null || !tr.docChanged)
  2336. return cur;
  2337. const { deleted, pos } = tr.mapping.mapResult(cur);
  2338. return deleted ? null : pos;
  2339. }
  2340. },
  2341. props: {
  2342. decorations: drawCellSelection,
  2343. handleDOMEvents: {
  2344. mousedown: handleMouseDown
  2345. },
  2346. createSelectionBetween(view) {
  2347. return tableEditingKey.getState(view.state) != null ? view.state.selection : null;
  2348. },
  2349. handleTripleClick,
  2350. handleKeyDown,
  2351. handlePaste
  2352. },
  2353. appendTransaction(_, oldState, state) {
  2354. return normalizeSelection(
  2355. state,
  2356. fixTables(state, oldState),
  2357. allowTableNodeSelection
  2358. );
  2359. }
  2360. });
  2361. }
  2362. export {
  2363. CellBookmark,
  2364. CellSelection,
  2365. ResizeState,
  2366. TableMap,
  2367. TableView,
  2368. clipCells as __clipCells,
  2369. insertCells as __insertCells,
  2370. pastedCells as __pastedCells,
  2371. addColSpan,
  2372. addColumn,
  2373. addColumnAfter,
  2374. addColumnBefore,
  2375. addRow,
  2376. addRowAfter,
  2377. addRowBefore,
  2378. cellAround,
  2379. colCount,
  2380. columnIsHeader,
  2381. columnResizing,
  2382. columnResizingPluginKey,
  2383. deleteColumn,
  2384. deleteRow,
  2385. deleteTable,
  2386. findCell,
  2387. fixTables,
  2388. fixTablesKey,
  2389. goToNextCell,
  2390. handlePaste,
  2391. inSameTable,
  2392. isInTable,
  2393. mergeCells,
  2394. moveCellForward,
  2395. nextCell,
  2396. pointsAtCell,
  2397. removeColSpan,
  2398. removeColumn,
  2399. removeRow,
  2400. rowIsHeader,
  2401. selectedRect,
  2402. selectionCell,
  2403. setCellAttr,
  2404. splitCell,
  2405. splitCellWithType,
  2406. tableEditing,
  2407. tableEditingKey,
  2408. tableNodeTypes,
  2409. tableNodes,
  2410. toggleHeader,
  2411. toggleHeaderCell,
  2412. toggleHeaderColumn,
  2413. toggleHeaderRow,
  2414. updateColumnsOnResize
  2415. };