-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmain.ts
More file actions
692 lines (618 loc) · 23.9 KB
/
Copy pathmain.ts
File metadata and controls
692 lines (618 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
import {
mdiCheckCircleOutline,
mdiDelete,
mdiPencil,
mdiDotsHorizontal,
} from "@mdi/js";
import { LitElement, html, nothing } from "lit";
import { property, state, query } from "lit/decorators.js";
import type { HomeAssistant } from "custom-card-helpers";
import { formatDateNumeric } from "custom-card-helpers";
import { localize } from '../localize/localize';
import { VERSION } from "./const";
import { loadConfigDashboard } from "./helpers";
import { commonStyle } from './styles'
import { EntityRegistryEntry, IntegrationConfig, IntervalType, INTERVAL_TYPES, getIntervalTypeLabels, Label, Task, Tag } from './types';
import { completeTask, getConfig, loadLabelRegistry, loadRegistryEntries, loadTags, loadTask, loadTasks, removeTask, saveTask, updateTask } from './data/websockets';
interface TaskFormData {
title: string;
interval_value: number | "";
interval_type: string;
last_performed: string;
icon: string;
label: string[];
tag: string;
}
export class HomeMaintenancePanel extends LitElement {
@property() hass?: HomeAssistant;
@property() narrow!: boolean;
@state() private tags: Tag[] | null = null;
@state() private tasks: Task[] = [];
@state() private config: IntegrationConfig | null = null;
@state() private registry: EntityRegistryEntry[] = [];
@state() private labelRegistry: Label[] = [];
// New Task form state
@state() private _formData: TaskFormData = {
title: "",
interval_value: "",
interval_type: "days",
last_performed: "",
icon: "",
label: [],
tag: "",
};
private _advancedOpen: boolean = false;
// Edit dialog state
@state() private _editingTaskId: string | null = null;
@state() private _editFormData: TaskFormData = {
title: "",
interval_value: "",
interval_type: "days",
last_performed: "",
icon: "",
label: [],
tag: "",
};
// Shared overflow menu state
@state() private _selectedTaskId: string | null = null;
@query("#actions-menu") private _actionsMenu?: any;
private get _columns() {
return {
icon: {
title: "",
moveable: false,
showNarrow: false,
label: "icon",
type: "icon",
template: (task: Task) =>
task.icon ? html`<ha-icon .icon=${task.icon}></ha-icon>` : nothing,
},
tagIcon: {
title: "",
moveable: false,
showNarrow: false,
label: "tag",
type: "icon",
template: (task: any) =>
task.tagIcon ? html`<ha-icon .icon=${task.tagIcon}></ha-icon>` : nothing,
},
title: {
title: 'Title',
main: true,
showNarrow: true,
sortable: true,
filterable: true,
grows: true,
extraTemplate: (task: Task) => {
const entity = this.registry.find((entry) => entry.unique_id === task.id);
if (!entity) return nothing;
const labels = this.labelRegistry.filter((lr) => entity.labels.includes(lr.label_id));
return labels.length
? html`<ha-data-table-labels .labels=${labels}></ha-data-table-labels>`
: nothing;
},
},
interval_days: {
title: 'Interval',
showNarrow: false,
sortable: true,
minWidth: "100px",
maxWidth: "100px",
template: (task: Task) => {
const type = task.interval_type;
const isSingular = task.interval_value === 1;
const labelKey = isSingular ? type.slice(0, -1) : type;
return `${task.interval_value} ${localize(`intervals.${labelKey}`, this.hass!.language)}`;
}
},
last_performed: {
title: 'Last Performed',
showNarrow: false,
sortable: true,
minWidth: "150px",
maxWidth: "150px",
template: (task: Task) => {
if (!task.last_performed) return "-";
const date = new Date(this.computeISODate(task.last_performed));
return formatDateNumeric(date, this.hass!.locale);
}
},
next_due: {
title: localize('panel.cards.current.next', this.hass!.language),
showNarrow: true,
sortable: true,
direction: "asc",
minWidth: "100px",
maxWidth: "100px",
template: (task: any) => {
const now = new Date();
const next = new Date(task.next_due);
const isDue = next <= now;
return html`
<span style=${isDue ? "color: var(--error-color, red); font-weight: bold;" : ""}>
${formatDateNumeric(next, this.hass!.locale)}
</span>` || "—";
},
},
complete: {
minWidth: "64px",
maxWidth: "64px",
sortable: false,
groupable: false,
showNarrow: true,
moveable: false,
hideable: false,
type: "overflow",
template: (task: Task) => html`
<ha-icon-button
@click=${() => this._handleCompleteTaskClick(task.id)}
.label="Complete"
title="Mark Task Complete"
.path=${mdiCheckCircleOutline}
></ha-icon-button>
`,
},
actions: {
title: "",
label: "actions",
showNarrow: true,
moveable: false,
hideable: false,
type: "overflow-menu",
template: (task: Task) => html`
<ha-icon-button
@click=${(e: Event) => this._handleShowMenu(task.id, e)}
.label="Actions"
title="Actions"
.path=${mdiDotsHorizontal}
></ha-icon-button>
`,
},
}
};
private get _columnsToDisplay() {
return Object.fromEntries(
Object.entries(this._columns).filter(([_, col]) =>
this.narrow ? col.showNarrow !== false : true
)
);
}
private get _rows() {
return this.tasks.map((task: Task) => ({
icon: task.icon,
id: task.id,
title: task.title,
interval_value: task.interval_value,
interval_type: task.interval_type,
last_performed: task.last_performed ?? 'Never',
interval_days: (() => {
switch (task.interval_type) {
case "days":
return task.interval_value;
case "weeks":
return task.interval_value * 7;
case "months":
return task.interval_value * 30;
default:
return Number.MAX_SAFE_INTEGER;
}
})(),
next_due: (() => {
const [datePart] = task.last_performed.split("T");
const [year, month, day] = datePart.split("-").map(Number);
const next = new Date(year, month - 1, day);
switch (task.interval_type) {
case "days":
next.setDate(next.getDate() + task.interval_value);
break;
case "weeks":
next.setDate(next.getDate() + task.interval_value * 7);
break;
case "months":
next.setMonth(next.getMonth() + task.interval_value);
break;
default:
throw new Error(`Unsupported interval type: ${task.interval_type}`);
}
return next;
})(),
tagIcon: (() => task.tag_id && task.tag_id.trim() !== "" ? "mdi:tag" : undefined)(),
}));
}
private get _basicSchema() {
return [
{ name: "title", required: true, selector: { text: {} }, },
{ name: "interval_value", required: true, selector: { number: { min: 1, mode: "box" } }, },
{
name: "interval_type",
required: true,
selector: {
select: {
options: INTERVAL_TYPES.map((type) => ({
value: type,
label: getIntervalTypeLabels(this.hass!.language)[type],
})),
mode: "dropdown"
},
},
},
]
};
private get _advancedSchema() {
return [
{ name: "last_performed", selector: { date: {} }, },
{ name: "icon", selector: { icon: {} }, },
{ name: "label", selector: { label: { multiple: true } }, },
{ name: "tag", selector: { entity: { filter: { domain: "tag" } } }, },
]
};
private get _editSchema() {
return [
{ name: "interval_value", required: true, selector: { number: { min: 1, mode: "box" } }, },
{
name: "interval_type",
required: true,
selector: {
select: {
options: INTERVAL_TYPES.map((type) => ({
value: type,
label: getIntervalTypeLabels(this.hass!.language)[type],
})),
mode: "dropdown"
},
},
},
{ type: "constant", name: localize('panel.dialog.edit_task.sections.optional', this.hass!.language), disabled: true },
{ name: "last_performed", selector: { date: {} }, },
{ name: "icon", selector: { icon: {} }, },
{ name: "label", selector: { label: { multiple: true } }, },
{ name: "tag", selector: { entity: { filter: { domain: "tag" } } }, },
]
};
private _computeLabel = (schema: { name: string }): string => {
try {
return localize(`panel.cards.new.fields.${schema.name}.heading`, this.hass!.language) ?? schema.name;
} catch {
return schema.name;
}
}
private _computeHelper = (schema: { name: string }): string => {
try {
return localize(`panel.cards.new.fields.${schema.name}.helper`, this.hass!.language) ?? "";
} catch {
return "";
}
}
private _computeEditLabel = (schema: { name: string }): string => {
try {
return localize(`panel.dialog.edit_task.fields.${schema.name}.heading`, this.hass!.language) ?? schema.name;
} catch {
return schema.name;
}
}
private _computeEditHelper = (schema: { name: string }): string => {
try {
return localize(`panel.dialog.edit_task.fields.${schema.name}.helper`, this.hass!.language) ?? "";
} catch {
return "";
}
}
private async loadData() {
await loadConfigDashboard();
this.tags = await loadTags(this.hass!);
this.tasks = await loadTasks(this.hass!);
this.config = await getConfig(this.hass!);
this.registry = await loadRegistryEntries(this.hass!);
this.labelRegistry = await loadLabelRegistry(this.hass!);
}
private async resetForm() {
this._formData = {
title: "",
interval_value: "",
interval_type: "days",
last_performed: "",
icon: "",
label: [],
tag: "",
};
this.tasks = await loadTasks(this.hass!);
}
private async resetEditForm() {
this._editFormData = {
title: "",
interval_value: "",
interval_type: "days",
last_performed: "",
icon: "",
label: [],
tag: "",
};
}
private computeISODate(dateStr: string): string {
let isoDateStr: string;
if (dateStr) {
// Only take the YYYY-MM-DD part to avoid time zone issues
const [yearStr, monthStr, dayStr] = dateStr.split("T")[0].split("-");
const year = Number(yearStr);
const month = Number(monthStr);
const day = Number(dayStr);
if (!isNaN(year) && !isNaN(month) && !isNaN(day)) {
const parsedDate = new Date(year, month - 1, day);
parsedDate.setHours(0, 0, 0, 0);
isoDateStr = parsedDate.toISOString();
} else {
alert("Invalid date entered.");
const fallback = new Date();
fallback.setHours(0, 0, 0, 0);
isoDateStr = fallback.toISOString();
}
} else {
const today = new Date();
today.setHours(0, 0, 0, 0);
isoDateStr = today.toISOString();
}
return isoDateStr;
}
connectedCallback() {
super.connectedCallback();
this.loadData();
}
render() {
if (!this.hass) return html``;
if (!this.tasks || !this.tags) {
return html`<p>${localize('common.loading', this.hass.language)}</p>`;
}
return html`
<div class="header">
<div class="toolbar">
<ha-menu-button .hass=${this.hass} .narrow=${this.narrow}></ha-menu-button>
<div class="main-title">
${this.config?.options.sidebar_title}
</div>
<div class="version">
v${VERSION}
</div>
</div>
</div>
<div class="view">
<ha-card
header="${localize('panel.cards.new.title', this.hass.language)}"
class="card-new"
>
<div class="card-content">${this.renderForm()}</div>
</ha-card>
<ha-card
header="${localize('panel.cards.current.title', this.hass.language)}"
class="card-current"
>
<div class="card-content">${this.renderTasks()}</div>
</ha-card>
</div>
${this.renderEditDialog()}
${this.renderActionsMenu()}
`;
}
renderForm() {
if (!this.hass) return html``;
return html`
<ha-form
.hass=${this.hass}
.schema=${this._basicSchema}
.computeLabel=${this._computeLabel.bind(this)}
.computeHelper=${this._computeHelper.bind(this)}
.data=${this._formData}
@value-changed=${(e: CustomEvent) => this._handleFormValueChanged(e)}
></ha-form>
<ha-expansion-panel
header="${localize('panel.cards.new.sections.optional', this.hass.language)}"
.opened=${this._advancedOpen}
@opened-changed=${(e: CustomEvent) => (this._advancedOpen = e.detail.value)}
>
<ha-form
.hass=${this.hass}
.data=${this._formData}
.schema=${this._advancedSchema}
.computeLabel=${this._computeLabel.bind(this)}
.computeHelper=${this._computeHelper.bind(this)}
@value-changed=${(e: CustomEvent) => this._handleFormValueChanged(e)}
></ha-form>
</ha-expansion-panel>
<div class="form-field">
<ha-button @click=${this._handleAddTaskClick}>
${localize('panel.cards.new.actions.add_task', this.hass.language)}
</ha-button>
</div>
`;
}
renderTasks() {
if (!this.hass) return html``;
if (!this.tasks || this.tasks.length === 0) {
return html`<span>${localize('common.no_tasks', this.hass!.language)}</span>`;
}
return html`
<div class="table-wrapper">
<ha-data-table
.hass=${this.hass}
.columns=${this._columnsToDisplay}
.data=${this._rows}
.narrow=${this.narrow}
auto-height
id="tasks-table"
class="tasks-table"
clickable
>
</ha-data-table>
</div>
`;
}
renderEditDialog() {
if (!this.hass) return html``;
if (!this._editingTaskId) return html``;
return html`
<ha-dialog
open
heading="${localize('panel.dialog.edit_task.title', this.hass.language)}: ${this._editFormData.title}"
@closed=${this._handleDialogClosed}
>
<ha-form
.hass=${this.hass}
.schema=${this._editSchema}
.computeLabel=${this._computeEditLabel.bind(this)}
.computeHelper=${this._computeEditHelper.bind(this)}
.data=${this._editFormData}
@value-changed=${(e: CustomEvent) => this._handleEditFormValueChanged(e)}
></ha-form>
<ha-button appearance="plain" slot="secondaryAction" @click=${() => (this._editingTaskId = null)}>
${localize('panel.dialog.edit_task.actions.cancel', this.hass.language)}
</ha-button>
<ha-button appearance="accent" slot="primaryAction" @click=${this._handleSaveEditClick}>
${localize('panel.dialog.edit_task.actions.save', this.hass.language)}
</ha-button>
</ha-dialog>
`;
}
renderActionsMenu() {
if (!this.hass) return html``;
return html`
<ha-md-menu id="actions-menu" positioning="fixed">
<ha-md-menu-item
@click=${() => {
if (this._selectedTaskId) {
this._handleOpenEditDialogClick(this._selectedTaskId);
}
}}
>
<ha-svg-icon slot="start" path=${mdiPencil}></ha-svg-icon>
${localize('panel.cards.current.actions.edit', this.hass!.language)}
</ha-md-menu-item>
<ha-md-menu-item
@click=${() => {
if (this._selectedTaskId) {
this._handleRemoveTaskClick(this._selectedTaskId);
}
}}
>
<ha-svg-icon slot="start" path=${mdiDelete}></ha-svg-icon>
${localize('panel.cards.current.actions.remove', this.hass!.language)}
</ha-md-menu-item>
</ha-md-menu>
`;
}
private async _handleAddTaskClick() {
const { title, interval_value, interval_type, last_performed, tag, icon, label } = this._formData;
if (!title?.trim() || !interval_value || !interval_type) {
const msg = localize("panel.cards.new.alerts.required", this.hass!.language);
alert(msg);
return;
}
const payload: Record<string, any> = {
title: title.trim(),
interval_value,
interval_type,
last_performed: this.computeISODate(last_performed),
tag_id: tag?.trim() || undefined,
icon: icon?.trim() || "mdi:calendar-check",
labels: label ?? [],
};
try {
await saveTask(this.hass!, payload);
await this.resetForm();
} catch (error) {
console.error("Failed to add task:", error);
const msg = localize('panel.cards.new.alerts.error', this.hass!.language)
alert(msg);
}
};
private async _handleCompleteTaskClick(id: string) {
try {
await completeTask(this.hass!, id);
await this.loadData();
} catch (e) {
console.error("Failed to complete task:", e);
}
}
private async _handleOpenEditDialogClick(id: string) {
try {
const task: Task = await loadTask(this.hass!, id);
this._editingTaskId = task.id;
let labels: Label[] = [];
const entity = this.registry.find((entry) => entry.unique_id === task.id);
if (entity)
labels = this.labelRegistry.filter((lr) => entity.labels.includes(lr.label_id));
this._editFormData = {
title: task.title,
interval_value: task.interval_value,
interval_type: task.interval_type,
last_performed: task.last_performed ?? "",
icon: task.icon ?? "",
label: labels.map((l) => l.label_id),
tag: task.tag_id ?? "",
};
await this.updateComplete;
} catch (e) {
console.error("Failed to fetch task for edit:", e);
}
}
private async _handleSaveEditClick() {
if (!this._editingTaskId) return;
const lastPerformedISO = this.computeISODate(this._editFormData.last_performed);
if (!lastPerformedISO) return;
const updates: Record<string, any> = {
title: this._editFormData.title.trim(),
interval_value: Number(this._editFormData.interval_value),
interval_type: this._editFormData.interval_type,
last_performed: lastPerformedISO,
icon: this._editFormData.icon?.trim() || "mdi:calendar-check",
labels: this._editFormData.label,
};
if (this._editFormData.tag && this._editFormData.tag.trim() !== "") {
updates.tag_id = this._editFormData.tag.trim();
} else {
updates.tag_id = null;
}
const payload = {
task_id: this._editingTaskId,
updates,
};
try {
await updateTask(this.hass!, payload);
this._editingTaskId = null;
await this.resetEditForm();
await this.loadData();
} catch (e) {
console.error("Failed to update task:", e);
}
}
private async _handleRemoveTaskClick(id: string) {
const msg = localize('panel.cards.current.confirm_remove', this.hass!.language)
if (!confirm(msg)) return;
try {
await removeTask(this.hass!, id);
await this.loadData();
} catch (e) {
console.error("Failed to remove task:", e);
}
}
private _handleDialogClosed(e: CustomEvent) {
const action = e.detail?.action;
if (action === "close" || action === "cancel") {
this._editingTaskId = null;
}
}
private _handleFormValueChanged(ev: CustomEvent) {
this._formData = { ...this._formData, ...ev.detail.value };
}
private _handleEditFormValueChanged(ev: CustomEvent) {
this._editFormData = { ...this._editFormData, ...ev.detail.value };
}
private _handleShowMenu(taskId: string, ev: Event) {
this._selectedTaskId = taskId;
if (!this._actionsMenu) {
return;
}
this._actionsMenu.anchorElement = ev.currentTarget as HTMLElement;
this._actionsMenu.show();
ev.stopPropagation();
} static styles = commonStyle;
}
customElements.define("home-maintenance-panel", HomeMaintenancePanel);