remark-preview-to-frontmatter 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohsen Waheed Elsisi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # remark-preview-to-markdown
2
+
3
+ [remark](https://github.com/remarkjs/remark) plugin to add text from the beginning of a document to a property in frontmatter.
4
+
5
+ ## Contents
6
+
7
+ - [What is this](#what-is-this?)
8
+ - [When should I use this?](#when-should-I-use-this?)
9
+ - [Installation](#install)
10
+ - [usage](#use)
11
+ - [API](#api)
12
+ - [PluginOptions](#pluginoptions)
13
+
14
+ ## What is this?
15
+
16
+ This is a [unified](https://github.com/unifiedjs/unified) ([remark](https://github.com/remarkjs/remark)) plugin that extracts some text from the beginning of a markdown file (not including frontmatter and comments) and adds the extracted text as a frontmatter property.
17
+
18
+ ## When should I use this?
19
+
20
+ This plugin is useful in use cases where a preview of the document must be part of the files metadata. For example, blogging sites may use this to show a snippet of each individual blog post in a list of multiple posts.
21
+
22
+ This plugin selects the snippet based on a number of characters, hence for something like an abstract in a journal article, this plugin is not useful.
23
+
24
+ ## Install
25
+
26
+ The package is only available on npm:
27
+
28
+ ```shell
29
+ npm install remark-preview-to-frontmatter
30
+ ```
31
+
32
+ ## Use
33
+
34
+ Consider `exmaple.md`
35
+
36
+ ```md
37
+ _Lorem Ipsum_ is simply **dummy text** of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
38
+
39
+ sourced from [lipsum.com](https://www.lipsum.com/)
40
+ ```
41
+
42
+ To add a preview of this file in markdown, the following is done:
43
+
44
+ ```js
45
+ import fs from "fs/promises";
46
+ import { remark } from "remark";
47
+ import remarkFrontmatter from "remark-frontmatter";
48
+ import remarkPreviewToFrontmatter from "remark-preview-to-frontmatter";
49
+
50
+ const inputFIle = "./example.md";
51
+ const outputFile = "./output.md";
52
+
53
+ const inputMarkdown = await fs.readFile(inputFIle, "utf-8");
54
+
55
+ const outputMarkdown = await remark()
56
+ .use(remarkFrontmatter)
57
+ .use(remarkPreviewToFrontmatter, { charLimit: 100 })
58
+ .process(inputMarkdown);
59
+
60
+ await fs.writeFile(outputFile, String(outputMarkdown));
61
+
62
+ ```
63
+
64
+ `output.md` would look like this
65
+
66
+ ```md
67
+ ---
68
+ preview: Lorem Ipsum is simply dummy text of the printing and typesetting
69
+ industry. Lorem Ipsum has been the ...
70
+
71
+ ---
72
+
73
+ *Lorem Ipsum* is simply **dummy text** of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
74
+
75
+ sourced from [lipsum.com](https://www.lipsum.com/)
76
+ ```
77
+
78
+ ## API
79
+
80
+ The package only provides the default export used as a plugin to remark. Provding options is of course optional.
81
+
82
+ ```js
83
+ remark().use(remarkPreviewToFrontmatter, options)
84
+ ```
85
+
86
+ ### PluginOptions
87
+
88
+ | Field | type | default | purpose |
89
+ | ------------------------- | ------------ | ------- | -------------------------------------------------------------------- |
90
+ | `charLimit` | int | 200 | the number of maximum number of characters to include in the preview |
91
+ | `frontmatterKey` | string | preview | defined the key to use in the frontmatter |
92
+ | `appendEllipsis` | bool | true | whether to add "..." at end of preview |
93
+ | `allowMultipleLines` | bool | false | removes new lines and redundant whitespace from the text |
94
+ | `trailingWordBreakPolicy` | (see bellow) | break | how to handle a word if the charLimit lies within it |
95
+
96
+ `trailingWordBreakPolicy` acts when only part of the last word is included in the preview. For example, if the last word is *hello* and the `charLimit` is such that only the first three letters are taken, each policy will handle this scenario differently:
97
+
98
+ | policy | result | explanation |
99
+ | ----------- | ----------- | --------------------------------------------------------------- |
100
+ | `break` | hel | will strictlly apply the character limit |
101
+ | `full word` | hello | will preserve the whole word, exceed the limit |
102
+ | `remove` | *(nothing)* | will remove the incomplete word entirely, going under the limit |
@@ -0,0 +1,3 @@
1
+ import type { Root } from "mdast";
2
+ declare function extractPreviewText(tree: Root, charLimit: number): string;
3
+ export default extractPreviewText;
@@ -0,0 +1,15 @@
1
+ import { visit } from "unist-util-visit";
2
+ function extractPreviewText(tree, charLimit) {
3
+ let previewText = "";
4
+ visit(tree, ["text", "code", "inlineCode"], (node) => {
5
+ if (previewText.length >= charLimit)
6
+ return;
7
+ // @ts-ignore
8
+ if (node.value) {
9
+ // @ts-ignore
10
+ previewText += node.value + " ";
11
+ }
12
+ });
13
+ return previewText;
14
+ }
15
+ export default extractPreviewText;
@@ -0,0 +1,2 @@
1
+ import type { Root } from "mdast";
2
+ export default function modifyFrontmatter(tree: Root, key: string, previewText: string): void;
@@ -0,0 +1,27 @@
1
+ import { u } from "unist-builder";
2
+ import { visit } from "unist-util-visit";
3
+ import * as yaml from "yaml";
4
+ export default function modifyFrontmatter(tree, key, previewText) {
5
+ let frontmatterNodeExists = addPropertyIfYamlExists(tree, key, previewText);
6
+ if (!frontmatterNodeExists) {
7
+ insertNewYamlNode(key, previewText, tree);
8
+ }
9
+ }
10
+ function addPropertyIfYamlExists(tree, key, previewText) {
11
+ let nodeFound = false;
12
+ visit(tree, "yaml", (node) => {
13
+ nodeFound = true;
14
+ node.value = addYamlProperty(node.value, key, previewText);
15
+ });
16
+ return nodeFound;
17
+ }
18
+ function insertNewYamlNode(key, previewText, tree) {
19
+ const yamlContent = addYamlProperty("", key, previewText);
20
+ const yamlNode = u("yaml", yamlContent);
21
+ tree.children.unshift(yamlNode);
22
+ }
23
+ function addYamlProperty(yamlString, frontmatterKey, previewText) {
24
+ const parsedYaml = yaml.parse(yamlString) ?? {};
25
+ parsedYaml[frontmatterKey] = previewText;
26
+ return yaml.stringify(parsedYaml);
27
+ }
@@ -0,0 +1,2 @@
1
+ import remarkPreviewToFrontmatter from "./plugin.js";
2
+ export default remarkPreviewToFrontmatter;
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import remarkPreviewToFrontmatter from "./plugin.js";
2
+ export default remarkPreviewToFrontmatter;
@@ -0,0 +1,11 @@
1
+ import type { Root } from "mdast";
2
+ import { TrailingWordBreakPolicy } from "./wordBreaks.js";
3
+ interface PluginOptions {
4
+ charLimit?: number;
5
+ trailingWordBreakPolicy?: TrailingWordBreakPolicy;
6
+ frontmatterKey?: string;
7
+ allowMultipleLines?: boolean;
8
+ appendEllipsis?: boolean;
9
+ }
10
+ declare function remarkPreviewToFrontmatter(options?: PluginOptions): (tree: Root) => void;
11
+ export default remarkPreviewToFrontmatter;
package/dist/plugin.js ADDED
@@ -0,0 +1,26 @@
1
+ import modifyFrontmatter from "./frontmatter.js";
2
+ import trimPreviewTextToLength from "./wordBreaks.js";
3
+ import extractPreviewText from "./extractPreviewText.js";
4
+ const defaultOptions = {
5
+ charLimit: 200,
6
+ trailingWordBreakPolicy: "break",
7
+ frontmatterKey: "preview",
8
+ allowMultipleLines: false,
9
+ appendEllipsis: true,
10
+ };
11
+ function remarkPreviewToFrontmatter(options = {}) {
12
+ const { charLimit = defaultOptions.charLimit, trailingWordBreakPolicy = defaultOptions.trailingWordBreakPolicy, frontmatterKey = defaultOptions.frontmatterKey, allowMultipleLines = defaultOptions.allowMultipleLines, appendEllipsis = defaultOptions.appendEllipsis, } = options;
13
+ return function (tree) {
14
+ let previewText = extractPreviewText(tree, charLimit);
15
+ if (!allowMultipleLines) {
16
+ previewText = previewText.replace("\n", " ");
17
+ previewText = previewText.replace(/\s+/g, " ");
18
+ }
19
+ previewText = previewText.trim();
20
+ previewText = trimPreviewTextToLength(previewText, charLimit, trailingWordBreakPolicy);
21
+ if (appendEllipsis)
22
+ previewText = previewText + "...";
23
+ modifyFrontmatter(tree, frontmatterKey, previewText);
24
+ };
25
+ }
26
+ export default remarkPreviewToFrontmatter;
@@ -0,0 +1,2 @@
1
+ export type TrailingWordBreakPolicy = "break" | "remove" | "full word";
2
+ export default function trimPreviewTextToLength(text: string, limit: number, policy: TrailingWordBreakPolicy): string;
@@ -0,0 +1,31 @@
1
+ export default function trimPreviewTextToLength(text, limit, policy) {
2
+ let trimmedText = limit >= text.length ? text : text.slice(0, limit);
3
+ return applyTrailingWordBreakPolicy(text, trimmedText, policy);
4
+ }
5
+ function applyTrailingWordBreakPolicy(fullText, trimmedText, policy) {
6
+ if (policy == "break")
7
+ return trimmedText;
8
+ const [lastWordInPreview, lastWordInfullText] = getLastWords(fullText, trimmedText);
9
+ if (lastWordInPreview === lastWordInfullText)
10
+ return trimmedText;
11
+ if (policy == "remove") {
12
+ const previewWords = trimmedText.split(" ");
13
+ previewWords.pop();
14
+ return previewWords.join(" ");
15
+ }
16
+ else if (policy == "full word") {
17
+ const previewWords = trimmedText.split(" ");
18
+ previewWords.pop();
19
+ previewWords.push(lastWordInfullText);
20
+ return previewWords.join(" ");
21
+ }
22
+ throw new Error(`Unknown trailing word break policy: ${policy}`);
23
+ }
24
+ function getLastWords(fullText, textPreview) {
25
+ const previewTextWords = textPreview.split(" ");
26
+ const fullTextWords = fullText.split(" ");
27
+ const lastWordIndex = previewTextWords.length - 1;
28
+ const lastWordInPreview = previewTextWords[lastWordIndex];
29
+ const lastWordInfullText = fullTextWords[lastWordIndex];
30
+ return [lastWordInPreview, lastWordInfullText];
31
+ }
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "remark-preview-to-frontmatter",
3
+ "version": "1.0.0",
4
+ "author": "Mohsen Elsisi",
5
+ "description": "remark plugin to add text from the beginning of a document to a property in frontmatter.",
6
+ "keywords": [
7
+ "unified",
8
+ "remark",
9
+ "remark-plugin",
10
+ "markdown",
11
+ "frontmatter"
12
+ ],
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/mohsen-w-elsisi/remark-preview-to-frontmatter"
17
+ },
18
+ "type": "module",
19
+ "main": "dist/index.js",
20
+ "exports": {
21
+ ".": "./dist/index.js"
22
+ },
23
+ "types": "./dist/index.d.ts",
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "test": "npm run build && node tests/test.js"
27
+ },
28
+ "dependencies": {
29
+ "unist-builder": "^4.0.0",
30
+ "unist-util-visit": "^5.0.0",
31
+ "yaml": "^2.8.2"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^25.0.10",
35
+ "mdast-util-frontmatter": "^2.0.1",
36
+ "micromark-extension-frontmatter": "^2.0.0",
37
+ "remark": "^15.0.1",
38
+ "remark-frontmatter": "^5.0.0"
39
+ }
40
+ }