2021-09-02 05:15:31 -04:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
2021-10-17 12:45:58 -04:00
|
|
|
import type { FrontmatterExtractionResult } from './types'
|
2021-09-02 05:15:31 -04:00
|
|
|
|
|
|
|
const FRONTMATTER_BEGIN_REGEX = /^-{3,}$/
|
|
|
|
const FRONTMATTER_END_REGEX = /^(?:-{3,}|\.{3,})$/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Extracts a frontmatter block from a given multiline string.
|
|
|
|
* A valid frontmatter block requires the content to start with a line containing at least three dashes.
|
|
|
|
* The block is terminated by a line containing the same amount of dashes or dots as the first line.
|
2021-12-14 04:16:25 -05:00
|
|
|
* @param lines The lines from which the frontmatter should be extracted.
|
2021-10-04 06:50:39 -04:00
|
|
|
* @return { isPresent } false if no frontmatter block could be found, true if a block was found.
|
2021-09-02 05:15:31 -04:00
|
|
|
* { rawFrontmatterText } if a block was found, this property contains the extracted text without the fencing.
|
|
|
|
* { frontmatterLines } if a block was found, this property contains the number of lines to skip from the
|
|
|
|
* given multiline string for retrieving the non-frontmatter content.
|
|
|
|
*/
|
2021-12-14 04:16:25 -05:00
|
|
|
export const extractFrontmatter = (lines: string[]): FrontmatterExtractionResult => {
|
2021-09-02 05:15:31 -04:00
|
|
|
if (lines.length < 2 || !FRONTMATTER_BEGIN_REGEX.test(lines[0])) {
|
|
|
|
return {
|
2021-10-04 06:50:39 -04:00
|
|
|
isPresent: false
|
2021-09-02 05:15:31 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
for (let i = 1; i < lines.length; i++) {
|
|
|
|
if (lines[i].length === lines[0].length && FRONTMATTER_END_REGEX.test(lines[i])) {
|
|
|
|
return {
|
2021-10-04 06:50:39 -04:00
|
|
|
isPresent: true,
|
|
|
|
rawText: lines.slice(1, i).join('\n'),
|
|
|
|
lineOffset: i + 1
|
2021-09-02 05:15:31 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return {
|
2021-10-04 06:50:39 -04:00
|
|
|
isPresent: false
|
2021-09-02 05:15:31 -04:00
|
|
|
}
|
|
|
|
}
|