Andrew Krigline
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 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`. ![Image of the console showing renderPlayerList](https://i.imgur.com/rAkSIzr.png) 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>" ); }); ``` ![Image showing the button we just added.](https://i.imgur.com/puABjH2.png) :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>` ); ``` ![Image of the icon button](https://i.imgur.com/TB84Gkd.png) 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> ![Image of the styled button](https://i.imgur.com/3ErjFhE.png) ## 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. ![Image showing the Button Clicked log message.](https://i.imgur.com/k8Hspui.png) 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 %}

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully