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 15KB

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