gen-indices.js 1.8 KB

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