Skip to content

Commit

Permalink
add new Code component
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott committed Aug 23, 2021
1 parent 3ab89e0 commit acb88f1
Show file tree
Hide file tree
Showing 21 changed files with 124 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/perfect-emus-hear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Add new `<Code>` component, powered by the more modern shiki syntax highlighter.
2 changes: 1 addition & 1 deletion docs/src/pages/bg/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ _Бележка: някои функционалности (например: Fa

### API Справка

Тази секция е полезна, когато искате да научите повече детайли относно даден Astro API. Например - [Конфигурационната справка](/reference/configuration-reference) изброява всички възможни конфигурационни опции. [Справката за вградени компоненти](/reference/builtin-components) изброява всички възможни базови (core) компоненти, като `<Markdown />` и `<Prism />`.
Тази секция е полезна, когато искате да научите повече детайли относно даден Astro API. Например - [Конфигурационната справка](/reference/configuration-reference) изброява всички възможни конфигурационни опции. [Справката за вградени компоненти](/reference/builtin-components) изброява всички възможни базови (core) компоненти, като `<Markdown />` и `<Code />`.

### Версия на документацията

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/de/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Unsere Anleitung zu [Astro Komponenten](/core-concepts/astro-components) sollte

Dieser Dokumentationsabschnitt sollte für dich nützlich sein, wenn du mehr Details über eine bestimme Astro API erfahren möchtest.

So listet z.B. die [Konfigurations Dokumentation](/reference/configuration-reference) alle möglichen Konfigurationseigenschaften auf, die dir zur Verfügung stehen. In der [Dokumentation über eingebaute Komponenten](/reference/builtin-components) findest du alle verfügbaren Kernkomponenten wie `<Markdown />` und `<Prism />`.
So listet z.B. die [Konfigurations Dokumentation](/reference/configuration-reference) alle möglichen Konfigurationseigenschaften auf, die dir zur Verfügung stehen. In der [Dokumentation über eingebaute Komponenten](/reference/builtin-components) findest du alle verfügbaren Kernkomponenten wie `<Markdown />` und `<Code />`.

### Versionierte Dokumentation

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/es/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Nuestra guía sobre [componentes Astro](https://docs.astro.build/core-concepts/a

### Referencia de la API

Esta sección de documentación es útil cuando deseas obtener más detalles sobre una API de Astro en particular. Por ejemplo, la [referencia de configuración](https://docs.astro.build/reference/configuration-reference) enumera todas las opciones de configuración disponibles. La [referencia de componentes incluidos](https://docs.astro.build/reference/builtin-components) enumera todos los componentes básicos disponibles, como `<Markdown/>` y `<Prism/>`.
Esta sección de documentación es útil cuando deseas obtener más detalles sobre una API de Astro en particular. Por ejemplo, la [referencia de configuración](https://docs.astro.build/reference/configuration-reference) enumera todas las opciones de configuración disponibles. La [referencia de componentes incluidos](https://docs.astro.build/reference/builtin-components) enumera todos los componentes básicos disponibles, como `<Markdown />` y `<Code />`.

### Documentación versionada

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/fi/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Oppaamme [Astron komponenteista](/core-concepts/astro-components) esittelee uude

### API-luettelo

Tämä dokumentaation osa on hyödyllisin halutessasi oppia yksityiskohtia tietystä Astron rajapinnasta. Muun muassa [asetusluettelo](/reference/configuration-reference) listaa kaikki mahdolliset asetusvaihtoehdot. [Ydinkomponenttien luettelo](/reference/builtin-components) listaa kaikki käytössä olevat Astron mukana tulevat komponentit kuten `<Markdown />` ja `<Prism />`.
Tämä dokumentaation osa on hyödyllisin halutessasi oppia yksityiskohtia tietystä Astron rajapinnasta. Muun muassa [asetusluettelo](/reference/configuration-reference) listaa kaikki mahdolliset asetusvaihtoehdot. [Ydinkomponenttien luettelo](/reference/builtin-components) listaa kaikki käytössä olevat Astron mukana tulevat komponentit kuten `<Markdown />` ja `<Code />`.

### Dokumentaation versioinnista

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/fr/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Notre guide sur les [composants Astro](/core-concepts/astro-components) vous pr

### Documentation de l'API

Cette documentation vous sera utile si vous souhaitez comprendre en détails certaines API d'Astro. Par exemple, la [Documentation de la Configuration](/reference/configuration-reference) liste toutes les options de configuration à votre disposition. La [Documentation des Composants de base](/reference/builtin-components) liste tous les composants disponibles de base, comme `<Markdown />` et `<Prism />`.
Cette documentation vous sera utile si vous souhaitez comprendre en détails certaines API d'Astro. Par exemple, la [Documentation de la Configuration](/reference/configuration-reference) liste toutes les options de configuration à votre disposition. La [Documentation des Composants de base](/reference/builtin-components) liste tous les composants disponibles de base, comme `<Markdown />` et `<Code />`.

### Documentation versionnée

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Our helpful guide on [Astro components](/core-concepts/astro-components) introdu

### API Reference

This documentation section is useful when you want to learn more details about a particular Astro API. For example, [Configuration Reference](/reference/configuration-reference) lists all possible configuration options available to you. [Built-in Components Reference](/reference/builtin-components) lists all available core components, like `<Markdown />` and `<Prism />`.
This documentation section is useful when you want to learn more details about a particular Astro API. For example, [Configuration Reference](/reference/configuration-reference) lists all possible configuration options available to you. [Built-in Components Reference](/reference/builtin-components) lists all available core components, like `<Markdown />` and `<Code />`.

### Versioned Documentation

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/nl/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Onze gids over [Astro-componenten](/core-concepts/astro-components) helpt je doo

### API referentie

Deze documentatiesectie is handig als je meer details wilt weten over een bepaalde Astro API. [Configuratie referentie](/reference/configuration-reference) vermeldt bijvoorbeeld alle mogelijke configuratieopties die beschikbaar zijn. [Ingebouwde Componenten Referentie](/reference/builtin-components) geeft een overzicht van alle beschikbare kerncomponenten, zoals <Markdown /> en <Prism />.
Deze documentatiesectie is handig als je meer details wilt weten over een bepaalde Astro API. [Configuratie referentie](/reference/configuration-reference) vermeldt bijvoorbeeld alle mogelijke configuratieopties die beschikbaar zijn. [Ingebouwde Componenten Referentie](/reference/builtin-components) geeft een overzicht van alle beschikbare kerncomponenten, zoals <Markdown /> en <Code />.

### Documentatie versies

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/pt-br/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Nosso guia útil em [componentes Astro](/core-concepts/astro-components) apresen

### Referência da API

Esta seção de documentação é útil quando você deseja aprender mais detalhes sobre uma determinada API do Astro. Por exemplo, [Referência de Configuração](/reference/configuration-reference) lista todas as opções de configuração possíveis disponíveis para você. [Referência de componentes incorporados](/reference/builtin-components) listas todos os componentes base disponíveis, como `<Markdown />` e `<Prism />`.s
Esta seção de documentação é útil quando você deseja aprender mais detalhes sobre uma determinada API do Astro. Por exemplo, [Referência de Configuração](/reference/configuration-reference) lista todas as opções de configuração possíveis disponíveis para você. [Referência de componentes incorporados](/reference/builtin-components) listas todos os componentes base disponíveis, como `<Markdown />` e `<Code />`.s

### Documentação por Versão

Expand Down
13 changes: 9 additions & 4 deletions docs/src/pages/reference/builtin-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,21 @@ See our [Markdown Guide](/guides/markdown-content) for more info.

<!-- TODO: We should move some of the specific component info here. -->

## `<Prism />`
## `<Code />`

```astro
---
import { Prism } from 'astro/components';
import { Code } from 'astro/components';
---
<Prism code={`const foo = 'bar';`} />
<!-- Syntax highlight some JavaScript code. -->
<Code code={`const foo = 'bar';`} lang="js" />
<!-- Optional: customize your theme. -->
<Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" />
```

This component provides syntax highlighting for code blocks. Since this never changes in the client it makes sense to use an Astro component (it's equally reasonable to use a framework component for this kind of thing; Astro is server-only by default for all frameworks!).
This component provides syntax highlighting for code blocks at build time (no client-side JavaScript included). The component is powered internally by shiki and it supports all popular [themes](https://github.com/shikijs/shiki/blob/main/docs/themes.md) and [languages](https://github.com/shikijs/shiki/blob/main/docs/languages.md).

You can also use the `<Prism />` component for syntax highlighting powered by the [Prism](https://prismjs.com/) syntax highlighting library. However, this component is deprecated and will be removed in our v1.0 release.

## `<Debug />`

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/zh-CN/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Astro 是一个现代的静态网站生成工具. 你可以从 [我们的主页]

### API 参考文档

当你想了解某个特定的 Astro API 的更多细节时,这部分文档是有用的。例如 [配置参考](/reference/configuration-reference) 列出所有可能的配置选项供你使用。 [内置组件参考](/reference/builtin-components) 列出了所有可用的核心组件,如`<Markdown />``<Prism />`
当你想了解某个特定的 Astro API 的更多细节时,这部分文档是有用的。例如 [配置参考](/reference/configuration-reference) 列出所有可能的配置选项供你使用。 [内置组件参考](/reference/builtin-components) 列出了所有可用的核心组件,如`<Markdown />``<Code />`

### 其他版本文档

Expand Down
2 changes: 1 addition & 1 deletion docs/src/pages/zh-TW/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Astro 是利用現代技術的靜態網站生成工具。可以從[首頁](https

### API 參考手冊

如果想要深入探討某個 Astro API,這部分的文件會很有幫助。例如:[設定參考](/reference/configuration-reference)列出所有可以使用的設定選項。[內建元件參考](/reference/builtin-components)列出所有可以使用的核心元件,像是 `<Markdown />``<Prism />`
如果想要深入探討某個 Astro API,這部分的文件會很有幫助。例如:[設定參考](/reference/configuration-reference)列出所有可以使用的設定選項。[內建元件參考](/reference/builtin-components)列出所有可以使用的核心元件,像是 `<Markdown />``<Code />`

### 先前版本的文件

Expand Down
9 changes: 9 additions & 0 deletions packages/astro/components/Code.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
import shiki from 'shiki';
const { code, lang = 'plaintext', theme = 'nord' } = Astro.props;
const highlighter = await shiki.getHighlighter({theme});
const html = highlighter.codeToHtml(code, lang);
---
{html}
1 change: 1 addition & 0 deletions packages/astro/components/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as Markdown } from './Markdown.astro';
export { default as Prism } from './Prism.astro';
export { default as Code } from './Code.astro';
1 change: 1 addition & 0 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"rollup-plugin-terser": "^7.0.2",
"sass": "^1.32.13",
"semver": "^7.3.5",
"shiki": "^0.9.7",
"shorthash": "^0.0.2",
"slash": "^4.0.0",
"snowpack": "^3.8.6",
Expand Down
37 changes: 37 additions & 0 deletions packages/astro/test/astro-component-code.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { suite } from 'uvu';
import * as assert from 'uvu/assert';
import { doc } from './test-utils.js';
import { setup, setupBuild } from './helpers.js';

const Components = suite('<Code>');

setup(Components, './fixtures/astro-component-code');

Components('<Code> without lang or theme', async ({ runtime }) => {
let result = await runtime.load('/no-lang');
assert.ok(!result.error, `build error: ${result.error}`);
const $ = doc(result.contents);
assert.equal($('pre').length, 1);
assert.equal($('pre').attr('style'), 'background-color: #2e3440ff', 'applies default theme');
assert.equal($('pre > code').length, 1);
assert.ok($('pre > code span').length > 1, 'contains some generated spans');
});

Components('<Code lang="...">', async ({ runtime }) => {
let result = await runtime.load('/basic');
assert.ok(!result.error, `build error: ${result.error}`);
const $ = doc(result.contents);
assert.equal($('pre').length, 1);
assert.equal($('pre > code').length, 1);
assert.ok($('pre > code span').length > 6, 'contains many generated spans');
});

Components('<Code theme="...">', async ({ runtime }) => {
let result = await runtime.load('/custom-theme');
assert.ok(!result.error, `build error: ${result.error}`);
const $ = doc(result.contents);
assert.equal($('pre').length, 1);
assert.equal($('pre').attr('style'), 'background-color: #1E1E1E', 'applies custom theme');
});

Components.run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"workspaceRoot": "../../../../../"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
import {Code} from 'astro/components';
---
<html>
<head><title>Code component</title></head>
<body>
<Code code="console.log('hello world');" lang="js" />
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
import {Code} from 'astro/components';
---
<html>
<head><title>Code component</title></head>
<body>
<Code code="console.log('hello world');" lang="js" theme="dark-plus" />
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
import {Code} from 'astro/components';
---
<html>
<head><title>Code component</title></head>
<body>
<Code code="console.log('hello world');" />
</body>
</html>
23 changes: 22 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6047,7 +6047,7 @@ json5@^1.0.1:
dependencies:
minimist "^1.2.0"

json5@^2.1.2:
json5@^2.1.2, json5@^2.2.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.0.tgz#2dfefe720c6ba525d9ebd909950f0515316c89a3"
integrity sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==
Expand Down Expand Up @@ -7587,6 +7587,13 @@ onetime@^5.1.0, onetime@^5.1.2:
dependencies:
mimic-fn "^2.1.0"

onigasm@^2.2.5:
version "2.2.5"
resolved "https://registry.yarnpkg.com/onigasm/-/onigasm-2.2.5.tgz#cc4d2a79a0fa0b64caec1f4c7ea367585a676892"
integrity sha512-F+th54mPc0l1lp1ZcFMyL/jTs2Tlq4SqIHKIXGZOR/VkHkF9A7Fr5rRr5+ZG/lWeRsyrClLYRq7s/yFQ/XhWCA==
dependencies:
lru-cache "^5.1.1"

only@~0.0.2:
version "0.0.2"
resolved "https://registry.yarnpkg.com/only/-/only-0.0.2.tgz#2afde84d03e50b9a8edc444e30610a70295edfb4"
Expand Down Expand Up @@ -9173,6 +9180,15 @@ shell-quote@^1.6.1:
resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.7.2.tgz#67a7d02c76c9da24f99d20808fcaded0e0e04be2"
integrity sha512-mRz/m/JVscCrkMyPqHc/bczi3OQHkLTqXHEFu0zDhK/qfv3UcOA4SVmRCLmos4bhjr9ekVQubj/R7waKapmiQg==

shiki@^0.9.7:
version "0.9.7"
resolved "https://registry.yarnpkg.com/shiki/-/shiki-0.9.7.tgz#9c760254798a9bbc6df52bbd26f888486f780079"
integrity sha512-rOoAmwRWDiGKjQ1GaSKmbp1J5CamCera+I+DMM3wG/phbwNYQPt1mrjBBZbK66v80Vl1/A9TTLgXVHMbgtOCIQ==
dependencies:
json5 "^2.2.0"
onigasm "^2.2.5"
vscode-textmate "5.2.0"

shorthash@^0.0.2:
version "0.0.2"
resolved "https://registry.yarnpkg.com/shorthash/-/shorthash-0.0.2.tgz#59b268eecbde59038b30da202bcfbddeb2c4a4eb"
Expand Down Expand Up @@ -10614,6 +10630,11 @@ vscode-nls@^5.0.0:
resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-5.0.0.tgz#99f0da0bd9ea7cda44e565a74c54b1f2bc257840"
integrity sha512-u0Lw+IYlgbEJFF6/qAqG2d1jQmJl0eyAGJHoAJqr2HT4M2BNuQYSEiSE75f52pXHSJm8AlTjnLLbBFPrdz2hpA==

vscode-textmate@5.2.0:
version "5.2.0"
resolved "https://registry.yarnpkg.com/vscode-textmate/-/vscode-textmate-5.2.0.tgz#01f01760a391e8222fe4f33fbccbd1ad71aed74e"
integrity sha512-Uw5ooOQxRASHgu6C7GVvUxisKXfSgW4oFlO+aa+PAkgmH89O3CXxEEzNRNtHSqtXFTl0nAC1uYj0GMSH27uwtQ==

vscode-uri@^2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-2.1.2.tgz#c8d40de93eb57af31f3c715dd650e2ca2c096f1c"
Expand Down

0 comments on commit acb88f1

Please sign in to comment.