Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions .changeset/tidy-eagles-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@modern-js/doc-core': patch
---

feat: add doc medium-zoom plugin

feat: 增加 medium-zoom 插件
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ exports[`test getRootPixelCode > should getRootPixelCode with custom options 1`]
typeof window !== 'undefined' && setRootPixel();"
`;

exports[`test getRootPixelCode > should getRootPixelCode with custom options 2`] = `"function setRootPixel(){function n(n){return(new RegExp(\\"[?&]\\"+n+\\"=([^&#\\\\b]+)\\").exec(location.search||\\"\\")||[])[1]}function e(){var e,i=\\"widthKey\\",t=document.documentElement;if(i&&+n(i))e=+n(i);else if(e=window.innerWidth&&t.clientWidth?Math.min(window.innerWidth,t.clientWidth):window.innerWidth||t.clientWidth||document.body&&document.body.clientWidth||750,(screen.orientation&&screen.orientation.angle||window.orientation)/90%2){var o=window.innerHeight&&t.clientHeight?Math.min(window.innerHeight,t.clientHeight):window.innerHeight||t.clientHeight||document.body&&document.body.clientHeight||750;e=Math.max(o,350)}var d=5*e/750;d=d<64?d:5,window.ROOT_FONT_SIZE=d,t.style.fontSize=d+\\"px\\"}function i(n){n?e():setTimeout(e,30)}i(!0),window.addEventListener(\\"resize\\",i,!1),\\"onorientationchange\\"in window&&window.addEventListener(\\"orientationchange\\",i,!1)}\\"undefined\\"!=typeof window&&setRootPixel();"`;
exports[`test getRootPixelCode > should getRootPixelCode with custom options 2`] = `"function setRootPixel(){function n(n){return(new RegExp(\\"[?&]\\"+n+\\"=([^&#\\\\b]+)\\").exec(location.search||\\"\\")||[])[1]}function e(){var e,i=\\"widthKey\\",t=document.documentElement;if(+n(i))e=+n(i);else if(e=window.innerWidth&&t.clientWidth?Math.min(window.innerWidth,t.clientWidth):window.innerWidth||t.clientWidth||document.body&&document.body.clientWidth||750,(screen.orientation&&screen.orientation.angle||window.orientation)/90%2){var o=window.innerHeight&&t.clientHeight?Math.min(window.innerHeight,t.clientHeight):window.innerHeight||t.clientHeight||document.body&&document.body.clientHeight||750;e=Math.max(o,350)}var d=5*e/750;d=d<64?d:5,window.ROOT_FONT_SIZE=d,t.style.fontSize=d+\\"px\\"}function i(n){n?e():setTimeout(e,30)}i(!0),window.addEventListener(\\"resize\\",i,!1),\\"onorientationchange\\"in window&&window.addEventListener(\\"orientationchange\\",i,!1)}\\"undefined\\"!=typeof window&&setRootPixel();"`;

exports[`test getRootPixelCode > should getRootPixelCode with default options 1`] = `
"function setRootPixel() {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/doc-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"@modern-js/builder-rspack-provider": "workspace:*",
"@modern-js/mdx-rs-binding": "^0.1.8",
"@modern-js/remark-container": "workspace:*",
"@modern-js/doc-plugin-medium-zoom": "workspace:*",
"@modern-js/utils": "workspace:*",
"@types/compression": "^1.7.2",
"@types/polka": "^0.5.4",
Expand All @@ -79,7 +80,6 @@
"html-to-text": "^9.0.3",
"lodash-es": "^4.17.21",
"mdast-util-mdxjs-esm": "^1.3.0",
"medium-zoom": "1.0.8",
"node-fetch": "3.3.0",
"nprogress": "^0.2.0",
"ora": "5.4.1",
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/doc-core/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from './constants';
import { createModernBuilder } from './createBuilder';
import { writeSearchIndex } from './searchIndex';
import { modifyConfig, beforeBuild, afterBuild } from './hooks';
import { modifyConfig, beforeBuild, afterBuild, loadPlugins } from './hooks';
import { logger } from './utils';
import { APPEARANCE_KEY, normalizeSlash } from '@/shared/utils';
import type { Route } from '@/node/route/RouteService';
Expand Down Expand Up @@ -137,6 +137,8 @@ export async function renderPages(config: UserConfig) {

export async function build(rootDir: string, config: UserConfig) {
const isProd = true;
await loadPlugins(config);

const modifiedConfig = await modifyConfig({
config,
});
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/doc-core/src/node/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { UserConfig } from 'shared/types';
import { removeLeadingSlash } from '../shared/utils';
import { createModernBuilder } from './createBuilder';
import { writeSearchIndex } from './searchIndex';
import { modifyConfig, beforeBuild, afterBuild } from './hooks';
import { modifyConfig, beforeBuild, afterBuild, loadPlugins } from './hooks';

interface ServerInstance {
close: () => Promise<void>;
Expand All @@ -14,7 +14,7 @@ export async function dev(
): Promise<ServerInstance> {
const base = config.doc?.base ?? '';
const isProd = false;

await loadPlugins(config);
try {
const modifiedConfig = await modifyConfig({
config,
Expand Down
50 changes: 40 additions & 10 deletions packages/cli/doc-core/src/node/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { UserConfig, PageIndexInfo, DocPlugin } from 'shared/types';
import { pluginLastUpdated } from './plugins/lastUpdated';
import { AdditionalPage } from '@/shared/types/Plugin';

type HookOptions = {
Expand All @@ -8,20 +7,35 @@ type HookOptions = {
pageData?: PageIndexInfo;
};

function getPlugins(config: UserConfig) {
const plugins: DocPlugin[] = config.doc?.plugins || [];
let docPlugins: DocPlugin[] = [];

// The init function is used to initialize the doc plugins and will execute before the build process.
export async function loadPlugins(config: UserConfig) {
// Clear docPlugins first, for the watch mode
docPlugins = [];
const enableLastUpdated =
config.doc.themeConfig?.lastUpdated ||
config.doc.themeConfig?.locales?.some(locale => locale.lastUpdated);
const mediumZoomConfig = config.doc.mediumZoom ?? true;
if (enableLastUpdated) {
plugins.push(pluginLastUpdated());
const { pluginLastUpdated } = await import('./plugins/lastUpdated');
docPlugins.push(pluginLastUpdated());
}
if (mediumZoomConfig) {
const { pluginMediumZoom } = await import(
'@modern-js/doc-plugin-medium-zoom'
);
docPlugins.push(
pluginMediumZoom(
typeof mediumZoomConfig === 'object' ? mediumZoomConfig : undefined,
),
);
}
return plugins;
docPlugins.push(...(config.doc.plugins || []));
}

export async function modifyConfig(hookOptions: HookOptions) {
const { config } = hookOptions;
const docPlugins = getPlugins(config);

// config hooks
for (const plugin of docPlugins) {
Expand All @@ -35,7 +49,6 @@ export async function modifyConfig(hookOptions: HookOptions) {

export async function beforeBuild(hookOptions: HookOptions) {
const { config, isProd = true } = hookOptions;
const docPlugins = getPlugins(config);

// beforeBuild hooks
return await Promise.all(
Expand All @@ -49,7 +62,6 @@ export async function beforeBuild(hookOptions: HookOptions) {

export async function afterBuild(hookOptions: HookOptions) {
const { config, isProd = true } = hookOptions;
const docPlugins = getPlugins(config);

// afterBuild hooks
return await Promise.all(
Expand All @@ -63,7 +75,6 @@ export async function afterBuild(hookOptions: HookOptions) {

export async function extendPageData(hookOptions: HookOptions): Promise<void> {
const { pageData } = hookOptions;
const docPlugins = getPlugins(hookOptions.config);
// extendPageData hooks
await Promise.all(
docPlugins
Expand All @@ -78,7 +89,6 @@ export async function addPages(
hookOptions: HookOptions,
): Promise<AdditionalPage[]> {
const { config } = hookOptions;
const docPlugins = getPlugins(config);

// addPages hooks
const result = await Promise.all(
Expand All @@ -91,3 +101,23 @@ export async function addPages(

return result.flat();
}

export async function globalUIComponents(): Promise<string[]> {
// globalUIComponents hooks
const result = docPlugins.map(plugin => {
return plugin.globalUIComponents || [];
});

return result.flat();
}

export async function globalStyles(): Promise<string[]> {
// globalStyles hooks
const result = docPlugins
.filter(plugin => typeof plugin.globalStyles === 'string')
.map(plugin => {
return plugin.globalStyles;
});

return result;
}
6 changes: 4 additions & 2 deletions packages/cli/doc-core/src/node/runtimeModule/globalStyles.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { join } from 'path';
import { globalStyles } from '../hooks';
import RuntimeModulesPlugin from './RuntimeModulePlugin';
import { RuntimeModuleID } from '.';
import { UserConfig } from '@/shared/types';

export function globalStylesVMPlugin(
export async function globalStylesVMPlugin(
_scanDir: string,
config: UserConfig,
_isSSR: boolean,
runtimeTempDir: string,
) {
const modulePath = join(runtimeTempDir, `${RuntimeModuleID.GlobalStyles}.js`);
const globalStylesByPlugins = await globalStyles();
const moduleContent = [
config.doc?.globalStyles || '',
...(config.doc?.plugins || []).map(plugin => plugin.globalStyles || ''),
...globalStylesByPlugins,
]
.filter(source => source.length > 0)
.map(source => `import '${source}';`)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { join } from 'path';
import { globalUIComponents } from '../hooks';
import RuntimeModulesPlugin from './RuntimeModulePlugin';
import { RuntimeModuleID } from '.';
import { UserConfig } from '@/shared/types';

export function globalUIComponentsVMPlugin(
export async function globalUIComponentsVMPlugin(
_scanDir: string,
config: UserConfig,
_isSSR: boolean,
Expand All @@ -14,11 +15,10 @@ export function globalUIComponentsVMPlugin(
runtimeTempDir,
`${RuntimeModuleID.GlobalComponents}.js`,
);
const globalUIComponentsByPlugins = await globalUIComponents();
const moduleContent = [
...(config.doc?.globalUIComponents || []),
...(config.doc?.plugins || [])
.map(plugin => plugin.globalUIComponents || [])
.flat(),
...globalUIComponentsByPlugins,
]
.map(source => `import Comp_${index++} from '${source}';`)
.concat(
Expand Down
8 changes: 8 additions & 0 deletions packages/cli/doc-core/src/shared/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,14 @@ export interface DocConfig<ThemeConfig = DefaultThemeConfig> {
* Search options
*/
search?: SearchOptions;
/**
* Whether to enable medium-zoom, default is true
*/
mediumZoom?:
| boolean
| {
selector?: string;
};
}

export type BaseRuntimePageInfo = Omit<
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { MDXProvider } from '@mdx-js/react';
import mediumZoom from 'medium-zoom';
import { Aside } from '../../components/Aside';
import { DocFooter } from '../../components/DocFooter';
import { useLocaleSiteData, useSidebarData } from '../../logic';
Expand All @@ -20,15 +19,6 @@ export interface DocLayoutProps {
afterOutline?: React.ReactNode;
}

function DocContent() {
const { pathname } = useLocation();
useEffect(() => {
const images = document.querySelectorAll('.modern-doc img');
mediumZoom(images);
}, [pathname]);
return <Content />;
}

export function DocLayout(props: DocLayoutProps) {
const { beforeDocFooter, beforeDoc, afterDoc, beforeOutline, afterOutline } =
props;
Expand Down Expand Up @@ -86,7 +76,7 @@ export function DocLayout(props: DocLayoutProps) {
<div className="modern-doc">
<TabDataContext.Provider value={{ tabData, setTabData }}>
<MDXProvider components={getCustomMDXComponent()}>
<DocContent />
<Content />
</MDXProvider>
</TabDataContext.Provider>
<div>
Expand Down
6 changes: 0 additions & 6 deletions packages/cli/doc-core/src/theme-default/styles/base.css
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,6 @@ button:focus-visible {
height: 2px;
}

/* https://github.com/francoischalifour/medium-zoom#debugging */
.medium-zoom-overlay,
.medium-zoom-image--opened {
z-index: 999;
}

:root {
--code-color-text: #414141;
--code-color-background: transparent;
Expand Down
11 changes: 11 additions & 0 deletions packages/cli/doc-plugin-medium-zoom/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module.exports = {
root: true,
extends: ['@modern-js'],
ignorePatterns: ['index.d.ts', 'MediumZoom.tsx'],
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
},
parserOptions: {
project: require.resolve('./tsconfig.json'),
},
};
41 changes: 41 additions & 0 deletions packages/cli/doc-plugin-medium-zoom/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
.DS_Store

.pnp
.pnp.js
.env.local
.env.*.local
.history
.rts*
*.log*
*.pid
*.pid.*
*.report
*.lcov
lib-cov

node_modules/
.npm
.lock-wscript
.yarn-integrity
.node_repl_history
.nyc_output
*.tsbuildinfo
.eslintcache
.sonarlint

dist/
coverage/
release/
output/
output_resource/

.vscode/**/*
!.vscode/settings.json
!.vscode/extensions.json
.idea/

**/*/typings/auto-generated

.changeset/pre.json

.pnpm-store/
37 changes: 37 additions & 0 deletions packages/cli/doc-plugin-medium-zoom/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
.DS_Store

.pnp
.pnp.js
.env.local
.env.*.local
.history
.rts*
*.log*
*.pid
*.pid.*
*.report
*.lcov
lib-cov

node_modules/
.npm
.lock-wscript
.yarn-integrity
.node_repl_history
.nyc_output
*.tsbuildinfo
.eslintcache
.sonarlint

coverage/
release/
output/
output_resource/
tests/

.vscode/**/*
!.vscode/settings.json
!.vscode/extensions.json
.idea/

**/*/api/typings/auto-generated
1 change: 1 addition & 0 deletions packages/cli/doc-plugin-medium-zoom/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
strict-peer-dependencies=false
5 changes: 5 additions & 0 deletions packages/cli/doc-plugin-medium-zoom/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "avoid"
}
1 change: 1 addition & 0 deletions packages/cli/doc-plugin-medium-zoom/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# @modern-js/doc-plugin-medium-zoom
Loading