Calling a TW macro from a JS widget?

If macro is written in JS, then very easy, require it and use its exported .run function

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const dateDurationMacro = require('$:/plugins/linonetwo/tw-calendar/date-duration-macro');
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const getDateDuration = dateDurationMacro.run as (startDateString: string, endDateString: string) => string;

// use it
const startDate = $tw.utils.formatDateString(argument.event.start, '[UTC]YYYY0MM0DD0hh0mm0ss0XXX');
        const endDate = $tw.utils.formatDateString(argument.event.end, '[UTC]YYYY0MM0DD0hh0mm0ss0XXX');
        const durationText = getDateDuration(startDate, endDate);

If it is written in wikitext, then wikify it by makeChildWidget, like this

        const childTree = $tw.wiki.parseText('text/vnd.tiddlywiki', tiddler.fields.caption).tree;
        const astNode = { type: 'tiddler', children: childTree };
        const newWidgetNode = context.widget.makeChildWidget(astNode, { variables: context.widget.variables });
        // render tw content needs a temp real dom element, can't use vdom from `createElement`
        const temporaryEle = context.widget.document.createElement('div');
        // eslint-disable-next-line unicorn/no-null
        newWidgetNode.render(temporaryEle, null);
        captionResult = temporaryEle.textContent;

The variables here is very important, you can get it from parentWidget.variables.

Examples are from Calendar and Agenda plugin tw-calendar with Mobile friendly agenda page layout

1 Like