Skip to content

Commit

Permalink
[gem-book] Improve onlyFile
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Jan 1, 2024
1 parent d79c8ff commit 7d620ba
Show file tree
Hide file tree
Showing 8 changed files with 39 additions and 41 deletions.
6 changes: 2 additions & 4 deletions packages/gem-book/src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ const cliConfig: Required<CliUniqueConfig> = {
build: false,
json: false,
debug: false,
onlyFile: false,
};

function readConfig(configPath: string) {
Expand Down Expand Up @@ -105,7 +104,7 @@ function readFiles(filenames: string[], dir: string, link: string, config?: Fron
if (cliConfig.debug) {
checkRelativeLink(fullPath, docsRootDir);
}
const { title, headings, isNav, navTitle, navOrder, sidebarIgnore, hero, features, redirect } = getMetadata(
const { title, isNav, navTitle, navOrder, sidebarIgnore, hero, features, redirect } = getMetadata(
fullPath,
bookConfig.displayRank,
);
Expand All @@ -114,7 +113,6 @@ function readFiles(filenames: string[], dir: string, link: string, config?: Fron
type: 'file',
link: `${link}${filename}`,
hash: getHash(fullPath),
children: cliConfig.onlyFile ? undefined : headings,
isNav,
navTitle,
sidebarIgnore,
Expand Down Expand Up @@ -308,7 +306,7 @@ program
cliConfig.json = true;
})
.option('--only-file', 'not include heading navigation', () => {
cliConfig.debug = true;
bookConfig.onlyFile = true;
})
.option('--debug', 'enabled debug mode', () => {
cliConfig.debug = true;
Expand Down
22 changes: 3 additions & 19 deletions packages/gem-book/src/bin/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,7 @@ export function getHash(fullPath: string) {
return hash.digest('hex').substring(0, 8);
}

type FileMetadata = FrontMatter & {
title: string;
headings?: NavItem[];
};

export function getMetadata(fullPath: string, displayRank: boolean | undefined): FileMetadata {
export function getMetadata(fullPath: string, displayRank: boolean | undefined) {
const getTitle = () => {
const basename = path.basename(fullPath);
if (isIndexFile(basename)) return '';
Expand All @@ -143,24 +138,13 @@ export function getMetadata(fullPath: string, displayRank: boolean | undefined):
};
const parseMd = (fullPath: string) => {
const md = readFileSync(fullPath, 'utf8');
const { attributes, body } = fm<FileMetadata>(md);
const { attributes, body } = fm<FrontMatter>(md);
const html = marked(body);
const { window } = new JSDOM(html);
const h1 = window.document.querySelector('h1');
const h2s = window.document.querySelectorAll('h2');
return {
...(attributes as FileMetadata),
...(attributes as FrontMatter),
title: (attributes.title || h1?.textContent || getTitle()).match(CUSTOM_HEADING_REG)![1],
headings: h2s.length
? [...h2s].map((heading) => {
const [, text, customId] = (heading.textContent as string).match(CUSTOM_HEADING_REG) as RegExpMatchArray;
return {
title: text,
link: `#${normalizeId(customId || text)}`,
type: 'heading',
} as NavItem;
})
: undefined,
};
};

Expand Down
2 changes: 1 addition & 1 deletion packages/gem-book/src/common/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type BookConfig = {
sidebar: SidebarConfig;
// navbar icon absolute path
icon?: string;
onlyFile?: boolean;
} & CommonConfig;

export interface CliUniqueConfig {
Expand All @@ -44,7 +45,6 @@ export interface CliUniqueConfig {
theme?: string;
build?: boolean;
json?: boolean;
onlyFile?: boolean;
debug?: boolean;
}

Expand Down
28 changes: 19 additions & 9 deletions packages/gem-book/src/element/elements/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
useStore,
refobject,
RefObject,
history,
} from '@mantou/gem';
import { mediaQuery } from '@mantou/gem/helper/mediaquery';

Expand All @@ -20,6 +21,7 @@ import { bookStore, locationStore } from '../store';
import { GemBookElement } from '..';

import { icons } from './icons';
import { tocStore } from './toc';

import '@mantou/gem/elements/link';
import '@mantou/gem/elements/use';
Expand All @@ -31,6 +33,7 @@ export const [sidebarStore, updateSidebarStore] = useStore({ open: false });
@customElement('gem-book-sidebar')
@connectStore(bookStore)
@connectStore(sidebarStore)
@connectStore(tocStore)
export class SideBar extends GemElement {
@refobject navRef: RefObject<HTMLElement>;

Expand Down Expand Up @@ -60,8 +63,9 @@ export class SideBar extends GemElement {
{ type = 'file', link, title, children, sidebarIgnore }: NavItem,
isTop = false,
): TemplateResult | null => {
const { path } = history.getParams();
const { homePage, config } = bookStore;
const homeMode = config?.homeMode;
const { homeMode, onlyFile } = config || {};
if (sidebarIgnore || (homeMode && homePage === link)) {
return html`<!-- No need to render homepage item -->`;
}
Expand All @@ -82,23 +86,29 @@ export class SideBar extends GemElement {
return html`
<gem-book-side-link
class=${classMap({ item: true, link: true, single: isTop, [type]: true })}
pattern=${children ? new URL(link, location.origin).pathname : link}
pattern=${link}
href=${link}
>
${title ? capitalize(title) : 'No title'}
</gem-book-side-link>
${children
? html`<div class="links item hash">${children.map((item) => this.#renderItem(item))}</div>`
${!onlyFile && path === link
? html`<div class="links item hash">
${tocStore.elements
.filter((e) => e.tagName === 'H2')
.map((h) =>
this.#renderItem({
type: 'heading',
title: h.textContent || '',
link: `#${h.id}`,
}),
)}
</div>`
: null}
`;
}
case 'heading': {
return html`
<gem-book-side-link
class=${classMap({ item: true, link: true, single: isTop, [type]: true })}
hash=${link}
href=${link}
>
<gem-book-side-link class=${classMap({ item: true, link: true, single: isTop, [type]: true })} hash=${link}>
# ${title ? capitalize(title) : 'No title'}
</gem-book-side-link>
`;
Expand Down
4 changes: 2 additions & 2 deletions packages/gem-book/src/element/elements/toc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { theme, themeStore } from '../helper/theme';

import '@mantou/gem/elements/link';

export const [tocStore, updateTocStore] = useStore<{ elements: HTMLHeadingElement[] }>({
elements: [],
export const [tocStore, updateTocStore] = useStore({
elements: [] as HTMLHeadingElement[],
});

type State = {
Expand Down
9 changes: 7 additions & 2 deletions packages/gem/src/elements/base/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,16 @@ export class GemLinkElement extends GemElement {
history.pushIgnoreCloseHandle({
path: pathname,
query: search,
hash: hash,
hash,
title: this.docTitle,
});
} else {
history.pushIgnoreCloseHandle({ path: this.path, query: this.query, hash: this.hash, title: this.docTitle });
history.pushIgnoreCloseHandle({
path: this.path,
query: this.query,
hash: this.hash,
title: this.docTitle,
});
}
};

Expand Down
6 changes: 3 additions & 3 deletions packages/gem/src/lib/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ function normalizeParams(params: UpdateHistoryParams): HistoryParams {
const title = params.title || (pathChanged ? '' : document.title);
const statusChanged = params.close || params.data || params.open || params.shouldClose;
// 没提供 hash 又没有改变 URL 又不是状态更新时使用当前 hash
const hash = params.hash || (!pathChanged && statusChanged ? decodeURIComponent(location.hash) : '');
const hash = decodeURIComponent(params.hash ? params.hash : !pathChanged && statusChanged ? location.hash : '');
return { ...params, title, path, query, hash };
}

Expand Down Expand Up @@ -190,7 +190,7 @@ if (!window._GEMHISTORY) {
// 点击 `<a>`
window.addEventListener('hashchange', ({ isTrusted }) => {
if (isTrusted) {
gemHistory.replace({ hash: decodeURIComponent(location.hash) });
gemHistory.replace({ hash: location.hash });
}
});

Expand Down Expand Up @@ -254,7 +254,7 @@ if (!window._GEMHISTORY) {
paramsMap.set(newState.$key, {
path: pathname,
query: new QueryString(search),
hash,
hash: encodeURIComponent(hash),
title: newState.$title, // document.title 是导航前的
data: newState,
});
Expand Down
3 changes: 2 additions & 1 deletion packages/gem/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ export function addMicrotaskToStack(func: () => void) {
microtaskStack.push(func);
}

// 不编码 hash 用于比较
export function absoluteLocation(currentPath = '', relativePath = '') {
const { pathname, search, hash } = new URL(relativePath, location.origin + currentPath);
return pathname + search + hash;
return pathname + search + decodeURIComponent(hash);
}

// eslint-disable-next-line @typescript-eslint/ban-types
Expand Down

0 comments on commit 7d620ba

Please sign in to comment.