A place to cache linked articles (think custom and personal wayback machine)
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.html 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 Future of Web Software Is HTML-over-WebSockets (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://alistapart.com/article/the-future-of-web-software-is-html-over-websockets/">
  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>The Future of Web Software Is HTML-over-WebSockets</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://alistapart.com/article/the-future-of-web-software-is-html-over-websockets/" title="Lien vers le contenu original">Source originale</a>
  67. </p>
  68. </nav>
  69. <hr>
  70. <p>The future of web-based software architectures is already taking form, and this time it’s server-rendered (again). Papa’s got a brand new bag: HTML-over-WebSockets and broadcast everything all the time.</p>
  71. <p>The dual approach of marrying a Single Page App with an API service has left many dev teams mired in endless JSON wrangling and state discrepancy bugs across two layers. This costs dev time, slows release cycles, and saps the bandwidth for innovation.</p>
  72. <p>But a new WebSockets-driven approach is catching web developers’ attention. One that reaffirms the promises of classic server-rendered frameworks: fast prototyping, server-side state management, solid rendering performance, rapid feature development, and straightforward SEO. One that enables multi-user collaboration and reactive, responsive designs <em>without building two separate apps</em>. The end result is a single-repo application that feels to users just as responsive as a client-side all-JavaScript affair, but with straightforward templating and far fewer loading spinners, and no state misalignments, since state only lives in one place. All of this sets us up for a considerably easier (and faster!) development path. </p>
  73. <p>Reclaiming all of that time spent addressing architecture difficulties grants you a pool of surplus hours that you can use to do awesome. Spend your dev budget, and your company’s salary budget, happily building full-stack features yourself, and innovating on things that benefit your company and customers. </p>
  74. <p>And in my opinion, there’s no better app framework for reclaiming tedious development time than Ruby on Rails. Take another look at the underappreciated Stimulus. Beef up the View in your MVC with ViewComponents. Add in the <a href="https://cableready.stimulusreflex.com/">CableReady</a> and <a href="https://docs.stimulusreflex.com/">StimulusReflex</a> libraries for that Reactive Rails (as it has been dubbed) new car smell, and you’re off to the races. But we’ll get back to Rails in a bit…</p>
  75. <h2 id="section2">This all started with web frameworks…<a class="subhead-anchor" href="#section2">#section2</a></h2>
  76. <p>Web frameworks burst onto the scene around 2005 amidst a sea of mostly figure-it-out-for-yourself scripting language libraries glued together and thrown onto hand-maintained Apache servers. This new architecture promised developers a more holistic approach that wrapped up all the fiddly stuff in no-touch conventions, freeing developers to focus on programming ergonomics, code readability, and fast-to-market features. All a developer had to do was learn the framework’s core language, get up to speed on the framework itself and its conventions, and then start churning out sophisticated web apps while their friends were still writing XML configuration files for all those <em>other</em> approaches.</p>
  77. <p>Despite the early criticisms that always plague new approaches, these server-rendered frameworks became tools of choice, especially for fast-moving startups—strapped for resources—that needed an attractive, feature-rich app up <em>yesterday</em>.</p>
  78. <h2 id="section3">But then the <em>JavaScript everything</em> notion took hold…<a class="subhead-anchor" href="#section3">#section3</a></h2>
  79. <p>As the web development world pushed deeper into the 2010s, the tides began to turn, and server-rendered frameworks took something of a backseat to the Single Page Application, wholly built in JavaScript and run entirely on the client’s computer. At many companies, the “server” became relegated to hosting an API data service only, with most of the business logic and all of the HTML rendering happening on the client, courtesy of the big ’ol package of JavaScript that visitors were forced to download when they first hit the site. </p>
  80. <p>This is where things started to get ugly.</p>
  81. <p>Fast-forward to 2020 and the <a href="https://www.nngroup.com/articles/the-need-for-speed/">web isn’t getting any faster</a>, as we were promised it would with SPAs. Shoving megabytes of JavaScript down an iPhone 4’s throat doesn’t make for a great user experience. And if you thought building a professional web app took serious resources, what about building a web app <em>and</em> an API service <em>and</em> a communication layer between them? Do we really believe that every one of our users is going to have a device capable of digesting 100 kB of JSON and rendering a complicated HTML table <em>faster</em> than a server-side app could on even a mid-grade server?</p>
  82. <p>Developing and hosting these JavaScript-forward apps didn’t get any cheaper either. In many cases we’re now doing twice the work, and maybe even paying twice the developers, to achieve the same results we had before with server-side app development.</p>
  83. <p>In 2005, app frameworks blew everyone’s minds with “build a blog app in 15 minutes” videos. Fifteen years <em>later</em>, doing the same thing with an SPA approach can require two codebases, a JSON serialization layer, and dozens of spinners all over the place so we can still claim a 50ms First Contentful Paint. Meanwhile, the user watches some blank gray boxes, hoping for HTML to finally render from all the JSON their browser is requesting and digesting. </p>
  84. <p>How did we get here? This is not my beautiful house! Were we smart in giving up all of that server-rendered <em>developer happiness</em> and doubling down on staff and the time to implement in order to chase the promise of providing our users some fancier user interfaces?</p>
  85. <p>Well. Yes. Sort of.</p>
  86. <p>We’re not building web software for <em>us</em>. We’re building it for <em>them</em>. The users of our software have expectations of how it’s going to work for <em>them</em>. We have to meet them where they are. Our users are no longer excited about full-page refreshes and ugly Rube Goldberg-ian multi-form workflows. The SPA approach was the next logical leap from piles of unorganized spaghetti JavaScript living on the server. The problem, though: it was a 5% improvement, not a 500% improvement. </p>
  87. <h2 id="section4">Is 5% better worth twice the work? What about the developer cost?<a class="subhead-anchor" href="#section4">#section4</a></h2>
  88. <p>Bedazzling the web app certainly makes things <em>fancier</em> from the user’s perspective. Done well, it can make the app feel slicker and more interactive, and it opens up a wealth of new non-native interaction elements. Canonizing those elements as <em>components</em> was the next natural evolution. Gone are the days of thinking through how an entire HTML document could be mutated to give the <em>illusion</em> of the user interacting with an atomic widget on the page—now, that can be implemented directly, and we can think about our UX in terms of component breakdowns. But, alas, the costs begin to bite us almost immediately.</p>
  89. <p>Go ahead, write that slick little rating stars component. Add some cool animations, make the mouseover and click area feel good, give some endorphin-generating feedback when a selection is made. But now what? In a real app, we need to <em>persist</em> that change, right? The database has to be changed to reflect this new state, and the app in front of the user’s eyes needs to reflect that new reality too. </p>
  90. <p>In the old days, we’d give the user a couple star GIFs, each a link that hit the same server endpoint with a different param value. Server-side, we’d save that change to the database, then send back a whole new HTML page for their browser to re-render; maybe we’d even get fancy and use AJAX to do it <em>behind the scenes</em>, obviating the need for the full HTML and render. Let’s say the former costs <em>x</em> in developer time and salary (and we won’t even talk about lost opportunity cost for features rolled out too late for the market). In that case, the fancy AJAX-based approach costs <em>x</em> + <em>n (you know, some “extra JavaScript sprinkles”)</em>, but the cost of lots and lots of <em>n</em> grows as our app becomes more and more of a JavaScript spaghetti sprinkles mess.</p>
  91. <p>Over in the SPA world, we’re now writing JavaScript in the client-side app and using JSX or Handlebars templates to render the component, then code to persist that change to the front-end data store, then a PUT request to the API, where we’re also writing an API endpoint to handle the request, a JSON serializer (probably with its own pseudo-template) to package up our successful response, and then front-end code to ensure we re-render the component (and some branching logic to maybe rollback and re-render the client-side state change if the backend failed on us). This costs a lot more than even <em>x + n </em>in developer time and salary. And if you’ve split your team into “front-end” and “back-end” people, you might as well go ahead and double <em>that</em> cost (both time and money) for many non-trivial components where you need two different people to finish the implementation. Sure, the SPA mitigates some of the ever-growing spaghetti problem, but at what cost for a business racing to be relevant in the market or get something important out to the people who need it?</p>
  92. <p>One of the other arguments we hear in support of the SPA is the reduction in cost of cyber infrastructure. As if pushing that hosting burden onto the client (without their consent, for the most part, but that’s another topic) is somehow saving us on our cloud bills. But that’s ridiculous. For any non-trivial application, you’re still paying for a server to host the API and maybe another for the database, not to mention load balancers, DNS, etc. And here’s the thing: <em>none of that cost even comes close to what a software company pays its developers!</em> Seriously, think about it. I’ve yet to work at any business where our technical infrastructure was anything more than a fraction of our salary overhead. And good developers expect raises. Cloud servers generally just get <em>cheaper</em> over time.</p>
  93. <p>If you want to be efficient with your money—especially as a cash-strapped startup—you don’t need to cheap out on cloud servers; you need to get <em>more features faster out of your existing high-performance team</em>.</p>
  94. <p>In the old, old days, before the web frameworks, you’d pay a developer for six weeks to finally unveil…the log-in page. Cue the sad trombone. Then frameworks made that log-in page an hour of work, total, and people were launching web startups overnight. The trumpets sound! Now, with our SPA approach, we’re back to a bunch of extra work. <em>It’s costing us more money because we’re writing two apps at once</em>. There’s that trombone again…</p>
  95. <p>We’re paying a lot of money for that 5% user experience improvement.</p>
  96. <p>But what if we could take the best client-side JavaScript ideas and libraries from that 5% improvement and reconnect them with the developer ergonomics and salary savings of a single codebase? What if components and organized JavaScript could all live in one rock-solid app framework optimized for server-side rendering? What if there <em>is</em> a path to a 500% jump?</p>
  97. <p>Sound impossible? It’s not. I’ve seen it, like C-beams glittering in the dark near the Tannhäuser Gate. I’ve built that 500% app, in my free time, with my kids running around behind me barking like dogs. Push broadcasts to logged-in users. Instant updates to the client-side DOM in milliseconds. JavaScript-driven 3D animations that interact with real-time chat windows. All in a single codebase, running on the same server hardware I’d use for a “classic” server-rendered app (and maybe I can even scale that hardware down since I’m rendering HTML fragments more often than full-page documents). No separate front-end app. Clean, componentized JavaScript and server-side code, married like peanut butter and jelly. It’s real, I tell you!</p>
  98. <h2 id="section5">Socket to me! (Get it? Get it? Ah, nevermind…)<a class="subhead-anchor" href="#section5">#section5</a></h2>
  99. <p>Finalized in 2011, support for WebSockets in modern browsers ramped up throughout the 2010s and is now fully supported in all modern browsers. With the help of a small bit of client-side JavaScript, you get a <a href="https://en.wikipedia.org/wiki/Duplex_(telecommunications)#FULL-DUPLEX">full-duplex</a> socket connection between browser and server. Data can pass both ways, and can be pushed from either side at any time, no user-initiated request needed.</p>
  100. <p>Like the game industry’s ever-expanding moves into cloud-based gaming, the future of web apps is not going to be about pushing even heavier obligations onto the user/client, but rather the opposite: let the client act as a thin terminal that renders the state of things for the human. WebSockets provide the communication layer, seamless and fast; a direct shot from the server to the human.</p>
  101. <p>But this wasn’t terribly easy for many developers to grok at first. I sure didn’t. And the benefits weren’t exactly clear either. After years (decades, even) of wrapping our heads around the HTTP request cycle, to which all server-handled features must conform, adopting this WebSocket tech layer required a lot of head scratching. As with many clever new technologies or protocols, we needed a higher-level abstraction that provided something really effective for getting a new feature in front of a user, fast.</p>
  102. <h2 id="section6">Enter HTML-over-WebSockets…<a class="subhead-anchor" href="#section6">#section6</a></h2>
  103. <p>Want a hyper-responsive datalist typeahead that is perfectly synced with the database? On every keystroke, send a query down the WebSocket and get back <em>precisely</em> the changed set of <strong>option</strong> tags, nothing more, nothing less.</p>
  104. <p>How about client-side validations? Easy. On every input change, round up the form values and send ’em down the WebSocket. Let your server framework validate and send back changes to the HTML of the form, including any errors that need to be rendered. No need for JSON or complicated error objects.</p>
  105. <p>User presence indicators? Dead simple. Just check who has an active socket connection.</p>
  106. <p>What about multi-user chat? Or document collaboration? In classic frameworks and SPAs, these are the features we put off because of their difficulty and the code acrobatics needed to keep everyone’s states aligned. With HTML-over-the-wire, we’re just pushing tiny bits of HTML based on one user’s changes to <em>every other</em> <em>user</em> currently subscribed to the channel. They’ll see <em>exactly</em> the same thing as if they hit refresh and asked the server for the entire HTML page anew. And you can get those bits to every user in under 30ms.</p>
  107. <p>We’re not throwing away the promise of components either. Where this WebSockets-based approach can be seen as a thick server/thin client, so too can our components. It’s fractal, baby! Make that component <em>do</em> delightful things for the user with smart JavaScript, and then just ask the server for updated HTML, and mutate the DOM. No need for a client-side data store to manage the component’s state since it’ll render itself to look <em>exactly like what the server knows it should look like now</em>. The HTML comes from the server, so no need for JSX or Handlebars or &lt;insert other JavaScript templating library here&gt;. The server is always in control: rendering the initial component’s appearance <em>and</em> updating it in response to any state change, all through the socket. </p>
  108. <p>And there’s nothing saying you have to use those socket channels to send <em>only</em> HTML. Send a tiny bit of text, and have the client do something smart. Send a chat message from one user to every other user, and have their individual clients render that message in whatever app theme they’re currently using. Imagine the possibilities!</p>
  109. <h2 id="section7">But it’s complex/expensive/requires a bunch of new infrastructure, right?<a class="subhead-anchor" href="#section7">#section7</a></h2>
  110. <p>Nope. Prominent open-source web servers support it natively, generally without needing any kind of extra configuration or setup. Many server-side frameworks will automatically ship the JS code to the client for native support in communicating over the socket. In Rails, for example, setting up your app to use WebSockets is as easy as configuring the built-in ActionCable and then deploying as usual on the same hardware you would have used otherwise. Anecdotally, the typical single Rails server process seems to be perfectly happy supporting nearly 4,000 active connections. And you can easily swap in the excellent <a href="https://docs.anycable.io">AnyCable</a> to bump that up to around 10,000+ connections per node by not relying on the built-in Ruby WebSocket server. Again, this is on the usual hardware you’d be running your web server on in the first place. You don’t need to set up any extra hardware or increase your cloud infrastructure.</p>
  111. <p>This new approach is quickly appearing as extensions, libraries, or alternative configurations in a variety of languages and web frameworks, from Django’s <a href="https://sockpuppet.argpar.se">Sockpuppet</a> to Phoenix’s <a href="https://dockyard.com/blog/2018/12/12/phoenix-liveview-interactive-real-time-apps-no-need-to-write-javascript">LiveView</a> and beyond. Seriously, go dig around for WebSockets-based libraries for your favorite app framework and then step into a new way of thinking about your app architectures. Build something amazing and marvel at the glorious HTML bits zipping along on the socket, like jet fighters passing in the night. It’s more than a new technical approach; it’s a new mindset, and maybe even a new wellspring of key app features that will drive your startup success.</p>
  112. <p>But I’d be remiss if I didn’t highlight for the reader <em>my </em>contender for Best Framework in a Leading Role. Sure, any app framework can adopt this approach, but for my money, there’s a strong case to be made that the vanguard could be Ruby on Rails. </p>
  113. <h2 id="section8">So we come back around to Rails, 15 years on from its launch…<a class="subhead-anchor" href="#section8">#section8</a></h2>
  114. <p>Set up a Rails 6 app with the latest versions of <a href="https://github.com/turbolinks/turbolinks">Turbolinks</a>, <a href="https://stimulus.hotwire.dev">Stimulus</a>, <a href="https://docs.stimulusreflex.com">StimulusReflex</a>, <a href="https://cableready.stimulusreflex.com">CableReady</a>, and GitHub’s <a href="https://github.com/github/view_component">ViewComponent</a> gem, and you can be working with Reactive Rails in a way that simultaneously feels like building a classic Rails app <em>and </em>like building a modern, componentized SPA, in a single codebase, with all the benefits of server-side rendering, HTML fragment caching, easy SEO, rock-solid security, and the like. You’ll suddenly find your toolbelt bursting with straightforward tools to solve previously daunting challenges.</p>
  115. <p>Oh, and with Turbolinks, you also get wrappers allowing for hybrid native/HTML UIs in the same codebase. Use a quick deploy solution like Heroku or Hatchbox, and one developer can build a responsive, reactive, multi-platform app in their spare time. Just see <a href="https://dev.to/julianrubisch/twitter-clone-with-stimulusreflex-gone-hybrid-native-app-17fm">this Twitter clone</a> if you don’t believe me. </p>
  116. <p>OK, that all sounds exciting, but why Rails specifically? Isn’t it old and boring? You already said any framework can benefit from this new WebSocket, DOM-morphing approach, right? </p>
  117. <p>Sure. But where Rails has always shined is in its ability to make rapid prototyping, well…<em>rapid</em>, and in its deep ecosystem of well-polished gems. Rails also hasn’t stopped pushing the envelope forward, with the latest version 6.1.3 of the framework boasting a ton of cool features. </p>
  118. <p>If you’ve got a small, resource-strapped team, Rails (and Ruby outside of the framework) still serves as a potent force multiplier that lets you punch way above your weight, which probably explains the <a href="https://charliereese.ca/article/top-50-y-combinator-tech-startups">$92 billion in revenue it’s helped drive over the years</a>. With this new approach, there’s a <em>ton</em> more weight behind that punch. While your competitors are fiddling with their JSON serializers and struggling to optimize away all the loading spinners, you’re rolling out a new multi-user collaborative feature every week…or every <em>day</em>. </p>
  119. <p>You win. Your fellow developers win. Your business wins. And, most importantly, your <em>users</em> win.</p>
  120. <p>That’s what Rails promised from the day it was released to the community. That’s why Rails spawned so many imitators in other languages, and why it saw such explosive growth in the startup world for years. And that same old rapid prototyping spirit, married to this new HTML-over-the-wire approach, positions Rails for a powerful resurgence. </p>
  121. <p>Ruby luminary and <a href="https://www.amazon.com/Obie-Fernandez/e/B001IGV0LS">author</a> of <em>The Ruby Way</em>, Obie Fernandez, <a href="https://medium.com/@obie/react-is-dead-long-live-reactive-rails-long-live-stimulusreflex-and-viewcomponent-cd061e2b0fe2">seems to think so</a>.</p>
  122. <p>Heck, even <a href="https://www.youtube.com/watch?v=utxCm3uLhIE">Russ Hanneman thinks this approach with StimulusReflex is the new hotness</a>.</p>
  123. <p>And the good folks over at Basecamp (creators of Rails in the first place), dropped their own take on the concept, <a href="https://hotwire.dev">Hotwire</a>, just in time for the 2020 holidays, so your options for tackling this new and exciting technique continue to expand.</p>
  124. <p>Don’t call it a comeback, because Rails has been here for years. With this new architectural approach, brimming with HTML-over-WebSockets and full-duplex JavaScript interactions, Rails becomes something new, something beautiful, something that demands attention (again). </p>
  125. <p>Reactive Rails, with StimulusReflex and friends, is a must-look for anyone exhausted from toiling with JSON endpoints or JSX, and I’m super excited to see the new crop of apps that it enables.</p>
  126. </article>
  127. <hr>
  128. <footer>
  129. <p>
  130. <a href="/david/" title="Aller à l’accueil"><svg class="icon icon-home">
  131. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-home"></use>
  132. </svg> Accueil</a> •
  133. <a href="/david/log/" title="Accès au flux RSS"><svg class="icon icon-rss2">
  134. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-rss2"></use>
  135. </svg> Suivre</a> •
  136. <a href="http://larlet.com" title="Go to my English profile" data-instant><svg class="icon icon-user-tie">
  137. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-user-tie"></use>
  138. </svg> Pro</a> •
  139. <a href="mailto:david%40larlet.fr" title="Envoyer un courriel"><svg class="icon icon-mail">
  140. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-mail"></use>
  141. </svg> Email</a> •
  142. <abbr class="nowrap" title="Hébergeur : Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33184162340"><svg class="icon icon-hammer2">
  143. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-hammer2"></use>
  144. </svg> Légal</abbr>
  145. </p>
  146. <template id="theme-selector">
  147. <form>
  148. <fieldset>
  149. <legend><svg class="icon icon-brightness-contrast">
  150. <use xlink:href="/static/david/icons2/symbol-defs-2021-12.svg#icon-brightness-contrast"></use>
  151. </svg> Thème</legend>
  152. <label>
  153. <input type="radio" value="auto" name="chosen-color-scheme" checked> Auto
  154. </label>
  155. <label>
  156. <input type="radio" value="dark" name="chosen-color-scheme"> Foncé
  157. </label>
  158. <label>
  159. <input type="radio" value="light" name="chosen-color-scheme"> Clair
  160. </label>
  161. </fieldset>
  162. </form>
  163. </template>
  164. </footer>
  165. <script src="/static/david/js/instantpage-5.1.0.min.js" type="module"></script>
  166. <script>
  167. function loadThemeForm(templateName) {
  168. const themeSelectorTemplate = document.querySelector(templateName)
  169. const form = themeSelectorTemplate.content.firstElementChild
  170. themeSelectorTemplate.replaceWith(form)
  171. form.addEventListener('change', (e) => {
  172. const chosenColorScheme = e.target.value
  173. localStorage.setItem('theme', chosenColorScheme)
  174. toggleTheme(chosenColorScheme)
  175. })
  176. const selectedTheme = localStorage.getItem('theme')
  177. if (selectedTheme && selectedTheme !== 'undefined') {
  178. form.querySelector(`[value="${selectedTheme}"]`).checked = true
  179. }
  180. }
  181. const prefersColorSchemeDark = '(prefers-color-scheme: dark)'
  182. window.addEventListener('load', () => {
  183. let hasDarkRules = false
  184. for (const styleSheet of Array.from(document.styleSheets)) {
  185. let mediaRules = []
  186. for (const cssRule of styleSheet.cssRules) {
  187. if (cssRule.type !== CSSRule.MEDIA_RULE) {
  188. continue
  189. }
  190. // WARNING: Safari does not have/supports `conditionText`.
  191. if (cssRule.conditionText) {
  192. if (cssRule.conditionText !== prefersColorSchemeDark) {
  193. continue
  194. }
  195. } else {
  196. if (cssRule.cssText.startsWith(prefersColorSchemeDark)) {
  197. continue
  198. }
  199. }
  200. mediaRules = mediaRules.concat(Array.from(cssRule.cssRules))
  201. }
  202. // WARNING: do not try to insert a Rule to a styleSheet you are
  203. // currently iterating on, otherwise the browser will be stuck
  204. // in a infinite loop…
  205. for (const mediaRule of mediaRules) {
  206. styleSheet.insertRule(mediaRule.cssText)
  207. hasDarkRules = true
  208. }
  209. }
  210. if (hasDarkRules) {
  211. loadThemeForm('#theme-selector')
  212. }
  213. })
  214. </script>
  215. </body>
  216. </html>