Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mustache lambdas emiting any object including components (extended #951) #955

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 28 additions & 19 deletions mwdb/web/src/commons/helpers/renderTokens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ export type Token = {

export type Option = {
searchEndpoint: string;
lambdaResults?: { [id: string]: any };
};

// Custom renderer into React components
export function renderTokens(tokens: Token[], options?: Option): any {
export function renderTokens(tokens: Token[], options: Option): any {
const renderers = {
text(token: Token) {
return token.tokens
Expand Down Expand Up @@ -89,24 +90,32 @@ export function renderTokens(tokens: Token[], options?: Option): any {
);
},
link(token: Token) {
if (token.href && token.href.startsWith("search#")) {
const query = token.href.slice("search#".length);
const search =
"?" +
new URLSearchParams({
q: decodeURIComponent(query),
}).toString();
return (
<Link
key={uniqueId()}
to={{
pathname: options?.searchEndpoint,
search,
}}
>
{renderTokens(token.tokens ?? [], options)}
</Link>
);
if (token.href) {
if (token.href.startsWith("search#")) {
const query = token.href.slice("search#".length);
const search =
"?" +
new URLSearchParams({
q: decodeURIComponent(query),
}).toString();
return (
<Link
key={uniqueId()}
to={{
pathname: options?.searchEndpoint,
search,
}}
>
{renderTokens(token.tokens ?? [], options)}
</Link>
);
} else if (token.href.startsWith("lambda#")) {
const id = token.href.slice("lambda#".length);
if (!options.lambdaResults?.hasOwnProperty(id)) {
return <i>{`(BUG: No lambda result for ${id})`}</i>;
}
return options.lambdaResults[id];
}
}
return (
<a key={uniqueId()} href={token.href}>
Expand Down
74 changes: 62 additions & 12 deletions mwdb/web/src/components/RichAttribute/MarkedMustache.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import _, { uniqueId } from "lodash";
import Mustache, { Context } from "mustache";
import { marked, Tokenizer } from "marked";
import {
Expand All @@ -6,6 +7,7 @@ import {
renderTokens,
Token,
} from "@mwdb-web/commons/helpers";
import { fromPlugins } from "@mwdb-web/commons/plugins";

/**
* Markdown with Mustache templates for React
Expand All @@ -24,6 +26,10 @@ function appendToLastElement(array: string[], value: string) {
return [...array.slice(0, -1), array[array.length - 1] + value];
}

function isFunction(obj: Object): boolean {
return typeof obj === "function";
}

function splitName(name: string) {
if (name === ".")
// Special case for "this"
Expand Down Expand Up @@ -80,13 +86,22 @@ class MustacheContext extends Mustache.Context {
globalView: any;
lastPath: string[] | null;
lastValue: string | null;
constructor(view: Object, parent?: Context, globalView?: any) {
lambdaResults: { [id: string]: any };
lambdas: { [name: string]: Function };
constructor(
view: Object,
parent?: MustacheContext,
globalView?: any,
lambdas?: { [name: string]: Function }
) {
super(view, parent);
this.globalView = globalView === undefined ? view : globalView;
// Stored absolute path of last lookup
this.lastPath = null;
// Stored value from last lookup to determine the type
this.lastValue = null;
this.lambdaResults = parent ? parent.lambdaResults : {};
this.lambdas = parent ? parent.lambdas : lambdas || {};
}

push(view: Object): Context {
Expand All @@ -111,8 +126,29 @@ class MustacheContext extends Mustache.Context {
searchable = true;
}
if (!name) return undefined;
const path = splitName(name);

let currentObject = this.view;
if (this.lambdas[name]) {
const lambda = this.lambdas[name];
const currentContext = this;
return function lambdaFunction(
this: any,
text: string,
renderer: Function
): string {
let lambdaResultId = uniqueId("lambda_result");
let result = lambda.call(this, text, renderer);
if (typeof result !== "string") {
currentContext.lambdaResults[lambdaResultId] = result;
// Emit reference in markdown
return `[](lambda#${lambdaResultId})`;
} else {
return result;
}
};
}

const path = splitName(name);
for (let element of path) {
if (!Object.prototype.hasOwnProperty.call(currentObject, element))
return undefined;
Expand All @@ -121,10 +157,7 @@ class MustacheContext extends Mustache.Context {
this.lastPath = this.getParentPath()!.concat(path);
this.lastValue = currentObject;
if (searchable) {
if (
typeof currentObject === "object" ||
typeof currentObject === "function"
)
if (isFunction(currentObject) || typeof currentObject === "object")
// Non-primitives are not directly searchable
return undefined;
const query = makeQuery(
Expand Down Expand Up @@ -157,10 +190,6 @@ class MustacheWriter extends Mustache.Writer {
: escapeMarkdown(value);
return "";
}

render(template: string, view: Object) {
return super.render(template, new MustacheContext(view));
}
}

// Overrides to not use HTML escape
Expand Down Expand Up @@ -213,10 +242,31 @@ const mustacheWriter = new MustacheWriter();
const markedTokenizer = new MarkedTokenizer();

export function renderValue(template: string, value: Object, options: Option) {
const markdown = mustacheWriter.render(template, value);
const lambdas = fromPlugins("mustacheExtensions").reduce((prev, curr) => {
return {
...prev,
...curr,
};
}, {});
const context = new MustacheContext(
{
...value,
},
undefined,
undefined,
lambdas
);
const markdown = mustacheWriter.render(template, context);
const tokens = marked.lexer(markdown, {
...marked.defaults,
tokenizer: markedTokenizer,
}) as Token[];
return <div>{renderTokens(tokens, options)}</div>;
return (
<div>
{renderTokens(tokens, {
...options,
lambdaResults: context.lambdaResults,
})}
</div>
);
}
Loading