Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
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.

recherche.html 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. {% extends "base_2020.html" %}
  2. {% block lang %}fr{% endblock %}
  3. {% block title %}Recherche{% endblock %}
  4. {% block description %}Voici l’espace personnel de David Larlet sur le Web.{% endblock %}
  5. {% block content %}
  6. <article>
  7. <header>
  8. <h1>Recherche</h1>
  9. </header>
  10. <nav>
  11. <p class="center">
  12. <nobr>
  13. <a href="/david/" title="Aller à l’accueil">
  14. <svg class="icon icon-home">
  15. <use xlink:href="/static/david/icons2/symbol-defs-2022-03.svg#icon-home"></use>
  16. </svg>
  17. Accueil</a>
  18. </nobr>
  19. </p>
  20. </nav>
  21. <hr>
  22. <form action="https://duckduckgo.com/" method="get" id="form-search">
  23. <label for="input-search">Termes de votre recherche :</label>
  24. <input type="search" name="q" id="input-search" required>
  25. <input type="hidden" name="sites" value="larlet.fr">
  26. <button>Chercher</button>
  27. <button type="reset">Annuler</button>
  28. </form>
  29. <p id="search-status" role="status"></p>
  30. <div id="search-results"></div>
  31. <hr>
  32. <p>
  33. Seuls les écrits de ces dernières années sont indexés.
  34. Vous pouvez aussi consulter les archives chronologiques de
  35. <a href="/david/2023/">2023</a>,
  36. <a href="/david/2022/">2022</a>,
  37. <a href="/david/2021/">2021</a>,
  38. <a href="/david/2020/">2020</a>,
  39. <a href="/david/blog/">etc</a>.
  40. </p>
  41. {% endblock content %}
  42. {% block extra_body %}
  43. <template id="search-result">
  44. <h2>
  45. <a href="${url}">${title}</a> (${date})
  46. </h2>
  47. <p>${content}</p>
  48. </template>
  49. {# djlint:off #}
  50. <script id="search-index" type="application/json">{{ search_index }}</script>
  51. {# djlint:on #}
  52. <!-- French stopwords from https://github.com/stopwords-iso/stopwords-fr -->
  53. <script id="search-stop-words" type="application/json">
  54. [
  55. "a", "abord", "absolument", "afin", "ah", "ai", "aie", "aient", "aies",
  56. "ailleurs", "ainsi", "ait", "allaient", "allo", "allons", "allô",
  57. "alors", "anterieur", "anterieure", "anterieures", "apres", "après",
  58. "as", "assez", "attendu", "au", "aucun", "aucune", "aucuns", "aujourd",
  59. "aujourd'hui", "aupres", "auquel", "aura", "aurai", "auraient", "aurais",
  60. "aurait", "auras", "aurez", "auriez", "aurions", "aurons", "auront",
  61. "aussi", "autant", "autre", "autrefois", "autrement", "autres", "autrui",
  62. "aux", "auxquelles", "auxquels", "avaient", "avais", "avait", "avant",
  63. "avec", "avez", "aviez", "avions", "avoir", "avons", "ayant", "ayez",
  64. "ayons", "b", "bah", "bas", "basee", "bat", "beau", "beaucoup", "bien",
  65. "bigre", "bon", "boum", "bravo", "brrr", "c", "car", "ce", "ceci",
  66. "cela", "celle", "celle-ci", "celle-là", "celles", "celles-ci",
  67. "celles-là", "celui", "celui-ci", "celui-là", "celà", "cent",
  68. "cependant", "certain", "certaine", "certaines", "certains", "certes",
  69. "ces", "cet", "cette", "ceux", "ceux-ci", "ceux-là", "chacun", "chacune",
  70. "chaque", "cher", "chers", "chez", "chiche", "chut", "chère", "chères",
  71. "ci", "cinq", "cinquantaine", "cinquante", "cinquantième", "cinquième",
  72. "clac", "clic", "combien", "comme", "comment", "comparable",
  73. "comparables", "compris", "concernant", "contre", "couic", "crac", "d",
  74. "da", "dans", "de", "debout", "dedans", "dehors", "deja", "delà",
  75. "depuis", "dernier", "derniere", "derriere", "derrière", "des",
  76. "desormais", "desquelles", "desquels", "dessous", "dessus", "deux",
  77. "deuxième", "deuxièmement", "devant", "devers", "devra", "devrait",
  78. "different", "differentes", "differents", "différent", "différente",
  79. "différentes", "différents", "dire", "directe", "directement", "dit",
  80. "dite", "dits", "divers", "diverse", "diverses", "dix", "dix-huit",
  81. "dix-neuf", "dix-sept", "dixième", "doit", "doivent", "donc", "dont",
  82. "dos", "douze", "douzième", "dring", "droite", "du", "duquel", "durant",
  83. "dès", "début", "désormais", "e", "effet", "egale", "egalement",
  84. "egales", "eh", "elle", "elle-même", "elles", "elles-mêmes", "en",
  85. "encore", "enfin", "entre", "envers", "environ", "es", "essai", "est",
  86. "et", "etant", "etc", "etre", "eu", "eue", "eues", "euh", "eurent",
  87. "eus", "eusse", "eussent", "eusses", "eussiez", "eussions", "eut", "eux",
  88. "eux-mêmes", "exactement", "excepté", "extenso", "exterieur", "eûmes",
  89. "eût", "eûtes", "f", "fais", "faisaient", "faisant", "fait", "faites",
  90. "façon", "feront", "fi", "flac", "floc", "fois", "font", "force",
  91. "furent", "fus", "fusse", "fussent", "fusses", "fussiez", "fussions",
  92. "fut", "fûmes", "fût", "fûtes", "g", "gens", "h", "ha", "haut", "hein",
  93. "hem", "hep", "hi", "ho", "holà", "hop", "hormis", "hors", "hou", "houp",
  94. "hue", "hui", "huit", "huitième", "hum", "hurrah", "hé", "hélas", "i",
  95. "ici", "il", "ils", "importe", "j", "je", "jusqu", "jusque", "juste",
  96. "k", "l", "la", "laisser", "laquelle", "las", "le", "lequel", "les",
  97. "lesquelles", "lesquels", "leur", "leurs", "longtemps", "lors",
  98. "lorsque", "lui", "lui-meme", "lui-même", "là", "lès", "m", "ma",
  99. "maint", "maintenant", "mais", "malgre", "malgré", "maximale", "me",
  100. "meme", "memes", "merci", "mes", "mien", "mienne", "miennes", "miens",
  101. "mille", "mince", "mine", "minimale", "moi", "moi-meme", "moi-même",
  102. "moindres", "moins", "mon", "mot", "moyennant", "multiple", "multiples",
  103. "même", "mêmes", "n", "na", "naturel", "naturelle", "naturelles", "ne",
  104. "neanmoins", "necessaire", "necessairement", "neuf", "neuvième", "ni",
  105. "nombreuses", "nombreux", "nommés", "non", "nos", "notamment", "notre",
  106. "nous", "nous-mêmes", "nouveau", "nouveaux", "nul", "néanmoins", "nôtre",
  107. "nôtres", "o", "oh", "ohé", "ollé", "olé", "on", "ont", "onze",
  108. "onzième", "ore", "ou", "ouf", "ouias", "oust", "ouste", "outre",
  109. "ouvert", "ouverte", "ouverts", "o|", "où", "p", "paf", "pan", "par",
  110. "parce", "parfois", "parle", "parlent", "parler", "parmi", "parole",
  111. "parseme", "partant", "particulier", "particulière", "particulièrement",
  112. "pas", "passé", "pendant", "pense", "permet", "personne", "personnes",
  113. "peu", "peut", "peuvent", "peux", "pff", "pfft", "pfut", "pif", "pire",
  114. "pièce", "plein", "plouf", "plupart", "plus", "plusieurs", "plutôt",
  115. "possessif", "possessifs", "possible", "possibles", "pouah", "pour",
  116. "pourquoi", "pourrais", "pourrait", "pouvait", "prealable",
  117. "precisement", "premier", "première", "premièrement", "pres", "probable",
  118. "probante", "procedant", "proche", "près", "psitt", "pu", "puis",
  119. "puisque", "pur", "pure", "q", "qu", "quand", "quant", "quant-à-soi",
  120. "quanta", "quarante", "quatorze", "quatre", "quatre-vingt", "quatrième",
  121. "quatrièmement", "que", "quel", "quelconque", "quelle", "quelles",
  122. "quelqu'un", "quelque", "quelques", "quels", "qui", "quiconque",
  123. "quinze", "quoi", "quoique", "r", "rare", "rarement", "rares",
  124. "relative", "relativement", "remarquable", "rend", "rendre", "restant",
  125. "reste", "restent", "restrictif", "retour", "revoici", "revoilà", "rien",
  126. "s", "sa", "sacrebleu", "sait", "sans", "sapristi", "sauf", "se", "sein",
  127. "seize", "selon", "semblable", "semblaient", "semble", "semblent",
  128. "sent", "sept", "septième", "sera", "serai", "seraient", "serais",
  129. "serait", "seras", "serez", "seriez", "serions", "serons", "seront",
  130. "ses", "seul", "seule", "seulement", "si", "sien", "sienne", "siennes",
  131. "siens", "sinon", "six", "sixième", "soi", "soi-même", "soient", "sois",
  132. "soit", "soixante", "sommes", "son", "sont", "sous", "souvent", "soyez",
  133. "soyons", "specifique", "specifiques", "speculatif", "stop",
  134. "strictement", "subtiles", "suffisant", "suffisante", "suffit", "suis",
  135. "suit", "suivant", "suivante", "suivantes", "suivants", "suivre",
  136. "sujet", "superpose", "sur", "surtout", "t", "ta", "tac", "tandis",
  137. "tant", "tardive", "te", "tel", "telle", "tellement", "telles", "tels",
  138. "tenant", "tend", "tenir", "tente", "tes", "tic", "tien", "tienne",
  139. "tiennes", "tiens", "toc", "toi", "toi-même", "ton", "touchant",
  140. "toujours", "tous", "tout", "toute", "toutefois", "toutes", "treize",
  141. "trente", "tres", "trois", "troisième", "troisièmement", "trop", "très",
  142. "tsoin", "tsouin", "tu", "té", "u", "un", "une", "unes", "uniformement",
  143. "unique", "uniques", "uns", "v", "va", "vais", "valeur", "vas", "vers",
  144. "via", "vif", "vifs", "vingt", "vivat", "vive", "vives", "vlan", "voici",
  145. "voie", "voient", "voilà", "voire", "vont", "vos", "votre", "vous",
  146. "vous-mêmes", "vu", "vé", "vôtre", "vôtres", "w", "x", "y", "z", "zut",
  147. "à", "â", "ça", "ès", "étaient", "étais", "était", "étant", "état",
  148. "étiez", "étions", "été", "étée", "étées", "étés", "êtes", "être", "ô"
  149. ]
  150. </script>
  151. <script type="text/javascript">
  152. /* See:
  153. * https://gomakethings.com/how-to-create-a-search-page-for-a-static-website-with-vanilla-js/
  154. * https://gomakethings.com/how-to-update-the-url-of-a-page-without-causing-a-reload-using-vanilla-javascript/
  155. */
  156. ;
  157. (function() {
  158. // Retrieving the search index and stopwords from JSON.
  159. // See https://v8.dev/blog/cost-of-javascript-2019#json
  160. let searchIndex = JSON.parse(
  161. document.getElementById('search-index').textContent
  162. )
  163. let stopWords = JSON.parse(
  164. document.getElementById('search-stop-words').textContent
  165. )
  166. // Get the DOM elements
  167. let form = document.querySelector('#form-search')
  168. let input = document.querySelector('#input-search')
  169. let resultList = document.querySelector('#search-results')
  170. let searchStatus = document.querySelector('#search-status')
  171. let searchResultTemplate = document.querySelector('#search-result')
  172. // Make sure required content exists
  173. if (
  174. !form ||
  175. !input ||
  176. !resultList ||
  177. !searchStatus ||
  178. !searchIndex ||
  179. !stopWords ||
  180. !searchResultTemplate
  181. )
  182. return
  183. // Create a submit handler
  184. form.addEventListener('submit', function(event) {
  185. event.preventDefault()
  186. search(input.value)
  187. })
  188. // Create a typeahead handler
  189. form.addEventListener('keyup', function(event) {
  190. search(input.value)
  191. })
  192. // Create a reset handler
  193. form.addEventListener('reset', function() {
  194. search('')
  195. searchStatus.innerHTML = ''
  196. })
  197. // Check for query strings onload
  198. onload()
  199. /**
  200. * If there's a query string search term, search it on page load
  201. */
  202. function onload() {
  203. let query = new URLSearchParams(window.location.search).get('s')
  204. if (!query) return
  205. input.value = query
  206. search(query)
  207. }
  208. /**
  209. * Search for matches
  210. * @param {String} query The term to search for
  211. */
  212. function search(query) {
  213. // Create a regex for each query
  214. let regMap = query
  215. .toLowerCase()
  216. .split(' ')
  217. .filter(function(word) {
  218. return word.length && !stopWords.includes(word)
  219. })
  220. .map(function(word) {
  221. return new RegExp(word, 'i')
  222. })
  223. // Get and sort the results
  224. let results = searchIndex
  225. .reduce(function(results, article, index) {
  226. // Setup priority count
  227. let priority = 0
  228. // Assign priority
  229. for (let reg of regMap) {
  230. if (reg.test(article.title)) {
  231. priority += 100
  232. }
  233. let occurences = article.content.match(reg)
  234. if (occurences) {
  235. priority += occurences.length
  236. }
  237. }
  238. // If any matches, push to results
  239. if (priority > 0) {
  240. results.push({
  241. priority: priority,
  242. article: article,
  243. })
  244. }
  245. return results
  246. }, [])
  247. .sort(function(article1, article2) {
  248. return article2.priority - article1.priority
  249. })
  250. // Display the results
  251. showResults(results, regMap)
  252. // Update the URL
  253. updateURL(query)
  254. }
  255. /**
  256. * Show the search results in the UI
  257. * @param {Array} results The results to display
  258. * @param {List} regMap Regular expressions for the highlights
  259. */
  260. function showResults(results, regMap) {
  261. let status = 'Aucune publication n’a été trouvée 😢'
  262. let searchResults = ''
  263. if (results.length) {
  264. const plural = results.length > 1 ? 's' : ''
  265. status = `${results.length} publication${plural} trouvée${plural} 🙌`
  266. searchResults = results
  267. .map(function(result) {
  268. return interpolate(searchResultTemplate.innerHTML, {
  269. url: result.article.url,
  270. title: highlightText(result.article.title, regMap),
  271. date: result.article.date,
  272. content: highlightText(result.article.content, regMap),
  273. })
  274. })
  275. .join('')
  276. }
  277. searchStatus.innerHTML = status
  278. resultList.innerHTML = searchResults
  279. }
  280. /**
  281. * Get a template from a string
  282. * https://stackoverflow.com/a/41015840
  283. * https://gomakethings.com/html-templates-with-vanilla-javascript/
  284. * @param {String} str The string to interpolate
  285. * @param {Object} params The parameters
  286. * @return {String} The interpolated string
  287. */
  288. function interpolate(str, params) {
  289. let names = Object.keys(params)
  290. let vals = Object.values(params)
  291. return new Function(...names, `return \`${str}\``)(...vals)
  292. }
  293. /**
  294. * Highlight the text in the UI
  295. * @param {String} text The content to highlight
  296. * @param {List} regMap Regular expressions for the highlights
  297. */
  298. function highlightText(text, regMap) {
  299. // TODO: deal with close matches when multiple words are looked for,
  300. // it does not look trivial because you have to memorize positions
  301. // then create extracts.
  302. // For instance: `microsoft github`
  303. const extractBoundariesSize = 100
  304. const textLength = text.length
  305. let extracts = []
  306. for (let reg of regMap) {
  307. const index = text.search(reg)
  308. if (index === -1) {
  309. continue
  310. }
  311. let extract = text.substring(
  312. index - extractBoundariesSize,
  313. index + reg.source.length + extractBoundariesSize
  314. )
  315. // TODISCUSS: we replace with the source but in case there is
  316. // an uppercase letter it will disappear from the extract
  317. // (is that confusing or closer to what is expected?)
  318. extract = extract.replace(reg, `<mark>${reg.source}</mark>`)
  319. const prefixEllipsis = index - extractBoundariesSize >= 0 ? '…' : ''
  320. const suffixEllipsis =
  321. index + extractBoundariesSize <= textLength ? '…' : ''
  322. extracts.push(`${prefixEllipsis}${extract}${suffixEllipsis}`)
  323. }
  324. if (!extracts.length && textLength < 200) {
  325. // If there is no match but it's a short title, return it.
  326. return text
  327. }
  328. return extracts.join('')
  329. }
  330. /**
  331. * Update the URL with a query string for the search string
  332. * @param {String} query The search query
  333. */
  334. function updateURL(query) {
  335. // Create the properties
  336. let state = history.state
  337. let title = document.title
  338. let url = window.location.origin + window.location.pathname
  339. if (query) {
  340. url += '?s=' + encodeURI(query)
  341. }
  342. // Update the URL
  343. history.pushState(state, title, url)
  344. }
  345. })()
  346. </script>
  347. {% endblock %}