From 9b3e5265bdadbbe076a0be2280731c520fd61853 Mon Sep 17 00:00:00 2001 From: Stefan Imhoff Date: Sat, 10 Jun 2023 18:55:54 +0200 Subject: [PATCH] feat: add remark widont extension Idea from this article: https://eatmon.co/blog/remove-runts-markdown/ --- astro.config.mjs | 4 ++-- package.json | 3 ++- pnpm-lock.yaml | 3 +++ src/utils/index.ts | 1 + src/utils/remark-widont.ts | 17 +++++++++++++++++ 5 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 src/utils/remark-widont.ts diff --git a/astro.config.mjs b/astro.config.mjs index de2f847..374f9f8 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -2,7 +2,7 @@ import mdx from '@astrojs/mdx'; import preact from '@astrojs/preact'; import tailwind from '@astrojs/tailwind'; import { astroImageTools } from 'astro-imagetools'; -import { remarkReadingTime } from './src/utils'; +import { remarkReadingTime, remarkWidont } from './src/utils'; import { defineConfig } from 'astro/config'; @@ -17,7 +17,7 @@ export default defineConfig({ }, integrations: [ mdx({ - remarkPlugins: [remarkReadingTime], + remarkPlugins: [remarkReadingTime, remarkWidont], }), tailwind(), preact({ compat: true }), diff --git a/package.json b/package.json index ac8a1ef..e5638fb 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,8 @@ "react-dom": "npm:@preact/compat@^17.1.2", "reading-time": "^1.5.0", "sharp": "^0.32.1", - "tailwindcss": "^3.3.2" + "tailwindcss": "^3.3.2", + "unist-util-visit": "^4.1.2" }, "devDependencies": { "@types/mdast": "^3.0.11", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 28f15ce..9a50f9e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -84,6 +84,9 @@ dependencies: tailwindcss: specifier: ^3.3.2 version: 3.3.2 + unist-util-visit: + specifier: ^4.1.2 + version: 4.1.2 devDependencies: '@types/mdast': diff --git a/src/utils/index.ts b/src/utils/index.ts index 5b68f26..3ca76a3 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -2,6 +2,7 @@ export * from './date'; export * from './format-posts'; export * from './pick-two-random-colors'; export * from './remark-reading-time'; +export * from './remark-widont'; export * from './sort-by-alphabet'; export * from './sort-by-date'; export * from './sort-by-sortkey'; diff --git a/src/utils/remark-widont.ts b/src/utils/remark-widont.ts new file mode 100644 index 0000000..748e7bd --- /dev/null +++ b/src/utils/remark-widont.ts @@ -0,0 +1,17 @@ +import { visit } from 'unist-util-visit'; + +import type { Literal, Node } from 'unist'; + +export function remarkWidont() { + function transformer(tree: Node) { + visit(tree, 'text', function (node: Literal) { + let wordCount = node.value.split(' ').length; + + if (wordCount >= 3) { + node.value = node.value.replace(/ ([^ ]*)$/, '\u00A0$1'); + } + }); + } + + return transformer; +}