mdast#Image TypeScript Examples
The following examples show how to use
mdast#Image.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dendronPreview.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
/** Makes the `.url` of the given image note a full path. */
export function makeImageUrlFullPath({
proc,
node,
}: {
proc: Unified.Processor;
node: Image;
}) {
// ignore web images
if (_.some(["http://", "https://"], (ent) => node.url.startsWith(ent))) {
return;
}
// assume that the path is relative to vault
const { wsRoot, vault } = MDUtilsV5.getProcData(proc);
const fpath = path.join(vault2Path({ wsRoot, vault }), decodeURI(node.url));
node.url = fpath;
}
Example #2
Source File: dendronPub.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
static handle(
node: Image,
{ proc, cOpts }: DendronUnifiedHandlerHandleOpts<PluginOpts>
): { node: Image; nextAction?: DendronUnifiedHandlerNextAction } {
const { config } = MDUtilsV5.getProcData(proc);
//handle assetPrefix
const publishingConfig = ConfigUtils.getPublishingConfig(config);
const assetsPrefix = MDUtilsV5.isV5Active(proc)
? publishingConfig.assetsPrefix
: cOpts?.assetsPrefix;
const imageNode = node;
if (!isWebUri(imageNode.url)) {
const imageUrl = _.trim(imageNode.url, "/");
imageNode.url = (assetsPrefix ? assetsPrefix + "/" : "/") + imageUrl;
}
return { node: imageNode };
}
Example #3
Source File: utils.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
static isImage(node: Node): node is Image {
return node.type === DendronASTTypes.IMAGE;
}
Example #4
Source File: remark.test.ts From joplin-utils with MIT License | 6 votes |
it('测试', () => {
const md = unified().use(remarkParse).use(remarkGfm).use(remarkStringify, {
bullet: '-',
fences: true,
incrementListMarker: false,
})
const res: Pick<ResourceProperties, 'id' | 'title'>[] = []
visit(md.parse(data.body), (node) => {
if (node.type !== 'link' && node.type !== 'image') {
return
}
const link = node as Link | Image
if (!link.url.startsWith(':/')) {
return
}
res.push({
id: link.url.slice(2),
title: (link.type === 'link'
? link.title ?? (link.children[0] as any).value
: link.alt) as string,
})
})
console.log('res: ', res)
})
Example #5
Source File: parseInternalLink.ts From joplin-utils with MIT License | 6 votes |
/**
* 解析 markdown 中所有引用的附件资源
* @param content
*/
export function parseInternalLink(content: string): Pick<ResourceProperties, 'id' | 'title'>[] {
const res: Pick<ResourceProperties, 'id' | 'title'>[] = []
visit(mdParser.parse(content), (node) => {
if (node.type !== 'link' && node.type !== 'image') {
return
}
const link = node as Link | Image
if (!link.url.startsWith(':/')) {
return
}
res.push({
id: parseInternalLinkToId(link.url),
title: (link.type === 'link' ? link.title ?? (link.children[0] as any).value : link.alt) as string,
})
})
return res
}
Example #6
Source File: dendronPub.ts From dendron with GNU Affero General Public License v3.0 | 4 votes |
function plugin(this: Unified.Processor, opts?: PluginOpts): Transformer {
const proc = this;
let { overrides, vault } = MDUtilsV4.getDendronData(proc);
const pOpts = MDUtilsV5.getProcOpts(proc);
const { mode } = pOpts;
const pData = MDUtilsV5.getProcData(proc);
const { dest, fname, config, insideNoteRef } = pData;
function transformer(tree: Node, _file: VFile) {
const root = tree as Root;
const { error: engineError, engine } = MDUtilsV4.getEngineFromProc(proc);
const insertTitle = !_.isUndefined(overrides?.insertTitle)
? overrides?.insertTitle
: opts?.insertTitle;
if (mode !== ProcMode.IMPORT && !insideNoteRef && root.children) {
if (!fname || !vault) {
// TODO: tmp
throw new DendronError({
message: `dendronPub - no fname or vault for node: ${JSON.stringify(
tree
)}`,
});
}
let note;
// Special Logic for 403 Error Static Page:
if (fname === "403") {
note = SiteUtils.create403StaticNote({ engine });
} else {
note = NoteUtils.getNoteByFnameFromEngine({
fname,
vault,
engine,
});
}
if (!note) {
throw new DendronError({ message: `no note found for ${fname}` });
}
if (insertTitle) {
const idx = _.findIndex(root.children, (ent) => ent.type !== "yaml");
root.children.splice(
idx,
0,
u(DendronASTTypes.HEADING, { depth: 1 }, [u("text", note.title)])
);
}
}
visitParents(tree, (node, ancestors) => {
const parent = _.last(ancestors);
if (_.isUndefined(parent) || !RemarkUtils.isParent(parent)) return; // root node
if (node.type === DendronASTTypes.HASHTAG) {
const hashtag = node as HashTag;
const parentIndex = _.findIndex(parent.children, node);
if (parentIndex === -1) return;
// For hashtags, convert them to regular links for rendering
// but not if they are inside of a link, otherwise they break link rendering.
if (!ancestors.some((node) => RemarkUtils.isLink(node))) {
node = hashTag2WikiLinkNoteV4(hashtag);
} else {
// If they are inside a link, rendering them as wikilinks will break the link rendering. Convert them to regular text.
node = text(hashtag.value);
}
parent.children[parentIndex] = node;
}
if (node.type === DendronASTTypes.USERTAG) {
const userTag = node as UserTag;
const parentIndex = _.findIndex(parent.children, node);
if (parentIndex === -1) return;
// Convert user tags to regular links for rendering
// but not if they are inside of a link, otherwise they break link rendering.
if (!ancestors.some((node) => RemarkUtils.isLink(node))) {
node = userTag2WikiLinkNoteV4(userTag);
} else {
node = text(userTag.value);
}
parent.children[parentIndex] = node;
}
if (
node.type === DendronASTTypes.WIKI_LINK &&
dest !== DendronASTDest.MD_ENHANCED_PREVIEW
) {
// If the target is Dendron, no processing of links is needed
if (dest === DendronASTDest.MD_DENDRON) return;
const _node = node as WikiLinkNoteV4;
// @ts-ignore
let value = node.value as string;
// we change this later
const valueOrig = value;
let isPublished = true;
const data = _node.data;
vault = MDUtilsV4.getVault(proc, data.vaultName, {
vaultMissingBehavior: VaultMissingBehavior.FALLBACK_TO_ORIGINAL_VAULT,
});
if (engineError) {
addError(proc, engineError);
}
let error: DendronError | undefined;
let note: NoteProps | undefined;
if (mode !== ProcMode.IMPORT) {
note = NoteUtils.getNoteByFnameFromEngine({
fname: valueOrig,
vault,
engine,
});
if (!note) {
error = new DendronError({ message: `no note found. ${value}` });
}
}
let color: string | undefined;
if (mode !== ProcMode.IMPORT && value.startsWith(TAGS_HIERARCHY)) {
const { color: maybeColor, type: colorType } = NoteUtils.color({
fname: value,
vault,
engine,
});
const enableRandomlyColoredTagsConfig =
ConfigUtils.getEnableRandomlyColoredTags(config);
if (
colorType === "configured" ||
(enableRandomlyColoredTagsConfig && !opts?.noRandomlyColoredTags)
) {
color = maybeColor;
}
}
const copts = opts?.wikiLinkOpts;
if (!note && opts?.transformNoPublish) {
const code = StatusCodes.FORBIDDEN;
value = _.toString(code);
addError(
proc,
new DendronError({
message: "no note",
code,
severity: ERROR_SEVERITY.MINOR,
})
);
} else if (note && opts?.transformNoPublish) {
if (error) {
value = _.toString(StatusCodes.FORBIDDEN);
addError(proc, error);
} else if (!config) {
const code = StatusCodes.FORBIDDEN;
value = _.toString(code);
addError(
proc,
new DendronError({
message: "no config",
code,
severity: ERROR_SEVERITY.MINOR,
})
);
} else {
isPublished = SiteUtils.isPublished({
note,
config,
engine,
});
if (!isPublished) {
value = _.toString(StatusCodes.FORBIDDEN);
}
}
}
let useId = copts?.useId;
if (
useId === undefined &&
MDUtilsV5.isV5Active(proc) &&
dest === DendronASTDest.HTML
) {
useId = true;
}
if (note && useId && isPublished) {
if (error) {
addError(proc, error);
} else {
value = note.id;
}
}
const alias = data.alias ? data.alias : value;
const href = SiteUtils.getSiteUrlPathForNote({
addPrefix: pOpts.flavor === ProcFlavor.PUBLISHING,
pathValue: value,
config,
pathAnchor: data.anchorHeader,
});
const exists = true;
// for rehype
//_node.value = newValue;
//_node.value = alias;
const { before, after } = linkExtras({ note, config });
_node.data = {
vaultName: data.vaultName,
alias,
permalink: href,
exists,
hName: "a",
hProperties: {
className: color ? "color-tag" : undefined,
style: color ? `--tag-color: ${color};` : undefined,
href,
},
hChildren: [
...before,
{
type: "text",
value: alias,
},
...after,
],
} as RehypeLinkData;
if (value === "403") {
_node.data = {
alias,
hName: "a",
hProperties: {
title: "Private",
href: "https://wiki.dendron.so/notes/hfyvYGJZQiUwQaaxQO27q.html",
target: "_blank",
class: "private",
},
hChildren: [
{
type: "text",
value: `${alias} (Private)`,
},
],
} as RehypeLinkData;
}
}
if (node.type === DendronASTTypes.REF_LINK_V2) {
// If the target is Dendron, no processing of refs is needed
if (dest === DendronASTDest.MD_DENDRON) return;
// we have custom compiler for markdown to handle note ref
const ndata = node.data as NoteRefDataV4;
const copts: NoteRefsOptsV2 = {
wikiLinkOpts: opts?.wikiLinkOpts,
};
const procOpts = MDUtilsV4.getProcOpts(proc);
const { data } = convertNoteRefASTV2({
link: ndata.link,
proc,
compilerOpts: copts,
procOpts,
});
if (data) {
parent.children = replacedUnrenderedRefWithConvertedData(
data,
parent.children
);
}
}
if (node.type === DendronASTTypes.BLOCK_ANCHOR) {
// no transform
if (dest !== DendronASTDest.HTML) {
return;
}
const anchorHTML = blockAnchor2html(node as BlockAnchor);
let target: Node | undefined;
const grandParent = ancestors[ancestors.length - 2];
if (
RemarkUtils.isParagraph(parent) &&
parent.children.length === 1 &&
isNotUndefined(grandParent) &&
RemarkUtils.isRoot(grandParent)
) {
// If the block anchor is at the top level, then it references the block before it
const parentIndex = _.indexOf(grandParent.children, parent);
const previous = grandParent.children[parentIndex - 1];
if (_.isUndefined(previous)) {
// Block anchor at the very start of the note, just add anchor to the start
target = grandParent;
} else {
// There's an actual block before the anchor
target = previous;
}
} else if (RemarkUtils.isTableRow(grandParent)) {
// An anchor inside a table references the whole table.
const greatGrandParent = ancestors[ancestors.length - 3];
if (
isNotUndefined(greatGrandParent) &&
RemarkUtils.isTable(greatGrandParent)
) {
// The table HTML generation drops anything not attached to a cell, so we put this in the first cell instead.
target = greatGrandParent.children[0]?.children[0];
}
} else {
// Otherwise, it references the block it's inside
target = parent;
}
if (_.isUndefined(target)) return;
if (RemarkUtils.isList(target)) {
// Can't install as a child of the list, has to go into a list item
target = target.children[0];
}
if (RemarkUtils.isTable(target)) {
// Can't install as a child of the table directly, has to go into a table cell
target = target.children[0].children[0];
}
if (RemarkUtils.isParent(target)) {
// Install the block anchor at the target node
target.children.unshift(anchorHTML);
} else if (RemarkUtils.isRoot(target)) {
// If the anchor is the first thing in the note, anchorHTML goes to the start of the document
target.children.unshift(anchorHTML);
} else if (RemarkUtils.isParent(grandParent)) {
// For some elements (for example code blocks) we can't install the block anchor on them.
// In that case we at least put a link before the element so that the link will at least work.
const targetIndex = _.indexOf(grandParent.children, target);
const targetWrapper = paragraph([
anchorHTML,
grandParent.children[targetIndex],
]);
grandParent.children.splice(targetIndex, 1, targetWrapper);
}
// Remove the block anchor itself since we install the anchor at the target
const index = _.indexOf(parent.children, node);
parent!.children.splice(index, 1);
// We might be adding and removing siblings here. We must return the index of the next sibling to traverse.
if (target === parent) {
// In this case, we removed block anchor but added a node to the start.
// As a result, the indices match and traversal can continue.
return;
} else if (parent.children.length === 0) {
// After removing the block anchor, there are no siblings left in the parent to traverse.
return -1;
} else {
// Otherwise, the next sibling got shifted down by 1 index, it will be at the same index as the block anchor.
return index;
}
}
// The url correction needs to happen for both regular and extended images
if (ImageNodeHandler.match(node, { pData, pOpts })) {
const { nextAction } = ImageNodeHandler.handle(node as Image, {
proc,
parent,
cOpts: opts,
});
if (nextAction) {
return nextAction;
}
}
if (
node.type === DendronASTTypes.EXTENDED_IMAGE &&
dest === DendronASTDest.HTML
) {
const index = _.indexOf(parent.children, node);
// Replace with the HTML containing the image including custom properties
parent.children.splice(
index,
1,
extendedImage2html(node as ExtendedImage)
);
}
return; // continue traversal
});
return tree;
}
return transformer;
}
Example #7
Source File: descriptionFormatter.ts From prettier-plugin-jsdoc with MIT License | 4 votes |
/**
* Trim, make single line with capitalized text. Insert dot if flag for it is
* set to true and last character is a word character
*
* @private
*/
function formatDescription(
tag: string,
text: string,
options: AllOptions,
formatOptions: FormatOptions,
): string {
if (!text) return text;
const { printWidth } = options;
const { tagStringLength = 0, beginningSpace } = formatOptions;
/**
* change list with dash to dot for example:
* 1- a thing
*
* to
*
* 1. a thing
*/
text = text.replace(/^(\d+)[-][\s|]+/g, "$1. "); // Start
text = text.replace(/\n+(\s*\d+)[-][\s]+/g, "\n$1. ");
const fencedCodeBlocks = text.matchAll(/```\S*?\n[\s\S]+?```/gm);
const indentedCodeBlocks = text.matchAll(
/^\r?\n^(?:(?:(?:[ ]{4}|\t).*(?:\r?\n|$))+)/gm,
);
const allCodeBlocks = [...fencedCodeBlocks, ...indentedCodeBlocks];
const tables: string[] = [];
text = text.replace(
/((\n|^)\|[\s\S]*?)((\n[^|])|$)/g,
(code, _1, _2, _3, _, offs: number) => {
// If this potential table is inside a code block, don't touch it
for (const block of allCodeBlocks) {
if (
block.index !== undefined &&
block.index <= offs + 1 &&
offs + code.length + 1 <= block.index + block[0].length
) {
return code;
}
}
code = _3 ? code.slice(0, -1) : code;
tables.push(code);
return `\n\n${TABLE}\n\n${_3 ? _3.slice(1) : ""}`;
},
);
if (
options.jsdocCapitalizeDescription &&
!TAGS_PEV_FORMATE_DESCRIPTION.includes(tag)
) {
text = capitalizer(text);
}
text = `${tagStringLength ? `${"!".repeat(tagStringLength - 1)}?` : ""}${
text.startsWith("```") ? "\n" : ""
}${text}`;
let tableIndex = 0;
const rootAst = fromMarkdown(text);
function stringifyASTWithoutChildren(
mdAst: Content | Root,
intention: string,
parent: Content | Root | null,
) {
if (mdAst.type === "inlineCode") {
return `\`${mdAst.value}\``;
}
if (mdAst.type === "code") {
let result = mdAst.value || "";
let _intention = intention;
if (result) {
// Remove two space from lines, maybe added previous format
if (mdAst.lang) {
const supportParsers = parserSynonyms(mdAst.lang.toLowerCase());
const parser = supportParsers?.includes(options.parser as any)
? options.parser
: supportParsers?.[0] || mdAst.lang;
result = formatCode(result, intention, {
...options,
parser,
jsdocKeepUnParseAbleExampleIndent: true,
});
} else if (options.jsdocPreferCodeFences || false) {
result = formatCode(result, _intention, {
...options,
jsdocKeepUnParseAbleExampleIndent: true,
});
} else {
_intention = intention + " ".repeat(4);
result = formatCode(result, _intention, {
...options,
jsdocKeepUnParseAbleExampleIndent: true,
});
}
}
const addFence = options.jsdocPreferCodeFences || !!mdAst.lang;
result = addFence ? result : result.trimEnd();
return result
? addFence
? `\n\n${_intention}\`\`\`${mdAst.lang || ""}${result}\`\`\``
: `\n${result}`
: "";
}
if ((mdAst as Text).value === TABLE) {
if (parent) {
(parent as any).costumeType = TABLE;
}
if (tables.length > 0) {
let result = tables?.[tableIndex] || "";
tableIndex++;
if (result) {
result = format(result, {
...options,
parser: "markdown",
}).trim();
}
return `${
result
? `\n\n${intention}${result.split("\n").join(`\n${intention}`)}`
: (mdAst as Text).value
}`;
}
}
if (mdAst.type === "break") {
return `\\\n`;
}
return ((mdAst as Text).value ||
(mdAst as Link).title ||
(mdAst as Image).alt ||
"") as string;
}
function stringyfy(
mdAst: Content | Root,
intention: string,
parent: Content | Root | null,
): string {
if (!Array.isArray((mdAst as Root).children)) {
return stringifyASTWithoutChildren(mdAst, intention, parent);
}
return ((mdAst as Root).children as Content[])
.map((ast, index) => {
switch (ast.type) {
case "listItem": {
let _listCount = `\n${intention}- `;
// .replace(/((?!(^))\n)/g, "\n" + _intention);
if (typeof (mdAst as List).start === "number") {
const count = index + (((mdAst as List).start as number) ?? 1);
_listCount = `\n${intention}${count}. `;
}
const _intention = intention + " ".repeat(_listCount.length - 1);
const result = stringyfy(ast, _intention, mdAst).trim();
return `${_listCount}${result}`;
}
case "list": {
let end = "";
/**
* Add empty line after list if that is end of description
* issue: {@link https://github.com/hosseinmd/prettier-plugin-jsdoc/issues/98}
*/
if (
tag !== DESCRIPTION &&
mdAst.type === "root" &&
index === mdAst.children.length - 1
) {
end = "\n";
}
return `\n${stringyfy(ast, intention, mdAst)}${end}`;
}
case "paragraph": {
const paragraph = stringyfy(ast, intention, parent);
if ((ast as any).costumeType === TABLE) {
return paragraph;
}
return `\n\n${paragraph
/**
* Break by backslash\
* issue: https://github.com/hosseinmd/prettier-plugin-jsdoc/issues/102
*/
.split("\\\n")
.map((_paragraph) => {
const links: string[] = [];
// Find jsdoc links and remove spaces
_paragraph = _paragraph.replace(
/{@(link|linkcode|linkplain)[\s](([^{}])*)}/g,
(_, tag: string, link: string) => {
links.push(link);
return `{@${tag}${"_".repeat(link.length)}}`;
},
);
_paragraph = _paragraph.replace(/\s+/g, " "); // Make single line
if (
options.jsdocCapitalizeDescription &&
!TAGS_PEV_FORMATE_DESCRIPTION.includes(tag)
)
_paragraph = capitalizer(_paragraph);
if (options.jsdocDescriptionWithDot)
_paragraph = _paragraph.replace(/([\w\p{L}])$/u, "$1."); // Insert dot if needed
let result = breakDescriptionToLines(
_paragraph,
printWidth,
intention,
);
// Replace links
result = result.replace(
/{@(link|linkcode|linkplain)([_]+)}/g,
(original: string, tag: string, underline: string) => {
const link = links[0];
if (link.length === underline.length) {
links.shift();
return `{@${tag} ${link}}`;
}
return original;
},
);
return result;
})
.join("\\\n")}`;
}
case "strong": {
return `**${stringyfy(ast, intention, mdAst)}**`;
}
case "emphasis": {
return `_${stringyfy(ast, intention, mdAst)}_`;
}
case "heading": {
return `\n\n${intention}${"#".repeat(ast.depth)} ${stringyfy(
ast,
intention,
mdAst,
)}`;
}
case "link":
case "image": {
return `[${stringyfy(ast, intention, mdAst)}](${ast.url})`;
}
case "linkReference": {
return `[${stringyfy(ast, intention, mdAst)}][${ast.label}]`;
}
case "definition": {
return `\n\n[${ast.label}]: ${ast.url}`;
}
case "blockquote": {
const paragraph = stringyfy(ast, "", mdAst);
return `${intention}> ${paragraph
.trim()
.replace(/(\n+)/g, `$1${intention}> `)}`;
}
}
return stringyfy(ast, intention, mdAst);
})
.join("");
}
let result = stringyfy(rootAst, beginningSpace, null);
result = result.replace(/^[\s\n]+/g, "");
result = result.replace(/^([!]+\?)/g, "");
return result;
}