blob: 1498efdc530fb953bb612d0107a037d3405aa184 [file] [log] [blame]
Adrià Vilanova Martínez0d92a0c2023-11-06 01:37:20 +01001import {MDCTooltip} from '@material/tooltip';
2
3import {shouldImplement} from '../../../../common/commonUtils.js';
4import {createExtBadge} from '../../utils/common.js';
5
6export default class BaseExtraInfoInjection {
7 constructor(infoHandler, optionsWatcher) {
8 if (this.constructor == BaseExtraInfoInjection) {
9 throw new Error('The base class cannot be instantiated.');
10 }
11
12 this.infoHandler = infoHandler;
13 this.optionsWatcher = optionsWatcher;
14 }
15
16 /**
17 * Method which actually injects the extra information. It should be
18 * implemented by the extending class.
19 */
20 inject() {
21 shouldImplement('inject');
22 }
23
24 async isEnabled() {
25 return await this.optionsWatcher.isEnabled('extrainfo');
26 }
27
28 /**
29 * This is the method which should be called when injecting extra information.
30 */
31 async injectIfEnabled(injectionDetails) {
32 const isEnabled = await this.isEnabled();
33 if (!isEnabled) return;
34
35 return this.infoHandler.getCurrentInfo(injectionDetails)
36 .then(info => this.inject(info, injectionDetails))
37 .catch(err => {
38 console.error(
39 `${this.constructor.name}: error while injecting extra info: `,
40 err);
41 });
42 }
43
44 /**
45 * Add chips which contain |chipContentList| to |node|. If |withContainer| is
46 * set to true, a container will contain all the chips.
47 */
48 addExtraInfoChips(chipContentList, node, withContainer = false) {
49 if (chipContentList.length == 0) return;
50
51 let container;
52 if (withContainer) {
53 container = document.createElement('div');
54 container.classList.add('TWPT-extrainfo-container');
55 } else {
56 container = node;
57 }
58
59 let tooltips = [];
60
61 for (const content of chipContentList) {
62 const tooltip = this.addChipToContainer(content, container);
63 tooltips.push(tooltip);
64 }
65
66 if (withContainer) node.append(container);
67
68 for (const tooltip of tooltips) new MDCTooltip(tooltip);
69 }
70
71 /**
72 * Adds a chip to the container and returns a tooltip element to be
73 * instantiated.
74 */
75 addChipToContainer(chipContent, container) {
76 let chip = document.createElement('material-chip');
77 chip.classList.add('TWPT-extrainfo-chip');
78
79 let chipContentContainer = document.createElement('div');
80 chipContentContainer.classList.add('TWPT-chip-content-container');
81
82 let content = document.createElement('div');
83 content.classList.add('TWPT-content');
84
85 const [badge, badgeTooltip] = createExtBadge();
86
87 let span = document.createElement('span');
88 span.append(chipContent);
89
90 content.append(badge, span);
91 chipContentContainer.append(content);
92 chip.append(chipContentContainer);
93 container.append(chip);
94
95 return badgeTooltip;
96 }
97}