A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <!doctype html><!-- This is a valid HTML5 document. -->
  2. <!-- Screen readers, SEO, extensions and so on. -->
  3. <html lang="fr">
  4. <!-- Has to be within the first 1024 bytes, hence before the `title` element
  5. See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
  6. <meta charset="utf-8">
  7. <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
  8. <!-- The viewport meta is quite crowded and we are responsible for that.
  9. See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
  10. <meta name="viewport" content="width=device-width,initial-scale=1">
  11. <!-- Required to make a valid HTML5 document. -->
  12. <title>The yaml document from hell (archive) — David Larlet</title>
  13. <meta name="description" content="Publication mise en cache pour en conserver une trace.">
  14. <!-- That good ol' feed, subscribe :). -->
  15. <link rel="alternate" type="application/atom+xml" title="Feed" href="/david/log/">
  16. <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
  17. <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons2/apple-touch-icon.png">
  18. <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons2/favicon-32x32.png">
  19. <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons2/favicon-16x16.png">
  20. <link rel="manifest" href="/static/david/icons2/site.webmanifest">
  21. <link rel="mask-icon" href="/static/david/icons2/safari-pinned-tab.svg" color="#07486c">
  22. <link rel="shortcut icon" href="/static/david/icons2/favicon.ico">
  23. <meta name="msapplication-TileColor" content="#f7f7f7">
  24. <meta name="msapplication-config" content="/static/david/icons2/browserconfig.xml">
  25. <meta name="theme-color" content="#f7f7f7" media="(prefers-color-scheme: light)">
  26. <meta name="theme-color" content="#272727" media="(prefers-color-scheme: dark)">
  27. <!-- Is that even respected? Retrospectively? What a shAItshow…
  28. https://neil-clarke.com/block-the-bots-that-feed-ai-models-by-scraping-your-website/ -->
  29. <meta name="robots" content="noai, noimageai">
  30. <!-- Documented, feel free to shoot an email. -->
  31. <link rel="stylesheet" href="/static/david/css/style_2021-01-20.css">
  32. <!-- See https://www.zachleat.com/web/comprehensive-webfonts/ for the trade-off. -->
  33. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_regular.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  34. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_bold.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  35. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_italic.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  36. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_regular.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  37. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_bold.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  38. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_italic.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  39. <script>
  40. function toggleTheme(themeName) {
  41. document.documentElement.classList.toggle(
  42. 'forced-dark',
  43. themeName === 'dark'
  44. )
  45. document.documentElement.classList.toggle(
  46. 'forced-light',
  47. themeName === 'light'
  48. )
  49. }
  50. const selectedTheme = localStorage.getItem('theme')
  51. if (selectedTheme !== 'undefined') {
  52. toggleTheme(selectedTheme)
  53. }
  54. </script>
  55. <meta name="robots" content="noindex, nofollow">
  56. <meta content="origin-when-cross-origin" name="referrer">
  57. <!-- Canonical URL for SEO purposes -->
  58. <link rel="canonical" href="https://ruudvanasseldonk.com/2023/01/11/the-yaml-document-from-hell">
  59. <body class="remarkdown h1-underline h2-underline h3-underline em-underscore hr-center ul-star pre-tick" data-instant-intensity="viewport-all">
  60. <article>
  61. <header>
  62. <h1>The yaml document from hell</h1>
  63. </header>
  64. <nav>
  65. <p class="center">
  66. <a href="/david/" title="Aller à l’accueil"><svg class="icon icon-home">
  67. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-home"></use>
  68. </svg> Accueil</a> •
  69. <a href="https://ruudvanasseldonk.com/2023/01/11/the-yaml-document-from-hell" title="Lien vers le contenu original">Source originale</a>
  70. </p>
  71. </nav>
  72. <hr>
  73. <article id="content" itemscope><p><span class="run-in">For a data format</span>, yaml is extremely complicated. It aims to be a human-friendly format, but in striving for that it introduces so much complexity, that I would argue it achieves the opposite result. Yaml is full of footguns and its friendliness is deceptive. In this post I want to demonstrate this through an example.</p><p>This post is a rant, and more opinionated than my usual writing.</p><h2 id="yaml-is-really-really-complex"><a href="#yaml-is-really-really-complex"></a>Yaml is really, really complex</h2><p>Json is simple. <a href="https://www.json.org/json-en.html">The entire json spec</a> consists of six railroad diagrams. It’s a simple data format with a simple syntax and that’s all there is to it. Yaml on the other hand, is complex. So complex, that <a href="https://yaml.org/spec/1.2.2/">its specification</a> consists of <em>10 chapters</em> with sections numbered four levels deep and a dedicated <a href="https://yaml.org/spec/1.2/errata.html">errata page</a>.</p><p>The json spec is not versioned. There were <a href="https://youtu.be/-C-JoyNuQJs?t=965">two changes</a> to it in 2005 (the removal of comments, and the addition of scientific notation for numbers), but it has been frozen since — almost two decades now. The yaml spec on the other hand is versioned. The latest revision is fairly recent, 1.2.2 from October 2021. Yaml 1.2 differs substantially from 1.1: the same document can parse differently under different yaml versions. We will see multiple examples of this later.</p><p>Json is so obvious that Douglas Crockford claims <a href="https://www.youtube.com/watch?v=-C-JoyNuQJs">to have discovered it</a> — not invented. I couldn’t find any reference for how long it took him to write up the spec, but it was probably hours rather than weeks. The change from yaml 1.2.1 to 1.2.2 on the other hand, was <a href="https://yaml.com/blog/2021-10/new-yaml-spec/">a multi-year effort by a team of experts</a>:</p><blockquote><p>This revision is the result of years of work by the new <abbr>YAML</abbr> language development team. Each person on this team has a deep knowledge of the language and has written and maintains important open source <abbr>YAML</abbr> frameworks and tools.</p></blockquote><p>Furthermore this team plans to actively evolve yaml, rather than to freeze it.</p><p>When you work with a format as complex as yaml, it is difficult to be aware of all the features and subtle behaviors it has. There is <a href="https://yaml-multiline.info/">an entire website</a> dedicated to picking one of <a href="https://stackoverflow.com/a/21699210/135889">the 63 different multi-line string syntaxes</a>. This means that it can be very difficult for a human to predict how a particular document will parse. Let’s look an example to highlight this.</p><h2 id="the-yaml-document-from-hell"><a href="#the-yaml-document-from-hell"></a>The yaml document from hell</h2><p>Consider the following document.</p><pre><code>server_config:
  74. port_mapping:
  75. # Expose only ssh and http to the public internet.
  76. - 22:22
  77. - 80:80
  78. - 443:443
  79. serve:
  80. - /robots.txt
  81. - /favicon.ico
  82. - *.html
  83. - *.png
  84. - !.git # Do not expose our Git repository to the entire world.
  85. geoblock_regions:
  86. # The legal team has not approved distribution in the Nordics yet.
  87. - dk
  88. - fi
  89. - is
  90. - no
  91. - se
  92. flush_cache:
  93. on: [push, memory_pressure]
  94. priority: background
  95. allow_postgres_versions:
  96. - 9.5.25
  97. - 9.6.24
  98. - 10.23
  99. - 12.13</code></pre><p>Let’s break this down section by section and see how the data maps to json.</p><h2 id="sexagesimal-numbers"><a href="#sexagesimal-numbers"></a>Sexagesimal numbers</h2><p>Let’s start with something that you might find in a container runtime configuration:</p><pre><code>port_mapping:
  100. - 22:22
  101. - 80:80
  102. - 443:443</code></pre><div class="sourceCode" id="cb3"><pre class="sourceCode json"><code class="sourceCode json"><span id="cb3-1"><span class="fu">{</span><span class="dt">"port_mapping"</span><span class="fu">:</span> <span class="ot">[</span><span class="dv">1342</span><span class="ot">,</span> <span class="st">"80:80"</span><span class="ot">,</span> <span class="st">"443:443"</span><span class="ot">]</span><span class="fu">}</span></span></code></pre></div><p>Huh, what happened here? As it turns out, numbers from 0 to 59 separated by colons are <a href="https://yaml.org/spec/1.1/#id858600">sexagesimal (base 60) number literals</a>. This arcane feature was present in yaml 1.1, but silently removed from yaml 1.2, so the list element will parse as <code>1342</code> or <code>"22:22"</code> depending on which version your parser uses. Although yaml 1.2 is more than 10 years old by now, you would be mistaken to think that it is widely supported: the latest version libyaml at the time of writing (which is used among others by <a href="https://pypi.org/project/PyYAML/6.0/">PyYAML</a>) implements yaml 1.1 and parses <code>22:22</code> as <code>1342</code>.</p><p>The following snippet is actually invalid:</p><pre><code>serve:
  103. - /robots.txt
  104. - /favicon.ico
  105. - *.html
  106. - *.png
  107. - !.git</code></pre><p>Yaml allows you to create an <em>anchor</em> by adding an <code>&amp;</code> and a name in front of a value, and then you can later reference that value with an <em>alias</em>: a <code>*</code> followed by the name. In this case no anchors are defined, so the aliases are invalid. Let’s avoid them for now and see what happens.</p><pre><code>serve:
  108. - /robots.txt
  109. - /favicon.ico
  110. - !.git</code></pre><div class="sourceCode" id="cb6"><pre class="sourceCode json"><code class="sourceCode json"><span id="cb6-1"><span class="fu">{</span><span class="dt">"serve"</span><span class="fu">:</span> <span class="ot">[</span><span class="st">"/robots.txt"</span><span class="ot">,</span> <span class="st">"/favicon.ico"</span><span class="ot">,</span> <span class="st">""</span><span class="ot">]</span><span class="fu">}</span></span></code></pre></div><p>Now the interpretation depends on the parser you are using. The element starting with <code>!</code> is a <a href="https://yaml.org/spec/1.2.2/#3212-tags">tag</a>. This feature is intended to enable a parser to convert the fairly limited yaml data types into richer types that might exist in the host language. A tag starting with <code>!</code> is up to the parser to interpret, often by calling a constructor with the given name and providing it the value that follows after the tag. This means that <strong>loading an untrusted yaml document is generally unsafe</strong>, as it may lead to arbitrary code execution. (In Python, you can avoid this pitfall by using <code>yaml.safe_load</code> instead of <code>yaml.load</code>.) In our case above, PyYAML fails to load the document because it doesn’t know the <code>.git</code> tag. Go’s yaml package is less strict and returns an empty string.</p><h2 id="the-norway-problem"><a href="#the-norway-problem"></a>The Norway problem</h2><p>This pitfall is so infamous that it became known as “<a href="https://hitchdev.com/strictyaml/why/implicit-typing-removed/">the Norway problem</a>”:</p><pre><code>geoblock_regions:
  111. - dk
  112. - fi
  113. - is
  114. - no
  115. - se</code></pre><div class="sourceCode" id="cb8"><pre class="sourceCode json"><code class="sourceCode json"><span id="cb8-1"><span class="fu">{</span><span class="dt">"geoblock_regions"</span><span class="fu">:</span> <span class="ot">[</span><span class="st">"dk"</span><span class="ot">,</span> <span class="st">"fi"</span><span class="ot">,</span> <span class="st">"is"</span><span class="ot">,</span> <span class="kw">false</span><span class="ot">,</span> <span class="st">"se"</span><span class="ot">]</span><span class="fu">}</span></span></code></pre></div><p>What is that <code>false</code> doing there? The literals <code>off</code>, <code>no</code>, and <code>n</code>, in various capitalizations (<a href="https://yaml.org/type/bool.html">but not any capitalization</a>!), are all <code>false</code> in yaml 1.1, while <code>on</code>, <code>yes</code>, and <code>y</code> are true. In yaml 1.2 these alternative spellings of the boolean literals are no longer allowed, but they are so pervasive in the wild that a compliant parser would have a hard time reading many documents. Go’s yaml library therefore <a href="https://github.com/go-yaml/yaml/tree/v3.0.1#compatibility">made the choice</a> of implementing a custom variant somewhere in between yaml 1.1 and 1.2 that behaves differently depending on the context:</p><blockquote><p>The yaml package supports most of <abbr>YAML</abbr> 1.2, but preserves some behavior from 1.1 for backwards compatibility. <abbr>YAML</abbr> 1.1 bools (yes/no, on/off) are supported as long as they are being decoded into a typed bool value. Otherwise they behave as a string.</p></blockquote><p>Note that it only does that since version 3.0.0, which was released in May 2022. <a href="https://github.com/go-yaml/yaml/commit/b145382a4cda47600eceb779844b8090b5807c4f">Earlier versions behave differently</a>.</p><h2 id="non-string-keys"><a href="#non-string-keys"></a>Non-string keys</h2><p>While keys in json are always strings, in yaml they can be any value, including booleans.</p><pre><code>flush_cache:
  116. on: [push, memory_pressure]
  117. priority: background</code></pre><div class="sourceCode" id="cb10"><pre class="sourceCode json"><code class="sourceCode json"><span id="cb10-1"><span class="fu">{</span></span>
  118. <span id="cb10-2"> <span class="dt">"flush_cache"</span><span class="fu">:</span> <span class="fu">{</span></span>
  119. <span id="cb10-3"> <span class="dt">"True"</span><span class="fu">:</span> <span class="ot">[</span><span class="st">"push"</span><span class="ot">,</span> <span class="st">"memory_pressure"</span><span class="ot">]</span><span class="fu">,</span></span>
  120. <span id="cb10-4"> <span class="dt">"priority"</span><span class="fu">:</span> <span class="st">"background"</span></span>
  121. <span id="cb10-5"> <span class="fu">}</span></span>
  122. <span id="cb10-6"><span class="fu">}</span></span></code></pre></div><p>Combined with the previous feature of interpreting <code>on</code> as a boolean, this leads to a dictionary with <code>true</code> as one of the keys. It depends on the language how that maps to json, if at all. In Python it becomes the string <code>"True"</code>. The key <code>on</code> is common in the wild because <a href="https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on">it is used in GitHub Actions</a>. I would be really curious to know whether GitHub Actions’ parser looks at <code>"on"</code> or <code>true</code> under the hood.</p><h2 id="accidental-numbers"><a href="#accidental-numbers"></a>Accidental numbers</h2><p>Leaving strings unquoted can easily lead to unintentional numbers.</p><pre><code>allow_postgres_versions:
  123. - 9.5.25
  124. - 9.6.24
  125. - 10.23
  126. - 12.13</code></pre><div class="sourceCode" id="cb12"><pre class="sourceCode json"><code class="sourceCode json"><span id="cb12-1"><span class="fu">{</span><span class="dt">"allow_postgres_versions"</span><span class="fu">:</span> <span class="ot">[</span><span class="st">"9.5.25"</span><span class="ot">,</span> <span class="st">"9.6.24"</span><span class="ot">,</span> <span class="fl">10.23</span><span class="ot">,</span> <span class="fl">12.13</span><span class="ot">]</span><span class="fu">}</span></span></code></pre></div><p>Maybe the list is a contrived example, but imagine updating a config file that lists a single value of 9.6.24 and changing it to 10.23. Would you remember to add the quotes? What makes this even more insidious is that many dynamically typed applications implicitly convert the number to a string when needed, so your document works fine most of the time, except in some contexts it doesn’t. For example, the following Jinja template accepts both <code>version: "0.0"</code> and <code>version: 0.0</code>, but it only takes the true-branch for the former.</p><pre><code>{% if version %}
  127. Latest version: {{ version }}
  128. {% else %}
  129. Version not specified
  130. {% endif %}</code></pre><h2 id="runners-up"><a href="#runners-up"></a>Runners-up</h2><p>There is only so much I can fit into one artifical example. Some arcane yaml behaviors that did not make it in are <a href="https://yaml.org/spec/1.2.2/#68-directives">directives</a>, integers starting with <code>0</code> being octal literals (but only in yaml 1.1), <code>~</code> being an alternative spelling of <code>null</code>, and <code>?</code> introducing a <a href="https://yaml.org/spec/1.2.2/#example-mapping-between-sequences">complex mapping key</a>.</p><h2 id="syntax-highlighting-will-not-save-you"><a href="#syntax-highlighting-will-not-save-you"></a>Syntax highlighting will not save you</h2><p>You may have noticed that none of my examples have syntax highlighting enabled. Maybe I am being unfair to yaml, because syntax highlighting would highlight special constructs, so you can at least see that some values are not normal strings. However, due to multiple yaml versions being prevalent, and highlighters having different levels of sophistication, you can’t rely on this. I’m not trying to nitpick here: Vim, my blog generator, GitHub, and Codeberg, all have a unique way to highlight the example document from this post. No two of them pick out the same subset of values as non-strings!</p><h2 id="templating-yaml-is-a-terrible-terrible-idea"><a href="#templating-yaml-is-a-terrible-terrible-idea"></a>Templating yaml is a terrible, terrible idea</h2><p>I hope it is clear by now that working with yaml is subtle at the very least. What is even more subtle is concatenating and escaping arbitrary text fragments in such a way that the result is a valid yaml document, let alone one that does what you expect. Add to this the fact that whitespace is significant in yaml, and the result is a format that is <a href="https://twitter.com/memenetes/status/1600898397279502336">meme-worthily</a> difficult to template correctly. I truly do not understand why <a href="https://helm.sh/docs/chart_best_practices/templates/">tools based on such an error-prone practice</a> have gained so much mindshare, when there is a safer, easier, and more powerful alternative: generating json.</p><h2 id="alternative-configuration-formats"><a href="#alternative-configuration-formats"></a>Alternative configuration formats</h2><p>I think the main reason that yaml is so prevalent despite its pitfalls, is that for a long time it was the only viable configuration format. Often we need lists and nested data, which rules out flat formats like ini. Xml is noisy and annoying to write by hand. But most of all, we need comments, which rules out json. (As we saw before, json had comments very early on, but they were removed because people started putting parsing directives in there. I think this is the right call for a serialization format, but it makes json unsuitable as a configuration language.) So if what we really need is the json data model but a syntax that allows comments, what are some of the options?</p><ul><li><a href="https://toml.io/en/"><strong>Toml</strong></a> — Toml is similar to yaml in many ways: it has mostly the same data types; the syntax is not as verbose as json; and it allows comments. Unlike yaml it is not full of footguns, mostly because strings are always quoted, so you don’t have values that look like strings but aren’t. Toml is widely supported, you can probably find a toml parser for your favorite language. It’s even in the Python standard library — unlike yaml! A weak spot of toml is deeply nested data.</li><li><a href="https://code.visualstudio.com/docs/languages/json#_json-with-comments"><strong>Json with comments</strong></a>, <a href="https://nigeltao.github.io/blog/2021/json-with-commas-comments.html"><strong>Json with commas and comments</strong></a> — There exist various extensions of json that extend it just enough to make it a usable config format without introducing too much complexity. Json with comments is probably the most widespread, as it is used as the config format for Visual Studio Code. The main downside of these is that they haven’t really caught on (yet!), so they aren’t as widely supported as json or yaml.</li><li><strong>A simple subset of yaml</strong> — Many of the problems with yaml are caused by unquoted things that look like strings but behave differently. This is easy to avoid: always quote all strings. (Indeed, you can tell that somebody is an experienced yaml engineer when they defensively quote all the strings.) We can choose to always use <code>true</code> and <code>false</code> rather than <code>yes</code> and <code>no</code>, and generally stay away from the arcane features. The challenge with this is that any construct not explicitly forbidden will eventually make it into your codebase, and I am not aware of any good tool that can enforce a sane yaml subset.</li></ul><h2 id="generating-json-as-a-better-yaml"><a href="#generating-json-as-a-better-yaml"></a>Generating json as a better yaml</h2><p>Often the choice of format is not ours to make, and an application only accepts yaml. Not all is lost though, because yaml is a superset of json, so any tool that can produce json can be used to generate a yaml document.</p><p>Sometimes an application will start out with a need for just a configuration format, but over time you end up with many many similar stanzas, and you would like to share parts between them, and abstract some repetition away. This tends to happen in for example Kubernetes and GitHub Actions. When the configuration language does not support abstraction, people often reach for templating, which is a bad idea for the reasons explained earlier. Proper programming languages, possibly domain-specific ones, are a better fit. Some of my favorites are Nix and Python:</p><ul><li><a href="https://nixos.org/manual/nix/stable/language/index.html"><strong>Nix</strong></a> — Nix is the language used by the <a href="https://nixos.org/">Nix package manager</a>. It was created for writing package definitions, but it works remarkably well as a configuration format (and indeed it is used to configure NixOS). Functions, let-bindings, and string interpolation make it powerful for abstracting repetitive configuration. The syntax is light like toml, and it can <a href="https://nixos.org/manual/nix/stable/language/builtins.html#builtins-toJSON">export to json</a> or xml. It works well for simplifying a repetitive GitHub Actions workflow file, for example.</li><li><a href="https://www.python.org/"><strong>Python</strong></a> — Json documents double as valid Python literals with minimal adaptation, and Python supports trailing commas and comments. It has variables and functions, powerful string interpolation, and <a href="https://docs.python.org/3/library/json.html?highlight=json%20dump#json.dump"><code>json.dump</code></a> built in. A self-contained Python file that prints json to stdout goes a long way!</li></ul><p>Finally there are some tools in this category that I haven’t used enough to confidently recommend, but which deserve to be mentioned:</p><ul><li><a href="https://dhall-lang.org/"><strong>Dhall</strong></a> — Dhall is like Nix, but with types. It is less widespread, and personally I find the built-in function names unwieldy.</li><li><a href="https://cuelang.org/"><strong>Cue</strong></a> — Like Dhall, Cue integrates type/schema information into the config format. Cue is a superset of json, but despite that, I find the files that actually use Cue’s features to look foreign to me. Cue is on my radar to evaluate further, but I haven’t encountered a problem where Cue looked like the most suitable solution yet.</li><li><a href="https://github.com/hashicorp/hcl"><strong>Hashicorp Configuration Language</strong></a> — I haven’t used <abbr>HCL</abbr> extensively enough to have a strong opinion on it, but in the places where I worked with it, the potential for abstraction seemed more limited than what you can achieve with e.g. Nix.</li></ul><h2 id="conclusion"><a href="#conclusion"></a>Conclusion</h2><p>Yaml aims to be a more human-friendly alternative to json, but with all of its features, it became such a complex format with so many bizarre and unexpected behaviors, that it is difficult for humans to predict how a given yaml document will parse. If you are looking for a configuration format, toml is a friendly format without yaml’s footguns. For cases where you are stuck with yaml, generating json from a more suitable language can be a viable approach. Generating json also opens op the possibility for abstraction and reuse, in a way that is difficult to achieve safely by templating yaml.</p></article>
  131. </article>
  132. <hr>
  133. <footer>
  134. <p>
  135. <a href="/david/" title="Aller à l’accueil"><svg class="icon icon-home">
  136. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-home"></use>
  137. </svg> Accueil</a> •
  138. <a href="/david/log/" title="Accès au flux RSS"><svg class="icon icon-rss2">
  139. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-rss2"></use>
  140. </svg> Suivre</a> •
  141. <a href="http://larlet.com" title="Go to my English profile" data-instant><svg class="icon icon-user-tie">
  142. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-user-tie"></use>
  143. </svg> Pro</a> •
  144. <a href="mailto:david%40larlet.fr" title="Envoyer un courriel"><svg class="icon icon-mail">
  145. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-mail"></use>
  146. </svg> Email</a> •
  147. <abbr class="nowrap" title="Hébergeur : Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33184162340"><svg class="icon icon-hammer2">
  148. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-hammer2"></use>
  149. </svg> Légal</abbr>
  150. </p>
  151. <template id="theme-selector">
  152. <form>
  153. <fieldset>
  154. <legend><svg class="icon icon-brightness-contrast">
  155. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-brightness-contrast"></use>
  156. </svg> Thème</legend>
  157. <label>
  158. <input type="radio" value="auto" name="chosen-color-scheme" checked> Auto
  159. </label>
  160. <label>
  161. <input type="radio" value="dark" name="chosen-color-scheme"> Foncé
  162. </label>
  163. <label>
  164. <input type="radio" value="light" name="chosen-color-scheme"> Clair
  165. </label>
  166. </fieldset>
  167. </form>
  168. </template>
  169. </footer>
  170. <script src="/static/david/js/instantpage-5.1.0.min.js" type="module"></script>
  171. <script>
  172. function loadThemeForm(templateName) {
  173. const themeSelectorTemplate = document.querySelector(templateName)
  174. const form = themeSelectorTemplate.content.firstElementChild
  175. themeSelectorTemplate.replaceWith(form)
  176. form.addEventListener('change', (e) => {
  177. const chosenColorScheme = e.target.value
  178. localStorage.setItem('theme', chosenColorScheme)
  179. toggleTheme(chosenColorScheme)
  180. })
  181. const selectedTheme = localStorage.getItem('theme')
  182. if (selectedTheme && selectedTheme !== 'undefined') {
  183. form.querySelector(`[value="${selectedTheme}"]`).checked = true
  184. }
  185. }
  186. const prefersColorSchemeDark = '(prefers-color-scheme: dark)'
  187. window.addEventListener('load', () => {
  188. let hasDarkRules = false
  189. for (const styleSheet of Array.from(document.styleSheets)) {
  190. let mediaRules = []
  191. for (const cssRule of styleSheet.cssRules) {
  192. if (cssRule.type !== CSSRule.MEDIA_RULE) {
  193. continue
  194. }
  195. // WARNING: Safari does not have/supports `conditionText`.
  196. if (cssRule.conditionText) {
  197. if (cssRule.conditionText !== prefersColorSchemeDark) {
  198. continue
  199. }
  200. } else {
  201. if (cssRule.cssText.startsWith(prefersColorSchemeDark)) {
  202. continue
  203. }
  204. }
  205. mediaRules = mediaRules.concat(Array.from(cssRule.cssRules))
  206. }
  207. // WARNING: do not try to insert a Rule to a styleSheet you are
  208. // currently iterating on, otherwise the browser will be stuck
  209. // in a infinite loop…
  210. for (const mediaRule of mediaRules) {
  211. styleSheet.insertRule(mediaRule.cssText)
  212. hasDarkRules = true
  213. }
  214. }
  215. if (hasDarkRules) {
  216. loadThemeForm('#theme-selector')
  217. }
  218. })
  219. </script>
  220. </body>
  221. </html>