Skip to content

Commit

Permalink
chore: typescript configs
Browse files Browse the repository at this point in the history
  • Loading branch information
bennypowers committed Oct 14, 2024
1 parent 41d09bf commit e41af17
Show file tree
Hide file tree
Showing 73 changed files with 380 additions and 245 deletions.
13 changes: 7 additions & 6 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@ node_modules
_site
docs/pfe.min*
docs/assets/playgrounds/
docs/assets/javascript/elements/*.js.map
docs/assets/javascript/elements/*.d.ts
docs/assets/javascript/elements/*.js
docs/assets/javascript/elements/**/*.js.map
docs/assets/javascript/elements/**/*.d.ts
docs/assets/javascript/elements/**/*.js
docs/_plugins/**/*.js
docs/_includes/**/*.js
docs/_data/playgrounds.json
docs/assets/javascript/elements/playground-elements.js
docs/assets/javascript/elements/assets/playground-typescript-worker-*.js
docs/assets/javascript/environment.js
!docs/11ty-types.d.ts

# Build artifacts
elements.js
Expand All @@ -26,10 +25,13 @@ elements/*/test/*.js
react
lib/**/*.js
!elements/**/demo/*.css
*.tsbuildinfo
*.map
*.d.ts
!declaration.d.ts
*.tsbuildinfo
!docs/11ty-types.d.ts
!./docs/11ty-types.d.ts
!*/11ty-types.d.ts
custom-elements.json
test-results.xml
rhds.min.js
Expand Down Expand Up @@ -109,4 +111,3 @@ $RECYCLE.BIN/
# Windows shortcuts
*.lnk

!declaration.d.ts
2 changes: 1 addition & 1 deletion .stylelintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ rules:
ignoreTypes:
- heading
- actions
- rendered
- pending
- --rendered

selector-pseudo-element-no-unknown:
- true
Expand Down
62 changes: 53 additions & 9 deletions docs/11ty-types.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
declare module '@11ty/eleventy-plugin-syntaxhighlight/src/HighlightPairedShortcode.js' {
export default function HighlightPairedShortcode(content: string, language: string, highlightLines: string, options: object): any
}

declare module '@11ty/eleventy-plugin-syntaxhighlight/src/getAttributes.js' {
export default function getAttributes(...args: any[]): string
}
Expand Down Expand Up @@ -80,32 +76,46 @@ declare module '@11ty/eleventy/src/UserConfig.js' {
compile(inputContent: string): (this: CompileContext, data: unknown) => string | Promise<string>;
}

interface EleventyEventHandlerOptions {
interface EleventyBeforeEventHandlerOptions {
directories: EleventyData['directories'],
/** @deprecated */
dir: {input: string; output: string; includes: string, data: string; layouts: string;};
outputMode: 'js'|'json'|'ndjson';
runMode: 'build'|'serve'|'watch';
}

interface EleventyAfterEventHandlerOptions extends EleventyBeforeEventHandlerOptions {
results?: {inputPath:string;outputPath:string; url:string;content:string}[];
}

type TransformCallback = (this: TransformContext, content: string) => string | Promise<string>;

type AddCollectionCallback = (api: CollectionApi) => CollectionItem[] | Promise<CollectionItem[]>;

type OnCallback = (opts: EleventyEventHandlerOptions) => void | Promise<void>;
type OnCallback<O = EleventyBeforeEventHandlerOptions> = (opts: O) => void | Promise<void>;

export type PluginFunction<Opts = unknown> = (config: UserConfig, opts?: Opts) => void | Promise<void>

type FilterFunction<T = string, R = string> = (this: FilterContext, data: T, ...args: unknown[]) => R | Promise<R>;
type FilterFunction<T = string, R = string> = (this: FilterContext, data: T) => R | Promise<R>;
type FilterFunctionWithArgs<T = string, R = string> = (this: FilterContext, data: T, ...args: any[]) => R | Promise<R>;

type DataEntry =
| string
| number
| object
| Promise<string|number|object>
| (() => unknown)
| (() => Promise<unknown>);

export default class UserConfig {
addCollection(name: string, callback: AddCollectionCallback): void;
addDataExtension(names: string, processor: (content: string) => unknown | Promise<unknown>): void;
addExtension(extension: string, options: AddExtensionOptions): void;
addFilter(name: string, filter: FilterFunction): void;
addFilter(name: string, filter: FilterFunctionWithArgs): void;
addGlobalData(name: string, data: unknown | (() => unknown)): void;
addJavaScriptFunction(name: string, filter: FilterFunction): void;
addJavaScriptFunction(name: string, filter: FilterFunctionWithArgs): void;
addPassthroughCopy(items: string | Record<string, string>, copyOptions?: PassthroughCopyOptions): void;
addPlugin<Opts>(Plugin: PluginFunction<Opts> | {
initֵArguments?: Opts;
Expand All @@ -115,9 +125,15 @@ declare module '@11ty/eleventy/src/UserConfig.js' {
addWatchTarget(name: string, opts?: { resetConfig: boolean }): void;
amendLibrary(md: 'md', callback: ((md: MarkdownIt) => MarkdownIt)): void;
getFilter(name: string): FilterFunction;
globalData: Record<string, unknown | (() => unknown) | ((() => Promise<unknown>))>;
on(event: 'eleventy.before'| 'eleventy.beforeWatch' | 'eleventy.after', callback: OnCallback): void;
getFilter(name: string): FilterFunctionWithArgs;
globalData: { [key: string]: DataEntry };
on(event: 'eleventy.before', callback: OnCallback): void;
on(event: 'eleventy.after', callback: OnCallback<EleventyAfterEventHandlerOptions>): void;
on(event: 'eleventy.beforeWatch', callback: (changedFiles: string[]) => void | Promise<void>): void;
on(event: 'eleventy.contentMap', callback: (opts: ({ inputPathToUrl: Record<string, string>, urlToInputPath: Record<string, string> })) => void | Promise<void>): void;
on(event: 'eleventy.beforeConfig', callback: (config: UserConfig) => void | Promise<void>): void;
setQuietMode(quiet: boolean): void;
javascriptFunctions: Record<string, (...args: unknown[]) => any>;
watchIgnores: Set<string>;
}
}
Expand Down Expand Up @@ -162,7 +178,9 @@ declare module '@11ty/eleventy-plugin-syntaxhighlight' {
errorOnInvalidLanguage: boolean;
}>;
export default Plugin;
export function pairedShortcode(content: string, language: string, highlightLines: string, options: object): string;
}

declare module '@11ty/eleventy-plugin-directory-output' {
import { PluginFunction } from "@11ty/eleventy/src/UserConfig.js";
const Plugin: PluginFunction<{
Expand All @@ -173,6 +191,30 @@ declare module '@11ty/eleventy-plugin-directory-output' {
}>;
export default Plugin;
}

declare module '@11ty/eleventy-fetch' {
import { PluginFunction } from "@11ty/eleventy/src/UserConfig.js";
type Duration = `${number}${'d'|'m'|'h'}`;
type CacheType = 'json' | 'buffer' | 'text';
function EleventyFetch<T = unknown>(url: string, options: {
directory: string;
removeUrlQueryParams: boolean;
type: CacheType;
duration: Duration;
fetchOptions: { headers: Record<string, string> };
}): Promise<T>;
export default EleventyFetch;
export class AssetCache<T=unknown> {
constructor(tag: string);
isCacheValid(time: Duration): boolean;
save(data:T, type: CacheType): Promise<void>;
getCachedValue(): Promise<T>
cache: {
destroy(): void;
}
}
}

declare module '@patternfly/pfe-tools/11ty/plugins/anchors.cjs' {
import type { Cheerio } from 'cheerio';
import type { AnyNode } from 'domhandler';
Expand All @@ -183,12 +225,14 @@ declare module '@patternfly/pfe-tools/11ty/plugins/anchors.cjs' {
}>;
export default AnchorsPlugin;
}

declare module '@patternfly/pfe-tools/11ty/plugins/custom-elements-manifest.cjs' {
import type { PluginOptions } from '@patternfly/pfe-tools/11ty/plugins/types';
import { PluginFunction } from "@11ty/eleventy/src/UserConfig.js";
const Plugin: PluginFunction<PluginOptions>;
export default Plugin;
}

declare module 'eleventy-plugin-helmet' {
import { PluginFunction } from "@11ty/eleventy/src/UserConfig.js";
const Plugin: PluginFunction;
Expand Down
26 changes: 14 additions & 12 deletions docs/_includes/layouts/pages/element.11ty.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import type { ElementDocsPageData } from '../../../_plugins/element-docs.js';
import type { ElementDocsPageData } from '#11ty-plugins/element-docs.js';
import type { ClassMethod } from 'custom-elements-manifest';
import type { FileOptions, ProjectManifest } from 'playground-elements/shared/worker-api.js';

import { tokens } from '@rhds/tokens/meta.js';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFile } from 'node:fs/promises';
import { copyCell, dedent, getTokenHref } from '../../../_plugins/tokensHelpers.js';
import { copyCell, dedent, getTokenHref } from '#11ty-plugins/tokensHelpers.js';
import { Generator } from '@jspm/generator';
import { AssetCache } from '@11ty/eleventy-fetch';
import { Renderer } from '#uxdot/eleventy.config.js';
import { Renderer } from '#eleventy.config';
import type { ImportMap } from '#11ty-plugins/importMap.js';

type FileEntry = [string, FileOptions & { inline: string }];

Expand Down Expand Up @@ -43,16 +44,16 @@ interface Context extends EleventyPageRenderData {
playgrounds: Record<`rh-${string}`, ProjectManifest>;
}

export default class ElementsPage extends Renderer {
static assetCache = new AssetCache('rhds-ux-dot-import-map-jspmio');
export default class ElementsPage extends Renderer<Context> {
static assetCache = new AssetCache<ImportMap>('rhds-ux-dot-import-map-jspmio');

data() {
return {
layout: 'layouts/pages/has-toc.njk',
permalink: ({ doc }) => doc.permalink,
permalink: ({ doc }: Context) => doc.permalink,
eleventyComputed: {
title: ({ doc }) => doc.pageTitle,
tagName: ({ doc }) => doc.tagName,
title: ({ doc }: Context) => doc.pageTitle,
tagName: ({ doc }: Context) => doc.tagName,
},
};
}
Expand Down Expand Up @@ -138,9 +139,9 @@ export default class ElementsPage extends Renderer {
await assetCache.save(generator.getMap(), 'json');
}
const map = structuredClone(await assetCache.getCachedValue());
map.imports[`@rhds/elements/${tagName}/${tagName}.js`] =
map.imports['@rhds/elements'].replace('elements.js', `${tagName}/${tagName}.js`);
delete map.imports['@rhds/elements'];
map.imports![`@rhds/elements/${tagName}/${tagName}.js`] =
map.imports!['@rhds/elements'].replace('elements.js', `${tagName}/${tagName}.js`);
delete map.imports!['@rhds/elements'];
return JSON.stringify(map, null, 2);
}

Expand Down Expand Up @@ -776,7 +777,8 @@ export default class ElementsPage extends Renderer {
}

async #renderDemos(ctx: Context) {
const entries: FileEntry[] = Object.entries(ctx.playgrounds[ctx.tagName]?.files ?? {});
const tagName = ctx.tagName as `rh-${string}`;
const entries = Object.entries(ctx.playgrounds[tagName]?.files ?? {}) as FileEntry[];
return [
await this.#renderDemoHead(),
...await this.#renderPlaygrounds(ctx, entries),
Expand Down
2 changes: 1 addition & 1 deletion docs/_includes/layouts/pages/has-toc.njk
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ layout: layouts/base.njk
data-helmet>

<link rel="stylesheet"
href="/assets/javascript/elements/uxdot-toc-lightdom.css"
href="/assets/packages/@uxdot/elements/uxdot-toc-lightdom.css"
data-helmet>

<script type="module" data-helmet>
Expand Down
6 changes: 3 additions & 3 deletions docs/_includes/layouts/pages/tokens.11ty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { DesignToken } from '#11ty-plugins/tokensHelpers.js';
import tinycolor from 'tinycolor2';
import { tokens as tokensMeta } from '@rhds/tokens/meta.js';
import { createRequire } from 'node:module';
import { Renderer } from '#uxdot/eleventy.config.js';
import { Renderer } from '#eleventy.config';

const require = createRequire(import.meta.url);
const tokensJSON = require('@rhds/tokens/json/rhds.tokens.json');
Expand Down Expand Up @@ -52,7 +52,7 @@ interface Data {
tokenCategory: TokenCategory;
}

export default class TokensPage extends Renderer {
export default class TokensPage extends Renderer<Data> {
data() {
return {
layout: 'layouts/pages/has-toc.njk',
Expand Down Expand Up @@ -419,7 +419,7 @@ export default class TokensPage extends Renderer {
}
}

async render(ctx: Data) {
override async render(ctx: Data) {
const { tokenCategory } = ctx;
const { exclude, include, path, slug } = tokenCategory;
const name = path.split('.').pop()!;
Expand Down
23 changes: 12 additions & 11 deletions docs/_includes/partials/component/feedback.11ty.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import { Renderer } from '../../../../eleventy.config.ts';
import { dedent } from '../../../_plugins/tokensHelpers';
import { Renderer, type GlobalData } from '#eleventy.config';
import { dedent } from '#11ty-plugins/tokensHelpers.js';
import type { ElementDocsPageData } from '#11ty-plugins/element-docs.js';

const html = String.raw; // for editor highlighting

export default class Feedback extends Renderer {
async render({
doc,
title,
pfeconfig,
relatedItems,
}) {
pfeconfig ??= await import('@patternfly/pfe-tools/config.js').then(x => x.getPfeConfig());
interface Data {
title: string;
relatedItems: Record<string, string[]>;
doc: ElementDocsPageData;
}

export default class Feedback extends Renderer<Data> {
async render({ doc, title, relatedItems, pfeconfig }: Data & GlobalData) {
const name = doc?.tagName ?? this.slugify(title);
const related = [...new Set((relatedItems?.[name] ?? []) as string[])].map(x => {
const slug = this.getTagNameSlug(x);
return {
name: x,
url: slug === x ? `/patterns/${slug}` : `/elements/${slug}`,
text: pfeconfig.aliases[x] || this.deslugify(slug),
text: pfeconfig.aliases?.[x] || this.deslugify(slug),
};
}).sort((a, b) => a.text < b.text ? -1 : a.text > b.text ? 1 : 0);
return dedent(html`
Expand Down
2 changes: 1 addition & 1 deletion docs/_includes/partials/component/header.njk
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<uxdot-header {% if tabs %}has-subnav{% endif %} {% if tokenSearch %}has-search {% endif %}>
{#- TODO: cheap hack here to fix data spaghetti from demos page -#}
<h1 id="{{ headingId }}" class="page-title">
{{ (prettyName or heading or title) | replace('Demos |', '') }}
{{ prettyName or heading or title }}
{% if doc.planned %}
<rh-tag icon="notification-fill" color="gray">Planned</rh-tag>
{% endif %}
Expand Down
4 changes: 2 additions & 2 deletions docs/_plugins/alphabetize-tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ export default function(eleventyConfig: UserConfig, opts?: Options) {
for (const currentWeight of Object.keys(weights).sort() as unknown as number[]) {
// Sort by title alphabetically
weights[currentWeight].sort(function(a, b) {
if (a.data.title < b.data.title) {
if ((a.data?.title ?? 0) < (b.data?.title ?? 0)) {
return -1;
}
if (a.data.title > b.data.title) {
if ((a.data?.title ?? 0) > (b.data?.title ?? 0)) {
return 1;
}
return 0;
Expand Down
3 changes: 1 addition & 2 deletions docs/_plugins/element-demos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ export default function(eleventyConfig: UserConfig) {
return Parse5.serialize(document);
}
return content;
},
);
});

eleventyConfig.addTransform('demo-lightdom-css', async function(this, content) {
const { outputPath, inputPath } = this.page;
Expand Down
Loading

0 comments on commit e41af17

Please sign in to comment.