Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update script to support current tailwindui.com #11

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
BASE_URL=https://tailwindui.com

email=some-email
password=some-password
slowmo=0
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ The two steps process makes it easy to adjust for future needs.

```sh
# Format:
email=<[email protected]> password=<yourpassword> node tailwindui.js <react|vue|html>
yarn start <react|vue|html>

# Example:
email='[email protected]' password='pass123' node tailwindui.js react
yarn start react
```

The command will start chromium and navigate thru tailwindui.com website to copy the components codes. Here's how it looks like:
Expand All @@ -40,8 +40,8 @@ The two steps process makes it easy to adjust for future needs.
5. Now we can create the mdx files based on above json. To do so, run:

```sh
# Replace `react.json` suffix with `vue.json` as you fit
node tailwindui-storybook.js ./output/tailwindui.react.json react
# Replace "react" with "html" or "vue" (based on step 3)
yarn create-mdx react
```

![tailwindui-storybook](docs/tailwindui-storybook-mdx.gif)
Expand Down
Binary file added docs/hints/codeblock.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/hints/toggle-code-format.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/hints/toggle-code.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 41 additions & 0 deletions lib/getComponents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const baseUrl = process.env.BASE_URL;

async function getComponents(page, sectionUrl, type = "html") {
// Go to section url. Example: https://tailwindui.com/components/marketing/sections/heroes
await page.goto(sectionUrl);

const toggleCodeSelector = '[role=tablist] > [id^=headlessui-tabs-tab-]:nth-child(2)'
try {
// Element to toggle code snippet (hint: ../docs/hints/toggle-code.png).
// The element won't exist if the user doesn't have access to the paid component.
await page.waitForSelector(toggleCodeSelector, { timeout: 10 * 1000 });
} catch (error) {
console.warn(`You do not have access this section components: ${sectionUrl}`);
}

const components = await page.evaluate(([toggleCodeSelector, type]) => {
let components = [];
document.querySelectorAll('section[id^="component-"]').forEach((el) => {
// Toggle code block
el.querySelector(toggleCodeSelector)?.click();

// Change the type of code snippet to HTML/React/Vue (hint: ../docs/hints/toggle-code-format.png)
const toggleSnippetType = el.querySelector('select.form-select')
toggleSnippetType.value = type;
toggleSnippetType.dispatchEvent(new Event('change', { bubbles: true }));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bubbles: true is needed otherwise the onChange event won't be propagated to React and it won't rerender (SO).


// Extract code blocks (hint: ../docs/hints/codeblock.png)
const title = el.querySelector("h2 a").innerText;
const codeblock = el.querySelector('pre code')?.innerText;
codeblock && components.push({ title, codeblocks: { [type]: codeblock } });
});
return Promise.resolve(components);
}, [toggleCodeSelector, type]);

// Back to home page
await page.goto(baseUrl);

return components;
}

module.exports = getComponents
18 changes: 18 additions & 0 deletions lib/getSections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
async function getSections(page) {
const sections = await page.evaluate(([]) => {
const buildSections = [];
document
.querySelectorAll('a[href^="/components"]')
.forEach((el) => {
const title = el.children[1]?.innerText;
const countComponents = el.parentElement?.nextElementSibling?.innerText;
const url = el.href;
title && countComponents && buildSections.push({ title, componentsCount: parseInt(countComponents), url });
});
return Promise.resolve(buildSections);
}, []);

return sections;
}

module.exports = getSections
22 changes: 22 additions & 0 deletions lib/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const baseUrl = process.env.BASE_URL;
const selector = {
email: 'input#email',
password: 'input#password',
submit: 'button[type=submit]',
}

async function login(page, email, password) {
await page.goto(baseUrl + "/login");
await page.locator(selector.email).fill(email);
await page.locator(selector.password).fill(password);
await page.locator(selector.submit).click();

// Assert login succeeded
const loginFailedToken = "These credentials do not match our records";
const el = await page.$$(`:text("${loginFailedToken}")`);
if (el.length) {
throw new Error("invalid credentials");
}
}

module.exports = login
11 changes: 10 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
{
"name": "tailwindui-storybook",
"engine": ">=14",
"scripts": {
"start": "node -r dotenv/config tailwindui.js",
"create-mdx": "node -r dotenv/config tailwindui-storybook.js"
},
"dependencies": {
"dotenv": "^16.0.3",
"lodash": "^4.17.21",
"playwright": "^1.9.2"
"playwright": "^1.27.1"
},
"devDependencies": {
"ava": "^4.3.3"
}
}
39 changes: 39 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 18 additions & 19 deletions tailwindui-storybook.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,31 @@ const fs = require("fs");
const camelCase = require("lodash/camelCase");
const startCase = require("lodash/startCase");

const [, , jsonFile, componentType] = process.argv;
const createDir = require("./util/createDir");

if (!jsonFile || !componentType) {
console.log("usage: tailwind-storybook.js <jsonfile> <type>");
console.log("example: tailwind-storybook.js tailwindui.react.json react");
const componentType = process.argv[process.argv.length - 1];
if (!componentType.match(/react|html|vue/)) {
console.log("usage: tailwind-storybook.js <react|html|vue>");
console.log("example: tailwind-storybook.js react");
process.exit(0);
}

const sections = require(jsonFile);

const outputDir = `output/tailwindui-${componentType}`;

const storyFolder = `Tailwind UI`;

function createDir(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
console.log("[INFO] directory created:", dir);
}
const jsonFile = `./output/tailwindui.${componentType}.json`
if (!fs.existsSync(jsonFile)) {
console.error("[ERROR] could not find json file at", jsonFile)
console.log(`→ Have you run 'yarn start ${componentType}'?`)
process.exit(1)
}

function pascalCase(str) {
return startCase(camelCase(str)).replace(/ /g, "");
}
const sections = require(jsonFile)
const storyFolder = `Tailwind UI`;
const outputDir = `output/tailwindui-${componentType}`;

async function run() {
createDir(outputDir);

// Uncomment to see data structure
console.log("sections[0]:", sections[0]);
// console.log("sections[0]:", sections[0]);

sections.forEach((section) => {
const { title, components } = section;
Expand Down Expand Up @@ -84,4 +79,8 @@ ${componentStories.join("\n")}
});
}

function pascalCase(str) {
return startCase(camelCase(str)).replace(/ /g, "");
}

run();
Loading