index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/mui/material-ui/examples/material-ui-vite
petrpan-code/mui/material-ui/examples/material-ui-vite/src/theme.js
import { createTheme } from '@mui/material/styles'; import { red } from '@mui/material/colors'; // Create a theme instance. const theme = createTheme({ palette: { primary: { main: '#556cd6', }, secondary: { main: '#19857b', }, error: { main: red.A400, }, }, }); export default theme;
6,000
0
petrpan-code/mui/material-ui/netlify
petrpan-code/mui/material-ui/netlify/functions/deploy-succeeded.js
/** * @param {object} event * @param {string} event.body - https://jsoneditoronline.org/#left=cloud.fb1a4fa30a4f475fa6887071c682e2c1 */ exports.handler = async (event) => { const { payload } = JSON.parse(event.body); const repo = payload.review_url.match(/github\.com\/(.*)\/pull\/(.*)/); if (!repo) { throw new Error(`No repo found at review_url: ${payload.review_url}`); } // eslint-disable-next-line no-console console.info(`repo:`, repo[1]); // eslint-disable-next-line no-console console.info(`PR:`, repo[2]); // eslint-disable-next-line no-console console.info(`url:`, payload.deploy_ssl_url); // for more details > https://circleci.com/docs/2.0/api-developers-guide/# await fetch(`https://circleci.com/api/v2/project/gh/${repo[1]}/pipeline`, { method: 'POST', headers: { 'Content-type': 'application/json', // token from https://app.netlify.com/sites/material-ui/settings/deploys#environment-variables 'Circle-Token': process.env.CIRCLE_CI_TOKEN, }, body: JSON.stringify({ // For PR, /head is needed. https://support.circleci.com/hc/en-us/articles/360049841151 branch: `pull/${repo[2]}/head`, parameters: { // the parameters defined in .circleci/config.yml workflow: 'e2e-website', // name of the workflow 'e2e-base-url': payload.deploy_ssl_url, // deploy preview url }, }), }); return { statusCode: 200, body: {}, }; };
6,001
0
petrpan-code/mui/material-ui/netlify
petrpan-code/mui/material-ui/netlify/functions/feedback-management.js
const querystring = require('node:querystring'); const { App, AwsLambdaReceiver } = require('@slack/bolt'); const { JWT } = require('google-auth-library'); const { sheets } = require('@googleapis/sheets'); const X_FEEBACKS_CHANNEL_ID = 'C04U3R2V9UK'; const JOY_FEEBACKS_CHANNEL_ID = 'C050VE13HDL'; const TOOLPAD_FEEBACKS_CHANNEL_ID = 'C050MHU703Z'; const CORE_FEEBACKS_CHANNEL_ID = 'C041SDSF32L'; // The design feedback alert was removed in https://github.com/mui/material-ui/pull/39691 // This dead code is here to simplify the creation of special feedback channel const DESIGN_FEEDBACKS_CHANNEL_ID = 'C05HHSFH2QJ'; const getSlackChannelId = (url, specialCases) => { const { isDesignFeedback } = specialCases; if (isDesignFeedback) { return DESIGN_FEEDBACKS_CHANNEL_ID; } if (url.includes('/x/')) { return X_FEEBACKS_CHANNEL_ID; } if (url.includes('/joy-ui/')) { return JOY_FEEBACKS_CHANNEL_ID; } if (url.includes('/toolpad/')) { return TOOLPAD_FEEBACKS_CHANNEL_ID; } return CORE_FEEBACKS_CHANNEL_ID; }; const spreadSheetsIds = { forLater: '1NAUTsIcReVylWPby5K0omXWZpgjd9bjxE8V2J-dwPyc', }; // Setup of the slack bot (taken from https://slack.dev/bolt-js/deployments/aws-lambda) const awsLambdaReceiver = new AwsLambdaReceiver({ signingSecret: process.env.SLACK_SIGNING_SECRET, }); const app = new App({ token: process.env.SLACK_BOT_TOKEN, receiver: awsLambdaReceiver, signingSecret: process.env.SLACK_SIGNING_SECRET, }); // Define slack actions to answer app.action('delete_action', async ({ ack, body, client, logger }) => { try { await ack(); const { user: { username }, channel: { id: channelId }, message, actions: [{ value }], } = body; const { comment, currentLocationURL = '', commmentSectionURL = '' } = JSON.parse(value); const googleAuth = new JWT({ email: '[email protected]', key: process.env.G_SHEET_TOKEN.replace(/\\n/g, '\n'), scopes: ['https://www.googleapis.com/auth/spreadsheets'], }); const service = sheets({ version: 'v4', auth: googleAuth }); await service.spreadsheets.values.append({ spreadsheetId: spreadSheetsIds.forLater, range: 'Deleted messages!A:D', valueInputOption: 'USER_ENTERED', resource: { values: [[username, comment, currentLocationURL, commmentSectionURL]], }, }); await client.chat.delete({ channel: channelId, ts: message.ts, as_user: true, token: process.env.SLACK_BOT_TOKEN, }); } catch (error) { logger.error(JSON.stringify(error, null, 2)); } }); app.action('save_message', async ({ ack, body, client, logger }) => { try { await ack(); const { user: { username }, channel: { id: channelId }, message, actions: [{ value }], } = body; const { comment, currentLocationURL = '', commmentSectionURL = '' } = JSON.parse(value); const googleAuth = new JWT({ email: '[email protected]', key: process.env.G_SHEET_TOKEN.replace(/\\n/g, '\n'), scopes: ['https://www.googleapis.com/auth/spreadsheets'], }); const service = sheets({ version: 'v4', auth: googleAuth }); await service.spreadsheets.values.append({ spreadsheetId: spreadSheetsIds.forLater, range: 'Sheet1!A:D', valueInputOption: 'USER_ENTERED', resource: { values: [[username, comment, currentLocationURL, commmentSectionURL]], }, }); await client.chat.postMessage({ channel: channelId, thread_ts: message.ts, as_user: true, text: `Saved in <https://docs.google.com/spreadsheets/d/${spreadSheetsIds.forLater}/>`, }); } catch (error) { logger.error(JSON.stringify(error, null, 2)); } }); /** * @param {object} event * @param {object} context */ exports.handler = async (event, context, callback) => { if (event.httpMethod !== 'POST') { return { statusCode: 404 }; } try { const { payload } = querystring.parse(event.body); const data = JSON.parse(payload); if (data.callback_id === 'send_feedback') { // We send the feedback to the appopiate slack channel const { rating, comment, currentLocationURL, commmentSectionURL: inCommmentSectionURL, commmentSectionTitle, githubRepo, } = data; // The design feedback alert was removed in https://github.com/mui/material-ui/pull/39691 // This dead code is here to simplify the creation of special feedback channel const isDesignFeedback = inCommmentSectionURL.includes('#new-docs-api-feedback'); const commmentSectionURL = isDesignFeedback ? '' : inCommmentSectionURL; const simpleSlackMessage = [ `New comment ${rating === 1 ? '👍' : ''}${rating === 0 ? '👎' : ''}`, `>${comment.split('\n').join('\n>')}`, `sent from ${currentLocationURL}${ commmentSectionTitle ? ` (from section <${commmentSectionURL}|${commmentSectionTitle})>` : '' }`, ].join('\n\n'); const githubNewIssueParams = new URLSearchParams({ title: '[ ] Docs feedback', body: `Feedback received: ${comment} from ${commmentSectionURL} `, }); await app.client.chat.postMessage({ channel: getSlackChannelId(currentLocationURL, { isDesignFeedback }), text: simpleSlackMessage, // Fallback for notification blocks: [ { type: 'section', text: { type: 'mrkdwn', text: simpleSlackMessage, }, }, { type: 'actions', elements: [ { type: 'button', text: { type: 'plain_text', text: 'Create issue', emoji: true, }, url: `${githubRepo}/issues/new?${githubNewIssueParams}`, }, { type: 'button', text: { type: 'plain_text', text: 'Save', }, value: JSON.stringify({ comment, currentLocationURL, commmentSectionURL, }), action_id: 'save_message', }, { type: 'button', text: { type: 'plain_text', text: 'Delete', }, value: JSON.stringify({ comment, currentLocationURL, commmentSectionURL, }), style: 'danger', action_id: 'delete_action', }, ], }, ], as_user: true, unfurl_links: false, unfurl_media: false, }); } else { const handler = await awsLambdaReceiver.start(); return handler(event, context, callback); } } catch (error) { // eslint-disable-next-line no-console console.log(JSON.stringify(error, null, 2)); return { statusCode: 500, body: JSON.stringify({}), }; } return { statusCode: 200, body: JSON.stringify({}), }; };
6,002
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder-core/.eslintrc.js
module.exports = { rules: { 'import/no-default-export': 'error', 'import/prefer-default-export': 'off', }, };
6,003
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder-core/index.ts
export { projectSettings as baseUiProjectSettings } from './baseUi/projectSettings'; export { projectSettings as joyUiProjectSettings } from './joyUi/projectSettings'; export { projectSettings as materialUiProjectSettings } from './materialUi/projectSettings'; export { projectSettings as muiSystemProjectSettings } from './muiSystem/projectSettings';
6,004
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder-core/package.json
{ "name": "@mui-internal/api-docs-builder-core", "version": "1.0.0", "description": "MUI Core-specific settings for API docs generator", "private": "true", "main": "./index.ts", "scripts": { "test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/api-docs-builder/**/*.test.{js,ts,tsx}'", "typescript": "tsc -p tsconfig.json" }, "dependencies": { "@mui-internal/api-docs-builder": "1.0.0", "@mui/markdown": "^5.0.0", "docs": "^5.0.0", "lodash": "^4.17.21" }, "devDependencies": { "@types/chai": "^4.3.10", "@types/mocha": "^10.0.4", "@types/node": "^18.18.10", "@types/sinon": "^10.0.20", "chai": "^4.3.10", "sinon": "^15.2.0", "typescript": "^5.1.6" } }
6,005
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder-core/tsconfig.json
{ "compilerOptions": { "allowJs": true, "isolatedModules": true, "noEmit": true, "noUnusedLocals": false, "resolveJsonModule": true, "skipLibCheck": true, "esModuleInterop": true, "types": ["node", "mocha"], "target": "ES2020", "module": "CommonJS", "moduleResolution": "node", "strict": true, "baseUrl": "./", "paths": { "react-docgen": ["../api-docs-builder/react-docgen.d.ts"] } }, "include": ["./**/*.ts", "./**/*.js"], "exclude": ["node_modules"] }
6,006
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/generateApiLinks.ts
import kebabCase from 'lodash/kebabCase'; import { ReactApi as ComponentReactApi } from '@mui-internal/api-docs-builder/ApiBuilders/ComponentApiBuilder'; import { ReactApi as HookReactApi } from '@mui-internal/api-docs-builder/ApiBuilders/HookApiBuilder'; /** * Generates the api links, in a format that would point to the appropriate API tab */ export function generateApiLinks( builds: PromiseSettledResult<ComponentReactApi | HookReactApi | never[] | null>[], ) { const apiLinks: { pathname: string; title: string }[] = []; builds.forEach((build) => { if (build.status !== 'fulfilled' || build.value === null) { return; } const { value } = build as PromiseFulfilledResult<ComponentReactApi | HookReactApi>; const { name, demos } = value; // find a potential # in the pathname const hashIdx = demos.length > 0 ? demos[0].demoPathname.indexOf('#') : -1; let pathname = null; if (demos.length > 0) { // make sure the pathname doesn't contain # pathname = hashIdx >= 0 ? demos[0].demoPathname.substr(0, hashIdx) : demos[0].demoPathname; } if (pathname !== null) { // add the new apiLink, where pathame is in format of /react-component/components-api apiLinks.push({ pathname: `${pathname}${ name.startsWith('use') ? 'hooks-api' : 'components-api' }/#${kebabCase(name)}`, title: name, }); } }); apiLinks.sort((a, b) => (a.title > b.title ? 1 : -1)); return apiLinks; }
6,007
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/generateBaseUiApiPages.ts
import fs from 'fs'; import path from 'path'; import kebabCase from 'lodash/kebabCase'; import { getHeaders } from '@mui/markdown'; import findPagesMarkdown from '@mui-internal/api-docs-builder/utils/findPagesMarkdown'; import { writePrettifiedFile } from '@mui-internal/api-docs-builder/buildApiUtils'; export function generateBaseUIApiPages() { findPagesMarkdown().forEach((markdown) => { const markdownContent = fs.readFileSync(markdown.filename, 'utf8'); const markdownHeaders = getHeaders(markdownContent) as any; const pathnameTokens = markdown.pathname.split('/'); const productName = pathnameTokens[1]; const componentName = pathnameTokens[3]; // TODO: fix `productName` should be called `productId` and include the full name, // e.g. base-ui below. if ( productName === 'base' && (markdown.filename.indexOf('\\components\\') >= 0 || markdown.filename.indexOf('/components/') >= 0) ) { const { components, hooks } = markdownHeaders; const tokens = markdown.pathname.split('/'); const name = tokens[tokens.length - 1]; const importStatement = `docs/data${markdown.pathname}/${name}.md`; const demosSource = ` import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocsV2'; import AppFrame from 'docs/src/modules/components/AppFrame'; import * as pageProps from '${importStatement}?@mui/markdown'; export default function Page(props) { const { userLanguage, ...other } = props; return <MarkdownDocs {...pageProps} {...other} />; } Page.getLayout = (page) => { return <AppFrame>{page}</AppFrame>; }; `; const componentPageDirectory = `docs/pages/${productName}-ui/react-${componentName}/`; if (!fs.existsSync(componentPageDirectory)) { fs.mkdirSync(componentPageDirectory, { recursive: true }); } writePrettifiedFile( path.join(process.cwd(), `${componentPageDirectory}/index.js`), demosSource, ); if ((!components || components.length === 0) && (!hooks || hooks.length === 0)) { // Early return if it's a markdown file without components/hooks. return; } let apiTabImportStatements = ''; let staticProps = 'export const getStaticProps = () => {'; let componentsApiDescriptions = ''; let componentsPageContents = ''; let hooksApiDescriptions = ''; let hooksPageContents = ''; if (components && components.length > 0) { components.forEach((component: string) => { const componentNameKebabCase = kebabCase(component); apiTabImportStatements += `import ${component}ApiJsonPageContent from '../../api/${componentNameKebabCase}.json';`; staticProps += ` const ${component}ApiReq = require.context( 'docs/translations/api-docs-base/${componentNameKebabCase}', false, /${componentNameKebabCase}.*.json$/, ); const ${component}ApiDescriptions = mapApiPageTranslations(${component}ApiReq); `; componentsApiDescriptions += `${component} : ${component}ApiDescriptions ,`; componentsPageContents += `${component} : ${component}ApiJsonPageContent ,`; }); } if (hooks && hooks.length > 0) { hooks.forEach((hook: string) => { const hookNameKebabCase = kebabCase(hook); apiTabImportStatements += `import ${hook}ApiJsonPageContent from '../../api/${hookNameKebabCase}.json';`; staticProps += ` const ${hook}ApiReq = require.context( 'docs/translations/api-docs/${hookNameKebabCase}', false, /${hookNameKebabCase}.*.json$/, ); const ${hook}ApiDescriptions = mapApiPageTranslations(${hook}ApiReq); `; hooksApiDescriptions += `${hook} : ${hook}ApiDescriptions ,`; hooksPageContents += `${hook} : ${hook}ApiJsonPageContent ,`; }); } staticProps += ` return { props: { componentsApiDescriptions: {`; staticProps += componentsApiDescriptions; staticProps += '}, componentsApiPageContents: { '; staticProps += componentsPageContents; staticProps += '}, hooksApiDescriptions: {'; staticProps += hooksApiDescriptions; staticProps += '}, hooksApiPageContents: {'; staticProps += hooksPageContents; staticProps += ` },},};};`; const tabsApiSource = ` import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocsV2'; import AppFrame from 'docs/src/modules/components/AppFrame'; import * as pageProps from '${importStatement}?@mui/markdown'; import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations'; ${apiTabImportStatements} export default function Page(props) { const { userLanguage, ...other } = props; return <MarkdownDocs {...pageProps} {...other} />; } Page.getLayout = (page) => { return <AppFrame>{page}</AppFrame>; }; export const getStaticPaths = () => { return { paths: [{ params: { docsTab: 'components-api' } }, { params: { docsTab: 'hooks-api' } }], fallback: false, // can also be true or 'blocking' }; }; ${staticProps} `; const docsTabsPagesDirectory = `${componentPageDirectory}/[docsTab]`; if (!fs.existsSync(docsTabsPagesDirectory)) { fs.mkdirSync(docsTabsPagesDirectory, { recursive: true }); } writePrettifiedFile( path.join(process.cwd(), `${docsTabsPagesDirectory}/index.js`), tabsApiSource, ); } }); }
6,008
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/getBaseUiComponentInfo.test.ts
import path from 'path'; import fs from 'fs'; import { expect } from 'chai'; import sinon from 'sinon'; import { getBaseUiComponentInfo } from './getBaseUiComponentInfo'; describe('getBaseUiComponentInfo', () => { it('return correct info for base component file', () => { const info = getBaseUiComponentInfo( path.join(process.cwd(), `/packages/mui-base/src/Button/Button.tsx`), ); sinon.assert.match(info, { name: 'Button', apiPathname: '/base-ui/react-button/components-api/#button', muiName: 'MuiButton', apiPagesDirectory: sinon.match((value) => value.endsWith(path.join('docs', 'pages', 'base-ui', 'api')), ), }); info.readFile(); expect(info.getInheritance()).to.deep.equal(null); let existed = false; try { fs.readdirSync(path.join(process.cwd(), 'docs/data')); existed = true; // eslint-disable-next-line no-empty } catch (error) {} if (existed) { expect(info.getDemos()).to.deep.equal([ { demoPageTitle: 'Button', demoPathname: '/base-ui/react-button/', }, ]); } }); });
6,009
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/getBaseUiComponentInfo.ts
import fs from 'fs'; import path from 'path'; import kebabCase from 'lodash/kebabCase'; import { getHeaders, getTitle } from '@mui/markdown'; import { ComponentInfo, extractPackageFile, fixPathname, getApiPath, getMuiName, getSystemComponents, parseFile, } from '@mui-internal/api-docs-builder/buildApiUtils'; import findPagesMarkdown from '@mui-internal/api-docs-builder/utils/findPagesMarkdown'; import { migratedBaseComponents } from './migratedBaseComponents'; function findBaseDemos( componentName: string, pagesMarkdown: ReadonlyArray<{ pathname: string; components: readonly string[]; markdownContent: string; }>, ) { return pagesMarkdown .filter((page) => page.components.includes(componentName)) .map((page) => ({ demoPageTitle: getTitle(page.markdownContent), demoPathname: fixPathname(page.pathname), })); } export function getBaseUiComponentInfo(filename: string): ComponentInfo { const { name } = extractPackageFile(filename); let srcInfo: null | ReturnType<ComponentInfo['readFile']> = null; if (!name) { throw new Error(`Could not find the component name from: ${filename}`); } // resolve demos, so that we can getch the API url const allMarkdowns = findPagesMarkdown() .filter((markdown) => { if (migratedBaseComponents.some((component) => filename.includes(component))) { return markdown.filename.match(/[\\/]data[\\/]base[\\/]/); } return true; }) .map((markdown) => { const markdownContent = fs.readFileSync(markdown.filename, 'utf8'); const markdownHeaders = getHeaders(markdownContent) as any; return { ...markdown, markdownContent, components: markdownHeaders.components as string[], }; }); const demos = findBaseDemos(name, allMarkdowns); const apiPath = getApiPath(demos, name); return { filename, name, muiName: getMuiName(name), apiPathname: apiPath ?? `/base-ui/api/${kebabCase(name)}/`, apiPagesDirectory: path.join(process.cwd(), `docs/pages/base-ui/api`), isSystemComponent: getSystemComponents().includes(name), readFile: () => { srcInfo = parseFile(filename); return srcInfo; }, getInheritance: (inheritedComponent = srcInfo?.inheritedComponent) => { if (!inheritedComponent) { return null; } return { name: inheritedComponent, apiPathname: inheritedComponent === 'Transition' ? 'http://reactcommunity.org/react-transition-group/transition/#Transition-props' : `/base-ui/api/${kebabCase(inheritedComponent)}/`, }; }, getDemos: () => demos, }; }
6,010
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/getBaseUiHookInfo.test.ts
import path from 'path'; import fs from 'fs'; import { expect } from 'chai'; import sinon from 'sinon'; import { getBaseUiHookInfo } from './getBaseUiHookInfo'; describe('getBaseUiHookInfo', () => { it('return correct info for base hook file', () => { const info = getBaseUiHookInfo( path.join(process.cwd(), `/packages/mui-base/src/useButton/useButton.ts`), ); sinon.assert.match(info, { name: 'useButton', apiPathname: '/base-ui/react-button/hooks-api/#use-button', }); info.readFile(); let existed = false; try { fs.readdirSync(path.join(process.cwd(), 'docs/data')); existed = true; // eslint-disable-next-line no-empty } catch (error) {} if (existed) { expect(info.getDemos()).to.deep.equal([ { demoPageTitle: 'Button', demoPathname: '/base-ui/react-button/#hook', }, ]); } }); });
6,011
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/getBaseUiHookInfo.ts
import fs from 'fs'; import path from 'path'; import kebabCase from 'lodash/kebabCase'; import { getHeaders, getTitle } from '@mui/markdown'; import { ComponentInfo, HookInfo, extractPackageFile, fixPathname, getApiPath, parseFile, } from '@mui-internal/api-docs-builder/buildApiUtils'; import findPagesMarkdown from '@mui-internal/api-docs-builder/utils/findPagesMarkdown'; import { migratedBaseComponents } from './migratedBaseComponents'; export function getBaseUiHookInfo(filename: string): HookInfo { const { name } = extractPackageFile(filename); let srcInfo: null | ReturnType<ComponentInfo['readFile']> = null; if (!name) { throw new Error(`Could not find the hook name from: ${filename}`); } const allMarkdowns = findPagesMarkdown() .filter((markdown) => { if (migratedBaseComponents.some((component) => filename.includes(component))) { return markdown.filename.match(/[\\/]data[\\/]base[\\/]/); } return true; }) .map((markdown) => { const markdownContent = fs.readFileSync(markdown.filename, 'utf8'); const markdownHeaders = getHeaders(markdownContent) as any; return { ...markdown, markdownContent, hooks: markdownHeaders.hooks as string[], }; }); const demos = findBaseHooksDemos(name, allMarkdowns); const apiPath = getApiPath(demos, name); const result = { filename, name, apiPathname: apiPath ?? `/base-ui/api/${kebabCase(name)}/`, apiPagesDirectory: path.join(process.cwd(), `docs/pages/base-ui/api`), readFile: () => { srcInfo = parseFile(filename); return srcInfo; }, getDemos: () => demos, }; return result; } function findBaseHooksDemos( hookName: string, pagesMarkdown: ReadonlyArray<{ pathname: string; hooks: readonly string[]; markdownContent: string; }>, ) { return pagesMarkdown .filter((page) => page.hooks && page.hooks.includes(hookName)) .map((page) => ({ demoPageTitle: getTitle(page.markdownContent), demoPathname: `${fixPathname(page.pathname)}#hook${page.hooks?.length > 1 ? 's' : ''}`, })); }
6,012
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/migratedBaseComponents.ts
export const migratedBaseComponents = [ 'Badge', 'Button', 'ClickAwayListener', 'FocusTrap', 'Input', 'MenuItem', 'Menu', 'Modal', 'NoSsr', 'OptionGroup', 'Option', 'Popper', 'Portal', 'Select', 'Slider', 'Switch', 'TablePagination', 'TabPanel', 'TabsList', 'Tabs', 'Tab', ];
6,013
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/baseUi/projectSettings.ts
import path from 'path'; import { LANGUAGES } from 'docs/config'; import { ProjectSettings } from '@mui-internal/api-docs-builder'; import findApiPages from '@mui-internal/api-docs-builder/utils/findApiPages'; import { getBaseUiComponentInfo } from './getBaseUiComponentInfo'; import { getBaseUiHookInfo } from './getBaseUiHookInfo'; import { generateBaseUIApiPages } from './generateBaseUiApiPages'; import { generateApiLinks } from './generateApiLinks'; export const projectSettings: ProjectSettings = { output: { apiManifestPath: path.join(process.cwd(), 'docs/data/base/pagesApi.js'), }, typeScriptProjects: [ { name: 'base', rootPath: path.join(process.cwd(), 'packages/mui-base'), entryPointPath: 'src/index.d.ts', }, ], getApiPages: () => findApiPages('docs/pages/base-ui/api'), getComponentInfo: getBaseUiComponentInfo, getHookInfo: getBaseUiHookInfo, translationLanguages: LANGUAGES, skipComponent: () => false, onCompleted: () => { generateBaseUIApiPages(); }, onWritingManifestFile(builds, source) { const apiLinks = generateApiLinks(builds); if (apiLinks.length > 0) { return `module.exports = ${JSON.stringify(apiLinks)}`; } return source; }, };
6,014
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/joyUi/getJoyUiComponentInfo.ts
import fs from 'fs'; import path from 'path'; import kebabCase from 'lodash/kebabCase'; import { getHeaders, getTitle } from '@mui/markdown'; import { ComponentInfo, extractPackageFile, fixPathname, getMuiName, getSystemComponents, parseFile, } from '@mui-internal/api-docs-builder/buildApiUtils'; import findPagesMarkdown from '@mui-internal/api-docs-builder/utils/findPagesMarkdown'; export function getJoyUiComponentInfo(filename: string): ComponentInfo { const { name } = extractPackageFile(filename); let srcInfo: null | ReturnType<ComponentInfo['readFile']> = null; if (!name) { throw new Error(`Could not find the component name from: ${filename}`); } return { filename, name, muiName: getMuiName(name), apiPathname: `/joy-ui/api/${kebabCase(name)}/`, apiPagesDirectory: path.join(process.cwd(), `docs/pages/joy-ui/api`), isSystemComponent: getSystemComponents().includes(name), readFile: () => { srcInfo = parseFile(filename); return srcInfo; }, getInheritance: (inheritedComponent = srcInfo?.inheritedComponent) => { if (!inheritedComponent) { return null; } // `inheritedComponent` node is coming from test files. // `inheritedComponent` must include `Unstyled` suffix for parser to recognise that the component inherits Base UI component // e.g., Joy Menu inherits Base UI Popper, and its test file uses the name `PopperUnstyled` so that we can recognise here that // Joy Menu is inheriting a base component. In terms of documentation, we should no longer use the name `PopperUnstyled`, and hence // we remove the suffix here. return { name: inheritedComponent.replace(/unstyled/i, ''), apiPathname: `/${ inheritedComponent.match(/unstyled/i) ? 'base-ui' : 'joy-ui' }/api/${kebabCase(inheritedComponent.replace(/unstyled/i, ''))}/`, }; }, getDemos: () => { const allMarkdowns = findPagesMarkdown().map((markdown) => { const markdownContent = fs.readFileSync(markdown.filename, 'utf8'); const markdownHeaders = getHeaders(markdownContent) as any; return { ...markdown, markdownContent, components: markdownHeaders.components as string[], }; }); return allMarkdowns .filter((page) => page.pathname.startsWith('/joy') && page.components.includes(name)) .map((page) => ({ demoPageTitle: getTitle(page.markdownContent), demoPathname: fixPathname(page.pathname), })); }, }; }
6,015
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/joyUi/projectSettings.ts
import path from 'path'; import { LANGUAGES } from 'docs/config'; import { ProjectSettings } from '@mui-internal/api-docs-builder'; import findApiPages from '@mui-internal/api-docs-builder/utils/findApiPages'; import { getJoyUiComponentInfo } from './getJoyUiComponentInfo'; export const projectSettings: ProjectSettings = { output: { apiManifestPath: path.join(process.cwd(), 'docs/data/joy/pagesApi.js'), }, typeScriptProjects: [ { name: 'joy', rootPath: path.join(process.cwd(), 'packages/mui-joy'), entryPointPath: 'src/index.ts', }, ], getApiPages: () => findApiPages('docs/pages/joy-ui/api'), getComponentInfo: getJoyUiComponentInfo, translationLanguages: LANGUAGES, skipComponent(filename: string) { // Container's demo isn't ready // GlobalStyles's demo isn't ready return ( filename.match(/(ThemeProvider|CssVarsProvider|Container|ColorInversion|GlobalStyles)/) !== null ); }, };
6,016
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/materialUi/getMaterialUiComponentInfo.test.ts
import path from 'path'; import fs from 'fs'; import { expect } from 'chai'; import sinon from 'sinon'; import { getMaterialUiComponentInfo } from './getMaterialUiComponentInfo'; describe('getMaterialUiComponentInfo', () => { it('return correct info for material component file', () => { const info = getMaterialUiComponentInfo( path.join(process.cwd(), `/packages/mui-material/src/Button/Button.js`), ); sinon.assert.match(info, { name: 'Button', apiPathname: '/material-ui/api/button/', muiName: 'MuiButton', apiPagesDirectory: sinon.match((value) => value.endsWith(path.join('docs', 'pages', 'material-ui', 'api')), ), }); expect(info.getInheritance('ButtonBase')).to.deep.equal({ name: 'ButtonBase', apiPathname: '/material-ui/api/button-base/', }); let existed = false; try { fs.readdirSync(path.join(process.cwd(), 'docs/data')); existed = true; // eslint-disable-next-line no-empty } catch (error) {} if (existed) { expect(info.getDemos()).to.deep.equal([ { demoPageTitle: 'Button Group', demoPathname: '/material-ui/react-button-group/', }, { demoPageTitle: 'Button', demoPathname: '/material-ui/react-button/', }, ]); } }); });
6,017
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/materialUi/getMaterialUiComponentInfo.ts
import fs from 'fs'; import path from 'path'; import kebabCase from 'lodash/kebabCase'; import { getHeaders, getTitle } from '@mui/markdown'; import { ComponentInfo, extractPackageFile, fixPathname, getMuiName, getSystemComponents, parseFile, } from '@mui-internal/api-docs-builder/buildApiUtils'; import findPagesMarkdown from '@mui-internal/api-docs-builder/utils/findPagesMarkdown'; export function getMaterialUiComponentInfo(filename: string): ComponentInfo { const { name } = extractPackageFile(filename); let srcInfo: null | ReturnType<ComponentInfo['readFile']> = null; if (!name) { throw new Error(`Could not find the component name from: ${filename}`); } return { filename, name, muiName: getMuiName(name), apiPathname: `/material-ui/api/${kebabCase(name)}/`, apiPagesDirectory: path.join(process.cwd(), `docs/pages/material-ui/api`), isSystemComponent: getSystemComponents().includes(name), readFile: () => { srcInfo = parseFile(filename); return srcInfo; }, getInheritance: (inheritedComponent = srcInfo?.inheritedComponent) => { if (!inheritedComponent) { return null; } // `inheritedComponent` node is coming from test files. // `inheritedComponent` must include `Unstyled` suffix for parser to recognise that the component inherits Base UI component // e.g., Joy Menu inherits Base UI Popper, and its test file uses the name `PopperUnstyled` so that we can recognise here that // Joy Menu is inheriting a base component. In terms of documentation, we should no longer use the name `PopperUnstyled`, and hence // we remove the suffix here. return { name: inheritedComponent.replace(/unstyled/i, ''), apiPathname: inheritedComponent === 'Transition' ? 'http://reactcommunity.org/react-transition-group/transition/#Transition-props' : `/${ inheritedComponent.match(/unstyled/i) ? 'base-ui' : 'material-ui' }/api/${kebabCase(inheritedComponent.replace(/unstyled/i, ''))}/`, }; }, getDemos: () => { const allMarkdowns = findPagesMarkdown().map((markdown) => { const markdownContent = fs.readFileSync(markdown.filename, 'utf8'); const markdownHeaders = getHeaders(markdownContent) as any; return { ...markdown, markdownContent, components: markdownHeaders.components as string[], }; }); return allMarkdowns .filter((page) => page.pathname.startsWith('/material') && page.components.includes(name)) .map((page) => ({ demoPageTitle: getTitle(page.markdownContent), demoPathname: fixPathname(page.pathname), })); }, }; }
6,018
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/materialUi/projectSettings.ts
import path from 'path'; import { LANGUAGES } from 'docs/config'; import { ProjectSettings } from '@mui-internal/api-docs-builder'; import findApiPages from '@mui-internal/api-docs-builder/utils/findApiPages'; import { getMaterialUiComponentInfo } from './getMaterialUiComponentInfo'; export const projectSettings: ProjectSettings = { output: { apiManifestPath: path.join(process.cwd(), 'docs/data/material/pagesApi.js'), }, typeScriptProjects: [ { name: 'material', rootPath: path.join(process.cwd(), 'packages/mui-material'), entryPointPath: 'src/index.d.ts', }, { name: 'lab', rootPath: path.join(process.cwd(), 'packages/mui-lab'), entryPointPath: 'src/index.d.ts', }, ], getApiPages: () => findApiPages('docs/pages/material-ui/api'), getComponentInfo: getMaterialUiComponentInfo, translationLanguages: LANGUAGES, skipComponent(filename: string) { return filename.match(/(ThemeProvider|CssVarsProvider|Grid2)/) !== null; }, };
6,019
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/muiSystem/getSystemComponentInfo.ts
import fs from 'fs'; import path from 'path'; import kebabCase from 'lodash/kebabCase'; import { getHeaders, getTitle } from '@mui/markdown'; import { ComponentInfo, extractPackageFile, getMuiName, parseFile, fixPathname, } from '@mui-internal/api-docs-builder/buildApiUtils'; import findPagesMarkdown from '@mui-internal/api-docs-builder/utils/findPagesMarkdown'; const migratedBaseComponents = [ 'Badge', 'Button', 'ClickAwayListener', 'FocusTrap', 'Input', 'MenuItem', 'Menu', 'Modal', 'NoSsr', 'OptionGroup', 'Option', 'Popper', 'Portal', 'Select', 'Slider', 'Switch', 'TablePagination', 'TabPanel', 'TabsList', 'Tabs', 'Tab', ]; export function getSystemComponentInfo(filename: string): ComponentInfo { const { name } = extractPackageFile(filename); let srcInfo: null | ReturnType<ComponentInfo['readFile']> = null; if (!name) { throw new Error(`Could not find the component name from: ${filename}`); } return { filename, name, muiName: getMuiName(name), apiPathname: `/system/api/${kebabCase(name)}/`, apiPagesDirectory: path.join(process.cwd(), `docs/pages/system/api`), isSystemComponent: true, readFile: () => { srcInfo = parseFile(filename); return srcInfo; }, getInheritance() { return null; }, getDemos: () => { const allMarkdowns = findPagesMarkdown() .filter((markdown) => { if (migratedBaseComponents.some((component) => filename.includes(component))) { return markdown.filename.match(/[\\/]data[\\/]system[\\/]/); } return true; }) .map((markdown) => { const markdownContent = fs.readFileSync(markdown.filename, 'utf8'); const markdownHeaders = getHeaders(markdownContent) as any; return { ...markdown, markdownContent, components: markdownHeaders.components as string[], }; }); return allMarkdowns .filter((page) => page.components.includes(name)) .map((page) => ({ demoPageTitle: pathToSystemTitle({ ...page, title: getTitle(page.markdownContent), }), demoPathname: fixPathname(page.pathname), })); }, }; } interface PageMarkdown { pathname: string; title: string; components: readonly string[]; } function pathToSystemTitle(page: PageMarkdown) { const defaultTitle = page.title; if (page.pathname.startsWith('/material')) { return `${defaultTitle} (Material UI)`; } if (page.pathname.startsWith('/system')) { return `${defaultTitle} (MUI System)`; } if (page.pathname.startsWith('/joy')) { return `${defaultTitle} (Joy UI)`; } return defaultTitle; }
6,020
0
petrpan-code/mui/material-ui/packages/api-docs-builder-core
petrpan-code/mui/material-ui/packages/api-docs-builder-core/muiSystem/projectSettings.ts
import path from 'path'; import { LANGUAGES } from 'docs/config'; import { ProjectSettings } from '@mui-internal/api-docs-builder'; import findApiPages from '@mui-internal/api-docs-builder/utils/findApiPages'; import { getSystemComponentInfo } from './getSystemComponentInfo'; export const projectSettings: ProjectSettings = { output: { apiManifestPath: path.join(process.cwd(), 'docs/data/system/pagesApi.js'), }, typeScriptProjects: [ { name: 'system', rootPath: path.join(process.cwd(), 'packages/mui-system'), entryPointPath: 'src/index.d.ts', }, ], getApiPages: () => findApiPages('docs/pages/system/api'), getComponentInfo: getSystemComponentInfo, translationLanguages: LANGUAGES, skipComponent(filename) { return filename.match(/(ThemeProvider|CssVarsProvider|GlobalStyles)/) !== null; }, };
6,021
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/.eslintrc.js
module.exports = { rules: { 'import/prefer-default-export': 'off', }, };
6,022
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/ProjectSettings.ts
import { ComponentInfo, HookInfo } from './buildApiUtils'; import { CreateTypeScriptProjectOptions } from './utils/createTypeScriptProject'; import { ReactApi as ComponentReactApi } from './ApiBuilders/ComponentApiBuilder'; import { ReactApi as HookReactApi } from './ApiBuilders/HookApiBuilder'; export interface ProjectSettings { output: { /** * The output path of `pagesApi` generated from `input.pageDirectory` */ apiManifestPath: string; }; /** * Component directories to be used to generate API */ typeScriptProjects: CreateTypeScriptProjectOptions[]; getApiPages: () => Array<{ pathname: string }>; getComponentInfo: (filename: string) => ComponentInfo; getHookInfo?: (filename: string) => HookInfo; /** * Callback function to be called when the API generation is completed */ onCompleted?: () => void; /** * Callback to customize the manifest file before it's written to the disk */ onWritingManifestFile?: ( builds: PromiseSettledResult<ComponentReactApi | HookReactApi | null | never[]>[], source: string, ) => string; /** * Languages to which the API docs will be generated */ translationLanguages: string[]; /** * Fuction called to detemine whether to skip the generation of a particular component's API docs */ skipComponent: (filename: string) => boolean; }
6,023
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/buildApi.ts
import { mkdirSync } from 'fs'; import path from 'path'; import * as fse from 'fs-extra'; import kebabCase from 'lodash/kebabCase'; import findComponents from './utils/findComponents'; import findHooks from './utils/findHooks'; import { writePrettifiedFile } from './buildApiUtils'; import generateComponentApi, { ReactApi as ComponentReactApi, } from './ApiBuilders/ComponentApiBuilder'; import generateHookApi from './ApiBuilders/HookApiBuilder'; import { CreateTypeScriptProjectOptions, TypeScriptProjectBuilder, createTypeScriptProjectBuilder, } from './utils/createTypeScriptProject'; import { ProjectSettings } from './ProjectSettings'; const apiDocsTranslationsDirectory = path.resolve('docs', 'translations', 'api-docs'); async function removeOutdatedApiDocsTranslations( components: readonly ComponentReactApi[], ): Promise<void> { const componentDirectories = new Set<string>(); const files = await fse.readdir(apiDocsTranslationsDirectory); await Promise.all( files.map(async (filename) => { const filepath = path.join(apiDocsTranslationsDirectory, filename); const stats = await fse.stat(filepath); if (stats.isDirectory()) { componentDirectories.add(filepath); } }), ); const currentComponentDirectories = new Set( components.map((component) => { return path.resolve(apiDocsTranslationsDirectory, kebabCase(component.name)); }), ); const outdatedComponentDirectories = new Set(componentDirectories); currentComponentDirectories.forEach((componentDirectory) => { outdatedComponentDirectories.delete(componentDirectory); }); await Promise.all( Array.from(outdatedComponentDirectories, (outdatedComponentDirectory) => { return fse.remove(outdatedComponentDirectory); }), ); } export async function buildApi(projectsSettings: ProjectSettings[], grep: RegExp | null = null) { const allTypeScriptProjects = projectsSettings .flatMap((setting) => setting.typeScriptProjects) .reduce((acc, project) => { acc[project.name] = project; return acc; }, {} as Record<string, CreateTypeScriptProjectOptions>); const buildTypeScriptProject = createTypeScriptProjectBuilder(allTypeScriptProjects); let allBuilds: Array<PromiseSettledResult<ComponentReactApi | null>> = []; for (let i = 0; i < projectsSettings.length; i += 1) { const setting = projectsSettings[i]; // eslint-disable-next-line no-await-in-loop const projectBuilds = await buildSingleProject(setting, buildTypeScriptProject, grep); // @ts-ignore ignore hooks builds for now allBuilds = [...allBuilds, ...projectBuilds]; } if (grep === null) { const componentApis = allBuilds .filter((build): build is PromiseFulfilledResult<ComponentReactApi> => { return build.status === 'fulfilled' && build.value !== null; }) .map((build) => { return build.value; }); await removeOutdatedApiDocsTranslations(componentApis); } } async function buildSingleProject( projectSettings: ProjectSettings, buildTypeScriptProject: TypeScriptProjectBuilder, grep: RegExp | null, ) { const tsProjects = projectSettings.typeScriptProjects.map((project) => buildTypeScriptProject(project.name), ); const apiPagesManifestPath = projectSettings.output.apiManifestPath; const manifestDir = apiPagesManifestPath.match(/(.*)\/[^/]+\./)?.[1]; if (manifestDir) { mkdirSync(manifestDir, { recursive: true }); } const apiBuilds = tsProjects.flatMap((project) => { const projectComponents = findComponents(path.join(project.rootPath, 'src')).filter( (component) => { if (projectSettings.skipComponent(component.filename)) { return false; } if (grep === null) { return true; } return grep.test(component.filename); }, ); const projectHooks = findHooks(path.join(project.rootPath, 'src')).filter((hook) => { if (grep === null) { return true; } return grep.test(hook.filename); }); const componentsBuilds = projectComponents.map(async (component) => { try { const componentInfo = projectSettings.getComponentInfo(component.filename); mkdirSync(componentInfo.apiPagesDirectory, { mode: 0o777, recursive: true }); return await generateComponentApi(componentInfo, project, projectSettings); } catch (error: any) { error.message = `${path.relative(process.cwd(), component.filename)}: ${error.message}`; throw error; } }); const hooksBuilds = projectHooks.map(async (hook) => { if (!projectSettings.getHookInfo) { return []; } try { const { filename } = hook; const hookInfo = projectSettings.getHookInfo(filename); mkdirSync(hookInfo.apiPagesDirectory, { mode: 0o777, recursive: true }); return generateHookApi(hookInfo, project, projectSettings); } catch (error: any) { error.message = `${path.relative(process.cwd(), hook.filename)}: ${error.message}`; throw error; } }); return [...componentsBuilds, ...hooksBuilds]; }); const builds = await Promise.allSettled(apiBuilds); const fails = builds.filter( (promise): promise is PromiseRejectedResult => promise.status === 'rejected', ); fails.forEach((build) => { console.error(build.reason); }); if (fails.length > 0) { process.exit(1); } let source = `module.exports = ${JSON.stringify(projectSettings.getApiPages())}`; if (projectSettings.onWritingManifestFile) { source = projectSettings.onWritingManifestFile(builds, source); } writePrettifiedFile(apiPagesManifestPath, source); projectSettings.onCompleted?.(); return builds; }
6,024
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/buildApiUtils.test.ts
import sinon from 'sinon'; import { extractPackageFile } from './buildApiUtils'; describe('buildApiUtils', () => { describe('extractPackageFilePath', () => { it('return info if path is a package (material)', () => { const result = extractPackageFile('/material-ui/packages/mui-material/src/Button/Button.js'); sinon.assert.match(result, { packagePath: 'mui-material', muiPackage: 'mui-material', name: 'Button', }); }); it('return info if path is a package (lab)', () => { const result = extractPackageFile( '/material-ui/packages/mui-lab/src/LoadingButton/LoadingButton.js', ); sinon.assert.match(result, { packagePath: 'mui-lab', muiPackage: 'mui-lab', name: 'LoadingButton', }); }); it('return info if path is a package (base)', () => { const result = extractPackageFile('/material-ui/packages/mui-base/src/Tab/Tab.tsx'); sinon.assert.match(result, { packagePath: 'mui-base', muiPackage: 'mui-base', name: 'Tab', }); }); it('return info if path is a package (data-grid)', () => { const result = extractPackageFile('/material-ui/packages/grid/x-data-grid/src/DataGrid.tsx'); sinon.assert.match(result, { packagePath: 'x-data-grid', muiPackage: 'mui-data-grid', name: 'DataGrid', }); }); it('return info if path is a package (data-grid-pro)', () => { const result = extractPackageFile( '/material-ui/packages/grid/x-data-grid-pro/src/DataGridPro.tsx', ); sinon.assert.match(result, { packagePath: 'x-data-grid-pro', muiPackage: 'mui-data-grid-pro', name: 'DataGridPro', }); }); it('return null if path is not a package', () => { const result = extractPackageFile( '/material-ui/docs/pages/material/getting-started/getting-started.md', ); sinon.assert.match(result, { packagePath: null, name: null, }); }); }); });
6,025
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/buildApiUtils.ts
import fs from 'fs'; import path from 'path'; import * as ts from 'typescript'; import * as prettier from 'prettier'; import kebabCase from 'lodash/kebabCase'; import { getLineFeed } from '@mui-internal/docs-utilities'; import { replaceComponentLinks } from './utils/replaceUrl'; import { TypeScriptProject } from './utils/createTypeScriptProject'; /** * TODO: this should really be fixed in findPagesMarkdown(). * Plus replaceComponentLinks() shouldn't exist in the first place, * the markdown folder location should match the URLs. */ export function fixPathname(pathname: string): string { let fixedPathname; if (pathname.startsWith('/material')) { fixedPathname = replaceComponentLinks(`${pathname.replace(/^\/material/, '')}/`); } else if (pathname.startsWith('/joy')) { fixedPathname = replaceComponentLinks(`${pathname.replace(/^\/joy/, '')}/`).replace( 'material-ui', 'joy-ui', ); } else if (pathname.startsWith('/base')) { fixedPathname = `${pathname .replace('/base/', '/base-ui/') .replace('/components/', '/react-')}/`; } else { fixedPathname = `${pathname.replace('/components/', '/react-')}/`; } return fixedPathname; } const DEFAULT_PRETTIER_CONFIG_PATH = path.join(process.cwd(), 'prettier.config.js'); export function writePrettifiedFile( filename: string, data: string, prettierConfigPath: string = DEFAULT_PRETTIER_CONFIG_PATH, options: object = {}, ) { const prettierConfig = prettier.resolveConfig.sync(filename, { config: prettierConfigPath, }); if (prettierConfig === null) { throw new Error( `Could not resolve config for '${filename}' using prettier config path '${prettierConfigPath}'.`, ); } fs.writeFileSync(filename, prettier.format(data, { ...prettierConfig, filepath: filename }), { encoding: 'utf8', ...options, }); } let systemComponents: string[] | undefined; // making the resolution lazy to avoid issues when importing something irrelevant from this file (i.e. `getSymbolDescription`) // the eager resolution results in errors when consuming externally (i.e. `mui-x`) export function getSystemComponents() { if (!systemComponents) { systemComponents = fs .readdirSync(path.resolve('packages', 'mui-system', 'src')) // Normalization, the Unstable_ prefix doesn't count. .map((pathname) => pathname.replace('Unstable_', '')) .filter((pathname) => pathname.match(/^[A-Z][a-zA-Z]+$/)); } return systemComponents; } export function getMuiName(name: string) { return `Mui${name.replace('Styled', '')}`; } export function extractPackageFile(filePath: string) { filePath = filePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'); const match = filePath.match( /.*\/packages.*\/(?<packagePath>[^/]+)\/src\/(.*\/)?(?<name>[^/]+)\.(js|tsx|ts|d\.ts)/, ); const result = { packagePath: match ? match.groups?.packagePath! : null, name: match ? match.groups?.name! : null, }; return { ...result, muiPackage: result.packagePath?.replace('x-', 'mui-'), }; } export function parseFile(filename: string) { const src = fs.readFileSync(filename, 'utf8'); return { src, shouldSkip: filename.indexOf('internal') !== -1 || !!src.match(/@ignore - internal component\./) || !!src.match(/@ignore - internal hook\./) || !!src.match(/@ignore - do not document\./), spread: !src.match(/ = exactProp\(/), EOL: getLineFeed(src), inheritedComponent: src.match(/\/\/ @inheritedComponent (.*)/)?.[1], }; } export type ComponentInfo = { /** * Full path to the source file. */ filename: string; /** * Component name as imported in the docs, in the global MUI namespace. */ name: string; /** * Component name with `Mui` prefix, in the global HTML page namespace. */ muiName: string; apiPathname: string; readFile: () => { src: string; spread: boolean; shouldSkip: boolean; EOL: string; inheritedComponent?: string; }; getInheritance: (inheritedComponent?: string) => null | { /** * Component name */ name: string; /** * API pathname */ apiPathname: string; }; getDemos: () => Array<{ demoPageTitle: string; demoPathname: string }>; apiPagesDirectory: string; skipApiGeneration?: boolean; /** * If `true`, the component's name match one of the system components. */ isSystemComponent?: boolean; }; export type HookInfo = { /** * Full path to the source file. */ filename: string; /** * Hook name as imported in the docs, in the global MUI namespace. */ name: string; apiPathname: string; readFile: ComponentInfo['readFile']; getDemos: ComponentInfo['getDemos']; apiPagesDirectory: string; skipApiGeneration?: boolean; }; export const getApiPath = ( demos: Array<{ demoPageTitle: string; demoPathname: string }>, name: string, ) => { let apiPath = null; if (demos && demos.length > 0) { // remove the hash from the demoPathname, for e.g. "#hooks" const cleanedDemosPathname = demos[0].demoPathname.split('#')[0]; apiPath = `${cleanedDemosPathname}${ name.startsWith('use') ? 'hooks-api' : 'components-api' }/#${kebabCase(name)}`; } return apiPath; }; export function formatType(rawType: string) { if (!rawType) { return ''; } const prefix = 'type FakeType = '; const signatureWithTypeName = `${prefix}${rawType}`; const prettifiedSignatureWithTypeName = prettier.format(signatureWithTypeName, { printWidth: 999, singleQuote: true, semi: false, trailingComma: 'none', parser: 'typescript', }); return prettifiedSignatureWithTypeName.slice(prefix.length).replace(/\n$/, ''); } export function getSymbolDescription(symbol: ts.Symbol, project: TypeScriptProject) { return symbol .getDocumentationComment(project.checker) .flatMap((comment) => comment.text.split('\n')) .filter((line) => !line.startsWith('TODO')) .join('\n'); } export function getSymbolJSDocTags(symbol: ts.Symbol) { return Object.fromEntries(symbol.getJsDocTags().map((tag) => [tag.name, tag])); } export function stringifySymbol(symbol: ts.Symbol, project: TypeScriptProject) { let rawType: string; const declaration = symbol.declarations?.[0]; if (declaration && ts.isPropertySignature(declaration)) { rawType = declaration.type?.getText() ?? ''; } else { rawType = project.checker.typeToString( project.checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration!), symbol.valueDeclaration, ts.TypeFormatFlags.NoTruncation, ); } return formatType(rawType); }
6,026
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/index.ts
export { buildApi } from './buildApi'; export type { ProjectSettings } from './ProjectSettings';
6,027
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/package.json
{ "name": "@mui-internal/api-docs-builder", "version": "1.0.0", "private": "true", "main": "./index.ts", "scripts": { "test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/api-docs-builder/**/*.test.{js,ts,tsx}'", "typescript": "tsc -p tsconfig.json" }, "dependencies": { "@babel/core": "^7.23.3", "@babel/preset-typescript": "^7.23.3", "@babel/traverse": "^7.23.3", "@mui-internal/docs-utilities": "^1.0.0", "@mui/markdown": "^5.0.0", "@mui/utils": "^5.14.18", "ast-types": "^0.14.2", "doctrine": "^3.0.0", "fast-glob": "^3.3.2", "fs-extra": "^11.1.1", "lodash": "^4.17.21", "prettier": "^2.8.8", "react-docgen": "^5.4.3", "recast": "^0.23.4", "remark": "^13.0.0", "unist-util-visit": "^2.0.3" }, "devDependencies": { "@types/babel__core": "^7.20.4", "@types/babel__traverse": "^7.20.4", "@types/chai": "^4.3.10", "@types/doctrine": "^0.0.9", "@types/mdast": "4.0.3", "@types/mocha": "^10.0.4", "@types/node": "^18.18.10", "@types/sinon": "^10.0.20", "chai": "^4.3.10", "sinon": "^15.2.0", "typescript": "^5.1.6" } }
6,028
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/react-docgen.d.ts
declare module 'react-docgen' { import { namedTypes } from 'ast-types'; // `import { NodePath } from 'ast-types';` points to `const NodePath: NodePathConstructor` for unknown reasons. import { NodePath as AstTypesNodePath } from 'ast-types/lib/node-path'; export type Node = namedTypes.Node; // sound wrapper around `NodePath` from `ast-types` i.e. no `any` export type NodePath<SpecificNode extends Node = Node, Value = unknown> = AstTypesNodePath< SpecificNode, Value | undefined >; export interface Documentation { toObject(): ReactDocgenApi; } export type Handler = ( documentation: Documentation, componentDefinition: NodePath, importer: Importer, ) => void; export const defaultHandlers: readonly Handler[]; export type Importer = (path: NodePath, name: string) => NodePath | undefined; export type Resolver = ( ast: ASTNode, parser: unknown, importer: Importer, ) => NodePath | NodePath[] | undefined; export namespace resolver { export const findAllComponentDefinitions: Resolver; export const findExportedComponentDefinition: Resolver; export const findAllExportedComponentDefinitions: Resolver; } export interface ReactDocgenApi { description: string; props?: Record<string, PropDescriptor>; } export interface BasePropTypeDescriptor { computed?: boolean; description?: string; raw: string; required?: boolean; type?: PropType; } interface ArrayOfPropTypeDescriptor extends BasePropTypeDescriptor { name: 'arrayOf'; value: PropTypeDescriptor; } interface CustomPropTypeDescriptor extends BasePropTypeDescriptor { name: 'custom'; } interface EnumPropTypeDescriptor extends BasePropTypeDescriptor { name: 'enum'; value: readonly StringPropTypeDescriptor[]; } interface ArrayPropTypeDescriptor extends BasePropTypeDescriptor { name: 'array'; } interface BoolPropTypeDescriptor extends BasePropTypeDescriptor { name: 'bool'; } interface FuncPropTypeDescriptor extends BasePropTypeDescriptor { name: 'func'; } interface NumberPropTypeDescriptor extends BasePropTypeDescriptor { name: 'number'; } interface ObjectPropTypeDescriptor extends BasePropTypeDescriptor { name: 'object'; } interface StringPropTypeDescriptor extends BasePropTypeDescriptor { name: 'string'; value: string; } interface AnyPropTypeDescriptor extends BasePropTypeDescriptor { name: 'any'; } interface ElementPropTypeDescriptor extends BasePropTypeDescriptor { name: 'element'; } interface NodePropTypeDescriptor extends BasePropTypeDescriptor { name: 'node'; } interface SymbolPropTypeDescriptor extends BasePropTypeDescriptor { name: 'symbol'; } interface ObjectOfPropTypeDescriptor extends BasePropTypeDescriptor { name: 'objectOf'; } interface ShapePropTypeDescriptor extends BasePropTypeDescriptor { name: 'shape'; value: Record<string, PropTypeDescriptor>; } interface ExactPropTypeDescriptor extends BasePropTypeDescriptor { name: 'exact'; } interface UnionPropTypeDescriptor extends BasePropTypeDescriptor { name: 'union'; value: readonly PropTypeDescriptor[]; } interface ElementTypePropTypeDescriptor extends BasePropTypeDescriptor { name: 'elementType'; } // not listed in react-docgen interface InstanceOfPropTypeDescriptor extends BasePropTypeDescriptor { name: 'instanceOf'; value: string; } export type PropTypeDescriptor = | ShapePropTypeDescriptor | ArrayOfPropTypeDescriptor | CustomPropTypeDescriptor | EnumPropTypeDescriptor | ArrayPropTypeDescriptor | BoolPropTypeDescriptor | FuncPropTypeDescriptor | NumberPropTypeDescriptor | ObjectPropTypeDescriptor | StringPropTypeDescriptor | AnyPropTypeDescriptor | ElementPropTypeDescriptor | NodePropTypeDescriptor | SymbolPropTypeDescriptor | ObjectOfPropTypeDescriptor | ExactPropTypeDescriptor | UnionPropTypeDescriptor | ElementTypePropTypeDescriptor | InstanceOfPropTypeDescriptor; export interface PropDescriptor { defaultValue?: { computed: boolean; value: string }; // augmented by docs/src/modules/utils/defaultPropsHandler.js jsdocDefaultValue?: { computed?: boolean; value: string }; description?: string; required?: boolean; /** * react-docgen has this as nullable but it was never treated as such */ type: PropTypeDescriptor; } export interface AllLiteralPropType { type: 'AllLiteral'; } export interface TypeApplicationPropType { applications: readonly string[]; type: 'TypeApplication'; } export interface StringLiteralTypePropType { type: 'StringLiteralType'; } export interface UnionPropType { type: 'UnionType'; elements: readonly PropType[]; } export type PropType = | AllLiteralPropType | StringLiteralType | TypeApplicationPropType | UnionPropType; export function parse( source: string, componentResolver: null | Resolver, handlers: null | readonly Handler[], options: { filename: string }, ): any; export namespace utils { export function getPropertyName(path: NodePath): string | undefined; export function isReactForwardRefCall(path: NodePath, importer: Importer): boolean; export function printValue(path: NodePath): string; export function resolveExportDeclaration(path: NodePath, importer: Importer): NodePath[]; export function resolveToValue(path: NodePath, importer: Importer): NodePath; } }
6,029
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/api-docs-builder/tsconfig.json
{ "compilerOptions": { "allowJs": true, "isolatedModules": true, "noEmit": true, "noUnusedLocals": false, "resolveJsonModule": true, "skipLibCheck": true, "esModuleInterop": true, "types": ["node", "mocha"], "target": "ES2020", "module": "CommonJS", "moduleResolution": "node", "strict": true, "baseUrl": "./", "paths": { "react-docgen": ["./react-docgen.d.ts"] } }, "include": ["./**/*.ts", "./**/*.js"], "exclude": ["node_modules"] }
6,030
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/ApiBuilders/ComponentApiBuilder.ts
import { mkdirSync, readFileSync, writeFileSync } from 'fs'; import path from 'path'; import * as astTypes from 'ast-types'; import * as babel from '@babel/core'; import traverse from '@babel/traverse'; import * as _ from 'lodash'; import kebabCase from 'lodash/kebabCase'; import remark from 'remark'; import remarkVisit from 'unist-util-visit'; import { Link } from 'mdast'; import { defaultHandlers, parse as docgenParse, ReactDocgenApi } from 'react-docgen'; import { unstable_generateUtilityClass as generateUtilityClass } from '@mui/utils'; import { renderMarkdown } from '@mui/markdown'; import { ProjectSettings } from '../ProjectSettings'; import { ComponentInfo, writePrettifiedFile } from '../buildApiUtils'; import muiDefaultPropsHandler from '../utils/defaultPropsHandler'; import parseTest from '../utils/parseTest'; import generatePropTypeDescription, { getChained } from '../utils/generatePropTypeDescription'; import createDescribeableProp, { DescribeablePropDescriptor, } from '../utils/createDescribeableProp'; import generatePropDescription from '../utils/generatePropDescription'; import parseStyles, { Classes, Styles } from '../utils/parseStyles'; import { TypeScriptProject } from '../utils/createTypeScriptProject'; import parseSlotsAndClasses, { Slot } from '../utils/parseSlotsAndClasses'; export type AdditionalPropsInfo = { cssApi?: boolean; sx?: boolean; slotsApi?: boolean; 'joy-size'?: boolean; 'joy-color'?: boolean; 'joy-variant'?: boolean; }; export interface ReactApi extends ReactDocgenApi { demos: ReturnType<ComponentInfo['getDemos']>; EOL: string; filename: string; apiPathname: string; forwardsRefTo: string | undefined; inheritance: ReturnType<ComponentInfo['getInheritance']>; /** * react component name * @example 'Accordion' */ name: string; muiName: string; description: string; spread: boolean | undefined; /** * If `true`, the component supports theme default props customization. * If `null`, we couldn't infer this information. * If `undefined`, it's not applicable in this context, e.g. Base UI components. */ themeDefaultProps: boolean | undefined | null; /** * result of path.readFileSync from the `filename` in utf-8 */ src: string; styles: Styles; classes: Classes; slots: Slot[]; propsTable: _.Dictionary<{ default: string | undefined; required: boolean | undefined; type: { name: string | undefined; description: string | undefined }; deprecated: true | undefined; deprecationInfo: string | undefined; signature: undefined | { type: string; describedArgs?: string[]; returned?: string }; additionalInfo?: AdditionalPropsInfo; }>; /** * Different ways to import components */ imports: string[]; translations: { componentDescription: string; propDescriptions: { [key: string]: { description: string; requiresRef?: boolean; deprecated?: string; typeDescriptions?: { [t: string]: string }; }; }; classDescriptions: { [key: string]: { description: string; conditions?: string } }; slotDescriptions?: { [key: string]: string }; }; } const cssComponents = ['Box', 'Grid', 'Typography', 'Stack']; /** * Produces markdown of the description that can be hosted anywhere. * * By default we assume that the markdown is hosted on mui.com which is * why the source includes relative url. We transform them to absolute urls with * this method. */ export async function computeApiDescription( api: { description: ReactApi['description'] }, options: { host: string }, ): Promise<string> { const { host } = options; const file = await remark() .use(function docsLinksAttacher() { return function transformer(tree) { remarkVisit(tree, 'link', (linkNode: Link) => { if ((linkNode.url as string).startsWith('/')) { linkNode.url = `${host}${linkNode.url}`; } }); }; }) .process(api.description); return file.contents.toString().trim(); } /** * Add demos & API comment block to type definitions, e.g.: * /** * * Demos: * * * * - [Icons](https://mui.com/components/icons/) * * - [Material Icons](https://mui.com/components/material-icons/) * * * * API: * * * * - [Icon API](https://mui.com/api/icon/) */ async function annotateComponentDefinition(api: ReactApi) { const HOST = 'https://mui.com'; const typesFilename = api.filename.replace(/\.js$/, '.d.ts'); const fileName = path.parse(api.filename).name; const typesSource = readFileSync(typesFilename, { encoding: 'utf8' }); const typesAST = await babel.parseAsync(typesSource, { configFile: false, filename: typesFilename, presets: [require.resolve('@babel/preset-typescript')], }); if (typesAST === null) { throw new Error('No AST returned from babel.'); } let start = 0; let end = null; traverse(typesAST, { ExportDefaultDeclaration(babelPath) { if (api.filename.includes('mui-base')) { // Base UI does not use default exports. return; } /** * export default function Menu() {} */ let node: babel.Node = babelPath.node; if (node.declaration.type === 'Identifier') { // declare const Menu: {}; // export default Menu; if (babel.types.isIdentifier(babelPath.node.declaration)) { const bindingId = babelPath.node.declaration.name; const binding = babelPath.scope.bindings[bindingId]; // The JSDoc MUST be located at the declaration if (babel.types.isFunctionDeclaration(binding.path.node)) { // For function declarations the binding is equal to the declaration // /** // */ // function Component() {} node = binding.path.node; } else { // For variable declarations the binding points to the declarator. // /** // */ // const Component = () => {} node = binding.path.parentPath!.node; } } } const { leadingComments } = node; const leadingCommentBlocks = leadingComments != null ? leadingComments.filter(({ type }) => type === 'CommentBlock') : null; const jsdocBlock = leadingCommentBlocks != null ? leadingCommentBlocks[0] : null; if (leadingCommentBlocks != null && leadingCommentBlocks.length > 1) { throw new Error( `Should only have a single leading jsdoc block but got ${ leadingCommentBlocks.length }:\n${leadingCommentBlocks .map(({ type, value }, index) => `#${index} (${type}): ${value}`) .join('\n')}`, ); } if (jsdocBlock?.start != null && jsdocBlock?.end != null) { start = jsdocBlock.start; end = jsdocBlock.end; } else if (node.start != null) { start = node.start - 1; end = start; } }, ExportNamedDeclaration(babelPath) { if (!api.filename.includes('mui-base')) { return; } let node: babel.Node = babelPath.node; if (node.declaration == null) { // export { Menu }; node.specifiers.forEach((specifier) => { if (specifier.type === 'ExportSpecifier' && specifier.local.name === fileName) { const binding = babelPath.scope.bindings[specifier.local.name]; if (babel.types.isFunctionDeclaration(binding.path.node)) { // For function declarations the binding is equal to the declaration // /** // */ // function Component() {} node = binding.path.node; } else { // For variable declarations the binding points to the declarator. // /** // */ // const Component = () => {} node = binding.path.parentPath!.node; } } }); } else if (babel.types.isFunctionDeclaration(node.declaration)) { // export function Menu() {} if (node.declaration.id?.name === fileName) { node = node.declaration; } } else { return; } const { leadingComments } = node; const leadingCommentBlocks = leadingComments != null ? leadingComments.filter(({ type }) => type === 'CommentBlock') : null; const jsdocBlock = leadingCommentBlocks != null ? leadingCommentBlocks[0] : null; if (leadingCommentBlocks != null && leadingCommentBlocks.length > 1) { throw new Error( `Should only have a single leading jsdoc block but got ${ leadingCommentBlocks.length }:\n${leadingCommentBlocks .map(({ type, value }, index) => `#${index} (${type}): ${value}`) .join('\n')}`, ); } if (jsdocBlock?.start != null && jsdocBlock?.end != null) { start = jsdocBlock.start; end = jsdocBlock.end; } else if (node.start != null) { start = node.start - 1; end = start; } }, }); if (end === null || start === 0) { throw new TypeError( `${api.filename}: Don't know where to insert the jsdoc block. Probably no default export or named export matching the file name was found.`, ); } let inheritanceAPILink = null; if (api.inheritance !== null) { inheritanceAPILink = `[${api.inheritance.name} API](${ api.inheritance.apiPathname.startsWith('http') ? api.inheritance.apiPathname : `${HOST}${api.inheritance.apiPathname}` })`; } const markdownLines = (await computeApiDescription(api, { host: HOST })).split('\n'); // Ensure a newline between manual and generated description. if (markdownLines[markdownLines.length - 1] !== '') { markdownLines.push(''); } markdownLines.push( 'Demos:', '', ...api.demos.map((demo) => { return `- [${demo.demoPageTitle}](${ demo.demoPathname.startsWith('http') ? demo.demoPathname : `${HOST}${demo.demoPathname}` })`; }), '', ); markdownLines.push( 'API:', '', `- [${api.name} API](${ api.apiPathname.startsWith('http') ? api.apiPathname : `${HOST}${api.apiPathname}` })`, ); if (api.inheritance !== null) { markdownLines.push(`- inherits ${inheritanceAPILink}`); } const jsdoc = `/**\n${markdownLines .map((line) => (line.length > 0 ? ` * ${line}` : ` *`)) .join('\n')}\n */`; const typesSourceNew = typesSource.slice(0, start) + jsdoc + typesSource.slice(end); writeFileSync(typesFilename, typesSourceNew, { encoding: 'utf8' }); } /** * Substitute CSS class description conditions with placeholder */ function extractClassConditions(descriptions: any) { const classConditions: { [key: string]: { description: string; conditions?: string; nodeName?: string }; } = {}; const stylesRegex = /((Styles|State class|Class name) applied to )(.*?)(( if | unless | when |, ){1}(.*))?\./; Object.entries(descriptions).forEach(([className, description]: any) => { if (className) { const conditions = description.match(stylesRegex); if (conditions && conditions[6]) { classConditions[className] = { description: renderMarkdown( description.replace(stylesRegex, '$1{{nodeName}}$5{{conditions}}.'), ), nodeName: renderMarkdown(conditions[3]), conditions: renderMarkdown(conditions[6].replace(/`(.*?)`/g, '<code>$1</code>')), }; } else if (conditions && conditions[3] && conditions[3] !== 'the root element') { classConditions[className] = { description: renderMarkdown(description.replace(stylesRegex, '$1{{nodeName}}$5.')), nodeName: renderMarkdown(conditions[3]), }; } else { classConditions[className] = { description: renderMarkdown(description) }; } } }); return classConditions; } /** * @param filepath - absolute path * @example toGitHubPath('/home/user/material-ui/packages/Accordion') === '/packages/Accordion' * @example toGitHubPath('C:\\Development\material-ui\packages\Accordion') === '/packages/Accordion' */ export function toGitHubPath(filepath: string): string { return `/${path.relative(process.cwd(), filepath).replace(/\\/g, '/')}`; } const generateApiTranslations = ( outputDirectory: string, reactApi: ReactApi, languages: string[], ) => { const componentName = reactApi.name; const apiDocsTranslationPath = path.resolve(outputDirectory, kebabCase(componentName)); function resolveApiDocsTranslationsComponentLanguagePath( language: (typeof languages)[0], ): string { const languageSuffix = language === 'en' ? '' : `-${language}`; return path.join(apiDocsTranslationPath, `${kebabCase(componentName)}${languageSuffix}.json`); } mkdirSync(apiDocsTranslationPath, { mode: 0o777, recursive: true, }); writePrettifiedFile( resolveApiDocsTranslationsComponentLanguagePath('en'), JSON.stringify(reactApi.translations), ); languages.forEach((language) => { if (language !== 'en') { try { writePrettifiedFile( resolveApiDocsTranslationsComponentLanguagePath(language), JSON.stringify(reactApi.translations), undefined, { flag: 'wx' }, ); } catch (error) { // File exists } } }); }; const generateApiPage = ( apiPagesDirectory: string, translationPagesDirectory: string, reactApi: ReactApi, onlyJsonFile: boolean = false, ) => { const normalizedApiPathname = reactApi.apiPathname.replace(/\\/g, '/'); /** * Gather the metadata needed for the component's API page. */ const pageContent = { // Sorted by required DESC, name ASC props: _.fromPairs( Object.entries(reactApi.propsTable).sort(([aName, aData], [bName, bData]) => { if ((aData.required && bData.required) || (!aData.required && !bData.required)) { return aName.localeCompare(bName); } if (aData.required) { return -1; } return 1; }), ), name: reactApi.name, imports: reactApi.imports, styles: { classes: reactApi.styles.classes, globalClasses: _.fromPairs( Object.entries(reactApi.styles.globalClasses).filter(([className, globalClassName]) => { // Only keep "non-standard" global classnames return globalClassName !== `Mui${reactApi.name}-${className}`; }), ), name: reactApi.styles.name, }, ...(reactApi.slots?.length > 0 && { slots: reactApi.slots }), ...((reactApi.classes?.classes.length > 0 || (reactApi.classes?.globalClasses && Object.keys(reactApi.classes.globalClasses).length > 0)) && { classes: { classes: reactApi.classes.classes, globalClasses: reactApi.classes.globalClasses, }, }), spread: reactApi.spread, themeDefaultProps: reactApi.themeDefaultProps, muiName: normalizedApiPathname.startsWith('/joy-ui') ? reactApi.muiName.replace('Mui', 'Joy') : reactApi.muiName, forwardsRefTo: reactApi.forwardsRefTo, filename: toGitHubPath(reactApi.filename), inheritance: reactApi.inheritance ? { component: reactApi.inheritance.name, pathname: reactApi.inheritance.apiPathname, } : null, demos: `<ul>${reactApi.demos .map((item) => `<li><a href="${item.demoPathname}">${item.demoPageTitle}</a></li>`) .join('\n')}</ul>`, cssComponent: cssComponents.indexOf(reactApi.name) >= 0, }; writePrettifiedFile( path.resolve(apiPagesDirectory, `${kebabCase(reactApi.name)}.json`), JSON.stringify(pageContent), ); if (!onlyJsonFile) { writePrettifiedFile( path.resolve(apiPagesDirectory, `${kebabCase(reactApi.name)}.js`), `import * as React from 'react'; import ApiPage from 'docs/src/modules/components/ApiPage'; import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations'; import jsonPageContent from './${kebabCase(reactApi.name)}.json'; export default function Page(props) { const { descriptions, pageContent } = props; return <ApiPage descriptions={descriptions} pageContent={pageContent} />; } Page.getInitialProps = () => { const req = require.context( '${translationPagesDirectory}/${kebabCase(reactApi.name)}', false, /${kebabCase(reactApi.name)}.*.json$/, ); const descriptions = mapApiPageTranslations(req); return { descriptions, pageContent: jsonPageContent, }; }; `.replace(/\r?\n/g, reactApi.EOL), ); } }; const attachTranslations = (reactApi: ReactApi) => { const translations: ReactApi['translations'] = { componentDescription: reactApi.description, propDescriptions: {}, classDescriptions: {}, }; Object.entries(reactApi.props!).forEach(([propName, propDescriptor]) => { let prop: DescribeablePropDescriptor | null; try { prop = createDescribeableProp(propDescriptor, propName); } catch (error) { prop = null; } if (prop) { const { deprecated, jsDocText, signatureArgs, signatureReturn, requiresRef } = generatePropDescription(prop, propName); // description = renderMarkdownInline(`${description}`); const typeDescriptions: { [t: string]: string } = {}; (signatureArgs || []).concat(signatureReturn || []).forEach(({ name, description }) => { typeDescriptions[name] = renderMarkdown(description); }); translations.propDescriptions[propName] = { description: renderMarkdown(jsDocText), requiresRef: requiresRef || undefined, deprecated: renderMarkdown(deprecated) || undefined, typeDescriptions: Object.keys(typeDescriptions).length > 0 ? typeDescriptions : undefined, }; } }); /** * Slot descriptions. */ if (reactApi.slots?.length > 0) { translations.slotDescriptions = {}; reactApi.slots.forEach((slot: Slot) => { const { name, description } = slot; translations.slotDescriptions![name] = description; }); } /** * CSS class descriptions. */ translations.classDescriptions = extractClassConditions( reactApi.styles.classes.length || Object.keys(reactApi.styles.globalClasses).length ? reactApi.styles.descriptions : reactApi.classes.descriptions, ); reactApi.translations = translations; }; const attachPropsTable = (reactApi: ReactApi) => { const propErrors: Array<[propName: string, error: Error]> = []; type Pair = [string, ReactApi['propsTable'][string]]; const componentProps: ReactApi['propsTable'] = _.fromPairs( Object.entries(reactApi.props!).map(([propName, propDescriptor]): Pair => { let prop: DescribeablePropDescriptor | null; try { prop = createDescribeableProp(propDescriptor, propName); } catch (error) { propErrors.push([`[${reactApi.name}] \`${propName}\``, error as Error]); prop = null; } if (prop === null) { // have to delete `componentProps.undefined` later return [] as any; } const defaultValue = propDescriptor.jsdocDefaultValue?.value; const { signature: signatureType, signatureArgs, signatureReturn, } = generatePropDescription(prop, propName); const propTypeDescription = generatePropTypeDescription(propDescriptor.type); const chainedPropType = getChained(prop.type); const requiredProp = prop.required || /\.isRequired/.test(prop.type.raw) || (chainedPropType !== false && chainedPropType.required); const deprecation = (propDescriptor.description || '').match(/@deprecated(\s+(?<info>.*))?/); const additionalPropsInfo: AdditionalPropsInfo = {}; const normalizedApiPathname = reactApi.apiPathname.replace(/\\/g, '/'); if (propName === 'classes') { additionalPropsInfo.cssApi = true; } else if (propName === 'sx') { additionalPropsInfo.sx = true; } else if (propName === 'slots' && !normalizedApiPathname.startsWith('/material-ui')) { additionalPropsInfo.slotsApi = true; } else if (normalizedApiPathname.startsWith('/joy-ui')) { switch (propName) { case 'size': additionalPropsInfo['joy-size'] = true; break; case 'color': additionalPropsInfo['joy-color'] = true; break; case 'variant': additionalPropsInfo['joy-variant'] = true; break; default: } } let signature: ReactApi['propsTable'][string]['signature']; if (signatureType !== undefined) { signature = { type: signatureType, describedArgs: signatureArgs?.map((arg) => arg.name), returned: signatureReturn?.name, }; } return [ propName, { type: { name: propDescriptor.type.name, description: propTypeDescription !== propDescriptor.type.name ? propTypeDescription : undefined, }, default: defaultValue, // undefined values are not serialized => saving some bytes required: requiredProp || undefined, deprecated: !!deprecation || undefined, deprecationInfo: renderMarkdown(deprecation?.groups?.info || '').trim() || undefined, signature, additionalInfo: Object.keys(additionalPropsInfo).length === 0 ? undefined : additionalPropsInfo, }, ]; }), ); if (propErrors.length > 0) { throw new Error( `There were errors creating prop descriptions:\n${propErrors .map(([propName, error]) => { return ` - ${propName}: ${error}`; }) .join('\n')}`, ); } // created by returning the `[]` entry delete componentProps.undefined; reactApi.propsTable = componentProps; }; /** * Helper to get the import options * @param name The name of the component * @param filename The filename where its defined (to infer the package) * @returns an array of import command */ const getComponentImports = (name: string, filename: string) => { const githubPath = toGitHubPath(filename); const rootImportPath = githubPath.replace( /\/packages\/mui(?:-(.+?))?\/src\/.*/, (match, pkg) => `@mui/${pkg}`, ); const subdirectoryImportPath = githubPath.replace( /\/packages\/mui(?:-(.+?))?\/src\/([^\\/]+)\/.*/, (match, pkg, directory) => `@mui/${pkg}/${directory}`, ); let namedImportName = name; const defaultImportName = name; if (/Unstable_/.test(githubPath)) { namedImportName = `Unstable_${name} as ${name}`; } const useNamedImports = rootImportPath === '@mui/base'; const subpathImport = useNamedImports ? `import { ${namedImportName} } from '${subdirectoryImportPath}';` : `import ${defaultImportName} from '${subdirectoryImportPath}';`; const rootImport = `import { ${namedImportName} } from '${rootImportPath}';`; return [subpathImport, rootImport]; }; /** * - Build react component (specified filename) api by lookup at its definition (.d.ts or ts) * and then generate the API page + json data * - Generate the translations * - Add the comment in the component filename with its demo & API urls (including the inherited component). * this process is done by sourcing markdown files and filter matched `components` in the frontmatter */ export default async function generateComponentApi( componentInfo: ComponentInfo, project: TypeScriptProject, projectSettings: ProjectSettings, ) { const { filename, name, muiName, apiPathname, apiPagesDirectory, getInheritance, getDemos, readFile, skipApiGeneration, isSystemComponent, } = componentInfo; const { shouldSkip, spread, EOL, src } = readFile(); if (shouldSkip) { return null; } let reactApi: ReactApi; if (isSystemComponent) { try { reactApi = docgenParse( src, (ast) => { let node; astTypes.visit(ast, { visitVariableDeclaration: (variablePath) => { const definitions: any[] = []; if (variablePath.node.declarations) { variablePath .get('declarations') .each((declarator: any) => definitions.push(declarator.get('init'))); } definitions.forEach((definition) => { // definition.value.expression is defined when the source is in TypeScript. const expression = definition.value?.expression ? definition.get('expression') : definition; if (expression.value?.callee) { const definitionName = expression.value.callee.name; if (definitionName === `create${name}`) { node = expression; } } }); return false; }, }); return node; }, defaultHandlers, { filename }, ); } catch (error) { // fallback to default logic if there is no `create*` definition. if ((error as Error).message === 'No suitable component definition found.') { reactApi = docgenParse(src, null, defaultHandlers.concat(muiDefaultPropsHandler), { filename, }); } else { throw error; } } } else { reactApi = docgenParse(src, null, defaultHandlers.concat(muiDefaultPropsHandler), { filename, }); } // Ignore what we might have generated in `annotateComponentDefinition` const annotatedDescriptionMatch = reactApi.description.match(/(Demos|API):\r?\n\r?\n/); if (annotatedDescriptionMatch !== null) { reactApi.description = reactApi.description.slice(0, annotatedDescriptionMatch.index).trim(); } reactApi.filename = filename; reactApi.name = name; reactApi.imports = getComponentImports(name, filename); reactApi.muiName = muiName; reactApi.apiPathname = apiPathname; reactApi.EOL = EOL; reactApi.demos = getDemos(); if (reactApi.demos.length === 0) { throw new Error( 'Unable to find demos. \n' + `Be sure to include \`components: ${reactApi.name}\` in the markdown pages where the \`${reactApi.name}\` component is relevant. ` + 'Every public component should have a demo. ', ); } const testInfo = await parseTest(filename); // no Object.assign to visually check for collisions reactApi.forwardsRefTo = testInfo.forwardsRefTo; reactApi.spread = testInfo.spread ?? spread; reactApi.themeDefaultProps = testInfo.themeDefaultProps; reactApi.inheritance = getInheritance(testInfo.inheritComponent); // Both `slots` and `classes` are empty if // interface `${componentName}Slots` wasn't found. // Currently, Base UI and Joy UI components support this interface const { slots, classes } = parseSlotsAndClasses({ project, componentName: reactApi.name, muiName: reactApi.muiName, }); reactApi.slots = slots; reactApi.classes = classes; reactApi.styles = parseStyles({ project, componentName: reactApi.name }); if (reactApi.styles.classes.length > 0 && !filename.includes('mui-base')) { reactApi.styles.name = reactApi.muiName; } reactApi.styles.classes.forEach((key) => { const globalClass = generateUtilityClass(reactApi.styles.name || reactApi.muiName, key); reactApi.styles.globalClasses[key] = globalClass; }); // if `reactApi.classes` and `reactApi.styles` both exist, // API documentation includes both "CSS" Section and "State classes" Section; // we either want (1) "Slots" section and "State classes" section, or (2) "CSS" section if ( (reactApi.styles.classes?.length || Object.keys(reactApi.styles.globalClasses || {})?.length) && (reactApi.classes.classes?.length || Object.keys(reactApi.classes.globalClasses || {})?.length) ) { reactApi.styles.classes = []; reactApi.styles.globalClasses = {}; } attachPropsTable(reactApi); attachTranslations(reactApi); // eslint-disable-next-line no-console console.log('Built API docs for', reactApi.apiPathname); const normalizedApiPathname = reactApi.apiPathname.replace(/\\/g, '/'); const normalizedFilename = reactApi.filename.replace(/\\/g, '/'); if (!skipApiGeneration) { // Generate pages, json and translations let translationPagesDirectory = 'docs/translations/api-docs'; if (normalizedApiPathname.startsWith('/joy-ui') && normalizedFilename.includes('mui-joy/src')) { translationPagesDirectory = 'docs/translations/api-docs-joy'; } else if ( normalizedApiPathname.startsWith('/base') && normalizedFilename.includes('mui-base/src') ) { translationPagesDirectory = 'docs/translations/api-docs-base'; } generateApiTranslations( path.join(process.cwd(), translationPagesDirectory), reactApi, projectSettings.translationLanguages, ); // Once we have the tabs API in all projects, we can make this default const generateOnlyJsonFile = normalizedApiPathname.startsWith('/base'); generateApiPage(apiPagesDirectory, translationPagesDirectory, reactApi, generateOnlyJsonFile); // Add comment about demo & api links (including inherited component) to the component file await annotateComponentDefinition(reactApi); } return reactApi; }
6,031
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/ApiBuilders/HookApiBuilder.ts
import { mkdirSync, readFileSync, writeFileSync } from 'fs'; import path from 'path'; import * as ts from 'typescript'; import * as astTypes from 'ast-types'; import * as _ from 'lodash'; import * as babel from '@babel/core'; import traverse from '@babel/traverse'; import { defaultHandlers, parse as docgenParse, ReactDocgenApi } from 'react-docgen'; import kebabCase from 'lodash/kebabCase'; import upperFirst from 'lodash/upperFirst'; import { renderMarkdown } from '@mui/markdown'; import { ProjectSettings } from '../ProjectSettings'; import { toGitHubPath, computeApiDescription } from './ComponentApiBuilder'; import { getSymbolDescription, getSymbolJSDocTags, HookInfo, stringifySymbol, writePrettifiedFile, } from '../buildApiUtils'; import { TypeScriptProject } from '../utils/createTypeScriptProject'; interface ParsedProperty { name: string; description: string; tags: { [tagName: string]: ts.JSDocTagInfo }; required: boolean; typeStr: string; } const parseProperty = (propertySymbol: ts.Symbol, project: TypeScriptProject): ParsedProperty => ({ name: propertySymbol.name, description: getSymbolDescription(propertySymbol, project), tags: getSymbolJSDocTags(propertySymbol), required: !propertySymbol.declarations?.find(ts.isPropertySignature)?.questionToken, typeStr: stringifySymbol(propertySymbol, project), }); export interface ReactApi extends ReactDocgenApi { demos: ReturnType<HookInfo['getDemos']>; EOL: string; filename: string; apiPathname: string; parameters?: ParsedProperty[]; returnValue?: ParsedProperty[]; /** * hook name * @example 'useButton' */ name: string; description: string; /** * Different ways to import components */ imports: string[]; /** * result of path.readFileSync from the `filename` in utf-8 */ src: string; parametersTable: _.Dictionary<{ default: string | undefined; required: boolean | undefined; type: { name: string | undefined; description: string | undefined }; deprecated: true | undefined; deprecationInfo: string | undefined; }>; returnValueTable: _.Dictionary<{ default: string | undefined; required: boolean | undefined; type: { name: string | undefined; description: string | undefined }; deprecated: true | undefined; deprecationInfo: string | undefined; }>; translations: { hookDescription: string; parametersDescriptions: { [key: string]: { description: string; deprecated?: string; }; }; returnValueDescriptions: { [key: string]: { description: string; deprecated?: string; }; }; }; } /** * Add demos & API comment block to type definitions, e.g.: * /** * * Demos: * * * * - [Button](https://mui.com/base-ui/react-button/) * * * * API: * * * * - [useButton API](https://mui.com/base-ui/api/use-button/) */ async function annotateHookDefinition(api: ReactApi) { const HOST = 'https://mui.com'; const typesFilename = api.filename.replace(/\.js$/, '.d.ts'); const fileName = path.parse(api.filename).name; const typesSource = readFileSync(typesFilename, { encoding: 'utf8' }); const typesAST = await babel.parseAsync(typesSource, { configFile: false, filename: typesFilename, presets: [require.resolve('@babel/preset-typescript')], }); if (typesAST === null) { throw new Error('No AST returned from babel.'); } let start = 0; let end = null; traverse(typesAST, { ExportDefaultDeclaration(babelPath) { if (api.filename.includes('mui-base')) { // Base UI does not use default exports. return; } /** * export default function Menu() {} */ let node: babel.Node = babelPath.node; if (node.declaration.type === 'Identifier') { // declare const Menu: {}; // export default Menu; if (babel.types.isIdentifier(babelPath.node.declaration)) { const bindingId = babelPath.node.declaration.name; const binding = babelPath.scope.bindings[bindingId]; // The JSDoc MUST be located at the declaration if (babel.types.isFunctionDeclaration(binding.path.node)) { // For function declarations the binding is equal to the declaration // /** // */ // function Component() {} node = binding.path.node; } else { // For variable declarations the binding points to the declarator. // /** // */ // const Component = () => {} node = binding.path.parentPath!.node; } } } const { leadingComments } = node; const leadingCommentBlocks = leadingComments != null ? leadingComments.filter(({ type }) => type === 'CommentBlock') : null; const jsdocBlock = leadingCommentBlocks != null ? leadingCommentBlocks[0] : null; if (leadingCommentBlocks != null && leadingCommentBlocks.length > 1) { throw new Error( `Should only have a single leading jsdoc block but got ${ leadingCommentBlocks.length }:\n${leadingCommentBlocks .map(({ type, value }, index) => `#${index} (${type}): ${value}`) .join('\n')}`, ); } if (jsdocBlock?.start != null && jsdocBlock?.end != null) { start = jsdocBlock.start; end = jsdocBlock.end; } else if (node.start != null) { start = node.start - 1; end = start; } }, ExportNamedDeclaration(babelPath) { if (!api.filename.includes('mui-base')) { return; } let node: babel.Node = babelPath.node; if (babel.types.isTSDeclareFunction(node.declaration)) { // export function useHook() in .d.ts if (node.declaration.id?.name !== fileName) { return; } } else if (node.declaration == null) { // export { useHook }; node.specifiers.forEach((specifier) => { if (specifier.type === 'ExportSpecifier' && specifier.local.name === fileName) { const binding = babelPath.scope.bindings[specifier.local.name]; if (babel.types.isFunctionDeclaration(binding.path.node)) { // For function declarations the binding is equal to the declaration // /** // */ // function useHook() {} node = binding.path.node; } else { // For variable declarations the binding points to the declarator. // /** // */ // const useHook = () => {} node = binding.path.parentPath!.node; } } }); } else if (babel.types.isFunctionDeclaration(node.declaration)) { // export function useHook() in .ts if (node.declaration.id?.name !== fileName) { return; } } else { return; } const { leadingComments } = node; const leadingCommentBlocks = leadingComments != null ? leadingComments.filter(({ type }) => type === 'CommentBlock') : null; const jsdocBlock = leadingCommentBlocks != null ? leadingCommentBlocks[0] : null; if (leadingCommentBlocks != null && leadingCommentBlocks.length > 1) { throw new Error( `Should only have a single leading jsdoc block but got ${ leadingCommentBlocks.length }:\n${leadingCommentBlocks .map(({ type, value }, index) => `#${index} (${type}): ${value}`) .join('\n')}`, ); } if (jsdocBlock?.start != null && jsdocBlock?.end != null) { start = jsdocBlock.start; end = jsdocBlock.end; } else if (node.start != null) { start = node.start - 1; end = start; } }, }); if (end === null || start === 0) { throw new TypeError( `${api.filename}: Don't know where to insert the jsdoc block. Probably no default export found`, ); } const markdownLines = (await computeApiDescription(api, { host: HOST })).split('\n'); // Ensure a newline between manual and generated description. if (markdownLines[markdownLines.length - 1] !== '') { markdownLines.push(''); } if (api.demos && api.demos.length > 0) { markdownLines.push( 'Demos:', '', ...api.demos.map((item) => { return `- [${item.demoPageTitle}](${ item.demoPathname.startsWith('http') ? item.demoPathname : `${HOST}${item.demoPathname}` })`; }), '', ); } markdownLines.push( 'API:', '', `- [${api.name} API](${ api.apiPathname.startsWith('http') ? api.apiPathname : `${HOST}${api.apiPathname}` })`, ); const jsdoc = `/**\n${markdownLines .map((line) => (line.length > 0 ? ` * ${line}` : ` *`)) .join('\n')}\n */`; const typesSourceNew = typesSource.slice(0, start) + jsdoc + typesSource.slice(end); writeFileSync(typesFilename, typesSourceNew, { encoding: 'utf8' }); } const attachTable = ( reactApi: ReactApi, params: ParsedProperty[], tableName: 'parametersTable' | 'returnValueTable', ) => { const propErrors: Array<[propName: string, error: Error]> = []; const parameters: ReactApi[typeof tableName] = params .map((p) => { const { name: propName, ...propDescriptor } = p; let prop: Omit<ParsedProperty, 'name'> | null; try { prop = propDescriptor; } catch (error) { propErrors.push([propName, error as Error]); prop = null; } if (prop === null) { // have to delete `componentProps.undefined` later return [] as any; } const defaultTag = propDescriptor.tags?.default; const defaultValue: string | undefined = defaultTag?.text?.[0]?.text; const requiredProp = prop.required; const deprecation = (propDescriptor.description || '').match(/@deprecated(\s+(?<info>.*))?/); const typeDescription = (propDescriptor.typeStr ?? '') .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); return { [propName]: { type: { // The docgen generates this structure for the components. For consistency in the structure // we are adding the same value in both the name and the description name: typeDescription, description: typeDescription, }, default: defaultValue, // undefined values are not serialized => saving some bytes required: requiredProp || undefined, deprecated: !!deprecation || undefined, deprecationInfo: renderMarkdown(deprecation?.groups?.info || '').trim() || undefined, }, }; }) .reduce((acc, curr) => ({ ...acc, ...curr }), {}) as unknown as ReactApi['parametersTable']; if (propErrors.length > 0) { throw new Error( `There were errors creating prop descriptions:\n${propErrors .map(([propName, error]) => { return ` - ${propName}: ${error}`; }) .join('\n')}`, ); } // created by returning the `[]` entry delete parameters.undefined; reactApi[tableName] = parameters; }; const generateTranslationDescription = (description: string) => { return renderMarkdown(description.replace(/\n@default.*$/, '')); }; const attachTranslations = (reactApi: ReactApi) => { const translations: ReactApi['translations'] = { hookDescription: reactApi.description, parametersDescriptions: {}, returnValueDescriptions: {}, }; (reactApi.parameters ?? []).forEach(({ name: propName, description }) => { if (description) { translations.parametersDescriptions[propName] = { description: generateTranslationDescription(description), }; const deprecation = (description || '').match(/@deprecated(\s+(?<info>.*))?/); if (deprecation !== null) { translations.parametersDescriptions[propName].deprecated = renderMarkdown(deprecation?.groups?.info || '').trim() || undefined; } } }); (reactApi.returnValue ?? []).forEach(({ name: propName, description }) => { if (description) { translations.returnValueDescriptions[propName] = { description: generateTranslationDescription(description), }; const deprecation = (description || '').match(/@deprecated(\s+(?<info>.*))?/); if (deprecation !== null) { translations.parametersDescriptions[propName].deprecated = renderMarkdown(deprecation?.groups?.info || '').trim() || undefined; } } }); reactApi.translations = translations; }; const generateApiJson = (outputDirectory: string, reactApi: ReactApi) => { /** * Gather the metadata needed for the component's API page. */ const pageContent = { // Sorted by required DESC, name ASC parameters: _.fromPairs( Object.entries(reactApi.parametersTable).sort(([aName, aData], [bName, bData]) => { if ((aData.required && bData.required) || (!aData.required && !bData.required)) { return aName.localeCompare(bName); } if (aData.required) { return -1; } return 1; }), ), returnValue: _.fromPairs( Object.entries(reactApi.returnValueTable).sort(([aName, aData], [bName, bData]) => { if ((aData.required && bData.required) || (!aData.required && !bData.required)) { return aName.localeCompare(bName); } if (aData.required) { return -1; } return 1; }), ), name: reactApi.name, filename: toGitHubPath(reactApi.filename), imports: reactApi.imports, demos: `<ul>${reactApi.demos .map((item) => `<li><a href="${item.demoPathname}">${item.demoPageTitle}</a></li>`) .join('\n')}</ul>`, }; writePrettifiedFile( path.resolve(outputDirectory, `${kebabCase(reactApi.name)}.json`), JSON.stringify(pageContent), ); }; const generateApiTranslations = ( outputDirectory: string, reactApi: ReactApi, languages: string[], ) => { const hookName = reactApi.name; const apiDocsTranslationPath = path.resolve(outputDirectory, kebabCase(hookName)); function resolveApiDocsTranslationsComponentLanguagePath( language: (typeof languages)[0], ): string { const languageSuffix = language === 'en' ? '' : `-${language}`; return path.join(apiDocsTranslationPath, `${kebabCase(hookName)}${languageSuffix}.json`); } mkdirSync(apiDocsTranslationPath, { mode: 0o777, recursive: true, }); writePrettifiedFile( resolveApiDocsTranslationsComponentLanguagePath('en'), JSON.stringify(reactApi.translations), ); languages.forEach((language) => { if (language !== 'en') { try { writePrettifiedFile( resolveApiDocsTranslationsComponentLanguagePath(language), JSON.stringify(reactApi.translations), undefined, { flag: 'wx' }, ); } catch (error) { // File exists } } }); }; const extractInfoFromType = (typeName: string, project: TypeScriptProject): ParsedProperty[] => { // Generate the params let result: ParsedProperty[] = []; try { const exportedSymbol = project.exports[typeName]; const type = project.checker.getDeclaredTypeOfSymbol(exportedSymbol); // @ts-ignore const typeDeclaration = type?.symbol?.declarations?.[0]; if (!typeDeclaration) { return []; } const properties: Record<string, ParsedProperty> = {}; // @ts-ignore const propertiesOnProject = type.getProperties(); // @ts-ignore propertiesOnProject.forEach((propertySymbol) => { properties[propertySymbol.name] = parseProperty(propertySymbol, project); }); result = Object.values(properties) .filter((property) => !property.tags.ignore) .sort((a, b) => a.name.localeCompare(b.name)); } catch (e) { console.error(`No declaration for ${typeName}`); } return result; }; /** * Helper to get the import options * @param name The name of the hook * @param filename The filename where its defined (to infer the package) * @returns an array of import command */ const getHookImports = (name: string, filename: string) => { const githubPath = toGitHubPath(filename); const rootImportPath = githubPath.replace( /\/packages\/mui(?:-(.+?))?\/src\/.*/, (match, pkg) => `@mui/${pkg}`, ); const subdirectoryImportPath = githubPath.replace( /\/packages\/mui(?:-(.+?))?\/src\/([^\\/]+)\/.*/, (match, pkg, directory) => `@mui/${pkg}/${directory}`, ); let namedImportName = name; const defaultImportName = name; if (/unstable_/.test(githubPath)) { namedImportName = `unstable_${name} as ${name}`; } const useNamedImports = rootImportPath === '@mui/base'; const subpathImport = useNamedImports ? `import { ${namedImportName} } from '${subdirectoryImportPath}';` : `import ${defaultImportName} from '${subdirectoryImportPath}';`; const rootImport = `import { ${namedImportName} } from '${rootImportPath}';`; return [subpathImport, rootImport]; }; export default async function generateHookApi( hooksInfo: HookInfo, project: TypeScriptProject, projectSettings: ProjectSettings, ) { const { filename, name, apiPathname, apiPagesDirectory, getDemos, readFile, skipApiGeneration } = hooksInfo; const { shouldSkip, EOL, src } = readFile(); if (shouldSkip) { return null; } const reactApi: ReactApi = docgenParse( src, (ast) => { let node; astTypes.visit(ast, { visitFunctionDeclaration: (functionPath) => { if (functionPath.node?.id?.name === name) { node = functionPath; } return false; }, }); return node; }, defaultHandlers, { filename }, ); const parameters = extractInfoFromType(`${upperFirst(name)}Parameters`, project); const returnValue = extractInfoFromType(`${upperFirst(name)}ReturnValue`, project); // Ignore what we might have generated in `annotateHookDefinition` const annotatedDescriptionMatch = reactApi.description.match(/(Demos|API):\r?\n\r?\n/); if (annotatedDescriptionMatch !== null) { reactApi.description = reactApi.description.slice(0, annotatedDescriptionMatch.index).trim(); } reactApi.filename = filename; reactApi.name = name; reactApi.imports = getHookImports(name, filename); reactApi.apiPathname = apiPathname; reactApi.EOL = EOL; reactApi.demos = getDemos(); if (reactApi.demos.length === 0) { // TODO: Enable this error once all public hooks are documented // throw new Error( // 'Unable to find demos. \n' + // `Be sure to include \`hooks: ${reactApi.name}\` in the markdown pages where the \`${reactApi.name}\` hook is relevant. ` + // 'Every public hook should have a demo. ', // ); } attachTable(reactApi, parameters, 'parametersTable'); reactApi.parameters = parameters; attachTable(reactApi, returnValue, 'returnValueTable'); reactApi.returnValue = returnValue; attachTranslations(reactApi); // eslint-disable-next-line no-console console.log('Built API docs for', reactApi.name); if (!skipApiGeneration) { // Generate pages, json and translations generateApiTranslations( path.join(process.cwd(), 'docs/translations/api-docs'), reactApi, projectSettings.translationLanguages, ); generateApiJson(apiPagesDirectory, reactApi); // Add comment about demo & api links to the component hook file await annotateHookDefinition(reactApi); } return reactApi; }
6,032
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/createDescribeableProp.ts
import * as doctrine from 'doctrine'; import { PropDescriptor, PropTypeDescriptor } from 'react-docgen'; export interface DescribeablePropDescriptor { annotation: doctrine.Annotation; defaultValue: string | null; required: boolean; type: PropTypeDescriptor; } /** * Returns `null` if the prop should be ignored. * Throws if it is invalid. * @param prop * @param propName */ export default function createDescribeableProp( prop: PropDescriptor, propName: string, ): DescribeablePropDescriptor | null { const { defaultValue, jsdocDefaultValue, description, required, type } = prop; const renderedDefaultValue = defaultValue?.value.replace(/\r?\n/g, ''); const renderDefaultValue = Boolean( renderedDefaultValue && // Ignore "large" default values that would break the table layout. renderedDefaultValue.length <= 150, ); if (description === undefined) { throw new Error(`The "${propName}" prop is missing a description.`); } const annotation = doctrine.parse(description, { sloppy: true, }); if ( annotation.description.trim() === '' || annotation.tags.some((tag) => tag.title === 'ignore') ) { return null; } if (jsdocDefaultValue !== undefined && defaultValue === undefined) { // Assume that this prop: // 1. Is typed by another component // 2. Is forwarded to that component // Then validation is handled by the other component. // Though this does break down if the prop is used in other capacity in the implementation. // So let's hope we don't make this mistake too often. } else if (jsdocDefaultValue === undefined && defaultValue !== undefined && renderDefaultValue) { const shouldHaveDefaultAnnotation = // Discriminator for polymorphism which is not documented at the component level. // The documentation of `component` does not know in which component it is used. propName !== 'component'; if (shouldHaveDefaultAnnotation) { throw new Error( `JSDoc @default annotation not found. Add \`@default ${defaultValue.value}\` to the JSDoc of this prop.`, ); } } else if (jsdocDefaultValue !== undefined) { // `defaultValue` can't be undefined or we would've thrown earlier. if (jsdocDefaultValue.value !== defaultValue!.value) { throw new Error( `Expected JSDoc @default annotation for prop '${propName}' of "${jsdocDefaultValue.value}" to equal runtime default value of "${defaultValue?.value}"`, ); } } return { annotation, defaultValue: renderDefaultValue ? renderedDefaultValue! : null, required: Boolean(required), type, }; }
6,033
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/createTypeScriptProject.ts
import path from 'path'; import fs from 'fs'; import * as ts from 'typescript'; export interface TypeScriptProject { name: string; rootPath: string; exports: Record<string, ts.Symbol>; program: ts.Program; checker: ts.TypeChecker; } export interface CreateTypeScriptProjectOptions { name: string; rootPath: string; /** * Config to use to build this package. * The path must be relative to the root path. * @default 'tsconfig.build.json` */ tsConfigPath?: string; /** * File used as root of the package. * This property is used to gather the exports of the project. * The path must be relative to the root path. */ entryPointPath?: string; /** * Files to include in the project. * By default, it will use the files defined in the tsconfig. */ files?: string[]; } export const createTypeScriptProject = ( options: CreateTypeScriptProjectOptions, ): TypeScriptProject => { const { name, rootPath, tsConfigPath: inputTsConfigPath = 'tsconfig.build.json', entryPointPath: inputEntryPointPath, files, } = options; const tsConfigPath = path.join(rootPath, inputTsConfigPath); const tsConfigFile = ts.readConfigFile(tsConfigPath, (filePath) => fs.readFileSync(filePath).toString(), ); if (tsConfigFile.error) { throw tsConfigFile.error; } // The build config does not parse the `.d.ts` files, but we sometimes need them to get the exports. if (tsConfigFile.config.exclude) { tsConfigFile.config.exclude = tsConfigFile.config.exclude.filter( (pattern: string) => pattern !== 'src/**/*.d.ts', ); } const tsConfigFileContent = ts.parseJsonConfigFileContent( tsConfigFile.config, ts.sys, path.dirname(tsConfigPath), ); if (tsConfigFileContent.errors.length > 0) { throw tsConfigFileContent.errors[0]; } const program = ts.createProgram({ rootNames: files ?? tsConfigFileContent.fileNames, options: tsConfigFileContent.options, }); const checker = program.getTypeChecker(); let exports: TypeScriptProject['exports']; if (inputEntryPointPath) { const entryPointPath = path.join(rootPath, inputEntryPointPath); const sourceFile = program.getSourceFile(entryPointPath); exports = Object.fromEntries( checker.getExportsOfModule(checker.getSymbolAtLocation(sourceFile!)!).map((symbol) => { return [symbol.name, symbol]; }), ); } else { exports = {}; } return { name, rootPath, exports, program, checker, }; }; export type TypeScriptProjectBuilder = ( projectName: string, options?: { files?: string[] }, ) => TypeScriptProject; export const createTypeScriptProjectBuilder = ( projectsConfig: Record<string, Omit<CreateTypeScriptProjectOptions, 'name'>>, ): TypeScriptProjectBuilder => { const projects = new Map<string, TypeScriptProject>(); return (projectName: string, options: { files?: string[] } = {}) => { const cachedProject = projects.get(projectName); if (cachedProject != null) { return cachedProject; } // eslint-disable-next-line no-console console.log(`Building new TS project: ${projectName}`); const project = createTypeScriptProject({ name: projectName, ...projectsConfig[projectName], ...options, }); projects.set(projectName, project); return project; }; };
6,034
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/defaultPropsHandler.ts
import { namedTypes as types } from 'ast-types'; import { parse as parseDoctrine, Annotation } from 'doctrine'; import { utils as docgenUtils, NodePath, Documentation, Importer, Handler } from 'react-docgen'; const { getPropertyName, isReactForwardRefCall, printValue, resolveToValue } = docgenUtils; // based on https://github.com/reactjs/react-docgen/blob/735f39ef784312f4c0e740d4bfb812f0a7acd3d5/src/handlers/defaultPropsHandler.js#L1-L112 // adjusted for material-ui getThemedProps function getDefaultValue(propertyPath: NodePath, importer: Importer) { if (!types.AssignmentPattern.check(propertyPath.get('value').node)) { return null; } let path: NodePath = propertyPath.get('value', 'right'); let node = path.node; let defaultValue: string | undefined; if (types.Literal.check(path.node)) { // @ts-expect-error TODO upstream fix defaultValue = node.raw; } else { if (types.AssignmentPattern.check(path.node)) { path = resolveToValue(path.get('right'), importer); } else { path = resolveToValue(path, importer); } if (types.ImportDeclaration.check(path.node)) { if (types.TSAsExpression.check(node)) { node = node.expression; } if (!types.Identifier.check(node)) { const locationHint = node.loc != null ? `${node.loc.start.line}:${node.loc.start.column}` : 'unknown location'; throw new TypeError( `Unable to follow data flow. Expected an 'Identifier' resolve to an 'ImportDeclaration'. Instead attempted to resolve a '${node.type}' at ${locationHint}.`, ); } defaultValue = node.name; } else { node = path.node; defaultValue = printValue(path); } } if (defaultValue !== undefined) { return { value: defaultValue, computed: types.CallExpression.check(node) || types.MemberExpression.check(node) || types.Identifier.check(node), }; } return null; } function getJsdocDefaultValue(jsdoc: Annotation): { value: string } | undefined { const defaultTag = jsdoc.tags.find((tag) => tag.title === 'default'); if (defaultTag === undefined) { return undefined; } return { value: defaultTag.description || '' }; } function getDefaultValuesFromProps( properties: NodePath, documentation: Documentation, importer: Importer, ) { const { props: documentedProps } = documentation.toObject(); const implementedProps: Record<string, NodePath> = {}; properties .filter((propertyPath: NodePath) => types.Property.check(propertyPath.node), undefined) .forEach((propertyPath: NodePath) => { const propName = getPropertyName(propertyPath); if (propName) { implementedProps[propName] = propertyPath; } }); // Sometimes we list props in .propTypes even though they're implemented by another component // These props are spread so they won't appear in the component implementation. Object.entries(documentedProps || []).forEach(([propName, propDescriptor]) => { if (propDescriptor.description === undefined) { // private props have no propsType validator and therefore // not description. // They are either not subject to eslint react/prop-types // or are and then we catch these issues during linting. return; } const jsdocDefaultValue = getJsdocDefaultValue( parseDoctrine(propDescriptor.description, { sloppy: true, }), ); if (jsdocDefaultValue) { propDescriptor.jsdocDefaultValue = jsdocDefaultValue; } const propertyPath = implementedProps[propName]; if (propertyPath !== undefined) { const defaultValue = getDefaultValue(propertyPath, importer); if (defaultValue) { propDescriptor.defaultValue = defaultValue; } } }); } function getRenderBody(componentDefinition: NodePath, importer: Importer): NodePath { const value = resolveToValue(componentDefinition, importer); if (isReactForwardRefCall(value, importer)) { return value.get('arguments', 0, 'body', 'body'); } return value.get('body', 'body'); } /** * Handle the case where `props` is explicitly declared with/without `React.forwardRef(…)`: * * @example * const Component = React.forwardRef((props, ref) => { * const { className, ...other } = props; * }) */ function getExplicitPropsDeclaration( componentDefinition: NodePath, importer: Importer, ): NodePath | undefined { const functionNode = getRenderBody(componentDefinition, importer); let propsPath: NodePath | undefined; // visitVariableDeclarator, can't use visit body.node since it looses scope information functionNode .filter((path: NodePath) => { return types.VariableDeclaration.check(path.node); }, undefined) .forEach((path: NodePath) => { const declaratorPath = path.get('declarations', 0); // find `const {} = props` // but not `const ownerState = props` if ( declaratorPath.get('init', 'name').value === 'props' && declaratorPath.get('id', 'type').value === 'ObjectPattern' ) { propsPath = declaratorPath.get('id'); } }); if (!propsPath) { console.error(`${functionNode.parent.value.id.name}: could not find props declaration to generate jsdoc table. The component declaration should be in this format: function Component(props: ComponentProps) { const { ...spreadAsUsual } = props; ... } `); } return propsPath; } const defaultPropsHandler: Handler = (documentation, componentDefinition, importer) => { const props = getExplicitPropsDeclaration(componentDefinition, importer); if (props !== undefined) { getDefaultValuesFromProps(props.get('properties'), documentation, importer); } }; export default defaultPropsHandler;
6,035
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/escapeCell.ts
export default function escapeCell(value: string): string { // As the pipe is use for the table structure return value.replace(/</g, '&lt;').replace(/`&lt;/g, '`<').replace(/\|/g, '\\|'); }
6,036
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/findApiPages.test.ts
import { expect } from 'chai'; import { extractApiPage } from './findApiPages'; describe('extractApiPage', () => { it('return info for api page', () => { expect( extractApiPage('/material-ui/docs/pages/material-ui/api/accordion-actions.js'), ).to.deep.equal({ apiPathname: '/material-ui/api/accordion-actions', }); }); });
6,037
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/findApiPages.ts
import path from 'path'; import * as fse from 'fs-extra'; const getAllFiles = (dirPath: string, arrayOfFiles: string[] = []) => { const files = fse.readdirSync(dirPath); files.forEach((file) => { if (fse.statSync(`${dirPath}/${file}`).isDirectory()) { arrayOfFiles = getAllFiles(`${dirPath}/${file}`, arrayOfFiles); } else { arrayOfFiles.push(path.join(__dirname, dirPath, '/', file)); } }); return arrayOfFiles; }; export function extractApiPage(filePath: string) { filePath = filePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'); return { apiPathname: filePath .replace(/^.*\/pages/, '') .replace(/\.(js|tsx)/, '') .replace(/^\/index$/, '/') // Replace `index` by `/`. .replace(/\/index$/, ''), }; } export default function findApiPages(relativeFolder: string) { let pages: Array<{ pathname: string }> = []; let filePaths: string[] = []; try { filePaths = getAllFiles(path.join(process.cwd(), relativeFolder)); } catch (error) { // eslint-disable-next-line no-console console.log(error); return []; } filePaths.forEach((itemPath) => { if (itemPath.endsWith('.js')) { const data = extractApiPage(itemPath); pages.push({ pathname: data.apiPathname }); } }); // sort by pathnames without '-' so that e.g. card comes before card-action pages = pages.sort((a, b) => { const pathnameA = a.pathname.replace(/-/g, ''); const pathnameB = b.pathname.replace(/-/g, ''); if (pathnameA < pathnameB) { return -1; } if (pathnameA > pathnameB) { return 1; } return 0; }); return pages; }
6,038
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/findComponents.ts
import fs from 'fs'; import path from 'path'; import findIndexFile from './findIndexFile'; const componentRegex = /^(Unstable_)?([A-Z][a-z]+)+2?\.(js|tsx)/; /** * Returns the component source in a flat array. * @param {string} directory * @param {Array<{ filename: string, indexFilename: string }>} components */ export default function findComponents( directory: string, components: { filename: string; indexFilename: string | null }[] = [], ) { const items = fs.readdirSync(directory); items.forEach((item) => { const itemPath = path.resolve(directory, item); if (fs.statSync(itemPath).isDirectory()) { findComponents(itemPath, components); return; } if (!componentRegex.test(item)) { return; } const indexFile = findIndexFile(directory); components.push({ filename: itemPath, ...indexFile, }); }); return components; }
6,039
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/findHooks.ts
import fs from 'fs'; import path from 'path'; import findIndexFile from './findIndexFile'; const hooksRegexp = /use([A-Z][a-z]+)+\.(js|tsx|ts)/; /** * Returns the hook source in a flat array. * @param {string} directory * @param {Array<{ filename: string }>} hooks */ export default function findHooks( directory: string, hooks: { filename: string; indexFilename: string | null }[] = [], ) { const items = fs.readdirSync(directory); items.forEach((item) => { const itemPath = path.resolve(directory, item); if (fs.statSync(itemPath).isDirectory()) { findHooks(itemPath, hooks); return; } if (!hooksRegexp.test(item)) { return; } const indexFile = findIndexFile(directory); hooks.push({ filename: itemPath, ...indexFile, }); }); return hooks; }
6,040
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/findIndexFile.ts
import fs from 'fs'; import path from 'path'; const indexFileRegex = /^index.(js|ts)$/; /** * Returns index.js/ts in any directory or null * @param {string} directory */ export default function getIndexFile(directory: string) { const items = fs.readdirSync(directory); const indexFile = items.reduce((prev, curr) => { if (!indexFileRegex.test(curr)) { return prev; } return curr; }, ''); return { indexFilename: indexFile ? path.join(directory, indexFile) : null, }; }
6,041
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/findPagesMarkdown.ts
import fs from 'fs'; import path from 'path'; interface MarkdownPage { filename: string; pathname: string; } /** * Returns the markdowns of the documentation in a flat array. */ export default function findPagesMarkdown( directory: string = path.resolve(__dirname, '../../../docs/data'), pagesMarkdown: MarkdownPage[] = [], ) { const items = fs.readdirSync(directory); items.forEach((item) => { const filename = path.resolve(directory, item); if (fs.statSync(filename).isDirectory()) { findPagesMarkdown(filename, pagesMarkdown); return; } // Ignore non en-US source markdown. if (!/\.md$/.test(item) || /-(zh|pt)\.md/.test(item)) { return; } let pathname = filename .replace(new RegExp(`\\${path.sep}`, 'g'), '/') .replace(/^.*\/data/, '') .replace('.md', ''); // Remove the last pathname segment. pathname = pathname.split('/').slice(0, 4).join('/'); pagesMarkdown.push({ // Relative location of the markdown file in the file system. filename, // Relative location of the page in the URL. pathname, }); }); return pagesMarkdown; }
6,042
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/generatePropDescription.ts
import * as doctrine from 'doctrine'; import * as recast from 'recast'; import { PropTypeDescriptor } from 'react-docgen'; import { isElementTypeAcceptingRefProp, isElementAcceptingRefProp, } from './generatePropTypeDescription'; import { DescribeablePropDescriptor } from './createDescribeableProp'; import escapeCell from './escapeCell'; function resolveType(type: NonNullable<doctrine.Tag['type']>): string { if (type.type === 'AllLiteral') { return 'any'; } if (type.type === 'VoidLiteral') { return 'void'; } if (type.type === 'NullLiteral') { return 'null'; } if (type.type === 'UndefinedLiteral') { return 'undefined'; } if (type.type === 'TypeApplication') { return `${resolveType(type.expression)}<${type.applications .map((typeApplication) => { return resolveType(typeApplication); }) .join(', ')}>`; } if (type.type === 'UnionType') { return type.elements.map((t) => resolveType(t)).join(' | '); } if (type.type === 'RecordType') { if (type.fields.length === 0) { return '{}'; } return `{ ${type.fields.map((field) => resolveType(field)).join(', ')} }`; } if (type.type === 'FieldType') { return `${type.key}: ${type.value ? resolveType(type.value) : 'any'}`; } if ('name' in type) { return type.name; } throw new TypeError(`resolveType for '${type.type}' not implemented`); } function getDeprecatedInfo(type: PropTypeDescriptor) { const marker = /deprecatedPropType\((\r*\n)*\s*PropTypes\./g; const match = type.raw.match(marker); const startIndex = type.raw.search(marker); if (match) { const offset = match[0].length; return { propTypes: type.raw.substring(startIndex + offset, type.raw.indexOf(',')), explanation: recast.parse(type.raw).program.body[0].expression.arguments[1].value, }; } return false; } export default function generatePropDescription( prop: DescribeablePropDescriptor, propName: string, ): { deprecated: string; jsDocText: string; signature?: string; signatureArgs?: { name: string; description: string }[]; signatureReturn?: { name: string; description: string }; requiresRef?: boolean; } { const { annotation } = prop; const type = prop.type; let deprecated = ''; if (type.name === 'custom') { const deprecatedInfo = getDeprecatedInfo(type); if (deprecatedInfo) { deprecated = `*Deprecated*. ${deprecatedInfo.explanation}<br><br>`; } } const jsDocText = escapeCell(annotation.description); // Split up the parsed tags into 'arguments' and 'returns' parsed objects. If there's no // 'returns' parsed object (i.e., one with title being 'returns'), make one of type 'void'. const parsedArgs: readonly doctrine.Tag[] = annotation.tags.filter( (tag) => tag.title === 'param', ); let parsedReturns: { description?: string | null; type?: doctrine.Type | null } | undefined = annotation.tags.find((tag) => tag.title === 'returns'); let signature; let signatureArgs; let signatureReturn; if (type.name === 'func' && (parsedArgs.length > 0 || parsedReturns !== undefined)) { parsedReturns = parsedReturns ?? { type: { type: 'VoidLiteral' } }; // Remove new lines from tag descriptions to avoid markdown errors. annotation.tags.forEach((tag) => { if (tag.description) { tag.description = tag.description.replace(/\r*\n/g, ' '); } }); const returnType = parsedReturns.type; if (returnType == null) { throw new TypeError( `Function signature for prop '${propName}' has no return type. Try \`@returns void\`. Otherwise it might be a bug with doctrine.`, ); } const returnTypeName = resolveType(returnType); signature = `function(${parsedArgs .map((tag, index) => { if (tag.type != null && tag.type.type === 'OptionalType') { return `${tag.name}?: ${(tag.type.expression as any).name}`; } if (tag.type === undefined) { throw new TypeError( `In function signature for prop '${propName}' Argument #${index} has no type.`, ); } return `${tag.name}: ${resolveType(tag.type!)}`; }) .join(', ')}) => ${returnTypeName}`; signatureArgs = parsedArgs .filter((tag) => tag.description && tag.name) .map((tag) => ({ name: tag.name!, description: tag.description! })); if (parsedReturns.description) { signatureReturn = { name: returnTypeName, description: parsedReturns.description }; } } const requiresRef = isElementAcceptingRefProp(type) || isElementTypeAcceptingRefProp(type) || undefined; return { deprecated, jsDocText, signature, signatureArgs, signatureReturn, requiresRef, }; }
6,043
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/generatePropTypeDescription.ts
import * as recast from 'recast'; import { parse as docgenParse, PropTypeDescriptor } from 'react-docgen'; import escapeCell from './escapeCell'; function getDeprecatedInfo(type: PropTypeDescriptor) { const marker = /deprecatedPropType\((\r*\n)*\s*PropTypes\./g; const match = type.raw.match(marker); const startIndex = type.raw.search(marker); if (match) { const offset = match[0].length; return { propTypes: type.raw.substring(startIndex + offset, type.raw.indexOf(',')), explanation: recast.parse(type.raw).program.body[0].expression.arguments[1].value, }; } return false; } export function getChained(type: PropTypeDescriptor) { if (type.raw) { const marker = 'chainPropTypes'; const indexStart = type.raw.indexOf(marker); if (indexStart !== -1) { const parsed = docgenParse( ` import PropTypes from 'prop-types'; const Foo = () => <div /> Foo.propTypes = { bar: ${recast.print(recast.parse(type.raw).program.body[0].expression.arguments[0]).code} } export default Foo `, null, null, // helps react-docgen pickup babel.config.js { filename: './' }, ); return { type: parsed.props.bar.type, required: parsed.props.bar.required, }; } } return false; } export function isElementTypeAcceptingRefProp(type: PropTypeDescriptor): boolean { return type.raw === 'elementTypeAcceptingRef'; } function isRefType(type: PropTypeDescriptor): boolean { return type.raw === 'refType'; } function isIntegerType(type: PropTypeDescriptor): boolean { return type.raw.startsWith('integerPropType'); } export function isElementAcceptingRefProp(type: PropTypeDescriptor): boolean { return /^elementAcceptingRef/.test(type.raw); } export default function generatePropTypeDescription(type: PropTypeDescriptor): string | undefined { switch (type.name) { case 'custom': { if (isElementTypeAcceptingRefProp(type)) { return 'element type'; } if (isElementAcceptingRefProp(type)) { return 'element'; } if (isIntegerType(type)) { return 'integer'; } if (isRefType(type)) { return 'ref'; } if (type.raw === 'HTMLElementType') { return 'HTML element'; } if (type.raw === '() => null') { return 'any'; } const deprecatedInfo = getDeprecatedInfo(type); if (deprecatedInfo !== false) { return generatePropTypeDescription({ // eslint-disable-next-line react/forbid-foreign-prop-types name: deprecatedInfo.propTypes, } as any); } const chained = getChained(type); if (chained !== false) { return generatePropTypeDescription(chained.type); } return type.raw; } case 'shape': return `{ ${Object.keys(type.value) .map((subValue) => { const subType = type.value[subValue]; return `${subValue}${subType.required ? '' : '?'}: ${generatePropTypeDescription( subType, )}`; }) .join(', ')} }`; case 'union': return ( type.value .map((type2) => { return generatePropTypeDescription(type2); }) // Display one value per line as it's better for visibility. .join('<br>&#124;&nbsp;') ); case 'enum': return ( type.value .map((type2) => { return escapeCell(type2.value); }) // Display one value per line as it's better for visibility. .join('<br>&#124;&nbsp;') ); case 'arrayOf': { return `Array&lt;${generatePropTypeDescription(type.value)}&gt;`; } case 'instanceOf': { if (type.value.startsWith('typeof')) { return /typeof (.*) ===/.exec(type.value)![1]; } return type.value; } default: return type.name; } }
6,044
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/getPropsFromComponentNode.ts
import * as ts from 'typescript'; import { TypeScriptProject } from './createTypeScriptProject'; export interface ParsedProp { /** * If `true`, some signatures do not contain this property. * e.g: `id` in `{ id: number, value: string } | { value: string }` */ onlyUsedInSomeSignatures: boolean; signatures: { symbol: ts.Symbol; componentType: ts.Type }[]; } export interface ParsedComponent { name: string; location: ts.Node; type: ts.Type; sourceFile: ts.SourceFile | undefined; props: Record<string, ParsedProp>; } function isTypeJSXElementLike(type: ts.Type, project: TypeScriptProject): boolean { const symbol = type.symbol ?? type.aliasSymbol; if (symbol) { const name = project.checker.getFullyQualifiedName(symbol); return ( // Remove once global JSX namespace is no longer used by React name === 'global.JSX.Element' || name === 'React.JSX.Element' || name === 'React.ReactElement' || name === 'React.ReactNode' ); } if (type.isUnion()) { return type.types.every( // eslint-disable-next-line no-bitwise (subType) => subType.flags & ts.TypeFlags.Null || isTypeJSXElementLike(subType, project), ); } return false; } function isStyledFunction(node: ts.VariableDeclaration): boolean { return ( !!node.initializer && ts.isCallExpression(node.initializer) && ts.isCallExpression(node.initializer.expression) && ts.isIdentifier(node.initializer.expression.expression) && node.initializer.expression.expression.escapedText === 'styled' ); } function getJSXLikeReturnValueFromFunction(type: ts.Type, project: TypeScriptProject) { return type .getCallSignatures() .filter((signature) => isTypeJSXElementLike(signature.getReturnType(), project)); } function parsePropsType({ name, type, shouldInclude = () => true, location, sourceFile, }: { name: string; type: ts.Type; location: ts.Node; shouldInclude?: (data: { name: string; depth: number }) => boolean; sourceFile: ts.SourceFile | undefined; }): ParsedComponent { const parsedProps: Record<string, ParsedProp> = {}; type .getProperties() .filter((property) => shouldInclude({ name: property.getName(), depth: 1 })) .forEach((property) => { parsedProps[property.getName()] = { signatures: [ { symbol: property, componentType: type, }, ], onlyUsedInSomeSignatures: false, }; }); return { name, location, type, sourceFile, props: parsedProps, }; } function parseFunctionComponent({ node, shouldInclude, project, }: { node: ts.VariableDeclaration | ts.FunctionDeclaration; shouldInclude?: (data: { name: string; depth: number }) => boolean; project: TypeScriptProject; }): ParsedComponent | null { if (!node.name) { return null; } const symbol = project.checker.getSymbolAtLocation(node.name); if (!symbol) { return null; } const componentName = node.name.getText(); // Discriminate render functions to components if (componentName[0].toUpperCase() !== componentName[0]) { return null; } const signatures = getJSXLikeReturnValueFromFunction( project.checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration!), project, ); if (signatures.length === 0) { return null; } const parsedComponents = signatures.map((signature) => parsePropsType({ shouldInclude, name: componentName, type: project.checker.getTypeOfSymbolAtLocation( signature.parameters[0], signature.parameters[0].valueDeclaration!, ), location: signature.parameters[0].valueDeclaration!, sourceFile: node.getSourceFile(), }), ); const squashedProps: Record<string, ParsedProp> = {}; parsedComponents.forEach((parsedComponent) => { Object.keys(parsedComponent.props).forEach((propName) => { if (!squashedProps[propName]) { squashedProps[propName] = parsedComponent.props[propName]; } else { squashedProps[propName].signatures = [ ...squashedProps[propName].signatures, ...parsedComponent.props[propName].signatures, ]; } }); }); const squashedParsedComponent: ParsedComponent = { ...parsedComponents[0], props: squashedProps, }; Object.keys(squashedParsedComponent.props).forEach((propName) => { squashedParsedComponent.props[propName].onlyUsedInSomeSignatures = squashedParsedComponent.props[propName].signatures.length < signatures.length; }); return squashedParsedComponent; } export interface GetPropsFromComponentDeclarationOptions { project: TypeScriptProject; node: ts.Node; /** * Called before a PropType is added to a component/object * @returns true to include the prop, false to skip it */ shouldInclude?: (data: { name: string; depth: number }) => boolean; /** * Control if const declarations should be checked * @default false * @example declare const Component: React.JSXElementConstructor<Props>; */ checkDeclarations?: boolean; } function getPropsFromVariableDeclaration({ node, project, checkDeclarations, shouldInclude, }: { node: ts.VariableDeclaration } & Pick< GetPropsFromComponentDeclarationOptions, 'project' | 'checkDeclarations' | 'shouldInclude' >) { const type = project.checker.getTypeAtLocation(node.name); if (!node.initializer) { if ( checkDeclarations && type.aliasSymbol && type.aliasTypeArguments && project.checker.getFullyQualifiedName(type.aliasSymbol) === 'React.JSXElementConstructor' ) { const propsType = type.aliasTypeArguments[0]; if (propsType === undefined) { throw new TypeError( 'Unable to find symbol for `props`. This is a bug in typescript-to-proptypes.', ); } return parsePropsType({ name: node.name.getText(), type: propsType, location: node.name, shouldInclude, sourceFile: node.getSourceFile(), }); } if (checkDeclarations) { return parseFunctionComponent({ node, shouldInclude, project, }); } return null; } if ( (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer)) && node.initializer.parameters.length === 1 ) { return parseFunctionComponent({ node, shouldInclude, project, }); } // x = React.memo((props:type) { return <div/> }) // x = React.forwardRef((props:type) { return <div/> }) if (ts.isCallExpression(node.initializer) && node.initializer.arguments.length > 0) { const potentialComponent = node.initializer.arguments[0]; if ( (ts.isArrowFunction(potentialComponent) || ts.isFunctionExpression(potentialComponent)) && potentialComponent.parameters.length > 0 && getJSXLikeReturnValueFromFunction( project.checker.getTypeAtLocation(potentialComponent), project, ).length > 0 ) { const propsSymbol = project.checker.getSymbolAtLocation( potentialComponent.parameters[0].name, ); if (propsSymbol) { return parsePropsType({ name: node.name.getText(), type: project.checker.getTypeOfSymbolAtLocation( propsSymbol, propsSymbol.valueDeclaration!, ), location: propsSymbol.valueDeclaration!, shouldInclude, sourceFile: node.getSourceFile(), }); } } } // handle component factories: x = createComponent() if ( checkDeclarations && node.initializer && !isStyledFunction(node) && getJSXLikeReturnValueFromFunction(type, project).length > 0 ) { return parseFunctionComponent({ node, shouldInclude, project, }); } return null; } export function getPropsFromComponentNode({ node, shouldInclude, project, checkDeclarations, }: GetPropsFromComponentDeclarationOptions): ParsedComponent | null { let parsedComponent: ParsedComponent | null = null; // function x(props: type) { return <div/> } if ( ts.isFunctionDeclaration(node) && node.name && node.parameters.length === 1 && getJSXLikeReturnValueFromFunction(project.checker.getTypeAtLocation(node.name), project) .length > 0 ) { parsedComponent = parseFunctionComponent({ node, shouldInclude, project }); } else if (ts.isVariableDeclaration(node)) { parsedComponent = getPropsFromVariableDeclaration({ node, project, checkDeclarations, shouldInclude, }); } else if (ts.isVariableStatement(node)) { // const x = ... ts.forEachChild(node.declarationList, (variableNode) => { if (parsedComponent != null) { return; } // x = (props: type) => { return <div/> } // x = function(props: type) { return <div/> } // x = function y(props: type) { return <div/> } // x = react.memo((props:type) { return <div/> }) if (ts.isVariableDeclaration(variableNode) && variableNode.name) { parsedComponent = getPropsFromVariableDeclaration({ node: variableNode, project, checkDeclarations, shouldInclude, }); } if ( ts.isClassDeclaration(variableNode) && variableNode.name && variableNode.heritageClauses && variableNode.heritageClauses.length === 1 ) { const heritage = variableNode.heritageClauses[0]; if (heritage.types.length !== 1) { return; } const arg = heritage.types[0]; if (!arg.typeArguments) { return; } parsedComponent = parsePropsType({ shouldInclude, name: variableNode.name.getText(), location: arg.typeArguments[0], type: project.checker.getTypeAtLocation(arg.typeArguments[0]), sourceFile: node.getSourceFile(), }); } }); } return parsedComponent; }
6,045
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/parseSlotsAndClasses.ts
import * as ts from 'typescript'; import { getSymbolDescription, getSymbolJSDocTags } from '../buildApiUtils'; import { TypeScriptProject } from './createTypeScriptProject'; import { Classes } from './parseStyles'; // If GLOBAL_STATE_CLASSES is changed, GlobalStateSlot in // \packages\mui-utils\src\generateUtilityClass\generateUtilityClass.ts must be updated accordingly. const GLOBAL_STATE_CLASSES: string[] = [ 'active', 'checked', 'completed', 'disabled', 'error', 'expanded', 'focused', 'focusVisible', 'open', 'readOnly', 'required', 'selected', ]; export interface Slot { class: string | null; name: string; description: string; default?: string; } function extractClasses({ project, componentName, }: { project: TypeScriptProject; componentName: string; }): { classNames: string[]; descriptions: Record<string, string> } { const result: { classNames: string[]; descriptions: Record<string, string> } = { classNames: [], descriptions: {}, }; const classesInterface = `${componentName}Classes`; const classesType = project.checker.getDeclaredTypeOfSymbol(project.exports[classesInterface]); const classesTypeDeclaration = classesType?.symbol?.declarations?.[0]; if (classesTypeDeclaration && ts.isInterfaceDeclaration(classesTypeDeclaration)) { const classesProperties = classesType.getProperties(); classesProperties.forEach((symbol) => { result.classNames.push(symbol.name); result.descriptions[symbol.name] = getSymbolDescription(symbol, project); }); } return result; } export default function parseSlotsAndClasses({ project, componentName, muiName, }: { project: TypeScriptProject; componentName: string; muiName: string; }): { slots: Slot[]; classes: Classes } { let result: { slots: Slot[]; classes: Classes } = { slots: [], classes: { classes: [], globalClasses: {}, descriptions: {} }, }; const slotsInterface = `${componentName}Slots`; try { const exportedSymbol = project.exports[slotsInterface]; const type = project.checker.getDeclaredTypeOfSymbol(exportedSymbol); const typeDeclaration = type?.symbol?.declarations?.[0]; if (!typeDeclaration || !ts.isInterfaceDeclaration(typeDeclaration)) { return result; } // Obtain an array of classes for the given component const { classNames, descriptions: classDescriptions } = extractClasses({ project, componentName, }); const slots: Record<string, Slot> = {}; const propertiesOnProject = type.getProperties(); propertiesOnProject.forEach((propertySymbol) => { const tags = getSymbolJSDocTags(propertySymbol); if (tags.ignore) { return; } const slotName = propertySymbol.name; slots[slotName] = { name: slotName, description: getSymbolDescription(propertySymbol, project), default: tags.default?.text?.[0].text, class: classNames.includes(slotName) ? `.${muiName}-${slotName}` : null, }; }); const classNamesLeftover = classNames.filter( (className) => !Object.keys(slots).includes(className), ); const globalStateClassNames: Record<string, string> = {}; const otherClassNames: string[] = []; classNamesLeftover.forEach((className) => { if (GLOBAL_STATE_CLASSES.includes(className)) { globalStateClassNames[className] = `Mui-${className}`; } else { otherClassNames.push(className); } }); result = { slots: Object.values(slots), classes: { classes: otherClassNames .concat(Object.keys(globalStateClassNames)) .sort((a, b) => a.localeCompare(b)), globalClasses: globalStateClassNames, descriptions: classDescriptions, }, }; } catch (e) { console.error(`No declaration for ${slotsInterface}`); } return result; }
6,046
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/parseStyles.ts
import * as ts from 'typescript'; import { getSymbolDescription } from '../buildApiUtils'; import { TypeScriptProject } from './createTypeScriptProject'; import { getPropsFromComponentNode } from './getPropsFromComponentNode'; import resolveExportSpecifier from './resolveExportSpecifier'; export interface Classes { classes: string[]; globalClasses: Record<string, string>; descriptions: Record<string, string>; } export interface Styles extends Classes { name: string | null; } const EMPTY_STYLES: Styles = { classes: [], descriptions: {}, globalClasses: {}, name: null, }; function removeUndefinedFromType(type: ts.Type) { // eslint-disable-next-line no-bitwise if (type.flags & ts.TypeFlags.Union) { return (type as ts.UnionType).types.find((subType) => { return subType.flags !== ts.TypeFlags.Undefined; }); } return type; } /** * Gets class names and descriptions from the {ComponentName}Classes interface. */ function extractClasses(project: TypeScriptProject, componentName: string): Styles { const result: Styles = { classes: [], descriptions: {}, globalClasses: {}, name: null, }; const classesInterfaceName = `${componentName}Classes`; if (!project.exports[classesInterfaceName]) { return EMPTY_STYLES; } const classesType = project.checker.getDeclaredTypeOfSymbol( project.exports[classesInterfaceName], ); const classesTypeDeclaration = classesType?.symbol?.declarations?.[0]; if (classesTypeDeclaration && ts.isInterfaceDeclaration(classesTypeDeclaration)) { const classesProperties = classesType.getProperties(); classesProperties.forEach((symbol) => { result.classes.push(symbol.name); result.descriptions[symbol.name] = getSymbolDescription(symbol, project); }); return result; } return EMPTY_STYLES; } export default function parseStyles({ project, componentName, }: { project: TypeScriptProject; componentName: string; }): Styles { const exportedSymbol = project.exports[componentName] ?? project.exports[`Unstable_${componentName}`]; if (!exportedSymbol) { throw new Error(`No exported component for the componentName "${componentName}"`); } const localeSymbol = resolveExportSpecifier(exportedSymbol, project); const declaration = localeSymbol.valueDeclaration!; const classesProp = getPropsFromComponentNode({ node: declaration, project, shouldInclude: ({ name }) => name === 'classes', checkDeclarations: true, })?.props.classes; if (classesProp == null) { // We could not infer the type of the classes prop, so we try to extract them from the {ComponentName}Classes interface return extractClasses(project, componentName); } const classes: Record<string, string> = {}; classesProp.signatures.forEach((propType) => { const type = project.checker.getTypeAtLocation(propType.symbol.declarations?.[0]!); removeUndefinedFromType(type) ?.getProperties() .forEach((property) => { classes[property.escapedName.toString()] = getSymbolDescription(property, project); }); }); return { classes: Object.keys(classes), descriptions: Object.fromEntries( Object.entries(classes).filter((descriptionEntry) => !!descriptionEntry[1]), ), globalClasses: {}, name: null, }; }
6,047
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/parseTest.ts
import * as path from 'path'; import * as babel from '@babel/core'; import { readFile } from 'fs-extra'; import glob from 'fast-glob'; const workspaceRoot = path.join(__dirname, '../../../'); const babelConfigPath = path.join(workspaceRoot, 'babel.config.js'); function getTestFilesNames(filepath: string) { return glob.sync( path .join( path.dirname(filepath), `/{tests/,}{*.,}${path.basename(filepath, path.extname(filepath))}.test.{js,ts,tsx}`, ) .replace(/\\/g, '/'), { absolute: true }, ); } async function parseWithConfig(filename: string, configFilePath: string) { const source = await readFile(filename, { encoding: 'utf8' }); const partialConfig = babel.loadPartialConfig({ configFile: configFilePath, filename, }); if (partialConfig === null) { throw new Error(`Could not load a babel config for ${filename} located at ${configFilePath}.`); } return babel.parseAsync(source, partialConfig.options); } function findConformanceDescriptor( file: babel.ParseResult, ): null | { name: string; body: babel.types.ObjectExpression } { const { types: t } = babel; let descriptor = null; babel.traverse(file, { CallExpression(babelPath) { const { node: callExpression } = babelPath; const { callee } = callExpression; if (t.isIdentifier(callee) && callee.name.startsWith('describeConformance')) { const [, optionsFactory] = callExpression.arguments; if ( t.isArrowFunctionExpression(optionsFactory) && t.isObjectExpression(optionsFactory.body) ) { // describeConformance(element, () => options); descriptor = { name: callee.name, body: optionsFactory.body, }; } else { throw new Error( `Only an arrow function returning an object expression is supported as the second argument to \`describeConformance\` ` + `e.g. \`describeConformance(element, () => ({ someOption: someValue }))\` `, ); } } }, }); return descriptor; } function getRefInstance(valueNode: babel.Node): string | undefined { if (babel.types.isIdentifier(valueNode)) { return valueNode.name; } if (!babel.types.isMemberExpression(valueNode)) { throw new Error( 'Expected a member expression (e.g. window.HTMLDivElement) or a global identifier (e.g. Object) in refInstanceof. ' + 'If the ref will not be resolved use `refInstanceof: undefined`.', ); } const { object, property } = valueNode; if (!babel.types.isIdentifier(object)) { throw new Error( `Expected an Identifier as the object of the MemberExpression of refInstanceOf but got '${object.type}'`, ); } if (!babel.types.isIdentifier(property)) { throw new Error( `Expected an Identifier as the property of the MemberExpression of refInstanceOf but got '${object.type}'`, ); } switch (object.name) { case 'window': return property.name; case 'React': return `React.${property.name}`; default: throw new Error(`Unrecognized member expression starting with '${object.name}'`); } } function getInheritComponentName(valueNode: babel.types.Node): string | undefined { return (valueNode as any).name; } function getSkippedTests(valueNode: babel.types.Node): string[] { if (!babel.types.isArrayExpression(valueNode)) { throw new TypeError( `Unable to determine skipped tests from '${valueNode.type}'. Expected an 'ArrayExpression' i.e. \`skippedTests: ["a", "b"]\`.`, ); } return valueNode.elements.map((element) => { if (!babel.types.isStringLiteral(element)) { throw new TypeError( `Unable to determine skipped test from '${element?.type}'. Expected a 'StringLiter' i.e. \`"a"\`.`, ); } return element.value; }); } export interface ParseResult { forwardsRefTo: string | undefined; inheritComponent: string | undefined; spread: boolean | undefined; themeDefaultProps: boolean | undefined | null; } export default async function parseTest(componentFilename: string): Promise<ParseResult> { const testFilenames = getTestFilesNames(componentFilename); if (testFilenames.length === 0) { throw new Error( `Could not find any test file next to ${componentFilename}. The test filename should end with '.test.{js,ts,tsx}'.`, ); } let descriptor: ReturnType<typeof findConformanceDescriptor> = null; // eslint-disable-next-line no-restricted-syntax for await (const testFilename of testFilenames) { if (descriptor === null) { const babelParseResult = await parseWithConfig(testFilename, babelConfigPath); if (babelParseResult === null) { throw new Error(`Could not parse ${testFilename}.`); } descriptor = findConformanceDescriptor(babelParseResult); } } const result: ParseResult = { forwardsRefTo: undefined, inheritComponent: undefined, spread: undefined, themeDefaultProps: null, }; if (descriptor === null) { return result; } let skippedTests: string[] = []; descriptor.body.properties.forEach((property) => { if (!babel.types.isObjectProperty(property)) { return; } const key: string = (property.key as any).name; switch (key) { case 'refInstanceof': result.forwardsRefTo = getRefInstance(property.value); break; case 'inheritComponent': result.inheritComponent = getInheritComponentName(property.value); break; case 'skip': skippedTests = getSkippedTests(property.value); break; default: break; } }); result.spread = !skippedTests.includes('propsSpread'); result.themeDefaultProps = descriptor.name === 'describeConformanceUnstyled' ? undefined : !skippedTests.includes('themeDefaultProps'); return result; }
6,048
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/replaceUrl.test.js
import { expect } from 'chai'; import replaceUrl, { replaceMaterialLinks, replaceAPILinks, replaceComponentLinks, } from './replaceUrl'; describe('replaceUrl', () => { it('replace material related pathname', () => { expect(replaceMaterialLinks(`/guides/minimizing-bundle-size/`)).to.equal( `/material-ui/guides/minimizing-bundle-size/`, ); expect(replaceMaterialLinks(`/customization/theme-components/#default-props`)).to.equal( `/material-ui/customization/theme-components/#default-props`, ); expect(replaceMaterialLinks(`/getting-started/usage/`)).to.equal( `/material-ui/getting-started/usage/`, ); expect(replaceMaterialLinks(`/discover-more/related-projects/`)).to.equal( `/material-ui/discover-more/related-projects/`, ); expect(replaceMaterialLinks(`/experimental-api/css-theme-variables/overview/`)).to.equal( `/material-ui/experimental-api/css-theme-variables/overview/`, ); expect(replaceMaterialLinks(`/migration/migration-grid-v2/`)).to.equal( `/material-ui/migration/migration-grid-v2/`, ); }); it('should not change if links have been updated', () => { expect(replaceMaterialLinks(`/material-ui/guides/minimizing-bundle-size/`)).to.equal( `/material-ui/guides/minimizing-bundle-size/`, ); expect( replaceMaterialLinks(`/material-ui/customization/theme-components/#default-props`), ).to.equal(`/material-ui/customization/theme-components/#default-props`); expect(replaceMaterialLinks(`/material-ui/getting-started/usage/`)).to.equal( `/material-ui/getting-started/usage/`, ); expect(replaceMaterialLinks(`/material-ui/discover-more/related-projects/`)).to.equal( `/material-ui/discover-more/related-projects/`, ); }); it('replace correct component links', () => { expect(replaceComponentLinks(`/components/button-group/`)).to.equal( `/material-ui/react-button-group/`, ); expect(replaceComponentLinks(`/components/button-group/#main-content`)).to.equal( `/material-ui/react-button-group/#main-content`, ); expect(replaceComponentLinks(`/components/buttons/`)).to.equal(`/material-ui/react-button/`); expect(replaceComponentLinks(`/components/buttons/#main-content`)).to.equal( `/material-ui/react-button/#main-content`, ); expect(replaceComponentLinks(`/components/checkboxes/`)).to.equal( `/material-ui/react-checkbox/`, ); expect(replaceComponentLinks(`/components/checkboxes/#main-content`)).to.equal( `/material-ui/react-checkbox/#main-content`, ); expect(replaceComponentLinks(`/components/radio-buttons/`)).to.equal( `/material-ui/react-radio-button/`, ); expect(replaceComponentLinks(`/components/radio-buttons/#main-content`)).to.equal( `/material-ui/react-radio-button/#main-content`, ); expect(replaceComponentLinks(`/components/selects/`)).to.equal(`/material-ui/react-select/`); expect(replaceComponentLinks(`/components/selects/#main-content`)).to.equal( `/material-ui/react-select/#main-content`, ); expect(replaceComponentLinks(`/components/switches/`)).to.equal(`/material-ui/react-switch/`); expect(replaceComponentLinks(`/components/switches/#main-content`)).to.equal( `/material-ui/react-switch/#main-content`, ); expect(replaceComponentLinks(`/components/text-fields/`)).to.equal( `/material-ui/react-text-field/`, ); expect(replaceComponentLinks(`/components/text-fields/#main-content`)).to.equal( `/material-ui/react-text-field/#main-content`, ); expect(replaceComponentLinks(`/components/avatars/`)).to.equal(`/material-ui/react-avatar/`); expect(replaceComponentLinks(`/components/avatars/#main-content`)).to.equal( `/material-ui/react-avatar/#main-content`, ); expect(replaceComponentLinks(`/components/badges/`)).to.equal(`/material-ui/react-badge/`); expect(replaceComponentLinks(`/components/badges/#main-content`)).to.equal( `/material-ui/react-badge/#main-content`, ); expect(replaceComponentLinks(`/components/chips/`)).to.equal(`/material-ui/react-chip/`); expect(replaceComponentLinks(`/components/chips/#main-content`)).to.equal( `/material-ui/react-chip/#main-content`, ); expect(replaceComponentLinks(`/components/dividers/`)).to.equal(`/material-ui/react-divider/`); expect(replaceComponentLinks(`/components/dividers/#main-content`)).to.equal( `/material-ui/react-divider/#main-content`, ); expect(replaceComponentLinks(`/components/icons/`)).to.equal(`/material-ui/icons/`); expect(replaceComponentLinks(`/components/material-icons/`)).to.equal( `/material-ui/material-icons/`, ); expect(replaceComponentLinks(`/components/lists/`)).to.equal(`/material-ui/react-list/`); expect(replaceComponentLinks(`/components/lists/#main-content`)).to.equal( `/material-ui/react-list/#main-content`, ); expect(replaceComponentLinks(`/components/image-list/`)).to.equal( `/material-ui/react-image-list/`, ); expect(replaceComponentLinks(`/components/image-list/#main-content`)).to.equal( `/material-ui/react-image-list/#main-content`, ); expect(replaceComponentLinks(`/components/no-ssr/`)).to.equal(`/material-ui/react-no-ssr/`); expect(replaceComponentLinks(`/components/no-ssr/#main-content`)).to.equal( `/material-ui/react-no-ssr/#main-content`, ); expect(replaceComponentLinks(`/components/trap-focus/`)).to.equal( `/material-ui/react-trap-focus/`, ); expect(replaceComponentLinks(`/components/trap-focus/#main-content`)).to.equal( `/material-ui/react-trap-focus/#main-content`, ); expect(replaceComponentLinks(`/components/progress/`)).to.equal(`/material-ui/react-progress/`); expect(replaceComponentLinks(`/components/progress/#main-content`)).to.equal( `/material-ui/react-progress/#main-content`, ); expect(replaceComponentLinks(`/components/tables/`)).to.equal(`/material-ui/react-table/`); expect(replaceComponentLinks(`/components/tables/#main-content`)).to.equal( `/material-ui/react-table/#main-content`, ); expect(replaceComponentLinks(`/components/tooltips/`)).to.equal(`/material-ui/react-tooltip/`); expect(replaceComponentLinks(`/components/tooltips/#main-content`)).to.equal( `/material-ui/react-tooltip/#main-content`, ); expect(replaceComponentLinks(`/components/dialogs/`)).to.equal(`/material-ui/react-dialog/`); expect(replaceComponentLinks(`/components/dialogs/#main-content`)).to.equal( `/material-ui/react-dialog/#main-content`, ); expect(replaceComponentLinks(`/components/snackbars/`)).to.equal( `/material-ui/react-snackbar/`, ); expect(replaceComponentLinks(`/components/snackbars/#main-content`)).to.equal( `/material-ui/react-snackbar/#main-content`, ); expect(replaceComponentLinks(`/components/cards/`)).to.equal(`/material-ui/react-card/`); expect(replaceComponentLinks(`/components/cards/#main-content`)).to.equal( `/material-ui/react-card/#main-content`, ); expect(replaceComponentLinks(`/components/breadcrumbs/`)).to.equal( `/material-ui/react-breadcrumbs/`, ); expect(replaceComponentLinks(`/components/breadcrumbs/#main-content`)).to.equal( `/material-ui/react-breadcrumbs/#main-content`, ); expect(replaceComponentLinks(`/components/drawers/`)).to.equal(`/material-ui/react-drawer/`); expect(replaceComponentLinks(`/components/drawers/#main-content`)).to.equal( `/material-ui/react-drawer/#main-content`, ); expect(replaceComponentLinks(`/components/links/`)).to.equal(`/material-ui/react-link/`); expect(replaceComponentLinks(`/components/links/#main-content`)).to.equal( `/material-ui/react-link/#main-content`, ); expect(replaceComponentLinks(`/components/menus/`)).to.equal(`/material-ui/react-menu/`); expect(replaceComponentLinks(`/components/menus/#main-content`)).to.equal( `/material-ui/react-menu/#main-content`, ); expect(replaceComponentLinks(`/components/steppers/`)).to.equal(`/material-ui/react-stepper/`); expect(replaceComponentLinks(`/components/steppers/#main-content`)).to.equal( `/material-ui/react-stepper/#main-content`, ); expect(replaceComponentLinks(`/components/tabs/`)).to.equal(`/material-ui/react-tabs/`); expect(replaceComponentLinks(`/components/tabs/#main-content`)).to.equal( `/material-ui/react-tabs/#main-content`, ); expect(replaceComponentLinks(`/components/transitions/`)).to.equal(`/material-ui/transitions/`); expect(replaceComponentLinks(`/components/pickers/`)).to.equal(`/material-ui/pickers/`); expect(replaceComponentLinks(`/components/about-the-lab/`)).to.equal( `/material-ui/about-the-lab/`, ); expect(replaceComponentLinks(`/components/data-grid/demo/`)).to.equal( `/x/react-data-grid/demo/`, ); }); it('replace correct API links', () => { expect(replaceAPILinks(`/api/button/`)).to.equal(`/material-ui/api/button/`); expect(replaceAPILinks(`/api/no-ssr/`)).to.equal(`/base-ui/api/no-ssr/`); expect(replaceAPILinks(`/api/portal/`)).to.equal(`/base-ui/api/portal/`); expect(replaceAPILinks(`/api/textarea-autosize/`)).to.equal(`/base-ui/api/textarea-autosize/`); expect(replaceAPILinks(`/api/button-unstyled/`)).to.equal(`/base-ui/api/button-unstyled/`); expect(replaceAPILinks(`/api/loading-button/`)).to.equal(`/material-ui/api/loading-button/`); expect(replaceAPILinks(`/api/tab-list/`)).to.equal(`/material-ui/api/tab-list/`); expect(replaceAPILinks(`/api/tab-panel/`)).to.equal(`/material-ui/api/tab-panel/`); expect(replaceAPILinks(`/api/tab-panel-unstyled/`)).to.equal( `/base-ui/api/tab-panel-unstyled/`, ); expect(replaceAPILinks(`/api/tabs-list-unstyled/`)).to.equal( `/base-ui/api/tabs-list-unstyled/`, ); expect(replaceAPILinks(`/api/tabs-unstyled/`)).to.equal(`/base-ui/api/tabs-unstyled/`); expect(replaceAPILinks(`/api/unstable-trap-focus/`)).to.equal( `/base-ui/api/unstable-trap-focus/`, ); expect(replaceAPILinks(`/api/click-away-listener/`)).to.equal( `/base-ui/api/click-away-listener/`, ); expect(replaceAPILinks(`/api/data-grid/data-grid/`)).to.equal(`/x/api/data-grid/data-grid/`); expect(replaceAPILinks(`/system/basic/`)).to.equal(`/system/basic/`); }); it('should do nothing if the components have updated', () => { expect(replaceComponentLinks(`/material-ui/react-button-group/`)).to.equal( `/material-ui/react-button-group/`, ); expect(replaceComponentLinks(`/x/react-data-grid/demo/`)).to.equal(`/x/react-data-grid/demo/`); }); it('should do nothing if the APIs have updated', () => { expect(replaceAPILinks(`/material-ui/api/button/`)).to.equal(`/material-ui/api/button/`); expect(replaceAPILinks(`/base-ui/api/button-unstyled/`)).to.equal( `/base-ui/api/button-unstyled/`, ); expect(replaceAPILinks(`/material-ui/api/loading-button/`)).to.equal( `/material-ui/api/loading-button/`, ); expect(replaceAPILinks(`/x/api/data-grid/`)).to.equal(`/x/api/data-grid/`); }); it('only replace links for new routes (/material-ui/* & /x/*)', () => { expect(replaceUrl(`/guides/minimizing-bundle-size/`, '/material-ui/react-buttons')).to.equal( `/material-ui/guides/minimizing-bundle-size/`, ); expect( replaceUrl(`/components/data-grid/getting-started/#main-content`, '/x/react-data-grid'), ).to.equal(`/x/react-data-grid/getting-started/#main-content`); expect( replaceUrl(`/components/data-grid/components/#main-content`, '/x/react-data-grid'), ).to.equal(`/x/react-data-grid/components/#main-content`); expect(replaceUrl(`/api/button-unstyled`, '/base-ui/api/button-unstyled')).to.equal( `/base-ui/api/button-unstyled`, ); expect(replaceUrl(`/styles/api/`, `/system/basics`)).to.equal(`/system/styles/api/`); }); it('[i18n] only replace links for new routes (/material-ui/* & /x/*)', () => { expect( replaceUrl(`/zh/guides/minimizing-bundle-size/`, '/zh/material-ui/react-buttons'), ).to.equal(`/zh/material-ui/guides/minimizing-bundle-size/`); expect( replaceUrl(`/zh/components/data-grid/getting-started/#main-content`, '/zh/x/react-data-grid'), ).to.equal(`/zh/x/react-data-grid/getting-started/#main-content`); expect( replaceUrl(`/zh/components/data-grid/components/#main-content`, '/zh/x/react-data-grid'), ).to.equal(`/zh/x/react-data-grid/components/#main-content`); expect(replaceUrl(`/zh/api/button-unstyled`, '/zh/base-ui/api/button-unstyled')).to.equal( `/zh/base-ui/api/button-unstyled`, ); expect(replaceUrl(`/zh/styles/api/`, `/system/basics`)).to.equal(`/zh/system/styles/api/`); }); it('does not replace for old routes', () => { expect(replaceUrl(`/guides/minimizing-bundle-size/`, '/components/buttons')).to.equal( `/guides/minimizing-bundle-size/`, ); expect( replaceUrl(`/components/data-grid/getting-started/#main-content`, '/components/buttons'), ).to.equal(`/components/data-grid/getting-started/#main-content`); }); it('does not replace for x marketing page', () => { expect(replaceUrl(`/components/data-grid/getting-started/#main-content`, '/x/')).to.equal( `/components/data-grid/getting-started/#main-content`, ); }); });
6,049
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/replaceUrl.ts
export function isNewLocation(url: string) { url = url.replace(/^\/[a-z]{2}\//, '/'); if (url === '/x' || url === '/x/') { // skipped if it is the X marketing page return false; } return ( url.startsWith('/x') || url.startsWith('/material-ui') || url.startsWith('/base') || url.startsWith('/joy-ui') || url.startsWith('/system') ); } export const replaceMaterialLinks = (url: string) => { if (isNewLocation(url)) { return url; } return url.replace( /(guides|customization|getting-started|discover-more|experimental-api|migration)/, 'material-ui/$1', ); }; export const replaceComponentLinks = (url: string) => { if (isNewLocation(url)) { return url; } url = url.replace(/\/components\/data-grid/, '/x/react-data-grid'); if (isNewLocation(url)) { return url; } if (url.startsWith('/customization')) { url = url.replace('customization', 'material-ui/customization'); } else if (url.match(/components\/(icons|material-icons|transitions|pickers|about-the-lab)/)) { url = url.replace(/\/components\/(.*)/, '/material-ui/$1'); } else { url = url.replace(/\/components\/(.*)/, '/material-ui/react-$1'); // TODO remove, fix the markdown files to match the URLs if (!url.match(/\/react-(tabs|breadcrumbs)/)) { url = url .replace(/(react-[-a-z]+)(x|ch)es([^a-z-])/, '$1$2$3') .replace(/(react-[-a-z]+)s([^a-z-])/, '$1$2') .replace(/(react-[-a-z]+)(x|ch)es$/, '$1$2') .replace(/(react-[-a-z]+)s$/, '$1') .replace(/react-trap-focu/, 'react-trap-focus') .replace(/react-circular-progres/, 'react-circular-progress') .replace(/react-linear-progres/, 'react-linear-progress') .replace(/react-progres/, 'react-progress'); } } return url; }; export const replaceAPILinks = (url: string) => { if (isNewLocation(url) || !url.replace(/^\/[a-zA-Z]{2}\//, '/').startsWith('/api')) { return url; } url = url .replace(/\/api\/data-grid(.*)/, '/x/api/data-grid$1') .replace( /\/api\/(unstable-trap-focus|click-away-listener|no-ssr|portal|textarea-autosize)(.*)/, '/base-ui/api/$1$2', ) .replace(/\/api\/([^/]+-unstyled)(.*)/, '/base-ui/api/$1$2'); if (isNewLocation(url)) { return url; } url = url.replace( /\/api\/(loading-button|tab-list|tab-panel|date-picker|date-time-picker|time-picker|calendar-picker|calendar-picker-skeleton|desktop-picker|mobile-date-picker|month-picker|pickers-day|static-date-picker|year-picker|masonry|timeline|timeline-connector|timeline-content|timeline-dot|timeline-item|timeline-opposite-content|timeline-separator|unstable-trap-focus|tree-item|tree-view)(.*)/, '/material-ui/api/$1$2', ); if (isNewLocation(url)) { return url; } return url.replace(/\/api\/(.*)/, '/material-ui/api/$1'); }; export default function replaceUrl(url: string, asPath: string) { if (isNewLocation(asPath)) { url = replaceMaterialLinks(replaceAPILinks(replaceComponentLinks(url))); url = url.replace(/^\/styles\/(.*)/, '/system/styles/$1'); url = url.replace(/^\/([a-z]{2})\/styles\/(.*)/, '/$1/system/styles/$2'); } return url; }
6,050
0
petrpan-code/mui/material-ui/packages/api-docs-builder
petrpan-code/mui/material-ui/packages/api-docs-builder/utils/resolveExportSpecifier.ts
import * as ts from 'typescript'; import { TypeScriptProject } from './createTypeScriptProject'; function shouldAliasSymbol(symbol: ts.Symbol) { const declaration = symbol.declarations?.[0]; if (!declaration) { return false; } /** * - `export { XXX }` * - `export { XXX } from './modules'` */ if (ts.isExportSpecifier(declaration)) { return true; } /** * - `export default XXX` */ if (ts.isExportAssignment(declaration)) { /** * Return `true` only for `export default XXX` * Not for `export default React.memo(XXX)` for example. */ return declaration.expression.kind === ts.SyntaxKind.Identifier; } return false; } /** * Goes to the root symbol of ExportSpecifier * That corresponds to one of the following patterns * - `export { XXX }` * - `export { XXX } from './modules'` * - `export default XXX` * * Do not go to the root definition for TypeAlias (ie: `export type XXX = YYY`) * Because we usually want to keep the description and tags of the aliased symbol. */ export default function resolveExportSpecifier(symbol: ts.Symbol, project: TypeScriptProject) { let resolvedSymbol = symbol; while (shouldAliasSymbol(resolvedSymbol)) { let newResolvedSymbol; try { newResolvedSymbol = project.checker.getImmediateAliasedSymbol(resolvedSymbol); } catch (err) { newResolvedSymbol = null; } if (!newResolvedSymbol) { throw new Error(`Impossible to resolve export specifier for symbol "${symbol.escapedName}"`); } resolvedSymbol = newResolvedSymbol; } return resolvedSymbol; }
6,051
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/docs-utilities/README.md
# @mui-internal/docs-utilities This package contains utilities shared between docs generation scripts. It is private and not meant to be published.
6,052
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/docs-utilities/index.d.ts
export function getLineFeed(source: string): string; export function fixBabelGeneratorIssues(source: string): string; export function fixLineEndings(source: string, target: string): string; export function getUnstyledFilename(filename: string, definitionFile?: boolean): string;
6,053
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/docs-utilities/index.js
const { EOL } = require('os'); /** * @param {string} source */ function getLineFeed(source) { const match = source.match(/\r?\n/); return match === null ? EOL : match[0]; } const fixBabelIssuesRegExp = /(?<=(\/>)|,)(\r?\n){2}/g; /** * @param {string} source */ function fixBabelGeneratorIssues(source) { return source.replace(fixBabelIssuesRegExp, '\n'); } /** * @param {string} source * @param {string} target */ function fixLineEndings(source, target) { return target.replace(/\r?\n/g, getLineFeed(source)); } /** * Converts styled or regular component d.ts file to unstyled d.ts * @param {string} filename - the file of the styled or regular mui component */ function getUnstyledFilename(filename, definitionFile = false) { if (filename.indexOf('mui-base') > -1) { return filename; } let unstyledFile = ''; const separator = filename.indexOf('/') > -1 ? '/' : '\\'; if (filename.indexOf('mui-base') === -1) { unstyledFile = filename .replace(/.d.ts$/, '') .replace(/.tsx?$/, '') .replace(/.js$/, ''); unstyledFile = unstyledFile.replace(/Styled/g, ''); if (separator === '/') { unstyledFile = unstyledFile.replace( /packages\/mui-lab|packages\/mui-material/g, 'packages/mui-base', ); } else { unstyledFile = unstyledFile.replace( /packages\\mui-lab|packages\\mui-material/g, 'packages\\mui-base', ); } } return definitionFile ? `${unstyledFile}.d.ts` : `${unstyledFile}.js`; } export { getLineFeed, fixBabelGeneratorIssues, fixLineEndings, getUnstyledFilename };
6,054
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/docs-utilities/package.json
{ "name": "@mui-internal/docs-utilities", "version": "1.0.0", "private": "true", "main": "index.js" }
6,055
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/README.md
# eslint-plugin-material-ui Custom eslint rules for MUI. ## List of supported rules - `disallow-active-element-as-key-event-target` - `docgen-ignore-before-comment` - `no-hardcoded-labels` - `rules-of-use-theme-variants` - ~~`restricted-path-imports`~~ ### disallow-active-element-as-key-event-target Prevent `fireEvent.keyDown(document.activeElement)`. The implementation we use already verifies that the passed target can be the target of a `keydown` event. Passing the target explicitly (e.g. `fireEvent.keyDown(getByRole('tab', { selected: true }))`) makes the test more readable. ### docgen-ignore-before-comment Enforce correct usage of `@ignore` in the prop-types block comments. ### no-hardcoded-labels Prevent the usage of hardcoded labels. The docs are translated via Crowdin, we prefer to use `t` from the redux store. ### rules-of-use-theme-variants Ensures correct usage of `useThemeVariants` so that all props are passed as well as their resolved default values. ### ~~restricted-path-imports~~ Removed in favor of [`no-restricted-imports`](https://eslint.org/docs/latest/rules/no-restricted-imports) using the following configuration: ```json { "rules": { "no-restricted-imports": [ "error", { "patterns": ["@mui/*/*/*"] } ] } } ```
6,056
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/package.json
{ "name": "eslint-plugin-material-ui", "version": "5.0.0", "private": true, "description": "Custom eslint rules for MUI.", "main": "src/index.js", "dependencies": { "emoji-regex": "^10.3.0" }, "devDependencies": { "@types/eslint": "^8.44.7", "@typescript-eslint/parser": "^6.8.0", "eslint": "^8.53.0" }, "peerDependencies": { "eslint": "^8.47.0" }, "scripts": { "test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/eslint-plugin-material-ui/**/*.test.js'" }, "repository": { "type": "git", "url": "https://github.com/mui/material-ui.git" }, "license": "MIT" }
6,057
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/index.js
/* eslint-disable global-require */ module.exports.rules = { 'disallow-active-element-as-key-event-target': require('./rules/disallow-active-element-as-key-event-target'), 'docgen-ignore-before-comment': require('./rules/docgen-ignore-before-comment'), 'mui-name-matches-component-name': require('./rules/mui-name-matches-component-name'), 'no-hardcoded-labels': require('./rules/no-hardcoded-labels'), 'rules-of-use-theme-variants': require('./rules/rules-of-use-theme-variants'), 'no-empty-box': require('./rules/no-empty-box'), 'straight-quotes': require('./rules/straight-quotes'), };
6,058
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/disallow-active-element-as-key-event-target.js
/** * @type {import('eslint').Rule.RuleModule} */ const rule = { meta: { messages: { 'keyboard-target': "Don't use document.activeElement as a target for keyboard events. Prefer the actual element.", }, }, create(context) { /** * @param {import('estree').Node} node */ function isDocumentActiveElementNode(node) { return ( node.type === 'MemberExpression' && node.object.name === 'document' && node.property.name === 'activeElement' ); } return { /** * @param {import('estree').CallExpression} node */ CallExpression(node) { const keyboardEventDispatchers = ['keyDown', 'keyUp']; const { arguments: [firstArgument], callee, } = node; const isFireKeyboardEvent = callee.type === 'MemberExpression' && keyboardEventDispatchers.indexOf(callee.property.name) !== -1 && callee.object.name === 'fireEvent'; const targetsDocumentActiveElement = firstArgument !== undefined && (firstArgument.type === 'TSNonNullExpression' ? isDocumentActiveElementNode(firstArgument.expression) : isDocumentActiveElementNode(firstArgument)); if (isFireKeyboardEvent && targetsDocumentActiveElement) { context.report({ messageId: 'keyboard-target', node: firstArgument }); } }, }; }, }; module.exports = rule;
6,059
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/disallow-active-elements-as-key-event-target.test.js
const eslint = require('eslint'); const rule = require('./disallow-active-element-as-key-event-target'); const ruleTester = new eslint.RuleTester({ parser: require.resolve('@typescript-eslint/parser'), parserOptions: { sourceType: 'module' }, }); ruleTester.run('disallow-active-element-as-key-event-target', rule, { valid: [ "import { fireEvent } from '@mui-internal/test-utils';\nfireEvent.keyDown(getByRole('button'), { key: ' ' })", "import { fireEvent } from '@mui-internal/test-utils';\nfireEvent.keyDown(document.body, { key: 'Esc' })", "import { fireEvent } from '@mui-internal/test-utils';\nfireEvent.keyUp(document.body, { key: 'Tab' })", ], invalid: [ { code: "import { fireEvent } from '@mui-internal/test-utils';\nfireEvent.keyUp(document.activeElement, { key: 'LeftArrow' })", errors: [ { message: "Don't use document.activeElement as a target for keyboard events. Prefer the actual element.", type: 'MemberExpression', }, ], }, { code: "import { fireEvent } from '@mui-internal/test-utils';\nfireEvent.keyDown(document.activeElement, { key: 'DownArrow' })", errors: [ { message: "Don't use document.activeElement as a target for keyboard events. Prefer the actual element.", type: 'MemberExpression', }, ], }, { code: "import { fireEvent } from 'any-path';\nfireEvent.keyDown(document.activeElement, { key: 'DownArrow' })", errors: [ { message: "Don't use document.activeElement as a target for keyboard events. Prefer the actual element.", type: 'MemberExpression', }, ], }, { code: "fireEvent.keyDown(document.activeElement, { key: 'DownArrow' })", errors: [ { message: "Don't use document.activeElement as a target for keyboard events. Prefer the actual element.", type: 'MemberExpression', }, ], }, { // test non-null assertion operator code: "import { fireEvent } from '@mui-internal/test-utils';\nfireEvent.keyUp(document.activeElement!, { key: 'LeftArrow' })", errors: [ { message: "Don't use document.activeElement as a target for keyboard events. Prefer the actual element.", type: 'TSNonNullExpression', }, ], }, ], });
6,060
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/docgen-ignore-before-comment.js
module.exports = { create: (context) => { const sourceCode = context.sourceCode; sourceCode.getAllComments().forEach((comment) => { if (comment.type !== 'Block') { return; } /** * The regex has 5 groups (mostly for readability) that match: * 1. '/**', * 2. One or more comment lines beginning with '*', * 3. '* @ignore', * 4. Any number of comment lines beginning with '*', * 5. '* /' (without the space). * * All lines can begin with any number of spaces. */ if (comment.value.match(/( *\*\n)( *\*.*\n)+( *\* @ignore\n)( *\*.*\n)*( )/)) { context.report(comment, '@ignore should be at the beginning of a block comment.'); } }); return {}; }, };
6,061
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/docgen-ignore-before-comment.test.js
const eslint = require('eslint'); const rule = require('./docgen-ignore-before-comment'); const ruleTester = new eslint.RuleTester({ parser: require.resolve('@typescript-eslint/parser') }); ruleTester.run('ignore-before-comment', rule, { valid: [ '\n/**\n * @ignore\n */\n', '\n/**\n * @ignore\n * Comment.\n */\n', '\n/**\n * @ignore\n * Multi-line\n * comment.\n */\n', '\n /**\n * @ignore\n * Indented\n * multi-line\n * comment.\n */\n', ], invalid: [ { code: '\n/**\n * Comment.\n * @ignore\n */\n', errors: [ { message: '@ignore should be at the beginning of a block comment.', type: 'Block' }, ], }, { code: '\n /**\n * Multi-line\n * comment.\n * @ignore\n */\n', errors: [ { message: '@ignore should be at the beginning of a block comment.', type: 'Block' }, ], }, { code: '\n /**\n * Multi-line\n * @ignore\n * comment.\n */\n', errors: [ { message: '@ignore should be at the beginning of a block comment.', type: 'Block' }, ], }, { code: '\n /**\n * Indented\n * multi-line\n * comment.\n * @ignore\n */\n', errors: [ { message: '@ignore should be at the beginning of a block comment.', type: 'Block' }, ], }, ], });
6,062
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/mui-name-matches-component-name.js
/** * @type {import('eslint').Rule.RuleModule} */ const rule = { meta: { messages: { nameMismatch: "Expected `name` to be 'Mui{{ componentName }}' but instead got '{{ name }}'.", noComponent: 'Unable to find component for this call.', noNameProperty: 'Unable to find `name` property. Did you forget to pass `name`?', noNameSecondArgument: "Unable to find name argument. Expected `{{ customHook }}(firstParameter, 'MuiComponent')`.", noNameValue: 'Unable to resolve `name`. Please hardcode the `name` i.e. use a string literal.', }, schema: [ { type: 'object', properties: { customHooks: { type: 'array', items: { type: 'string', }, }, }, additionalProperties: false, }, ], }, create(context) { const [options = {}] = context.options; const { customHooks = [] } = options; function resolveUseThemePropsNameLiteral(node) { if (!node.arguments[0].properties) { return null; } const nameProperty = node.arguments[0].properties.find( (property) => property.key.name === 'name', ); if (nameProperty === undefined) { context.report({ node: node.arguments[0], messageId: 'noNameProperty' }); return null; } if (nameProperty.value.type !== 'Literal') { context.report({ node: nameProperty.value, messageId: 'noNameValue' }); return null; } return nameProperty.value; } function resolveCustomHookNameLiteral(node) { const secondArgument = node.arguments[1]; if (secondArgument === undefined) { context.report({ node: node.arguments[0], messageId: 'noNameSecondArgument', data: { customHook: node.callee.name }, }); return null; } if (secondArgument.type !== 'Literal') { context.report({ node: secondArgument, messageId: 'noNameValue' }); return null; } return secondArgument; } return { CallExpression(node) { let nameLiteral = null; const isUseThemePropsCall = node.callee.name === 'useThemeProps'; if (isUseThemePropsCall) { let isCalledFromCustomHook = false; let parent = node.parent; while (parent != null) { if (parent.type === 'FunctionExpression' || parent.type === 'FunctionDeclaration') { if (customHooks.includes(parent.id.name)) { isCalledFromCustomHook = true; } break; } parent = parent.parent; } if (!isCalledFromCustomHook) { nameLiteral = resolveUseThemePropsNameLiteral(node); } } else if (customHooks.includes(node.callee.name)) { nameLiteral = resolveCustomHookNameLiteral(node); } if (nameLiteral !== null) { let componentName = null; let parent = node.parent; while (parent != null && componentName === null) { if (parent.type === 'FunctionExpression' || parent.type === 'FunctionDeclaration') { componentName = parent.id.name; } if ( parent.type === 'VariableDeclarator' && parent.init.type.match(/(CallExpression|TSAsExpression)/) ) { const callee = parent.init.type === 'TSAsExpression' ? parent.init.expression.callee : parent.init.callee; if (callee.name.includes(parent.id.name)) { // For component factory, e.g. const Container = createContainer({ ... }) componentName = parent.id.name; } } parent = parent.parent; } const name = nameLiteral.value; if (componentName === null) { context.report({ node, messageId: 'noComponent' }); } else if (name !== `Mui${componentName}`) { context.report({ node: nameLiteral, messageId: `nameMismatch`, data: { componentName, name }, }); } } }, }; }, }; module.exports = rule;
6,063
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/mui-name-matches-component-name.test.js
const eslint = require('eslint'); const rule = require('./mui-name-matches-component-name'); const ruleTester = new eslint.RuleTester({ parser: require.resolve('@typescript-eslint/parser') }); ruleTester.run('mui-name-matches-component-name', rule, { valid: [ ` const StaticDateRangePicker = React.forwardRef(function StaticDateRangePicker<TDate>( inProps: StaticDateRangePickerProps<TDate>, ref: React.Ref<HTMLDivElement>, ) { const props = useThemeProps({ props: inProps, name: 'MuiStaticDateRangePicker' }); }); `, ` function CssBaseline(inProps) { useThemeProps({ props: inProps, name: 'MuiCssBaseline' }); } `, ` const Container = createContainer({ createStyledComponent: styled('div', { name: 'MuiContainer', slot: 'Root', overridesResolver: (props, styles) => { const { ownerState } = props; return [ styles.root, ownerState.fixed && styles.fixed, ownerState.disableGutters && styles.disableGutters, ]; }, }), useThemeProps: (inProps) => useThemeProps({ props: inProps, name: 'MuiContainer' }), }); `, ` const Grid2 = createGrid2({ createStyledComponent: styled('div', { name: 'MuiGrid2', overridesResolver: (props, styles) => styles.root, }), componentName: 'MuiGrid2', useThemeProps: (inProps) => useThemeProps({ props: inProps, name: 'MuiGrid2' }), }) as OverridableComponent<Grid2TypeMap>; `, { code: ` const StaticDateRangePicker = React.forwardRef(function StaticDateRangePicker<TDate>( inProps: StaticDateRangePickerProps<TDate>, ref: React.Ref<HTMLDivElement>, ) { const props = useDatePickerDefaultizedProps(inProps, 'MuiStaticDateRangePicker'); }); `, options: [{ customHooks: ['useDatePickerDefaultizedProps'] }], }, { code: ` function useDatePickerDefaultizedProps(props, name) { useThemeProps({ props, name }); } `, options: [{ customHooks: ['useDatePickerDefaultizedProps'] }], }, ], invalid: [ { code: ` const StaticDateRangePicker = React.forwardRef(function StaticDateRangePicker<TDate>( inProps: StaticDateRangePickerProps<TDate>, ref: React.Ref<HTMLDivElement>, ) { const props = useThemeProps({ props: inProps, name: 'MuiPickersDateRangePicker' }); }); `, errors: [ { message: "Expected `name` to be 'MuiStaticDateRangePicker' but instead got 'MuiPickersDateRangePicker'.", type: 'Literal', }, ], }, { code: 'useThemeProps({ props: inProps })', errors: [ { message: 'Unable to find `name` property. Did you forget to pass `name`?', type: 'ObjectExpression', }, ], }, { code: 'useThemeProps({ props: inProps, name })', errors: [ { message: 'Unable to resolve `name`. Please hardcode the `name` i.e. use a string literal.', type: 'Identifier', }, ], }, { code: "useThemeProps({ props: inProps, name: 'MuiPickersDateRangePicker' })", errors: [{ message: 'Unable to find component for this call.', type: 'CallExpression' }], }, { code: ` const StaticDateRangePicker = React.forwardRef(function StaticDateRangePicker<TDate>( inProps: StaticDateRangePickerProps<TDate>, ref: React.Ref<HTMLDivElement>, ) { const props = useDatePickerDefaultizedProps(inProps); }); `, options: [{ customHooks: ['useDatePickerDefaultizedProps'] }], errors: [ { message: "Unable to find name argument. Expected `useDatePickerDefaultizedProps(firstParameter, 'MuiComponent')`.", type: 'Identifier', }, ], }, { code: ` const StaticDateRangePicker = React.forwardRef(function StaticDateRangePicker<TDate>( inProps: StaticDateRangePickerProps<TDate>, ref: React.Ref<HTMLDivElement>, ) { const props = useDatePickerDefaultizedProps(inProps, 'MuiPickersDateRangePicker'); }); `, options: [{ customHooks: ['useDatePickerDefaultizedProps'] }], errors: [ { message: "Expected `name` to be 'MuiStaticDateRangePicker' but instead got 'MuiPickersDateRangePicker'.", type: 'Literal', }, ], }, ], });
6,064
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/no-empty-box.js
/** * @type {import('eslint').Rule.RuleModule} */ const rule = { meta: { docs: { description: 'Disallow use of <Box /> that should be a DOM host element.', }, messages: { emptyBox: 'Empty <Box /> is not allowed, use host DOM element instead: <{{component}}>.', }, // fixable: 'code', TODO type: 'suggestion', schema: [], }, create(context) { return { JSXOpeningElement(node) { if (node.name.name !== 'Box') { return; } let component = 'div'; let validUse = false; node.attributes.forEach((decl) => { // We can't know, let's say it's ok. if (decl.type === 'JSXSpreadAttribute') { validUse = true; return; } const name = decl.name.name; if (name === 'component') { component = decl.value.value; return; } validUse = true; }); if (!validUse) { context.report({ node, messageId: 'emptyBox', data: { component }, // fix: (fixer) => { // return fixer.replaceTextRange(node.name.range, component); // }, }); } }, }; }, }; module.exports = rule;
6,065
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/no-empty-box.test.js
const eslint = require('eslint'); const rule = require('./no-empty-box'); const ruleTester = new eslint.RuleTester({ parser: require.resolve('@typescript-eslint/parser'), parserOptions: { ecmaFeatures: { jsx: true }, }, }); ruleTester.run('no-empty-box', rule, { valid: ['<Box sx={{ width: 1 }}>Foo</Box>', '<Box sx={{ width: 1 }} />', '<Box {...props} />'], invalid: [ { code: '<Box>Foo</Box>', errors: [ { messageId: 'emptyBox', type: 'JSXOpeningElement', data: { component: 'div', }, }, ], }, { code: '<Box component="span">Foo</Box>', errors: [ { messageId: 'emptyBox', type: 'JSXOpeningElement', data: { component: 'span', }, }, ], }, ], });
6,066
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/no-hardcoded-labels.js
const createEmojiRegex = require('emoji-regex'); const defaultAllow = ['API']; module.exports = { meta: { messages: { 'literal-label': "Don't use hardcoded labels. Prefer translated values by using `useTranslate`. New translations should be added to `docs/translations/translations.json`.", }, schema: [ { type: 'object', properties: { allow: { oneOf: [ { type: 'array', items: { type: 'string', }, }, { type: 'string', }, ], }, }, additionalProperties: false, }, ], }, create(context) { const { allow: allowOption = [] } = context.options[0] || {}; const emojiRegex = createEmojiRegex(); const allow = defaultAllow.concat(allowOption); function valueViolatesRule(value) { const sanitizedValue = typeof value === 'string' ? value.trim() : value; const hasTranslateableContent = sanitizedValue !== '' && !emojiRegex.test(sanitizedValue) && /\w+/.test(sanitizedValue); return hasTranslateableContent && !allow.includes(sanitizedValue); } return { JSXExpressionContainer(node) { if (node.parent.type === 'JSXElement') { const isTemplateLiteral = node.expression.type === 'TemplateLiteral'; const isStringLiteral = node.expression.type === 'Literal' && typeof node.expression.value === 'string'; if ((isStringLiteral && valueViolatesRule(node.expression.value)) || isTemplateLiteral) { context.report({ messageId: 'literal-label', node }); } } }, JSXText(node) { if (node.parent.type === 'JSXElement') { if (valueViolatesRule(node.value)) { context.report({ messageId: 'literal-label', node }); } } }, Literal(node) { const canLabelComponent = node.parent.type === 'JSXElement' || (node.parent.type === 'JSXAttribute' && ['aria-label'].includes(node.parent.name.name)); if (canLabelComponent && valueViolatesRule(node.value)) { context.report({ messageId: 'literal-label', node }); } }, }; }, };
6,067
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/no-hardcoded-labels.test.js
const eslint = require('eslint'); const rule = require('./no-hardcoded-labels'); const ruleTester = new eslint.RuleTester({ parser: require.resolve('@typescript-eslint/parser'), parserOptions: { ecmaFeatures: { jsx: true }, }, }); ruleTester.run('no-hardcoded-labels', rule, { valid: [ '<button>{42}</button>', '<button aria-label={t("a")} />', '<button data-label="a" />', '<button>{t("a")}</button>', '<button>{166}</button>', '<button> <TranslatedLabelAfterWhiteSpace /></button>', { code: '<a>MUI</a>', options: [{ allow: 'MUI' }] }, '<span> ❤️</span>', `<button>{t("a")}{' '}</button>`, '<h2>{componentName} API</h2>', '<span>*</span>', '<span>.{className}</span>', ], invalid: [ { code: '<button aria-label="a" />', errors: [{ messageId: 'literal-label' }] }, { code: '<button>test<Component /></button>', errors: [{ messageId: 'literal-label' }] }, { code: '<label>test<Component /></label>', errors: [{ messageId: 'literal-label' }] }, { code: "<label>{'< Back to blog'}</label>", errors: [{ messageId: 'literal-label' }] }, { code: '<label>{`< Back to blog`}</label>', errors: [{ messageId: 'literal-label' }] }, ], });
6,068
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/rules-of-use-theme-variants.js
module.exports = { meta: { type: 'problem', }, create(context) { function getComponentProps(componentBlockNode) { // finds the declarator in `const {...} = props;` let componentPropsDeclarator = null; componentBlockNode.body.forEach((node) => { if (node.type === 'VariableDeclaration') { const propsDeclarator = node.declarations.find((declarator) => { return declarator.init && declarator.init.name === 'props'; }); if (propsDeclarator !== undefined) { componentPropsDeclarator = propsDeclarator; } } }); return componentPropsDeclarator !== null ? componentPropsDeclarator.id : undefined; } function getComponentBlockNode(hookCallNode) { let node = hookCallNode.parent; while (node !== undefined) { if (node.type === 'BlockStatement') { return node; } node = node.parent; } return null; } return { CallExpression(node) { if (node.callee.name === 'useThemeVariants') { const componentBlockNode = getComponentBlockNode(node); const componentProps = getComponentProps(componentBlockNode); const defaultProps = componentProps === undefined ? [] : componentProps.properties.filter((objectProperty) => { return ( objectProperty.type === 'Property' && objectProperty.value.type === 'AssignmentPattern' ); }); const [variantProps] = node.arguments; const unsupportedComponentPropsNode = componentProps !== undefined && componentProps.type !== 'ObjectPattern'; if (unsupportedComponentPropsNode) { context.report({ node: componentProps, message: `Can only analyze object patterns but found '${componentProps.type}'. Prefer \`const {...} = props;\``, }); } if (defaultProps.length === 0) { return; } if (variantProps.type !== 'ObjectExpression') { context.report({ node: variantProps, message: `Can only analyze object patterns but found '${variantProps.type}'. Prefer \`{...props}\`.`, }); return; } const variantPropsRestNode = variantProps.properties.find((objectProperty) => { return objectProperty.type === 'SpreadElement'; }); if ( variantPropsRestNode !== undefined && variantProps.properties.indexOf(variantPropsRestNode) !== 0 && defaultProps.length > 0 ) { context.report({ node: variantPropsRestNode, message: 'The props spread must come first in the `useThemeVariants` props. Otherwise destructured props with default values could be overridden.', }); } defaultProps.forEach((componentProp) => { const isPassedToVariantProps = variantProps.properties.find((variantProp) => { return ( variantProp.type === 'Property' && componentProp.key.name === variantProp.key.name ); }) !== undefined; if (!isPassedToVariantProps) { context.report({ node: variantProps, message: `Prop \`${componentProp.key.name}\` is not passed to \`useThemeVariants\` props.`, }); } }); } }, }; }, };
6,069
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/rules-of-use-theme-variants.test.js
const eslint = require('eslint'); const rule = require('./rules-of-use-theme-variants'); const ruleTester = new eslint.RuleTester({ parser: require.resolve('@typescript-eslint/parser'), parserOptions: { ecmaFeatures: { jsx: true }, }, }); ruleTester.run('rules-of-use-theme-variants', rule, { valid: [ // allowed but dangerous ` { const useCustomThemeVariants = props => useThemeVariants(props); }`, ` { useThemeVariants(props); } `, ` { const { className, value: valueProp, ...other } = props; useThemeVariants(props); } `, ` { const { className, disabled = false, value: valueProp, ...other } = props; useThemeVariants({ ...props, disabled }); } `, ` { const { className, value: valueProp, ...other } = props; const [stateA, setStateA] = React.useState(0); const [stateB, setStateB] = React.useState(0); useThemeVariants({ stateA, ...props, stateB }); } `, // unnecessary spread but it's not the responsibility of this rule to catch "unnecessary" spread ` { const { className, value: valueProp, ...other } = props; useThemeVariants({ ...props}); } `, ], invalid: [ { code: ` { const { disabled = false, ...other } = props; useThemeVariants({ ...props}); } `, errors: [ { message: 'Prop `disabled` is not passed to `useThemeVariants` props.', line: 4, column: 20, endLine: 4, endColumn: 31, }, ], }, { code: ` { const { disabled = false, variant = 'text', ...other } = props; useThemeVariants({ ...props, disabled }); } `, errors: [ { message: 'Prop `variant` is not passed to `useThemeVariants` props.', line: 4, column: 20, endLine: 4, endColumn: 42, }, ], }, { code: ` { const { disabled = false, ...other } = props; useThemeVariants({ disabled, ...props }); } `, errors: [ { message: 'The props spread must come first in the `useThemeVariants` props. Otherwise destructured props with default values could be overridden.', line: 4, column: 32, endLine: 4, endColumn: 40, }, ], }, // this is valid code but not analyzable by this rule { code: ` { const { disabled = false, ...other } = props; const themeVariantProps = { ...props, disabled }; useThemeVariants(themeVariantProps); } `, errors: [ { message: "Can only analyze object patterns but found 'Identifier'. Prefer `{...props}`.", line: 5, column: 20, endLine: 5, endColumn: 37, }, ], }, ], });
6,070
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/straight-quotes.js
// eslint-disable-next-line material-ui/straight-quotes const nonStraightQuotes = /[‘’“”]/gm; /** * @type {import('eslint').Rule.RuleModule} */ const rule = { meta: { docs: { description: 'Only allow straight quotes. Curly quotes can still be used but in specific context where relevant.', }, messages: { wrongQuotes: 'Only allow straight quotes. Curly quotes can still be used but in specific context where relevant.', }, // fixable: 'code', TODO type: 'suggestion', schema: [], }, create(context) { return { Program(node) { const value = context.sourceCode.text; let match; // eslint-disable-next-line no-cond-assign while ((match = nonStraightQuotes.exec(value)) !== null) { context.report({ node, loc: { start: context.sourceCode.getLocFromIndex(match.index), end: context.sourceCode.getLocFromIndex(match.index + 1), }, messageId: 'wrongQuotes', }); } }, }; }, }; module.exports = rule;
6,071
0
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src
petrpan-code/mui/material-ui/packages/eslint-plugin-material-ui/src/rules/straight-quotes.test.js
/* eslint-disable material-ui/straight-quotes */ const eslint = require('eslint'); const rule = require('./straight-quotes'); const ruleTester = new eslint.RuleTester({ parser: require.resolve('@typescript-eslint/parser') }); ruleTester.run('straight-quotes', rule, { valid: [ ` const values = [ { title: 'Put community first 💙', }, ]; `, ], invalid: [ { code: ` const values = [ { title: 'Put community first 💙', description: 'We never lose sight of who we’re serving and why.', }, ]; `, errors: [ { messageId: 'wrongQuotes', line: 5, }, ], }, { code: ` // reference ID (also known as “SHA” or “hash”) of the commit we're building. const values = 'foo'; `, errors: [ { line: 2, column: 32, messageId: 'wrongQuotes', }, { line: 2, column: 36, messageId: 'wrongQuotes', }, { line: 2, column: 41, messageId: 'wrongQuotes', }, { line: 2, column: 46, messageId: 'wrongQuotes', }, ], }, ], });
6,072
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/feedback/README.md
# Rating This Lambda function stores and retrieves page feedback using DynamoDB. It is already deployed in the MUI AWS account. Request credentials if you need to update dev for testing, or to deploy a new prod version. If you wish to deploy your own instance for testing, follow the steps below. ## Prerequisites Create an AWS profile in ~/.aws/credentials called "claudia" with credentials corresponding to an IAM user with AmazonAPIGatewayAdministrator, AWSLambdaFullAccess and IAMFullAccess policies. You can do that with `aws configure --profile claudia`. Create a table in DynamoDB, with a `string` partition key called `id`, and a sort key called `page`. You can do that from the DynamoDB web console, or using the AWS CLI command line. Here is an example command that will create the `feedback-dev` table with the minimal provisioned throughput: ```bash aws dynamodb create-table --profile claudia --region us-east-1 \ --attribute-definitions AttributeName=id,AttributeType=S AttributeName=page,AttributeType=S \ --key-schema AttributeName=id,KeyType=HASH AttributeName=page,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=1 \ --query TableDescription.TableArn --output text \ --table-name feedback-dev ``` You will need to repeat this command to create a table for production, for example `feedback-prod`. For on-demand throughput, replace: ```bash --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=1 \ ``` with: ```bash --billing-mode PAY_PER_REQUEST \ ``` The project includes an IAM access policy that will grant the lambda function access to the tables. You can edit the [policies/access-dynamodb.json](policies/access-dynamodb.json) file to change the access permissions. These are only applied on create (`yarn setup`). Alternatively, to avoid inadvertently pushing changes, use the `--policies` flag with `yarn setup` to refer to a copy of this directory, and exclude it in your `~/.gitignore`. > ⚠️ You will need to update the "Resource" key in this file with the value returned after creating each table. ## Get started > ⚠️ When setting up for the first time, you will need to delete the included `claudia.json` file that is specific to the MUI installation. Alternatively, if making changes to the function that you intend to submit back, then to avoid inadvertently committing changes to `claudia.json`, use `--config` with each command to create and use a local config file, and exclude this file in your `~/.gitignore`. To set this up, first [set up the credentials](https://claudiajs.com/tutorials/installing.html#configuring-access-credentials), then: 1. run `yarn install` (from the root workspace) to install the dependencies 1. Navigate into the directory of this README, e.g. `cd docs/packages/feedback` 1. run `yarn setup` to create the lambda function on AWS under the default name. This will also ask you for table names for development and production. If you used the above AWS command, they will be `feedback-dev` and `feedback-dev` respectively. 1. Test the API using the [example requests below](#testing) For subsequent updates, use the `npm run deploy` command. ## Stage variables The table name, stored in the API Gateway stage variables, is passed to each request processor in the `request.env` key-value map. Check out [index.js](index.js) to see it in use. The value is set during the first deployment, using `--configure-table-dev` & `--configure-table-prod`. This works using a post-deploy step (check out the last line of [index.js](index.js) for the actual setup, and [Configuring stage variables using post-deployment steps](https://github.com/claudiajs/claudia-api-builder/blob/master/docs/api.md#configuring-stage-variables-using-post-deployment-steps) for more information about the API). ## The API - `POST` to `/feedback` - stores a new rating data object - `GET` from `/feedback/{id}` - returns all ratings with id `{id}` - `GET` from `/rating/average` - returns average ratings for all pages ## Testing Claudia will print the API URL after it is created (typically something in the format `https://[API ID].execute-api.[REGION].amazonaws.com/<version>`). Replace `<API-URL>` with that value in the examples below: You can test the API by using `curl` (or using a fancier client like [Postman](https://www.getpostman.com/)). Below are some examples with `curl`. ### Create new feedback This will create a feedback entry from the data stored in [example.json](example.json). Change the data in the file to create ratings: ```bash curl -H "Content-Type: application/json" -X POST --data @example.json <API-URL>/feedback ``` Add the UUID returned to `example.json` with key `id` to store more feedback under the same id. ### Retrieve feedback This will get the feedback stored for ID d6890562-3606-4c14-a765-da81919057d1 ```bash curl <API-URL>/feedback/d6890562-3606-4c14-a765-da81919057d1 ``` ### Retrieve average ratings This will get the average feedback stored for all pages ```bash curl <API-URL>/feedback/average ``` ### Testing with the documentation Create the file `docs/.env.local` containing an environment variable `FEEDBACK_URL` with your API URL without the version. For example: ```bash FEEDBACK_URL=https://abcd123ef4.execute-api.us-east-1.amazonaws.com ``` If already running, restart the local docs site. Feedback should now be posted to your deployment.
6,073
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/feedback/claudia.json
{ "lambda": { "role": "feedback-executor", "name": "feedback", "region": "us-east-1" }, "api": { "id": "hgvi836wi8", "module": "index" } }
6,074
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/feedback/example.json
{ "page": "/material-ui/react-card", "version": "5.0.0", "rating": 5, "comment": "Yay!", "language": "en" }
6,075
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/feedback/index.js
/* eslint-disable no-console */ const ApiBuilder = require('claudia-api-builder'); const AWS = require('aws-sdk'); const { v4: uuid } = require('uuid'); const api = new ApiBuilder(); const dynamoDb = new AWS.DynamoDB.DocumentClient(); async function dbGet(request, id, page) { const stage = request.context.stage; const params = { TableName: request.env[`${stage}TableName`], Key: { id, page, }, ConsistentRead: true, }; try { console.log('dbGet()', params); const response = await dynamoDb.get(params).promise(); console.log({ response }); return response.Item; } catch (error) { console.error(error); throw error; } } async function dbPut(request, id, item = {}) { const stage = request.context.stage; const { page, rating, comment, version, language } = request.body; const params = { TableName: request.env[`${stage}TableName`], Item: { id, page, rating, comment, version, language, dateTime: new Date().toString(), }, }; await Object.assign(params.Item, item); try { console.log('dbPut()', params); const response = await dynamoDb.put(params).promise(); console.log({ response }); return params.Item; } catch (error) { console.error(error); throw error; } } async function dbQuery(request, id) { const stage = request.context.stage; const params = { TableName: request.env[`${stage}TableName`], KeyConditionExpression: 'id = :id', ExpressionAttributeValues: { ':id': id, }, ConsistentRead: true, }; try { console.log('dbQuery()', params); const response = await dynamoDb.query(params).promise(); console.log({ response }); return response.Items; } catch (error) { console.error(error); throw error; } } async function updateAverageRating(request, currentUserRating) { console.log('updateAverageRating()'); const id = 'average'; const pageAverage = await dbGet(request, id, request.body.page); const average = (pageAverage && pageAverage.rating) || 0; let count = (pageAverage && pageAverage.count) || 0; let rating; if (currentUserRating !== null) { rating = (average * count - currentUserRating + request.body.rating) / count; } else { rating = (average * count + request.body.rating) / (count + 1); count += 1; } const newAverageRating = { rating, count, comment: undefined, language: undefined, }; return dbPut(request, id, newAverageRating); } api.post( '/feedback', async (request) => { console.log('POST /feedback', request.body); const id = request.body.id || uuid(); let currentRating = null; if (request.body.id) { const userPage = await dbGet(request, id, request.body.page); console.log({ userPage }); currentRating = userPage && userPage.rating; } try { const result = await dbPut(request, id); await updateAverageRating(request, currentRating); return result; } catch (error) { console.log(error); throw error; } }, { success: 201 }, ); api.get('/feedback/{id}', (request) => { console.log(`GET /feedback/${request.pathParams.id}`); return (async () => { const result = await dbQuery(request, request.pathParams.id); return result.reduce((acc, curr) => { const { rating, comment, count } = curr; acc[curr.page] = { rating, comment, count }; return acc; }, {}); })(); }); api.addPostDeployConfig('devTableName', 'DynamoDB Development Table Name:', 'configure-table-dev'); api.addPostDeployConfig('prodTableName', 'DynamoDB Production Table Name:', 'configure-table-prod'); module.exports = api;
6,076
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/feedback/package.json
{ "name": "feedback", "version": "5.0.0", "description": "Store and retrieve page ratings and comments", "main": "./index.js", "license": "MIT", "author": "MUI Team", "private": true, "files": [ "*.js" ], "scripts": { "claudia": "claudia --profile claudia", "curl": "curl -H \"Content-Type: application/json\" -X POST --data @example.json https://hgvi836wi8.execute-api.us-east-1.amazonaws.com/dev/rating", "setup": "claudia create --profile claudia --version dev --region us-east-1 --api-module index --policies policies --configure-table-dev --configure-table-prod --no-optional-dependencies", "update": "claudia update --profile claudia --version dev --no-optional-dependencies", "deploy": "claudia update --profile claudia --version dev --no-optional-dependencies && claudia --profile claudia set-version --version prod", "reconfigure": "claudia update --profile claudia --configure-db" }, "dependencies": { "claudia-api-builder": "^4.1.2", "uuid": "^9.0.1" }, "devDependencies": { "claudia": "^5.14.1" }, "optionalDependencies": { "aws-sdk": "^2.1490.0" } }
6,077
0
petrpan-code/mui/material-ui/packages/feedback
petrpan-code/mui/material-ui/packages/feedback/policies/access-dynamodb.json
{ "Version": "2012-10-17", "Statement": [ { "Action": ["dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query"], "Effect": "Allow", "Resource": "arn:aws:dynamodb:us-east-1:446171413463:table/feedback-dev" }, { "Action": ["dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query"], "Effect": "Allow", "Resource": "arn:aws:dynamodb:us-east-1:446171413463:table/feedback-dev" } ] }
6,078
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/extractImports.js
const importModuleRegexp = /^\s*import (?:["'\s]*(?:[\w*{}\n, ]+)from\s*)?["'\s]*([^"'{}$\s]+)["'\s].*/gm; function extractImports(code) { return (code.match(importModuleRegexp) || []).map((x) => x.replace(importModuleRegexp, '$1')); } module.exports = extractImports;
6,079
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/extractImports.test.js
import { expect } from 'chai'; import extractImports from './extractImports'; describe('extractImports', () => { it('finds all imports', () => { const imports = extractImports(` import { Component } from '@angular2/core'; import defaultMember from "module-1"; import * as name from "module-2 "; import { member } from " module-3"; import { member as alias } from "module-4"; import { member1 , member2 } from "module-5"; import { member1 , member2 as alias2 , member3 as alias3 } from "module-6"; import defaultMember, { member, member } from "module-7"; import defaultMember, * as name from "module-8"; import "module-9"; import "module-10"; import * from './smdn'; import \${importName} from 'module11/\${importName}'; `); expect(imports[0]).to.equal('@angular2/core'); expect(imports[1]).to.equal('module-1'); expect(imports[2]).to.equal('module-2'); expect(imports[3]).to.equal('module-3'); expect(imports[4]).to.equal('module-4'); expect(imports[5]).to.equal('module-5'); expect(imports[6]).to.equal('module-6'); expect(imports[7]).to.equal('module-7'); expect(imports[8]).to.equal('module-8'); expect(imports[9]).to.equal('module-9'); expect(imports[10]).to.equal('module-10'); expect(imports[11]).to.equal('./smdn'); expect(imports[12]).to.equal(undefined); // It's not a valid import }); });
6,080
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/index.d.ts
interface TableOfContentsEntry { children: TableOfContentsEntry; hash: string; level: number; text: string; } export function createRender(context: { headingHashes: Record<string, string>; toc: TableOfContentsEntry[]; userLanguage: string; ignoreLanguagePages: (path: string) => boolean; }): (markdown: string) => string; export function getHeaders(markdown: string): Record<string, string | string[]>; export function getTitle(markdown: string): string; export function renderMarkdown(markdown: string): string;
6,081
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/index.js
const { createRender, getHeaders, getTitle, renderMarkdown } = require('./parseMarkdown'); module.exports = { createRender, getHeaders, getTitle, renderMarkdown };
6,082
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/loader.js
const { promises: fs, readdirSync } = require('fs'); const path = require('path'); const prepareMarkdown = require('./prepareMarkdown'); const extractImports = require('./extractImports'); const notEnglishMarkdownRegExp = /-([a-z]{2})\.md$/; /** * @param {string} string */ function upperCaseFirst(string) { return `${string[0].toUpperCase()}${string.slice(1)}`; } /** * @param {string} moduleID * @example moduleIDToJSIdentifier('./Box.js') === '$$IndexJs' * @example moduleIDToJSIdentifier('./Box-new.js') === '$$BoxNewJs' * @example moduleIDToJSIdentifier('../Box-new.js') === '$$$BoxNewJs' */ function moduleIDToJSIdentifier(moduleID) { const delimiter = /(\.|-|\/|:)/; return moduleID .split(delimiter) .filter((part) => !delimiter.test(part)) .map((part) => (part.length === 0 ? '$' : part)) .map(upperCaseFirst) .join(''); } const componentPackageMapping = { 'material-ui': {}, 'base-ui': {}, 'joy-ui': {}, }; const packages = [ { productId: 'material-ui', paths: [ path.join(__dirname, '../../packages/mui-base/src'), path.join(__dirname, '../../packages/mui-lab/src'), path.join(__dirname, '../../packages/mui-material/src'), ], }, { productId: 'base-ui', paths: [path.join(__dirname, '../../packages/mui-base/src')], }, { productId: 'joy-ui', paths: [path.join(__dirname, '../../packages/mui-joy/src')], }, ]; packages.forEach((pkg) => { pkg.paths.forEach((pkgPath) => { const match = pkgPath.match(/packages(?:\\|\/)([^/\\]+)(?:\\|\/)src/); const packageName = match ? match[1] : null; if (!packageName) { throw new Error(`cannot find package name from path: ${pkgPath}`); } const filePaths = readdirSync(pkgPath); filePaths.forEach((folder) => { if (folder.match(/^[A-Z]/)) { if (!componentPackageMapping[pkg.productId]) { throw new Error(`componentPackageMapping must have "${pkg.productId}" as a key`); } // filename starts with Uppercase = component componentPackageMapping[pkg.productId][folder] = packageName; } }); }); }); /** * @type {import('webpack').loader.Loader} */ module.exports = async function demoLoader() { const englishFilepath = this.resourcePath; const options = this.getOptions(); const englishFilename = path.basename(englishFilepath, '.md'); const files = await fs.readdir(path.dirname(englishFilepath)); const translations = await Promise.all( files .map((filename) => { if (filename === `${englishFilename}.md`) { return { filename, userLanguage: 'en', }; } const matchNotEnglishMarkdown = filename.match(notEnglishMarkdownRegExp); if ( filename.startsWith(englishFilename) && matchNotEnglishMarkdown !== null && options.languagesInProgress.indexOf(matchNotEnglishMarkdown[1]) !== -1 ) { return { filename, userLanguage: matchNotEnglishMarkdown[1], }; } return null; }) .filter((translation) => translation) .map(async (translation) => { const filepath = path.join(path.dirname(englishFilepath), translation.filename); this.addDependency(filepath); const markdown = await fs.readFile(filepath, { encoding: 'utf8' }); return { ...translation, markdown, }; }), ); // Use .. as the docs runs from the /docs folder const repositoryRoot = path.join(this.rootContext, '..'); const fileRelativeContext = path .relative(repositoryRoot, this.context) // win32 to posix .replace(/\\/g, '/'); const { docs } = prepareMarkdown({ fileRelativeContext, translations, componentPackageMapping, options, }); const demos = {}; const importedModuleIDs = new Set(); const components = {}; const demoModuleIDs = new Set(); const componentModuleIDs = new Set(); const demoNames = Array.from( new Set( docs.en.rendered .filter((markdownOrComponentConfig) => { return typeof markdownOrComponentConfig !== 'string' && markdownOrComponentConfig.demo; }) .map((demoConfig) => { return demoConfig.demo; }), ), ); await Promise.all( demoNames.map(async (demoName) => { const multipleDemoVersionsUsed = !demoName.endsWith('.js'); // TODO: const moduleID = demoName; // The import paths currently use a completely different format. // They should just use relative imports. let moduleID = `./${demoName.replace( `pages/${fileRelativeContext.replace(/^docs\/src\/pages\//, '')}/`, '', )}`; if (multipleDemoVersionsUsed) { moduleID = `${moduleID}/system/index.js`; } const moduleFilepath = path.join( path.dirname(this.resourcePath), moduleID.replace(/\//g, path.sep), ); this.addDependency(moduleFilepath); demos[demoName] = { module: moduleID, raw: await fs.readFile(moduleFilepath, { encoding: 'utf8' }), }; demoModuleIDs.add(moduleID); extractImports(demos[demoName].raw).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); if (multipleDemoVersionsUsed) { // Add Tailwind demo data const tailwindModuleID = moduleID.replace('/system/index.js', '/tailwind/index.js'); try { // Add JS demo data const tailwindModuleFilepath = path.join( path.dirname(this.resourcePath), tailwindModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTailwind = tailwindModuleID; demos[demoName].rawTailwind = await fs.readFile(tailwindModuleFilepath, { encoding: 'utf8', }); this.addDependency(tailwindModuleFilepath); demoModuleIDs.add(tailwindModuleID); extractImports(demos[demoName].rawTailwind).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTailwind); } catch (error) { // tailwind js demo doesn't exists } try { // Add TS demo data const tailwindTSModuleID = tailwindModuleID.replace('.js', '.tsx'); const tailwindTSModuleFilepath = path.join( path.dirname(this.resourcePath), tailwindTSModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTSTailwind = tailwindTSModuleID; demos[demoName].rawTailwindTS = await fs.readFile(tailwindTSModuleFilepath, { encoding: 'utf8', }); this.addDependency(tailwindTSModuleFilepath); demoModuleIDs.add(tailwindTSModuleID); extractImports(demos[demoName].rawTailwindTS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTSTailwind); } catch (error) { // tailwind TS demo doesn't exists } // Add plain CSS demo data const cssModuleID = moduleID.replace('/system/index.js', '/css/index.js'); try { // Add JS demo data const cssModuleFilepath = path.join( path.dirname(this.resourcePath), cssModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleCSS = cssModuleID; demos[demoName].rawCSS = await fs.readFile(cssModuleFilepath, { encoding: 'utf8', }); this.addDependency(cssModuleFilepath); demoModuleIDs.add(cssModuleID); extractImports(demos[demoName].rawCSS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleCSS); } catch (error) { // plain css js demo doesn't exists } try { // Add TS demo data const cssTSModuleID = cssModuleID.replace('.js', '.tsx'); const cssTSModuleFilepath = path.join( path.dirname(this.resourcePath), cssTSModuleID.replace(/\//g, path.sep), ); demos[demoName].moduleTSCSS = cssTSModuleID; demos[demoName].rawCSSTS = await fs.readFile(cssTSModuleFilepath, { encoding: 'utf8', }); this.addDependency(cssTSModuleFilepath); demoModuleIDs.add(cssTSModuleID); extractImports(demos[demoName].rawCSSTS).forEach((importModuleID) => importedModuleIDs.add(importModuleID), ); demoModuleIDs.add(demos[demoName].moduleTSCSS); } catch (error) { // plain css demo doesn't exists } // Tailwind preview try { const tailwindPreviewFilepath = moduleFilepath.replace( `${path.sep}system${path.sep}index.js`, `${path.sep}tailwind${path.sep}index.tsx.preview`, ); const tailwindJsxPreview = await fs.readFile(tailwindPreviewFilepath, { encoding: 'utf8', }); this.addDependency(tailwindPreviewFilepath); demos[demoName].tailwindJsxPreview = tailwindJsxPreview; } catch (error) { // No preview exists. This is fine. } // CSS preview try { const cssPreviewFilepath = moduleFilepath.replace( `${path.sep}system${path.sep}index.js`, `${path.sep}css${path.sep}index.tsx.preview`, ); const cssJsxPreview = await fs.readFile(cssPreviewFilepath, { encoding: 'utf8', }); this.addDependency(cssPreviewFilepath); demos[demoName].cssJsxPreview = cssJsxPreview; } catch (error) { // No preview exists. This is fine. } } try { const previewFilepath = moduleFilepath.replace(/\.js$/, '.tsx.preview'); const jsxPreview = await fs.readFile(previewFilepath, { encoding: 'utf8' }); this.addDependency(previewFilepath); demos[demoName].jsxPreview = jsxPreview; } catch (error) { // No preview exists. This is fine. } try { const moduleTS = moduleID.replace(/\.js$/, '.tsx'); const moduleTSFilepath = path.join( path.dirname(this.resourcePath), moduleTS.replace(/\//g, path.sep), ); this.addDependency(moduleTSFilepath); const rawTS = await fs.readFile(moduleTSFilepath, { encoding: 'utf8' }); // In development devs can choose whether they want to work on the TS or JS version. // But this leads to building both demo version i.e. more build time. demos[demoName].moduleTS = this.mode === 'production' ? moduleID : moduleTS; demos[demoName].rawTS = rawTS; demoModuleIDs.add(demos[demoName].moduleTS); } catch (error) { // TS version of the demo doesn't exist. This is fine. } }), ); const componentNames = Array.from( new Set( docs.en.rendered .filter((markdownOrComponentConfig) => { return ( typeof markdownOrComponentConfig !== 'string' && markdownOrComponentConfig.component ); }) .map((componentConfig) => { return componentConfig.component; }), ), ); componentNames.forEach((componentName) => { const moduleID = path.join(this.rootContext, 'src', componentName).replace(/\\/g, '/'); components[moduleID] = componentName; componentModuleIDs.add(moduleID); }); const transformed = ` ${Array.from(importedModuleIDs) .map((moduleID) => { return `import * as ${moduleIDToJSIdentifier( moduleID.replace('@', '$'), )} from '${moduleID}';`; }) .join('\n')} ${Array.from(demoModuleIDs) .map((moduleID) => { return `import ${moduleIDToJSIdentifier(moduleID)} from '${moduleID}';`; }) .join('\n')} ${Array.from(componentModuleIDs) .map((moduleID) => { return `import ${moduleIDToJSIdentifier(moduleID)} from '${moduleID}';`; }) .join('\n')} export const docs = ${JSON.stringify(docs, null, 2)}; export const demos = ${JSON.stringify(demos, null, 2)}; demos.scope = { process: {}, import: { ${Array.from(importedModuleIDs) .map((moduleID) => ` "${moduleID}": ${moduleIDToJSIdentifier(moduleID.replace('@', '$'))},`) .join('\n')} }, }; export const demoComponents = { ${Array.from(demoModuleIDs) .map((moduleID) => { return ` "${moduleID}": ${moduleIDToJSIdentifier(moduleID)},`; }) .join('\n')} }; export const srcComponents = { ${Array.from(componentModuleIDs) .map((moduleID) => { return ` "${components[moduleID]}": ${moduleIDToJSIdentifier(moduleID)},`; }) .join('\n')} }; `; return transformed; };
6,083
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/package.json
{ "name": "@mui/markdown", "version": "5.0.0", "private": true, "main": "./index.js", "types": "./index.d.ts", "exports": { ".": "./index.js", "./loader": "./loader.js", "./prism": "./prism.js" }, "dependencies": { "@babel/runtime": "^7.23.2", "lodash": "^4.17.21", "marked": "^5.1.2", "prismjs": "^1.29.0" }, "devDependencies": { "@types/chai": "^4.3.10", "chai": "^4.3.10" } }
6,084
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/parseMarkdown.js
const { marked } = require('marked'); const textToHash = require('./textToHash'); const prism = require('./prism'); /** * Option used by `marked` the library parsing markdown. */ const markedOptions = { gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: true, smartypants: false, headerPrefix: false, headerIds: false, mangle: false, }; const headerRegExp = /---[\r\n]([\s\S]*)[\r\n]---/; const titleRegExp = /# (.*)[\r\n]/; const descriptionRegExp = /<p class="description">(.*?)<\/p>/s; const headerKeyValueRegExp = /(.*?):[\r\n]?\s+(\[[^\]]+\]|.*)/g; const emptyRegExp = /^\s*$/; /** * Same as https://github.com/markedjs/marked/blob/master/src/helpers.js * Need to duplicate because `marked` does not export `escape` function */ const escapeTest = /[&<>"']/; const escapeReplace = /[&<>"']/g; const escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/; const escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; const escapeReplacements = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', }; const getEscapeReplacement = (ch) => escapeReplacements[ch]; function escape(html, encode) { if (encode) { if (escapeTest.test(html)) { return html.replace(escapeReplace, getEscapeReplacement); } } else if (escapeTestNoEncode.test(html)) { return html.replace(escapeReplaceNoEncode, getEscapeReplacement); } return html; } function checkUrlHealth(href, linkText, context) { const url = new URL(href, 'https://mui.com/'); if (/\/{2,}$/.test(url.pathname)) { throw new Error( [ 'docs-infra: Duplicated trailing slashes. The following link:', `[${linkText}](${href}) in ${context.location} has duplicated trailing slashes, please only add one.`, '', 'See https://ahrefs.com/blog/trailing-slash/ for more details.', '', ].join('\n'), ); } // External links to MUI, ignore if (url.host !== 'mui.com') { return; } /** * Break for links like: * /material-ui/customization/theming * * It needs to be: * /material-ui/customization/theming/ */ if (url.pathname[url.pathname.length - 1] !== '/') { throw new Error( [ 'docs-infra: Missing trailing slash. The following link:', `[${linkText}](${href}) in ${context.location} is missing a trailing slash, please add it.`, '', 'See https://ahrefs.com/blog/trailing-slash/ for more details.', '', ].join('\n'), ); } // Relative links if (href[0] !== '#' && !(href.startsWith('https://') || href.startsWith('http://'))) { /** * Break for links like: * material-ui/customization/theming/ * * It needs to be: * /material-ui/customization/theming/ */ if (href[0] !== '/') { throw new Error( [ 'docs-infra: Missing leading slash. The following link:', `[${linkText}](${href}) in ${context.location} is missing a leading slash, please add it.`, '', ].join('\n'), ); } } } /** * Extract information from the top of the markdown. * For instance, the following input: * * --- * title: Backdrop React Component * components: Backdrop * --- * * # Backdrop * * should output: * { title: 'Backdrop React Component', components: ['Backdrop'] } */ function getHeaders(markdown) { let header = markdown.match(headerRegExp); if (!header) { return { components: [], }; } header = header[1]; try { let regexMatches; const headers = {}; // eslint-disable-next-line no-cond-assign while ((regexMatches = headerKeyValueRegExp.exec(header)) !== null) { const key = regexMatches[1]; let value = regexMatches[2].replace(/(.*)/, '$1'); if (value[0] === '[') { // Need double quotes to JSON parse. value = value.replace(/'/g, '"'); // Remove the comma after the last value e.g. ["foo", "bar",] -> ["foo", "bar"]. value = value.replace(/,\s+\]$/g, ']'); headers[key] = JSON.parse(value); } else { // Remove trailing single quote yml escaping. headers[key] = value.replace(/^'|'$/g, ''); } } if (headers.components) { headers.components = headers.components .split(',') .map((x) => x.trim()) .sort(); } else { headers.components = []; } if (headers.hooks) { headers.hooks = headers.hooks .split(',') .map((x) => x.trim()) .sort(); } else { headers.hooks = []; } return headers; } catch (err) { throw new Error( `docs-infra: ${err.message} in getHeader(markdown) with markdown: \n\n${header}\n`, ); } } function getContents(markdown) { const rep = markdown .replace(headerRegExp, '') // Remove header information .split(/^{{("(?:demo|component)":.*)}}$/gm) // Split markdown into an array, separating demos .flatMap((text) => text.split(/^(<codeblock.*?<\/codeblock>)$/gmsu)) .filter((content) => !emptyRegExp.test(content)); // Remove empty lines return rep; } function getTitle(markdown) { const matches = markdown.match(titleRegExp); if (matches === null) { return ''; } return matches[1].replace(/`/g, ''); } function getDescription(markdown) { const matches = markdown.match(descriptionRegExp); if (matches === null) { return undefined; } return matches[1].trim().replace(/`/g, ''); } function getCodeblock(content) { if (content.startsWith('<codeblock')) { const storageKey = content.match(/^<codeblock [^>]*storageKey=["|'](\S*)["|'].*>/m)?.[1]; const blocks = [...content.matchAll(/^```(\S*) (\S*)\n(.*?)\n```/gmsu)].map( ([, language, tab, code]) => ({ language, tab, code }), ); const blocksData = blocks.filter( (block) => block.tab !== undefined && !emptyRegExp.test(block.code), ); return { type: 'codeblock', data: blocksData, storageKey, }; } return undefined; } /** * @param {string} markdown */ function renderMarkdown(markdown) { // Check if the markdown contains an inline list. Unordered lists are block elements and cannot be parsed inline. if (/[-*+] `([A-Za-z]+)`/g.test(markdown)) { return marked.parse(markdown, markedOptions); } // Two new lines result in a newline in the table. // All other new lines must be eliminated to prevent markdown mayhem. return marked .parseInline(markdown, markedOptions) .replace(/(\r?\n){2}/g, '<br>') .replace(/\r?\n/g, ' '); } // Help rank mui.com on component searches first. const noSEOadvantage = [ 'https://m2.material.io/', 'https://m3.material.io/', 'https://material.io/', 'https://getbootstrap.com/', 'https://icons.getbootstrap.com/', 'https://pictogrammers.com/', 'https://www.w3.org/', 'https://tailwindcss.com/', 'https://heroicons.com/', 'https://react-icons.github.io/', 'https://fontawesome.com/', 'https://www.radix-ui.com/', 'https://react-spectrum.adobe.com/', 'https://headlessui.com/', ]; /** * Creates a function that MUST be used to render non-inline markdown. * It keeps track of a table of contents and hashes of its items. * This is important to create anchors that are invariant between languages. * * @typedef {object} TableOfContentsEntry * @property {TableOfContentsEntry[]} children * @property {string} hash * @property {number} level * @property {string} text * @param {object} context * @param {Record<string, string>} context.headingHashes - WILL BE MUTATED * @param {TableOfContentsEntry[]} context.toc - WILL BE MUTATED * @param {string} context.userLanguage * @param {object} context.options */ function createRender(context) { const { headingHashes, toc, userLanguage, options } = context; const headingHashesFallbackTranslated = {}; let headingIndex = -1; /** * @param {string} markdown */ function render(markdown) { const renderer = new marked.Renderer(); renderer.heading = (headingHtml, level) => { // Main title, no need for an anchor. // It adds noises to the URL. // // Small title, no need for an anchor. // It reduces the risk of duplicated id and it's fewer elements in the DOM. if (level === 1 || level >= 4) { return `<h${level}>${headingHtml}</h${level}>`; } // Remove links to avoid nested links in the TOCs let headingText = headingHtml.replace(/<a\b[^>]*>/gi, '').replace(/<\/a>/gi, ''); // Remove `code` tags headingText = headingText.replace(/<code\b[^>]*>/gi, '').replace(/<\/code>/gi, ''); // Standardizes the hash from the default location (en) to different locations // Need english.md file parsed first let hash; if (userLanguage === 'en') { hash = textToHash(headingText, headingHashes); } else { headingIndex += 1; hash = Object.keys(headingHashes)[headingIndex]; if (!hash) { hash = textToHash(headingText, headingHashesFallbackTranslated); } } // enable splitting of long words from function name + first arg name // Closing parens are less interesting since this would only allow breaking one character earlier. // Applying the same mechanism would also allow breaking of non-function signatures like "Community help (free)". // To detect that we enabled breaking of open/closing parens we'd need a context-sensitive parser. const displayText = headingText.replace(/([^\s]\()/g, '$1&#8203;'); // create a nested structure with 2 levels starting with level 2 e.g. // [{...level2, children: [level3, level3, level3]}, level2] if (level === 2) { toc.push({ text: displayText, level, hash, children: [], }); } else if (level === 3) { if (!toc[toc.length - 1]) { throw new Error(`docs-infra: Missing parent level for: ${headingText}\n`); } toc[toc.length - 1].children.push({ text: displayText, level, hash, }); } return [ `<h${level} id="${hash}">`, headingHtml, `<a aria-labelledby="${hash}" class="anchor-link" href="#${hash}" tabindex="-1">`, '<svg><use xlink:href="#anchor-link-icon" /></svg>', '</a>', `<button title="Post a comment" class="comment-link" data-feedback-hash="${hash}">`, '<svg><use xlink:href="#comment-link-icon" /></svg>', `</button>`, `</h${level}>`, ].join(''); }; renderer.link = (href, linkTitle, linkText) => { let more = ''; if (linkTitle) { more += ` title="${linkTitle}"`; } if (noSEOadvantage.some((domain) => href.indexOf(domain) !== -1)) { more = ' target="_blank" rel="noopener nofollow"'; } let finalHref = href; checkUrlHealth(href, linkText, context); if (userLanguage !== 'en' && href.indexOf('/') === 0 && !options.ignoreLanguagePages(href)) { finalHref = `/${userLanguage}${href}`; } // This logic turns link like: // https://github.com/mui/material-ui/blob/-/packages/mui-joy/src/styles/components.d.ts // into a permalink: // https://github.com/mui/material-ui/blob/v5.11.15/packages/mui-joy/src/styles/components.d.ts if (finalHref.startsWith(`${options.env.SOURCE_CODE_REPO}/blob/-/`)) { finalHref = finalHref.replace( `${options.env.SOURCE_CODE_REPO}/blob/-/`, `${options.env.SOURCE_CODE_REPO}/blob/v${options.env.LIB_VERSION}/`, ); } return `<a href="${finalHref}"${more}>${linkText}</a>`; }; renderer.code = (code, infostring, escaped) => { // https://github.com/markedjs/marked/blob/30e90e5175700890e6feb1836c57b9404c854466/src/Renderer.js#L15 const lang = (infostring || '').match(/\S*/)[0]; const out = prism(code, lang); if (out != null && out !== code) { escaped = true; code = out; } code = `${code.replace(/\n$/, '')}\n`; if (!lang) { return `<pre><code>${escaped ? code : escape(code, true)}</code></pre>\n`; } return `<div class="MuiCode-root"><pre><code class="language-${escape(lang, true)}">${ escaped ? code : escape(code, true) }</code></pre>${[ '<button data-ga-event-category="code" data-ga-event-action="copy-click" aria-label="Copy the code" class="MuiCode-copy">', '<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="ContentCopyRoundedIcon">', '<use class="MuiCode-copy-icon" xlink:href="#copy-icon" />', '<use class="MuiCode-copied-icon" xlink:href="#copied-icon" />', '</svg>', '<span class="MuiCode-copyKeypress"><span>(or</span> $keyC<span>)</span></span></button></div>', ].join('')}\n`; }; marked.use({ extensions: [ { name: 'callout', level: 'block', start(src) { const match = src.match(/:::/); return match ? match.index : undefined; }, tokenizer(src) { const rule = /^ {0,3}(:{3,}(?=[^:\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~:]* *(?=\n|$)|$)/; const match = rule.exec(src); if (match) { const token = { type: 'callout', raw: match[0], text: match[3].trim(), severity: match[2], tokens: [], }; this.lexer.blockTokens(token.text, token.tokens); return token; } return undefined; }, renderer(token) { return `<aside class="MuiCallout-root MuiCallout-${token.severity}"> ${ ['info', 'success', 'warning', 'error'].includes(token.severity) ? [ '<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="ContentCopyRoundedIcon">', `<use class="MuiCode-copied-icon" xlink:href="#${token.severity}-icon" />`, '</svg>', ].join('\n') : '' } <div class="MuiCallout-content"> ${this.parser.parse(token.tokens)}\n</div></aside>`; }, }, ], }); return marked(markdown, { ...markedOptions, renderer }); } return render; } module.exports = { createRender, getContents, getDescription, getCodeblock, getHeaders, getTitle, renderMarkdown, };
6,085
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/parseMarkdown.test.js
import { expect } from 'chai'; import { getContents, getDescription, getTitle, getHeaders, getCodeblock, renderMarkdown, createRender, } from './parseMarkdown'; describe('parseMarkdown', () => { describe('getTitle', () => { it('remove backticks', () => { expect( getTitle(` # \`@mui/styled-engine\` <p class="description">Configuring your preferred styling library.</p> `), ).to.equal('@mui/styled-engine'); }); }); describe('getDescription', () => { it('trims the description', () => { expect( getDescription(` <p class="description"> Some description </p> `), ).to.equal('Some description'); }); it('remove backticks', () => { expect( getDescription(` <p class="description"> Some \`description\` </p> `), ).to.equal('Some description'); }); it('should not be greedy', () => { expect( getDescription(` <p class="description"> Some description </p> ## Foo <p>bar</p> `), ).to.equal('Some description'); }); }); describe('getHeaders', () => { it('should return a correct result', () => { expect( getHeaders(` --- title: React Alert component components: Alert, AlertTitle hooks: useAlert githubLabel: 'component: alert' packageName: '@mui/lab' waiAria: https://www.w3.org/TR/wai-aria-practices/#alert authors: ['foo', 'bar'] --- `), ).to.deep.equal({ components: ['Alert', 'AlertTitle'], hooks: ['useAlert'], githubLabel: 'component: alert', packageName: '@mui/lab', title: 'React Alert component', waiAria: 'https://www.w3.org/TR/wai-aria-practices/#alert', authors: ['foo', 'bar'], }); }); it('should work with authors broken in two lines', () => { expect( getHeaders(` --- title: React Alert component components: Alert, AlertTitle githubLabel: 'component: alert' packageName: '@mui/lab' waiAria: https://www.w3.org/TR/wai-aria-practices/#alert authors: ['foo', 'bar'] --- `), ).to.deep.equal({ components: ['Alert', 'AlertTitle'], hooks: [], githubLabel: 'component: alert', packageName: '@mui/lab', title: 'React Alert component', waiAria: 'https://www.w3.org/TR/wai-aria-practices/#alert', authors: ['foo', 'bar'], }); }); it('should work with one author per line', () => { expect( getHeaders(` --- title: React Alert component components: Alert, AlertTitle githubLabel: 'component: alert' packageName: '@mui/lab' waiAria: https://www.w3.org/TR/wai-aria-practices/#alert authors: [ 'foo', 'bar', ] --- `), ).to.deep.equal({ components: ['Alert', 'AlertTitle'], hooks: [], githubLabel: 'component: alert', packageName: '@mui/lab', title: 'React Alert component', waiAria: 'https://www.w3.org/TR/wai-aria-practices/#alert', authors: ['foo', 'bar'], }); }); }); describe('getContents', () => { describe('Split markdown into an array, separating demos', () => { it('returns a single entry without a demo', () => { expect(getContents('# SomeGuide\nwhich has no demo')).to.deep.equal([ '# SomeGuide\nwhich has no demo', ]); }); it('uses a `{{"demo"` marker to split', () => { expect( getContents('# SomeGuide\n{{"demo": "GuideDemo.js" }}\n## NextHeading'), ).to.deep.equal(['# SomeGuide\n', '"demo": "GuideDemo.js" ', '\n## NextHeading']); }); it('ignores possible code', () => { expect(getContents('# SomeGuide\n```jsx\n<Button props={{\nfoo: 1\n}}')).to.deep.equal([ '# SomeGuide\n```jsx\n<Button props={{\nfoo: 1\n}}', ]); }); }); describe('Split markdown into an array, separating codeblocks', () => { it('uses a `<codeblock>` tag to split', () => { expect( getContents( [ '## Tabs', '', '<codeblock storageKey="package-manager">', '', '```bash npm', 'npm install @mui/material @emotion/react @emotion/styled', '```', '', '```bash yarn', 'yarn add @mui/material @emotion/react @emotion/styled', '```', '', '</codeblock>', ].join('\n'), ), ).to.deep.equal([ '## Tabs\n\n', [ '<codeblock storageKey="package-manager">', '', '```bash npm', 'npm install @mui/material @emotion/react @emotion/styled', '```', '', '```bash yarn', 'yarn add @mui/material @emotion/react @emotion/styled', '```', '', '</codeblock>', ].join('\n'), ]); }); }); }); describe('getCodeblock', () => { it('should return undefined if no codeblock found', () => { const codeblock = getCodeblock('## Tabs'); expect(codeblock).to.equal(undefined); }); it('should return the codeblock', () => { const codeblock = getCodeblock( [ '<codeblock storageKey="package-manager">', '', '```bash npm', 'npm install @mui/material @emotion/react @emotion/styled', '# `@emotion/react` and `@emotion/styled` are peer dependencies', '```', '', '```sh yarn', 'yarn add @mui/material @emotion/react @emotion/styled', '# `@emotion/react` and `@emotion/styled` are peer dependencies', '```', '', '</codeblock>', ].join('\n'), ); expect(codeblock).to.deep.equal({ type: 'codeblock', storageKey: 'package-manager', data: [ { language: 'bash', tab: 'npm', code: [ 'npm install @mui/material @emotion/react @emotion/styled', '# `@emotion/react` and `@emotion/styled` are peer dependencies', ].join('\n'), }, { language: 'sh', tab: 'yarn', code: [ 'yarn add @mui/material @emotion/react @emotion/styled', '# `@emotion/react` and `@emotion/styled` are peer dependencies', ].join('\n'), }, ], }); }); }); describe('renderMarkdown', () => { it('should render markdown lists correctly', () => { expect( renderMarkdown( [ 'The track presentation:', '- `normal` the track will render a bar representing the slider value.', '- `inverted` the track will render a bar representing the remaining slider value.', '- `false` the track will render without a bar.', ].join('\n'), ), ).to.equal( [ '<p>The track presentation:</p>', '<ul>', '<li><code>normal</code> the track will render a bar representing the slider value.</li>', '<li><code>inverted</code> the track will render a bar representing the remaining slider value.</li>', '<li><code>false</code> the track will render without a bar.</li>', '</ul>', '', ].join('\n'), ); }); it('should render inline descriptions correctly', () => { expect( renderMarkdown( 'Allows to control whether the dropdown is open. This is a controlled counterpart of `defaultOpen`.', ), ).to.equal( 'Allows to control whether the dropdown is open. This is a controlled counterpart of <code>defaultOpen</code>.', ); }); }); describe('createRender', () => { it('should collect headers correctly', () => { const context = { toc: [], headingHashes: {} }; const render = createRender(context); expect( render( [ '# Accordion', '## Basic features 🧪', '## Using `slots` and `slotProps`', '### Specific example', ].join('\n'), ), ).to.equal( [ `<h1>Accordion</h1>`, `<h2 id="basic-features">Basic features 🧪<a aria-labelledby="basic-features" class="anchor-link" href="#basic-features" tabindex="-1"><svg><use xlink:href="#anchor-link-icon" /></svg></a><button title="Post a comment" class="comment-link" data-feedback-hash="basic-features"><svg><use xlink:href="#comment-link-icon" /></svg></button></h2>`, `<h2 id="using-slots-and-slotprops">Using <code>slots</code> and <code>slotProps</code><a aria-labelledby="using-slots-and-slotprops" class="anchor-link" href="#using-slots-and-slotprops" tabindex="-1"><svg><use xlink:href="#anchor-link-icon" /></svg></a><button title="Post a comment" class="comment-link" data-feedback-hash="using-slots-and-slotprops"><svg><use xlink:href="#comment-link-icon" /></svg></button></h2>`, `<h3 id="specific-example">Specific example<a aria-labelledby="specific-example" class="anchor-link" href="#specific-example" tabindex="-1"><svg><use xlink:href="#anchor-link-icon" /></svg></a><button title="Post a comment" class="comment-link" data-feedback-hash="specific-example"><svg><use xlink:href="#comment-link-icon" /></svg></button></h3>`, ].join(''), ); expect(context.toc).to.deep.equal([ { children: [], hash: 'basic-features', level: 2, text: 'Basic features 🧪', }, { children: [ { hash: 'specific-example', level: 3, text: 'Specific example', }, ], hash: 'using-slots-and-slotprops', level: 2, text: 'Using slots and slotProps', }, ]); }); }); });
6,086
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/prepareMarkdown.js
const fs = require('fs'); const path = require('path'); const kebabCase = require('lodash/kebabCase'); const { createRender, getContents, getDescription, getCodeblock, getHeaders, getTitle, } = require('./parseMarkdown'); const BaseUIReexportedComponents = ['ClickAwayListener', 'NoSsr', 'Portal', 'TextareaAutosize']; /** * @param {string} productId * @example 'material' * @param {string} componentPkg * @example 'mui-base' * @param {string} component * @example 'Button' * @returns {string} */ function resolveComponentApiUrl(productId, componentPkg, component) { if (!productId) { return `/api/${kebabCase(component)}/`; } if (productId === 'x-date-pickers') { return `/x/api/date-pickers/${kebabCase(component)}/`; } if (productId === 'x-charts') { return `/x/api/charts/${kebabCase(component)}/`; } if (productId === 'x-tree-view') { return `/x/api/tree-view/${kebabCase(component)}/`; } if (componentPkg === 'mui-base' || BaseUIReexportedComponents.indexOf(component) >= 0) { return `/base-ui/react-${kebabCase(component)}/components-api/#${kebabCase(component)}`; } return `/${productId}/api/${kebabCase(component)}/`; } /** * @param {object} config * @param {Array<{ markdown: string, filename: string, userLanguage: string }>} config.translations - Mapping of locale to its markdown * @param {string} config.fileRelativeContext - posix filename relative to repository root directory * @param {object} config.options - provided to the webpack loader */ function prepareMarkdown(config) { const { fileRelativeContext, translations, componentPackageMapping = {}, options } = config; const demos = {}; /** * @type {Record<string, { rendered: Array<string | { component: string } | { demo:string }> }>} */ const docs = {}; const headingHashes = {}; translations // Process the English markdown before the other locales. // English ToC anchor links are used in all languages .sort((a) => (a.userLanguage === 'en' ? -1 : 1)) .forEach((translation) => { const { filename, markdown, userLanguage } = translation; const headers = getHeaders(markdown); const location = headers.filename || `/${fileRelativeContext}/${filename}`; const title = headers.title || getTitle(markdown); const description = headers.description || getDescription(markdown); if (title == null || title === '') { throw new Error(`docs-infra: Missing title in the page: ${location}\n`); } if (title.length > 70) { throw new Error( [ `docs-infra: The title "${title}" is too long (${title.length} characters).`, 'It needs to have fewer than 70 characters—ideally less than 60. For more details, see:', 'https://developers.google.com/search/docs/advanced/appearance/title-link', '', ].join('\n'), ); } if (description == null || description === '') { throw new Error(`docs-infra: Missing description in the page: ${location}\n`); } if (description.length > 170) { throw new Error( [ `docs-infra: The description "${description}" is too long (${description.length} characters).`, 'It needs to have fewer than 170 characters—ideally less than 160. For more details, see:', 'https://ahrefs.com/blog/meta-description/#4-be-concise', '', ].join('\n'), ); } const contents = getContents(markdown); if (headers.unstyled) { contents.push(` ## Unstyled :::success [Base UI](/base-ui/) provides a headless ("unstyled") version of this [${title}](${headers.unstyled}). Try it if you need more flexibility in customization and a smaller bundle size. ::: `); } if (headers.components.length > 0) { contents.push(` ## API See the documentation below for a complete reference to all of the props and classes available to the components mentioned here. ${headers.components .map((component) => { const componentPkgMap = componentPackageMapping[headers.productId]; const componentPkg = componentPkgMap ? componentPkgMap[component] : null; return `- [\`<${component} />\`](${resolveComponentApiUrl( headers.productId, componentPkg, component, )})`; }) .join('\n')} ${headers.hooks .map((hook) => { const componentPkgMap = componentPackageMapping[headers.productId]; const componentPkg = componentPkgMap ? componentPkgMap[hook] : null; return `- [\`${hook}\`](${resolveComponentApiUrl(headers.productId, componentPkg, hook)})`; }) .join('\n')} `); } const toc = []; const render = createRender({ headingHashes, toc, userLanguage, location, options, }); const rendered = contents.map((content) => { if (/^"(demo|component)": "(.*)"/.test(content)) { try { return JSON.parse(`{${content}}`); } catch (err) { console.error('JSON.parse fails with: ', `{${content}}`); console.error(err); return null; } } const codeblock = getCodeblock(content); if (codeblock) { return codeblock; } return render(content); }); // fragment link symbol rendered.unshift( `<svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="comment-link-icon" viewBox="0 0 24 24"> <path d="M5.025 14H6.95c.183 0 .35-.029.5-.087a1.24 1.24 0 0 0 .425-.288L13.65 7.9a.622.622 0 0 0 .2-.45.622.622 0 0 0-.2-.45l-2.3-2.3a.622.622 0 0 0-.45-.2.622.622 0 0 0-.45.2l-5.725 5.775a1.24 1.24 0 0 0-.287.425 1.37 1.37 0 0 0-.088.5v1.925c0 .184.067.342.2.475a.65.65 0 0 0 .475.2Zm5.325 0h5.725c.367 0 .68-.129.938-.387.258-.258.387-.57.387-.938 0-.366-.13-.679-.387-.937a1.277 1.277 0 0 0-.938-.388H13L10.35 14Zm-5.5 4.4-2.4 2.4c-.417.417-.896.509-1.437.275C.47 20.842.2 20.434.2 19.85V3.55c0-.733.258-1.358.775-1.875A2.554 2.554 0 0 1 2.85.9h16.3c.733 0 1.358.259 1.875.775.517.517.775 1.142.775 1.875v12.2c0 .734-.258 1.359-.775 1.875a2.554 2.554 0 0 1-1.875.775H4.85Z"/> </symbol> </svg>`, ); rendered.unshift( `<svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="anchor-link-icon" viewBox="0 0 12 6"> <path d="M8.9176 0.083252H7.1676C6.84677 0.083252 6.58427 0.345752 6.58427 0.666585C6.58427 0.987419 6.84677 1.24992 7.1676 1.24992H8.9176C9.8801 1.24992 10.6676 2.03742 10.6676 2.99992C10.6676 3.96242 9.8801 4.74992 8.9176 4.74992H7.1676C6.84677 4.74992 6.58427 5.01242 6.58427 5.33325C6.58427 5.65409 6.84677 5.91659 7.1676 5.91659H8.9176C10.5276 5.91659 11.8343 4.60992 11.8343 2.99992C11.8343 1.38992 10.5276 0.083252 8.9176 0.083252ZM3.6676 2.99992C3.6676 3.32075 3.9301 3.58325 4.25094 3.58325H7.75094C8.07177 3.58325 8.33427 3.32075 8.33427 2.99992C8.33427 2.67909 8.07177 2.41659 7.75094 2.41659H4.25094C3.9301 2.41659 3.6676 2.67909 3.6676 2.99992ZM4.83427 4.74992H3.08427C2.12177 4.74992 1.33427 3.96242 1.33427 2.99992C1.33427 2.03742 2.12177 1.24992 3.08427 1.24992H4.83427C5.1551 1.24992 5.4176 0.987419 5.4176 0.666585C5.4176 0.345752 5.1551 0.083252 4.83427 0.083252H3.08427C1.47427 0.083252 0.167603 1.38992 0.167603 2.99992C0.167603 4.60992 1.47427 5.91659 3.08427 5.91659H4.83427C5.1551 5.91659 5.4176 5.65409 5.4176 5.33325C5.4176 5.01242 5.1551 4.74992 4.83427 4.74992Z" /> </symbol> </svg>`, ); rendered.unshift( `<svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="copy-icon" viewBox="0 0 24 24"> <path d="M15 20H5V7c0-.55-.45-1-1-1s-1 .45-1 1v13c0 1.1.9 2 2 2h10c.55 0 1-.45 1-1s-.45-1-1-1zm5-4V4c0-1.1-.9-2-2-2H9c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h9c1.1 0 2-.9 2-2zm-2 0H9V4h9v12z" /> +</symbol> </svg>`, ); rendered.unshift(` <svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="copied-icon" viewBox="0 0 24 24"> <path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.24 11.28L9.69 11.2c-.38-.39-.38-1.01 0-1.4.39-.39 1.02-.39 1.41 0l1.36 1.37 4.42-4.46c.39-.39 1.02-.39 1.41 0 .38.39.38 1.01 0 1.4l-5.13 5.17c-.37.4-1.01.4-1.4 0zM3 6c-.55 0-1 .45-1 1v13c0 1.1.9 2 2 2h13c.55 0 1-.45 1-1s-.45-1-1-1H5c-.55 0-1-.45-1-1V7c0-.55-.45-1-1-1z" /> </symbol> </svg>`); // icons for callout (info, success, warning, error) rendered.unshift( `<svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="info-icon" viewBox="0 0 20 20"> <path d="M9.996 14c.21 0 .39-.072.535-.216a.72.72 0 0 0 .219-.534v-3.5a.728.728 0 0 0-.214-.534.72.72 0 0 0-.532-.216.734.734 0 0 0-.535.216.72.72 0 0 0-.219.534v3.5c0 .213.071.39.214.534a.72.72 0 0 0 .532.216Zm0-6.5c.21 0 .39-.071.535-.214a.714.714 0 0 0 .219-.532.736.736 0 0 0-.214-.535.714.714 0 0 0-.532-.219.736.736 0 0 0-.535.214.714.714 0 0 0-.219.532c0 .21.071.39.214.535.143.146.32.219.532.219Zm.01 10.5a7.81 7.81 0 0 1-3.11-.625 8.065 8.065 0 0 1-2.552-1.719 8.066 8.066 0 0 1-1.719-2.551A7.818 7.818 0 0 1 2 9.99c0-1.104.208-2.14.625-3.105a8.066 8.066 0 0 1 4.27-4.26A7.818 7.818 0 0 1 10.009 2a7.75 7.75 0 0 1 3.106.625 8.083 8.083 0 0 1 4.26 4.265A7.77 7.77 0 0 1 18 9.994a7.81 7.81 0 0 1-.625 3.11 8.066 8.066 0 0 1-1.719 2.552 8.083 8.083 0 0 1-2.546 1.719 7.77 7.77 0 0 1-3.104.625Z"/> </symbol> </svg>`, ); rendered.unshift( `<svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="success-icon" viewBox="0 0 20 20"> <path d="m8.938 10.875-1.25-1.23a.718.718 0 0 0-.521-.228.718.718 0 0 0-.521.229.73.73 0 0 0 0 1.062l1.77 1.771c.153.153.327.23.521.23a.718.718 0 0 0 .521-.23l3.896-3.896a.73.73 0 0 0 0-1.062.718.718 0 0 0-.52-.23.718.718 0 0 0-.521.23l-3.376 3.354ZM10 18a7.796 7.796 0 0 1-3.104-.625 8.065 8.065 0 0 1-2.552-1.719 8.064 8.064 0 0 1-1.719-2.552A7.797 7.797 0 0 1 2 10c0-1.111.208-2.15.625-3.115a8.064 8.064 0 0 1 4.27-4.26A7.797 7.797 0 0 1 10 2c1.111 0 2.15.208 3.115.625a8.096 8.096 0 0 1 4.26 4.26C17.792 7.851 18 8.89 18 10a7.797 7.797 0 0 1-.625 3.104 8.066 8.066 0 0 1-4.26 4.271A7.774 7.774 0 0 1 10 18Z"/> </symbol> </svg>`, ); rendered.unshift( `<svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="warning-icon" viewBox="0 0 20 20"> <path d="M2.33 17a.735.735 0 0 1-.665-.375.631.631 0 0 1-.094-.375.898.898 0 0 1 .115-.396L9.353 3.062a.621.621 0 0 1 .281-.27.85.85 0 0 1 .729 0 .622.622 0 0 1 .281.27l7.667 12.792c.07.125.108.257.114.396a.63.63 0 0 1-.093.375.842.842 0 0 1-.271.27.728.728 0 0 1-.394.105H2.33Zm7.664-2.5c.211 0 .39-.072.536-.214a.714.714 0 0 0 .218-.532.736.736 0 0 0-.214-.535.714.714 0 0 0-.531-.22.736.736 0 0 0-.536.215.714.714 0 0 0-.219.531c0 .212.072.39.215.536.143.146.32.219.531.219Zm0-2.5c.211 0 .39-.072.536-.216a.72.72 0 0 0 .218-.534v-2.5a.728.728 0 0 0-.214-.534.72.72 0 0 0-.531-.216.734.734 0 0 0-.536.216.72.72 0 0 0-.219.534v2.5c0 .212.072.39.215.534a.72.72 0 0 0 .531.216Z"/> </symbol> </svg>`, ); rendered.unshift( `<svg style="display: none;" xmlns="http://www.w3.org/2000/svg"> <symbol id="error-icon" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M2 7.4v5.2a2 2 0 0 0 .586 1.414l3.4 3.4A2 2 0 0 0 7.4 18h5.2a2 2 0 0 0 1.414-.586l3.4-3.4A2 2 0 0 0 18 12.6V7.4a2 2 0 0 0-.586-1.414l-3.4-3.4A2 2 0 0 0 12.6 2H7.4a2 2 0 0 0-1.414.586l-3.4 3.4A2 2 0 0 0 2 7.4Zm11.03-.43a.75.75 0 0 1 0 1.06L11.06 10l1.97 1.97a.75.75 0 1 1-1.06 1.06L10 11.06l-1.97 1.97a.75.75 0 0 1-1.06-1.06L8.94 10 6.97 8.03a.75.75 0 0 1 1.06-1.06L10 8.94l1.97-1.97a.75.75 0 0 1 1.06 0Z" clip-rule="evenodd"/> </symbol> </svg>`, ); docs[userLanguage] = { description, location, rendered, toc, title, headers, }; }); if (docs.en.headers.card === 'true') { const slug = docs.en.location.replace(/(.*)\/(.*)\.md/, '$2'); const exists = fs.existsSync( path.resolve(__dirname, `../../docs/public/static/blog/${slug}/card.png`), ); if (!exists) { throw new Error( [ `MUI: the card image for the blog post "${slug}" is missing.`, `Add a docs/public/static/blog/${slug}/card.png file and then restart Next.js or else remove card: true from the headers.`, ].join('\n'), ); } } return { demos, docs }; } module.exports = prepareMarkdown;
6,087
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/prepareMarkdown.test.js
import { expect } from 'chai'; import prepareMarkdown from './prepareMarkdown'; describe('prepareMarkdown', () => { const defaultParams = { fileRelativeContext: 'test/bar', options: { env: {}, }, }; it('returns the table of contents with html and emojis preserved and <a> tags stripped', () => { const markdown = ` # Support <p class="description">Foo</p> ## Community help (free) ### GitHub <img src="/static/images/logos/github.svg" width="24" height="24" alt="GitHub logo" loading="lazy" /> ### Unofficial 👍 ### Warning ⚠️ ### Header with Pro plan <a title="Pro plan" href="/x/introduction/licensing/#plan-pro"><span class="plan-pro"></span></a> ### Header with \`code\` `; const { docs: { en: { toc }, }, } = prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); expect(toc).to.have.deep.ordered.members([ { children: [ { hash: 'github', level: 3, text: 'GitHub <img src="/static/images/logos/github.svg" width="24" height="24" alt="GitHub logo" loading="lazy" />', }, { hash: 'unofficial', level: 3, text: 'Unofficial 👍' }, { hash: 'warning', level: 3, text: 'Warning ⚠️' }, { hash: 'header-with-pro-plan', level: 3, text: 'Header with Pro plan <span class="plan-pro"></span>', }, { hash: 'header-with-code', level: 3, text: 'Header with code', }, ], hash: 'community-help-free', level: 2, text: 'Community help (free)', }, ]); }); it('enables word-break for function signatures', () => { const markdown = ` # Theming <p class="description">Foo</p> ## API ### responsiveFontSizes(theme, options) => theme ### createTheme(options, ...args) => theme `; const { docs: { en: { toc }, }, } = prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); expect(toc).to.have.deep.ordered.members([ { children: [ { hash: 'responsivefontsizes-theme-options-theme', level: 3, text: 'responsiveFontSizes(&#8203;theme, options) =&gt; theme', }, { hash: 'createtheme-options-args-theme', level: 3, text: 'createTheme(&#8203;options, ...args) =&gt; theme', }, ], hash: 'api', level: 2, text: 'API', }, ]); }); it('use english hash for different locales', () => { const markdownEn = ` # Localization <p class="description">Foo</p> ## Locales ### Example ### Use same hash `; const markdownPt = ` # Localização <p class="description">Foo</p> ## Idiomas ### Exemplo ### Usar o mesmo hash `; const markdownZh = ` # 所在位置 <p class="description">Foo</p> ## 语言环境 ### 例 ### 使用相同的哈希 `; const { docs: { en: { toc: tocEn }, pt: { toc: tocPt }, zh: { toc: tocZh }, }, } = prepareMarkdown({ pageFilename: '/same-hash-test', translations: [ { filename: 'localization.md', markdown: markdownEn, userLanguage: 'en' }, { filename: 'localization-pt.md', markdown: markdownPt, userLanguage: 'pt' }, { filename: 'localization-zh.md', markdown: markdownZh, userLanguage: 'zh' }, ], }); expect(tocZh).to.have.deep.ordered.members([ { children: [ { hash: 'example', level: 3, text: '例', }, { hash: 'use-same-hash', level: 3, text: '使用相同的哈希', }, ], hash: 'locales', level: 2, text: '语言环境', }, ]); expect(tocPt).to.have.deep.ordered.members([ { children: [ { hash: 'example', level: 3, text: 'Exemplo', }, { hash: 'use-same-hash', level: 3, text: 'Usar o mesmo hash', }, ], hash: 'locales', level: 2, text: 'Idiomas', }, ]); expect(tocEn).to.have.deep.ordered.members([ { children: [ { hash: 'example', level: 3, text: 'Example', }, { hash: 'use-same-hash', level: 3, text: 'Use same hash', }, ], hash: 'locales', level: 2, text: 'Locales', }, ]); }); it('use translated hash for translations are not synced', () => { const markdownEn = ` # Localization <p class="description">Foo</p> ## Locales ### Example ### Use same hash `; const markdownPt = ` # Localização <p class="description">Foo</p> ## Idiomas ### Exemplo ### Usar o mesmo hash ### Usar traduzido `; const { docs: { en: { toc: tocEn }, pt: { toc: tocPt }, }, } = prepareMarkdown({ pageFilename: '/same-hash-test', translations: [ { filename: 'localization.md', markdown: markdownEn, userLanguage: 'en' }, { filename: 'localization-pt.md', markdown: markdownPt, userLanguage: 'pt' }, ], }); expect(tocPt).to.have.deep.ordered.members([ { children: [ { hash: 'example', level: 3, text: 'Exemplo', }, { hash: 'use-same-hash', level: 3, text: 'Usar o mesmo hash', }, { hash: 'usar-traduzido', level: 3, text: 'Usar traduzido', }, ], hash: 'locales', level: 2, text: 'Idiomas', }, ]); expect(tocEn).to.have.deep.ordered.members([ { children: [ { hash: 'example', level: 3, text: 'Example', }, { hash: 'use-same-hash', level: 3, text: 'Use same hash', }, ], hash: 'locales', level: 2, text: 'Locales', }, ]); }); it('should report missing trailing splashes', () => { const markdown = ` # Localization <p class="description">Foo</p> [bar](/bar/) [foo](/foo) `; expect(() => { prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); }).to.throw(`docs-infra: Missing trailing slash. The following link: [foo](/foo) in /test/bar/index.md is missing a trailing slash, please add it. See https://ahrefs.com/blog/trailing-slash/ for more details. `); }); it('should report missing leading splashes', () => { const markdown = ` # Localization <p class="description">Foo</p> [bar](/bar/) [foo](foo/) `; expect(() => { prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); }).to.throw(`docs-infra: Missing leading slash. The following link: [foo](foo/) in /test/bar/index.md is missing a leading slash, please add it. `); }); it('should report title too long', () => { const markdown = ` # Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo <p class="description">Foo</p> `; expect(() => { prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); }).to .throw(`docs-infra: The title "Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" is too long (117 characters). It needs to have fewer than 70 characters—ideally less than 60. For more details, see: https://developers.google.com/search/docs/advanced/appearance/title-link `); }); it('should report description too long', () => { const markdown = ` # Foo <p class="description">Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo</p> `; expect(() => { prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); }).to .throw(`docs-infra: The description "Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" is too long (188 characters). It needs to have fewer than 170 characters—ideally less than 160. For more details, see: https://ahrefs.com/blog/meta-description/#4-be-concise `); }); it('should not accept sh', () => { const markdown = ` # Foo <p class="description">Fo</p> \`\`\`sh npm install @mui/material \`\`\` `; expect(() => { prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); }).to.throw(`docs-infra: Unsupported language: "sh" in: \`\`\`sh npm install @mui/material \`\`\` Use "bash" instead. `); }); it('should report duplicated trailing splashes', () => { const markdown = ` # Localization <p class="description">Foo</p> [foo](/foo/) [bar](/bar//#foo) `; expect(() => { prepareMarkdown({ ...defaultParams, translations: [{ filename: 'index.md', markdown, userLanguage: 'en' }], }); }).to.throw(`docs-infra: Duplicated trailing slashes.`); }); });
6,088
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/prism.d.ts
export default function highlight(code: string, language: string): string;
6,089
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/prism.js
const prism = require('prismjs'); require('prismjs/components/prism-css'); require('prismjs/components/prism-bash'); require('prismjs/components/prism-diff'); require('prismjs/components/prism-javascript'); require('prismjs/components/prism-json'); require('prismjs/components/prism-jsx'); require('prismjs/components/prism-markup'); require('prismjs/components/prism-tsx'); function highlight(code, language) { let prismLanguage; switch (language) { case 'ts': prismLanguage = prism.languages.tsx; break; case 'js': prismLanguage = prism.languages.jsx; break; case 'sh': throw new Error( [ `docs-infra: Unsupported language: "sh" in:`, '', '```sh', code, '```', '', 'Use "bash" instead.', '', ].join('\n'), ); case 'diff': prismLanguage = { ...prism.languages.diff }; // original `/^[-<].*$/m` matches lines starting with `<` which matches // <SomeComponent /> // we will only use `-` as the deleted marker prismLanguage.deleted = /^[-].*$/m; break; default: prismLanguage = prism.languages[language]; break; } if (!prismLanguage) { if (language) { throw new Error(`unsupported language: "${language}", "${code}"`); } else { prismLanguage = prism.languages.jsx; } } return prism.highlight(code, prismLanguage); } module.exports = highlight;
6,090
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/textToHash.js
function makeUnique(hash, unique, i = 1) { const uniqueHash = i === 1 ? hash : `${hash}-${i}`; if (!unique[uniqueHash]) { unique[uniqueHash] = true; return uniqueHash; } return makeUnique(hash, unique, i + 1); } /** * @param {string} text - HTML from e.g. parseMarkdown#render * @param {Record<string, boolean>} [unique] - Ensures that each output is unique in `unique` * @returns {string} that is safe to use in fragment links */ function textToHash(text, unique = {}) { return makeUnique( encodeURI( text .toLowerCase() .replace(/<\/?[^>]+(>|$)/g, '') // remove HTML .replace(/=&gt;|&lt;| \/&gt;|<code>|<\/code>|&#39;/g, '') .replace(/[!@#$%^&*()=_+[\]{}`~;:'"|,.<>/?\s]+/g, '-') .replace( /([\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])\uFE0F?/g, '', ) // remove emojis .replace(/-+/g, '-') .replace(/^-|-$/g, ''), ), unique, ); } module.exports = textToHash;
6,091
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdown/textToHash.test.js
import { expect } from 'chai'; import { parseInline as renderInlineMarkdown } from 'marked'; import textToHash from './textToHash'; describe('textToHash', () => { it('should hash as expected', () => { const table = [ ['createTheme(options) => theme', 'createtheme-options-theme'], ['Typography - Font family', 'typography-font-family'], ["barre d'application", 'barre-dapplication'], [ 'createGenerateClassName([options]) => class name generator', 'creategenerateclassname-options-class-name-generator', ], ['@mui/material/styles vs @mui/styles', 'mui-material-styles-vs-mui-styles'], ['Blog 📝', 'blog'], ]; table.forEach((entry, index) => { const [markdown, expected] = entry; const text = renderInlineMarkdown(markdown, { mangle: false, headerIds: false }); const actual = textToHash(text); expect(actual).to.equal(expected, `snapshot #${index} matches`); }); }); it('should generate a unique hash', () => { const unique = {}; expect(textToHash('Styling solution', unique)).to.equal('styling-solution'); expect(textToHash('Styling solution', unique)).to.equal('styling-solution-2'); }); });
6,092
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdownlint-rule-mui/git-diff.js
module.exports = { names: ['gitDiff'], description: 'Respect the format output of git diff.', tags: ['spaces'], function: (params, onError) => { params.tokens.forEach((token) => { if (token.type === 'fence' && token.info === 'diff') { token.content.split('\n').forEach((line, index) => { if ( line[0] !== ' ' && line[0] !== '-' && line[0] !== '+' && line !== '' && line.indexOf('@@ ') !== 0 && line.indexOf('diff --git ') !== 0 && line.indexOf('index ') !== 0 ) { onError({ lineNumber: token.lineNumber + index + 1, detail: `The line start with "+" or "-" or " ": ${line}`, }); } }); } }); }, };
6,093
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdownlint-rule-mui/straight-quotes.js
// eslint-disable-next-line material-ui/straight-quotes const nonStraightQuotes = /[‘’“”]/; module.exports = { names: ['straightQuotes'], description: 'Only allow straight quotes.', tags: ['spelling'], function: (params, onError) => { params.lines.forEach((line, lineNumber) => { // It will match // opening single quote: \xE2\x80\x98 // closing single quote: \xE2\x80\x99 // opening double quote: \xE2\x80\x9C // closing double quote: \xE2\x80\x9D if (nonStraightQuotes.test(line)) { onError({ lineNumber: lineNumber + 1, detail: `For line: ${line}`, }); } }); }, };
6,094
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdownlint-rule-mui/table-alignment.js
function attr(attrs) { return (attrs || []).reduce((acc, item) => ({ ...acc, [item[0]]: item[1] }), {}); } module.exports = { names: ['tableAlignment'], description: 'Set table alignment.', tags: ['table'], function: (params, onError) => { params.tokens.forEach((token) => { // This is wrong: // | Version | Supported | // | ------- | ------------------ | // // The second column should be left aligned because it contains text: // | Version | Supported | // | ------- | :----------------- | // // However, columns that includes numbers should be right aligned: // | Version | Supported | // | ------: | :----------------- | // // More details: https://ux.stackexchange.com/questions/24066/what-is-the-best-practice-for-data-table-cell-content-alignment // // In this check we expect the style to be 'text-align:right' or equivalent. if (token.type === 'th_open' && attr(token.attrs).style == null) { onError({ lineNumber: token.lineNumber, detail: `${params.lines[token.lineNumber - 1]}`, }); } }); }, };
6,095
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/markdownlint-rule-mui/terminal-language.js
module.exports = { names: ['terminalLanguage'], description: 'Set the right language for terminal code.', tags: ['code'], function: (params, onError) => { params.tokens.forEach((token) => { if (token.type === 'fence' && token.info === 'sh') { onError({ lineNumber: token.lineNumber, detail: `Use "bash" instead of "sh".`, }); } }); }, };
6,096
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/mui-base/CONTRIBUTING.md
# Contributing ## Creating a new hook ### File structure When creating a new hook, follow the file structure found in other hooks' directories: Taking the imaginary `useAwesomeControl` as an example: - 📂 `useAwesomeControl` - 📄 `index.ts` - aggregates the public exports from all the other files in the directory - 📄 `useAwesomeControl.test.tsx` - unit tests - 📄 `useAwesomeControl.spec.tsx` - (optional) type tests - 📄 `useAwesomeControl.ts` - the implementation of the hook - 📄 `useAwesomeControl.types.ts` - type definitions ### Implementation Most Base UI hooks have a similar structure: 1. [Parameters destructuring](#parameters-destructuring) 2. Hook-specific logic 3. [Event handler factory functions](#event-handler-factory-functions) 4. [Slot props resolvers](#slot-props-resolvers) #### Parameters destructuring The parameters type must be called `[HookName]Parameters`. There are docs generation scripts that require this pattern. ```ts function useAwesomeControl(parameters: UseAwesomeControlParameters) { const { disabled, readOnly } = parameters; // the rest of the hook's logic... } ``` #### Event handler factory functions We don't define event handlers directly as functions because they must be able to access and call other handlers provided by developers in slot props resolvers. In other words, instead of defining the `handleClick(event: React.MouseEvent) => void` function, we define the `createHandleClick(otherHandlers: EventHandlers) => (event: React.MouseEvent) => void`. The `otherHandlers` parameter contains external handlers provided by developers. By convention, we call them `createHandle[EventName]`. If we allow a developer to skip running our logic for a given handler, we check the `event.defaultMuiPrevented` field. It's an equivalent of the native `defaultPrevented` that works just for Base UI code: ```tsx const createHandleKeyDown = (otherHandlers: EventHandlers) => (event: React.KeyboardEvent & MuiCancellableEvent) => { // Run the external handler first. // It can potentially set the defaultMuiPrevented field. otherHandlers.onKeyDown?.(event); // If the field is set, do not execute the usual handler logic. if (event.defaultMuiPrevented) { return; } // handler-specific logic... ``` #### Slot props resolvers These are functions called `get[SlotName]Props` that accept additional (optional) props and return props to be placed on slots of a component. Many components have just one slot (that we call "root"), but more complex components can have more. The order of merging props for the resulting object is important so that users can override the build-in props when necessary: 1. built-in props 2. external props 3. ref 4. event handlers Refs and event handlers can be placed in any order. They just have to be after external props. Example: ```tsx const getRootProps = <OtherHandlers extends EventHandlers>( otherHandlers: OtherHandlers = {} as OtherHandlers, ): UseAwesomeControlRootSlotProps<OtherHandlers> => { return { id, disabled, role: 'button' as const, ...otherHandlers, // if `id`, `disabled`, or `role` is provided here, they will override the default values set by us. ref: handleListboxRef, // refs mustn't be overridden, so they come after `...otherHandlers` onMouseDown: createHandleMouseDown(otherHandlers), // here we execute the event handler factory supplying it with external props }; }; ``` It's common that a hook uses other hooks and combines their `get*Props` with its own. To handle these cases, we have the `combineHooksSlotProps` utility. It creates a function that merges two other slot resolver functions: ```tsx const createHandleClick = (otherHandlers: EventHandlers) => (event: React.KeyboardEvent) => { /* ... */ } const { getRootProps as getListRootProps } = useList(/* ... */); const getOwnRootEventHandlers = (otherHandlers: EventHandlers = {}) => ({ onClick: createHandleClick(otherHandlers), }); const getRootProps = <TOther extends EventHandlers>( otherHandlers: TOther = {} as TOther, ): UseAwesomeControlRootSlotProps => { const getCombinedRootProps = combineHooksSlotProps(getOwnRootEventHandlers, getListRootProps); return { ...getCombinedRootProps(otherHandlers), role: 'combobox' } } ``` #### Ref handling When a hook needs to access the DOM node it operates on, it should create a ref and return it in the `get*Props` function. However, since the user of the hook may already have a ref to the element, we accept the refs in parameters and merge them with our refs using the `useForkRef` function, so the callers of the hook don't have to do it. Since hooks can operate on many elements (when dealing with multiple slots), we call refs in input parameters `[slotName]Ref`. Example: ```ts interface AwesomeControlHookParameters { rootRef?: React.Ref<Element>; // ... } const useAwesomeControlHook = (parameters: AwesomeControlHookParameters) { const { rootRef: externalRef } = parameters; const innerRef = React.useRef<HTMLDivElement | null>(null); const handleRef = useForkRef(externalRef, innerRef); return { // parameters omitted for the sake of brevity getRootProps: () => { ref: handleRef }, rootRef: handleRef } } ``` Note that the merged ref (`handleRef`) is not only returned as a part of root props but also as a field of the hook's return object. This is helpful in situations where the ref needs to be merged with yet another ref. ### Types Defining proper types can tremendously help developers use the hooks. The following types are required for each hook: - [HookName]Parameters - input parameters - [HookName]ReturnValue - the shape of the object returned by the hook - [HookName][SlotName]SlotProps - return values of slot props resolvers The parameters and return value types are usually straightforward. The definition of slot props, however, is more complex as it must take into consideration the object passed as an argument to the props resolver function: ```ts export interface UseMenuReturnValue { getListboxProps: <TOther extends EventHandlers>( otherHandlers?: TOther, ) => UseMenuListboxSlotProps; // ... } interface UseMenuListboxSlotEventHandlers { onBlur: React.FocusEventHandler; onKeyDown: React.KeyboardEventHandler; } export type UseMenuListboxSlotProps<TOther = {}> = UseListRootSlotProps< Omit<TOther, keyof UseMenuListboxSlotEventHandlers> & UseMenuListboxSlotEventHandlers > & { ref: React.RefCallback<Element> | null; role: React.AriaRole; }; ```
6,097
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/mui-base/README.md
<!-- markdownlint-disable-next-line --> <p align="center"> <a href="https://mui.com/base-ui/" rel="noopener" target="_blank"><img width="150" height="133" src="https://mui.com/static/logo.svg" alt="Base UI logo"></a> </p> <h1 align="center">Base UI</h1> Base UI is a library of unstyled React UI components and hooks. With Base UI, you gain complete control over your app's CSS and accessibility features. ## Installation Install the package in your project directory with: ```bash npm install @mui/base ``` ## Documentation <!-- #default-branch-switch --> Visit [https://mui.com/base-ui/](https://mui.com/base-ui/) to view the full documentation. ## Questions For how-to questions that don't involve making changes to the code base, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/base-ui) instead of GitHub issues. Use the "base-ui" tag on Stack Overflow to make it easier for the community to find your question. ## Examples Our documentation features [a collection of example projects using Base UI](https://github.com/mui/material-ui/tree/master/examples). ## Contributing Read the [contributing guide](/CONTRIBUTING.md) to learn about our development process, how to propose bug fixes and improvements, and how to build and test your changes. Contributing to Base UI is about more than just issues and pull requests! There are many other ways to [support MUI](https://mui.com/material-ui/getting-started/faq/#mui-is-awesome-how-can-i-support-the-project) beyond contributing to the code base. ## Changelog The [changelog](https://github.com/mui/material-ui/releases) is regularly updated to reflect what's changed in each new release. ## Roadmap Future plans and high-priority features and enhancements can be found in our [roadmap](https://mui.com/material-ui/discover-more/roadmap/). ## License This project is licensed under the terms of the [MIT license](/LICENSE). ## Security For details of supported versions and contact details for reporting security issues, please refer to the [security policy](https://github.com/mui/material-ui/security/policy).
6,098
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/mui-base/package.json
{ "name": "@mui/base", "version": "5.0.0-beta.24", "private": false, "author": "MUI Team", "description": "A library of headless ('unstyled') React UI components and low-level hooks.", "main": "./src/index.js", "keywords": [ "react", "react-component", "mui", "unstyled", "a11y" ], "repository": { "type": "git", "url": "https://github.com/mui/material-ui.git", "directory": "packages/mui-base" }, "license": "MIT", "bugs": { "url": "https://github.com/mui/material-ui/issues" }, "homepage": "https://mui.com/base-ui/", "funding": { "type": "opencollective", "url": "https://opencollective.com/mui-org" }, "scripts": { "build": "yarn build:legacy && yarn build:modern && yarn build:node && yarn build:stable && yarn build:types && yarn build:copy-files", "build:legacy": "node ../../scripts/build.mjs legacy", "build:modern": "node ../../scripts/build.mjs modern", "build:node": "node ../../scripts/build.mjs node", "build:stable": "node ../../scripts/build.mjs stable", "build:copy-files": "node ../../scripts/copyFiles.mjs", "build:types": "node ../../scripts/buildTypes.mjs", "prebuild": "rimraf build tsconfig.build.tsbuildinfo", "release": "yarn build && npm publish build", "test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-base/**/*.test.{js,ts,tsx}'", "typescript": "tslint -p tsconfig.json \"{src,test}/**/*.{spec,d}.{ts,tsx}\" && tsc -p tsconfig.json", "typescript:module-augmentation": "node scripts/testModuleAugmentation.js" }, "dependencies": { "@babel/runtime": "^7.23.2", "@floating-ui/react-dom": "^2.0.4", "@mui/types": "^7.2.9", "@mui/utils": "^5.14.18", "@popperjs/core": "^2.11.8", "clsx": "^2.0.0", "prop-types": "^15.8.1" }, "devDependencies": { "@mui-internal/test-utils": "^1.0.0", "@mui/material": "^5.14.18", "@testing-library/react": "^14.1.2", "@testing-library/user-event": "^14.5.1", "@types/chai": "^4.3.10", "@types/prop-types": "^15.7.10", "@types/react": "18.2.37", "@types/react-dom": "18.2.15", "@types/sinon": "^10.0.20", "chai": "^4.3.10", "fast-glob": "^3.3.2", "lodash": "^4.17.21", "react": "^18.2.0", "react-dom": "^18.2.0", "sinon": "^15.2.0" }, "peerDependencies": { "@types/react": "^17.0.0 || ^18.0.0", "react": "^17.0.0 || ^18.0.0", "react-dom": "^17.0.0 || ^18.0.0" }, "peerDependenciesMeta": { "@types/react": { "optional": true } }, "sideEffects": false, "publishConfig": { "access": "public" }, "engines": { "node": ">=12.0.0" } }
6,099