|
@@ -1,6 +1,7 @@
|
|
|
// See: https://github.com/martypdx/rehype-add-classes for the original implementation.
|
|
// See: https://github.com/martypdx/rehype-add-classes for the original implementation.
|
|
|
// Re-implemeted in TypeScript.
|
|
// Re-implemeted in TypeScript.
|
|
|
import { selectAll, HastNode, Element } from 'hast-util-select';
|
|
import { selectAll, HastNode, Element } from 'hast-util-select';
|
|
|
|
|
+import { Properties } from 'hast-util-select/lib/types';
|
|
|
import { Plugin } from 'unified';
|
|
import { Plugin } from 'unified';
|
|
|
|
|
|
|
|
export type SelectorName = string; // e.g. 'h1'
|
|
export type SelectorName = string; // e.g. 'h1'
|
|
@@ -8,9 +9,7 @@ export type ClassName = string; // e.g. 'header'
|
|
|
export type Additions = Record<SelectorName, ClassName>;
|
|
export type Additions = Record<SelectorName, ClassName>;
|
|
|
export type AdditionsEntry = [SelectorName, ClassName];
|
|
export type AdditionsEntry = [SelectorName, ClassName];
|
|
|
|
|
|
|
|
-const generateWriter = (className: string) => (element: Element) => {
|
|
|
|
|
- const { properties } = element;
|
|
|
|
|
-
|
|
|
|
|
|
|
+export const addClassToProperties = (properties: Properties | undefined, className: string): void => {
|
|
|
if (properties == null) {
|
|
if (properties == null) {
|
|
|
return;
|
|
return;
|
|
|
}
|
|
}
|
|
@@ -20,9 +19,19 @@ const generateWriter = (className: string) => (element: Element) => {
|
|
|
return;
|
|
return;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ if (Array.isArray(properties.className)) {
|
|
|
|
|
+ properties.className.push(className);
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
properties.className += ` ${className}`;
|
|
properties.className += ` ${className}`;
|
|
|
};
|
|
};
|
|
|
|
|
|
|
|
|
|
+const generateWriter = (className: string) => (element: Element) => {
|
|
|
|
|
+ const { properties } = element;
|
|
|
|
|
+ addClassToProperties(properties, className);
|
|
|
|
|
+};
|
|
|
|
|
+
|
|
|
const adder = (entry: AdditionsEntry) => {
|
|
const adder = (entry: AdditionsEntry) => {
|
|
|
const [selectorName, className] = entry;
|
|
const [selectorName, className] = entry;
|
|
|
const writer = generateWriter(className);
|
|
const writer = generateWriter(className);
|
|
@@ -30,7 +39,7 @@ const adder = (entry: AdditionsEntry) => {
|
|
|
return (node: HastNode) => selectAll(selectorName, node).forEach(writer);
|
|
return (node: HastNode) => selectAll(selectorName, node).forEach(writer);
|
|
|
};
|
|
};
|
|
|
|
|
|
|
|
-export const addClass: Plugin<[Additions]> = (additions) => {
|
|
|
|
|
|
|
+export const rehypePlugin: Plugin<[Additions]> = (additions) => {
|
|
|
const adders = Object.entries(additions).map(adder);
|
|
const adders = Object.entries(additions).map(adder);
|
|
|
|
|
|
|
|
return node => adders.forEach(a => a(node as HastNode));
|
|
return node => adders.forEach(a => a(node as HastNode));
|