履歴: プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集

各行は、その日時に書かれた内容です。追加・削除は、1 つ前の版との行数の差です (全 6 版)。「差分」は比較する版、「基準」は比べる相手の版を選びます

日時タイトル文字数追加削除内容差分基準
2023/12/5 12:56:30プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 最新版27,067+129 -0表示差分—
2023/11/30 14:16:52プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 23,526+362 -218表示差分選択
2023/11/30 5:49:32プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 18,110+207 -41表示表示中選択
2023/11/30 0:36:00プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 14,091+153 -123表示差分選択
2023/11/28 10:21:21プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 13,513+1 -1表示差分選択
2023/11/28 10:21:12プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 13,512— —表示—基準

基準: プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 (2023/11/28 10:21:12) → 比較: プログラミング/svelte/ブログ的なもの作り-投稿・表示・編集 (2023/11/30 5:49:32)

@@ -2,177 +2,195 @@
* ブログ的なものを作ってみる [#x6384456]
-上の内容の続き。
+#contents
** データベースの準備 [#ua1c2e03]
+編集履歴をすべて残すため、記事が書き換えられた場合にも新しいレコードを追加するのみ。
+
+- 古いレコードの newRevisionId に新しいレコードの id を持たせる
+-- newRevisionId != null の記事は古いものということ
+- 削除済みの記事には deletedAt に日付が入る
+
prisma/schema.prisma
- model AuthUser {
+ model User {
...
roles Role[]
+ articles Article[]
- @@map("auth_user")
}
...
+ model Article {
- + id String @id @default(uuid())
- + author AuthUser @relation(fields: [authorId], references: [id])
+ + id Int @id @default(autoincrement())
+ + author User @relation(fields: [authorId], references: [id])
+ authorId String @map("author_id")
+ title String
- + slug String? @unique
+ body String
- + newRevisionId String? @unique @map("new_revision_id")
+ + newRevisionId Int? @unique @map("new_revision_id")
+ oldRevision Article? @relation("ArticleRevision", fields: [newRevisionId], references: [id])
+ newRevision Article? @relation("ArticleRevision")
+ createdAt DateTime @default(now()) @map("created_at")
- + deletedAt DateTime? @default(now()) @map("deleted_at")
+ + deletedAt DateTime? @map("deleted_at")
+ attachments Attachment[]
+ +
+ + @@index([deletedAt, title, createdAt])
+ + @@index([newRevisionId, deletedAt, title])
+ + @@index([newRevisionId, deletedAt, createdAt])
+ }
- +
+ +
+ model Attachment {
+ id String @ id @default(uuid())
+ article Article @relation(fields: [articleId], references: [id])
- + articleId String
+ + articleId Int
+ body Bytes
+ createdAt DateTime @default(now()) @map("created_at")
+ modifiedAt DateTime @default(now()) @map("modified_at")
+ +
+ + @@index([articleId])
+ }
newRevisionId がなく deletedAt もないものが最新の記事ということになる
-最も新しいものだけに slug を付与する。
-
-- slug 化について~
-https://qiita.com/Yarakashi_Kikohshi/items/af0b334af1a1e73a5661#-url-%E3%83%95%E3%83%A9%E3%82%B0%E3%83%A1%E3%83%B3%E3%83%88%E8%AD%98%E5%88%A5%E5%AD%90
-- https://www.npmjs.com/package/slugify
-
-ただし、古い版から slug が変化する場合には古い版の slug も残しておき、
-そこから最新版へリダイレクトする。
-
-articles/123 のように数字でアクセスした場合には id で検索して
-その最新版へリダイレクトする。
-
-StackOverflow などでは /questions/[id]/[slug] としていて、
-[slug] の有無にかかわらず [id] まででアクセスできるみたい。
-[slug] は任意の文字列で構わない。
-
-SEO 的に [slug] が付いていることだけが重要なのだとすればこれが一番いい。
-古い番号からは 301 Moved Permanently で新しい番号に飛べばいい。
-
-その方針なら slug をデータベースに持たせる必要はないのか。
-
-prisma/schema.prisma
- model Article {
- ...
-
- - slug String? @unique
-
newRevision の投稿時に Attachment をどのように引き継ぐかが問題?
どうせ表示の時にしか必要にならないので、表示の際に古いものも含めて全部列挙すればそれでよいかも?
LANG: console
- $ pnpm prisma migrate dev --name "add Article and Attachment"
+ $ pnpm prisma migrate dev --name "add Article and Attachment tables"
Environment variables loaded from .env
Prisma schema loaded from prisma\schema.prisma
- Datasource "db": SQLite database "dev.db" at "file:dev.db"
+ Datasource "db": SQLite database "dev.db" at "file:./dev.db"
- Applying migration `20231127041011_add_article_and_attachment`
+ Applying migration `20231130003510_add_article_and_attachment_tables`
The following migration(s) have been created and applied from new schema changes:
migrations/
- └─ 20231127041011_add_article_and_attachment/
+ └─ 20231130003510_add_article_and_attachment_tables/
└─ migration.sql
Your database is now in sync with your schema.
- ✔ Generated Prisma Client (v5.6.0) to .\node_modules\.pnpm\@prisma+client@5.6.0_prisma@5.6.0\node_modules\@prisma\client in 346ms
+ ✔ Generated Prisma Client (v5.6.0) to .\node_modules\.pnpm\@prisma+client@5.6.0_prisma@5.6.0\node_modules\@prisma\client in 199ms
** routes [#p0f2dd8e]
-- 投稿 (loggedIn)/articles/new
+- 投稿 /articles/(loggedIn)/new
- 一覧表示 /articles
-- 記事表示 /articles/[id]/[ [slug] ]
-- 編集 (loggedIn)/articles/[id]/edit
-- 削除 (loggedIn)/articles/[id]/delete
+- 記事表示 /articles/[...titleOrId]
+- 編集 /articles/[id]/(loggedIn)/edit
+- 削除 /articles/[id]/(loggedIn)/delete
** 投稿画面 [#t7c8104d]
-新たに LabeledTextArea を作成した。
+新たに TextArea を作成した。
-その中で editorProps というのを新しく作って、TextArea にそのまま渡すようにした。
-
-https://stackoverflow.com/questions/76285794/svelte-components-intrinsicelements-or-sveltehtmlelements-for-extending-with-ht
-
-src/lib/components/LabeledTextArea.svelte
+src/lib/components/TextArea.svelte
LANG: ts
<script lang="ts">
import type { Writable } from 'svelte/store';
- import type { SvelteHTMLElements } from 'svelte/elements';
export let name: string;
export let label: string;
- export let type = 'text';
+ export let labelAlt: string = '';
export let value: string;
export let disabled = false;
export let errors: Writable<{}> | undefined = undefined;
+ export let props: svelteHTML.IntrinsicElements['textarea'] | undefined = undefined;
- export let editorProps: SvelteHTMLElements['textarea'] | undefined = undefined;;
-
let key = name as keyof typeof errors;
</script>
- <label for={name} class="label"><span class="text-base label-text">{label}</span></label>
- <textarea {...{ name, type, ...editorProps }} bind:value disabled={disabled} on:input
- class="w-full input input-bordered input-primary" class:input-error={errors && $errors && $errors[key]} />
- {#if errors && $errors && $errors[key]}<span class="text-xs text-red-600">{$errors[key]}</span>{/if}
+ <div class="form-control w-full">
+ <label for={name} class="label">
+ <span class="label-text">{label}</span>
+ {#if labelAlt}<span class="label-text-alt">{labelAlt}</span>{/if}
+ </label>
+ <textarea
+ {...{ name, ...props }}
+ bind:value
+ {disabled}
+ on:input
+ class="w-full textarea textarea-bordered textarea-primary"
+ class:input-error={errors && $errors && $errors[key]}
+ />
+ {#if errors && $errors && $errors[key]}
+ <label class="label" for={name}>
+ <span class="label-text-alt text-error">{$errors[key]}</span>
+ </label>
+ {/if}
+ </div>
+
後で見た目をもっと凝ったものにしたいけど今はこれで。
-(loggedIn)/articles/new/+page.svelte
+src/routes/articles/(login)/new/+page.svelte
LANG: html
<script lang="ts">
import type { PageData } from './$types';
import { superForm } from 'sveltekit-superforms/client';
import Form from '$lib/components/Form.svelte';
- import LabeledInput from '$lib/components/LabeledInput.svelte';
- import LabeledTextArea from '$lib/components/LabeledTextArea.svelte';
- import SubmitButton from '$lib/components/SubmitButton.svelte';
+ import InputText from '$lib/components/InputText.svelte';
+ import TextArea from '$lib/components/TextArea.svelte';
+ import Button from '$lib/components/Button.svelte';
export let data: PageData;
const { form, message, errors, submitting, capture, restore, enhance } = superForm(data.form, {
- taintedMessage: false
+ taintedMessage: false,
});
export const snapshot = { capture, restore };
</script>
- <div><h1>記事の投稿</h1>
+ <div>
+ <h1>記事の投稿</h1>
<Form message={$message} {enhance}>
- <LabeledInput name="title" label="タイトル" bind:value={$form.title} disabled={$submitting} {errors} />
+ <InputText
+ name="title"
+ label="タイトル"
+ bind:value={$form.title}
+ disabled={$submitting}
+ {errors}
+ />
- <LabeledTextArea name="body" label="本文" bind:value={$form.body} disabled={$submitting} {errors}
- editorProps={{style: 'height: 20em; overflow-y: scroll'}}/>
+ <TextArea
+ name="body"
+ label="本文"
+ bind:value={$form.body}
+ disabled={$submitting}
+ {errors}
+ props={{ style: 'height: 30em; overflow-y: scroll' }}
+ />
- <SubmitButton disabled={$submitting}>記事を投稿</SubmitButton>
+ <Button disabled={$submitting}>記事を投稿</Button>
<div>
- <a class="text-sm text-blue-600 hover:underline hover:text-blue-400" href="/">トップへ戻る</a>
+ <!-- svelte-ignore a11y-invalid-attribute -->
+ <a class="link" href="javascript:history.back()">トップへ戻る</a>
</div>
</Form>
</div>
+src/lib/zod/articles/new.ts
+ LANG: ts
+ import { z } from 'zod';
+
+ export const schema = z.object({
+ title: z.string().regex(/[^0-9]/, {
+ message: 'タイトルが空あるいは数値のページは作成できません',
+ }),
+ body: z.string(),
+ });
+
タイトルと本文と作者を設定してレコードを作成する。
-(loggedIn)/articles/new/+page.server.ts
+src/routes/articles/(login)/new/+page.server.ts
LANG: ts
import type { Actions, PageServerLoad } from './$types';
- import { schema } from '$lib/formSchemas/article';
+ import { schema } from '$lib/zod/articles/new';
import { superValidate } from 'sveltekit-superforms/server';
- import { fail } from '@sveltejs/kit';
- import { redirect } from 'sveltekit-flash-message/server';
-
+ import { fail, redirect } from '@sveltejs/kit';
+ import { setFlash } from 'sveltekit-flash-message/server';
+ import { path, addErrorToForm } from '$lib/server';
import { db } from '$lib/server/db';
export const load = (async () => {
@@ -180,62 +198,220 @@
return { form };
}) satisfies PageServerLoad;
- export const actions: Actions = {
+ export const actions = {
default: async (event) => {
// フォームデータのバリデーション
const form = await superValidate(event, schema);
+ if (await db.article.findFirst({ where: { title: form.data.title } })) {
+ addErrorToForm(form, 'title', '既存のページと重複しています');
+ }
if (!form.valid) {
return fail(400, { form });
}
// 記事を投稿する
- const article = await db.article.create({data:{
- authorId: event.locals.session.user.id,
- ...form.data,
- }})
+ const article = await db.article.create({
+ data: {
+ authorId: event.locals.session!.user.userId,
+ ...form.data,
+ },
+ });
- return redirect(302, `/articles/${article.id}`, {type: 'success', message: '記事を投稿しました'}, event);
+ setFlash({ type: 'success', message: '記事を投稿しました' }, event);
+ throw redirect(302, path(article));
+ },
+ } satisfies Actions;
+
+ LANG: console
+ $ git add . && git commit -m "Article の投稿を可能にした"
+
+** 記事表示用のアドレス [#e2289487]
+
+実は上のコードの最後は path(article) という呼び出しを行っていて、
+これがまだ実装されていない。
+
+個々の記事を表示するためのアドレスはこの形にしたい。
+
+ /articles/[...titleOrId]
+
+[...titleOrId] には記事番号あるいは encodeURI されたタイトルが入る。
+
+スプレッド構文的に見えるため params.titleOrId は文字列配列になるのかと思ったけど、
+実際に渡されるのは "/" を含む可能性のある「文字列」だった。
+
+params.titleOrId が
+
++ 数字だけを含むなら記事番号(id)と解釈する
++ それ以外ならタイトルと解釈する
+
+2. を正式なアドレスとしたいので、数字でアクセスした場合にも
+タイトル表記のアドレスへリダイレクトする
+
+記事のタイトルが変更された場合に古いタイトルでアクセスしてきたなら
+最新のページにリダイレクトする
+
+*** タイトルのエンコード・デコード [#q52d5736]
+
+さて、タイトルには特殊文字が含まれるのでそのまま URL としては使えない
+
+英語が主に使われている場所では slug 化してアドレスに直すことが多いのだけれど、
+今の用途では title は日本語であることが多いのでそのまま encodeURI してしまおう。
+
+- encodeURI
+-- UTF8ベースのエンコード
+-- その名の通り、URIそのものを渡しエンコードしてもらうもの
+-- そのため、URI内で意味をもつ #$&+,/:;=?@ の文字は変換されない
+-- スペースのエンコードは+ではなく%20
+- encodeURIComponent
+-- UTF-8ベースのエンコード
+-- その名の通り、URIを構成する一部分を渡しエンコードしてもらうもの
+-- URI内で意味を持つ #$&+,/:;=?@ もエンコードする
+-- encodeURIとの差は #$&+,/:;=?@ をエンコードするか否か
+-- URI全体をこの関数でエンコードすると、URIとして機能しなくなる
+
+encodeURI だけだと ?&# などパスに含まれちゃいけない文字がそのまま残るので、
+"/" でスプリットして個別に encodeURIComponent/decode するのが正しい。
+
+一方、そのまま encodeURIComponent を使うと
+スペースが "%20" になってしまって不格好なので、
+最後に "%20" を "+" に変換する。
+
+元々の % は %25 にエンコードされるので、何も考えず "%20" を "+" に置き換えて構わない。
+
+ LANG: ts
+ title.split('/')
+ .map(str=> encodeURIComponent(str).replaceAll('%20', '+'))
+ .join('/')
+
+戻すときは "+" を "%20" にしてから decodeURIComponent する。
+
+ LANG: ts
+ encoded.split('/')
+ .map(str=> decodeURIComponent(str.replaceAll('+', '%20')))
+ .join('/')
+
+*** ユーティリティ関数 [#y859bb59]
+
+以上を実現するのに使うユーティリティ関数を次のように実装した。
+
+- articleTitleEncode(title) エンコードする
+- articleTitleDecode(encoded) デコードする
+- newestArticle(article) 最新版を探して返す
+
+src/lib/server/db.ts
+ LANG: ts
+ import { PrismaClient, type Article, type User } from '@prisma/client';
+ ...
+
+ articleTitleEncode(title: string) {
+ return title.split('/')
+ .map(str=> encodeURIComponent(str).replaceAll('%20', '+'))
+ .join('/');
}
- };
+
+ articleTitleDecode(encoded: string) {
+ return encoded.split('/')
+ .map(str=> decodeURIComponent(str.replaceAll('+', '%20')))
+ .join('/');
+ }
+
+ async newestArticle(article: (Article & { author: User }) | number | null) {
+ if (!article) { return null; }
+ while (typeof article == 'number' || article?.newRevisionId) {
+ article = await this.article.findUnique({
+ where: {
+ id: typeof article == 'number' ? article : article.newRevisionId!,
+ deletedAt: null,
+ },
+ include: { author: true },
+ });
+ }
+ return article;
+ }
+これを使って path 関数に Article を指定可能にした。
-** 記事の表示 [#e2289487]
+src/lib/server/index.ts
+ LANG: ts
+ import type { Article } from '@prisma/client';
+ import { db } from '$lib/server/db';
+
+ export const urlRoot = process.env['URL_ROOT'] || '';
+ export function path(relative: string | Article) {
+ if (typeof relative == 'string') {
+ return urlRoot + relative;
+ } else {
+ // if (Object.hasOwn(relative, 'newRevisionId')) {
+ return urlRoot + '/articles/' + db.articleTitleEncode(relative.title);
+ }
+ }
-src/routes/articles/+page.server.ts
+ LANG: console
+ $ git add . && git commit -m "Article 記事の URL 生成ヘルパー"
+
+** 記事の簡易表示 [#e2289487]
+
+src/routes/articles/[...titleOrId]/+page.server.ts
LANG: ts
import type { PageServerLoad } from './$types';
+ import { error, redirect } from '@sveltejs/kit';
+ import { path } from '$lib/server';
import { db } from '$lib/server/db';
-
- export const load = (async () => {
- const articles = await db.article.findMany({
- where: {deletedAt: null, newRevisionId: null},
- orderBy: {createdAt: 'desc'},
- take: 20,
- include: {author: true}
- })
- return { articles };
+
+ export const load = (async (event) => {
+ if (event.params.titleOrId.match(/^\d+$/)) {
+ // 数値で指定なら該当記事にリダイレクト
+ const article = await db.newestArticle(Number(event.params.titleOrId));
+ if (!article) throw error(404);
+ throw redirect(302, path(article));
+ }
+ // タイトルで指定
+ const article = await db.article.findFirst({
+ where: {
+ deletedAt: null,
+ title: decodeURI(event.params.titleOrId),
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ include: { author: true },
+ });
+ if (!article) throw error(404);
+
+ // 最新版があればリダイレクト
+ const newest = await db.newestArticle(article);
+ if (newest?.id != article.id) {
+ throw redirect(302, path(newest!));
+ }
+ return { article };
}) satisfies PageServerLoad;
-src/routes/articles/+page.svelte
+表示はとりあえず <pre></pre> にソーステキストをそのまま貼っておく
+
+tailwindcss はそのまま使うと何もかもがリセットされていてアレなのだけれど、
+tailwindcss/typography を入れてあるので class="prose" で囲った領域は
+まともな表示(例えば h1 が大きくなるなど)になる。ただし maxWidth が 65ch
+に設定されてしまうため min-w-full でキャンセルしておく。
+
+src/routes/articles/[...titleOrId]/+page.svelte
+ LANG: html
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
</script>
- <div><h1>最新の記事</h1>
- {#each data.articles as article}
- <div>
- <div>{article.title}</div>
- <div><span>{article.author.name}</span><span>{article.createdAt.toString()}</span></div>
- <div>
- {article.body}
- </div>
- </div>
- {/each}
- </div>
+ <article class="prose min-w-full p-4">
+ <h1>{data.article.title}</h1>
+ <pre>
+ {data.article.body}
+ </pre>
+ </article>
+ LANG: console
+ $ git add . && git commit -m "Article の簡易表示ページを作成"
+
** markdown を解釈 [#tb240725]
さしあたり marked, highlight, katex を入れてみる。
@@ -244,7 +420,7 @@
$ npm install marked highlight.js katex
Packages: +4
++++
- Progress: resolved 388, reused 362, downloaded 4, added 4, done
+ Progress: resolved 383, reused 359, downloaded 1, added 4, done
dependencies:
+ highlight.js ^11.9.0
@@ -255,7 +431,7 @@
$ npm i --save-dev @types/katex
Packages: +1
+
- Progress: resolved 389, reused 366, downloaded 1, added 1, done
+ Progress: resolved 384, reused 361, downloaded 0, added 1, done
devDependencies:
+ @types/katex 0.16.7
@@ -266,39 +442,57 @@
- https://note.com/taatn0te/n/n17db53037ade
- https://katex.org/docs/node
+あたりを見ながら、
+- marked.parse で Markdown を html にできる
+
src/routes/articles/+page.svelte
- ...
+ LANG: ts
+ <script lang="ts">
+ import type { PageData } from './$types';
+ import { afterUpdate } from 'svelte';
+ import { marked } from 'marked';
+ import hljs from 'highlight.js';
+ import renderMathInElement from 'katex/contrib/auto-render';
+ import 'highlight.js/styles/stackoverflow-dark.min.css';
+ import 'katex/dist/katex.min.css';
- + import { marked } from 'marked';
- + import hljs from 'highlight.js';
- + import renderMathInElement from 'katex/contrib/auto-render';
-
- export let data: PageData;
- let articles: HTMLElement;
-
- + afterUpdate(()=>{
- + console.log('rendering...', articles);
- + renderMathInElement(articles, {
- + // customised options
- + // • auto-render specific keys, e.g.:
- + delimiters: [
- + {left: '$$', right: '$$', display: true},
- + {left: '$', right: '$', display: false},
- + {left: '\\(', right: '\\)', display: false},
- + {left: '\\[', right: '\\]', display: true}
- + ],
- + // • rendering keys, e.g.:
- + throwOnError : false
- + });
- + hljs.highlightAll();
- + })
-
- </script>
- ...
+ export let data: PageData;
+ let article: HTMLElement;
- - {article.body}
- + {@html marked.parse(article.body)}
+ afterUpdate(()=>{
+ console.log('rendering...', article);
+ renderMathInElement(article, {
+ // customised options
+ // • auto-render specific keys, e.g.:
+ delimiters: [
+ {left: '$$', right: '$$', display: true},
+ {left: '$', right: '$', display: false},
+ {left: '\\(', right: '\\)', display: false},
+ {left: '\\[', right: '\\]', display: true}
+ ],
+ // • rendering keys, e.g.:
+ throwOnError : false
+ });
+ hljs.highlightAll();
+ })
+ </script>
+
+ <article bind:this={article} class="prose max-w-full p-4">
+ <h1>{data.article.title}</h1>
+ <div>
+ <span>{data.article.author.name}</span>
+ <span>{data.article.createdAt.toLocaleString()}</span>
+ </div>
+ <content>
+ {@html marked.parse(data.article.body)}
+ </content>
+ </article>
+これである程度まともに表示されるようになった。
+
+ LANG: console
+ $ git add . && git commit -m "marked, highlightjs, katex を入れた"
+
** css を読み込む [#h51651b5]
node_modules に含まれるものは、
@@ -401,39 +595,39 @@
import hljs from 'highlight.js';
// code を言語 lang として highlight する
- const highlight = function(code: string, lang?: string){
+ const highlight = function (code: string, lang?: string) {
if (lang) {
- return hljs.highlight(code, {language: lang, ignoreIllegals: true}).value;
+ return hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
} else {
return hljs.highlightAuto(code).value;
}
- }
+ };
// highlight.js の言語名あるいはエイリアス名から正式な言語名を調べる
- const aliasToLang: {[alias: string]: string} = {};
- hljs.listLanguages().forEach(name=>{
+ const aliasToLang: { [alias: string]: string } = {};
+ hljs.listLanguages().forEach((name) => {
const lang = hljs.getLanguage(name);
aliasToLang[name] = name;
- lang?.aliases?.forEach(alias=>{
+ lang?.aliases?.forEach((alias) => {
aliasToLang[alias] = name;
- })
+ });
});
// HTML の特殊文字をエスケープ
// https://stackoverflow.com/questions/1787322/what-is-the-htmlspecialchars-equivalent-in-javascript
function escapeHtml(text: string) {
const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
- return text.replace(/[&<>"']/g, c=>map[c as keyof typeof map]);
+ return text.replace(/[&<>"']/g, (c) => map[c as keyof typeof map]);
}
// code ブロックをレンダリングする
const codeRenderer = (code: string, fileInfo = '', escaped: boolean) => {
const info = fileInfo.split(':');
- if(info[0]) {
- if(!aliasToLang[info[0]]) {
- const ext = info[0].split('.').findLast(()=>true);
- if(ext && aliasToLang[ext]){
+ if (info[0]) {
+ if (!aliasToLang[info[0]]) {
+ const ext = info[0].split('.').findLast(() => true);
+ if (ext && aliasToLang[ext]) {
// 拡張子
info.unshift(aliasToLang[ext]);
} else {
@@ -455,9 +649,11 @@
const fileTag = fileName ? `<span class="filename">${escapeHtml(fileName)}</span>` : '';
const langClass = lang ? ` language-${escapeHtml(lang)}` : '';
- return `<pre>${fileTag}<code class="hljs${langClass}">`
- + (escaped === false ? escapeHtml(code) : code)
- + '\n</code></pre>';
+ return (
+ `<pre>${fileTag}<code class="hljs${langClass}">` +
+ (escaped === false ? escapeHtml(code) : code) +
+ '\n</code></pre>'
+ );
};
export { codeRenderer };