MonthView.axaml.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. using Avalonia;
  2. using Avalonia.Animation;
  3. using Avalonia.Controls;
  4. using Avalonia.Controls.Primitives;
  5. using Avalonia.Controls.Shapes;
  6. using Avalonia.Controls.Templates;
  7. using Avalonia.Data;
  8. using Avalonia.Input;
  9. using Avalonia.Interactivity;
  10. using Avalonia.Layout;
  11. using Avalonia.Markup.Xaml;
  12. using Avalonia.Media;
  13. using Avalonia.Media.Transformation;
  14. using Avalonia.Metadata;
  15. using Avalonia.Styling;
  16. using Avalonia.Threading;
  17. using Avalonia.VisualTree;
  18. using CommunityToolkit.Mvvm.ComponentModel;
  19. using InABox.Core;
  20. using ReactiveUI;
  21. using System.Collections;
  22. using System.Collections.Specialized;
  23. using System.Diagnostics.CodeAnalysis;
  24. using System.Reactive.Linq;
  25. namespace InABox.Avalonia.Components;
  26. public class MonthViewCellEventArgs(DateTime date) : EventArgs
  27. {
  28. public DateTime Date { get; set; } = date;
  29. }
  30. public class MonthViewBlockEventArgs(object? value) : EventArgs
  31. {
  32. public object? Value { get; set; } = value;
  33. }
  34. public class MonthViewDateRangeEventArgs(DateTime startDate, DateTime endDate) : EventArgs
  35. {
  36. public DateTime StartDate { get; set; } = startDate;
  37. public DateTime EndDate { get; set; } = endDate;
  38. }
  39. public partial class MonthView : UserControl
  40. {
  41. public static readonly StyledProperty<double> MinimumBlockHeightProperty =
  42. AvaloniaProperty.Register<CalendarView, double>(nameof(MinimumBlockHeight), defaultValue: 15);
  43. public static readonly StyledProperty<IBinding?> StartDateMappingProperty =
  44. AvaloniaProperty.Register<MonthView, IBinding?>(nameof(StartDateMapping));
  45. public static readonly StyledProperty<IBinding?> EndDateMappingProperty =
  46. AvaloniaProperty.Register<MonthView, IBinding?>(nameof(EndDateMapping));
  47. public static readonly StyledProperty<IBinding?> ColourMappingProperty =
  48. AvaloniaProperty.Register<MonthView, IBinding?>(nameof(ColourMapping));
  49. public static readonly StyledProperty<IEnumerable?> ItemsSourceProperty =
  50. AvaloniaProperty.Register<MonthView, IEnumerable?>(nameof(ItemsSource));
  51. public static readonly StyledProperty<IDataTemplate?> ItemTemplateProperty =
  52. AvaloniaProperty.Register<MonthView, IDataTemplate?>(nameof(ItemTemplate));
  53. public static readonly StyledProperty<DayOfWeek> FirstDayOfWeekProperty =
  54. AvaloniaProperty.Register<MonthView, DayOfWeek>(nameof(FirstDayOfWeek), DayOfWeek.Sunday);
  55. public static readonly StyledProperty<DateTime> CurrentDateProperty =
  56. AvaloniaProperty.Register<MonthView, DateTime>(nameof(CurrentDate), DateTime.Now);
  57. public double MinimumBlockHeight
  58. {
  59. get => GetValue(MinimumBlockHeightProperty);
  60. set => SetValue(MinimumBlockHeightProperty, value);
  61. }
  62. [AssignBinding]
  63. [InheritDataTypeFromItems(nameof(ItemsSource))]
  64. public IBinding? StartDateMapping
  65. {
  66. get => GetValue(StartDateMappingProperty);
  67. set => SetValue(StartDateMappingProperty, value);
  68. }
  69. [AssignBinding]
  70. [InheritDataTypeFromItems(nameof(ItemsSource))]
  71. public IBinding? EndDateMapping
  72. {
  73. get => GetValue(EndDateMappingProperty);
  74. set => SetValue(EndDateMappingProperty, value);
  75. }
  76. [AssignBinding]
  77. [InheritDataTypeFromItems(nameof(ItemsSource))]
  78. public IBinding? ColourMapping
  79. {
  80. get => GetValue(ColourMappingProperty);
  81. set => SetValue(ColourMappingProperty, value);
  82. }
  83. public IEnumerable? ItemsSource
  84. {
  85. get => GetValue(ItemsSourceProperty);
  86. set => SetValue(ItemsSourceProperty, value);
  87. }
  88. [InheritDataTypeFromItems(nameof(ItemsSource))]
  89. public IDataTemplate? ItemTemplate
  90. {
  91. get => GetValue(ItemTemplateProperty);
  92. set => SetValue(ItemTemplateProperty, value);
  93. }
  94. public DayOfWeek FirstDayOfWeek
  95. {
  96. get => GetValue(FirstDayOfWeekProperty);
  97. set => SetValue(FirstDayOfWeekProperty, value);
  98. }
  99. public DateTime CurrentDate
  100. {
  101. get => GetValue(CurrentDateProperty);
  102. set => SetValue(CurrentDateProperty, value);
  103. }
  104. public event EventHandler<MonthViewCellEventArgs>? CellClicked;
  105. public event EventHandler<MonthViewCellEventArgs>? CellHeld;
  106. public event EventHandler<MonthViewBlockEventArgs>? BlockClicked;
  107. public event EventHandler<MonthViewBlockEventArgs>? BlockHeld;
  108. public event EventHandler<MonthViewDateRangeEventArgs>? DateRangeChanged;
  109. static MonthView()
  110. {
  111. MinimumBlockHeightProperty.Changed.AddClassHandler<MonthView>(Render_Changed);
  112. ItemsSourceProperty.Changed.AddClassHandler<MonthView>(ItemsSource_Changed);
  113. FirstDayOfWeekProperty.Changed.AddClassHandler<MonthView>(Render_Changed);
  114. CurrentDateProperty.Changed.AddClassHandler<MonthView>(Render_Changed);
  115. }
  116. private static void Render_Changed(MonthView view, AvaloniaPropertyChangedEventArgs args)
  117. {
  118. view.Render();
  119. }
  120. public MonthView()
  121. {
  122. InitializeComponent();
  123. }
  124. private static void ItemsSource_Changed(MonthView view, AvaloniaPropertyChangedEventArgs args)
  125. {
  126. if(args.OldValue is INotifyCollectionChanged oldNotify)
  127. {
  128. oldNotify.CollectionChanged -= view.Collection_Changed;
  129. }
  130. view.Render(itemsChanged: true);
  131. if(view.ItemsSource is INotifyCollectionChanged notify)
  132. {
  133. notify.CollectionChanged += view.Collection_Changed;
  134. }
  135. }
  136. private void Collection_Changed(object? sender, NotifyCollectionChangedEventArgs e)
  137. {
  138. Render(itemsChanged: true);
  139. }
  140. private void Canvas_SizeChanged(object? sender, SizeChangedEventArgs e)
  141. {
  142. Render();
  143. }
  144. private DateTime _startDate;
  145. private class Block : StyledElement
  146. {
  147. public static readonly StyledProperty<DateTime> StartTimeProperty =
  148. AvaloniaProperty.Register<Block, DateTime>(nameof(StartDate));
  149. public static readonly StyledProperty<DateTime> EndTimeProperty =
  150. AvaloniaProperty.Register<Block, DateTime>(nameof(EndDate));
  151. public static readonly StyledProperty<bool> HoveredProperty =
  152. AvaloniaProperty.Register<Block, bool>(nameof(Hovered));
  153. public int NColumns { get; set; } = -1;
  154. public DateTime StartDate
  155. {
  156. get => GetValue(StartTimeProperty);
  157. set => SetValue(StartTimeProperty, value);
  158. }
  159. public DateTime EndDate
  160. {
  161. get => GetValue(EndTimeProperty);
  162. set => SetValue(EndTimeProperty, value);
  163. }
  164. public bool Hovered
  165. {
  166. get => GetValue(HoveredProperty);
  167. set => SetValue(HoveredProperty, value);
  168. }
  169. public object? Content { get; set; }
  170. public override string ToString()
  171. {
  172. return $"Block({StartDate:yyyy-MM-dd} - {EndDate:yyyy-MM-dd})";
  173. }
  174. }
  175. private List<IDisposable> _oldSubscriptions = new();
  176. private List<Block> _blocks = new();
  177. private void RecreateBlocksList()
  178. {
  179. if (ItemsSource is null) return;
  180. var startBinding = StartDateMapping;
  181. var endBinding = EndDateMapping;
  182. if(startBinding is null || endBinding is null)
  183. {
  184. return;
  185. }
  186. foreach(var subscription in _oldSubscriptions)
  187. {
  188. subscription.Dispose();
  189. }
  190. _oldSubscriptions.Clear();
  191. _blocks.Clear();
  192. foreach(var item in ItemsSource)
  193. {
  194. if (item is null) continue;
  195. var block = new Block
  196. {
  197. [!Block.StartTimeProperty] = startBinding,
  198. [!Block.EndTimeProperty] = endBinding,
  199. [Block.DataContextProperty] = item,
  200. Content = item
  201. };
  202. _oldSubscriptions.Add(block.GetObservable(Block.StartTimeProperty).Skip(1).Subscribe(x => UpdateBlock(block)));
  203. _oldSubscriptions.Add(block.GetObservable(Block.EndTimeProperty).Skip(1).Subscribe(x => UpdateBlock(block)));
  204. _blocks.Add(block);
  205. }
  206. _blocks.SortBy(x => x.StartDate);
  207. }
  208. private void UpdateBlock(Block block)
  209. {
  210. Render();
  211. }
  212. private static int FloorMod(int a, int b)
  213. {
  214. return ((a % b) + b) % b;
  215. }
  216. private class DayBlockEntry(Block block, int level)
  217. {
  218. public Block Block { get; set; } = block;
  219. public int Level { get; set; } = level;
  220. }
  221. private class DayBlock : StyledElement
  222. {
  223. public static readonly StyledProperty<int> OverflowProperty =
  224. AvaloniaProperty.Register<Block, int>(nameof(Overflow), 0);
  225. public DateTime Date { get; set; }
  226. public List<DayBlockEntry> Blocks { get; set; } = new();
  227. public int Level { get; set; } = 0;
  228. public int Overflow
  229. {
  230. get => GetValue(OverflowProperty);
  231. set => SetValue(OverflowProperty, value);
  232. }
  233. }
  234. private bool _itemsChanged = false;
  235. private bool _rerendering = false;
  236. private void Render(bool itemsChanged = false)
  237. {
  238. _itemsChanged = _itemsChanged || itemsChanged;
  239. if (!_rerendering)
  240. {
  241. _rerendering = true;
  242. Dispatcher.UIThread.InvokeAsync(DoRender);
  243. }
  244. }
  245. private double _colWidth;
  246. private double _colSpace;
  247. private double _rowHeight;
  248. private (DateTime, DateTime)? _lastDateRange;
  249. private const double _dayLabelWidth = 18;
  250. private List<Border> _blockControls = new();
  251. private void DoRender()
  252. {
  253. _rerendering = false;
  254. var itemsChanged = _itemsChanged;
  255. _itemsChanged = false;
  256. if (itemsChanged)
  257. {
  258. RecreateBlocksList();
  259. }
  260. var firstDayOfMonth = new DateTime(CurrentDate.Year, CurrentDate.Month, 1);
  261. var dayDiff = FloorMod(firstDayOfMonth.DayOfWeek - FirstDayOfWeek, 7);
  262. var startDate = firstDayOfMonth.AddDays(-dayDiff);
  263. _startDate = startDate;
  264. var dateRange = (start: _startDate, end: _startDate.AddDays(41)); // 41 because 6 rows, 7 columns, but minus 1.
  265. if(_lastDateRange != dateRange)
  266. {
  267. _lastDateRange = dateRange;
  268. Dispatcher.UIThread.InvokeAsync(() =>
  269. {
  270. DateRangeChanged?.Invoke(this, new(dateRange.start, dateRange.end));
  271. });
  272. }
  273. Canvas.Children.Clear();
  274. HeaderCanvas.Children.Clear();
  275. var colSpace = 1;
  276. if (Canvas.Bounds.Width == 0 || Canvas.Bounds.Height == 0) return;
  277. var columnWidth = (Canvas.Bounds.Width - 6 * colSpace) / 7;
  278. var rowHeight = (Canvas.Bounds.Height - 5 * colSpace) / 6;
  279. _colSpace = colSpace;
  280. _rowHeight = rowHeight;
  281. _colWidth = columnWidth;
  282. var minBlockHeight = 15;
  283. var dayLabelSpace = 22;
  284. var usableRowSpace = rowHeight - dayLabelSpace - 1;
  285. var nBlocksPerRow = (int)Math.Floor(usableRowSpace / minBlockHeight);
  286. var blockHeight = nBlocksPerRow == 0 ? minBlockHeight : usableRowSpace / nBlocksPerRow;
  287. // Row Separators
  288. for(int week = 1; week < 6; ++week)
  289. {
  290. var rowSeparator = new Rectangle
  291. {
  292. Width = Canvas.Bounds.Width,
  293. Height = 0.75,
  294. Fill = new SolidColorBrush(Colors.LightGray)
  295. };
  296. Canvas.SetTop(rowSeparator, (rowHeight + colSpace) * week - colSpace);
  297. Canvas.Children.Add(rowSeparator);
  298. }
  299. // Column Separators
  300. for(int day = 1; day < 7; ++day)
  301. {
  302. var colSeparator = new Rectangle
  303. {
  304. Height = Canvas.Bounds.Height,
  305. Width = 0.75,
  306. Fill = new SolidColorBrush(Colors.LightGray)
  307. };
  308. Canvas.SetLeft(colSeparator, (columnWidth + colSpace) * day - colSpace);
  309. Canvas.Children.Add(colSeparator);
  310. }
  311. // Day of Week Header Labels
  312. for(int day = 0; day < 7; ++day)
  313. {
  314. var dayOfWeek = (DayOfWeek)FloorMod((int)FirstDayOfWeek + day, 7);
  315. var block = new TextBlock
  316. {
  317. Text = dayOfWeek.ToString()[0..3],
  318. Margin = new(0, 0),
  319. Foreground = new SolidColorBrush(
  320. dayOfWeek == DateTime.Today.DayOfWeek && DateTime.Today.Month == CurrentDate.Month
  321. ? Colors.CornflowerBlue
  322. : Colors.Black),
  323. Width = columnWidth,
  324. TextAlignment = TextAlignment.Center,
  325. VerticalAlignment = VerticalAlignment.Center
  326. }.WithClasses("ExtraSmall", "Bold");
  327. block.SizeChanged += HeaderBlock_SizeChanged;
  328. Canvas.SetLeft(block, day * (columnWidth + colSpace));
  329. HeaderCanvas.Children.Add(block);
  330. }
  331. var dayBlocks = new Dictionary<DateTime, DayBlock>();
  332. // Cells and Day Labels
  333. for(int week = 0; week < 6; ++week)
  334. {
  335. for(int day = 0; day < 7; ++day)
  336. {
  337. var date = _startDate.AddDays(day + week * 7);
  338. var dayBlock = dayBlocks.GetValueOrAdd(date);
  339. dayBlock.Date = date;
  340. var cell = new Rectangle
  341. {
  342. Fill = new SolidColorBrush(Colors.Transparent),
  343. Width = _colWidth,
  344. Height = _rowHeight
  345. };
  346. cell.PointerPressed += Cell_PointerPressed;
  347. cell.PointerReleased += Cell_PointerReleased;
  348. Canvas.SetLeft(cell, day * (columnWidth + colSpace));
  349. Canvas.SetTop(cell, week * (rowHeight + colSpace));
  350. Canvas.Children.Add(cell);
  351. var border = new Border
  352. {
  353. Margin = new(2),
  354. Background = new SolidColorBrush(date == DateTime.Today && CurrentDate.Month == date.Month ? Colors.CornflowerBlue : Colors.Transparent),
  355. Width = _dayLabelWidth,
  356. Height = _dayLabelWidth,
  357. CornerRadius = new(_dayLabelWidth / 2),
  358. IsHitTestVisible = false
  359. };
  360. var block = new TextBlock
  361. {
  362. Text = date.Day.ToString(),
  363. Foreground = new SolidColorBrush(date.Month == CurrentDate.Month ? Colors.Black : Colors.Gray),
  364. HorizontalAlignment = HorizontalAlignment.Center,
  365. VerticalAlignment = VerticalAlignment.Center,
  366. FontSize = 10
  367. }.WithClass("Bold");
  368. border.Child = block;
  369. Canvas.SetLeft(border, day * (columnWidth + colSpace));
  370. Canvas.SetTop(border, week * (rowHeight + colSpace));
  371. Canvas.Children.Add(border);
  372. var overflowBorder = new Border
  373. {
  374. Margin = new(2),
  375. Background = new SolidColorBrush(Colors.Red),
  376. Width = 18,
  377. Height = 18,
  378. CornerRadius = new(9)
  379. };
  380. var overflowText = new TextBlock
  381. {
  382. [!TextBlock.TextProperty] = dayBlock.GetObservable(DayBlock.OverflowProperty)
  383. .Select(x => $"+{x}")
  384. .ToBinding(),
  385. Foreground = new SolidColorBrush(Colors.White),
  386. HorizontalAlignment = HorizontalAlignment.Center,
  387. VerticalAlignment = VerticalAlignment.Center,
  388. FontSize = 10
  389. }.WithClass("Bold");
  390. overflowBorder.Child = overflowText;
  391. overflowBorder[!Border.IsVisibleProperty] = dayBlock.GetObservable(DayBlock.OverflowProperty)
  392. .Select(x => x > 0)
  393. .ToBinding();
  394. overflowBorder.Tag = dayBlock;
  395. overflowBorder.PointerPressed += OverflowBorder_PointerPressed;
  396. overflowBorder.PointerReleased += OverflowBorder_PointerReleased;
  397. Canvas.SetRight(overflowBorder, Canvas.Bounds.Width - (day * (columnWidth + colSpace) + columnWidth));
  398. Canvas.SetTop(overflowBorder, week * (rowHeight + colSpace));
  399. Canvas.Children.Add(overflowBorder);
  400. }
  401. }
  402. // Blocks
  403. _blockControls.Clear();
  404. var colourBinding = ColourMapping;
  405. foreach(var block in _blocks)
  406. {
  407. for(var day = block.StartDate; day <= block.EndDate; day = day.AddDays(1))
  408. {
  409. dayBlocks.GetValueOrAdd(day).Blocks.Add(new(block, -1));
  410. }
  411. }
  412. foreach(var block in _blocks)
  413. {
  414. var startWeek = (int)Math.Floor((block.StartDate.Date - _startDate).Days / 7.0);
  415. var endWeek = (int)Math.Floor((block.EndDate.Date - _startDate).Days / 7.0);
  416. if (startWeek > 5) continue;
  417. if (endWeek < 0) continue;
  418. for (var week = Math.Max(startWeek, 0); week <= Math.Min(endWeek, 5); ++week)
  419. {
  420. // So, for each week, we need to find what level the block fits in. If any of the days are already full,
  421. // they don't count for working out the level.
  422. var startDay = week == startWeek ? FloorMod(block.StartDate.DayOfWeek - FirstDayOfWeek, 7) : 0;
  423. var endDay = week == endWeek ? FloorMod(block.EndDate.DayOfWeek - FirstDayOfWeek, 7) : 6;
  424. // Because the blocks are sorted, we actually only need to check the first day of the block. If that's full,
  425. // then we check the next day, etc.
  426. var startDateForWeek = _startDate.AddDays(week * 7 + startDay);
  427. var endDateForWeek = _startDate.AddDays(week * 7 + endDay);
  428. var level = -1;
  429. for(var checkDay = startDateForWeek; checkDay <= endDateForWeek; checkDay = checkDay.AddDays(1))
  430. {
  431. var dayBlock = dayBlocks.GetValueOrAdd(checkDay);
  432. var n = 0;
  433. while (true)
  434. {
  435. if(!dayBlock.Blocks.Any(x => x.Level == n))
  436. {
  437. break;
  438. }
  439. ++n;
  440. }
  441. if(n < nBlocksPerRow)
  442. {
  443. level = n;
  444. break;
  445. }
  446. else
  447. {
  448. // Skip this day.
  449. ++startDay;
  450. dayBlock.Overflow = Math.Max(dayBlock.Blocks.Count - nBlocksPerRow, 0);
  451. }
  452. }
  453. if (level < 0)
  454. {
  455. continue;
  456. }
  457. else
  458. {
  459. for(var day = startDateForWeek; day <= endDateForWeek; day = day.AddDays(1))
  460. {
  461. var entry = dayBlocks.GetValueOrAdd(day).Blocks.First(x => x.Block == block);
  462. entry.Level = level;
  463. }
  464. }
  465. var border = CreateControl(block, new Thickness(1, 1, endDateForWeek == block.EndDate ? 3 : 0, 1));
  466. Canvas.SetLeft(border, startDay * (columnWidth + colSpace));
  467. Canvas.SetTop(border, level * blockHeight + dayLabelSpace + week * (rowHeight + colSpace));
  468. border.Width = (endDay - startDay) * (columnWidth + colSpace) + columnWidth;
  469. border.Height = blockHeight;
  470. Canvas.Children.Add(border);
  471. }
  472. }
  473. /*var minY = double.MaxValue;
  474. var colX = 0.0;
  475. var i = 0;
  476. foreach(var columnKey in _columns)
  477. {
  478. if(!_blocks.TryGetValue(columnKey, out var columnBlocks))
  479. {
  480. continue;
  481. }
  482. var contentControl = new ContentControl
  483. {
  484. Content = columnKey,
  485. Width = colWidth * columnBlocks.Columns!.Count,
  486. [!Block.ContentTemplateProperty] = this[!HeaderTemplateProperty],
  487. };
  488. Canvas.SetLeft(contentControl, colX);
  489. HeaderCanvas.Children.Add(contentControl);
  490. contentControl.SizeChanged += ContentControl_SizeChanged;
  491. foreach(var column in columnBlocks.Columns!)
  492. {
  493. foreach(var block in column)
  494. {
  495. var blockY = GetRow(block.StartTime) * rowHeight;
  496. minY = Math.Min(blockY, minY);
  497. Canvas.SetTop(block, blockY);
  498. Canvas.SetLeft(block, colX);
  499. block.Height = Math.Max((GetRow(block.EndTime) - GetRow(block.StartTime)) * rowHeight, 5);
  500. block.Width = colWidth * block.NColumns;
  501. Canvas.Children.Add(block);
  502. }
  503. colX += colWidth;
  504. }
  505. if(i < _blocks.Count - 1)
  506. {
  507. var rectangle = new Rectangle
  508. {
  509. Width = 0.75,
  510. Height = Canvas.Height,
  511. Fill = new SolidColorBrush(Colors.LightGray)
  512. };
  513. Canvas.SetLeft(rectangle, colX);
  514. Canvas.Children.Add(rectangle);
  515. var headRectangle = new Rectangle
  516. {
  517. Width = 0.75,
  518. [!Rectangle.HeightProperty] = HeaderCanvas.WhenValueChanged(x => x.Bounds)
  519. .Select(x => x.Height)
  520. .ToBinding(),
  521. Fill = new SolidColorBrush(Colors.LightGray)
  522. };
  523. Canvas.SetLeft(headRectangle, colX);
  524. HeaderCanvas.Children.Add(headRectangle);
  525. colX += colSpace;
  526. }
  527. ++i;
  528. }
  529. Canvas.Width = colX;
  530. HeaderCanvas.Width = colX;
  531. if(minY == double.MaxValue)
  532. {
  533. ScrollViewer.Offset = new(0, 0);
  534. }
  535. else
  536. {
  537. ScrollViewer.Offset = new(0, Math.Max(minY - RowHeight / 2, 0));
  538. }
  539. var lines = new List<Control>();
  540. LabelCanvas.Children.Clear();
  541. LabelCanvas.Height = Canvas.Height;
  542. var y = rowHeight;
  543. for(var time = RowInterval; time < TimeSpan.FromHours(24); time += RowInterval)
  544. {
  545. var rectangle = new Rectangle
  546. {
  547. Width = Canvas.Width,
  548. Height = 0.75,
  549. Fill = new SolidColorBrush(Colors.LightGray)
  550. };
  551. Canvas.SetLeft(rectangle, 0);
  552. Canvas.SetTop(rectangle, y);
  553. lines.Add(rectangle);
  554. var block = new TextBlock
  555. {
  556. Text = time.ToString("hh\\:mm"),
  557. Margin = new(0, -5, 0, 0)
  558. }.WithClass("ExtraSmall");
  559. block.SizeChanged += Block_SizeChanged;
  560. Canvas.SetTop(block, y);
  561. LabelCanvas.Children.Add(block);
  562. y += rowHeight;
  563. }
  564. Canvas.Children.InsertRange(0, lines);*/
  565. }
  566. private Rectangle? _selectedRectangle;
  567. private void Cell_PointerPressed(object? sender, PointerPressedEventArgs e)
  568. {
  569. if (sender is not Rectangle rectangle) return;
  570. if(_selectedRectangle is not null)
  571. {
  572. _selectedRectangle.Fill = new SolidColorBrush(Colors.Transparent);
  573. _selectedRectangle = null;
  574. }
  575. if (ClosePopup()) return;
  576. if (!TryGetDateFromPosition(e, out var date)) return;
  577. _selectedRectangle = rectangle;
  578. _selectedRectangle.Fill = new SolidColorBrush(Colors.LightBlue, opacity: 0.5);
  579. PressedAction(() => CellHeld?.Invoke(this, new(date)));
  580. }
  581. private void Cell_PointerReleased(object? sender, PointerReleasedEventArgs e)
  582. {
  583. if (sender is not Rectangle rectangle) return;
  584. if (!TryGetDateFromPosition(e, out var date)) return;
  585. ReleasedAction(() =>
  586. {
  587. if(_selectedRectangle is not null)
  588. {
  589. _selectedRectangle.Fill = new SolidColorBrush(Colors.Transparent);
  590. _selectedRectangle = null;
  591. }
  592. CellClicked?.Invoke(this, new(date));
  593. });
  594. }
  595. private void RootPointerPressed(object? sender, PointerPressedEventArgs e)
  596. {
  597. }
  598. private Control? _magnifiedDayBackground;
  599. private Control? _magnifiedDayControl;
  600. private DayBlock? _magnifiedDay;
  601. private bool ClosePopup()
  602. {
  603. if(_magnifiedDayControl is not null)
  604. {
  605. _magnifiedDay = null;
  606. Canvas.Children.Remove(_magnifiedDayControl);
  607. Canvas.Children.Remove(_magnifiedDayBackground!);
  608. _magnifiedDayControl = null;
  609. _magnifiedDayBackground = null;
  610. return true;
  611. }
  612. else
  613. {
  614. return false;
  615. }
  616. }
  617. private void OverflowBorder_PointerReleased(object? sender, PointerReleasedEventArgs e)
  618. {
  619. if (sender is not Border control
  620. || control.Tag is not DayBlock dayBlock) return;
  621. e.Handled = true;
  622. if(_magnifiedDay == dayBlock)
  623. {
  624. return;
  625. }
  626. if(_magnifiedDayControl is not null)
  627. {
  628. Canvas.Children.Remove(_magnifiedDayControl);
  629. Canvas.Children.Remove(_magnifiedDayBackground!);
  630. }
  631. _magnifiedDay = dayBlock;
  632. _magnifiedDayBackground = new Rectangle
  633. {
  634. Fill = new SolidColorBrush(Colors.Black, opacity: 0.2),
  635. Width = Canvas.Bounds.Width,
  636. Height = Canvas.Bounds.Height,
  637. };
  638. Canvas.Children.Add(_magnifiedDayBackground);
  639. _magnifiedDayBackground.PointerReleased += _magnifiedDayBackground_PointerReleased;
  640. var popoutBorder = new Border
  641. {
  642. BorderBrush = new SolidColorBrush(Colors.LightGray),
  643. BorderThickness = new(0.75),
  644. Background = new SolidColorBrush(Colors.White),
  645. Width = _colWidth * 1.5,
  646. BoxShadow = new(new BoxShadow
  647. {
  648. Color = Colors.Gray,
  649. OffsetX = 0,
  650. OffsetY = 0,
  651. Blur = 10
  652. })
  653. };
  654. popoutBorder.PointerPressed += PopoutBorder_PointerPressed;
  655. var list = new StackPanel();
  656. // Day label
  657. {
  658. var dayOfWeek = dayBlock.Date.DayOfWeek.ToString()[..3];
  659. var dayLabel = new TextBlock
  660. {
  661. Text = $"{dayOfWeek} {dayBlock.Date.Day} {dayBlock.Date:MMM}",
  662. Foreground = new SolidColorBrush(dayBlock.Date.Month == DateTime.Today.Month ? Colors.Black : Colors.Gray),
  663. HorizontalAlignment = HorizontalAlignment.Left,
  664. VerticalAlignment = VerticalAlignment.Center,
  665. Margin = new(2),
  666. FontSize = 10
  667. }.WithClass("Bold");
  668. list.Children.Add(dayLabel);
  669. }
  670. foreach(var blockEntry in dayBlock.Blocks)
  671. {
  672. var blockControl = CreateControl(blockEntry.Block, new(1));
  673. list.Children.Add(blockControl);
  674. }
  675. popoutBorder.Child = list;
  676. _magnifiedDayControl = popoutBorder;
  677. var day = (dayBlock.Date - _startDate).Days;
  678. var rowIdx = (int)Math.Floor(day / 7.0);
  679. var colIdx = day - rowIdx * 7;
  680. var centre = new Point(
  681. colIdx * (_colWidth + _colSpace) + _colWidth / 2,
  682. rowIdx * (_rowHeight + _colSpace) + _rowHeight / 2);
  683. popoutBorder.SizeChanged += (o, e) =>
  684. {
  685. Canvas.SetLeft(popoutBorder,
  686. Math.Clamp(centre.X - popoutBorder.Bounds.Width / 2, 0, Canvas.Bounds.Width - popoutBorder.Bounds.Width));
  687. Canvas.SetTop(popoutBorder,
  688. Math.Clamp(centre.Y - popoutBorder.Bounds.Height / 2, 0, Canvas.Bounds.Height - popoutBorder.Bounds.Height));
  689. };
  690. var animation = new Animation();
  691. {
  692. animation.Duration = TimeSpan.FromSeconds(0.1);
  693. var startFrame = new KeyFrame
  694. {
  695. Cue = new(0),
  696. };
  697. startFrame.Setters.Add(new Setter()
  698. {
  699. Property = Border.OpacityProperty,
  700. Value = 0.0
  701. });
  702. startFrame.Setters.Add(new Setter()
  703. {
  704. Property = ScaleTransform.ScaleXProperty,
  705. Value = 0.0
  706. });
  707. startFrame.Setters.Add(new Setter()
  708. {
  709. Property = ScaleTransform.ScaleYProperty,
  710. Value = 0.0
  711. });
  712. animation.Children.Add(startFrame);
  713. var endFrame = new KeyFrame
  714. {
  715. Cue = new(1.0),
  716. };
  717. endFrame.Setters.Add(new Setter()
  718. {
  719. Property = Border.OpacityProperty,
  720. Value = 1.0
  721. });
  722. endFrame.Setters.Add(new Setter()
  723. {
  724. Property = ScaleTransform.ScaleXProperty,
  725. Value = 1.0
  726. });
  727. endFrame.Setters.Add(new Setter()
  728. {
  729. Property = ScaleTransform.ScaleYProperty,
  730. Value = 1.0
  731. });
  732. animation.Children.Add(endFrame);
  733. }
  734. var backgroundAnimation = new Animation();
  735. {
  736. backgroundAnimation.Duration = TimeSpan.FromSeconds(0.1);
  737. var startFrame = new KeyFrame
  738. {
  739. Cue = new(0),
  740. };
  741. startFrame.Setters.Add(new Setter()
  742. {
  743. Property = Border.OpacityProperty,
  744. Value = 0.0
  745. });
  746. backgroundAnimation.Children.Add(startFrame);
  747. var endFrame = new KeyFrame
  748. {
  749. Cue = new(1.0),
  750. };
  751. endFrame.Setters.Add(new Setter()
  752. {
  753. Property = Border.OpacityProperty,
  754. Value = 1.0
  755. });
  756. backgroundAnimation.Children.Add(endFrame);
  757. }
  758. animation.RunAsync(popoutBorder).LogIfFail();
  759. backgroundAnimation.RunAsync(_magnifiedDayBackground).LogIfFail();
  760. Canvas.Children.Add(_magnifiedDayControl);
  761. }
  762. private void _magnifiedDayBackground_PointerReleased(object? sender, PointerReleasedEventArgs e)
  763. {
  764. ClosePopup();
  765. }
  766. private void OverflowBorder_PointerPressed(object? sender, PointerPressedEventArgs e)
  767. {
  768. if (sender is not Border border
  769. || border.Tag is not DayBlock dayBlock) return;
  770. e.Handled = true;
  771. }
  772. private void PopoutBorder_PointerPressed(object? sender, PointerPressedEventArgs e)
  773. {
  774. e.Handled = true;
  775. }
  776. private Control CreateControl(Block block, Thickness margin)
  777. {
  778. var border = new Border
  779. {
  780. };
  781. var innerBorder = new Border
  782. {
  783. [Border.DataContextProperty] = block.Content,
  784. Margin = margin,
  785. Tag = block
  786. };
  787. if(ColourMapping is not null)
  788. {
  789. innerBorder[!Border.BackgroundProperty] = ColourMapping;
  790. }
  791. innerBorder.PointerEntered += InnerBorder_PointerEntered;
  792. innerBorder.PointerExited += InnerBorder_PointerExited;
  793. innerBorder.PointerPressed += InnerBorder_PointerPressed;
  794. innerBorder.PointerReleased += InnerBorder_PointerReleased;
  795. innerBorder[!Border.BorderBrushProperty] = block.GetObservable(Block.HoveredProperty)
  796. .Select(x => x ? new SolidColorBrush(Colors.Black) : new SolidColorBrush(Colors.Transparent))
  797. .ToBinding();
  798. innerBorder.BorderThickness = new(1);
  799. border.Child = innerBorder;
  800. var contentControl = new ContentControl();
  801. contentControl.Content = block.Content;
  802. contentControl[!ContentControl.ContentTemplateProperty] = this[!ItemTemplateProperty];
  803. innerBorder.Child = contentControl;
  804. _blockControls.Add(innerBorder);
  805. return border;
  806. }
  807. private void InnerBorder_PointerPressed(object? sender, PointerPressedEventArgs e)
  808. {
  809. if (sender is not Border border
  810. || border.Tag is not Block block) return;
  811. if(_magnifiedDayControl is not null
  812. && !border.HasParent(_magnifiedDayControl))
  813. {
  814. ClosePopup();
  815. }
  816. e.Handled = true;
  817. PressedAction(() => BlockHeld?.Invoke(this, new(block.Content)));
  818. }
  819. private void InnerBorder_PointerReleased(object? sender, PointerReleasedEventArgs e)
  820. {
  821. if (sender is not Border border
  822. || border.Tag is not Block block) return;
  823. e.Handled = true;
  824. ReleasedAction(() => BlockClicked?.Invoke(this, new(block.Content)));
  825. }
  826. private void InnerBorder_PointerExited(object? sender, PointerEventArgs e)
  827. {
  828. if (sender is not Border border
  829. || border.Tag is not Block block) return;
  830. block.Hovered = _blockControls.Where(x => x.Tag == block).Any(x => x.IsPointerOver);
  831. }
  832. private void InnerBorder_PointerEntered(object? sender, PointerEventArgs e)
  833. {
  834. if (sender is not Border border
  835. || border.Tag is not Block block) return;
  836. block.Hovered = _blockControls.Where(x => x.Tag == block).Any(x => x.IsPointerOver);
  837. }
  838. private bool TryGetDateFromPosition(PointerEventArgs e, out DateTime date)
  839. {
  840. var point = e.GetPosition(Canvas);
  841. var rowIdx = Math.Clamp((int)Math.Floor(point.Y / _rowHeight), 0, 5);
  842. var colIdx = Math.Clamp((int)Math.Floor(point.X / (_colWidth + _colSpace)), 0, 6);
  843. date = _startDate.AddDays(rowIdx * 7 + colIdx);
  844. return true;
  845. }
  846. private CancellationTokenSource? cts = null;
  847. private void PressedAction(Action onHeld)
  848. {
  849. cts?.Cancel();
  850. cts = new();
  851. Task.Delay(1000).ContinueWith(task =>
  852. {
  853. cts = null;
  854. onHeld();
  855. }, cts.Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
  856. }
  857. private void ReleasedAction(Action onRelease)
  858. {
  859. if(cts is not null)
  860. {
  861. cts.Cancel();
  862. onRelease();
  863. }
  864. }
  865. private void HeaderBlock_SizeChanged(object? sender, SizeChangedEventArgs e)
  866. {
  867. if (sender is not TextBlock block) return;
  868. Canvas.SetTop(block, HeaderCanvas.Bounds.Height / 2 - block.Bounds.Height / 2);
  869. }
  870. }