Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: insert site custom CSS with highest priority #6227

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,6 @@ function testValidateThemeConfig(partialThemeConfig) {
});
}

function testOk(partialThemeConfig) {
expect(
testValidateThemeConfig({...DEFAULT_CONFIG, ...partialThemeConfig}),
).toEqual({
...DEFAULT_CONFIG,
...partialThemeConfig,
});
}

describe('themeConfig', () => {
test('should accept valid theme config', () => {
const userConfig = {
Expand Down Expand Up @@ -477,31 +468,13 @@ describe('themeConfig', () => {
});

describe('customCss config', () => {
test('should accept customCss undefined', () => {
testOk({
customCss: undefined,
});
});

test('should accept customCss string', () => {
testOk({
customCss: './path/to/cssFile.css',
});
});

test('should accept customCss string array', () => {
testOk({
customCss: ['./path/to/cssFile.css', './path/to/cssFile2.css'],
});
});

test('should reject customCss number', () => {
test('should reject customCss string', () => {
expect(() =>
testValidateThemeConfig({
customCss: 42,
customCss: './path/to/cssFile.css',
}),
).toThrowErrorMatchingInlineSnapshot(
`"\\"customCss\\" must be one of [array, string]"`,
`"themeConfig.customCss is invalid. Custom css used to be provided as themeOptions.customCss, but it is deprecated now."`,
);
});
});
Expand Down
1 change: 1 addition & 0 deletions packages/docusaurus-theme-classic/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,4 @@ export function getSwizzleComponentList(): string[] {
}

export {validateThemeConfig} from './validateThemeConfig';
export {validateOptions} from './options';
47 changes: 47 additions & 0 deletions packages/docusaurus-theme-classic/src/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {Joi} from '@docusaurus/utils-validation';
import type {
ValidationResult,
OptionValidationContext,
} from '@docusaurus/types';
import type {Options} from '@docusaurus/theme-classic';

const DEFAULT_OPTIONS: Options = {
customCss: null,
};

export const Schema = Joi.object({
customCss: Joi.alternatives()
.try(Joi.array().items(Joi.string().required()), Joi.string().required())
.optional()
.default(DEFAULT_OPTIONS.customCss)
.warning('deprecate.error', {
msg: `theme.customCss option is deprecated.
Please use siteConfig.styling.css instead.

Note that this also changes the CSS insertion order!
This enables your site CSS to override default theme CSS more easily, without using !important

Before: custom site CSS was inserted before Infima CSS and theme modules.
After: custom site CSS will be inserted after Infima CSS and theme modules.

See also https://github.com/facebook/docusaurus/pull/6227
slorber marked this conversation as resolved.
Show resolved Hide resolved
`,
})
.messages({
'deprecate.error': '{#msg}',
}),
});

export function validateOptions({
validate,
options,
}: OptionValidationContext<Options>): ValidationResult<Options> {
return validate(Schema, options);
}
2 changes: 1 addition & 1 deletion packages/docusaurus-theme-classic/src/theme-classic.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

declare module '@docusaurus/theme-classic' {
export type Options = {
customCss?: string | string[];
customCss?: string | string[] | null;
};
}

Expand Down
12 changes: 7 additions & 5 deletions packages/docusaurus-theme-classic/src/validateThemeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,10 +244,6 @@ const FooterLinkItemSchema = Joi.object({
// (users may need additional attributes like target, aria-role, data-customAttribute...)
.unknown();

const CustomCssSchema = Joi.alternatives()
.try(Joi.array().items(Joi.string().required()), Joi.string().required())
.optional();

const ThemeConfigSchema = Joi.object({
// TODO temporary (@alpha-58)
disableDarkMode: Joi.any().forbidden().messages({
Expand All @@ -259,7 +255,13 @@ const ThemeConfigSchema = Joi.object({
'any.unknown':
'defaultDarkMode theme config is deprecated. Please use the new colorMode attribute. You likely want: config.themeConfig.colorMode.defaultMode = "dark"',
}),
customCss: CustomCssSchema,

// TODO temporary
customCss: Joi.any().forbidden().messages({
slorber marked this conversation as resolved.
Show resolved Hide resolved
'any.unknown':
'themeConfig.customCss is invalid. Custom css used to be provided as themeOptions.customCss, but it is deprecated now.',
}),

colorMode: ColorModeSchema,
image: Joi.string(),
docs: DocsSchema,
Expand Down
6 changes: 6 additions & 0 deletions packages/docusaurus-types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export type ThemeConfig = {
[key: string]: unknown;
};

export type StylingConfig = {
css: string[];
};

// Docusaurus config, after validation/normalization
export interface DocusaurusConfig {
baseUrl: string;
Expand All @@ -33,6 +37,7 @@ export interface DocusaurusConfig {
// trailingSlash undefined = legacy retrocompatible behavior => /file => /file/index.html
trailingSlash: boolean | undefined;
i18n: I18nConfig;
styling: StylingConfig;
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Is this new styling.css config a good API design @Josh-Cena ?

Is styling a good name?

I'd like later to add new styling options like primary color leading to an attempt to auto-generate a color palette, that we could map to Infima/tailwind CSS vars in theme.

IMHO users shouldn't need to write any CSS to be able to tweak a bit the site colors. v1 had options for that too: https://v1.docusaurus.io/docs/en/site-config.html#colors-object

Note: we already have a config.stylesheets API but it's not exactly the same: this just insert a raw CSS file into the HTML head, and this CSS is never processed/optimized. I suspect it's not widely used because it's documented only in one place: https://docusaurus.io/docs/api/docusaurus-config#stylesheets

Copy link
Collaborator

Choose a reason for hiding this comment

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

I would have gone for styles... but styling, sure 👍

config.stylesheets is not only rarely used but also very misleading: when I help build other sites (e.g. https://typescript-eslint.io/) I often hack this field for injecting <link /> tags...

onBrokenLinks: ReportingSeverity;
onBrokenMarkdownLinks: ReportingSeverity;
onDuplicateRoutes: ReportingSeverity;
Expand Down Expand Up @@ -419,6 +424,7 @@ interface HtmlTagObject {
innerHTML?: string;
}

// TODO weird useless type, refactor
export type ValidationResult<T> = T;
slorber marked this conversation as resolved.
Show resolved Hide resolved

export type ValidationSchema<T> = Joi.ObjectSchema<T>;
Expand Down
22 changes: 19 additions & 3 deletions packages/docusaurus/src/server/configValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import logger from '@docusaurus/logger';
import {DocusaurusConfig, I18nConfig} from '@docusaurus/types';
import {DocusaurusConfig, I18nConfig, StylingConfig} from '@docusaurus/types';
import {DEFAULT_CONFIG_FILE_NAME, STATIC_DIR_NAME} from '@docusaurus/utils';
import {
Joi,
Expand All @@ -24,9 +24,14 @@ export const DEFAULT_I18N_CONFIG: I18nConfig = {
localeConfigs: {},
};

export const DEFAULT_STYLING_CONFIG: StylingConfig = {
css: [],
};

export const DEFAULT_CONFIG: Pick<
DocusaurusConfig,
| 'i18n'
| 'styling'
| 'onBrokenLinks'
| 'onBrokenMarkdownLinks'
| 'onDuplicateRoutes'
Expand All @@ -41,6 +46,7 @@ export const DEFAULT_CONFIG: Pick<
| 'staticDirectories'
> = {
i18n: DEFAULT_I18N_CONFIG,
styling: DEFAULT_STYLING_CONFIG,
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
onDuplicateRoutes: 'warn',
Expand Down Expand Up @@ -101,7 +107,7 @@ const LocaleConfigSchema = Joi.object({
direction: Joi.string().equal('ltr', 'rtl').default('ltr'),
});

const I18N_CONFIG_SCHEMA = Joi.object<I18nConfig>({
const I18nConfigSchema = Joi.object<I18nConfig>({
defaultLocale: Joi.string().required(),
locales: Joi.array().items().min(1).items(Joi.string().required()).required(),
localeConfigs: Joi.object()
Expand All @@ -123,6 +129,15 @@ const SiteUrlSchema = URISchema.required().custom((value, helpers) => {
return value;
}, 'siteUrlCustomValidation');

const StylingSchema = Joi.object({
css: Joi.alternatives()
.try(
Joi.array().items(Joi.string().required()).required(),
Joi.string().custom((val) => [val]), // normalize: string -> string[]
)
.default(DEFAULT_STYLING_CONFIG.css),
}).default(DEFAULT_STYLING_CONFIG);

// TODO move to @docusaurus/utils-validation
export const ConfigSchema = Joi.object({
baseUrl: Joi.string()
Expand All @@ -134,7 +149,8 @@ export const ConfigSchema = Joi.object({
title: Joi.string().required(),
url: SiteUrlSchema,
trailingSlash: Joi.boolean(), // No default value! undefined = retrocompatible legacy behavior!
i18n: I18N_CONFIG_SCHEMA,
i18n: I18nConfigSchema,
styling: StylingSchema,
onBrokenLinks: Joi.string()
.equal('ignore', 'log', 'warn', 'error', 'throw')
.default(DEFAULT_CONFIG.onBrokenLinks),
Expand Down
19 changes: 19 additions & 0 deletions packages/docusaurus/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,22 @@ function createMDXFallbackPlugin({
};
}

function createSiteCSSPlugin({
siteConfig,
}: {
siteConfig: DocusaurusConfig;
}): LoadedPlugin {
return {
name: 'docusaurus-site-styling-css-plugin',
content: null,
options: {},
version: {type: 'synthetic'},
getClientModules() {
return siteConfig.styling.css;
},
};
}

export async function load(
siteDir: string,
options: LoadContextOptions = {},
Expand Down Expand Up @@ -315,6 +331,9 @@ export async function load(

plugins.push(createBootstrapPlugin({siteConfig}));
plugins.push(createMDXFallbackPlugin({siteDir, siteConfig}));
// Added last, because the site CSS must be inserted after all other clientModules
// See also https://github.com/facebook/docusaurus/pull/6227
plugins.push(createSiteCSSPlugin({siteConfig}));

// Load client modules.
const clientModules = loadClientModules(plugins);
Expand Down
5 changes: 4 additions & 1 deletion website/docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ const config = {
// - force trailing slashes for deploy previews
// - avoid trailing slashes in prod
trailingSlash: isDeployPreview,
styling: {
css: require.resolve('./src/css/custom.css'),
},
stylesheets: [
{
href: 'https://cdn.jsdelivr.net/npm/katex@0.13.24/dist/katex.min.css',
Expand Down Expand Up @@ -304,7 +307,7 @@ const config = {
remarkPlugins: [npm2yarn],
},
theme: {
customCss: [require.resolve('./src/css/custom.css')],
customCss: [require.resolve('./src/css/customLegacy.css')],
},
gtag: !isDeployPreview
? {
Expand Down
12 changes: 12 additions & 0 deletions website/src/css/customLegacy.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


/* Used to test CSS insertion order */
.test-marker-theme-custom-css-legacy {
content: "theme-custom-css-legacy";
}
3 changes: 2 additions & 1 deletion website/testCSSOrder.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ const EXPECTED_CSS_MARKERS = [
'.tabs__item',

// Test markers
'.test-marker-site-custom-css-unique-rule',
'.test-marker-theme-custom-css-legacy', // TODO should be removed later
'.test-marker-site-client-module',
'.test-marker-theme-layout',
'.test-marker-site-index-page',
'.test-marker-site-custom-css-unique-rule',

// lazy loaded lib
'.DocSearch-Modal',
Expand Down