gen-indices.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. const algoliasearch = require('algoliasearch');
  5. const slugify = require('transliteration').slugify;
  6. const key = require('./algolia-key');
  7. const client = algoliasearch('4C63BTGP6S', key);
  8. const langs = {
  9. 'zh-CN': 'element-zh',
  10. 'en-US': 'element-en',
  11. 'es': 'element-es',
  12. 'fr-FR': 'element-fr'
  13. };
  14. ['zh-CN', 'en-US', 'es', 'fr-FR'].forEach(lang => {
  15. const indexName = langs[lang];
  16. const index = client.initIndex(indexName);
  17. index.clearIndex(err => {
  18. if (err) return;
  19. fs.readdir(path.resolve(__dirname, `../../examples/docs/${ lang }`), (err, files) => {
  20. if (err) return;
  21. let indices = [];
  22. files.forEach(file => {
  23. const component = file.replace('.md', '');
  24. const content = fs.readFileSync(path.resolve(__dirname, `../../examples/docs/${ lang }/${ file }`), 'utf8');
  25. const matches = content
  26. .replace(/:::[\s\S]*?:::/g, '')
  27. .replace(/```[\s\S]*?```/g, '')
  28. .match(/#{2,4}[^#]*/g)
  29. .map(match => match.replace(/\n+/g, '\n').split('\n').filter(part => !!part))
  30. .map(match => {
  31. const length = match.length;
  32. if (length > 2) {
  33. const desc = match.slice(1, length).join('');
  34. return [match[0], desc];
  35. }
  36. return match;
  37. });
  38. indices = indices.concat(matches.map(match => {
  39. const isComponent = match[0].indexOf('###') < 0;
  40. const title = match[0].replace(/#{2,4}/, '').trim();
  41. const index = { component, title };
  42. index.ranking = isComponent ? 2 : 1;
  43. index.anchor = slugify(title);
  44. index.content = (match[1] || title).replace(/<[^>]+>/g, '');
  45. return index;
  46. }));
  47. });
  48. index.addObjects(indices, (err, res) => {
  49. console.log(err, res);
  50. });
  51. });
  52. });
  53. });