gen-indices.js 1.8 KB

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