Skip to content

Commit

Permalink
docs(readme): fix attribute name composition (#2254)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomMenga authored Dec 4, 2023
1 parent a8c4d21 commit 0713997
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 13 deletions.
48 changes: 37 additions & 11 deletions ci/docs_generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,37 @@
import fs from 'fs';

import { customElementsManifestToMarkdown } from '@custom-elements-manifest/to-markdown';
import type { Package } from 'custom-elements-manifest/schema';
import type { Attribute, CustomElement, Package } from 'custom-elements-manifest/schema';
import * as glob from 'glob';
// eslint-disable-next-line @typescript-eslint/naming-convention
import MagicString from 'magic-string';
import { format, resolveConfig } from 'prettier';

const manifestFilePath = './dist/components/custom-elements.json';
import componentAnalyzerConfig from '../config/custom-elements-manifest.config';

const manifestFilePath = `${componentAnalyzerConfig.outdir}/custom-elements.json`;
const tempFolderPath = './dist/docs';
const componentsFolder = './src/components';
const inheritedFromColumnIndex = 6;
const propertyColumnIndex = 1;
const attributeColumnIndex = 2;

function toKebabCase(value: string): string {
return value.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
function getAttributeName(propertyName: string, attributes: Attribute[]): string {
const name = propertyName.replace(/'|`/g, '').trim();
const attr = attributes.find((a) => a.fieldName === name)?.name;
return attr ? `\`${attr}\`` : '-';
}

/**
* Add the 'attribute' column.
* Removes the 'Inherited from' column.
* Replace 'Fields' title with 'Properties'
*/
function updateFieldsTable(newDocs: MagicString, sections: RegExpMatchArray[]): void {
function updateFieldsTable(
newDocs: MagicString,
sections: RegExpMatchArray[],
attributes: Attribute[],
): void {
const fieldsSectionIndex = sections.findIndex((sect) => sect.groups!.name === 'Fields');
const startIndex = sections[fieldsSectionIndex]?.index;
const endIndex = sections[fieldsSectionIndex + 1]?.index;
Expand All @@ -44,9 +52,16 @@ function updateFieldsTable(newDocs: MagicString, sections: RegExpMatchArray[]):
tableRows.forEach((row) => row.splice(inheritedFromColumnIndex, 1));

// Generate the 'attribute' column by copying the property column and transform string to kebab case
[tableRows[0][propertyColumnIndex].replace('Name', 'Attribute').trim()]
.concat(tableRows.slice(1).map((entry) => toKebabCase(entry[propertyColumnIndex]).trim()))
.forEach((attributeColumn, i) => tableRows[i].splice(attributeColumnIndex, 0, attributeColumn));
const attributeColumn = [
tableRows[0][propertyColumnIndex].replace('Name', 'Attribute').trim(),
tableRows[1][propertyColumnIndex],
...tableRows.slice(2).map((entry) => getAttributeName(entry[propertyColumnIndex], attributes)),
];

// Insert the attribute column in the table
attributeColumn.forEach((attributeColumn, i) =>
tableRows[i].splice(attributeColumnIndex, 0, attributeColumn),
);

const fieldsTable = tableRows.map((cols) => cols.join('|')).join('\n');
newDocs.update(
Expand All @@ -56,7 +71,12 @@ function updateFieldsTable(newDocs: MagicString, sections: RegExpMatchArray[]):
);
}

async function updateComponentReadme(name: string, tag: string, docs: string): Promise<void> {
async function updateComponentReadme(
name: string,
tag: string,
docs: string,
manifest: CustomElement,
): Promise<void> {
const path = glob.sync(`${componentsFolder}/**/${tag.replace(/^sbb-/, '')}/readme.md`)[0];
if (!fs.existsSync(path)) {
console.error(`Component ${name} has no readme file, please create it following the template`);
Expand All @@ -75,7 +95,7 @@ async function updateComponentReadme(name: string, tag: string, docs: string): P
// Remove the title
newDocs.replace(/^# class: `.*`\n/m, '');

updateFieldsTable(newDocs, sections);
updateFieldsTable(newDocs, sections, manifest.attributes!);
newDocs = new MagicString(newDocs.toString());

// Unescape `
Expand Down Expand Up @@ -116,6 +136,7 @@ const markdown: string = customElementsManifestToMarkdown(manifest, {
'mixins',
],
});
const manifestDeclarations = manifest.modules.flatMap((m) => m.declarations);

if (!fs.existsSync(tempFolderPath)) {
fs.mkdirSync(tempFolderPath, { recursive: true });
Expand All @@ -136,6 +157,11 @@ for (let i = 0; i < matches.length; i++) {
// If there is a `<hr/>` it indicates corrupted data respect. mixed data over different components.
// If we just stop before occurrence of `<hr/>` we are not including the corrupted data.
const hrIndex = componentMarkdown.indexOf('<hr/>');
await updateComponentReadme(compName, compTag, componentMarkdown.substring(0, hrIndex));
const markdownDoc = componentMarkdown.substring(0, hrIndex);
const compManifest = manifestDeclarations.find(
(c) => c?.kind === 'class' && c.name === compName,
) as CustomElement;

await updateComponentReadme(compName, compTag, markdownDoc, compManifest);
}
console.log('Docs generated successfully');
2 changes: 1 addition & 1 deletion src/components/file-selector/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ It's suggested to have a different value for each variant, e.g.:
| `titleContent` | `title-content` | public | `string \| undefined` | | The title displayed in `dropzone` variant. |
| `disabled` | `disabled` | public | `boolean` | | Whether the component is disabled. |
| `accessibilityLabel` | `accessibility-label` | public | `string \| undefined` | | This will be forwarded as aria-label to the native input element. |
| `files` | `files` | public | `File[]` | | Gets the currently selected files. |
| `files` | - | public | `File[]` | | Gets the currently selected files. |

## Methods

Expand Down
2 changes: 1 addition & 1 deletion src/components/form-field/form-field/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ technology will announce errors when they appear.
| `width` | `width` | public | `'default' \| 'collapse'` | `'default'` | Defines the width of the component: - `default`: the component has defined width and min-width; - `collapse`: the component adapts itself to its inner input content. |
| `floatingLabel` | `floating-label` | public | `boolean` | `false` | Whether the label should float. If activated, the placeholder of the input is hidden. |
| `negative` | `negative` | public | `boolean` | `false` | Negative coloring variant flag. |
| `inputElement` | `input-element` | public | `HTMLInputElement \| HTMLSelectElement \| HTMLElement` | | Returns the input element. |
| `inputElement` | - | public | `HTMLInputElement \| HTMLSelectElement \| HTMLElement` | | Returns the input element. |

## Methods

Expand Down

0 comments on commit 0713997

Please sign in to comment.