# Starting the UI: HTML Injection
###### tags: `module-tutorial` `foundry-vtt`
## Planning the UI
Here's what we're hoping to end up with:
1. Add a button to the Player List entry for our user which when clicked, opens a window with all of our user's todos.
2. From that window, allow the user to create, edit, and delete ToDos.
## I. Finding the right Hook
Foundry has a system of [Hooks](https://foundryvtt.wiki/en/development/getting-started-with-development#is-there-a-list-of-hooks) which allow modules to safely interact with events in the Foundry ecosystem.
One such hook happens when any given UI element is rendered. We should toggle Hook debugging on and take a look to see if one for the Player List exists. With the Developer Mode module, this is as simple as opening the Dev Mode Settings and enabling CONFIG.debug overrides, and then the Hooks debug flag.
With this log on and the console open, click on the player list size toggle. Watch as we interact with the UI element that there is a hook fired: `renderPlayerList`.

We also see what arguments are being passed to the Hook as it's fired:
1. A `PlayerList` class - we're not very interested in this
2. Something that looks like an array of HTML elements - this is interesting to us
3. Some other object - not very interesting to us
#2 here is the element being painted on the page inside a jQuery wrapper. If we can change that element while the hook is running, we can change what is rendered on the page.
### How do we change the element?
Taking a look at the [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM) of the player list, we can see it's pretty basic. There's a heading and a list. The list has list items inside it, and each [list item](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li) has an [attribute](https://developer.mozilla.org/en-US/docs/Glossary/Attribute) (which looks like it's a custom [data attribute](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes)): `data-user-id` which looks like it records the ID of the user that list item represents.
We want to put a button on the player list item which corresponds to the logged in user, and we can use this `data-user-id` attribute to do so.
### Bringing it all together
Our goal is clear at this point:
1. Register a hook callback for `renderPlayerList`
2. Modify that second argument in the callback to include a button
3. Register a listener on that button to open a window
We'll have to come back to the whole "open a window" part, but we can at least get the button and listener working up front.
:::info
**Programming Concept: Event Listener**
An [event listener](https://developer.mozilla.org/en-US/docs/Web/API/EventListener) is a fancy way to say "piece of code that reacts to something happening." In most cases, this 'something' is a user input like a mouse click or typing into a form element.
:::
## II. Hooking into `renderPlayerList`
We're going to use the jQuery bundled with Foundry Core to make our lives a little easier. We're also going to use the FontAwesome icons bundled with Foundry Core to label our button instead of text. There's a `tasks` icon which would be perfect for this.
In the `todo-list.js` file, after the `ToDoList` class definition, add this:
```js=
Hooks.on('renderPlayerList', (playerList, html) => {
// find the element which has our logged in user's id
const loggedInUserListItem = html.find(`[data-user-id="${game.userId}"]`)
// insert a button at the end of this element
loggedInUserListItem.append(
"<button type='button' class='todo-list-icon-button'><i class='fas fa-tasks'></i></button>"
);
});
```

:partying-face:
## III. Adding a Localized Tooltip
We should add a tooltip on this button so people don't wonder what it is, and we should ensure this tooltip is localized.
### Add the title to our language file
Open up `languages/en.json` that we made a while ago and add a key to it: `button-title`.
```json=
{
"TODO-LIST": {
"button-title": "Open To-Do list"
}
}
```
### Apply localized string to button
Back in our `renderPlayerList` hook, we need to convert our button element string into a [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to make use of Foundry Core's built-in i18n methods.
```js=
// create localized tooltip
const tooltip = game.i18n.localize('TODOS.button-title');
// insert a button at the end of this element
loggedInUserListItem.append(
`<button type='button' class='todo-list-icon-button' title='${tooltip}'><i class='fas fa-tasks'></i></button>`
);
```
### Test!
Refresh and verify that when hovering over the button, the value we assigned in the languages file shows up.
> ***Narrator.*** It does not.
### Debugging Localization Problems
Instead of "Open To-Do list", we see the exact key we told Foundry to localize.
When this happens, it happens because Foundry Core can't find a key in its loaded localization files which matches. Most often, this is because of a typo; we should double check our JSON.
Our `button-title` key is nested within an object with the key `TODO-LIST`. We asked Foundry to find `TODOS.button-title`, instead of `TODO-LIST.button-title`, and that's why it failed.
Quick fix and test again.
```js=
const tooltip = game.i18n.localize('TODO-LIST.button-title');
```
That seems to have fixed it! Now to make things look pretty.
## III. Styling our Button
There's a lot of room for improvement on how our button looks right now.
### It's too large.
Inspecting the button, we can see that it's parent element has some classes applied to it, one of which is `flexrow`. This is a utility class in [Foundry Core's style.css](https://foundryvtt.wiki/en/development/guides/builtin-css) which turns the element into a [Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) row.
Looking at our injected button we can see that since it is a child of a `.flexrow` element, it gains the style rule: `flex: 1`. Without going into too much detail, this means the button will grow as much as it can in the space available.
We want the opposite, instead the button should never grow.
Luckily, there are some other utility classes in Foundry's style.css which we can use. Apply `flex0` to our button and refresh.
```js=
loggedInUserListItem.append(
`<button type='button' class='todo-list-icon-button flex0' title='${tooltip}'><i class='fas fa-tasks'></i></button>`
);
```

Better already. For the next steps, we'll need to open our own `styles/todo-list.css` file.
### Make it look... "better"
Getting caught up in the intricacies of CSS will only make this tutorial longer, so here's a CSS snippet that will make it look 'better'.
This works because we applied a class (`.todo-list-icon-button`) to our injected button.
```css=
.todo-list-icon-button {
background: transparent;
padding: 0;
color: white;
line-height: normal;
border: 0;
align-self: center;
}
.todo-list-icon-button > i {
margin-right: 0;
}
.todo-list-icon-button:hover, .todo-list-icon-button:focus {
box-shadow: none;
text-shadow: 0 0 5px red;
}
```
<details>
<summary>Summary of Changes</summary>
- Remove the background, border, and padding from the button
- Change the color of the button to be white
- Remove some defaults that apply to icons in buttons
- Improve the alignment of the button in the row
- Replace the hover and focus effects to be text-shadows instead of box-shadows
</details>

## IV. Add an event listener to our button
The last step with the button (for now) is to make it do _something._ We're not picky for now.
We will be using jQuery's [`on`](https://api.jquery.com/on/) method to make our lives easier here. Within the callback in the `renderPlayerList` hook, add this:
```js=
html.on('click', '.todo-list-icon-button', (event) => {
ToDoList.log(true, 'Button Clicked!');
});
```
Note I'm using the `log` helper we created during the optional step of Setting Up. If you chose not to do this step, you would instead do something with the default `console.log`.
With this in place, we can refresh and try clicking on the button while watching the console.

Perfect.
## V. Wrapping Up
In this section we...
- Learned about hooks and how to find them.
- Registered a Hook callback.
- Injected some HTML into a Core element with that Hook callback.
- Localized a string with Foundry Core's i18n implementation.
- Debugged why our localization string wasn't displaying properly.
- Styled our injected HTML with Foundry Core provided classes.
- Further styled our element with custom CSS in our stylesheet file.
- Added an event listener to make the button interactable.
<details>
<summary>Final renderPlayerList Hook</summary>
```js=
Hooks.on('renderPlayerList', (playerList, html) => {
// find the element which has our logged in user's id
const loggedInUserListItem = html.find(`[data-user-id="${game.userId}"]`)
// create localized tooltip
const tooltip = game.i18n.localize('TODO-LIST.button-title');
// insert a button at the end of this element
loggedInUserListItem.append(
`<button type='button' class='todo-list-icon-button flex0' title="${tooltip}">
<i class='fas fa-tasks'></i>
</button>`
);
// register an event listener for this button
html.on('click', '.todo-list-icon-button', (event) => {
ToDoList.log(true, 'Button Clicked!');
});
});
```
</details>
<details>
<summary>Final todo-list.css</summary>
```css=
.todo-list-icon-button {
background: transparent;
padding: 0;
color: white;
line-height: normal;
border: 0;
align-self: center;
}
.todo-list-icon-button > i {
margin-right: 0;
}
.todo-list-icon-button:hover, .todo-list-icon-button:focus {
box-shadow: none;
text-shadow: 0 0 5px red;
}
```
</details>
Next Step: [Making a FormApplication](/NBub2oFIT6yeh4NlOGTVFw)
{%hackmd io_aG7zdTKyRe3cpLcsxzw %}