Skip to content

Commit

Permalink
[gem-book] Fixed <gbp-sandpack> container query
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Jan 2, 2024
1 parent 93b280e commit 13b3501
Show file tree
Hide file tree
Showing 14 changed files with 145 additions and 113 deletions.
5 changes: 4 additions & 1 deletion packages/gem-book/docs/zh/002-guide/003-cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ npx gem-book -h

`gem-book` 命令会自动从项目根目录查找配置文件 `gem-book.cli.json`,支持大部分命令行选项(同时提供时合并命令行选项),例如:

<gbp-raw src="/gem-book.cli.json"><gbp-raw>
<gbp-raw src="gem-book.cli.json" range="1,3-"><gbp-raw>

> [!TIP]
> 使用 json schema: `"$schema": "https://unpkg.com/gem-book/schema.json"`
## 命令行选项

Expand Down
2 changes: 1 addition & 1 deletion packages/gem-book/docs/zh/002-guide/004-metadata.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ sidebarIgnore: true

[首页](./003-cli.md#--home-mode)还支持 `hero` `features`,例如:

<gbp-raw src="docs/en/README.md" range="1-19"></gbp-raw>
<gbp-raw src="docs/zh/README.md" range="1-19"></gbp-raw>

## 重定向

Expand Down
2 changes: 1 addition & 1 deletion packages/gem-book/docs/zh/002-guide/006-deploy.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 部署

只需要使用 `--build` 构建前端资源(`index.html``gem-book.json`...),然后为输出目录提供静态服务即可。
只需要使用 `--build` 构建前端资源(`index.html``*.js`...),然后为输出目录提供静态服务即可。

> [!WARNING]
> 由于 `<gem-book>` 使用了 [History API](https://developer.mozilla.org/en-US/docs/Web/API/History),所以默认不支持 Github Pages
Expand Down
2 changes: 1 addition & 1 deletion packages/gem-book/docs/zh/002-guide/007-extension.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ gem-book docs --plugin raw
然后在 Markdown 中使用它来渲染仓库中的文件:

```md
<gbp-raw src="/src/plugins/raw.ts"></gbp-raw>
<gbp-raw src="src/plugins/raw.ts"></gbp-raw>
```

[这里](../003-plugins.md)查看所有内置插件。
Expand Down
2 changes: 1 addition & 1 deletion packages/gem-book/docs/zh/002-guide/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ GemBook 将 [Markdown](https://zh.wikipedia.org/wiki/Markdown) 内容渲染成
# 创建文档
mkdir docs && echo '# Hello <gem-book>!' > docs/readme.md

# 启动本地服务打开文档站,修改文档将自动刷新
# 启动本地服务打开文档站,修改文档将自动更新
npx gem-book docs

# 指定标题
Expand Down
6 changes: 3 additions & 3 deletions packages/gem-book/docs/zh/003-plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,20 @@ yarn add gem-book

用于显示远端代码,如果提供的 `src` 只包含路径,则会从当前项目的 GitHub 上读取内容(受 [`sourceDir`](./002-guide/003-cli.md#--source-dir)[`sourceBranch`](./002-guide/003-cli.md#--source-branch) 影响),比如:

<gbp-raw src="package.json" range="2-3,-6--4" highlight="89"><gbp-raw>
<gbp-raw src="package.json" range="2-3,-4--6" highlight="-5"><gbp-raw>

```md
<!-- `range` 指定显示的范围,支持使用负数 -->

<gbp-raw src="package.json" range="2-3,-6--4" highlight="89"><gbp-raw>
<gbp-raw src="package.json" range="2-3,-4--6" highlight="-5"><gbp-raw>
```

## `<gbp-media>`

显示远端多媒体内容,比如图片,视频,获取资源方式和 `<gbp-raw>` 一样:

```md
<gbp-media src="/preview.png"></gbp-media>
<gbp-media src="preview.png"></gbp-media>
```

## `<gbp-import>`
Expand Down
15 changes: 8 additions & 7 deletions packages/gem-book/src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ function readConfig(fullPath: string) {
}
}
});

if (cliConfig.debug) inspectObject(cliConfig);

obj.nav = obj.nav?.filter((e) => {
if (e.title?.toLowerCase() === 'github') {
bookConfig.github = e.link;
Expand Down Expand Up @@ -231,7 +234,7 @@ async function generateBookConfig(dir: string) {
}
}
// eslint-disable-next-line no-console
console.log(`${new Date().toISOString()} <gem-book> config file updated! ${Date.now() - t}ms`);
console.log(`${new Date().toISOString()} book config updated! ${Date.now() - t}ms`);
}

program
Expand Down Expand Up @@ -361,16 +364,14 @@ program

await generateBookConfig(dir);

if (cliConfig.debug) inspectObject(cliConfig);

let server = cliConfig.json ? undefined : startBuilder(dir, cliConfig, bookConfig);
let themeWatcher = watchTheme();

if (server) {
if (!cliConfig.build) {
devServerEventTarget.addEventListener(UPDATE_EVENT, ({ detail }: CustomEvent<string>) => {
server?.sendMessage(server.webSocketServer?.clients || [], UPDATE_EVENT, detail);
});

let themeWatcher = watchTheme();
if (configPath) {
fs.watch(
configPath,
Expand All @@ -380,7 +381,7 @@ program
bookConfig = structuredClone(initBookConfig);
readConfig(configPath);
await generateBookConfig(dir);
server!.stopCallback(() => {
server?.stopCallback(() => {
server = startBuilder(dir, cliConfig, bookConfig);
devServerEventTarget.dispatchEvent(
Object.assign(new Event(UPDATE_EVENT), {
Expand All @@ -391,7 +392,7 @@ program
themeWatcher = watchTheme();
});
},
100,
300,
{ trailing: true },
),
);
Expand Down
1 change: 0 additions & 1 deletion packages/gem-book/src/element/elements/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ export class Main extends GemElement {
width: 100%;
box-sizing: border-box;
z-index: 1;
container-type: inline-size;
}
:host > :first-child {
margin-top: 0;
Expand Down
6 changes: 2 additions & 4 deletions packages/gem-book/src/element/elements/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export class GemBookPluginElement<T = any> extends GemElement<T> {
@globalemitter error: Emitter<ErrorEvent | Event> = console.error;

Check warning on line 58 in packages/gem-book/src/element/elements/plugin.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

/**获取资源的远端 GitHub raw 地址,如果使用 `DEV_MODE`,则返回本机服务的 URL */
getRemoteURL(originSrc = '') {
getRemoteURL(originSrc = '', dev = GemBookPluginElement.devMode) {
const config = GemBookPluginElement.config;
let url = originSrc;
if (originSrc && !/^(https?:)?\/\//.test(originSrc)) {
Expand All @@ -67,9 +67,7 @@ export class GemBookPluginElement<T = any> extends GemElement<T> {
const repo = new URL(config.github).pathname;
const src = `${originSrc.startsWith('/') ? '' : '/'}${originSrc}`;
const basePath = config.base ? `/${config.base}` : '';
url = GemBookPluginElement.devMode
? `/_assets${src}`
: `${rawOrigin}${repo}/${config.sourceBranch}${basePath}${src}`;
url = dev ? `/_assets${src}` : `${rawOrigin}${repo}/${config.sourceBranch}${basePath}${src}`;
}
return url;
}
Expand Down
109 changes: 64 additions & 45 deletions packages/gem-book/src/element/elements/pre.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ export class Pre extends GemElement {
@attribute status: 'hidden' | 'active' | '';
@boolattribute editable: boolean;
@boolattribute linenumber: boolean;
@boolattribute headless: boolean;

@refobject codeRef: RefObject<HTMLElement>;

Expand All @@ -232,6 +233,10 @@ export class Pre extends GemElement {
return !!this.range || this.linenumber;
}

get #headless() {
return !this.filename || this.headless;
}

constructor() {
super();
new MutationObserver(() => this.update()).observe(this, {
Expand All @@ -243,7 +248,7 @@ export class Pre extends GemElement {

#getRanges(range: string, lines: string[]) {
const len = lines.length;
const ranges = range.split(/,\s*/);
const ranges = range.trim().split(/\s*,\s*/);
return ranges.map((range) => {
// 第二位可以省略,第一位不行
// 3-4
Expand All @@ -256,7 +261,7 @@ export class Pre extends GemElement {
const [startStr, endStr = startStr] = range.split(/(?<!-|^)-/);
const [start, end] = [parseInt(startStr) || 1, parseInt(endStr) || 0];
// 包含首尾
return [start < 0 ? len + start + 1 : start, end < 0 ? len + end + 1 : end || len];
return [start < 0 ? len + start + 1 : start, end < 0 ? len + end + 1 : end || len].sort((a, b) => a - b);
});
}

Expand Down Expand Up @@ -396,15 +401,29 @@ export class Pre extends GemElement {
display: none;
}
:host {
display: block;
font-family: ${theme.codeFont};
background: rgba(${theme.textColorRGB}, 0.05);
}
.filename {
font-size: 0.75em;
padding: 1rem;
line-height: 1;
border-bottom: 1px solid ${theme.borderColor};
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
color: rgba(${theme.textColorRGB}, 0.5);
}
.container {
height: 100%;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: currentColor;
position: relative;
display: flex;
font-size: 0.875em;
font-family: ${theme.codeFont};
line-height: ${lineHeight};
background: rgba(${theme.textColorRGB}, 0.05);
--comment-color: var(--code-comment-color, #6e6e6e);
--section-color: var(--code-section-color, #c9252d);
--title-color: var(--code-title-color, #4646c6);
Expand All @@ -417,6 +436,7 @@ export class Pre extends GemElement {
}
.gem-code,
.linenumber {
padding: ${padding};
box-sizing: border-box;
min-height: 100%;
height: max-content;
Expand All @@ -427,12 +447,9 @@ export class Pre extends GemElement {
scrollbar-color: currentColor;
font-family: inherit;
flex-grow: 1;
box-sizing: border-box;
display: block;
text-align: left;
white-space: pre;
tab-size: 2;
padding: ${padding};
hyphens: none;
overflow-clip-box: content-box;
box-shadow: none;
Expand All @@ -445,8 +462,7 @@ export class Pre extends GemElement {
display: inline-flex;
flex-direction: column;
flex-shrink: 0;
padding: 1em;
min-width: 1em;
min-width: 3.5em;
text-align: right;
border-right: 1px solid ${theme.borderColor};
color: rgba(${theme.textColorRGB}, 0.5);
Expand Down Expand Up @@ -558,42 +574,45 @@ export class Pre extends GemElement {
}
}
</style>
${lineNumbersParts
.reduce((p, c) => p.concat(Array(IGNORE_LINE)).concat(c))
.map((linenumber, index) =>
highlightLineSet.has(linenumber)
? html`
<span
class="gem-highlight"
style=${styleMap({
top: `calc(${index} * ${lineHeight} + ${padding})`,
})}
></span>
`
: '',
)}
${this.#linenumber
? html`
<div class="linenumber">
${lineNumbersParts.map(
(numbers, index, arr) => html`
${numbers.map((n) => html`<span>${n}</span>`)}${arr.length - 1 !== index
? html`<span class="linenumber-ignore"></span>`
: ''}
`,
)}
</div>
`
: ''}
<code
ref=${this.codeRef.ref}
class="gem-code"
contenteditable=${this.editable ? contenteditableValue : false}
@compositionstart=${this.#compositionstartHandle}
@compositionend=${this.#compositionendHandle}
@input=${this.#onInput}
>${parts.join('\n'.repeat(IGNORE_LINE + 1))}</code
>
${!this.#headless ? html`<div class="filename">${this.filename}</div>` : ''}
<div class="container">
${lineNumbersParts
.reduce((p, c) => p.concat(Array(IGNORE_LINE)).concat(c))
.map((linenumber, index) =>
highlightLineSet.has(linenumber)
? html`
<span
class="gem-highlight"
style=${styleMap({
top: `calc(${index} * ${lineHeight} + ${padding})`,
})}
></span>
`
: '',
)}
${this.#linenumber
? html`
<div class="linenumber">
${lineNumbersParts.map(
(numbers, index, arr) => html`
${numbers.map((n) => html`<span>${n}</span>`)}${arr.length - 1 !== index
? html`<span class="linenumber-ignore"></span>`
: ''}
`,
)}
</div>
`
: ''}
<code
ref=${this.codeRef.ref}
class="gem-code"
contenteditable=${this.editable ? contenteditableValue : false}
@compositionstart=${this.#compositionstartHandle}
@compositionend=${this.#compositionendHandle}
@input=${this.#onInput}
>${parts.join('\n'.repeat(IGNORE_LINE + 1))}</code
>
</div>
`;
}
}
10 changes: 6 additions & 4 deletions packages/gem-book/src/plugins/code-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ customElements.whenDefined('gem-book').then(() => {
width: 1em;
}
::slotted(*) {
display: none;
background: rgba(${theme.textColorRGB}, 0.03);
margin: 0 !important;
border-radius: 0 !important;
Expand All @@ -90,10 +89,13 @@ customElements.whenDefined('gem-book').then(() => {

#parseContents = () => {
return [...this.querySelectorAll<Pre>('gem-book-pre')].map((element) => {
const filename = element.getAttribute('filename') || '';
element.dataset.filename = filename;
element.setAttribute('headless', '');
return {
element,
filename,
code: element.textContent,
filename: element.getAttribute('filename') || '',
lang: element.getAttribute('codelang') || '',
status: element.getAttribute('status') || '',
} as File;
Expand Down Expand Up @@ -146,8 +148,8 @@ customElements.whenDefined('gem-book').then(() => {
</div>
<slot></slot>
<style>
::slotted([filename='${currentFile?.filename}']) {
display: block;
::slotted(:not([data-filename='${currentFile?.filename}'])) {
display: none;
}
</style>
`;
Expand Down
7 changes: 6 additions & 1 deletion packages/gem-book/src/plugins/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,12 @@ customElements.whenDefined('gem-book').then(() => {
};

mounted = () => {
Promise.all(this.src.split(',').map((src) => this.#loadResource(src)))
Promise.all(
this.src
.trim()
.split(/\s*,\s*/)
.map((src) => this.#loadResource(src)),
)
.then(() => {
this.setState({ loading: false, error: false });
})
Expand Down
Loading

0 comments on commit 13b3501

Please sign in to comment.