commit 29a8575b08e754fd1754d383eeb7ca974069f74f Author: Gabriel Fontes Date: Tue Jun 8 20:24:50 2021 -0300 Initial commit Not actually initial, i'm just squashing everything as i had possibly sensitive data while the repo was private diff --git a/projects/website/.gitignore b/projects/website/.gitignore new file mode 100644 index 00000000..2ca86829 --- /dev/null +++ b/projects/website/.gitignore @@ -0,0 +1,4 @@ +_site/ +.sass-cache/ +.jekyll-cache/ +.jekyll-metadata diff --git a/projects/website/.well-known/openpgpkey/hu/cn8ync4xki49nnyu761y3ayofhshbj46 b/projects/website/.well-known/openpgpkey/hu/cn8ync4xki49nnyu761y3ayofhshbj46 new file mode 100644 index 00000000..de774863 Binary files /dev/null and b/projects/website/.well-known/openpgpkey/hu/cn8ync4xki49nnyu761y3ayofhshbj46 differ diff --git a/projects/website/.well-known/openpgpkey/policy b/projects/website/.well-known/openpgpkey/policy new file mode 100644 index 00000000..ff72a588 --- /dev/null +++ b/projects/website/.well-known/openpgpkey/policy @@ -0,0 +1 @@ +# Policy flags for domain misterio.me diff --git a/projects/website/404.md b/projects/website/404.md new file mode 100644 index 00000000..2823203b --- /dev/null +++ b/projects/website/404.md @@ -0,0 +1,6 @@ +--- +layout: default +title: 404 +--- +# 404 +Page not found. Try the [home](/). diff --git a/projects/website/CNAME b/projects/website/CNAME new file mode 100644 index 00000000..87c25588 --- /dev/null +++ b/projects/website/CNAME @@ -0,0 +1 @@ +misterio.me \ No newline at end of file diff --git a/projects/website/Gemfile b/projects/website/Gemfile new file mode 100644 index 00000000..4ad23493 --- /dev/null +++ b/projects/website/Gemfile @@ -0,0 +1,4 @@ +source "https://rubygems.org" + +gem "jekyll" +gem "webrick", "~> 1.7" diff --git a/projects/website/Gemfile.lock b/projects/website/Gemfile.lock new file mode 100644 index 00000000..121a27dc --- /dev/null +++ b/projects/website/Gemfile.lock @@ -0,0 +1,69 @@ +GEM + remote: https://rubygems.org/ + specs: + addressable (2.7.0) + public_suffix (>= 2.0.2, < 5.0) + colorator (1.1.0) + concurrent-ruby (1.1.9) + em-websocket (0.5.2) + eventmachine (>= 0.12.9) + http_parser.rb (~> 0.6.0) + eventmachine (1.2.7) + ffi (1.15.1) + forwardable-extended (2.6.0) + http_parser.rb (0.6.0) + i18n (1.8.10) + concurrent-ruby (~> 1.0) + jekyll (4.2.0) + addressable (~> 2.4) + colorator (~> 1.0) + em-websocket (~> 0.5) + i18n (~> 1.0) + jekyll-sass-converter (~> 2.0) + jekyll-watch (~> 2.0) + kramdown (~> 2.3) + kramdown-parser-gfm (~> 1.0) + liquid (~> 4.0) + mercenary (~> 0.4.0) + pathutil (~> 0.9) + rouge (~> 3.0) + safe_yaml (~> 1.0) + terminal-table (~> 2.0) + jekyll-sass-converter (2.1.0) + sassc (> 2.0.1, < 3.0) + jekyll-watch (2.2.1) + listen (~> 3.0) + kramdown (2.3.1) + rexml + kramdown-parser-gfm (1.1.0) + kramdown (~> 2.0) + liquid (4.0.3) + listen (3.5.1) + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) + mercenary (0.4.0) + pathutil (0.16.2) + forwardable-extended (~> 2.6) + public_suffix (4.0.6) + rb-fsevent (0.11.0) + rb-inotify (0.10.1) + ffi (~> 1.0) + rexml (3.2.5) + rouge (3.26.0) + safe_yaml (1.0.5) + sassc (2.4.0) + ffi (~> 1.9) + terminal-table (2.0.0) + unicode-display_width (~> 1.1, >= 1.1.1) + unicode-display_width (1.7.0) + webrick (1.7.0) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + jekyll + webrick (~> 1.7) + +BUNDLED WITH + 2.2.19 diff --git a/projects/website/LICENSE b/projects/website/LICENSE new file mode 100644 index 00000000..5cfa9b7c --- /dev/null +++ b/projects/website/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Gabriel Fontes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/projects/website/README.md b/projects/website/README.md new file mode 100644 index 00000000..ea6520ba --- /dev/null +++ b/projects/website/README.md @@ -0,0 +1,3 @@ +# misterio.me + +My personal website. For now just a static water.css (with some cool interactive js). SSR with rocket and tera coming soon. diff --git a/projects/website/_config.yml b/projects/website/_config.yml new file mode 100644 index 00000000..68730c99 --- /dev/null +++ b/projects/website/_config.yml @@ -0,0 +1 @@ +include: [".well-known"] diff --git a/projects/website/_data/navigation.yml b/projects/website/_data/navigation.yml new file mode 100644 index 00000000..ab24ff01 --- /dev/null +++ b/projects/website/_data/navigation.yml @@ -0,0 +1,4 @@ +- name: about + link: / +- name: blog + link: /blog.html diff --git a/projects/website/_includes/footer.html b/projects/website/_includes/footer.html new file mode 100644 index 00000000..db7d9369 --- /dev/null +++ b/projects/website/_includes/footer.html @@ -0,0 +1,24 @@ + diff --git a/projects/website/_includes/nav.html b/projects/website/_includes/nav.html new file mode 100644 index 00000000..b9d83757 --- /dev/null +++ b/projects/website/_includes/nav.html @@ -0,0 +1,29 @@ + diff --git a/projects/website/_includes/scheme-datalist.html b/projects/website/_includes/scheme-datalist.html new file mode 100644 index 00000000..f41fab5f --- /dev/null +++ b/projects/website/_includes/scheme-datalist.html @@ -0,0 +1,188 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/projects/website/_includes/scheme-dialog.html b/projects/website/_includes/scheme-dialog.html new file mode 100644 index 00000000..fb2b61a7 --- /dev/null +++ b/projects/website/_includes/scheme-dialog.html @@ -0,0 +1,64 @@ + +
+ +

Color scheme

+
+
+
+ + + + {% include scheme-datalist.html %} +
+
+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+

█

+
+

+ Powered by + flavours +

+ +
+
diff --git a/projects/website/_layouts/default.html b/projects/website/_layouts/default.html new file mode 100644 index 00000000..01860bb8 --- /dev/null +++ b/projects/website/_layouts/default.html @@ -0,0 +1,71 @@ + + + + + + Gabriel Fontes | {{ page.title }} + + + + + + + + + + + + + + + + + + + + + + + + + +
+ {% include nav.html %} {% include scheme-dialog.html %} +
{{ content }}
+ {% include footer.html %} + + + + + + diff --git a/projects/website/_layouts/post.html b/projects/website/_layouts/post.html new file mode 100644 index 00000000..fdcc889f --- /dev/null +++ b/projects/website/_layouts/post.html @@ -0,0 +1,7 @@ +--- +layout: default +--- +

{{ page.title }}

+

{{ page.date | date_to_string }} - {{ page.author }}

+ +{{ content }} diff --git a/projects/website/_posts/2021-06-08-hello-world.md b/projects/website/_posts/2021-06-08-hello-world.md new file mode 100644 index 00000000..17307f0c --- /dev/null +++ b/projects/website/_posts/2021-06-08-hello-world.md @@ -0,0 +1,167 @@ +--- +layout: post +author: Gabriel Fontes +--- + +Here's a writeup on how i made this website + +I've been wanting to get into blogging random tech rants, maybe something useful too. Guides, maybe? + +Well, i kept putting this off for quite a while, as i just couldn't decide which way to build it. I've considered the big frameworks, server side rendering, handwritting static assets, all the stuff. + +Okay. So (as you can see) i got it done and i'm writing my first blog entry, about the blog itself. + +How did i build it? + + +## Semantic HTML and 170+ CSS schemes +I decided to start building the [about page](/) as a purely static page. I was looking for a good and pure CSS library i could use, as to keep the site as simple and lightweight as possible, considering i don't need any dynamic content. + +First, i'm not a huge fan of utility CSS or heavily class based HTML. In my opinion, HTML should have as much semantic meaning as possible, and not be concerned with how a CSS sheet does the styling. I also love markdown, and i like having a 1:1 conversion from it to HTML, without having to add stuff. Blogging in markdown was big on the site wishlist. + +Second, although they might be useful (specially when CSS did not support variables), i prefer to use CSS variables (root level custom properties) instead of preprocessors such as sass. + +My reason for this is my aim of using [base16](https://github.com/chriskempson/base16) schemes to dynamically theme my website (170+ themes!) in a lazy way. That is, only loading any specific scheme on demand. Using a preprocessor would end up in generating full CSS sheets for each scheme option, which is not very bandwidth effective. + +There's a plethora of different ways to offer schemes to a user. I did by factoring out all colors on my base CSS sheet to variables, and using [flavours](https://github.com/misterio77/flavours) to generate a CSS sheet (with just the 16 color variables) for each scheme. These can be selected using a `input` field, and will set the `link` tag's `href` value to the scheme, overwriting the default two schemes (one light and one dark, for `prefers-color-scheme: dark`) i specified on the base sheet. + +With that done, i also set a tiny `localStorage` key to the browser, so the scheme preference can be persisted across visits. + +Here's a code snippet: +```js +let chosen_scheme_css = document.getElementById("chosen-scheme"); + +// Set a given scheme +function setTheme(scheme) { +chosen_scheme_css.setAttribute( + "href", + "/assets/schemes/" + scheme + ".css" +); +localStorage.setItem("current-scheme", scheme); +} +// Reset scheme to defaults (rose-pine moon or dawn, depending on preference) +function resetTheme() { +chosen_scheme_css.removeAttribute("href"); +localStorage.removeItem("current-scheme"); +} + +// Get stored scheme from localStorage and reapply it +let stored_scheme = localStorage.getItem("current-scheme"); +if (stored_scheme) { +setTheme(stored_scheme); +} +``` + +This seems to me a very simple and clean way of doing it, without introducing complicated JS libraries to the equation. The colors even fade based on `animation` CSS property! + +## A simple CSS styling + +With that in mind, i set out to search for a minimal and semantic CSS sheet, preferably one using CSS variables. + +Checking a few lists, i found [water.css](https://watercss.kognise.dev/), and it ticked all the boxes. It looks absolutely beautiful and is pure CSS. + +All i had to do get my theming working was three `link` elements, which import, in order: +- Water.css +- My own sheet, which maps base0x variables to water.css ones, and provides two default schemes +- The user defined color scheme, once set (has an empty href by default) + +## Code reuse and markdown pages + +Okay, that's good enough for a personal website with a single page. But what if i want other pages with the same common elements, such as the navbar, the scheme dialog, footer... We would have to duplicate everything, ending up in (a lot of) duplicated HTML code, and a lot of pain to make changes in all of them at once. + +Fetching content at runtime from a full fledged server little overkill for a blog that i update once in a blue moon. When we don't need user generated data, manipulating the website at compile time makes a lot more sense. Enter Static Site Generation, or SSG. + +Again, another problem of complete solutions is flexibility. I already have my styling and structure set, i just wanted a simple tool to factor out duplicated code. I stumbled upon [Jekyll](https://jekyllrb.com/) and its simplistic and modular goodness. + +Jekyll is very straightforward and doesn't force you to change everything to support it. It works with templating (liquid) and markdown rendering. You can factor out common stuff from your website into includes (that work kinda like componentes) or layouts. All of this gets built into static assets, it doesn't get in your way and works great. + +## Automating style building + +One of (the most useful, i think) my little projects is called [flavours](https://github.com/misterio77/flavours). It's a unixy CLI tool that downloads and builds color schemes and templates that follow the [base16](https://github.com/chriskempson/base16) standard. + +It's mostly built for people that use heavily customizable desktop programs (terminals, window managers, status bars, etc). The ideia is setting up just once, and them instantly theming your entire setup with any base16 scheme, by replacing delimiters inside text configuration files (people call them dots). Schemes are really easy to make (flavours can even generate them from images, usually wallpapers), so this allows the power of infinite color schemes on a desktop. + +It also works as a standard [base16 builder](https://github.com/chriskempson/base16/blob/master/builder.md), replacing scheme variables inside templates and outputting them. There's a CSS variables template, so it's really easy to generate a CSS sheet for hundreds of different schemes. Here's how that template looks: +{% raw %} +```css +/* {{scheme-name}} by {{scheme-author}} */ +:root { + --base00: #{{base00-hex}}; + --base01: #{{base01-hex}}; + --base02: #{{base02-hex}}; + --base03: #{{base03-hex}}; + --base04: #{{base04-hex}}; + --base05: #{{base05-hex}}; + --base06: #{{base06-hex}}; + --base07: #{{base07-hex}}; + --base08: #{{base08-hex}}; + --base09: #{{base09-hex}}; + --base0A: #{{base0A-hex}}; + --base0B: #{{base0B-hex}}; + --base0C: #{{base0C-hex}}; + --base0D: #{{base0D-hex}}; + --base0E: #{{base0E-hex}}; + --base0F: #{{base0F-hex}}; +} +``` +{% endraw %} +Pretty simple, huh? The spec provides those placeholders, which can be used in virtually any kind of file that specifies colors. + +Here's how it looks with a color scheme (`pasque`) applied: +```css +/* Pasque by Gabriel Fontes (https://github.com/Misterio77) */ +:root { + --base00: #271C3A; + --base01: #100323; + --base02: #3E2D5C; + --base03: #5D5766; + --base04: #BEBCBF; + --base05: #DEDCDF; + --base06: #EDEAEF; + --base07: #BBAADD; + --base08: #A92258; + --base09: #918889; + --base0A: #804ead; + --base0B: #C6914B; + --base0C: #7263AA; + --base0D: #8E7DC6; + --base0E: #953B9D; + --base0F: #59325C; +} +``` + +So, how do we generate one for every existing scheme? Additionally, there's a HTML tag `datalist` that allows for suggestions on an `input` form element. Maybe we can build one so the user knows which schemes are available? + +Of course. flavours allows for great scriptability, so just use a bash script: +```bash +datalist_file="_includes/scheme-datalist.html" +template_path=~/.local/share/flavours/base16/templates/styles/templates/css-variables.mustache + +# Add datalist opening tag +echo -n "" > $datalist_file +# For each scheme +flavours list -l | while read slug; do + # Get scheme file path + scheme_path=$(flavours info $slug | head -1 | cut -d '@' -f2) + # Build scheme + flavours build $scheme_path $template_path > assets/schemes/$slug.css + # Add entry to datalist + echo -n "" >> $datalist_file +done +# Add datalist closing tag +echo "" >> $datalist_file +``` + +This script basically uses `flavours list` to get a list of all installed schemes and iterates over them. For each scheme, we build the `css-variables` template with it, outputting to the assets directory, and add its slug to the file with ``. + + +## Wrapping up + +Okay, this was my first blog entry, and that's how my simpl(ish) and minimalist site works. Feel free to check the [source code](https://github.com/misterio77/misterio-me) to learn more, or grab something for your own use (everything's MIT licensed). + +Here's a few links to the stuff i used: +- [water.css](https://github.com/kognise/water.css) (base CSS styling) +- [prism.js](https://github.com/PrismJS/prism/) (code highlighting library) +- [jekyll](https://jekyllrb.com/) (static page generator) +- [base16](https://github.com/chriskempson/base16) (color theme spec) +- [flavours](https://github.com/misterio77/flavours) (base16 builder) diff --git a/projects/website/assets/imports/polyfills/datalist.js b/projects/website/assets/imports/polyfills/datalist.js new file mode 100644 index 00000000..6b93844b --- /dev/null +++ b/projects/website/assets/imports/polyfills/datalist.js @@ -0,0 +1,701 @@ +/* + * Datalist polyfill - https://github.com/mfranzke/datalist-polyfill + * @license Copyright(c) 2017 by Maximilian Franzke + * Supported by Christian, Johannes, @mitchhentges, @mertenhanisch, @ailintom, @Kravimir, @mischah, @hryamzik, @ottoville, @IceCreamYou, @wlekin, @eddr, @beebee1987, @mricherzhagen, @acespace90, @damien-git, @nexces, @Sora2455, @jscho13, @alexirion and @vinyfc93 - many thanks for that ! + */ +/* + * A minimal and dependency-free vanilla JavaScript datalist polyfill. + * Supports all standard's functionality as well as mimics other browsers behavior. + * Tests for native support of an inputs elements datalist functionality. + * Elsewhere the functionality gets emulated by a select element. + */ + +(function () { + 'use strict'; + + // Performance: Set local variables + var dcmnt = window.document, + ua = window.navigator.userAgent, + // Feature detection + datalistSupported = + 'list' in dcmnt.createElement('input') && + Boolean(dcmnt.createElement('datalist') && window.HTMLDataListElement), + // IE & EDGE browser detection via UserAgent + // TODO: obviously ugly. But sadly necessary until Microsoft enhances the UX within EDGE (compare to https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9573654/) + // Tested against the following UA strings: http://useragentstring.com/pages/useragentstring.php?name=Internet+Explorer + // And adapted out of https://gist.github.com/gaboratorium/25f08b76eb82b1e7b91b01a0448f8b1d : + isGteIE10 = Boolean(ua.match(/MSIE\s1[01]./) || ua.match(/rv:11./)), + isEDGE = Boolean(ua.indexOf('Edge/') !== -1); + + // Let's break here, if it's even already supported ... and not IE10+ or EDGE + if (datalistSupported && !isGteIE10 && !isEDGE) { + return false; + } + + // .matches polyfill + // TODO: probably needs enhancement on the expected to be supported browsers + if (!Element.prototype.matches) { + Element.prototype.matches = Element.prototype.msMatchesSelector; + } + + // Define some global settings and configurations + var touched = false, + // Speaking variables for the different keycodes + keyENTER = 13, + keyESC = 27, + keyUP = 38, + keyDOWN = 40, + // Defining the text / value seperator for displaying the value and text values ... + textValueSeperator = ' / ', + // ... and defining the different input types that are supported by this polyfill + supportedTypes = ['text', 'email', 'number', 'search', 'tel', 'url'], + // Classes for elements + classNameInput = 'polyfilled', + classNamePolyfillingSelect = 'polyfilling', + // Defining a most likely unique polyfill string + uniquePolyfillString = '###[P0LYFlLLed]###'; + + // Differentiate for touch interactions, adapted by https://medium.com/@david.gilbertson/the-only-way-to-detect-touch-with-javascript-7791a3346685 + window.addEventListener('touchstart', function onFirstTouch() { + touched = true; + + window.removeEventListener('touchstart', onFirstTouch); + }); + + // For observing any changes to the option elements within the datalist elements, define MutationObserver initially + var MutationObserver = + window.MutationObserver || window.WebKitMutationObserver, + obs; + + // Define a new observer + if (typeof MutationObserver !== 'undefined') { + obs = new MutationObserver(function (mutations) { + var datalistNeedsAnUpdate = false; + + // Look through all mutations that just occured + mutations.forEach(function (mutation) { + // Check if any of the mutated nodes was a datalist + if ( + mutation.target instanceof HTMLElement && + mutation.target.tagName.toLowerCase() === 'datalist' && + mutation.addedNodes.length > 1 + ) { + datalistNeedsAnUpdate = mutation.target; + } + }); + + if (datalistNeedsAnUpdate) { + var input = dcmnt.querySelector( + 'input[list="' + datalistNeedsAnUpdate.id + '"]' + ); + + if (getInputValue(input) !== '') { + // Prepare the options and toggle the visiblity afterwards + toggleVisibility( + prepOptions(datalistNeedsAnUpdate, input).length, + datalistNeedsAnUpdate.getElementsByClassName( + classNamePolyfillingSelect + )[0] + ); + } + } + }); + } + + // Function regarding the inputs interactions on keyup event + var inputInputList = function (event) { + var input = event.target, + datalist = input.list, + keyOpen = event.keyCode === keyUP || event.keyCode === keyDOWN; + + // Check for whether the events target was an input and still check for an existing instance of the datalist and polyfilling select + if (input.tagName.toLowerCase() !== 'input' || datalist === null) { + return; + } + + // Handling IE10+ & EDGE + if (isGteIE10 || isEDGE) { + // On keypress check for value + if ( + getInputValue(input) !== '' && + !keyOpen && + event.keyCode !== keyENTER && + event.keyCode !== keyESC && + // As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here + (isGteIE10 || input.type === 'text') + ) { + updateIEOptions(input, datalist); + + // TODO: Check whether this update is necessary depending on the options values + input.focus(); + } + + return; + } + + var visible = false, + // Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted) + datalistSelect = + datalist.getElementsByClassName(classNamePolyfillingSelect)[0] || + setUpPolyfillingSelect(input, datalist); + + // On an ESC or ENTER key press within the input, let's break here and afterwards hide the datalist select, but if the input contains a value or one of the opening keys have been pressed ... + if ( + event.keyCode !== keyESC && + event.keyCode !== keyENTER && + (getInputValue(input) !== '' || keyOpen) && + datalistSelect !== undefined + ) { + // ... prepare the options + if (prepOptions(datalist, input).length > 0) { + visible = true; + } + + var firstEntry = 0, + lastEntry = datalistSelect.options.length - 1; + + // ... preselect best fitting index + if (touched) { + datalistSelect.selectedIndex = firstEntry; + } else if (keyOpen && input.getAttribute('type') !== 'number') { + datalistSelect.selectedIndex = + event.keyCode === keyUP ? lastEntry : firstEntry; + + // ... and on arrow up or down keys, focus the select + datalistSelect.focus(); + } + } + + // Toggle the visibility of the datalist select according to previous checks + toggleVisibility(visible, datalistSelect); + }; + + // On keypress check all options for that as a substring, save the original value as a data-attribute and preset that inputs value (for sorting) for all option values (probably as well enhanced by a token) + var updateIEOptions = function (input, datalist) { + var inputValue = getInputValue(input); + + // Loop through the options + Array.prototype.slice.call(datalist.options, 0).forEach(function (option) { + // We're using .getAttribute instead of .dataset here for IE10- + var dataOriginalvalue = option.getAttribute('data-originalvalue'), + originalValue = dataOriginalvalue || option.value; + + // In case of that the original value hasn't been saved as data so far, do that now + if (!dataOriginalvalue) { + // We're using .setAttribute instead of .dataset here for IE10- + option.setAttribute('data-originalvalue', originalValue); + } + + // As we'd manipulate the value in the next step, we'd like to put in that value as either a label or text if none of those exist + if (!option.label && !option.text) { + option.label = originalValue; + } + + /* As mentioned in the discussion within #GH-63: + Check for whether the current option is a valid suggestion and replace its value by + - the current input string, as IE10+ and EDGE don't do substring, but only prefix matching (#GH-36, #GH-39) + - followed by a unique string that should prevent any interferance + - and the original string, that is still necessary e.g. for sorting within the suggestions list + As the value is being inserted on users selection, we'll replace that one within the upfollowing inputInputListIE function + */ + option.value = isValidSuggestion(option, inputValue) + ? inputValue + uniquePolyfillString + originalValue.toLowerCase() + : originalValue; + }); + }; + + // Check for the input and probably replace by correct options elements value + var inputInputListIE = function (event) { + var input = event.target, + datalist = input.list; + + if ( + !input.matches('input[list]') || + !input.matches('.' + classNameInput) || + !datalist + ) { + return; + } + + // Query for related option - and escaping the value as doublequotes wouldn't work + var option = datalist.querySelector( + 'option[value="' + + getInputValue(input).replace(/\\([\s\S])|(")/g, '\\$1$2') + + '"]' + ); + + // We're using .getAttribute instead of .dataset here for IE10- + if (option && option.getAttribute('data-originalvalue')) { + setInputValue(input, option.getAttribute('data-originalvalue')); + } + }; + + // Check for whether this is a valid suggestion + var isValidSuggestion = function (option, inputValue) { + var optValue = option.value.toLowerCase(), + inptValue = inputValue.toLowerCase(), + label = option.getAttribute('label'), + text = option.text.toLowerCase(); + + /* + "Each option element that is a descendant of the datalist element, that is not disabled, and whose value is a string that isn't the empty string, represents a suggestion. Each suggestion has a value and a label." + "If appropriate, the user agent should use the suggestion's label and value to identify the suggestion to the user." + */ + return Boolean( + option.disabled === false && + ((optValue !== '' && optValue.indexOf(inptValue) !== -1) || + (label && label.toLowerCase().indexOf(inptValue) !== -1) || + (text !== '' && text.indexOf(inptValue) !== -1)) + ); + }; + + // Focusin and -out events + var changesInputList = function (event) { + // Check for correct element on this event delegation + if (!event.target.matches('input[list]')) { + return; + } + + var input = event.target, + datalist = input.list; + + // Check for whether the events target was an input and still check for an existing instance of the datalist + if (input.tagName.toLowerCase() !== 'input' || datalist === null) { + return; + } + + // Test for whether this input has already been enhanced by the polyfill + if (!input.matches('.' + classNameInput)) { + prepareInput(input, event.type); + } + + // #GH-49: Microsoft EDGE / datalist popups get "emptied" when receiving focus via tabbing + if (isEDGE && event.type === 'focusin') { + // Set the value of the first option to it's value - this actually triggers a redraw of the complete list + var firstOption = input.list.options[0]; + + firstOption.value = firstOption.value; + } + + // Break here for IE10+ & EDGE + if (isGteIE10 || isEDGE) { + return; + } + + var // Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted) + datalistSelect = + datalist.getElementsByClassName(classNamePolyfillingSelect)[0] || + setUpPolyfillingSelect(input, datalist), + // Either have the select set to the state to get displayed in case of that it would have been focused or because it's the target on the inputs blur - and check for general existance of any option as suggestions + visible = + datalistSelect && + datalistSelect.querySelector('option:not(:disabled)') && + ((event.type === 'focusin' && getInputValue(input) !== '') || + (event.relatedTarget && event.relatedTarget === datalistSelect)); + + // Toggle the visibility of the datalist select according to previous checks + toggleVisibility(visible, datalistSelect); + }; + + // Prepare the input + var prepareInput = function (input, eventType) { + // We'd like to prevent autocomplete on the input datalist field + input.setAttribute('autocomplete', 'off'); + + // WAI ARIA attributes + input.setAttribute('role', 'textbox'); + input.setAttribute('aria-haspopup', 'true'); + input.setAttribute('aria-autocomplete', 'list'); + input.setAttribute('aria-owns', input.getAttribute('list')); + + // Bind the keyup event on the related datalists input + if (eventType === 'focusin') { + input.addEventListener('keyup', inputInputList); + + input.addEventListener('focusout', changesInputList, true); + + // As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here + if (isGteIE10 || (isEDGE && input.type === 'text')) { + input.addEventListener('input', inputInputListIE); + } + } else if (eventType === 'blur') { + input.removeEventListener('keyup', inputInputList); + + input.removeEventListener('focusout', changesInputList, true); + + // As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here + if (isGteIE10 || (isEDGE && input.type === 'text')) { + input.removeEventListener('input', inputInputListIE); + } + } + + // Add class for identifying that this input is even already being polyfilled + input.className += ' ' + classNameInput; + }; + + // Get the input value for dividing regular and mail types + var getInputValue = function (input) { + // In case of type=email and multiple attribute, we would need to grab the last piece + // Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly + return input.getAttribute('type') === 'email' && + input.getAttribute('multiple') !== null + ? input.value.slice(Math.max(0, input.value.lastIndexOf(',') + 1)) + : input.value; + }; + + // Set the input value for dividing regular and mail types + var setInputValue = function (input, datalistSelectValue) { + var lastSeperator; + + // In case of type=email and multiple attribute, we need to set up the resulting inputs value differently + input.value = + // Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly + input.getAttribute('type') === 'email' && + input.getAttribute('multiple') !== null && + (lastSeperator = input.value.lastIndexOf(',')) > -1 + ? input.value.slice(0, lastSeperator) + ',' + datalistSelectValue + : datalistSelectValue; + }; + + // Binding the focus event - matching the input[list]s happens in the function afterwards + dcmnt.addEventListener('focusin', changesInputList, true); + + // Break here for IE10+ & EDGE + if (isGteIE10 || isEDGE) { + return; + } + + // Function for preparing and sorting the options/suggestions + var prepOptions = function (datalist, input) { + if (typeof obs !== 'undefined') { + obs.disconnect(); + } + + var // Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted) + datalistSelect = + datalist.getElementsByClassName(classNamePolyfillingSelect)[0] || + setUpPolyfillingSelect(input, datalist), + inputValue = getInputValue(input), + newSelectValues = dcmnt.createDocumentFragment(), + disabledValues = dcmnt.createDocumentFragment(); + + // Create an array out of the options list + Array.prototype.slice + .call(datalist.querySelectorAll('option:not(:disabled)')) + // ... sort all entries and + .sort(function (a, b) { + var aValue = a.value, + bValue = b.value; + + // Using the knowledge that the values are URLs to allow the user to omit the scheme part and perform intelligent matching on the domain name + if (input.getAttribute('type') === 'url') { + aValue = aValue.replace(/(^\w+:|^)\/\//, ''); + bValue = bValue.replace(/(^\w+:|^)\/\//, ''); + } + + return aValue.localeCompare(bValue); + }) + .forEach(function (opt) { + var optionValue = opt.value, + label = opt.getAttribute('label'), + text = opt.text; + + // Put this option into the fragment that is meant to get inserted into the select. Additionally according to the specs ... + // TODO: This might get slightly changed/optimized in a future release + if (isValidSuggestion(opt, inputValue)) { + var textOptionPart = text.slice( + 0, + optionValue.length + textValueSeperator.length + ), + optionPart = optionValue + textValueSeperator; + + // The innertext should be 'value seperator text' in case they are different + if ( + text && + !label && + text !== optionValue && + textOptionPart !== optionPart + ) { + opt.textContent = optionValue + textValueSeperator + text; + } else if (!opt.text) { + // Manipulating the option inner text, that would get displayed + opt.textContent = label || optionValue; + } + + newSelectValues.appendChild(opt); + } else { + // ... or put this option that isn't relevant to the users into the fragment that is supposed to get inserted outside of the select + disabledValues.appendChild(opt); + } + }); + + // Input the options fragment into the datalists select + datalistSelect.appendChild(newSelectValues); + + var datalistSelectOptionsLength = datalistSelect.options.length; + + datalistSelect.size = + datalistSelectOptionsLength > 10 ? 10 : datalistSelectOptionsLength; + datalistSelect.multiple = !touched && datalistSelectOptionsLength < 2; + + // Input the unused options as siblings next to the select - and differentiate in between the regular, and the IE9 fix syntax upfront + (datalist.getElementsByClassName('ie9_fix')[0] || datalist).appendChild( + disabledValues + ); + + if (typeof obs !== 'undefined') { + obs.observe(datalist, { + childList: true, + }); + } + + return datalistSelect.options; + }; + + // Define function for setting up the polyfilling select + var setUpPolyfillingSelect = function (input, datalist) { + // Check for whether it's of one of the supported input types defined at the beginning + // Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly + // and still check for an existing instance + if ( + (input.getAttribute('type') && + supportedTypes.indexOf(input.getAttribute('type')) === -1) || + datalist === null + ) { + return; + } + + var rects = input.getClientRects(), + // Measurements + inputStyles = window.getComputedStyle(input), + datalistSelect = dcmnt.createElement('select'); + + // Setting a class for easier identifying that select afterwards + datalistSelect.setAttribute('class', classNamePolyfillingSelect); + + // Set general styling related definitions + datalistSelect.style.position = 'absolute'; + + // Initially hiding the datalist select + toggleVisibility(false, datalistSelect); + + // The select itself shouldn't be a possible target for tabbing + datalistSelect.setAttribute('tabindex', '-1'); + + // WAI ARIA attributes + datalistSelect.setAttribute('aria-live', 'polite'); + datalistSelect.setAttribute('role', 'listbox'); + if (!touched) { + datalistSelect.setAttribute('aria-multiselectable', 'false'); + } + + // The select should get positioned underneath the input field ... + if (inputStyles.getPropertyValue('display') === 'block') { + datalistSelect.style.marginTop = + '-' + inputStyles.getPropertyValue('margin-bottom'); + } else { + var direction = + inputStyles.getPropertyValue('direction') === 'rtl' ? 'right' : 'left'; + + datalistSelect.style.setProperty( + 'margin-' + direction, + '-' + + (rects[0].width + + parseFloat(inputStyles.getPropertyValue('margin-' + direction))) + + 'px' + ); + datalistSelect.style.marginTop = + parseInt(rects[0].height + (input.offsetTop - datalist.offsetTop), 10) + + 'px'; + } + + // Set the polyfilling selects border-radius equally to the one by the polyfilled input + datalistSelect.style.borderRadius = inputStyles.getPropertyValue( + 'border-radius' + ); + datalistSelect.style.minWidth = rects[0].width + 'px'; + + if (touched) { + var messageElement = dcmnt.createElement('option'); + + // ... and it's first entry should contain the localized message to select an entry + messageElement.textContent = datalist.title; + // ... and disable this option, as it shouldn't get selected by the user + messageElement.disabled = true; + // ... and assign a dividable class to it + messageElement.setAttribute('class', 'message'); + // ... and finally insert it into the select + datalistSelect.appendChild(messageElement); + } + + // Add select to datalist element ... + datalist.appendChild(datalistSelect); + + // ... and our upfollowing functions to the related event + if (touched) { + datalistSelect.addEventListener('change', changeDataListSelect); + } else { + datalistSelect.addEventListener('click', changeDataListSelect); + } + + datalistSelect.addEventListener('blur', changeDataListSelect); + datalistSelect.addEventListener('keydown', changeDataListSelect); + datalistSelect.addEventListener('keypress', datalistSelectKeyPress); + + return datalistSelect; + }; + + // Functions regarding changes to the datalist polyfilling created selects keypress + var datalistSelectKeyPress = function (event) { + var datalistSelect = event.target, + datalist = datalistSelect.parentNode, + input = dcmnt.querySelector('input[list="' + datalist.id + '"]'); + + // Check for whether the events target was a select or whether the input doesn't exist + if (datalistSelect.tagName.toLowerCase() !== 'select' || input === null) { + return; + } + + // Determine a relevant key - either printable characters (that would have a length of 1) or controlling like Backspace + if (event.key && (event.key === 'Backspace' || event.key.length === 1)) { + input.focus(); + + if (event.key === 'Backspace') { + input.value = input.value.slice(0, -1); + + // Dispatch the input event on the related input[list] + dispatchInputEvent(input); + } else { + input.value += event.key; + } + + prepOptions(datalist, input); + } + }; + + // Change, Click, Blur, Keydown + var changeDataListSelect = function (event) { + var datalistSelect = event.currentTarget, + datalist = datalistSelect.parentNode, + input = dcmnt.querySelector('input[list="' + datalist.id + '"]'); + + // Check for whether the events target was a select or whether the input doesn't exist + if (datalistSelect.tagName.toLowerCase() !== 'select' || input === null) { + return; + } + + var eventType = event.type, + // ENTER and ESC + visible = + eventType === 'keydown' && + event.keyCode !== keyENTER && + event.keyCode !== keyESC; + + // On change, click or after pressing ENTER or TAB key, input the selects value into the input on a change within the list + if ( + (eventType === 'change' || + eventType === 'click' || + (eventType === 'keydown' && + (event.keyCode === keyENTER || event.key === 'Tab'))) && + datalistSelect.value.length > 0 && + datalistSelect.value !== datalist.title + ) { + setInputValue(input, datalistSelect.value); + + // Dispatch the input event on the related input[list] + dispatchInputEvent(input); + + // Finally focusing the input, as other browser do this as well + if (event.key !== 'Tab') { + input.focus(); + } + + // #GH-51 / Prevent the form to be submitted on selecting a value via ENTER key within the select + if (event.keyCode === keyENTER) { + event.preventDefault(); + } + + // Set the visibility to false afterwards, as we're done here + visible = false; + } else if (eventType === 'keydown' && event.keyCode === keyESC) { + // In case of the ESC key being pressed, we still want to focus the input[list] + input.focus(); + } + + // Toggle the visibility of the datalist select according to previous checks + toggleVisibility(visible, datalistSelect); + }; + + // Create and dispatch the input event; divided for IE9 usage + var dispatchInputEvent = function (input) { + var evt; + + if (typeof Event === 'function') { + evt = new Event('input', { + bubbles: true, + }); + } else { + evt = dcmnt.createEvent('Event'); + evt.initEvent('input', true, false); + } + + input.dispatchEvent(evt); + }; + + // Toggle the visibility of the datalist select + var toggleVisibility = function (visible, datalistSelect) { + if (visible) { + datalistSelect.removeAttribute('hidden'); + } else { + datalistSelect.setAttributeNode(dcmnt.createAttribute('hidden')); + } + + datalistSelect.setAttribute('aria-hidden', (!visible).toString()); + }; + + // Emulate the two properties regarding the datalist and input elements + // list property / https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement + (function (constructor) { + if ( + constructor && + constructor.prototype && + constructor.prototype.list === undefined + ) { + Object.defineProperty(constructor.prototype, 'list', { + get: function () { + /* + According to the specs ... + "The list IDL attribute must return the current suggestions source element, if any, or null otherwise." + "If there is no list attribute, or if there is no element with that ID, or if the first element with that ID is not a datalist element, then there is no suggestions source element." + */ + var element = dcmnt.getElementById(this.getAttribute('list')); + + return typeof this === 'object' && + this instanceof constructor && + element && + element.matches('datalist') + ? element + : null; + }, + }); + } + })(window.HTMLInputElement); + + // Options property / https://developer.mozilla.org/en/docs/Web/API/HTMLDataListElement + (function (constructor) { + if ( + constructor && + constructor.prototype && + constructor.prototype.options === undefined + ) { + Object.defineProperty(constructor.prototype, 'options', { + get: function () { + return typeof this === 'object' && this instanceof constructor + ? this.getElementsByTagName('option') + : null; + }, + }); + } + })(window.HTMLElement); +})(); + diff --git a/projects/website/assets/imports/polyfills/dialog.css b/projects/website/assets/imports/polyfills/dialog.css new file mode 100644 index 00000000..7832c158 --- /dev/null +++ b/projects/website/assets/imports/polyfills/dialog.css @@ -0,0 +1,39 @@ +/* Dialog Polyfill (https://github.com/GoogleChrome/dialog-polyfill/blob/master/dist/dialog-polyfill.css) */ +dialog { + position: absolute; + left: 0; right: 0; + width: -moz-fit-content; + width: -webkit-fit-content; + width: fit-content; + height: -moz-fit-content; + height: -webkit-fit-content; + height: fit-content; + margin: auto; + border: solid; + padding: 1em; + background: white; + color: black; + display: block; +} + +dialog:not([open]) { + display: none; +} + +dialog + .backdrop { + position: fixed; + top: 0; right: 0; bottom: 0; left: 0; + background: rgba(0,0,0,0.6); +} + +._dialog_overlay { + position: fixed; + top: 0; right: 0; bottom: 0; left: 0; +} + +dialog.fixed { + position: fixed; + top: 50%; + transform: translate(0, -50%); +} + diff --git a/projects/website/assets/imports/polyfills/dialog.js b/projects/website/assets/imports/polyfills/dialog.js new file mode 100644 index 00000000..aee7d963 --- /dev/null +++ b/projects/website/assets/imports/polyfills/dialog.js @@ -0,0 +1,866 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.dialogPolyfill = factory()); +}(this, function () { 'use strict'; + + // nb. This is for IE10 and lower _only_. + var supportCustomEvent = window.CustomEvent; + if (!supportCustomEvent || typeof supportCustomEvent === 'object') { + supportCustomEvent = function CustomEvent(event, x) { + x = x || {}; + var ev = document.createEvent('CustomEvent'); + ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null); + return ev; + }; + supportCustomEvent.prototype = window.Event.prototype; + } + + /** + * Dispatches the passed event to both an "on" handler as well as via the + * normal dispatch operation. Does not bubble. + * + * @param {!EventTarget} target + * @param {!Event} event + * @return {boolean} + */ + function safeDispatchEvent(target, event) { + var check = 'on' + event.type.toLowerCase(); + if (typeof target[check] === 'function') { + target[check](event); + } + return target.dispatchEvent(event); + } + + /** + * @param {Element} el to check for stacking context + * @return {boolean} whether this el or its parents creates a stacking context + */ + function createsStackingContext(el) { + while (el && el !== document.body) { + var s = window.getComputedStyle(el); + var invalid = function(k, ok) { + return !(s[k] === undefined || s[k] === ok); + }; + + if (s.opacity < 1 || + invalid('zIndex', 'auto') || + invalid('transform', 'none') || + invalid('mixBlendMode', 'normal') || + invalid('filter', 'none') || + invalid('perspective', 'none') || + s['isolation'] === 'isolate' || + s.position === 'fixed' || + s.webkitOverflowScrolling === 'touch') { + return true; + } + el = el.parentElement; + } + return false; + } + + /** + * Finds the nearest from the passed element. + * + * @param {Element} el to search from + * @return {HTMLDialogElement} dialog found + */ + function findNearestDialog(el) { + while (el) { + if (el.localName === 'dialog') { + return /** @type {HTMLDialogElement} */ (el); + } + if (el.parentElement) { + el = el.parentElement; + } else if (el.parentNode) { + el = el.parentNode.host; + } else { + el = null; + } + } + return null; + } + + /** + * Blur the specified element, as long as it's not the HTML body element. + * This works around an IE9/10 bug - blurring the body causes Windows to + * blur the whole application. + * + * @param {Element} el to blur + */ + function safeBlur(el) { + // Find the actual focused element when the active element is inside a shadow root + while (el && el.shadowRoot && el.shadowRoot.activeElement) { + el = el.shadowRoot.activeElement; + } + + if (el && el.blur && el !== document.body) { + el.blur(); + } + } + + /** + * @param {!NodeList} nodeList to search + * @param {Node} node to find + * @return {boolean} whether node is inside nodeList + */ + function inNodeList(nodeList, node) { + for (var i = 0; i < nodeList.length; ++i) { + if (nodeList[i] === node) { + return true; + } + } + return false; + } + + /** + * @param {HTMLFormElement} el to check + * @return {boolean} whether this form has method="dialog" + */ + function isFormMethodDialog(el) { + if (!el || !el.hasAttribute('method')) { + return false; + } + return el.getAttribute('method').toLowerCase() === 'dialog'; + } + + /** + * @param {!DocumentFragment|!Element} hostElement + * @return {?Element} + */ + function findFocusableElementWithin(hostElement) { + // Note that this is 'any focusable area'. This list is probably not exhaustive, but the + // alternative involves stepping through and trying to focus everything. + var opts = ['button', 'input', 'keygen', 'select', 'textarea']; + var query = opts.map(function(el) { + return el + ':not([disabled])'; + }); + // TODO(samthor): tabindex values that are not numeric are not focusable. + query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled + var target = hostElement.querySelector(query.join(', ')); + + if (!target && 'attachShadow' in Element.prototype) { + // If we haven't found a focusable target, see if the host element contains an element + // which has a shadowRoot. + // Recursively search for the first focusable item in shadow roots. + var elems = hostElement.querySelectorAll('*'); + for (var i = 0; i < elems.length; i++) { + if (elems[i].tagName && elems[i].shadowRoot) { + target = findFocusableElementWithin(elems[i].shadowRoot); + if (target) { + break; + } + } + } + } + return target; + } + + /** + * Determines if an element is attached to the DOM. + * @param {Element} element to check + * @return {boolean} whether the element is in DOM + */ + function isConnected(element) { + return element.isConnected || document.body.contains(element); + } + + /** + * @param {!Event} event + * @return {?Element} + */ + function findFormSubmitter(event) { + if (event.submitter) { + return event.submitter; + } + + var form = event.target; + if (!(form instanceof HTMLFormElement)) { + return null; + } + + var submitter = dialogPolyfill.formSubmitter; + if (!submitter) { + var target = event.target; + var root = ('getRootNode' in target && target.getRootNode() || document); + submitter = root.activeElement; + } + + if (!submitter || submitter.form !== form) { + return null; + } + return submitter; + } + + /** + * @param {!Event} event + */ + function maybeHandleSubmit(event) { + if (event.defaultPrevented) { + return; + } + var form = /** @type {!HTMLFormElement} */ (event.target); + + // We'd have a value if we clicked on an imagemap. + var value = dialogPolyfill.imagemapUseValue; + var submitter = findFormSubmitter(event); + if (value === null && submitter) { + value = submitter.value; + } + + // There should always be a dialog as this handler is added specifically on them, but check just + // in case. + var dialog = findNearestDialog(form); + if (!dialog) { + return; + } + + // Prefer formmethod on the button. + var formmethod = submitter && submitter.getAttribute('formmethod') || form.getAttribute('method'); + if (formmethod !== 'dialog') { + return; + } + event.preventDefault(); + + if (value != null) { + // nb. we explicitly check against null/undefined + dialog.close(value); + } else { + dialog.close(); + } + } + + /** + * @param {!HTMLDialogElement} dialog to upgrade + * @constructor + */ + function dialogPolyfillInfo(dialog) { + this.dialog_ = dialog; + this.replacedStyleTop_ = false; + this.openAsModal_ = false; + + // Set a11y role. Browsers that support dialog implicitly know this already. + if (!dialog.hasAttribute('role')) { + dialog.setAttribute('role', 'dialog'); + } + + dialog.show = this.show.bind(this); + dialog.showModal = this.showModal.bind(this); + dialog.close = this.close.bind(this); + + dialog.addEventListener('submit', maybeHandleSubmit, false); + + if (!('returnValue' in dialog)) { + dialog.returnValue = ''; + } + + if ('MutationObserver' in window) { + var mo = new MutationObserver(this.maybeHideModal.bind(this)); + mo.observe(dialog, {attributes: true, attributeFilter: ['open']}); + } else { + // IE10 and below support. Note that DOMNodeRemoved etc fire _before_ removal. They also + // seem to fire even if the element was removed as part of a parent removal. Use the removed + // events to force downgrade (useful if removed/immediately added). + var removed = false; + var cb = function() { + removed ? this.downgradeModal() : this.maybeHideModal(); + removed = false; + }.bind(this); + var timeout; + var delayModel = function(ev) { + if (ev.target !== dialog) { return; } // not for a child element + var cand = 'DOMNodeRemoved'; + removed |= (ev.type.substr(0, cand.length) === cand); + window.clearTimeout(timeout); + timeout = window.setTimeout(cb, 0); + }; + ['DOMAttrModified', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument'].forEach(function(name) { + dialog.addEventListener(name, delayModel); + }); + } + // Note that the DOM is observed inside DialogManager while any dialog + // is being displayed as a modal, to catch modal removal from the DOM. + + Object.defineProperty(dialog, 'open', { + set: this.setOpen.bind(this), + get: dialog.hasAttribute.bind(dialog, 'open') + }); + + this.backdrop_ = document.createElement('div'); + this.backdrop_.className = 'backdrop'; + this.backdrop_.addEventListener('mouseup' , this.backdropMouseEvent_.bind(this)); + this.backdrop_.addEventListener('mousedown', this.backdropMouseEvent_.bind(this)); + this.backdrop_.addEventListener('click' , this.backdropMouseEvent_.bind(this)); + } + + dialogPolyfillInfo.prototype = /** @type {HTMLDialogElement.prototype} */ ({ + + get dialog() { + return this.dialog_; + }, + + /** + * Maybe remove this dialog from the modal top layer. This is called when + * a modal dialog may no longer be tenable, e.g., when the dialog is no + * longer open or is no longer part of the DOM. + */ + maybeHideModal: function() { + if (this.dialog_.hasAttribute('open') && isConnected(this.dialog_)) { return; } + this.downgradeModal(); + }, + + /** + * Remove this dialog from the modal top layer, leaving it as a non-modal. + */ + downgradeModal: function() { + if (!this.openAsModal_) { return; } + this.openAsModal_ = false; + this.dialog_.style.zIndex = ''; + + // This won't match the native exactly because if the user set top on a centered + // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's + // possible to polyfill this perfectly. + if (this.replacedStyleTop_) { + this.dialog_.style.top = ''; + this.replacedStyleTop_ = false; + } + + // Clear the backdrop and remove from the manager. + this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_); + dialogPolyfill.dm.removeDialog(this); + }, + + /** + * @param {boolean} value whether to open or close this dialog + */ + setOpen: function(value) { + if (value) { + this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', ''); + } else { + this.dialog_.removeAttribute('open'); + this.maybeHideModal(); // nb. redundant with MutationObserver + } + }, + + /** + * Handles mouse events ('mouseup', 'mousedown', 'click') on the fake .backdrop element, redirecting them as if + * they were on the dialog itself. + * + * @param {!Event} e to redirect + */ + backdropMouseEvent_: function(e) { + if (!this.dialog_.hasAttribute('tabindex')) { + // Clicking on the backdrop should move the implicit cursor, even if dialog cannot be + // focused. Create a fake thing to focus on. If the backdrop was _before_ the dialog, this + // would not be needed - clicks would move the implicit cursor there. + var fake = document.createElement('div'); + this.dialog_.insertBefore(fake, this.dialog_.firstChild); + fake.tabIndex = -1; + fake.focus(); + this.dialog_.removeChild(fake); + } else { + this.dialog_.focus(); + } + + var redirectedEvent = document.createEvent('MouseEvents'); + redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window, + e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, + e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget); + this.dialog_.dispatchEvent(redirectedEvent); + e.stopPropagation(); + }, + + /** + * Focuses on the first focusable element within the dialog. This will always blur the current + * focus, even if nothing within the dialog is found. + */ + focus_: function() { + // Find element with `autofocus` attribute, or fall back to the first form/tabindex control. + var target = this.dialog_.querySelector('[autofocus]:not([disabled])'); + if (!target && this.dialog_.tabIndex >= 0) { + target = this.dialog_; + } + if (!target) { + target = findFocusableElementWithin(this.dialog_); + } + safeBlur(document.activeElement); + target && target.focus(); + }, + + /** + * Sets the zIndex for the backdrop and dialog. + * + * @param {number} dialogZ + * @param {number} backdropZ + */ + updateZIndex: function(dialogZ, backdropZ) { + if (dialogZ < backdropZ) { + throw new Error('dialogZ should never be < backdropZ'); + } + this.dialog_.style.zIndex = dialogZ; + this.backdrop_.style.zIndex = backdropZ; + }, + + /** + * Shows the dialog. If the dialog is already open, this does nothing. + */ + show: function() { + if (!this.dialog_.open) { + this.setOpen(true); + this.focus_(); + } + }, + + /** + * Show this dialog modally. + */ + showModal: function() { + if (this.dialog_.hasAttribute('open')) { + throw new Error('Failed to execute \'showModal\' on dialog: The element is already open, and therefore cannot be opened modally.'); + } + if (!isConnected(this.dialog_)) { + throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.'); + } + if (!dialogPolyfill.dm.pushDialog(this)) { + throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.'); + } + + if (createsStackingContext(this.dialog_.parentElement)) { + console.warn('A dialog is being shown inside a stacking context. ' + + 'This may cause it to be unusable. For more information, see this link: ' + + 'https://github.com/GoogleChrome/dialog-polyfill/#stacking-context'); + } + + this.setOpen(true); + this.openAsModal_ = true; + + // Optionally center vertically, relative to the current viewport. + if (dialogPolyfill.needsCentering(this.dialog_)) { + dialogPolyfill.reposition(this.dialog_); + this.replacedStyleTop_ = true; + } else { + this.replacedStyleTop_ = false; + } + + // Insert backdrop. + this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling); + + // Focus on whatever inside the dialog. + this.focus_(); + }, + + /** + * Closes this HTMLDialogElement. This is optional vs clearing the open + * attribute, however this fires a 'close' event. + * + * @param {string=} opt_returnValue to use as the returnValue + */ + close: function(opt_returnValue) { + if (!this.dialog_.hasAttribute('open')) { + throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.'); + } + this.setOpen(false); + + // Leave returnValue untouched in case it was set directly on the element + if (opt_returnValue !== undefined) { + this.dialog_.returnValue = opt_returnValue; + } + + // Triggering "close" event for any attached listeners on the . + var closeEvent = new supportCustomEvent('close', { + bubbles: false, + cancelable: false + }); + safeDispatchEvent(this.dialog_, closeEvent); + } + + }); + + var dialogPolyfill = {}; + + dialogPolyfill.reposition = function(element) { + var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; + var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2; + element.style.top = Math.max(scrollTop, topValue) + 'px'; + }; + + dialogPolyfill.isInlinePositionSetByStylesheet = function(element) { + for (var i = 0; i < document.styleSheets.length; ++i) { + var styleSheet = document.styleSheets[i]; + var cssRules = null; + // Some browsers throw on cssRules. + try { + cssRules = styleSheet.cssRules; + } catch (e) {} + if (!cssRules) { continue; } + for (var j = 0; j < cssRules.length; ++j) { + var rule = cssRules[j]; + var selectedNodes = null; + // Ignore errors on invalid selector texts. + try { + selectedNodes = document.querySelectorAll(rule.selectorText); + } catch(e) {} + if (!selectedNodes || !inNodeList(selectedNodes, element)) { + continue; + } + var cssTop = rule.style.getPropertyValue('top'); + var cssBottom = rule.style.getPropertyValue('bottom'); + if ((cssTop && cssTop !== 'auto') || (cssBottom && cssBottom !== 'auto')) { + return true; + } + } + } + return false; + }; + + dialogPolyfill.needsCentering = function(dialog) { + var computedStyle = window.getComputedStyle(dialog); + if (computedStyle.position !== 'absolute') { + return false; + } + + // We must determine whether the top/bottom specified value is non-auto. In + // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but + // Firefox returns the used value. So we do this crazy thing instead: check + // the inline style and then go through CSS rules. + if ((dialog.style.top !== 'auto' && dialog.style.top !== '') || + (dialog.style.bottom !== 'auto' && dialog.style.bottom !== '')) { + return false; + } + return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog); + }; + + /** + * @param {!Element} element to force upgrade + */ + dialogPolyfill.forceRegisterDialog = function(element) { + if (window.HTMLDialogElement || element.showModal) { + console.warn('This browser already supports , the polyfill ' + + 'may not work correctly', element); + } + if (element.localName !== 'dialog') { + throw new Error('Failed to register dialog: The element is not a dialog.'); + } + new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element)); + }; + + /** + * @param {!Element} element to upgrade, if necessary + */ + dialogPolyfill.registerDialog = function(element) { + if (!element.showModal) { + dialogPolyfill.forceRegisterDialog(element); + } + }; + + /** + * @constructor + */ + dialogPolyfill.DialogManager = function() { + /** @type {!Array} */ + this.pendingDialogStack = []; + + var checkDOM = this.checkDOM_.bind(this); + + // The overlay is used to simulate how a modal dialog blocks the document. + // The blocking dialog is positioned on top of the overlay, and the rest of + // the dialogs on the pending dialog stack are positioned below it. In the + // actual implementation, the modal dialog stacking is controlled by the + // top layer, where z-index has no effect. + this.overlay = document.createElement('div'); + this.overlay.className = '_dialog_overlay'; + this.overlay.addEventListener('click', function(e) { + this.forwardTab_ = undefined; + e.stopPropagation(); + checkDOM([]); // sanity-check DOM + }.bind(this)); + + this.handleKey_ = this.handleKey_.bind(this); + this.handleFocus_ = this.handleFocus_.bind(this); + + this.zIndexLow_ = 100000; + this.zIndexHigh_ = 100000 + 150; + + this.forwardTab_ = undefined; + + if ('MutationObserver' in window) { + this.mo_ = new MutationObserver(function(records) { + var removed = []; + records.forEach(function(rec) { + for (var i = 0, c; c = rec.removedNodes[i]; ++i) { + if (!(c instanceof Element)) { + continue; + } else if (c.localName === 'dialog') { + removed.push(c); + } + removed = removed.concat(c.querySelectorAll('dialog')); + } + }); + removed.length && checkDOM(removed); + }); + } + }; + + /** + * Called on the first modal dialog being shown. Adds the overlay and related + * handlers. + */ + dialogPolyfill.DialogManager.prototype.blockDocument = function() { + document.documentElement.addEventListener('focus', this.handleFocus_, true); + document.addEventListener('keydown', this.handleKey_); + this.mo_ && this.mo_.observe(document, {childList: true, subtree: true}); + }; + + /** + * Called on the first modal dialog being removed, i.e., when no more modal + * dialogs are visible. + */ + dialogPolyfill.DialogManager.prototype.unblockDocument = function() { + document.documentElement.removeEventListener('focus', this.handleFocus_, true); + document.removeEventListener('keydown', this.handleKey_); + this.mo_ && this.mo_.disconnect(); + }; + + /** + * Updates the stacking of all known dialogs. + */ + dialogPolyfill.DialogManager.prototype.updateStacking = function() { + var zIndex = this.zIndexHigh_; + + for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) { + dpi.updateZIndex(--zIndex, --zIndex); + if (i === 0) { + this.overlay.style.zIndex = --zIndex; + } + } + + // Make the overlay a sibling of the dialog itself. + var last = this.pendingDialogStack[0]; + if (last) { + var p = last.dialog.parentNode || document.body; + p.appendChild(this.overlay); + } else if (this.overlay.parentNode) { + this.overlay.parentNode.removeChild(this.overlay); + } + }; + + /** + * @param {Element} candidate to check if contained or is the top-most modal dialog + * @return {boolean} whether candidate is contained in top dialog + */ + dialogPolyfill.DialogManager.prototype.containedByTopDialog_ = function(candidate) { + while (candidate = findNearestDialog(candidate)) { + for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) { + if (dpi.dialog === candidate) { + return i === 0; // only valid if top-most + } + } + candidate = candidate.parentElement; + } + return false; + }; + + dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) { + var target = event.composedPath ? event.composedPath()[0] : event.target; + + if (this.containedByTopDialog_(target)) { return; } + + if (document.activeElement === document.documentElement) { return; } + + event.preventDefault(); + event.stopPropagation(); + safeBlur(/** @type {Element} */ (target)); + + if (this.forwardTab_ === undefined) { return; } // move focus only from a tab key + + var dpi = this.pendingDialogStack[0]; + var dialog = dpi.dialog; + var position = dialog.compareDocumentPosition(target); + if (position & Node.DOCUMENT_POSITION_PRECEDING) { + if (this.forwardTab_) { + // forward + dpi.focus_(); + } else if (target !== document.documentElement) { + // backwards if we're not already focused on + document.documentElement.focus(); + } + } + + return false; + }; + + dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) { + this.forwardTab_ = undefined; + if (event.keyCode === 27) { + event.preventDefault(); + event.stopPropagation(); + var cancelEvent = new supportCustomEvent('cancel', { + bubbles: false, + cancelable: true + }); + var dpi = this.pendingDialogStack[0]; + if (dpi && safeDispatchEvent(dpi.dialog, cancelEvent)) { + dpi.dialog.close(); + } + } else if (event.keyCode === 9) { + this.forwardTab_ = !event.shiftKey; + } + }; + + /** + * Finds and downgrades any known modal dialogs that are no longer displayed. Dialogs that are + * removed and immediately readded don't stay modal, they become normal. + * + * @param {!Array} removed that have definitely been removed + */ + dialogPolyfill.DialogManager.prototype.checkDOM_ = function(removed) { + // This operates on a clone because it may cause it to change. Each change also calls + // updateStacking, which only actually needs to happen once. But who removes many modal dialogs + // at a time?! + var clone = this.pendingDialogStack.slice(); + clone.forEach(function(dpi) { + if (removed.indexOf(dpi.dialog) !== -1) { + dpi.downgradeModal(); + } else { + dpi.maybeHideModal(); + } + }); + }; + + /** + * @param {!dialogPolyfillInfo} dpi + * @return {boolean} whether the dialog was allowed + */ + dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) { + var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1; + if (this.pendingDialogStack.length >= allowed) { + return false; + } + if (this.pendingDialogStack.unshift(dpi) === 1) { + this.blockDocument(); + } + this.updateStacking(); + return true; + }; + + /** + * @param {!dialogPolyfillInfo} dpi + */ + dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) { + var index = this.pendingDialogStack.indexOf(dpi); + if (index === -1) { return; } + + this.pendingDialogStack.splice(index, 1); + if (this.pendingDialogStack.length === 0) { + this.unblockDocument(); + } + this.updateStacking(); + }; + + dialogPolyfill.dm = new dialogPolyfill.DialogManager(); + dialogPolyfill.formSubmitter = null; + dialogPolyfill.imagemapUseValue = null; + + /** + * Installs global handlers, such as click listers and native method overrides. These are needed + * even if a no dialog is registered, as they deal with
. + */ + if (window.HTMLDialogElement === undefined) { + + /** + * If HTMLFormElement translates method="DIALOG" into 'get', then replace the descriptor with + * one that returns the correct value. + */ + var testForm = document.createElement('form'); + testForm.setAttribute('method', 'dialog'); + if (testForm.method !== 'dialog') { + var methodDescriptor = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'method'); + if (methodDescriptor) { + // nb. Some older iOS and older PhantomJS fail to return the descriptor. Don't do anything + // and don't bother to update the element. + var realGet = methodDescriptor.get; + methodDescriptor.get = function() { + if (isFormMethodDialog(this)) { + return 'dialog'; + } + return realGet.call(this); + }; + var realSet = methodDescriptor.set; + /** @this {HTMLElement} */ + methodDescriptor.set = function(v) { + if (typeof v === 'string' && v.toLowerCase() === 'dialog') { + return this.setAttribute('method', v); + } + return realSet.call(this, v); + }; + Object.defineProperty(HTMLFormElement.prototype, 'method', methodDescriptor); + } + } + + /** + * Global 'click' handler, to capture the or