Timeline.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. import dayjs, { Dayjs } from "dayjs";
  2. import {
  3. LitElement,
  4. html,
  5. customElement,
  6. property,
  7. TemplateResult,
  8. internalProperty,
  9. CSSResult,
  10. } from "lit-element";
  11. import { styleMap } from "lit-html/directives/style-map";
  12. import { unsafeHTML } from "lit-html/directives/unsafe-html";
  13. import SimpleBar from "simplebar";
  14. import { SimpleBarStyle } from "./styles/SimpleBar.styles";
  15. import { Event, IEvent } from "./Event";
  16. import { Ressource, IRessource } from "./Ressource";
  17. export { HorizontalResizer } from "./components/horizontal-resizer";
  18. import syncronizeElementsScrolling from "./utils/syncroScroll";
  19. import Selectable from "./utils/selectable";
  20. import { TimelineStyle } from "./styles/Timeline.style";
  21. export interface TimelineOptions {
  22. ressources?: Array<IRessource>;
  23. items?: Array<IEvent>;
  24. }
  25. interface TimelineContent {
  26. ressources: Array<Ressource>;
  27. items: Array<Event>;
  28. index: number;
  29. }
  30. interface TimeInterval {
  31. start: number;
  32. end: number;
  33. slots: Array<Event>;
  34. }
  35. type dayjsUnit = "y" | "M" | "d" | "h" | "m" | "s";
  36. export type UnitLegend = {
  37. [k in dayjsUnit]: string;
  38. };
  39. interface legendItem {
  40. colspan: number;
  41. title: string;
  42. }
  43. // TODO add selectable Slot
  44. // TODO enable to rearrange between different component.
  45. /**
  46. * This is a component that can display event in a Timeline.
  47. *
  48. */
  49. @customElement("jc-timeline")
  50. class Timeline extends LitElement {
  51. static get styles(): CSSResult[] {
  52. return [TimelineStyle, SimpleBarStyle];
  53. }
  54. customStyle: string;
  55. @internalProperty() // important for the refresh
  56. private rows: Array<Ressource>;
  57. @internalProperty() // important for the refresh
  58. private items: Array<Event>;
  59. private selectedList: Array<Selectable>;
  60. @property({ type: Number })
  61. public ressourceWidth: number;
  62. @property({ type: Object })
  63. private _start: Dayjs;
  64. @property({ type: String })
  65. public get start(): string {
  66. return this._start.toISOString();
  67. }
  68. public set start(value: string) {
  69. const d = dayjs(value);
  70. if (d.isValid()) {
  71. this._start = d < this._end ? d : this._end;
  72. this.updateLegend();
  73. } else {
  74. console.log("Invalid Date :", value);
  75. }
  76. }
  77. private _end: Dayjs;
  78. @property({ type: String })
  79. public get end(): string {
  80. return this._end.toISOString();
  81. }
  82. public set end(value: string) {
  83. const d = dayjs(value);
  84. if (d.isValid()) {
  85. this._end = this._start < d ? d : this._start;
  86. this.updateLegend();
  87. }
  88. }
  89. private _slotDuration = 30; // in minute
  90. @property({ type: Number })
  91. public get slotDuration(): number {
  92. return this._slotDuration;
  93. }
  94. public set slotDuration(value: number) {
  95. this._slotDuration = value;
  96. this.updateLegend();
  97. }
  98. private _legendSpan = 2; // in slot count
  99. @property({ type: Number })
  100. public get legendSpan(): number {
  101. return this._legendSpan;
  102. }
  103. public set legendSpan(value: number) {
  104. this._legendSpan = value;
  105. this.updateLegend();
  106. }
  107. @property({ type: Number })
  108. private rowHeight = 32; // in px
  109. @property({ type: Number })
  110. public slotWidth = 20; // in px
  111. @property({ type: String })
  112. private rowsTitle: string;
  113. private legendUnitFormat: UnitLegend = {
  114. y: "YYYY",
  115. M: "MMMM",
  116. d: "D",
  117. h: "H[h]",
  118. m: "m'",
  119. s: "s[s]",
  120. };
  121. @property({ type: Array })
  122. private legend: Array<Array<legendItem>>;
  123. constructor(options: TimelineOptions = {}) {
  124. super();
  125. this.rows = [];
  126. this.items = [];
  127. this._start = dayjs().startOf("day");
  128. this._end = this._start.endOf("day");
  129. this.rowsTitle = "Ressources";
  130. this.ressourceWidth = 200;
  131. this.selectedList = [];
  132. this.legend = [];
  133. this.defaultBackground = "";
  134. this.customStyle = "";
  135. if (options.ressources) {
  136. this.addRessources(options.ressources);
  137. }
  138. if (options.items) {
  139. this.addEvents(options.items);
  140. }
  141. this.updateLegend();
  142. this.render();
  143. }
  144. @property({ type: String })
  145. set defaultBackground(value: string) {
  146. this.style.setProperty("--default-background", value);
  147. }
  148. get defaultBackground(): string {
  149. return this.style.getPropertyValue("--default-background");
  150. }
  151. setLegendUnitFormatAll(legend: Partial<UnitLegend>): void {
  152. this.legendUnitFormat = { ...this.legendUnitFormat, ...legend };
  153. this.updateLegend();
  154. }
  155. setLegendUnitFormat(unit: dayjsUnit, format: string): void {
  156. this.legendUnitFormat[unit] = format;
  157. this.updateLegend();
  158. }
  159. addRessources(list: Array<IRessource>): Array<Ressource> {
  160. return list.map((r) => this.addRessource(r));
  161. 0;
  162. }
  163. // Ressource management
  164. /**
  165. * Add the ressource the the timeline or return the existing ressource with the same id
  166. * @param ressource
  167. * @returns The Ressource object registered to in the timeline
  168. */
  169. addRessource(ressource: IRessource, pos = Infinity): Ressource {
  170. const existingRessource = this.getRessourceFromId(ressource.id);
  171. if (existingRessource) {
  172. return existingRessource;
  173. }
  174. const r = Ressource.toRessource(ressource);
  175. if (r.parent !== undefined) {
  176. r.parent = this.getRessourceFromId(r.parent.id) ?? this.addRessource(r.parent);
  177. const idx = this.rows.indexOf(r.parent as Ressource);
  178. const alreadyChild = r.parent?.children.some((c) => c.id == r.id);
  179. if (idx > -1) {
  180. if (pos <= idx) {
  181. this.rows.splice(idx + 1, 0, r);
  182. if (!alreadyChild) r.parent.children = [r, ...r.parent.children];
  183. } else if (pos < idx + r.parent.children.length) {
  184. this.rows.splice(pos, 0, r);
  185. if (!alreadyChild) r.parent.children.splice(pos - idx, 0, r);
  186. } else {
  187. this.rows.splice(idx + r.parent.children.length + 1, 0, r);
  188. if (!alreadyChild) r.parent.children = [...r.parent.children, r];
  189. }
  190. } else {
  191. throw new Error("Not able to create ressource parent.\n" + r.id);
  192. }
  193. } else {
  194. if (pos < 0) {
  195. this.rows = [r, ...this.rows];
  196. } else {
  197. let idx = pos;
  198. while (idx < this.rows.length) {
  199. if (this.rows[idx].parent == undefined) {
  200. this.rows.splice(idx, 0, r);
  201. break;
  202. }
  203. idx++;
  204. }
  205. if (idx >= this.rows.length) {
  206. this.rows = [...this.rows, r];
  207. }
  208. }
  209. }
  210. this.addRessources(r.children);
  211. this._updateEventPosition(r);
  212. return r;
  213. }
  214. removeRessourceById(id: string): TimelineContent {
  215. return this._removeRessourceById(id);
  216. }
  217. _removeRessourceById(id: string, depth = 0): TimelineContent {
  218. const output: TimelineContent = { ressources: [], items: [], index: 0 };
  219. for (let i = 0; i < this.rows.length; i) {
  220. const ressource = this.rows[i];
  221. if (ressource.id === id) {
  222. output.index = i;
  223. output.ressources.push(ressource);
  224. // remove the top level children from it's parent.
  225. if (ressource.parent && depth === 0) {
  226. ressource.parent.children = ressource.parent.children.filter((o) => o.id !== id);
  227. }
  228. this.rows.splice(i, 1);
  229. } else if (ressource.parentId === id) {
  230. const partialOutput = this._removeRessourceById(ressource.id, depth + 1);
  231. output.ressources.push(...partialOutput.ressources);
  232. output.items.push(...partialOutput.items);
  233. } else {
  234. i++;
  235. }
  236. }
  237. // Recover deleted items
  238. output.items.push(...this.items.filter((i) => i.ressourceId === id));
  239. // Update items list
  240. this.items = this.items.filter((i) => i.ressourceId !== id);
  241. return output;
  242. }
  243. getRessources(): Array<Ressource> {
  244. return this.rows;
  245. }
  246. getRessourceFromId(id: string): Ressource | null {
  247. const tmp = this.rows.filter((r) => r.id === id);
  248. return tmp.length > 0 ? tmp[0] : null;
  249. }
  250. updateRessource<K extends keyof Ressource>(
  251. id: string,
  252. key: K,
  253. value: Ressource[K]
  254. ): Ressource | null {
  255. const ressource = this.getRessourceFromId(id);
  256. if (ressource) {
  257. if (key == "parent") {
  258. const content = this.removeRessourceById(id);
  259. ressource[key] = value;
  260. this.addRessource(ressource);
  261. this.addRessources(content.ressources);
  262. this.addEvents(content.items);
  263. } else {
  264. ressource[key] = value;
  265. this.rows = this.rows.map((r) => (r.id == ressource.id ? ressource : r));
  266. }
  267. this._updateEventPosition(ressource);
  268. return ressource;
  269. }
  270. return null;
  271. }
  272. setRowsTitle(title: string): void {
  273. this.rowsTitle = title;
  274. }
  275. getEventById(id: string): Event | undefined {
  276. return this.items.find((o) => o.id == id);
  277. }
  278. addEvents(list: Array<IEvent>): Array<Event | undefined> {
  279. return list.map((e) => this.addEvent(e));
  280. }
  281. // TimeSlot management
  282. /**
  283. * Add the event the the timeline or return the existing event with the same id
  284. * return undefined if the event ressource is not defined in the timeline
  285. * @param event
  286. * @returns
  287. */
  288. addEvent(event: IEvent): Event | undefined {
  289. const existingEvent = this.getEventById(event.id);
  290. if (existingEvent) {
  291. return existingEvent;
  292. }
  293. const ressource = this.rows.find((r) => r.id === event.ressourceId);
  294. if (ressource === undefined) {
  295. return undefined;
  296. }
  297. const timeslot = Event.toTimeSlot(event);
  298. this.items = [...this.items, timeslot];
  299. // Update timeslot status
  300. timeslot.isDisplayed =
  301. timeslot.end > this._start.toDate() || timeslot.start < this._end.toDate();
  302. this._updateEventPosition(ressource);
  303. return timeslot;
  304. }
  305. removeEventById(id: string): Array<Event> {
  306. const output = this.items.filter((o) => o.id === id);
  307. this.items = this.items.filter((o) => o.id !== id);
  308. return output;
  309. }
  310. updateEventById(id: string): Event | null {
  311. const output = this.removeEventById(id);
  312. if (output.length > 0) {
  313. this.addEvent(output[0]);
  314. return output[0];
  315. } else {
  316. return null;
  317. }
  318. }
  319. private _updateEventPosition(ressource: Ressource): void {
  320. const timeslots = this.items.filter((i) => i.ressourceId === ressource.id);
  321. if (timeslots.length === 0) {
  322. ressource.height = this.rowHeight + (ressource.collapseChildren ? 5 : 0);
  323. return;
  324. }
  325. const start = this._start.toDate().getTime();
  326. const end = this._end.toDate().getTime();
  327. // List potential interval
  328. const points = [start, end];
  329. const populateInterval = (d: Date) => {
  330. const t = d.getTime();
  331. if (start < t && t < end && !points.includes(t)) {
  332. points.push(t);
  333. }
  334. };
  335. timeslots.forEach((element) => {
  336. populateInterval(element.start);
  337. populateInterval(element.end);
  338. });
  339. points.sort();
  340. // Count maximum number of interval intersection
  341. const intervals: Array<TimeInterval> = [];
  342. for (let i = 0; i < points.length - 1; i++) {
  343. const startTime = points[i];
  344. const endTime = points[i + 1];
  345. intervals.push({
  346. start: points[i],
  347. end: points[i + 1],
  348. slots: timeslots.filter(
  349. (slot) => slot.start.getTime() <= startTime && endTime <= slot.end.getTime()
  350. ),
  351. });
  352. }
  353. // Update rows height
  354. const lineCount = intervals.reduce((acc, interval) => Math.max(acc, interval.slots.length), 0);
  355. ressource.height =
  356. this.rowHeight * Math.max(lineCount, 1) + (ressource.collapseChildren ? 5 : 0); // to avoid collapse rows
  357. // Solve the offset positioning of all items
  358. const sortTimeslots = (a: Event, b: Event): number => {
  359. const t = a.start.getTime() - b.start.getTime();
  360. if (t === 0) {
  361. const tend = b.end.getTime() - a.end.getTime();
  362. return tend === 0 ? ("" + a.id).localeCompare(b.id) : tend;
  363. }
  364. return t;
  365. };
  366. // Remove all items offset
  367. timeslots.forEach((slot) => (slot.offset = -1));
  368. timeslots.sort(sortTimeslots);
  369. timeslots[0].offset = 0;
  370. const potentialOffset: Array<number> = [];
  371. for (let i = 0; i < lineCount; i++) {
  372. potentialOffset.push(i);
  373. }
  374. intervals.forEach((intervals) => {
  375. intervals.slots.sort(sortTimeslots);
  376. const usedOffset = intervals.slots.map((o) => o.offset).filter((i) => i > -1);
  377. const availableOffset = potentialOffset.filter((i) => !usedOffset.includes(i));
  378. intervals.slots.forEach((slot) => {
  379. if (slot.offset === -1) {
  380. slot.offset = availableOffset.shift() || 0;
  381. }
  382. });
  383. });
  384. }
  385. getEvents(): Array<Event> {
  386. return this.items;
  387. }
  388. updateLegend(): void {
  389. const legend: Array<Array<legendItem>> = [];
  390. const legendUnitList: Array<dayjsUnit> = ["y", "M", "d", "h", "m", "s"];
  391. const legendMinUnitSpan = this.slotDuration * this.legendSpan;
  392. const deltaT = this._end.diff(this._start, "m");
  393. const nCol = Math.floor(deltaT / legendMinUnitSpan) + 1;
  394. for (const legendUnit of legendUnitList) {
  395. const currentDate = dayjs(this._start);
  396. const format = this.legendUnitFormat[legendUnit];
  397. let nextColumn = currentDate.add(legendMinUnitSpan, "m");
  398. // Check is the starting and end date can accomodate fews cell of the given unit for this unit of time
  399. const isLegendPossible =
  400. // Enough time to fit 1 cell AND
  401. this._end.diff(this._start, legendUnit) > 0 &&
  402. // Starting & Ending date have different legend
  403. (nextColumn.format(format) !== currentDate.format(format) ||
  404. // OR 2 consecutive legends can accomodate at least 1 grid cell
  405. currentDate.add(1, legendUnit).diff(currentDate, "m") >= legendMinUnitSpan);
  406. if (isLegendPossible) {
  407. let currentHeader = currentDate.format(format);
  408. const row: Array<legendItem> = [];
  409. let i = 0;
  410. for (let j = 0; j < nCol; j++) {
  411. i += this.legendSpan;
  412. nextColumn = nextColumn.add(legendMinUnitSpan, "m");
  413. const nextHeader = nextColumn.format(format);
  414. if (currentHeader !== nextHeader) {
  415. row.push({
  416. colspan: i,
  417. title: currentHeader,
  418. });
  419. i = 0;
  420. currentHeader = nextHeader;
  421. }
  422. }
  423. // IF the last title cover some column add it to the legend
  424. if (i > 0) {
  425. row.push({
  426. colspan: i,
  427. title: currentHeader,
  428. });
  429. }
  430. legend.push(row);
  431. }
  432. }
  433. this.legend = legend;
  434. }
  435. private _handleResizeX(e: CustomEvent<number>): void {
  436. e.stopPropagation();
  437. this.ressourceWidth += e.detail;
  438. if (this.ressourceWidth < 0) {
  439. this.ressourceWidth = 0;
  440. }
  441. }
  442. private _grabHeader(e: MouseEvent): void {
  443. const root = this.shadowRoot;
  444. if (root !== null) {
  445. const headerContainer = root.querySelector(
  446. ".jc-timeline-grid-title-container"
  447. ) as HTMLBaseElement;
  448. let lastPosX = e.clientX;
  449. const scroll = function (e: MouseEvent) {
  450. const scrollLeft = lastPosX - e.clientX;
  451. headerContainer.scrollBy({ left: scrollLeft });
  452. lastPosX = e.clientX;
  453. };
  454. const mouseUpListener = function (_e: MouseEvent) {
  455. window.removeEventListener("mousemove", scroll);
  456. window.removeEventListener("mouseup", mouseUpListener);
  457. };
  458. window.addEventListener("mousemove", scroll);
  459. window.addEventListener("mouseup", mouseUpListener);
  460. }
  461. }
  462. private _getEventResizerHandler(slot: Event, direction: "end" | "start") {
  463. return (evt: MouseEvent): void => {
  464. evt.stopPropagation();
  465. evt.preventDefault();
  466. const startPos = evt.clientX;
  467. const localSlot = slot;
  468. const localDir = direction;
  469. const initialDate = slot[direction];
  470. const resizeListener = (e: MouseEvent) => {
  471. const newDate = dayjs(initialDate)
  472. .add(Math.round((e.clientX - startPos) / this.slotWidth) * this.slotDuration, "m")
  473. .toDate();
  474. if (direction === "start" ? newDate < localSlot.end : localSlot.start < newDate) {
  475. if (localSlot[localDir] !== newDate) {
  476. localSlot[localDir] = newDate;
  477. this.updateEventById(slot.id);
  478. }
  479. }
  480. };
  481. const mouseUpListener = (_e: MouseEvent): void => {
  482. window.removeEventListener("mousemove", resizeListener);
  483. window.removeEventListener("mouseup", mouseUpListener);
  484. localSlot.moving = false;
  485. this.updateEventById(localSlot.id);
  486. if (initialDate !== localSlot[localDir]) {
  487. const cEvt = new CustomEvent("event-change", {
  488. detail: { items: [localSlot] },
  489. });
  490. this.dispatchEvent(cEvt);
  491. }
  492. };
  493. localSlot.moving = true;
  494. window.addEventListener("mousemove", resizeListener);
  495. window.addEventListener("mouseup", mouseUpListener);
  496. };
  497. }
  498. private _getEventGrabHandler(
  499. slot: Event,
  500. editable: boolean,
  501. ressourceEditable: boolean,
  502. callback: (e: MouseEvent, wasModified: boolean) => void
  503. ) {
  504. return (evt: MouseEvent): boolean => {
  505. evt.stopPropagation();
  506. evt.preventDefault();
  507. const startPos: number = evt.clientX;
  508. let hasChanged = false;
  509. const localSlot: Event = slot;
  510. // Register all current selected timeslot
  511. let localSlots: Array<Event> = this.selectedList
  512. .filter((s) => s instanceof Event)
  513. .map((s) => s as Event);
  514. if (!localSlots.includes(localSlot)) {
  515. localSlots = [localSlot];
  516. }
  517. const startDates = localSlots.map((slot) => slot.start);
  518. const endDates = localSlots.map((slot) => slot.end);
  519. const updatePosition = editable
  520. ? (e: MouseEvent) => {
  521. const changeTime =
  522. Math.round((e.clientX - startPos) / this.slotWidth) * this.slotDuration;
  523. return localSlots
  524. .map((slot, index) => {
  525. const prevStart = slot.start;
  526. slot.start = dayjs(startDates[index]).add(changeTime, "m").toDate();
  527. slot.end = dayjs(endDates[index]).add(changeTime, "m").toDate();
  528. return prevStart.getTime() !== slot.start.getTime();
  529. })
  530. .reduce((prev, curr) => prev || curr);
  531. }
  532. : (_e: MouseEvent) => {
  533. return false;
  534. };
  535. const updateRessource = ressourceEditable
  536. ? (e: MouseEvent) => {
  537. const rowId = this.shadowRoot
  538. ?.elementsFromPoint(e.clientX, e.clientY)
  539. .find((e) => e.tagName == "TD")
  540. ?.parentElement?.getAttribute("row-id");
  541. if (rowId) {
  542. const ressourceId = this.rows[Number(rowId)].id;
  543. if (ressourceId !== localSlot.ressourceId) {
  544. const oldRessource = this.getRessourceFromId(localSlot.ressourceId) as Ressource;
  545. localSlot.ressourceId = ressourceId;
  546. this._updateEventPosition(oldRessource);
  547. return true;
  548. }
  549. }
  550. return false;
  551. }
  552. : (_e: MouseEvent) => {
  553. return false;
  554. };
  555. const moveListener = (e: MouseEvent) => {
  556. // Evaluate the updatePosition to avoid || collapse
  557. const a = updatePosition(e);
  558. if (updateRessource(e) || a) {
  559. hasChanged = true;
  560. this.updateEventById(localSlot.id);
  561. }
  562. };
  563. const mouseUpListener = (e: MouseEvent) => {
  564. window.removeEventListener("mousemove", moveListener);
  565. window.removeEventListener("mouseup", mouseUpListener);
  566. localSlot.moving = false;
  567. this.updateEventById(slot.id);
  568. if (hasChanged) {
  569. const cEvt = new CustomEvent("event-change", {
  570. detail: { items: localSlots },
  571. });
  572. this.dispatchEvent(cEvt);
  573. }
  574. callback(e, hasChanged);
  575. };
  576. localSlot.moving = true;
  577. window.addEventListener("mousemove", moveListener);
  578. window.addEventListener("mouseup", mouseUpListener);
  579. return true;
  580. };
  581. }
  582. clearSelectedItems(): void {
  583. this.items.forEach((selectable) => {
  584. selectable.selected = false;
  585. this.updateEventById(selectable.id);
  586. });
  587. this.rows.forEach((selectable) => (selectable.selected = false));
  588. this.selectedList = [];
  589. }
  590. private _clearSelectionHandler = (_e: MouseEvent) => {
  591. const exclusionZone = document.querySelectorAll("[jc-timeline-keep-select]");
  592. if (Array.from(exclusionZone).some((e) => e.contains(_e.target as Node))) return;
  593. this.clearSelectedItems();
  594. const myEvent = new CustomEvent("item-selected", {
  595. detail: { items: [] },
  596. bubbles: true,
  597. composed: true,
  598. });
  599. this.dispatchEvent(myEvent);
  600. window.removeEventListener("click", this._clearSelectionHandler);
  601. };
  602. private _getEventClickHandler(clickedItem: Selectable) {
  603. const item = clickedItem;
  604. return (e: MouseEvent, wasModified = false) => {
  605. e.stopPropagation();
  606. const idx = this.selectedList.indexOf(item);
  607. if (idx > -1) {
  608. if (!wasModified) {
  609. if (e.ctrlKey) {
  610. this.selectedList.splice(idx, 1);
  611. item.selected = false;
  612. this.updateEventById(item.id);
  613. } else {
  614. this.clearSelectedItems();
  615. }
  616. }
  617. } else {
  618. if (this.selectedList.length > 0 && !e.ctrlKey) {
  619. this.clearSelectedItems();
  620. }
  621. item.selected = true;
  622. this.selectedList.push(item);
  623. this.updateEventById(item.id);
  624. }
  625. const myEvent = new CustomEvent("item-selected", {
  626. detail: { items: this.selectedList },
  627. bubbles: true,
  628. composed: true,
  629. });
  630. if (this.selectedList.length > 0) {
  631. window.addEventListener("click", this._clearSelectionHandler);
  632. }
  633. this.dispatchEvent(myEvent);
  634. };
  635. }
  636. firstUpdated(): void {
  637. const root = this.shadowRoot;
  638. if (root !== null) {
  639. const gridContainer = root.querySelector(".jc-timeline-grid-container") as HTMLBaseElement;
  640. const simplebar = new SimpleBar(gridContainer).getScrollElement() as HTMLBaseElement;
  641. syncronizeElementsScrolling(
  642. [simplebar, root.querySelector(".jc-timeline-grid-title-container") as HTMLBaseElement],
  643. "h"
  644. );
  645. syncronizeElementsScrolling(
  646. [simplebar, root.querySelector(".jc-timeline-rows") as HTMLBaseElement],
  647. "v"
  648. );
  649. }
  650. if (this.defaultBackground === "") {
  651. this.style.setProperty("--default-background", "SteelBlue");
  652. }
  653. }
  654. // RENDERING
  655. renderTimeslot(evt: Event): TemplateResult {
  656. if (!evt.isDisplayed) {
  657. return html``;
  658. }
  659. let rowTop = 0;
  660. let ressource: Ressource;
  661. let i: number;
  662. for (i = 0; i < this.rows.length && this.rows[i].id !== evt.ressourceId; i++) {
  663. ressource = this.rows[i];
  664. if (ressource.show) {
  665. rowTop += ressource.height ? ressource.height : this.rowHeight;
  666. }
  667. }
  668. ressource = this.rows[i];
  669. const minute2pixel = this.slotWidth / this.slotDuration;
  670. const left = dayjs(evt.start).diff(this._start, "m") * minute2pixel;
  671. const right = -dayjs(evt.end).diff(this._end, "m") * minute2pixel;
  672. const style = {
  673. height: this.rowHeight - 4 + "px",
  674. top: rowTop + evt.offset * this.rowHeight + "px",
  675. left: left + "px",
  676. right: right + "px",
  677. backgroundColor: "",
  678. };
  679. const bgColor = evt.bgColor ? evt.bgColor : ressource.eventBgColor;
  680. if (bgColor) {
  681. style.backgroundColor = bgColor;
  682. }
  683. // Show collapsed ressource
  684. if (!ressource.show) {
  685. style.height = "";
  686. style.top = rowTop - 6 + "px";
  687. return html`<div class="jc-timeslot empty" style="${styleMap(style)}"></div>`;
  688. }
  689. let content: TemplateResult = html`<div class="jc-timeslot-title">${evt.title}</div>
  690. ${evt.content ? unsafeHTML(evt.content) : ""}`;
  691. const resizer = evt.editable === null ? ressource.eventEditable : evt.editable;
  692. const editableRessource =
  693. evt.ressourceEditable === null ? ressource.eventRessourceEditable : evt.ressourceEditable;
  694. if (resizer) {
  695. content = html`<div
  696. class="jc-timeslot-resizer-start"
  697. @mousedown="${this._getEventResizerHandler(evt, "start")}"
  698. ></div>
  699. ${content}
  700. <div
  701. class="jc-timeslot-resizer-end"
  702. @mousedown="${this._getEventResizerHandler(evt, "end")}"
  703. ></div>`;
  704. }
  705. return html`<div
  706. class="jc-timeslot ${evt.moving ? "moving" : ""} ${evt.selected ? "selected" : ""}"
  707. start="${evt.start.getHours()}"
  708. end="${evt.end.getHours()}"
  709. style="${styleMap(style)}"
  710. eventid="${evt.id}"
  711. @mousedown="${this._getEventGrabHandler(
  712. evt,
  713. resizer,
  714. editableRessource,
  715. this._getEventClickHandler(evt)
  716. )}"
  717. @click="${(e: MouseEvent) => e.stopPropagation()}"
  718. >
  719. ${content}
  720. </div>`;
  721. }
  722. private _getCollapseRessourceHandler(item: Ressource): (e: MouseEvent) => void {
  723. return (_e: MouseEvent) => {
  724. item.collapseChildren = !item.collapseChildren;
  725. this._updateEventPosition(item);
  726. // Force rows refresh TODO improve this rerendering
  727. this.rows = [...this.rows];
  728. };
  729. }
  730. private _onRessourceDragStart(item: Ressource): (event: DragEvent) => void {
  731. return (event: DragEvent): void => {
  732. event.dataTransfer?.setData("text", item.id);
  733. };
  734. }
  735. private _onRessourceDragEnter(event: DragEvent): void {
  736. if (event.target instanceof HTMLElement) {
  737. const tgt = event.target;
  738. tgt.classList.add("target");
  739. }
  740. }
  741. private _onRessourceDragLeave(event: DragEvent): void {
  742. if (event.target instanceof HTMLElement) {
  743. event.target.classList.remove("target");
  744. }
  745. }
  746. private _onRessourceDrop(event: DragEvent): void {
  747. event.preventDefault();
  748. if (event.target instanceof HTMLElement) {
  749. event.target.classList.remove("target");
  750. const srcId = event.dataTransfer?.getData("text");
  751. const destinationId = event.target.parentElement?.getAttribute("ressourceId");
  752. if (srcId && destinationId && destinationId !== srcId) {
  753. // Check if destination is not child of parent
  754. const src = this.getRessourceFromId(srcId) as Ressource;
  755. const destination = this.getRessourceFromId(destinationId) as Ressource;
  756. if (destination.descendantOf(src)) {
  757. return;
  758. }
  759. // Remove src item from the current Ressource
  760. const movedContent = this.removeRessourceById(src.id);
  761. // Update the moved ressource position
  762. if (event.target.classList.contains("jc-ressource")) {
  763. movedContent.ressources[0].parent = destination;
  764. } else {
  765. movedContent.ressources[0].parent = destination.parent;
  766. let idx = this.rows.findIndex((v) => v.id === destinationId);
  767. if (event.target.classList.contains("jc-ressource-below")) {
  768. idx += 1;
  769. while (idx < this.rows.length && this.rows[idx].descendantOf(destination)) {
  770. idx += 1;
  771. }
  772. }
  773. const arr = this.rows;
  774. this.rows = [...arr.splice(0, idx), src, ...arr];
  775. }
  776. // Add moved children and associated slots
  777. this.addRessources(movedContent.ressources);
  778. this.addEvents(movedContent.items);
  779. this.dispatchEvent(
  780. new CustomEvent("reorder-ressource", {
  781. detail: { ressources: this.rows },
  782. })
  783. );
  784. }
  785. }
  786. }
  787. renderRessource(item: Ressource): TemplateResult {
  788. const depth = item.depth;
  789. const style = `--depth:${depth};` + (item.height ? `height:${item.height}px;` : "");
  790. const hasChild = item.children.length > 0;
  791. const collapseHandler = this._getCollapseRessourceHandler(item);
  792. return html`<tr>
  793. <td
  794. class="${item.selected ? "jc-ressource-selected" : ""}"
  795. style="${style}"
  796. ressourceId="${item.id}"
  797. @click="${this._getEventClickHandler(item)}"
  798. >
  799. <div class="jc-ressource-above"></div>
  800. <div class="jc-ressource" draggable="true" @dragstart="${this._onRessourceDragStart(item)}">
  801. ${Array(depth)
  802. .fill(0)
  803. .map((_i) => html`<i class="jc-spacer"></i>`)}${hasChild
  804. ? html`<i
  805. class="jc-spacer ${item.collapseChildren ? "extend" : "collapse"}"
  806. @click="${collapseHandler}"
  807. ></i>`
  808. : html`<i class="jc-spacer"></i>`}
  809. <span>${item.title}</span>
  810. </div>
  811. <div class="jc-ressource-below"></div>
  812. </td>
  813. </tr>`;
  814. }
  815. private renderGridRow(columns: Array<Dayjs>, id = "", height = 30): TemplateResult {
  816. return html`<tr ressourceid="${id}">
  817. ${columns.map(
  818. (d, i) =>
  819. html`<td
  820. style="height:${height}px;"
  821. class="jc-slot ${i % this.legendSpan === 0 ? "jc-major-slot" : ""}"
  822. start="${d.toISOString()}"
  823. >
  824. &nbsp;
  825. </td>`
  826. )}
  827. </tr>`;
  828. }
  829. render(): TemplateResult {
  830. const nCol = Math.floor(this._end.diff(this._start, "m") / this.slotDuration) + 1;
  831. const columns: Array<Dayjs> = [];
  832. for (let i = 0; i < nCol; i++) {
  833. columns.push(this._start.add(this.slotDuration * i, "m"));
  834. }
  835. const displayedRows = this.rows
  836. .map((r, i) => {
  837. return { i: i, r: r };
  838. })
  839. .filter((o) => o.r.show);
  840. return html`
  841. <style>
  842. ${this.customStyle}
  843. </style>
  844. <div
  845. class="jc-timeline-header"
  846. style=${styleMap({
  847. "--width": this.ressourceWidth + "px",
  848. })}
  849. >
  850. <div class="jc-timeline-rows-title">${this.rowsTitle}</div>
  851. <horizontal-resizer @resize-x="${this._handleResizeX}"></horizontal-resizer>
  852. <div class="jc-timeline-grid-title-container">
  853. <table @mousedown="${this._grabHeader}" style="width:${nCol * this.slotWidth}px;">
  854. <colgroup>
  855. ${columns.map((_) => html`<col style="min-width:${this.slotWidth}px" />`)}
  856. </colgroup>
  857. <tbody>
  858. ${this.legend.map(
  859. (arr) =>
  860. html`<tr class="jc-timeline-grid-title">
  861. ${arr.map((o) => html`<th colspan="${o.colspan}"><div>${o.title}</div></th>`)}
  862. </tr>`
  863. )}
  864. </tbody>
  865. </table>
  866. </div>
  867. </div>
  868. <div
  869. class="jc-timeline-content"
  870. style="${styleMap({ "--width": this.ressourceWidth + "px" })}"
  871. >
  872. <table
  873. class="jc-timeline-rows"
  874. @dragover="${(e: DragEvent) => e.preventDefault()}"
  875. @dragenter="${this._onRessourceDragEnter}"
  876. @dragleave="${this._onRessourceDragLeave}"
  877. @drop="${this._onRessourceDrop}"
  878. >
  879. ${this.rows.length > 0
  880. ? displayedRows.map((o) => this.renderRessource(o.r))
  881. : html`<tr class="empty">
  882. <td>No ressource</td>
  883. </tr>`}
  884. </table>
  885. <horizontal-resizer @resize-x="${this._handleResizeX}"></horizontal-resizer>
  886. <div class="jc-timeline-grid-container">
  887. <table style="width:${nCol * this.slotWidth}px;">
  888. <colgroup>
  889. ${columns.map((_) => html`<col style="min-width:${this.slotWidth}px" />`)}
  890. </colgroup>
  891. <tbody>
  892. ${this.rows.length > 0
  893. ? displayedRows.map((o) => this.renderGridRow(columns, o.r.id, o.r.height))
  894. : this.renderGridRow(columns)}
  895. </tbody>
  896. </table>
  897. <div class="jc-timeslots" style="width:${nCol * this.slotWidth}px;">
  898. ${this.items.map((slot) => this.renderTimeslot(slot))}
  899. </div>
  900. </div>
  901. </div>
  902. `;
  903. }
  904. }
  905. export default Timeline;