| 5 | const textElement = new Set(['heading', 'paragraph']); |
| 6 | |
| 7 | const extractExamples = file => { |
| 8 | const code = fs.readFileSync(file.path).toString(); |
| 9 | const componentName = file.path.match(/src\/components\/([a-zA-Z]+)\/readme.md$/i)[1]; |
| 10 | const examples = []; |
| 11 | const myPlugin = () => { |
| 12 | return tree => { |
| 13 | let index = 0; |
| 14 | tree.children.forEach(element => { |
| 15 | if (textElement.has(element.type)) { |
| 16 | if (!Array.isArray(examples[index])) { |
| 17 | examples.push([]); |
| 18 | } |
| 19 | examples[index].push({ |
| 20 | type: element.type, |
| 21 | depth: element.depth || 100, |
| 22 | text: element.children[0].value, |
| 23 | }); |
| 24 | } |
| 25 | if (element.type === 'code') { |
| 26 | index += 1; |
| 27 | } |
| 28 | }); |
| 29 | }; |
| 30 | }; |
| 31 | mdx.sync(code, { |
| 32 | remarkPlugins: [myPlugin], |
| 33 | }); |
| 34 | return examples.map((example, i) => { |
| 35 | example.sort((a, b) => a.depth - b.depth); |
| 36 | return { |
| 37 | objectID: `${componentName}-${i + 1}`, |
| 38 | type: 'example', |
| 39 | text: example[0].text, |
| 40 | componentName, |
| 41 | url: `https://react-rainbow.io/#!/${componentName}/${2 * i + 1}`, |
| 42 | description: example |
| 43 | .slice(1) |
| 44 | .map(part => part.text) |
| 45 | .join(), |
| 46 | }; |
| 47 | }); |
| 48 | }; |
| 49 | |
| 50 | module.exports = extractExamples; |