A place to cache linked articles (think custom and personal wayback machine)
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

vor 2 Jahren
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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>Understanding UUIDs, ULIDs and String Representations (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. <!-- Documented, feel free to shoot an email. -->
  28. <link rel="stylesheet" href="/static/david/css/style_2021-01-20.css">
  29. <!-- See https://www.zachleat.com/web/comprehensive-webfonts/ for the trade-off. -->
  30. <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>
  31. <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>
  32. <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>
  33. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_regular.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  34. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_bold.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  35. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_italic.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  36. <script>
  37. function toggleTheme(themeName) {
  38. document.documentElement.classList.toggle(
  39. 'forced-dark',
  40. themeName === 'dark'
  41. )
  42. document.documentElement.classList.toggle(
  43. 'forced-light',
  44. themeName === 'light'
  45. )
  46. }
  47. const selectedTheme = localStorage.getItem('theme')
  48. if (selectedTheme !== 'undefined') {
  49. toggleTheme(selectedTheme)
  50. }
  51. </script>
  52. <meta name="robots" content="noindex, nofollow">
  53. <meta content="origin-when-cross-origin" name="referrer">
  54. <!-- Canonical URL for SEO purposes -->
  55. <link rel="canonical" href="https://sudhir.io/uuids-ulids">
  56. <body class="remarkdown h1-underline h2-underline h3-underline em-underscore hr-center ul-star pre-tick" data-instant-intensity="viewport-all">
  57. <article>
  58. <header>
  59. <h1>Understanding UUIDs, ULIDs and String Representations</h1>
  60. </header>
  61. <nav>
  62. <p class="center">
  63. <a href="/david/" title="Aller à l’accueil"><svg class="icon icon-home">
  64. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-home"></use>
  65. </svg> Accueil</a> •
  66. <a href="https://sudhir.io/uuids-ulids" title="Lien vers le contenu original">Source originale</a>
  67. </p>
  68. </nav>
  69. <hr>
  70. <p class="lead">What UUIDs and ULIDs are under the hood, and how to encode and use them.</p>
  71. <p>Database and data storage systems need identifiers for each piece of information they store. Using numbers as identifiers is a one way to do it, but that has limitations — and we have alternatives in the form of UUIDs and ULIDs.</p>
  72. <h2>Numbers</h2>
  73. <p>The easiest and most intuitive way to generate IDs is to use numbers. They're small, efficient and simple. In SQL databases like PostgreSQL, MySQL, SQL Server or Oracle, the numeric primary key is normally called <code>SERIAL</code> with an explicit or implicit size. The common sizes are 4 bytes, which corresponds to a 32 digit (or <em>32 bit</em>) binary number, capable of representing numbers from 0 to 2,147,483,647; and a bigger version (<code>BIGSERIAL</code>) at 8 bytes, or 64 bits, which can go from 0 to 9,223,372,036,854,775,807.</p>
  74. <p>That's the first problem right there. When using a numeric primary key, you need to be sure the size of key you're using is big enough. 2,147,483,647 looks like a big number, but in the context of modern web applications it's not that large. An application that serves a few hundred thousand people can quickly blow through that number, especially if it's being used to identify individual items, changes, or events.</p>
  75. <p>Using 8 bytes gives you more headroom to grow — 9,223,372,036,854,775,807 of anything is pretty hard to hit. Most frameworks will / should set this as the primary key default when creating databases for you, but it always helps to double-check. I've experienced and heard of many times where tables have run out of 32-bit space and engineers had to run upgrades and migrations at the worst possible time. </p>
  76. <p>How does a numeric ID work, though? And what are its limitations? The first thing to remember is that if a number is being used as an identifier it needs to be unique — which means some entity needs to keep track of which numbers have already been used and make sure they're never used again. In most database systems, this is done via the use of a <em>sequence</em> object. When adding a new piece of data, this sequence object is asked for a new number — it checks its storage to get last number it gave out, increments it, durably updates the new number in storage, and then gives it out. The most common type of sequence is a <em>monotonically increasing</em> sequence, which means that each time you ask the <em>sequence</em> object for a number it'll give you the previous number it gave out plus one.</p>
  77. <p>You might have noticed that when you asked for a number the sequence object stored the number first and then gave it out to you. Why would it do that? Why not give you the number and then store it? This is an important distinction — if the sequence didn't store the number first before giving it out to you, and it crashed before storing that number, it would give the same number out again the next time someone asked for one. This is a catastrophic failure — multiple consumers will have received the same number out of a sequence whose main job is to make sure no two consumers get the same number. This means that the sequence implementation must err on the side of caution — it must update the number first <em>before</em> it gives it out to you.</p>
  78. <p>But there's a downside to this approach — what if <em>you</em> crash <em>before</em> using the number that you got out of the sequence generator? When you restart and try your work again, you'll get a new number, incremented even if no other consumer is using this sequence. That number that you first pulled out and didn't use is lost forever. This is a common error with sequences — you can never assume that the highest number you see as an ID is implicitly the count of the number of items or rows. This <em>may</em> the case if nothing has ever gone wrong during the lifetime of the system, but that's pretty unlikely.</p>
  79. <p>Numeric sequences also have the disadvantage of being a separate entity from the datasets that they're being used in, making them <em>implicitly coupled</em>. You can copy a table over to a new database and forget to copy over the sequence generator object and its state, setting yourself up for an unexpected blowup. You might make the mistake of resetting the sequence generator to a number that's already been used (usually back to zero). Or your database backup/restore script might make the same mistakes. When you have coupling like this, there's a lot that can go wrong.</p>
  80. <p>Then there's <em>scalability</em> — this is something you don't often need, but if and when you do need it it's always too late for simple fixes. Having a single place where identifiers are generated means that you can add data only as fast as your sequence generator can reliably generate IDs. If you suddenly have a million people who want to buy things on your store, you can't ask them to wait because your sequence generator can't number their order line items fast enough. And because a sequence must store each number to disk before giving it out, your entire system is bottle-necked by the speed of rewriting a number on one SSD or hard disk — no matter how many servers you have.</p>
  81. <p>On a scaling-related note, numeric IDs limit your sharding options — if you're trying to split your workloads across multiple databases, you'll need to be careful to make sure that sequences can't overlap. You might make one shard's sequence run in even numbers, and another one run in odd numbers, for example; or more complex schemes when you have more shards.</p>
  82. <p>So numeric IDs are simple and work great in many situations, but remember that they're separate objects from the data you're storing but still always need to managed in tandem with your data; choosing a small size is likely to cause a crash when you least expect it; they look like counters but they're not; and they'll limit how fast you can add new data by their nature.</p>
  83. <h2>UUIDs</h2>
  84. <p>With the rise of distributed systems it became more and more important to have identifiers that could be created on multiple computers simultaneously, without forcing them to communicate with each other. This is necessary either because the systems are geographically independent, like databases that take orders in different countries and then merge them for global sales reporting, or because the rate of identifier creation required was greater than what could be supported by one sequence generator.</p>
  85. <p>The most common type of UUID or GUID in use today is a 128-bit (16-byte) number, generated at random. This means that under the <a href="https://tools.ietf.org/html/rfc4122">RFC 4122</a> specification, where 122 bits are generated randomly, it can represent a number up to to <code>5.3×10^36</code>. That's a lot of zeroes, and makes for a very large number — so large we consider it practically unreachable under any single application, or even the combination of all human applications. The new internet protocol address format, IPv6, is also essentially a 128 bit number given as a unique address to every possible internet connected object.</p>
  86. <p>Most database systems support UUIDs, and do so efficiently. The human readable standard representation of a UUID looks like <code>xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx</code> with <code>x</code> being the hexadecimal representation of a random byte and <code>M</code> and <code>N</code> representing version information. This looks like a long string, but most databases will internally support an efficient binary UUID type that maps onto a 16-byte array. It's also possible to use all the bits for randomness, if you don't care about conformance to the specification.</p>
  87. <p>This entire idea of using random IDs assumes that your computers can generate random numbers that are random and unpredictable — this isn't an easy problem, and there's a lot of research being done in the field. The <a href="https://www.cloudflare.com/en-in/learning/ssl/lava-lamp-encryption/">Cloudflare lava lamp project</a> is an interesting look into how to tap into a real-world source of randomness. Studies into the nature of random number generators in modern computers and operating systems is its own topic, and for now we'll just assume that all our systems are using state-of-the-art cryptographic random number generators.</p>
  88. <p>Using UUIDs then allows us to rise above some of the problems we saw with numeric IDs. Since there's no single authority or sequence generator in charge of a particular identifier, it becomes possible to generate identifiers for anything at a practically unlimited rate. There's also no problems with generating identifiers at multiple places simultaneously — there's no need for them to coordinate, so if you need more identifier generation capacity you can just add more hardware to handle the problem. Because these identifiers are independent, it's also possible to merge them into a single dataset later (asynchronously) without reasonably expecting any problems.</p>
  89. <p>That last sentence might have raised your eyebrows, though. What does “without reasonably expecting any problems” mean?. The issue with random IDs that it is remotely possible that the same ID may be generated more than once, even by the same system. If you're using a single system it may be possible to check the data and reject a duplicate ID, but if you're using multiple systems this won't be possible. The chances of this happening are extremely remote, though — similar to your chances of winning the lottery multiple times and immediately being struck by lightning each time — but they're not strictly zero. There's a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions">mathematical treatment on the Wikipedia page</a>, but the basic premise is that the more IDs you generate they more your probability of a duplicate ID, or a <em>collision</em>, increases. This probability is actually more than just the naive assumption that it's <code>1 / TOTAL_POSSIBLE_IDS</code> because of an interesting concept called the <em>birthday paradox</em>. The probability that a your birthday is the same as mine is <code>1/365</code>, but in a room of 30 people the probability that <em>any</em> two people have the same birthday <em>isn't</em> <code>1/365</code>, because the universe now has many more chances to get a match. The same things applies with UUIDs, because each UUID you generate has the chance to collide with every UUID ever generated in the history of your dataset. In practice, though, this isn't a problem. Most applications will ignore the these odds, and some may have a contingency in place to handle a collision, but will almost never actually experience one. </p>
  90. <p>The bigger problem with UUIDs is they have no concept of <em>locality</em>. With numeric IDs, we could examine the ID and reasonably assume that higher numbers were generated later than lower ones, and the highest ID is the last one generated. This also helps optimize indexes in some databases — additions are made only on one side of the index tree, so it's possible to optimize for that use case. In a completely random UUID system, though, IDs are being inserted with no concept of location at all. Any ID has an equal chance of being inserted anywhere in the spectrum of possibilities. This means that indexes become wasteful — they're usually made to order items neatly, but if you put UUIDs in them you're wasting any ordering capability, and mostly causing extra bloat and book-keeping that won't be used. Alternate <a href="https://www.postgresql.org/docs/current/hash-intro.html">indexes based on hashing</a> are excellent for UUIDs, though, but they're not as popular or optimized because they only offer fast lookup and no sorting.</p>
  91. <h2>ULIDs To The Rescue</h2>
  92. <p>So given the two major problems of UUIDs, which are 1) collision possibilities across the history of all generated IDs, and 2) complete loss of locality, can we do better? Yes, we can!</p>
  93. <p>Instead of using all the 128 bits for randomness, what if we use the first 48 bits for a timestamp? 48 bits is enough to represent a millisecond-precision Unix timestamp (the number of milliseconds since an <em>epoch</em> at the beginning of Jan 1, 1970) till the year 10889 AD. Given the way we're going, humanity in its present form isn't likely to exist them, so when this becomes an issue it'll be somebody else's problem. More likely <em>something</em> else's problem.</p>
  94. <p>The remaining 80 bits are available for randomness, which means they still represent a pretty large number: ~1,208,925,820,000,000,000,000,000. You get to generate this many IDs inside a <em>single millisecond</em>.</p>
  95. <p>At one stroke, this solves both the problems we have. An ID generated at a particular millisecond in the past can never collide with one generated in the future, so we only need to worry about collisions inside the same millisecond — which is to say the amount of worrying we need to do is a lot closer to zero. It also introduces <em>locality</em> into the ID, which means that IDs generated later will have higher byte values than those generated earlier. Assuming they're encoded with the proper alphabet, they'll also sort correctly. We'll come back to encoding later.</p>
  96. <p>This time-based ULID system continues to give us all the advantages of a UUID system—it can be distributed, because there's no single sequence authority, the IDs can be merged into a single dataset later, and there's an even lower chance of global collision, because collisions are only possible inside the same millisecond. And because they sort based on time, we can use them in append-only settings, where we can keep adding them to our dataset without having to re-balance indexes. The ULID format also allows continuous archiving of our data — because we know we're not going to receive any more data with identifiers lower than those representing a particular time, we can just archive all data in permanent storage each hour or day or week if we wanted to. It would still be possible to quickly find the data we need based on the timestamp prefix.</p>
  97. <h2>Words Matter</h2>
  98. <p>Speaking of prefixes, the way we represent our IDs makes a big difference. SQL database systems will usually have an optimized 16-byte representation internally, but most No-SQL systems work on strings. Strings also come into play when sending the IDs over JSON, XML or any other format over the wire. Let's look at a few common encoding options:</p>
  99. <p>To start with, we're working with a 128 bit binary number that looks like this:</p>
  100. <pre><code>11111111011110001010111001101011011100010111011001000110111010011000000111000110010010111110111001100000101110101000000110111011
  101. </code></pre>
  102. <p>Encodings work with bytes instead of bits, so let's see what our ID looks like when split into 8-bit chunks, or bytes:</p>
  103. <pre><code>[11111111, 01111000, 10101110, 01101011, 01110001, 01110110, 01000110, 11101001, 10000001, 11000110, 01001011, 11101110, 01100000, 10111010, 10000001, 10111011]
  104. </code></pre>
  105. <p>In decimal, or <code>base10</code>, this is really just a sequence of numbers between 0 and 255:</p>
  106. <pre><code>[255, 120, 174, 107, 113, 118, 70, 233, 129, 198, 75, 238, 96, 186, 129, 187]
  107. </code></pre>
  108. <p>The UUID spec uses hexadecimal characters to represent IDs. Each hexadecimal character represents 4 bits, so it can represent the binary number 0000 (decimal 0) to 1111 (decimal 16). Since we're dealing with a byte, we'll need two hexadecimal characters for each byte in the sequence:</p>
  109. <pre><code>["ff", "78", "ae", "6b", "71", "76", "46", "e9", "81", "c6", "4b", "ee", "60", "ba", "81", "bb"]
  110. </code></pre>
  111. <p>If we smash them all together we get <code>ff78ae6b717646e981c64bee60ba81bb</code>, and if we insert hyphens according to the <a href="https://tools.ietf.org/html/rfc4122">RFC 4122 spec</a> we get:</p>
  112. <pre><code>ff78ae6b-7176-46e9-81c6-4bee60ba81bb
  113. </code></pre>
  114. <p>But of course this isn't the only way to do it. We had to use two characters for each byte because the hexadecimal alphabet has only 16 characters, which are <code>0123456789abcdef</code>. But what if we use more characters? What if we exactly double our available alphabet, to <code>0123456789ABCDEFGHJKMNPQRSTVWXYZ</code>? Then we wind up with a more compact representation:</p>
  115. <pre><code>7ZF2Q6PWBP8VMR3HJBXSGBN0DV
  116. </code></pre>
  117. <p>This alphabet, <code>0123456789ABCDEFGHJKMNPQRSTVWXYZ</code>, is <a href="https://www.crockford.com/base32.html">Douglas Crockford's Base32</a>, chosen for human readability and being able to call it out over a phone if required. You'll see that ambiguous letters like I and L have been omitted because they can be confused with 1 — along with other considerations.</p>
  118. <p>This Base32 is what's used in the ULID format. In a ULID the first 48 bits are the timestamp, so here's what a ULID that I generated looks like:</p>
  119. <pre><code>01EWW6K6EXQDX5JV0E9CAHPXG5
  120. </code></pre>
  121. <p>In binary, that's</p>
  122. <pre><code>1011101110011100001101001100110011101110110111011011110100101100101101100000011100100101100010101000110110111011000000101
  123. </code></pre>
  124. <p>or <code>1948255503464693300277367552865957381</code> if we're just using decimal.</p>
  125. <p>Using the process above, we can always just turn this back into the UUID format:</p>
  126. <pre><code>01773869-99dd-bb7a-596c-0e4b151b7605
  127. </code></pre>
  128. <p>If you remember, the first 48 bits it a timestamp, and 48 bits is 6 bytes, and since each byte is written with two hexadecimal characters, the first 12 characters are the timestamp component: <code>0177386999dd</code>. Convert that to to decimal and you get 1611559180765 — which is the number of UTC milliseconds between Jan 1, 1970 and the time I generated this ID.</p>
  129. <p><strong><em>All this is to say that UUIDs and ULIDs are really just big numbers. We can write them however we want, making their string representations as small or as big as we want.</em></strong></p>
  130. <p>We could use <a href="https://en.wikipedia.org/wiki/Base64">base64</a>, for instance, and write the ID as <code>AXc4aZndu3pZbAAADksVGw</code>. Or we could <a href="https://gist.github.com/snikch/6969879"></a><a href="https://gist.github.com/snikch/6969879">go all in</a> on UTF-8 and use a 1,112,064 character alphabet, including emoji and symbols.</p>
  131. <p>My personal favourite alphabet is the <strong><em>lexicographic base62</em></strong>.: </p>
  132. <pre><code>0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
  133. </code></pre>
  134. <p>This contains every number and every uppercase and lowercase English alphabet, and no symbols. This means it's safe for URLs, and results in fairly short identifiers — but most importantly, it sorts correctly under ASCII and UTF-8 sorting. This means that you can encode ULIDs with this alphabet, and as long as you make sure all your IDs are the same length (you can left pad to a standard length with a zero), they'll string sort correctly.</p>
  135. <p>This is fantastic for NoSQL databases — your primary identifier can now act as a timestamp and natural sort, allowing you to do time range queries on a UUID primary key.</p>
  136. <p>This is one of my pet subjects, so here are a few tools I've built to help work with UUIDs and ULIDs:</p>
  137. <h3>References</h3>
  138. <h3>Other Formats</h3>
  139. <p>I wrote about UUIDs and ULIDs because they're compatible with each other and widely supported, but there some other options if you just need strings: </p>
  140. <h3>PS</h3>
  141. <p>New UUID formats are also being proposed: <a href="https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-01">https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-01</a></p>
  142. <p>There's a Hacker News discussion here: <a href="https://news.ycombinator.com/item?id=29794186">https://news.ycombinator.com/item?id=29794186</a></p>
  143. </article>
  144. <hr>
  145. <footer>
  146. <p>
  147. <a href="/david/" title="Aller à l’accueil"><svg class="icon icon-home">
  148. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-home"></use>
  149. </svg> Accueil</a> •
  150. <a href="/david/log/" title="Accès au flux RSS"><svg class="icon icon-rss2">
  151. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-rss2"></use>
  152. </svg> Suivre</a> •
  153. <a href="http://larlet.com" title="Go to my English profile" data-instant><svg class="icon icon-user-tie">
  154. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-user-tie"></use>
  155. </svg> Pro</a> •
  156. <a href="mailto:david%40larlet.fr" title="Envoyer un courriel"><svg class="icon icon-mail">
  157. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-mail"></use>
  158. </svg> Email</a> •
  159. <abbr class="nowrap" title="Hébergeur : Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33184162340"><svg class="icon icon-hammer2">
  160. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-hammer2"></use>
  161. </svg> Légal</abbr>
  162. </p>
  163. <template id="theme-selector">
  164. <form>
  165. <fieldset>
  166. <legend><svg class="icon icon-brightness-contrast">
  167. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-brightness-contrast"></use>
  168. </svg> Thème</legend>
  169. <label>
  170. <input type="radio" value="auto" name="chosen-color-scheme" checked> Auto
  171. </label>
  172. <label>
  173. <input type="radio" value="dark" name="chosen-color-scheme"> Foncé
  174. </label>
  175. <label>
  176. <input type="radio" value="light" name="chosen-color-scheme"> Clair
  177. </label>
  178. </fieldset>
  179. </form>
  180. </template>
  181. </footer>
  182. <script src="/static/david/js/instantpage-5.1.0.min.js" type="module"></script>
  183. <script>
  184. function loadThemeForm(templateName) {
  185. const themeSelectorTemplate = document.querySelector(templateName)
  186. const form = themeSelectorTemplate.content.firstElementChild
  187. themeSelectorTemplate.replaceWith(form)
  188. form.addEventListener('change', (e) => {
  189. const chosenColorScheme = e.target.value
  190. localStorage.setItem('theme', chosenColorScheme)
  191. toggleTheme(chosenColorScheme)
  192. })
  193. const selectedTheme = localStorage.getItem('theme')
  194. if (selectedTheme && selectedTheme !== 'undefined') {
  195. form.querySelector(`[value="${selectedTheme}"]`).checked = true
  196. }
  197. }
  198. const prefersColorSchemeDark = '(prefers-color-scheme: dark)'
  199. window.addEventListener('load', () => {
  200. let hasDarkRules = false
  201. for (const styleSheet of Array.from(document.styleSheets)) {
  202. let mediaRules = []
  203. for (const cssRule of styleSheet.cssRules) {
  204. if (cssRule.type !== CSSRule.MEDIA_RULE) {
  205. continue
  206. }
  207. // WARNING: Safari does not have/supports `conditionText`.
  208. if (cssRule.conditionText) {
  209. if (cssRule.conditionText !== prefersColorSchemeDark) {
  210. continue
  211. }
  212. } else {
  213. if (cssRule.cssText.startsWith(prefersColorSchemeDark)) {
  214. continue
  215. }
  216. }
  217. mediaRules = mediaRules.concat(Array.from(cssRule.cssRules))
  218. }
  219. // WARNING: do not try to insert a Rule to a styleSheet you are
  220. // currently iterating on, otherwise the browser will be stuck
  221. // in a infinite loop…
  222. for (const mediaRule of mediaRules) {
  223. styleSheet.insertRule(mediaRule.cssText)
  224. hasDarkRules = true
  225. }
  226. }
  227. if (hasDarkRules) {
  228. loadThemeForm('#theme-selector')
  229. }
  230. })
  231. </script>
  232. </body>
  233. </html>