diff --git a/lib/docs/filters/react/clean_html_react_dev.rb b/lib/docs/filters/react/clean_html_react_dev.rb index 1ad201cd34..f52cc5f21b 100644 --- a/lib/docs/filters/react/clean_html_react_dev.rb +++ b/lib/docs/filters/react/clean_html_react_dev.rb @@ -64,11 +64,11 @@ def call node.replace("\n") end css('pre').each do |node| - node['data-language'] = 'jsx' + node['data-language'] ||= 'jsx' end - # Remove styling except for callouts and images - css('*:not([class*=image]):not(.note)').remove_attr('class').remove_attr('style') + # Remove styling except for callouts, images and file names + css('*:not([class*=image]):not(.note):not(._pre-heading)').remove_attr('class').remove_attr('style') doc end diff --git a/lib/docs/filters/react/sandpack_files_react_dev.rb b/lib/docs/filters/react/sandpack_files_react_dev.rb new file mode 100644 index 0000000000..79fa1e7ccc --- /dev/null +++ b/lib/docs/filters/react/sandpack_files_react_dev.rb @@ -0,0 +1,110 @@ +module Docs + class React + # react.dev only renders the active file of a multi-file Sandpack example; the source of + # every file is in the page's __NEXT_DATA__ script, which clean_html removes. + class SandpackFilesReactDevFilter < Filter + LANGUAGES = { 'css' => 'css', 'html' => 'html', 'json' => 'json', 'ts' => 'typescript' } + + def call + sandpacks = page_sandpacks + return doc if sandpacks.empty? + + # Pair each rendered example with the next example in the page data that has its tabs and + # its active file. Recipes and challenges only render their first example, so the data can + # have more. The first candidate is trusted only while every earlier example matched the + # very next one and it isn't part of such a group; otherwise all candidates must agree on + # the files. Unmatched examples keep the rendered file. + position = 0 + in_step = true + css('.sandpack--playground').each do |node| + tabs = node.css('.sp-tab-button') + active = node.at_css('.sp-tab-button[data-active="true"]') + pre = node.at_css('pre') + next in_step = false if tabs.empty? || active.nil? || pre.nil? + + paths = tabs.map { |tab| tab['title'] } + candidates = (position...sandpacks.length).select do |i| + files = sandpacks[i][:files] + paths.all? { |path| files.key?(path) } && same_code?(files[active['title']], pre.content) + end + index = candidates.first + trusted = in_step && index == position && !sandpacks[index][:grouped] + unless index && (trusted || candidates.map { |i| sandpacks[i][:files].values_at(*paths) }.uniq.one?) + next in_step = false + end + + in_step &&= index == position + position = index + 1 + files = sandpacks[index][:files] + node.replace(tabs.map { |tab| file_html(tab.content.strip, files[tab['title']]) }.join) + end + + doc + end + + private + + def page_sandpacks + script = at_css('script#__NEXT_DATA__') + return [] unless script + + content = JSON.parse(script.content).dig('props', 'pageProps', 'content') + return [] unless content.is_a?(String) + + sandpacks = [] + collect_sandpacks(JSON.parse(content), sandpacks) + sandpacks + rescue JSON::ParserError + [] + end + + # The content is a serialized React tree: elements are ["$r", type, key, props]. + def collect_sandpacks(node, sandpacks, grouped = false) + if node.is_a?(Array) && node.length == 4 && node[0] == '$r' + if node[1] == 'Sandpack' + sandpacks << { files: sandpack_files(node[3]['children']), grouped: grouped } + else + collect_sandpacks(node[3], sandpacks, grouped || %w(Recipes Challenges).include?(node[1])) + end + elsif node.is_a?(Array) + node.each { |child| collect_sandpacks(child, sandpacks, grouped) } + elsif node.is_a?(Hash) + node.each_value { |child| collect_sandpacks(child, sandpacks, grouped) } + end + end + + # Same file paths as react.dev's createFileMap. + def sandpack_files(children) + children = [children] unless children.is_a?(Array) && children[0].is_a?(Array) + children.each_with_object({}) do |child, files| + next unless child.is_a?(Array) && child[1] == 'pre' + props = child.dig(3, 'children', 3) + next unless props.is_a?(Hash) + + language = props['className'].to_s.delete_prefix('language-') + name = props['meta'].to_s.split.find { |token| token.include?('/') || token.include?('.') } + path = name ? "/#{name.delete_prefix('/')}" : { 'js' => '/src/App.js', 'css' => '/src/styles.css' }[language] + files[path] = { code: props['children'].to_s, language: language } if path + end + end + + def file_html(label, file) + %(
#{CGI.escapeHTML(label)}
) + + %(
#{CGI.escapeHTML(file[:code])}
) + end + + def same_code?(file, rendered) + return true if file[:code].gsub(/\s+/, '') == rendered.gsub(/\s+/, '') + return false unless file[:language] == 'json' + + # Sandpack adds an empty "devDependencies" to the package.json it renders. + source, shown = JSON.parse(file[:code]), JSON.parse(rendered) + return false unless source.is_a?(Hash) && shown.is_a?(Hash) + shown.delete('devDependencies') if shown['devDependencies'] == {} && !source.key?('devDependencies') + source == shown + rescue JSON::ParserError + false + end + end + end +end diff --git a/lib/docs/scrapers/react.rb b/lib/docs/scrapers/react.rb index e6b3051ebe..e6f1685816 100644 --- a/lib/docs/scrapers/react.rb +++ b/lib/docs/scrapers/react.rb @@ -18,6 +18,7 @@ class React < UrlScraper self.release = '19.3' self.base_url = 'https://react.dev' self.initial_paths = %w(/reference/react /learn) + html_filters.insert_before 'clean_html', 'react/sandpack_files_react_dev' html_filters.push 'react/entries_react_dev', 'react/clean_html_react_dev' options[:only_patterns] = [/\A\/learn/, /\A\/reference/] @@ -27,6 +28,7 @@ class React < UrlScraper self.release = '18.3.1' self.base_url = 'https://18.react.dev' self.initial_paths = %w(/reference/react /learn) + html_filters.insert_before 'clean_html', 'react/sandpack_files_react_dev' html_filters.push 'react/entries_react_dev', 'react/clean_html_react_dev' options[:only_patterns] = [/\A\/learn/, /\A\/reference/] diff --git a/test/lib/docs/scrapers/react_test.rb b/test/lib/docs/scrapers/react_test.rb new file mode 100644 index 0000000000..7c2f35169f --- /dev/null +++ b/test/lib/docs/scrapers/react_test.rb @@ -0,0 +1,205 @@ +require_relative '../../../test_helper' +require_relative '../../../../lib/docs' + +class ReactScraperTest < Minitest::Test + INDEX_JS = "import { createRoot } from 'react-dom/client';\nimport App from './App';\n\ncreateRoot(document.getElementById('root')).render();\n" + STRICT_INDEX_JS = "import { StrictMode } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport App from './App';\n\ncreateRoot(document.getElementById('root')).render();\n" + APP_JS = "import StoryTray from './StoryTray.js';\n\nexport default function App() {\n return ;\n}\n" + STORY_TRAY_JS = "export default function StoryTray({ stories }) {\n return ;\n}\n" + STYLES_CSS = "ul { margin: 0; }\n" + + def test_shows_every_file_of_a_sandpack_example + result = scrape( + playground([['/src/index.js', 'index.js'], ['/src/App.js', 'App.js'], ['/src/StoryTray.js', 'StoryTray.js']], active: '/src/StoryTray.js', code: STORY_TRAY_JS), + [sandpack([['src/index.js', 'js', INDEX_JS], ['src/App.js', 'js', APP_JS], ['src/StoryTray.js active', 'js', STORY_TRAY_JS], [nil, 'css', STYLES_CSS]])] + ) + + assert_equal %w(index.js App.js StoryTray.js), files(result).map(&:first) + assert_equal [INDEX_JS, APP_JS, STORY_TRAY_JS], files(result).map(&:last).map(&:content) + assert_equal %w(jsx jsx jsx), files(result).map { |_, pre| pre['data-language'] } + refute_includes result[:output], 'margin: 0' + end + + def test_pairs_examples_with_the_same_active_file_in_page_order + tabs = [['/src/index.js', 'index.js'], ['/src/App.js', 'App.js']] + result = scrape( + playground(tabs, active: '/src/App.js', code: APP_JS) + playground(tabs, active: '/src/App.js', code: APP_JS), + [ + sandpack([['src/index.js', 'js', INDEX_JS], ['src/App.js active', 'js', APP_JS]]), + sandpack([['src/index.js', 'js', STRICT_INDEX_JS], ['src/App.js active', 'js', APP_JS]]) + ] + ) + + index_files = files(result).select { |name, _| name == 'index.js' }.map(&:last).map(&:content) + assert_equal [INDEX_JS, STRICT_INDEX_JS], index_files + end + + def test_skips_examples_that_are_not_rendered_on_the_page + # Challenges and recipes only render their first example; the others are only in the page data. + hidden_app = "export default function App() {\n return

Challenge 2

;\n}\n" + result = scrape( + playground([['/src/App.js', 'App.js'], ['/src/StoryTray.js', 'StoryTray.js']], active: '/src/App.js', code: APP_JS), + [ + sandpack([['src/App.js', 'js', hidden_app], ['src/StoryTray.js', 'js', 'export default function StoryTray() {}']]), + sandpack([['src/App.js', 'js', APP_JS], ['src/StoryTray.js', 'js', STORY_TRAY_JS]]) + ] + ) + + assert_equal [APP_JS, STORY_TRAY_JS], files(result).map(&:last).map(&:content) + end + + def test_does_not_borrow_files_after_an_example_fails_to_match + tabs = [['/src/index.js', 'index.js'], ['/src/App.js', 'App.js']] + result = scrape( + playground(tabs, active: '/src/App.js', code: "export default function App() {\n return

cut off") + + playground(tabs, active: '/src/App.js', code: APP_JS), + [ + sandpack([['src/index.js', 'js', INDEX_JS], ['src/App.js active', 'js', APP_JS]]), + sandpack([['src/index.js', 'js', STRICT_INDEX_JS], ['src/App.js active', 'js', APP_JS]]) + ] + ) + + assert_empty files(result) + refute_includes result[:output], 'react-dom/client' + end + + def test_keeps_ambiguous_examples_after_skipping_examples_that_are_not_rendered + hidden_app = "export default function App() {\n return

Challenge 2

;\n}\n" + tabs = [['/src/index.js', 'index.js'], ['/src/App.js', 'App.js']] + result = scrape( + playground([['/src/App.js', 'App.js']], active: '/src/App.js', code: APP_JS) + playground(tabs, active: '/src/App.js', code: APP_JS), + [ + sandpack([['src/App.js', 'js', hidden_app]]), + sandpack([['src/App.js', 'js', APP_JS]]), + sandpack([['src/index.js', 'js', INDEX_JS], ['src/App.js active', 'js', APP_JS]]), + sandpack([['src/index.js', 'js', STRICT_INDEX_JS], ['src/App.js active', 'js', APP_JS]]) + ] + ) + + assert_equal %w(App.js), files(result).map(&:first) + refute_includes result[:output], 'react-dom/client' + end + + def test_does_not_take_files_from_hidden_recipes + recipe_app = "export default function App() {\n return

Recipe 1

;\n}\n" + tabs = [['/src/index.js', 'index.js'], ['/src/App.js', 'App.js']] + result = scrape( + playground(tabs, active: '/src/App.js', code: recipe_app) + playground(tabs, active: '/src/App.js', code: APP_JS), + [ + ['$r', 'Recipes', nil, { children: [ + sandpack([['src/index.js', 'js', INDEX_JS], ['src/App.js active', 'js', recipe_app]]), + sandpack([['src/index.js', 'js', INDEX_JS], ['src/App.js active', 'js', APP_JS]]) + ] }], + sandpack([['src/index.js', 'js', STRICT_INDEX_JS], ['src/App.js active', 'js', APP_JS]]) + ] + ) + + assert_equal [INDEX_JS, recipe_app], files(result).map(&:last).map(&:content) + end + + def test_matches_a_package_json_rendered_with_empty_dev_dependencies + package = %({\n "dependencies": {\n "immer": "1.7.3"\n }\n}\n) + rendered = %({\n "dependencies": {\n "immer": "1.7.3"\n },\n "devDependencies": {}\n}\n) + result = scrape( + playground([['/package.json', 'package.json'], ['/src/App.js', 'App.js']], active: '/package.json', code: rendered), + [sandpack([['package.json', 'json', package], ['src/App.js', 'js', APP_JS]])] + ) + + assert_equal [['package.json', package, 'json'], ['App.js', APP_JS, 'jsx']], files(result).map { |name, pre| [name, pre.content, pre['data-language']] } + end + + def test_ignores_options_in_braces_when_reading_file_names + result = scrape( + playground([['/src/App.js', 'App.js'], ['/src/StoryTray.js', 'StoryTray.js']], active: '/src/App.js', code: APP_JS), + [sandpack([['{2-4} src/App.js', 'js', APP_JS], ["src/StoryTray.js {expectedErrors: {'react-compiler': [4]}}", 'js', STORY_TRAY_JS]])] + ) + + assert_equal [APP_JS, STORY_TRAY_JS], files(result).map(&:last).map(&:content) + end + + def test_shows_every_file_in_the_react_18_documentation + result = scrape( + playground([['/src/App.js', 'App.js'], ['/src/StoryTray.js', 'StoryTray.js']], active: '/src/App.js', code: APP_JS), + [sandpack([['src/App.js', 'js', APP_JS], ['src/StoryTray.js', 'js', STORY_TRAY_JS]])], + version: '18' + ) + + assert_equal %w(App.js StoryTray.js), files(result).map(&:first) + end + + def test_uses_the_language_of_each_file + html = "\n
\n" + result = scrape( + playground([['/src/index.js', 'index.js'], ['/public/index.html', 'index.html']], active: '/src/index.js', code: INDEX_JS), + [sandpack([['src/index.js active', 'js', INDEX_JS], ['public/index.html', 'html', html]])] + ) + + assert_equal %w(jsx html), files(result).map { |_, pre| pre['data-language'] } + assert_equal html, files(result).last.last.content + end + + def test_keeps_the_rendered_file_when_the_page_data_does_not_match + result = scrape( + playground([['/src/index.js', 'index.js'], ['/src/App.js', 'App.js']], active: '/src/App.js', code: APP_JS), + [sandpack([['src/index.js', 'js', INDEX_JS], ['src/App.js active', 'js', "export default function Other() {}\n"]])] + ) + + assert_empty files(result) + assert_equal [APP_JS.strip], output(result).css('pre').map { |pre| pre.content.strip } + end + + def test_keeps_the_rendered_file_without_page_data + result = scrape(playground([['/src/index.js', 'index.js'], ['/src/App.js', 'App.js']], active: '/src/App.js', code: APP_JS), nil) + + assert_empty files(result) + assert_equal [APP_JS.strip], output(result).css('pre').map { |pre| pre.content.strip } + end + + private + + def scrape(body, sandpacks, version: '') + data = sandpacks && { props: { pageProps: { content: [['$r', 'MaxWidth', nil, { children: sandpacks }]].to_json } } } + html = <<~HTML + +
Reference

StrictMode

#{body}
+ #{%() if data} + + HTML + scraper = Docs::React.versions.find { |doc| doc.version == version }.new + context = scraper.options.merge(url: Docs::URL.parse("#{scraper.base_url}/reference/react/StrictMode"), download_images: false) + scraper.pipeline.call(Docs::Parser.new(html).html, context) + end + + # Markup of a react.dev Sandpack example: a tab per visible file, and only the active file's code. + def playground(tabs, active:, code:) + buttons = tabs.map do |path, label| + %() + end + tokens = CGI.escapeHTML(code).gsub(/\S+/) { |token| %(#{token}) } + <<~HTML +
+
#{buttons.join}
+
#{tokens}
+
+
+ HTML + end + + # A element as serialized in react.dev's __NEXT_DATA__. + def sandpack(files) + children = files.map do |meta, language, code| + props = { className: "language-#{language}", children: code } + props[:meta] = meta if meta + ['$r', 'pre', nil, { children: ['$r', 'code', nil, props] }] + end + ['$r', 'Sandpack', nil, { children: children }] + end + + def files(result) + output(result).css('div._pre-heading').map { |heading| [heading.content, heading.next_element] } + end + + def output(result) + Nokogiri::HTML.fragment(result[:output]) + end +end