Skip to content

Commit

Permalink
feat: support metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
v8tenko committed Jan 17, 2024
1 parent 253ccd1 commit edb6412
Show file tree
Hide file tree
Showing 27 changed files with 473 additions and 103 deletions.
6 changes: 0 additions & 6 deletions .eslintrc

This file was deleted.

11 changes: 11 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module.exports = {
"extends": ["@diplodoc/eslint-config"],
"root": true,
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
"env": {
"node": true
}
}
11 changes: 8 additions & 3 deletions src/cmd/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,13 @@ async function handler(args: Arguments<any>) {
addMapFile,
allowCustomResources,
resources,
metadata,
} = ArgvService.getConfig();

if (typeof metadata !== 'undefined' && !Array.isArray(metadata)) {
ArgvService.patch('metadata', [metadata]);
}

preparingTemporaryFolders(userOutputFolder);

await processServiceFiles();
Expand Down Expand Up @@ -242,9 +247,9 @@ async function handler(args: Arguments<any>) {
// collect paths of all resources
Object.keys(resources).forEach(
(type) =>
resources[type as keyof Resources]?.forEach((path: string) =>
resourcePaths.push(path),
),
resources[type as keyof Resources]?.forEach((path) => {
resourcePaths.push(path);
}),
);

//copy resources
Expand Down
3 changes: 2 additions & 1 deletion src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ interface YfmConfig {
buildDisabled: boolean;
lintConfig: LintConfig;
resources?: Resources;
metadata?: Record<string, string>[];
yandexCloudTranslateFolderId: string;
yandexCloudTranslateGlossaryPairs: YandexCloudTranslateGlossaryPair[];
}
Expand Down Expand Up @@ -241,7 +242,7 @@ export interface PathData {
}

export type Resources = {
[key in ResourceType]?: string[];
[type in ResourceType]?: string[];
};

export type YandexCloudTranslateGlossaryPair = {
Expand Down
8 changes: 7 additions & 1 deletion src/resolvers/md2html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export async function resolveMd2HTML(options: ResolverOptions): Promise<ResolveM
pathToDir === tocBase ? '' : pathToDir.replace(`${tocBase}${sep}`, '');
const relativePathToIndex = relative(pathToDir, `${tocBase}${sep}`);

const {input, lang, allowCustomResources} = ArgvService.getConfig();
const {input, lang, allowCustomResources, metadata: yfmMetadata = []} = ArgvService.getConfig();
const resolvedPath: string = resolve(input, inputPath);
const content: string = readFileSync(resolvedPath, 'utf8');

Expand All @@ -61,6 +61,12 @@ export async function resolveMd2HTML(options: ResolverOptions): Promise<ResolveM

const fileMeta = fileExtension === '.yaml' ? result.data.meta ?? {} : updatedMetadata;

if (Array.isArray(fileMeta?.metadata)) {
fileMeta.metadata.push(...yfmMetadata);
} else {
fileMeta.metadata = yfmMetadata;
}

if (allowCustomResources) {
const {script, style} = metadata?.resources || {};
fileMeta.style = (fileMeta.style || []).concat(style || []).map(fixRelativePath(inputPath));
Expand Down
3 changes: 2 additions & 1 deletion src/resolvers/md2md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ import {ChangelogItem} from '@diplodoc/transform/lib/plugins/changelog/types';

export async function resolveMd2Md(options: ResolveMd2MdOptions): Promise<void> {
const {inputPath, outputPath, metadata} = options;
const {input, output} = ArgvService.getConfig();
const {input, output, metadata: yfmMetadata} = ArgvService.getConfig();
const resolvedInputPath = resolve(input, inputPath);
const vars = getVarsPerFile(inputPath);

const content = await getContentWithUpdatedMetadata(
readFileSync(resolvedInputPath, 'utf8'),
metadata,
vars.__system,
yfmMetadata,
);

const {result, changelogs} = transformMd2Md(content, {
Expand Down
5 changes: 5 additions & 0 deletions src/services/argv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,13 @@ function set(argv: YfmArgv) {
_argv = argv;
}

function patch<Key extends keyof YfmArgv>(field: Key, value: YfmArgv[Key]) {
_argv[field] = value;
}

export default {
getConfig,
init,
set,
patch,
};
29 changes: 26 additions & 3 deletions src/services/metadata.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {dump} from 'js-yaml';
import {dump, load} from 'js-yaml';

import {VCSConnector} from '../vcs-connector/connector-models';
import {MetaDataOptions, Metadata, Resources} from '../models';
Expand All @@ -22,6 +22,7 @@ async function getContentWithUpdatedMetadata(
fileContent: string,
options?: MetaDataOptions,
systemVars?: unknown,
yfmMetadata?: Record<string, string>[],
): Promise<string> {
let result;

Expand All @@ -32,7 +33,9 @@ async function getContentWithUpdatedMetadata(
addSourcePath: options?.addSourcePath,
resources: options?.resources,
systemVars,
yfmMetadata,
});

result = await getContentWithUpdatedDynamicMetadata(result, options);

return result;
Expand All @@ -45,17 +48,24 @@ function getContentWithUpdatedStaticMetadata({
addSourcePath,
resources,
systemVars,
yfmMetadata = [],
}: {
fileContent: string;
sourcePath?: string;
addSystemMeta?: boolean;
addSourcePath?: boolean;
resources?: Resources;
systemVars?: unknown;
yfmMetadata?: Record<string, string>[];
}): string {
const newMetadatas: string[] = [];

if ((!addSystemMeta || !systemVars) && !addSourcePath && !resources) {
if (
(!addSystemMeta || !systemVars) &&
!addSourcePath &&
!resources &&
yfmMetadata.length === 0
) {
return fileContent;
}

Expand All @@ -76,8 +86,21 @@ function getContentWithUpdatedStaticMetadata({

if (matches && matches.length > 0) {
const [, fileMetadata, , fileMainContent] = matches;
const parsed = load(fileMetadata) as any;

if (Array.isArray(parsed.metadata)) {
parsed.metadata = [...yfmMetadata, ...parsed.metadata];
} else if (parsed.metadata) {
parsed.metadata = [...yfmMetadata, parsed.metadata];
}

const patchedMetada = dump(parsed);

return `${getUpdatedMetadataString(newMetadatas, patchedMetada)}${fileMainContent}`;
}

return `${getUpdatedMetadataString(newMetadatas, fileMetadata)}${fileMainContent}`;
if (yfmMetadata.length) {
newMetadatas.push(dump({metadata: yfmMetadata}));
}

return `${getUpdatedMetadataString(newMetadatas)}${fileContent}`;
Expand Down
58 changes: 38 additions & 20 deletions src/utils/markup.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,40 @@
import {join} from 'path';
import {platform} from 'process';

import {CUSTOM_STYLE, Platforms, ResourceType} from '../constants';
import {Resources, SinglePageResult} from '../models';
import {CUSTOM_STYLE, Platforms} from '../constants';
import {LeadingPage, Resources, SinglePageResult, TextItems} from '../models';
import {ArgvService, PluginService} from '../services';
import {preprocessPageHtmlForSinglePage} from './singlePage';

import {DocInnerProps, DocPageData, render} from '@diplodoc/client/ssr';
import manifest from '@diplodoc/client/manifest';

const dst = (bundlePath: string) => (target: string) => join(bundlePath, target);
export const сarriage = platform === Platforms.WINDOWS ? '\r\n' : '\n';

export interface TitleMeta {
title?: string;
}
export type Meta = TitleMeta & Resources;
type YfmMetadata = {
metadata: Record<string, string>[];
};

export type Meta = TitleMeta & Resources & YfmMetadata;

export function generateStaticMarkup(
props: DocInnerProps<DocPageData>,
pathToBundle: string,
): string {
const {title: metaTitle, style, script} = (props.data.meta as Meta) || {};
const {style, script, metadata, ...restYamlConfigMeta} = (props.data.meta as Meta) || {};
const {title: tocTitle} = props.data.toc;
const {title: pageTitle} = props.data;

const title = getTitle({
metaTitle,
metaTitle: props.data.meta.title,
tocTitle: tocTitle as string,
pageTitle,
});

const resources = getResources({style, script});

const {staticContent} = ArgvService.getConfig();
Expand All @@ -40,7 +46,7 @@ export function generateStaticMarkup(
<html lang="${props.lang}">
<head>
<meta charset="utf-8">
${getMetadata(props.data.meta as Record<string, string>)}
${getMetadata(metadata, restYamlConfigMeta)}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<style type="text/css">
Expand Down Expand Up @@ -93,21 +99,35 @@ function getTitle({tocTitle, metaTitle, pageTitle}: GetTitleOptions) {
return resultPageTitle && tocTitle ? `${resultPageTitle} | ${tocTitle}` : '';
}

function getMetadata(metadata: Record<string, string>): string {
if (!metadata) {
return '';
type Metadata = Record<string, string>[];

function getMetadata(metadata: Metadata | undefined, restMeta: LeadingPage['meta']): string {
let result = '';

const addMetaTagsFromObject = (value: Record<string, string | boolean | TextItems>) => {
const args = Object.entries(value).reduce(
(acc, [field, content]) => acc + `${field}="${content}" `,
'',
);

if (args.length) {
result += `<meta ${args}/>` + сarriage;
}
};

if (metadata) {
metadata.forEach(addMetaTagsFromObject);
}

// Exclude resources from meta, proceed them separately
const metaEntries = Object.entries(metadata).filter(
([key]) => !Object.keys(ResourceType).includes(key),
);
if (restMeta) {
Object.entries(restMeta)
.map(([name, value]) => {
return {name, content: value};
})
.forEach(addMetaTagsFromObject);
}

return metaEntries
.map(([name, content]) => {
return `<meta name="${name}" content="${content}">`;
})
.join('\n');
return result;
}

function getResources({style, script}: Resources) {
Expand All @@ -130,8 +150,6 @@ function getResources({style, script}: Resources) {
return resourcesTags.join('\n');
}

export const сarriage = platform === Platforms.WINDOWS ? '\r\n' : '\n';

export function joinSinglePageResults(
singlePageResults: SinglePageResult[],
root: string,
Expand Down
Loading

0 comments on commit edb6412

Please sign in to comment.