Skip to content

Commit

Permalink
🖇 Add linkBlock transformation and title/desc/thumb to link cache (#58)
Browse files Browse the repository at this point in the history
* Update mystjs. Add more definitive return type
* Add linkBlock transformation and title/desc/thumb to link cache

Co-authored-by: Yuxi Wang <[email protected]>
  • Loading branch information
fwkoch and Yxwww authored Apr 19, 2022
1 parent dd11eba commit 09616dd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
7 changes: 6 additions & 1 deletion src/web/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,12 @@ export class DocumentCache implements IDocumentCache {
this.$processed[id] = data;
const { oxa } = data.frontmatter ?? {};
if (oxa && typeof oxa === 'string') {
this.$links[oxa] = `/${id}`;
this.$links[oxa] = {
url: `/${id}`,
title: data.frontmatter.title || undefined,
description: data.frontmatter.description || undefined,
thumbnail: undefined,
};
}
}

Expand Down
19 changes: 16 additions & 3 deletions src/web/transforms/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,36 @@ import { oxaLink, oxaLinkToId } from '@curvenote/blocks';
import { GenericNode, selectAll } from 'mystjs';
import { Root } from './types';

export type LinkLookup = Record<string, string>;
type LinkInfo = {
url: string;
title?: string;
description?: string;
thumbnail?: string;
};

export type LinkLookup = Record<string, LinkInfo>;

export function transformLinks(mdast: Root, lookup: LinkLookup): boolean {
const links = selectAll('link', mdast) as GenericNode[];
const links = selectAll('link,linkBlock', mdast) as GenericNode[];
if (links.length === 0) return false;
let changed = 0;
links.forEach((link) => {
const oxa = link.oxa || oxaLinkToId(link.url);
if (!oxa) return;
link.oxa = oxa;
const key = oxaLink(oxa, false) as string;
const url = lookup[key];
const url = lookup[key].url;
if (url && url !== link.url) {
changed += 1;
// the `internal` flag is picked up in the link renderer (prefetch!)
link.internal = true;
link.url = url;
if (link.type === 'linkBlock') {
// Any values already present on the block override link info
link.title = link.title || lookup[key].title;
link.children = link.children || [{ type: 'text', value: lookup[key].description }];
link.thumbnail = link.thumbnail || lookup[key].thumbnail;
}
}
});
return changed > 0;
Expand Down

0 comments on commit 09616dd

Please sign in to comment.