You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3255 lines
261 KiB

/*
THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
if you want to view the source visit the plugins github repository
*/
'use strict';
var obsidian = require('obsidian');
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var lexer = createCommonjsModule(function (module) {
module.exports = Lexer;
Lexer.defunct = function (chr) {
throw new Error("Unexpected character at index " + (this.index - 1) + ": " + chr);
};
function Lexer(defunct) {
if (typeof defunct !== "function") defunct = Lexer.defunct;
var tokens = [];
var rules = [];
var remove = 0;
this.state = 0;
this.index = 0;
this.input = "";
this.addRule = function (pattern, action, start) {
var global = pattern.global;
if (!global) {
var flags = "g";
if (pattern.multiline) flags += "m";
if (pattern.ignoreCase) flags += "i";
pattern = new RegExp(pattern.source, flags);
}
if (Object.prototype.toString.call(start) !== "[object Array]") start = [0];
rules.push({
pattern: pattern,
global: global,
action: action,
start: start
});
return this;
};
this.setInput = function (input) {
remove = 0;
this.state = 0;
this.index = 0;
tokens.length = 0;
this.input = input;
return this;
};
this.lex = function () {
if (tokens.length) return tokens.shift();
this.reject = true;
while (this.index <= this.input.length) {
var matches = scan.call(this).splice(remove);
var index = this.index;
while (matches.length) {
if (this.reject) {
var match = matches.shift();
var result = match.result;
var length = match.length;
this.index += length;
this.reject = false;
remove++;
var token = match.action.apply(this, result);
if (this.reject) this.index = result.index;
else if (typeof token !== "undefined") {
switch (Object.prototype.toString.call(token)) {
case "[object Array]":
tokens = token.slice(1);
token = token[0];
default:
if (length) remove = 0;
return token;
}
}
} else break;
}
var input = this.input;
if (index < input.length) {
if (this.reject) {
remove = 0;
var token = defunct.call(this, input.charAt(this.index++));
if (typeof token !== "undefined") {
if (Object.prototype.toString.call(token) === "[object Array]") {
tokens = token.slice(1);
return token[0];
} else return token;
}
} else {
if (this.index !== index) remove = 0;
this.reject = true;
}
} else if (matches.length)
this.reject = true;
else break;
}
};
function scan() {
var matches = [];
var index = 0;
var state = this.state;
var lastIndex = this.index;
var input = this.input;
for (var i = 0, length = rules.length; i < length; i++) {
var rule = rules[i];
var start = rule.start;
var states = start.length;
if ((!states || start.indexOf(state) >= 0) ||
(state % 2 && states === 1 && !start[0])) {
var pattern = rule.pattern;
pattern.lastIndex = lastIndex;
var result = pattern.exec(input);
if (result && result.index === lastIndex) {
var j = matches.push({
result: result,
action: rule.action,
length: result[0].length
});
if (rule.global) index = j;
while (--j > index) {
var k = j - 1;
if (matches[j].length > matches[k].length) {
var temple = matches[j];
matches[j] = matches[k];
matches[k] = temple;
}
}
}
}
}
return matches;
}
}
});
/*!
* Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
var faDice = {
prefix: 'fas',
iconName: 'dice',
icon: [640, 512, [], "f522", "M592 192H473.26c12.69 29.59 7.12 65.2-17 89.32L320 417.58V464c0 26.51 21.49 48 48 48h224c26.51 0 48-21.49 48-48V240c0-26.51-21.49-48-48-48zM480 376c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24zm-46.37-186.7L258.7 14.37c-19.16-19.16-50.23-19.16-69.39 0L14.37 189.3c-19.16 19.16-19.16 50.23 0 69.39L189.3 433.63c19.16 19.16 50.23 19.16 69.39 0L433.63 258.7c19.16-19.17 19.16-50.24 0-69.4zM96 248c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24zm128 128c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24zm0-128c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24zm0-128c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24zm128 128c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24z"]
};
/*!
* Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
var faCopy = {
prefix: 'far',
iconName: 'copy',
icon: [448, 512, [], "f0c5", "M433.941 65.941l-51.882-51.882A48 48 0 0 0 348.118 0H176c-26.51 0-48 21.49-48 48v48H48c-26.51 0-48 21.49-48 48v320c0 26.51 21.49 48 48 48h224c26.51 0 48-21.49 48-48v-48h80c26.51 0 48-21.49 48-48V99.882a48 48 0 0 0-14.059-33.941zM266 464H54a6 6 0 0 1-6-6V150a6 6 0 0 1 6-6h74v224c0 26.51 21.49 48 48 48h96v42a6 6 0 0 1-6 6zm128-96H182a6 6 0 0 1-6-6V54a6 6 0 0 1 6-6h106v88c0 13.255 10.745 24 24 24h88v202a6 6 0 0 1-6 6zm6-256h-64V48h9.632c1.591 0 3.117.632 4.243 1.757l48.368 48.368a6 6 0 0 1 1.757 4.243V112z"]
};
/*!
* Font Awesome Free 5.15.3 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
var noop = function noop() {};
var _WINDOW = {};
var _DOCUMENT = {};
var _MUTATION_OBSERVER = null;
var _PERFORMANCE = {
mark: noop,
measure: noop
};
try {
if (typeof window !== 'undefined') _WINDOW = window;
if (typeof document !== 'undefined') _DOCUMENT = document;
if (typeof MutationObserver !== 'undefined') _MUTATION_OBSERVER = MutationObserver;
if (typeof performance !== 'undefined') _PERFORMANCE = performance;
} catch (e) {}
var _ref = _WINDOW.navigator || {},
_ref$userAgent = _ref.userAgent,
userAgent = _ref$userAgent === void 0 ? '' : _ref$userAgent;
var WINDOW = _WINDOW;
var DOCUMENT = _DOCUMENT;
var PERFORMANCE = _PERFORMANCE;
!!WINDOW.document;
var IS_DOM = !!DOCUMENT.documentElement && !!DOCUMENT.head && typeof DOCUMENT.addEventListener === 'function' && typeof DOCUMENT.createElement === 'function';
~userAgent.indexOf('MSIE') || ~userAgent.indexOf('Trident/');
var NAMESPACE_IDENTIFIER = '___FONT_AWESOME___';
var DEFAULT_FAMILY_PREFIX = 'fa';
var DEFAULT_REPLACEMENT_CLASS = 'svg-inline--fa';
var DATA_FA_I2SVG = 'data-fa-i2svg';
(function () {
try {
return process.env.NODE_ENV === 'production';
} catch (e) {
return false;
}
})();
var DUOTONE_CLASSES = {
GROUP: 'group',
SWAP_OPACITY: 'swap-opacity',
PRIMARY: 'primary',
SECONDARY: 'secondary'
};
var initial = WINDOW.FontAwesomeConfig || {};
function getAttrConfig(attr) {
var element = DOCUMENT.querySelector('script[' + attr + ']');
if (element) {
return element.getAttribute(attr);
}
}
function coerce(val) {
// Getting an empty string will occur if the attribute is set on the HTML tag but without a value
// We'll assume that this is an indication that it should be toggled to true
// For example <script data-search-pseudo-elements src="..."></script>
if (val === '') return true;
if (val === 'false') return false;
if (val === 'true') return true;
return val;
}
if (DOCUMENT && typeof DOCUMENT.querySelector === 'function') {
var attrs = [['data-family-prefix', 'familyPrefix'], ['data-replacement-class', 'replacementClass'], ['data-auto-replace-svg', 'autoReplaceSvg'], ['data-auto-add-css', 'autoAddCss'], ['data-auto-a11y', 'autoA11y'], ['data-search-pseudo-elements', 'searchPseudoElements'], ['data-observe-mutations', 'observeMutations'], ['data-mutate-approach', 'mutateApproach'], ['data-keep-original-source', 'keepOriginalSource'], ['data-measure-performance', 'measurePerformance'], ['data-show-missing-icons', 'showMissingIcons']];
attrs.forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
attr = _ref2[0],
key = _ref2[1];
var val = coerce(getAttrConfig(attr));
if (val !== undefined && val !== null) {
initial[key] = val;
}
});
}
var _default = {
familyPrefix: DEFAULT_FAMILY_PREFIX,
replacementClass: DEFAULT_REPLACEMENT_CLASS,
autoReplaceSvg: true,
autoAddCss: true,
autoA11y: true,
searchPseudoElements: false,
observeMutations: true,
mutateApproach: 'async',
keepOriginalSource: true,
measurePerformance: false,
showMissingIcons: true
};
var _config = _objectSpread({}, _default, initial);
if (!_config.autoReplaceSvg) _config.observeMutations = false;
var config = _objectSpread({}, _config);
WINDOW.FontAwesomeConfig = config;
var w = WINDOW || {};
if (!w[NAMESPACE_IDENTIFIER]) w[NAMESPACE_IDENTIFIER] = {};
if (!w[NAMESPACE_IDENTIFIER].styles) w[NAMESPACE_IDENTIFIER].styles = {};
if (!w[NAMESPACE_IDENTIFIER].hooks) w[NAMESPACE_IDENTIFIER].hooks = {};
if (!w[NAMESPACE_IDENTIFIER].shims) w[NAMESPACE_IDENTIFIER].shims = [];
var namespace = w[NAMESPACE_IDENTIFIER];
var functions = [];
var listener = function listener() {
DOCUMENT.removeEventListener('DOMContentLoaded', listener);
loaded = 1;
functions.map(function (fn) {
return fn();
});
};
var loaded = false;
if (IS_DOM) {
loaded = (DOCUMENT.documentElement.doScroll ? /^loaded|^c/ : /^loaded|^i|^c/).test(DOCUMENT.readyState);
if (!loaded) DOCUMENT.addEventListener('DOMContentLoaded', listener);
}
typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function';
typeof setImmediate === 'undefined' ? setTimeout : setImmediate;
var meaninglessTransform = {
size: 16,
x: 0,
y: 0,
rotate: 0,
flipX: false,
flipY: false
};
function insertCss(css) {
if (!css || !IS_DOM) {
return;
}
var style = DOCUMENT.createElement('style');
style.setAttribute('type', 'text/css');
style.innerHTML = css;
var headChildren = DOCUMENT.head.childNodes;
var beforeChild = null;
for (var i = headChildren.length - 1; i > -1; i--) {
var child = headChildren[i];
var tagName = (child.tagName || '').toUpperCase();
if (['STYLE', 'LINK'].indexOf(tagName) > -1) {
beforeChild = child;
}
}
DOCUMENT.head.insertBefore(style, beforeChild);
return css;
}
var idPool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function nextUniqueId() {
var size = 12;
var id = '';
while (size-- > 0) {
id += idPool[Math.random() * 62 | 0];
}
return id;
}
function htmlEscape(str) {
return "".concat(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function joinAttributes(attributes) {
return Object.keys(attributes || {}).reduce(function (acc, attributeName) {
return acc + "".concat(attributeName, "=\"").concat(htmlEscape(attributes[attributeName]), "\" ");
}, '').trim();
}
function joinStyles(styles) {
return Object.keys(styles || {}).reduce(function (acc, styleName) {
return acc + "".concat(styleName, ": ").concat(styles[styleName], ";");
}, '');
}
function transformIsMeaningful(transform) {
return transform.size !== meaninglessTransform.size || transform.x !== meaninglessTransform.x || transform.y !== meaninglessTransform.y || transform.rotate !== meaninglessTransform.rotate || transform.flipX || transform.flipY;
}
function transformForSvg(_ref) {
var transform = _ref.transform,
containerWidth = _ref.containerWidth,
iconWidth = _ref.iconWidth;
var outer = {
transform: "translate(".concat(containerWidth / 2, " 256)")
};
var innerTranslate = "translate(".concat(transform.x * 32, ", ").concat(transform.y * 32, ") ");
var innerScale = "scale(".concat(transform.size / 16 * (transform.flipX ? -1 : 1), ", ").concat(transform.size / 16 * (transform.flipY ? -1 : 1), ") ");
var innerRotate = "rotate(".concat(transform.rotate, " 0 0)");
var inner = {
transform: "".concat(innerTranslate, " ").concat(innerScale, " ").concat(innerRotate)
};
var path = {
transform: "translate(".concat(iconWidth / 2 * -1, " -256)")
};
return {
outer: outer,
inner: inner,
path: path
};
}
var ALL_SPACE = {
x: 0,
y: 0,
width: '100%',
height: '100%'
};
function fillBlack(abstract) {
var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (abstract.attributes && (abstract.attributes.fill || force)) {
abstract.attributes.fill = 'black';
}
return abstract;
}
function deGroup(abstract) {
if (abstract.tag === 'g') {
return abstract.children;
} else {
return [abstract];
}
}
function makeIconMasking (_ref) {
var children = _ref.children,
attributes = _ref.attributes,
main = _ref.main,
mask = _ref.mask,
explicitMaskId = _ref.maskId,
transform = _ref.transform;
var mainWidth = main.width,
mainPath = main.icon;
var maskWidth = mask.width,
maskPath = mask.icon;
var trans = transformForSvg({
transform: transform,
containerWidth: maskWidth,
iconWidth: mainWidth
});
var maskRect = {
tag: 'rect',
attributes: _objectSpread({}, ALL_SPACE, {
fill: 'white'
})
};
var maskInnerGroupChildrenMixin = mainPath.children ? {
children: mainPath.children.map(fillBlack)
} : {};
var maskInnerGroup = {
tag: 'g',
attributes: _objectSpread({}, trans.inner),
children: [fillBlack(_objectSpread({
tag: mainPath.tag,
attributes: _objectSpread({}, mainPath.attributes, trans.path)
}, maskInnerGroupChildrenMixin))]
};
var maskOuterGroup = {
tag: 'g',
attributes: _objectSpread({}, trans.outer),
children: [maskInnerGroup]
};
var maskId = "mask-".concat(explicitMaskId || nextUniqueId());
var clipId = "clip-".concat(explicitMaskId || nextUniqueId());
var maskTag = {
tag: 'mask',
attributes: _objectSpread({}, ALL_SPACE, {
id: maskId,
maskUnits: 'userSpaceOnUse',
maskContentUnits: 'userSpaceOnUse'
}),
children: [maskRect, maskOuterGroup]
};
var defs = {
tag: 'defs',
children: [{
tag: 'clipPath',
attributes: {
id: clipId
},
children: deGroup(maskPath)
}, maskTag]
};
children.push(defs, {
tag: 'rect',
attributes: _objectSpread({
fill: 'currentColor',
'clip-path': "url(#".concat(clipId, ")"),
mask: "url(#".concat(maskId, ")")
}, ALL_SPACE)
});
return {
children: children,
attributes: attributes
};
}
function makeIconStandard (_ref) {
var children = _ref.children,
attributes = _ref.attributes,
main = _ref.main,
transform = _ref.transform,
styles = _ref.styles;
var styleString = joinStyles(styles);
if (styleString.length > 0) {
attributes['style'] = styleString;
}
if (transformIsMeaningful(transform)) {
var trans = transformForSvg({
transform: transform,
containerWidth: main.width,
iconWidth: main.width
});
children.push({
tag: 'g',
attributes: _objectSpread({}, trans.outer),
children: [{
tag: 'g',
attributes: _objectSpread({}, trans.inner),
children: [{
tag: main.icon.tag,
children: main.icon.children,
attributes: _objectSpread({}, main.icon.attributes, trans.path)
}]
}]
});
} else {
children.push(main.icon);
}
return {
children: children,
attributes: attributes
};
}
function asIcon (_ref) {
var children = _ref.children,
main = _ref.main,
mask = _ref.mask,
attributes = _ref.attributes,
styles = _ref.styles,
transform = _ref.transform;
if (transformIsMeaningful(transform) && main.found && !mask.found) {
var width = main.width,
height = main.height;
var offset = {
x: width / height / 2,
y: 0.5
};
attributes['style'] = joinStyles(_objectSpread({}, styles, {
'transform-origin': "".concat(offset.x + transform.x / 16, "em ").concat(offset.y + transform.y / 16, "em")
}));
}
return [{
tag: 'svg',
attributes: attributes,
children: children
}];
}
function asSymbol (_ref) {
var prefix = _ref.prefix,
iconName = _ref.iconName,
children = _ref.children,
attributes = _ref.attributes,
symbol = _ref.symbol;
var id = symbol === true ? "".concat(prefix, "-").concat(config.familyPrefix, "-").concat(iconName) : symbol;
return [{
tag: 'svg',
attributes: {
style: 'display: none;'
},
children: [{
tag: 'symbol',
attributes: _objectSpread({}, attributes, {
id: id
}),
children: children
}]
}];
}
function makeInlineSvgAbstract(params) {
var _params$icons = params.icons,
main = _params$icons.main,
mask = _params$icons.mask,
prefix = params.prefix,
iconName = params.iconName,
transform = params.transform,
symbol = params.symbol,
title = params.title,
maskId = params.maskId,
titleId = params.titleId,
extra = params.extra,
_params$watchable = params.watchable,
watchable = _params$watchable === void 0 ? false : _params$watchable;
var _ref = mask.found ? mask : main,
width = _ref.width,
height = _ref.height;
var isUploadedIcon = prefix === 'fak';
var widthClass = isUploadedIcon ? '' : "fa-w-".concat(Math.ceil(width / height * 16));
var attrClass = [config.replacementClass, iconName ? "".concat(config.familyPrefix, "-").concat(iconName) : '', widthClass].filter(function (c) {
return extra.classes.indexOf(c) === -1;
}).filter(function (c) {
return c !== '' || !!c;
}).concat(extra.classes).join(' ');
var content = {
children: [],
attributes: _objectSpread({}, extra.attributes, {
'data-prefix': prefix,
'data-icon': iconName,
'class': attrClass,
'role': extra.attributes.role || 'img',
'xmlns': 'http://www.w3.org/2000/svg',
'viewBox': "0 0 ".concat(width, " ").concat(height)
})
};
var uploadedIconWidthStyle = isUploadedIcon && !~extra.classes.indexOf('fa-fw') ? {
width: "".concat(width / height * 16 * 0.0625, "em")
} : {};
if (watchable) {
content.attributes[DATA_FA_I2SVG] = '';
}
if (title) content.children.push({
tag: 'title',
attributes: {
id: content.attributes['aria-labelledby'] || "title-".concat(titleId || nextUniqueId())
},
children: [title]
});
var args = _objectSpread({}, content, {
prefix: prefix,
iconName: iconName,
main: main,
mask: mask,
maskId: maskId,
transform: transform,
symbol: symbol,
styles: _objectSpread({}, uploadedIconWidthStyle, extra.styles)
});
var _ref2 = mask.found && main.found ? makeIconMasking(args) : makeIconStandard(args),
children = _ref2.children,
attributes = _ref2.attributes;
args.children = children;
args.attributes = attributes;
if (symbol) {
return asSymbol(args);
} else {
return asIcon(args);
}
}
var noop$1 = function noop() {};
config.measurePerformance && PERFORMANCE && PERFORMANCE.mark && PERFORMANCE.measure ? PERFORMANCE : {
mark: noop$1,
measure: noop$1
};
/**
* Internal helper to bind a function known to have 4 arguments
* to a given context.
*/
var bindInternal4 = function bindInternal4(func, thisContext) {
return function (a, b, c, d) {
return func.call(thisContext, a, b, c, d);
};
};
/**
* # Reduce
*
* A fast object `.reduce()` implementation.
*
* @param {Object} subject The object to reduce over.
* @param {Function} fn The reducer function.
* @param {mixed} initialValue The initial value for the reducer, defaults to subject[0].
* @param {Object} thisContext The context for the reducer.
* @return {mixed} The final result.
*/
var reduce = function fastReduceObject(subject, fn, initialValue, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
iterator = thisContext !== undefined ? bindInternal4(fn, thisContext) : fn,
i,
key,
result;
if (initialValue === undefined) {
i = 1;
result = subject[keys[0]];
} else {
i = 0;
result = initialValue;
}
for (; i < length; i++) {
key = keys[i];
result = iterator(result, subject[key], key, subject);
}
return result;
};
function defineIcons(prefix, icons) {
var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var _params$skipHooks = params.skipHooks,
skipHooks = _params$skipHooks === void 0 ? false : _params$skipHooks;
var normalized = Object.keys(icons).reduce(function (acc, iconName) {
var icon = icons[iconName];
var expanded = !!icon.icon;
if (expanded) {
acc[icon.iconName] = icon.icon;
} else {
acc[iconName] = icon;
}
return acc;
}, {});
if (typeof namespace.hooks.addPack === 'function' && !skipHooks) {
namespace.hooks.addPack(prefix, normalized);
} else {
namespace.styles[prefix] = _objectSpread({}, namespace.styles[prefix] || {}, normalized);
}
/**
* Font Awesome 4 used the prefix of `fa` for all icons. With the introduction
* of new styles we needed to differentiate between them. Prefix `fa` is now an alias
* for `fas` so we'll easy the upgrade process for our users by automatically defining
* this as well.
*/
if (prefix === 'fas') {
defineIcons('fa', icons);
}
}
var styles = namespace.styles,
shims = namespace.shims;
var build = function build() {
var lookup = function lookup(reducer) {
return reduce(styles, function (o, style, prefix) {
o[prefix] = reduce(style, reducer, {});
return o;
}, {});
};
lookup(function (acc, icon, iconName) {
if (icon[3]) {
acc[icon[3]] = iconName;
}
return acc;
});
lookup(function (acc, icon, iconName) {
var ligatures = icon[2];
acc[iconName] = iconName;
ligatures.forEach(function (ligature) {
acc[ligature] = iconName;
});
return acc;
});
var hasRegular = 'far' in styles;
reduce(shims, function (acc, shim) {
var oldName = shim[0];
var prefix = shim[1];
var iconName = shim[2];
if (prefix === 'far' && !hasRegular) {
prefix = 'fas';
}
acc[oldName] = {
prefix: prefix,
iconName: iconName
};
return acc;
}, {});
};
build();
namespace.styles;
function iconFromMapping(mapping, prefix, iconName) {
if (mapping && mapping[prefix] && mapping[prefix][iconName]) {
return {
prefix: prefix,
iconName: iconName,
icon: mapping[prefix][iconName]
};
}
}
function toHtml(abstractNodes) {
var tag = abstractNodes.tag,
_abstractNodes$attrib = abstractNodes.attributes,
attributes = _abstractNodes$attrib === void 0 ? {} : _abstractNodes$attrib,
_abstractNodes$childr = abstractNodes.children,
children = _abstractNodes$childr === void 0 ? [] : _abstractNodes$childr;
if (typeof abstractNodes === 'string') {
return htmlEscape(abstractNodes);
} else {
return "<".concat(tag, " ").concat(joinAttributes(attributes), ">").concat(children.map(toHtml).join(''), "</").concat(tag, ">");
}
}
function MissingIcon(error) {
this.name = 'MissingIcon';
this.message = error || 'Icon unavailable';
this.stack = new Error().stack;
}
MissingIcon.prototype = Object.create(Error.prototype);
MissingIcon.prototype.constructor = MissingIcon;
var FILL = {
fill: 'currentColor'
};
var ANIMATION_BASE = {
attributeType: 'XML',
repeatCount: 'indefinite',
dur: '2s'
};
({
tag: 'path',
attributes: _objectSpread({}, FILL, {
d: 'M156.5,447.7l-12.6,29.5c-18.7-9.5-35.9-21.2-51.5-34.9l22.7-22.7C127.6,430.5,141.5,440,156.5,447.7z M40.6,272H8.5 c1.4,21.2,5.4,41.7,11.7,61.1L50,321.2C45.1,305.5,41.8,289,40.6,272z M40.6,240c1.4-18.8,5.2-37,11.1-54.1l-29.5-12.6 C14.7,194.3,10,216.7,8.5,240H40.6z M64.3,156.5c7.8-14.9,17.2-28.8,28.1-41.5L69.7,92.3c-13.7,15.6-25.5,32.8-34.9,51.5 L64.3,156.5z M397,419.6c-13.9,12-29.4,22.3-46.1,30.4l11.9,29.8c20.7-9.9,39.8-22.6,56.9-37.6L397,419.6z M115,92.4 c13.9-12,29.4-22.3,46.1-30.4l-11.9-29.8c-20.7,9.9-39.8,22.6-56.8,37.6L115,92.4z M447.7,355.5c-7.8,14.9-17.2,28.8-28.1,41.5 l22.7,22.7c13.7-15.6,25.5-32.9,34.9-51.5L447.7,355.5z M471.4,272c-1.4,18.8-5.2,37-11.1,54.1l29.5,12.6 c7.5-21.1,12.2-43.5,13.6-66.8H471.4z M321.2,462c-15.7,5-32.2,8.2-49.2,9.4v32.1c21.2-1.4,41.7-5.4,61.1-11.7L321.2,462z M240,471.4c-18.8-1.4-37-5.2-54.1-11.1l-12.6,29.5c21.1,7.5,43.5,12.2,66.8,13.6V471.4z M462,190.8c5,15.7,8.2,32.2,9.4,49.2h32.1 c-1.4-21.2-5.4-41.7-11.7-61.1L462,190.8z M92.4,397c-12-13.9-22.3-29.4-30.4-46.1l-29.8,11.9c9.9,20.7,22.6,39.8,37.6,56.9 L92.4,397z M272,40.6c18.8,1.4,36.9,5.2,54.1,11.1l12.6-29.5C317.7,14.7,295.3,10,272,8.5V40.6z M190.8,50 c15.7-5,32.2-8.2,49.2-9.4V8.5c-21.2,1.4-41.7,5.4-61.1,11.7L190.8,50z M442.3,92.3L419.6,115c12,13.9,22.3,29.4,30.5,46.1 l29.8-11.9C470,128.5,457.3,109.4,442.3,92.3z M397,92.4l22.7-22.7c-15.6-13.7-32.8-25.5-51.5-34.9l-12.6,29.5 C370.4,72.1,384.4,81.5,397,92.4z'
})
});
var OPACITY_ANIMATE = _objectSpread({}, ANIMATION_BASE, {
attributeName: 'opacity'
});
({
tag: 'circle',
attributes: _objectSpread({}, FILL, {
cx: '256',
cy: '364',
r: '28'
}),
children: [{
tag: 'animate',
attributes: _objectSpread({}, ANIMATION_BASE, {
attributeName: 'r',
values: '28;14;28;28;14;28;'
})
}, {
tag: 'animate',
attributes: _objectSpread({}, OPACITY_ANIMATE, {
values: '1;0;1;1;0;1;'
})
}]
});
({
tag: 'path',
attributes: _objectSpread({}, FILL, {
opacity: '1',
d: 'M263.7,312h-16c-6.6,0-12-5.4-12-12c0-71,77.4-63.9,77.4-107.8c0-20-17.8-40.2-57.4-40.2c-29.1,0-44.3,9.6-59.2,28.7 c-3.9,5-11.1,6-16.2,2.4l-13.1-9.2c-5.6-3.9-6.9-11.8-2.6-17.2c21.2-27.2,46.4-44.7,91.2-44.7c52.3,0,97.4,29.8,97.4,80.2 c0,67.6-77.4,63.5-77.4,107.8C275.7,306.6,270.3,312,263.7,312z'
}),
children: [{
tag: 'animate',
attributes: _objectSpread({}, OPACITY_ANIMATE, {
values: '1;0;0;0;0;1;'
})
}]
});
({
tag: 'path',
attributes: _objectSpread({}, FILL, {
opacity: '0',
d: 'M232.5,134.5l7,168c0.3,6.4,5.6,11.5,12,11.5h9c6.4,0,11.7-5.1,12-11.5l7-168c0.3-6.8-5.2-12.5-12-12.5h-23 C237.7,122,232.2,127.7,232.5,134.5z'
}),
children: [{
tag: 'animate',
attributes: _objectSpread({}, OPACITY_ANIMATE, {
values: '0;0;1;1;0;0;'
})
}]
});
namespace.styles;
function asFoundIcon(icon) {
var width = icon[0];
var height = icon[1];
var _icon$slice = icon.slice(4),
_icon$slice2 = _slicedToArray(_icon$slice, 1),
vectorData = _icon$slice2[0];
var element = null;
if (Array.isArray(vectorData)) {
element = {
tag: 'g',
attributes: {
class: "".concat(config.familyPrefix, "-").concat(DUOTONE_CLASSES.GROUP)
},
children: [{
tag: 'path',
attributes: {
class: "".concat(config.familyPrefix, "-").concat(DUOTONE_CLASSES.SECONDARY),
fill: 'currentColor',
d: vectorData[0]
}
}, {
tag: 'path',
attributes: {
class: "".concat(config.familyPrefix, "-").concat(DUOTONE_CLASSES.PRIMARY),
fill: 'currentColor',
d: vectorData[1]
}
}]
};
} else {
element = {
tag: 'path',
attributes: {
fill: 'currentColor',
d: vectorData
}
};
}
return {
found: true,
width: width,
height: height,
icon: element
};
}
namespace.styles;
var baseStyles = "svg:not(:root).svg-inline--fa {\n overflow: visible;\n}\n\n.svg-inline--fa {\n display: inline-block;\n font-size: inherit;\n height: 1em;\n overflow: visible;\n vertical-align: -0.125em;\n}\n.svg-inline--fa.fa-lg {\n vertical-align: -0.225em;\n}\n.svg-inline--fa.fa-w-1 {\n width: 0.0625em;\n}\n.svg-inline--fa.fa-w-2 {\n width: 0.125em;\n}\n.svg-inline--fa.fa-w-3 {\n width: 0.1875em;\n}\n.svg-inline--fa.fa-w-4 {\n width: 0.25em;\n}\n.svg-inline--fa.fa-w-5 {\n width: 0.3125em;\n}\n.svg-inline--fa.fa-w-6 {\n width: 0.375em;\n}\n.svg-inline--fa.fa-w-7 {\n width: 0.4375em;\n}\n.svg-inline--fa.fa-w-8 {\n width: 0.5em;\n}\n.svg-inline--fa.fa-w-9 {\n width: 0.5625em;\n}\n.svg-inline--fa.fa-w-10 {\n width: 0.625em;\n}\n.svg-inline--fa.fa-w-11 {\n width: 0.6875em;\n}\n.svg-inline--fa.fa-w-12 {\n width: 0.75em;\n}\n.svg-inline--fa.fa-w-13 {\n width: 0.8125em;\n}\n.svg-inline--fa.fa-w-14 {\n width: 0.875em;\n}\n.svg-inline--fa.fa-w-15 {\n width: 0.9375em;\n}\n.svg-inline--fa.fa-w-16 {\n width: 1em;\n}\n.svg-inline--fa.fa-w-17 {\n width: 1.0625em;\n}\n.svg-inline--fa.fa-w-18 {\n width: 1.125em;\n}\n.svg-inline--fa.fa-w-19 {\n width: 1.1875em;\n}\n.svg-inline--fa.fa-w-20 {\n width: 1.25em;\n}\n.svg-inline--fa.fa-pull-left {\n margin-right: 0.3em;\n width: auto;\n}\n.svg-inline--fa.fa-pull-right {\n margin-left: 0.3em;\n width: auto;\n}\n.svg-inline--fa.fa-border {\n height: 1.5em;\n}\n.svg-inline--fa.fa-li {\n width: 2em;\n}\n.svg-inline--fa.fa-fw {\n width: 1.25em;\n}\n\n.fa-layers svg.svg-inline--fa {\n bottom: 0;\n left: 0;\n margin: auto;\n position: absolute;\n right: 0;\n top: 0;\n}\n\n.fa-layers {\n display: inline-block;\n height: 1em;\n position: relative;\n text-align: center;\n vertical-align: -0.125em;\n width: 1em;\n}\n.fa-layers svg.svg-inline--fa {\n -webkit-transform-origin: center center;\n transform-origin: center center;\n}\n\n.fa-layers-counter, .fa-layers-text {\n display: inline-block;\n position: absolute;\n text-align: center;\n}\n\n.fa-layers-text {\n left: 50%;\n top: 50%;\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n -webkit-transform-origin: center center;\n transform-origin: center center;\n}\n\n.fa-layers-counter {\n background-color: #ff253a;\n border-radius: 1em;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n color: #fff;\n height: 1.5em;\n line-height: 1;\n max-width: 5em;\n min-width: 1.5em;\n overflow: hidden;\n padding: 0.25em;\n right: 0;\n text-overflow: ellipsis;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right;\n}\n\n.fa-layers-bottom-right {\n bottom: 0;\n right: 0;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom right;\n transform-origin: bottom right;\n}\n\n.fa-layers-bottom-left {\n bottom: 0;\n left: 0;\n right: auto;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom left;\n transform-origin: bottom left;\n}\n\n.fa-layers-top-right {\n right: 0;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right;\n}\n\n.fa-layers-top-left {\n left: 0;\n right: auto;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top left;\n transform-origin: top left;\n}\n\n.fa-lg {\n font-size: 1.3333333333em;\n line-height: 0.75em;\n vertical-align: -0.0667em;\n}\n\n.fa-xs {\n font-size: 0.75em;\n}\n\n.fa-sm {\n font-size: 0.875em;\n}\n\n.fa-1x {\n font-size: 1em;\n}\n\n.fa-2x {\n font-size: 2em;\n}\n\n.fa-3x {\n font-size: 3em;\n}\n\n.fa-4x {\n font-size: 4em;\n}\n\n.fa-5x {\n font-size: 5em;\n}\n\n.fa-6x {\n font-size: 6em;\n}\n\n.fa-7x {\n font-size: 7em;\n}\n\n.fa-8x {\n font-size: 8e
function css () {
var dfp = DEFAULT_FAMILY_PREFIX;
var drc = DEFAULT_REPLACEMENT_CLASS;
var fp = config.familyPrefix;
var rc = config.replacementClass;
var s = baseStyles;
if (fp !== dfp || rc !== drc) {
var dPatt = new RegExp("\\.".concat(dfp, "\\-"), 'g');
var customPropPatt = new RegExp("\\--".concat(dfp, "\\-"), 'g');
var rPatt = new RegExp("\\.".concat(drc), 'g');
s = s.replace(dPatt, ".".concat(fp, "-")).replace(customPropPatt, "--".concat(fp, "-")).replace(rPatt, ".".concat(rc));
}
return s;
}
var Library =
/*#__PURE__*/
function () {
function Library() {
_classCallCheck(this, Library);
this.definitions = {};
}
_createClass(Library, [{
key: "add",
value: function add() {
var _this = this;
for (var _len = arguments.length, definitions = new Array(_len), _key = 0; _key < _len; _key++) {
definitions[_key] = arguments[_key];
}
var additions = definitions.reduce(this._pullDefinitions, {});
Object.keys(additions).forEach(function (key) {
_this.definitions[key] = _objectSpread({}, _this.definitions[key] || {}, additions[key]);
defineIcons(key, additions[key]);
build();
});
}
}, {
key: "reset",
value: function reset() {
this.definitions = {};
}
}, {
key: "_pullDefinitions",
value: function _pullDefinitions(additions, definition) {
var normalized = definition.prefix && definition.iconName && definition.icon ? {
0: definition
} : definition;
Object.keys(normalized).map(function (key) {
var _normalized$key = normalized[key],
prefix = _normalized$key.prefix,
iconName = _normalized$key.iconName,
icon = _normalized$key.icon;
if (!additions[prefix]) additions[prefix] = {};
additions[prefix][iconName] = icon;
});
return additions;
}
}]);
return Library;
}();
function ensureCss() {
if (config.autoAddCss && !_cssInserted) {
insertCss(css());
_cssInserted = true;
}
}
function apiObject(val, abstractCreator) {
Object.defineProperty(val, 'abstract', {
get: abstractCreator
});
Object.defineProperty(val, 'html', {
get: function get() {
return val.abstract.map(function (a) {
return toHtml(a);
});
}
});
Object.defineProperty(val, 'node', {
get: function get() {
if (!IS_DOM) return;
var container = DOCUMENT.createElement('div');
container.innerHTML = val.html;
return container.children;
}
});
return val;
}
function findIconDefinition(iconLookup) {
var _iconLookup$prefix = iconLookup.prefix,
prefix = _iconLookup$prefix === void 0 ? 'fa' : _iconLookup$prefix,
iconName = iconLookup.iconName;
if (!iconName) return;
return iconFromMapping(library.definitions, prefix, iconName) || iconFromMapping(namespace.styles, prefix, iconName);
}
function resolveIcons(next) {
return function (maybeIconDefinition) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var iconDefinition = (maybeIconDefinition || {}).icon ? maybeIconDefinition : findIconDefinition(maybeIconDefinition || {});
var mask = params.mask;
if (mask) {
mask = (mask || {}).icon ? mask : findIconDefinition(mask || {});
}
return next(iconDefinition, _objectSpread({}, params, {
mask: mask
}));
};
}
var library = new Library();
var _cssInserted = false;
var icon = resolveIcons(function (iconDefinition) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _params$transform = params.transform,
transform = _params$transform === void 0 ? meaninglessTransform : _params$transform,
_params$symbol = params.symbol,
symbol = _params$symbol === void 0 ? false : _params$symbol,
_params$mask = params.mask,
mask = _params$mask === void 0 ? null : _params$mask,
_params$maskId = params.maskId,
maskId = _params$maskId === void 0 ? null : _params$maskId,
_params$title = params.title,
title = _params$title === void 0 ? null : _params$title,
_params$titleId = params.titleId,
titleId = _params$titleId === void 0 ? null : _params$titleId,
_params$classes = params.classes,
classes = _params$classes === void 0 ? [] : _params$classes,
_params$attributes = params.attributes,
attributes = _params$attributes === void 0 ? {} : _params$attributes,
_params$styles = params.styles,
styles = _params$styles === void 0 ? {} : _params$styles;
if (!iconDefinition) return;
var prefix = iconDefinition.prefix,
iconName = iconDefinition.iconName,
icon = iconDefinition.icon;
return apiObject(_objectSpread({
type: 'icon'
}, iconDefinition), function () {
ensureCss();
if (config.autoA11y) {
if (title) {
attributes['aria-labelledby'] = "".concat(config.replacementClass, "-title-").concat(titleId || nextUniqueId());
} else {
attributes['aria-hidden'] = 'true';
attributes['focusable'] = 'false';
}
}
return makeInlineSvgAbstract({
icons: {
main: asFoundIcon(icon),
mask: mask ? asFoundIcon(mask.icon) : {
found: false,
width: null,
height: null,
icon: {}
}
},
prefix: prefix,
iconName: iconName,
transform: _objectSpread({}, meaninglessTransform, transform),
symbol: symbol,
title: title,
maskId: maskId,
titleId: titleId,
extra: {
attributes: attributes,
styles: styles,
classes: classes
}
});
});
});
class Parser {
constructor(table) {
this.table = table;
}
parse(input) {
var length = input.length, table = this.table, output = [], stack = [], index = 0;
while (index < length) {
var token = input[index++];
switch (token.data) {
case "(":
stack.unshift(token);
break;
case ")":
while (stack.length) {
var token = stack.shift();
if (token.data === "(")
break;
else
output.push(token);
}
if (token.data !== "(")
throw new Error("Mismatched parentheses.");
break;
default:
if (table.hasOwnProperty(token.data)) {
while (stack.length) {
var punctuator = stack[0];
if (punctuator.data === "(")
break;
var operator = table[token.data], precedence = operator.precedence, antecedence = table[punctuator.data].precedence;
if (precedence > antecedence ||
(precedence === antecedence &&
operator.associativity === "right"))
break;
else
output.push(stack.shift());
}
stack.unshift(token);
}
else
output.push(token);
}
}
while (stack.length) {
var token = stack.shift();
if (token.data !== "(")
output.push(token);
else
throw new Error("Mismatched parentheses.");
}
return output;
}
}
function around(obj, factories) {
const removers = Object.keys(factories).map(key => around1(obj, key, factories[key]));
return removers.length === 1 ? removers[0] : function () { removers.forEach(r => r()); };
}
function around1(obj, method, createWrapper) {
const original = obj[method], hadOwn = obj.hasOwnProperty(method);
let current = createWrapper(original);
// Let our wrapper inherit static props from the wrapping method,
// and the wrapping method, props from the original method
if (original)
Object.setPrototypeOf(current, original);
Object.setPrototypeOf(wrapper, current);
obj[method] = wrapper;
// Return a callback to allow safe removal
return remove;
function wrapper(...args) {
// If we have been deactivated and are no longer wrapped, remove ourselves
if (current === original && obj[method] === wrapper)
remove();
return current.apply(this, args);
}
function remove() {
// If no other patches, just do a direct removal
if (obj[method] === wrapper) {
if (hadOwn)
obj[method] = original;
else
delete obj[method];
}
if (current === original)
return;
// Else pass future calls through, and remove wrapper from the prototype chain
current = original;
Object.setPrototypeOf(wrapper, original || Function);
}
}
const TAG_REGEX = /(?:(?<roll>\d+)[Dd])?#(?<tag>[\p{Letter}\p{Emoji_Presentation}\w/-]+)(?:\|(?<collapse>[\+-]))?(?:\|(?<types>[^\+-]+))?/u;
const TABLE_REGEX = /(?:(?<roll>\d+)[Dd])?\[\[(?<link>[\s\S]+?)#?\^(?<block>[\s\S]+?)\]\]\|?(?<header>[\s\S]+)?/;
const SECTION_REGEX = /(?:(?<roll>\d+)[Dd])?\[\[(?<link>[\s\S]+)\]\]\|?(?<types>[\s\S]+)?/;
const MATH_REGEX = /[\(\^\+\-\*\/\)]/;
const DICE_REGEX = /(?<dice>(?<roll>\d+)(?:[Dd]?\[?(?:-?\d+\s?,)?\s?(?:-?\d+|%|F)\]?)?)(?<conditional>(?:(?:=|=!|<|>|<=|>=|=<|=>|\-=|=\-)\d+)*)?/;
const OMITTED_REGEX = /(?<roll>\d+)?[Dd](?<faces>\[?(?:-?\d+\s?,)?\s?(?:-?\d+|%|F)\]?)?(?<conditional>(?:(?:=|=!|<|>|<=|>=|=<|=>|\-=|=\-)\d+)*)?/;
const CONDITIONAL_REGEX = /(?:(?<operator>=|=!|<|>|<=|>=|=<|=>|\-=|=\-)(?<comparer>\d+))/g;
const ICON_DEFINITION = "dice-roller-icon";
const COPY_DEFINITION = "dice-roller-copy";
/**
* Inserts a new result into a results map.
*
* @private
* @param {ResultMapInterface} map Results map to modify.
* @param {number} index Index to insert the new value.
* @param {ResultInterface} value Value to insert.
* @memberof DiceRoll
*/
function _insertIntoMap(map, index, value) {
/** Get all values above index, then reverse them */
let toUpdate = [...map].slice(index).reverse();
/** Loop through the values and re-insert them into the map at key + 1 */
toUpdate.forEach(([key, value]) => {
map.set(key + 1, value);
});
/** Insert the new value at the specified index */
map.set(index, value);
}
class BasicRoller extends obsidian.Events {
constructor(plugin, original, lexemes) {
super();
this.plugin = plugin;
this.original = original;
this.lexemes = lexemes;
this.containerEl = createDiv({
cls: "dice-roller",
attr: {
"aria-label-position": "top",
"data-dice": this.original
}
});
this.resultEl = this.containerEl.createDiv("dice-roller-result");
const icon = this.containerEl.createDiv({
cls: "dice-roller-button"
});
obsidian.setIcon(icon, ICON_DEFINITION);
this.containerEl.onclick = this.onClick.bind(this);
icon.onclick = this.onClick.bind(this);
}
setTooltip() {
if (this.plugin.data.displayResultsInline)
return;
this.containerEl.setAttrs({
"aria-label": this.tooltip
});
}
getRandomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
render() {
return __awaiter(this, void 0, void 0, function* () {
this.setTooltip();
yield this.build();
});
}
get inlineText() {
return `${this.tooltip.split("\n").join(" -> ")} -> `;
}
onClick(evt) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
evt.stopPropagation();
evt.stopImmediatePropagation();
if ((_a = window.getSelection()) === null || _a === void 0 ? void 0 : _a.isCollapsed) {
yield this.roll();
}
});
}
}
class GenericRoller extends BasicRoller {
}
class GenericFileRoller extends GenericRoller {
constructor(plugin, original, lexeme, source) {
super(plugin, original, [lexeme]);
this.plugin = plugin;
this.original = original;
this.lexeme = lexeme;
this.source = source;
this.getPath();
this.getFile();
}
getFile() {
return __awaiter(this, void 0, void 0, function* () {
this.file = this.plugin.app.metadataCache.getFirstLinkpathDest(this.path, this.source);
if (!this.file || !(this.file instanceof obsidian.TFile))
throw new Error("Could not load file.");
yield this.load();
this.registerFileWatcher();
});
}
registerFileWatcher() {
this.plugin.registerEvent(this.plugin.app.vault.on("modify", (file) => __awaiter(this, void 0, void 0, function* () {
if (file !== this.file)
return;
yield this.getOptions();
})));
}
}
class DiceRoller {
constructor(dice, lexeme) {
var _a;
this.lexeme = lexeme;
this.modifiers = new Map();
this.modifiersAllowed = true;
this.static = false;
this.conditions = [];
if (!/(\-?\d+)[dD]?(\d+|%|\[\d+,\s?\d+\])?/.test(dice)) {
throw new Error("Non parseable dice string passed to DiceRoll.");
}
this.dice = dice.split(" ").join("");
if (/^-?\d+$/.test(this.dice)) {
this.static = true;
this.modifiersAllowed = false;
}
let [, rolls, min = null, max = 1] = this.dice.match(/(\-?\d+)[dD]\[?(?:(-?\d+)\s?,)?\s?(-?\d+|%|F)\]?/) || [, 1, null, 1];
this.rolls = Number(rolls) || 1;
if (Number(max) < 0 && !min) {
min = -1;
}
if (max === "%")
max = 100;
if (max === "F") {
max = 1;
min = -1;
}
if (Number(max) < Number(min)) {
[max, min] = [min, max];
}
this.faces = { max: max ? Number(max) : 1, min: min ? Number(min) : 1 };
this.conditions = (_a = this.lexeme.conditionals) !== null && _a !== void 0 ? _a : [];
this.results = new Map([...this.roll()].map((n, i) => {
return [
i,
{
usable: true,
value: n,
display: `${n}`,
modifiers: new Set()
}
];
}));
}
get text() {
return `${this.result}`;
}
get result() {
if (this.static) {
return Number(this.dice);
}
const results = [...this.results].map(([, { usable, value }]) => usable ? value : 0);
return results.reduce((a, b) => a + b, 0);
}
get display() {
if (this.static) {
return `${this.result}`;
}
return `[${[...this.results]
.map(([, { modifiers, display }]) => `${display}${[...modifiers].join("")}`)
.join(", ")}]`;
}
keepLow(drop = 1) {
if (!this.modifiersAllowed) {
new obsidian.Notice("Modifiers are only allowed on dice rolls.");
return;
}
/* if (this.conditions?.length) {
new Notice("Modifiers are not permitted on conditioned dice.");
return;
} */
[...this.results]
.sort((a, b) => a[1].value - b[1].value)
.slice(drop - this.results.size)
.forEach(([index]) => {
const previous = this.results.get(index);
previous.usable = false;
previous.modifiers.add("d");
this.results.set(index, Object.assign({}, previous));
});
}
keepHigh(drop = 1) {
if (!this.modifiersAllowed) {
new obsidian.Notice("Modifiers are only allowed on dice rolls.");
return;
}
/* if (this.conditions?.length) {
new Notice("Modifiers are not permitted on conditioned dice.");
return;
} */
[...this.results]
.sort((a, b) => b[1].value - a[1].value)
.slice(drop)
.forEach(([index]) => {
const previous = this.results.get(index);
previous.usable = false;
previous.modifiers.add("d");
this.results.set(index, Object.assign({}, previous));
});
}
reroll(times, conditionals) {
if (!this.modifiersAllowed) {
new obsidian.Notice("Modifiers are only allowed on dice rolls.");
return;
}
/* if (this.conditions?.length) {
new Notice("Modifiers are not permitted on conditioned dice.");
return;
} */
/**
* Build Conditional
*/
if (!conditionals.length) {
conditionals.push({
operator: "=",
comparer: this.faces.min
});
}
/**
* Find values that pass the conditional.
*/
let i = 0, toReroll = [...this.results].filter(([, { value }]) => this.checkCondition(value, conditionals));
while (i < times &&
toReroll.filter(([, { value }]) => this.checkCondition(value, conditionals)).length > 0) {
i++;
toReroll.map(([, roll]) => {
roll.modifiers.add("r");
roll.value = this.getRandomBetween(this.faces.min, this.faces.max);
});
}
toReroll.forEach(([index, value]) => {
this.results.set(index, value);
});
}
explodeAndCombine(times, conditionals) {
if (!this.modifiersAllowed) {
new obsidian.Notice("Modifiers are only allowed on dice rolls.");
return;
}
/* if (this.conditions?.length) {
new Notice("Modifiers are not permitted on conditioned dice.");
return;
} */
/**
* Build Conditional
*/
if (!conditionals.length) {
conditionals.push({
operator: "=",
comparer: this.faces.max
});
}
/**
* Find values that pass the conditional
*/
let i = 0, toExplode = [...this.results].filter(([, { value }]) => this.checkCondition(value, conditionals));
toExplode.forEach(([index, value]) => {
let newRoll = this.getRandomBetween(this.faces.min, this.faces.max);
i++;
value.modifiers.add("!");
value.value += newRoll;
value.display = `${value.value}`;
this.results.set(index, value);
while (i < times && this.checkCondition(newRoll, conditionals)) {
i++;
newRoll = this.getRandomBetween(this.faces.min, this.faces.max);
value.value += newRoll;
value.display = `${value.value}`;
this.results.set(index, value);
}
});
}
explode(times, conditionals) {
if (!this.modifiersAllowed) {
new obsidian.Notice("Modifiers are only allowed on dice rolls.");
return;
}
/* if (this.conditions?.length) {
new Notice("Modifiers are not permitted on conditioned dice.");
return;
} */
/**
* Build Conditional
*/
if (!conditionals.length) {
conditionals.push({
operator: "=",
comparer: this.faces.max
});
}
/**
* Find values that pass the conditional
*/
let toExplode = [...this.results].filter(([, { value }]) => this.checkCondition(value, conditionals));
/** Track how many have been inserted */
let inserted = 0;
/** Loop through values that need to explode */
toExplode.forEach(([key, value]) => {
/** newRoll is the new value to check against the max face value */
let newRoll = value.value;
/** i tracks how many times this roll has been exploded */
let i = 0;
/**
* Explode max rolls.
*/
while (i < times && this.checkCondition(newRoll, conditionals)) {
let previous = this.results.get(key + inserted + i);
previous.modifiers.add("!");
newRoll = this.getRandomBetween(this.faces.min, this.faces.max);
/** Insert the new roll into the results map */
_insertIntoMap(this.results, key + inserted + i + 1, {
usable: true,
value: newRoll,
display: `${newRoll}`,
modifiers: new Set()
});
i++;
}
/** Update how many have been inserted. */
inserted += i;
});
}
_roll() {
if (this.static) {
return [Number(this.dice)];
}
return [...Array(this.rolls)].map(() => this.getRandomBetween(this.faces.min, this.faces.max));
}
roll() {
var _a;
const roll = this._roll();
this.results = new Map([...roll].map((n, i) => {
return [
i,
{
usable: true,
value: n,
display: `${n}`,
modifiers: new Set()
}
];
}));
for (let [type, modifier] of this.modifiers) {
this.applyModifier(type, modifier);
}
if ((_a = this.conditions) === null || _a === void 0 ? void 0 : _a.length)
this.applyConditions();
return roll;
}
applyConditions() {
for (let [index, result] of this.results) {
const negate = this.conditions.find(({ operator }) => operator === "-=" || operator === "=-");
if (negate) {
if (result.value === negate.comparer) {
result.value = -1;
result.modifiers.add("-");
continue;
}
}
const check = this.checkCondition(result.value, this.conditions);
if (!check) {
result.usable = false;
}
else {
result.modifiers.add("*");
result.value = 1;
}
}
}
applyModifier(type, modifier) {
switch (type) {
case "kh": {
this.keepHigh(modifier.data);
break;
}
case "kl": {
this.keepLow(modifier.data);
break;
}
case "!": {
this.explode(modifier.data, modifier.conditionals);
break;
}
case "!!": {
this.explodeAndCombine(modifier.data, modifier.conditionals);
break;
}
case "r": {
this.reroll(modifier.data, modifier.conditionals);
break;
}
}
}
checkCondition(value, conditions) {
if (!conditions || !conditions.length)
return value;
return conditions.some(({ operator, comparer }) => {
if (Number.isNaN(value) || Number.isNaN(comparer)) {
return false;
}
let result = false;
switch (operator) {
case "=":
result = value === comparer;
break;
case "!=":
case "=!":
result = value !== comparer;
break;
case "<":
result = value < comparer;
break;
case "<=":
result = value <= comparer;
break;
case ">":
result = value > comparer;
break;
case ">=":
result = value >= comparer;
break;
}
return result;
});
}
getRandomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
class StuntRoller extends DiceRoller {
constructor(dice, lexeme) {
super(`3d6`, lexeme);
this.lexeme = lexeme;
this.dice = dice;
}
get doubles() {
return (new Set([...this.results].map(([, { usable, value }]) => usable ? value : 0)).size < 3);
}
get result() {
if (this.static) {
return Number(this.dice);
}
const results = [...this.results].map(([, { usable, value }]) => usable ? value : 0);
return results.reduce((a, b) => a + b, 0);
}
get display() {
let str = [];
for (let result of this.results) {
if (result[0] == 0 && this.doubles) {
str.push(`${result[1].value}S`);
continue;
}
str.push(`${result[1].value}`);
}
return `[${str.join(", ")}]`;
}
}
class StackRoller extends GenericRoller {
constructor(plugin, original, lexemes) {
super(plugin, original, lexemes);
this.plugin = plugin;
this.original = original;
this.lexemes = lexemes;
this.stunted = "";
this.operators = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
"^": (a, b) => {
return Math.pow(a, b);
}
};
this.stack = [];
this.dice = [];
}
get tooltip() {
if (this._tooltip)
return this._tooltip;
let text = this.original;
this.dice.forEach((dice) => {
text = text.replace(dice.lexeme.original, dice.display);
});
return `${this.original}\n${text}`;
}
build() {
return __awaiter(this, void 0, void 0, function* () {
const result = [
this.result.toLocaleString(navigator.language, {
maximumFractionDigits: 2
})
];
if (this.plugin.data.displayResultsInline) {
result.unshift(this.inlineText);
}
this.resultEl.setText(result.join("") + this.stunted);
});
}
roll() {
return __awaiter(this, void 0, void 0, function* () {
let index = 0;
this.stunted = "";
for (const dice of this.lexemes) {
switch (dice.type) {
case "+":
case "-":
case "*":
case "/":
case "^":
case "math":
let b = this.stack.pop(), a = this.stack.pop();
if (!a) {
this.stack.push(b);
continue;
}
b.roll();
if (b instanceof StuntRoller) {
if (b.doubles) {
this.stunted = ` - ${b.results.get(0).value} Stunt Points`;
}
}
a.roll();
if (a instanceof StuntRoller) {
if (a.doubles) {
this.stunted = ` - ${a.results.get(0).value} Stunt Points`;
}
}
const result = this.operators[dice.data](a.result, b.result);
this.stack.push(new DiceRoller(`${result}`, dice));
break;
case "kh": {
let diceInstance = this.dice[index - 1];
let data = dice.data ? Number(dice.data) : 1;
diceInstance.modifiers.set("kh", {
data,
conditionals: []
});
break;
}
case "dl": {
let diceInstance = this.dice[index - 1];
let data = dice.data ? Number(dice.data) : 1;
data = diceInstance.results.size - data;
diceInstance.modifiers.set("kh", {
data,
conditionals: []
});
break;
}
case "kl": {
let diceInstance = this.dice[index - 1];
let data = dice.data ? Number(dice.data) : 1;
diceInstance.modifiers.set("kl", {
data,
conditionals: []
});
break;
}
case "dh": {
let diceInstance = this.dice[index - 1];
let data = dice.data ? Number(dice.data) : 1;
data = diceInstance.results.size - data;
diceInstance.modifiers.set("kl", {
data,
conditionals: []
});
break;
}
case "!": {
let diceInstance = this.dice[index - 1];
let data = Number(dice.data) || 1;
diceInstance.modifiers.set("!", {
data,
conditionals: dice.conditionals
});
break;
}
case "!!": {
let diceInstance = this.dice[index - 1];
let data = Number(dice.data) || 1;
diceInstance.modifiers.set("!!", {
data,
conditionals: dice.conditionals
});
break;
}
case "r": {
let diceInstance = this.dice[index - 1];
let data = Number(dice.data) || 1;
diceInstance.modifiers.set("r", {
data,
conditionals: dice.conditionals
});
break;
}
case "dice":
if (!this.dice[index]) {
this.dice[index] = new DiceRoller(dice.data, dice);
}
this.stack.push(this.dice[index]);
index++;
break;
case "stunt":
if (!this.dice[index]) {
this.dice[index] = new StuntRoller(dice.original, dice);
}
this.stack.push(this.dice[index]);
index++;
}
}
const final = this.stack.pop();
final.roll();
if (final instanceof StuntRoller) {
if (final.doubles) {
this.stunted = ` - ${final.results.get(0).value} Stunt Points`;
}
}
this.result = final.result;
this._tooltip = null;
this.render();
this.trigger("new-result");
return this.result;
});
}
toResult() {
return {
type: "dice",
result: this.result,
tooltip: this.tooltip
};
}
applyResult(result) {
return __awaiter(this, void 0, void 0, function* () {
if (result.type !== "dice")
return;
if (result.result) {
this.result = result.result;
}
if (result.tooltip) {
this._tooltip = result.tooltip;
}
yield this.render();
});
}
}
class SectionRoller extends GenericFileRoller {
constructor(plugin, original, lexeme, source, inline = true) {
super(plugin, original, lexeme, source);
this.plugin = plugin;
this.original = original;
this.lexeme = lexeme;
this.inline = inline;
this.containerEl.addClasses(["has-embed", "markdown-embed"]);
this.resultEl.addClass("internal-embed");
this.resultEl.setAttrs({ src: source });
this.copy = this.containerEl.createDiv({
cls: "dice-content-copy dice-roller-button no-show",
attr: { "aria-label": "Copy Contents" }
});
this.copy.addEventListener("click", (evt) => {
evt.stopPropagation();
navigator.clipboard
.writeText(this.displayFromCache(...this.results).trim())
.then(() => __awaiter(this, void 0, void 0, function* () {
new obsidian.Notice("Result copied to clipboard.");
}));
});
obsidian.setIcon(this.copy, COPY_DEFINITION);
}
get tooltip() {
return `${this.original}\n${this.path}`;
}
build() {
return __awaiter(this, void 0, void 0, function* () {
this.resultEl.empty();
if (this.plugin.data.displayResultsInline && this.inline) {
this.resultEl.createSpan({
text: this.inlineText
});
}
if (!this.results || !this.results.length) {
this.resultEl.createDiv({
cls: "dice-no-results",
text: "No results."
});
return;
}
if (this.plugin.data.copyContentButton) {
this.copy.removeClass("no-show");
}
for (const result of this.results) {
this.resultEl.onclick = (evt) => __awaiter(this, void 0, void 0, function* () {
if ((evt && evt.getModifierState("Control")) ||
evt.getModifierState("Meta")) {
evt.stopPropagation();
return;
}
});
const ret = this.resultEl.createDiv({
cls: "markdown-embed"
});
if (!this.plugin.data.displayResultsInline) {
ret.setAttrs({
"aria-label": `${this.file.basename}: ${result.type}`
});
}
if (!result) {
ret.createDiv({
cls: "dice-no-results",
text: "No results."
});
continue;
}
obsidian.MarkdownRenderer.renderMarkdown(this.displayFromCache(result), ret.createDiv(), this.source, null);
if (this.plugin.data.copyContentButton && this.results.length > 1) {
let copy = ret.createDiv({
cls: "dice-content-copy dice-roller-button",
attr: { "aria-label": "Copy Contents" }
});
copy.addEventListener("click", (evt) => {
evt.stopPropagation();
navigator.clipboard
.writeText(this.displayFromCache(result).trim())
.then(() => __awaiter(this, void 0, void 0, function* () {
new obsidian.Notice("Result copied to clipboard.");
}));
});
obsidian.setIcon(copy, COPY_DEFINITION);
}
}
});
}
load() {
return __awaiter(this, void 0, void 0, function* () {
yield this.getOptions();
});
}
displayFromCache(...caches) {
let res = [];
for (let cache of caches) {
res.push(this.content.slice(cache.position.start.offset, cache.position.end.offset));
}
return res.join("\n\n");
}
getPath() {
var _a;
const { groups } = this.lexeme.data.match(SECTION_REGEX);
const { roll = 1, link, types } = groups;
if (!link)
throw new Error("Could not parse link.");
this.rolls = (_a = (roll && !isNaN(Number(roll)) && Number(roll))) !== null && _a !== void 0 ? _a : 1;
this.path = link.replace(/(\[|\])/g, "");
this.types = types === null || types === void 0 ? void 0 : types.split(",");
}
getOptions() {
return __awaiter(this, void 0, void 0, function* () {
this.cache = this.plugin.app.metadataCache.getFileCache(this.file);
if (!this.cache || !this.cache.sections) {
throw new Error("Could not read file cache.");
}
this.content = yield this.plugin.app.vault.cachedRead(this.file);
this.options = this.cache.sections.filter(({ type }) => this.types
? this.types.includes(type)
: !["yaml", "thematicBreak"].includes(type));
this.loaded = true;
this.trigger("loaded");
});
}
roll() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if (!this.loaded) {
this.on("loaded", () => {
const options = [...this.options];
this.results = [...Array(this.rolls)]
.map(() => {
let option = options[this.getRandomBetween(0, options.length - 1)];
options.splice(options.indexOf(option), 1);
return option;
})
.filter((r) => r);
this.render();
this.trigger("new-result");
resolve(this.results[0]);
});
}
else {
const options = [...this.options];
this.results = [...Array(this.rolls)]
.map(() => {
let option = options[this.getRandomBetween(0, options.length - 1)];
options.splice(options.indexOf(option), 1);
return option;
})
.filter((r) => r);
this.render();
this.trigger("new-result");
resolve(this.results[0]);
}
});
});
}
toResult() {
return {
type: "section",
result: this.results
};
}
applyResult(result) {
return __awaiter(this, void 0, void 0, function* () {
if (result.type !== "section")
return;
if (result.result) {
this.results = result.result;
}
yield this.render();
});
}
}
class TagRoller extends GenericRoller {
constructor(plugin, original, lexeme, source) {
super(plugin, original, [lexeme]);
this.plugin = plugin;
this.original = original;
this.lexeme = lexeme;
this.source = source;
this.loaded = false;
this.containerEl.addClasses(["has-embed", "markdown-embed"]);
const { roll = 1, tag, collapse, types } = lexeme.data.match(TAG_REGEX).groups;
this.collapse =
collapse === "-"
? true
: collapse === "+"
? false
: !this.plugin.data.returnAllTags;
this.tag = `#${tag}`;
this.rolls = Number(roll);
this.types = types;
this.getFiles();
}
get typeText() {
var _a;
if (!((_a = this.types) === null || _a === void 0 ? void 0 : _a.length)) {
return "";
}
return `|${this.types}`;
}
getFiles() {
return __awaiter(this, void 0, void 0, function* () {
const files = this.plugin.app.plugins.plugins.dataview.index.tags.invMap.get(this.tag);
if (files)
files.delete(this.source);
if (!files || !files.size) {
throw new Error("No files found with that tag. Is the tag correct?\n\n" +
this.tag);
}
const links = Array.from(files).map((file) => `${this.rolls}d[[${file}]]${this.typeText}`);
this.results = links.map((link) => {
return new SectionRoller(this.plugin, link, {
data: link,
original: link,
conditionals: null,
type: "section"
}, this.source, false);
});
this.loaded = true;
this.trigger("loaded");
});
}
build() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
this.resultEl.empty();
if (this.plugin.data.displayResultsInline) {
this.resultEl.createSpan({
text: this.inlineText
});
}
if (this.collapse) {
this.chosen =
(_a = this.random) !== null && _a !== void 0 ? _a : this.getRandomBetween(0, this.results.length - 1);
let section = this.results[this.chosen];
this.random = null;
const container = this.resultEl.createDiv();
container.createEl("h5", {
cls: "dice-file-name",
text: section.file.basename
});
container.appendChild(section.containerEl);
}
else {
for (let section of this.results) {
const container = this.resultEl.createDiv();
container.createEl("h5", {
cls: "dice-file-name",
text: section.file.basename
});
container.appendChild(section.containerEl);
}
}
});
}
roll() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if (this.loaded) {
this.results.forEach((section) => __awaiter(this, void 0, void 0, function* () { return yield section.roll(); }));
this.render();
this.trigger("new-result");
resolve(this.result);
}
else {
this.on("loaded", () => {
this.results.forEach((section) => __awaiter(this, void 0, void 0, function* () { return yield section.roll(); }));
this.render();
this.trigger("new-result");
resolve(this.result);
});
}
});
});
}
get tooltip() {
return this.original;
}
toResult() {
return {
type: "tag",
random: this.chosen,
result: Object.fromEntries(this.results.map((section) => [
section.path,
section.toResult()
]))
};
}
applyResult(result) {
return __awaiter(this, void 0, void 0, function* () {
if (result.type !== "tag")
return;
if (result.result) {
for (let path in result.result) {
const section = this.results.find((section) => section.path === path);
if (!section)
continue;
section.applyResult(result.result[path]);
}
}
if (result.random) {
this.random = result.random;
}
yield this.render();
});
}
}
class LinkRoller extends GenericRoller {
constructor(plugin, original, lexeme, source) {
var _a;
super(plugin, original, [lexeme]);
this.plugin = plugin;
this.original = original;
this.lexeme = lexeme;
this.source = source;
const { roll = 1, tag } = lexeme.data.match(TAG_REGEX).groups;
this.tag = `#${tag}`;
this.rolls = (_a = (roll && !isNaN(Number(roll)) && Number(roll))) !== null && _a !== void 0 ? _a : 1;
this.getFiles();
}
get tooltip() {
return `${this.original}\n${this.result.basename}`;
}
roll() {
return __awaiter(this, void 0, void 0, function* () {
return ((this.result =
this.links[this.getRandomBetween(0, this.links.length - 1)]),
yield this.render(),
this.trigger("new-result"),
this.result);
});
}
build() {
return __awaiter(this, void 0, void 0, function* () {
this.resultEl.empty();
if (this.plugin.data.displayResultsInline) {
this.resultEl.createSpan({
text: this.inlineText
});
}
const link = this.resultEl.createEl("a", {
cls: "internal-link",
text: this.result.basename
});
link.onclick = (evt) => __awaiter(this, void 0, void 0, function* () {
var _a;
evt.stopPropagation();
this.plugin.app.workspace.openLinkText(this.result.path, (_a = this.plugin.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path, true);
});
link.onmouseenter = (evt) => __awaiter(this, void 0, void 0, function* () {
var _b;
this.plugin.app.workspace.trigger("link-hover", this, //not sure
link, //targetEl
this.result.path, //linkText
(_b = this.plugin.app.workspace.getActiveFile()) === null || _b === void 0 ? void 0 : _b.path //source
);
});
});
}
getFiles() {
return __awaiter(this, void 0, void 0, function* () {
const files = this.plugin.app.plugins.plugins.dataview.index.tags.invMap.get(this.tag);
if (files)
files.delete(this.source);
if (!files || !files.size) {
throw new Error("No files found with that tag. Is the tag correct?\n\n" +
this.tag);
}
this.links = Array.from(files).map((link) => this.plugin.app.metadataCache.getFirstLinkpathDest(link, this.source));
});
}
toResult() {
return {
type: "link",
result: this.result.path
};
}
applyResult(result) {
return __awaiter(this, void 0, void 0, function* () {
if (result.type !== "link")
return;
if (result.result) {
const file = this.plugin.app.vault.getAbstractFileByPath(result.result);
if (file && file instanceof obsidian.TFile) {
this.result = file;
}
}
yield this.render();
});
}
}
class TableRoller extends GenericFileRoller {
getPath() {
var _a;
const { groups } = this.lexeme.data.match(TABLE_REGEX);
const { roll = 1, link, block, header } = groups;
if (!link || !block)
throw new Error("Could not parse link.");
this.rolls = (_a = (roll && !isNaN(Number(roll)) && Number(roll))) !== null && _a !== void 0 ? _a : 1;
this.path = link.replace(/(\[|\])/g, "");
this.block = block
.replace(/(\^|#)/g, "")
.trim()
.toLowerCase();
this.header = header;
}
get tooltip() {
return `${this.original}\n${this.path} > ${this.block}${this.header ? " | " + this.header : ""}`;
}
build() {
return __awaiter(this, void 0, void 0, function* () {
this.resultEl.empty();
const result = [this.result];
if (this.plugin.data.displayResultsInline) {
result.unshift(this.inlineText);
}
const split = result.join("").split(/(\[\[(?:[\s\S]+?)\]\])/);
for (let str of split) {
if (/\[\[(?:[\s\S]+?)\]\]/.test(str)) {
//link;
const [, match] = str.match(/\[\[([\s\S]+?)\]\]/);
const internal = this.resultEl.createEl("a", {
cls: "internal-link",
text: match
});
internal.onmouseover = () => {
var _a;
this.plugin.app.workspace.trigger("link-hover", this, //not sure
internal, //targetEl
match.replace("^", "#^").split("|").shift(), //linkText
(_a = this.plugin.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path //source
);
};
internal.onclick = (ev) => __awaiter(this, void 0, void 0, function* () {
var _a;
ev.stopPropagation();
yield this.plugin.app.workspace.openLinkText(match.replace("^", "#^").split(/\|/).shift(), (_a = this.plugin.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path, ev.getModifierState("Control"));
});
continue;
}
this.resultEl.createSpan({ text: str });
}
});
}
roll() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => {
if (this.loaded) {
const options = [...this.options];
this.result = [...Array(this.rolls)]
.map(() => {
let option = options[this.getRandomBetween(0, options.length - 1)];
options.splice(options.indexOf(option), 1);
return option;
})
.join("||");
this.render();
this.trigger("new-result");
resolve(this.result);
}
else {
this.on("loaded", () => {
const options = [...this.options];
this.result = [...Array(this.rolls)]
.map(() => {
let option = options[this.getRandomBetween(0, options.length - 1)];
options.splice(options.indexOf(option), 1);
return option;
})
.join("||");
this.render();
this.trigger("new-result");
resolve(this.result);
});
}
});
});
}
load() {
return __awaiter(this, void 0, void 0, function* () {
yield this.getOptions();
});
}
getOptions() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
this.cache = this.plugin.app.metadataCache.getFileCache(this.file);
if (!this.cache ||
!this.cache.blocks ||
!(this.block in this.cache.blocks)) {
throw new Error("Could not read file cache. Does the block reference exist?\n\n" +
`${this.path} > ${this.block}`);
}
this.position = this.cache.blocks[this.block].position;
this.content = (_a = (yield this.plugin.app.vault.cachedRead(this.file))) === null || _a === void 0 ? void 0 : _a.slice(this.position.start.offset, this.position.end.offset);
let table = extract(this.content);
if (this.header && table.columns[this.header]) {
this.options = table.columns[this.header];
}
else {
if (this.header)
throw new Error(`Header ${this.header} was not found in table ${this.path} > ${this.block}.`);
this.options = table.rows;
}
this.loaded = true;
this.trigger("loaded");
});
}
toResult() {
return {
type: "table",
result: this.result
};
}
applyResult(result) {
return __awaiter(this, void 0, void 0, function* () {
if (result.type !== "table")
return;
if (result.result) {
this.result = result.result;
}
yield this.render();
});
}
}
const MATCH = /^\|?([\s\S]+?)\|?$/;
const SPLIT = /\|/;
function extract(content) {
const lines = content.split("\n");
const inner = lines.map((l) => { var _a; return ((_a = l.trim().match(MATCH)) !== null && _a !== void 0 ? _a : [, l.trim()])[1]; });
const headers = inner[0].split(SPLIT);
const rows = [];
const ret = [];
for (let index in headers) {
let header = headers[index];
if (!header.trim().length)
header = index;
ret.push([header.trim(), []]);
}
for (let line of lines.slice(2)) {
const entries = line
.trim()
.split(SPLIT)
.map((e) => e.trim())
.filter((e) => e.length);
rows.push(entries.join(" | "));
for (let index in entries) {
const entry = entries[index].trim();
if (!entry.length || !ret[index])
continue;
ret[index][1].push(entry);
}
}
return {
columns: Object.fromEntries(ret),
rows: rows
};
}
class SettingTab extends obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
this.plugin = plugin;
}
display() {
return __awaiter(this, void 0, void 0, function* () {
let { containerEl } = this;
containerEl.empty();
containerEl.addClass("dice-roller-settings");
containerEl.createEl("h2", { text: "Dice Roller Settings" });
new obsidian.Setting(containerEl)
.setName("Roll All Files for Tags")
.setDesc("Return a result for each file when rolling tags.")
.addToggle((t) => {
t.setValue(this.plugin.data.returnAllTags);
t.onChange((v) => __awaiter(this, void 0, void 0, function* () {
this.plugin.data.returnAllTags = v;
yield this.plugin.saveSettings();
}));
});
new obsidian.Setting(containerEl)
.setName("Always Return Links for Tags")
.setDesc("Enables random link rolling with the link parameter. Override by specifying a section type.")
.addToggle((t) => {
t.setValue(this.plugin.data.rollLinksForTags);
t.onChange((v) => __awaiter(this, void 0, void 0, function* () {
this.plugin.data.rollLinksForTags = v;
yield this.plugin.saveSettings();
}));
});
new obsidian.Setting(containerEl)
.setName("Add Copy Button to Section Results")
.setDesc("Randomly rolled sections will have a copy-content button to easy add result to clipboard.")
.addToggle((t) => {
t.setValue(this.plugin.data.copyContentButton);
t.onChange((v) => __awaiter(this, void 0, void 0, function* () {
this.plugin.data.copyContentButton = v;
yield this.plugin.saveSettings();
}));
});
new obsidian.Setting(containerEl)
.setName("Display Formula With Results")
.setDesc("Both the formula and the results will both be displayed in preview mode.")
.addToggle((t) => {
t.setValue(this.plugin.data.displayResultsInline);
t.onChange((v) => __awaiter(this, void 0, void 0, function* () {
this.plugin.data.displayResultsInline = v;
yield this.plugin.saveSettings();
}));
});
const save = new obsidian.Setting(containerEl)
.setName("Globally Save Results")
.setDesc("Dice results will be saved by default. This can be overridden using ")
.addToggle((t) => {
t.setValue(this.plugin.data.persistResults);
t.onChange((v) => __awaiter(this, void 0, void 0, function* () {
this.plugin.data.persistResults = v;
yield this.plugin.saveSettings();
}));
});
new obsidian.Setting(containerEl)
.setName("Default Roll")
.setDesc("Use this as the number of rolls when it is omitted.")
.addText((t) => {
t.setValue(`${this.plugin.data.defaultRoll}`);
t.inputEl.onblur = () => __awaiter(this, void 0, void 0, function* () {
if (isNaN(Number(t.inputEl.value))) {
new obsidian.Notice("The default roll must be a number.");
}
this.plugin.data.defaultRoll = Number(t.inputEl.value);
yield this.plugin.saveSettings();
});
});
new obsidian.Setting(containerEl)
.setName("Default Face")
.setDesc("Use this as the number of faces when it is omitted.")
.addText((t) => {
t.setValue(`${this.plugin.data.defaultFace}`);
t.inputEl.onblur = () => __awaiter(this, void 0, void 0, function* () {
if (isNaN(Number(t.inputEl.value))) {
new obsidian.Notice("The default face must be a number.");
}
this.plugin.data.defaultFace = Number(t.inputEl.value);
yield this.plugin.saveSettings();
});
});
save.descEl.createEl("code", { text: `dice-: formula` });
save.descEl.createEl("p", {
text: "Please note that the plugin will attempt to save the result but may not be able to."
});
this.additionalContainer = containerEl.createDiv("dice-roller-setting-additional-container");
this.buildFormulaSettings();
const div = containerEl.createDiv("coffee");
div.createEl("a", {
href: "https://www.buymeacoffee.com/valentine195"
}).createEl("img", {
attr: {
src: "https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=☕&slug=valentine195&button_colour=e3e7ef&font_colour=262626&font_family=Inter&outline_colour=262626&coffee_colour=ff0000"
}
});
});
}
buildFormulaSettings() {
this.additionalContainer.empty();
const addNew = this.additionalContainer.createDiv();
new obsidian.Setting(addNew)
.setName("Add Formula")
.setDesc("Add a new formula shortcut.")
.addButton((button) => {
let b = button
.setTooltip("Add Formula")
.setButtonText("+")
.onClick(() => __awaiter(this, void 0, void 0, function* () {
const formula = yield this.buildFormulaForm(addNew);
if (formula) {
this.plugin.data.formulas[formula.alias] =
formula.formula;
this.buildFormulaSettings();
yield this.plugin.saveSettings();
}
}));
return b;
});
const additional = this.additionalContainer.createDiv("additional");
const formulas = this.plugin.data.formulas;
for (const [alias, formula] of Object.entries(formulas)) {
const setting = new obsidian.Setting(additional).setName(alias);
setting.controlEl.createSpan({ text: formula });
setting
.addExtraButton((b) => b
.setIcon("pencil")
.setTooltip("Edit")
.onClick(() => __awaiter(this, void 0, void 0, function* () {
const edited = yield this.buildFormulaForm(addNew, {
alias,
formula
});
if (edited) {
delete this.plugin.data.formulas[alias];
this.plugin.data.formulas[edited.alias] =
edited.formula;
this.buildFormulaSettings();
yield this.plugin.saveSettings();
}
})))
.addExtraButton((b) => b
.setIcon("trash")
.setTooltip("Delete")
.onClick(() => __awaiter(this, void 0, void 0, function* () {
delete this.plugin.data.formulas[alias];
yield this.plugin.saveSettings();
this.buildFormulaSettings();
})));
}
if (!Object.values(formulas).length) {
additional.createSpan({
text: "Create a formula to see it here!",
cls: "no-formulas"
});
}
}
buildFormulaForm(el, temp = {
alias: null,
formula: null
}) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => {
const formulaEl = el.createDiv("add-new-formula");
const dataEl = formulaEl.createDiv("formula-data");
new obsidian.Setting(dataEl).setName("Alias").addText((t) => {
t.setValue(temp.alias).onChange((v) => (temp.alias = v));
});
new obsidian.Setting(dataEl).setName("Formula").addText((t) => {
t.setValue(temp.formula).onChange((v) => (temp.formula = v));
});
const buttonEl = formulaEl.createDiv("formula-buttons");
new obsidian.Setting(buttonEl)
.addButton((b) => b
.setCta()
.setButtonText("Save")
.onClick(() => __awaiter(this, void 0, void 0, function* () {
formulaEl.detach();
resolve(temp);
})))
.addExtraButton((b) => b
.setIcon("cross")
.setTooltip("Cancel")
.onClick(() => {
formulaEl.detach();
resolve(null);
}));
});
});
}
}
String.prototype.matchAll =
String.prototype.matchAll ||
function* matchAll(regexp) {
const flags = regexp.global ? regexp.flags : regexp.flags + "g";
const re = new RegExp(regexp, flags);
let match;
while ((match = re.exec(this))) {
yield match;
}
};
const DEFAULT_SETTINGS = {
returnAllTags: true,
rollLinksForTags: false,
copyContentButton: true,
displayResultsInline: false,
formulas: {},
persistResults: false,
results: {},
defaultRoll: 1,
defaultFace: 100
};
class DiceRollerPlugin extends obsidian.Plugin {
constructor() {
super(...arguments);
this.persistingFiles = new Set();
this.operators = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
"^": (a, b) => {
return Math.pow(a, b);
}
};
}
onload() {
return __awaiter(this, void 0, void 0, function* () {
console.log("DiceRoller plugin loaded");
this.data = Object.assign(DEFAULT_SETTINGS, yield this.loadData());
this.addSettingTab(new SettingTab(this.app, this));
const ICON_SVG = icon(faDice).html[0];
obsidian.addIcon(ICON_DEFINITION, ICON_SVG);
const COPY_SVG = icon(faCopy).html[0];
obsidian.addIcon(COPY_DEFINITION, COPY_SVG);
this.registerMarkdownPostProcessor((el, ctx) => __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e;
let nodeList = el.querySelectorAll("code");
if (!nodeList.length)
return;
const path = ctx.sourcePath;
const info = ctx.getSectionInfo(el);
const lineStart = (_a = ctx.getSectionInfo(el)) === null || _a === void 0 ? void 0 : _a.lineStart;
const file = this.app.vault.getAbstractFileByPath(ctx.sourcePath);
if (!file || !(file instanceof obsidian.TFile) || !info)
return;
const toPersist = {};
for (let index = 0; index < nodeList.length; index++) {
const node = nodeList.item(index);
if (/^dice\-mod:\s*([\s\S]+)\s*?/.test(node.innerText)) {
try {
let [full, content] = node.innerText.match(/^dice\-mod:\s*([\s\S]+)\s*?/);
if (content in this.data.formulas) {
content = this.data.formulas[content];
}
if (!DICE_REGEX.test(content)) {
new obsidian.Notice("Replacing note content may only be done with Dice Rolls.");
continue;
}
//build result map;
const roller = this.getRoller(content, ctx.sourcePath);
yield roller.roll();
const fileContent = (yield this.app.vault.cachedRead(file)).split("\n");
let splitContent = fileContent.slice(info.lineStart, info.lineEnd + 1);
splitContent = splitContent
.join("\n")
.replace(`\`${full}\``, `${roller.inlineText} **${roller.result}**`)
.split("\n");
fileContent.splice(info.lineStart, info.lineEnd - info.lineStart + 1, ...splitContent);
yield this.app.vault.modify(file, fileContent.join("\n"));
}
catch (e) {
console.error(e);
}
}
if (!/^dice(?:\+|\-)?:\s*([\s\S]+)\s*?/.test(node.innerText))
continue;
try {
let [, content] = node.innerText.match(/^dice(?:\+|\-)?:\s*([\s\S]+)\s*?/);
if (content in this.data.formulas) {
content = this.data.formulas[content];
}
//build result map;
const roller = this.getRoller(content, ctx.sourcePath);
yield roller.roll();
if ((this.data.persistResults &&
!/dice\-/.test(node.innerText)) ||
/dice\+/.test(node.innerText)) {
this.persistingFiles.add(ctx.sourcePath);
toPersist[index] = roller;
const result = (_e = (_d = (_c = (_b = this.data.results) === null || _b === void 0 ? void 0 : _b[path]) === null || _c === void 0 ? void 0 : _c[lineStart]) === null || _d === void 0 ? void 0 : _d[index]) !== null && _e !== void 0 ? _e : null;
if (result) {
yield roller.applyResult(result);
}
}
node.replaceWith(roller.containerEl);
}
catch (e) {
console.error(e);
new obsidian.Notice(`There was an error parsing the dice string: ${node.innerText}.\n\n${e}`, 5000);
continue;
}
}
if (path in this.data.results) {
this.data.results[path][lineStart] = {};
}
if (Object.entries(toPersist).length) {
const view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
if (view) {
const self = this;
let unregisterOnUnloadFile = around(view, {
onUnloadFile: function (next) {
return function (unloaded) {
var _a, _b, _c, _d;
return __awaiter(this, void 0, void 0, function* () {
if ((unloaded = file)) {
if (self.persistingFiles.has(path)) {
self.persistingFiles.delete(path);
self.data.results[path] = {};
}
for (let index in toPersist) {
const roller = toPersist[index];
const newLineStart = (_a = ctx.getSectionInfo(el)) === null || _a === void 0 ? void 0 : _a.lineStart;
if (newLineStart == null)
continue;
const result = {
[newLineStart]: Object.assign(Object.assign({}, ((_c = (_b = self.data.results[path]) === null || _b === void 0 ? void 0 : _b[newLineStart]) !== null && _c !== void 0 ? _c : {})), { [index]: roller.toResult() })
};
self.data.results[path] = Object.assign(Object.assign({}, ((_d = self.data.results[path]) !== null && _d !== void 0 ? _d : {})), result);
yield self.saveSettings();
}
}
unregisterOnUnloadFile();
return yield next.call(this, unloaded);
});
};
}
});
view.register(unregisterOnUnloadFile);
view.register(() => __awaiter(this, void 0, void 0, function* () {
var _f, _g, _h, _j;
if (this.persistingFiles.has(path)) {
this.persistingFiles.delete(path);
this.data.results[path] = {};
}
for (let index in toPersist) {
const roller = toPersist[index];
const newLineStart = (_f = ctx.getSectionInfo(el)) === null || _f === void 0 ? void 0 : _f.lineStart;
if (newLineStart == null)
continue;
const result = {
[newLineStart]: Object.assign(Object.assign({}, ((_h = (_g = this.data.results[path]) === null || _g === void 0 ? void 0 : _g[newLineStart]) !== null && _h !== void 0 ? _h : {})), { [index]: roller.toResult() })
};
this.data.results[path] = Object.assign(Object.assign({}, ((_j = this.data.results[path]) !== null && _j !== void 0 ? _j : {})), result);
yield this.saveSettings();
}
}));
}
}
}));
this.lexer = new lexer();
this.addLexerRules();
var exponent = {
precedence: 3,
associativity: "right"
};
var factor = {
precedence: 2,
associativity: "left"
};
var term = {
precedence: 1,
associativity: "left"
};
this.parser = new Parser({
"+": term,
"-": term,
"*": factor,
"/": factor,
"^": exponent
});
});
}
parseDice(content, source) {
return __awaiter(this, void 0, void 0, function* () {
const roller = this.getRoller(content, source);
return { result: yield roller.roll() };
});
}
clearEmpties(o) {
for (var k in o) {
if (!o[k] || typeof o[k] !== "object") {
continue;
}
this.clearEmpties(o[k]);
if (Object.keys(o[k]).length === 0) {
delete o[k];
}
}
}
saveSettings() {
return __awaiter(this, void 0, void 0, function* () {
this.clearEmpties(this.data.results);
yield this.saveData(this.data);
});
}
getRoller(content, source) {
const lexemes = this.parse(content);
const type = this.getTypeFromLexemes(lexemes);
switch (type) {
case "dice": {
return new StackRoller(this, content, lexemes);
}
case "table": {
return new TableRoller(this, content, lexemes[0], source);
}
case "section": {
return new SectionRoller(this, content, lexemes[0], source);
}
case "tag": {
if (!this.app.plugins.plugins.dataview) {
throw new Error("Tags are only supported with the Dataview plugin installed.");
}
return new TagRoller(this, content, lexemes[0], source);
}
case "link": {
return new LinkRoller(this, content, lexemes[0], source);
}
}
}
getTypeFromLexemes(lexemes) {
if (lexemes.some(({ type }) => type === "table")) {
return "table";
}
if (lexemes.some(({ type }) => type === "section")) {
return "section";
}
if (lexemes.some(({ type }) => type === "tag")) {
return "tag";
}
if (lexemes.some(({ type }) => type === "link")) {
return "link";
}
return "dice";
}
addLexerRules() {
this.lexer.addRule(/\s+/, function () {
/* skip whitespace */
});
this.lexer.addRule(/[{}]+/, function () {
/* skip brackets */
});
this.lexer.addRule(TABLE_REGEX, function (lexeme) {
return {
type: "table",
data: lexeme,
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(SECTION_REGEX, function (lexeme) {
return {
type: "section",
data: lexeme,
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(TAG_REGEX, (lexeme) => {
var _a;
const { groups } = lexeme.match(TAG_REGEX);
let type = "tag";
if (groups.types === "link" ||
(this.data.rollLinksForTags && !((_a = groups.types) === null || _a === void 0 ? void 0 : _a.length))) {
type = "link";
}
return {
type,
data: lexeme,
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(DICE_REGEX, function (lexeme) {
const { dice, conditional } = lexeme.match(DICE_REGEX).groups;
let conditionals = [];
if (conditional) {
let matches = conditional.matchAll(CONDITIONAL_REGEX);
if (matches) {
for (let match of matches) {
if (!match)
continue;
const { comparer, operator } = match.groups;
conditionals.push({
comparer: Number(comparer),
operator
});
}
}
}
return {
type: "dice",
data: dice,
original: lexeme,
conditionals
}; // symbols
});
this.lexer.addRule(OMITTED_REGEX, (lexeme) => {
const { roll = this.data.defaultRoll, faces = this.data.defaultFace, conditional } = lexeme.match(OMITTED_REGEX).groups;
let conditionals = [];
if (conditional) {
let matches = conditional.matchAll(CONDITIONAL_REGEX);
if (matches) {
for (let match of matches) {
if (!match)
continue;
const { comparer, operator } = match.groups;
conditionals.push({
comparer: Number(comparer),
operator
});
}
}
}
return {
type: "dice",
data: `${roll}d${faces}`,
original: lexeme,
conditionals
}; // symbols
});
this.lexer.addRule(MATH_REGEX, function (lexeme) {
return {
type: "math",
data: lexeme,
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(/1[Dd]S/, function (lexeme) {
var _a;
const [, dice] = (_a = lexeme.match(/1[Dd]S/)) !== null && _a !== void 0 ? _a : [, "1"];
return {
type: "stunt",
data: dice,
original: lexeme,
conditionals: []
}; // symbols
});
this.lexer.addRule(/kh?(?!:l)(\d*)/, function (lexeme) {
/** keep high */
return {
type: "kh",
data: lexeme.replace(/^\D+/g, ""),
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(/dl?(?!:h)\d*/, function (lexeme) {
/** drop low */
return {
type: "dl",
data: lexeme.replace(/^\D+/g, ""),
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(/kl\d*/, function (lexeme) {
/** keep low */
return {
type: "kl",
data: lexeme.replace(/^\D+/g, ""),
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(/dh\d*/, function (lexeme) {
/** drop high */
return {
type: "dh",
data: lexeme.replace(/^\D+/g, ""),
original: lexeme,
conditionals: null
};
});
this.lexer.addRule(/!!(i|\d+)?(?:(!?=|=!|>=?|<=?)(-?\d+))*/, function (lexeme) {
/** explode and combine */
let [, data = `1`] = lexeme.match(/!!(i|\d+)?(?:(!?=|=!|>=?|<=?)(-?\d+))*/), conditionals = [];
if (/(?:(!?=|=!|>=?|<=?)(-?\d+))+/.test(lexeme)) {
for (const [, operator, comparer] of lexeme.matchAll(/(?:(!?=|=!|>=?|<=?)(-?\d+))/g)) {
conditionals.push({
operator: operator,
comparer: Number(comparer)
});
}
}
if (/!!i/.test(lexeme)) {
data = `100`;
}
return {
type: "!!",
data: data,
original: lexeme,
conditionals: conditionals
};
});
this.lexer.addRule(/!(i|\d+)?(?:(!?=|=!?|>=?|<=?)(-?\d+))*/, function (lexeme) {
/** explode */
let [, data = `1`] = lexeme.match(/!(i|\d+)?(?:(!?=|=!?|>=?|<=?)(-?\d+))*/), conditionals = [];
if (/(?:(!?=|=!|>=?|<=?)(\d+))+/.test(lexeme)) {
for (const [, operator, comparer] of lexeme.matchAll(/(?:(!?=|=!?|>=?|<=?)(-?\d+))/g)) {
conditionals.push({
operator: operator,
comparer: Number(comparer)
});
}
}
if (/!i/.test(lexeme)) {
data = `100`;
}
return {
type: "!",
data: data,
original: lexeme,
conditionals: conditionals
};
});
this.lexer.addRule(/r(i|\d+)?(?:(!?=|=!|>=?|<=?)(-?\d+))*/, function (lexeme) {
/** reroll */
let [, data = `1`] = lexeme.match(/r(i|\d+)?(?:(!?=|=!|>=?|<=?)(-?\d+))*/), conditionals = [];
if (/(?:(!?={1,2}|>=?|<=?)(-?\d+))+/.test(lexeme)) {
for (const [, operator, comparer] of lexeme.matchAll(/(?:(!?=|=!|>=?|<=?)(-?\d+))/g)) {
conditionals.push({
operator: operator,
comparer: Number(comparer)
});
}
}
if (/ri/.test(lexeme)) {
data = `100`;
}
return {
type: "r",
data: data,
original: lexeme,
conditionals: conditionals
};
});
}
onunload() {
console.log("DiceRoller unloaded");
}
parse(input) {
this.lexer.setInput(input);
var tokens = [], token;
while ((token = this.tryLex()))
tokens.push(token);
return this.parser.parse(tokens);
}
tryLex() {
try {
return this.lexer.lex();
}
catch (e) { }
}
}
module.exports = DiceRollerPlugin;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFpbi5qcyIsInNvdXJjZXMiOlsibm9kZV9tb2R1bGVzL3RzbGliL3RzbGliLmVzNi5qcyIsIm5vZGVfbW9kdWxlcy9sZXgvbGV4ZXIuanMiLCJub2RlX21vZHVsZXMvQGZvcnRhd2Vzb21lL2ZyZWUtc29saWQtc3ZnLWljb25zL2luZGV4LmVzLmpzIiwibm9kZV9tb2R1bGVzL0Bmb3J0YXdlc29tZS9mcmVlLXJlZ3VsYXItc3ZnLWljb25zL2luZGV4LmVzLmpzIiwibm9kZV9tb2R1bGVzL0Bmb3J0YXdlc29tZS9mb250YXdlc29tZS1zdmctY29yZS9pbmRleC5lcy5qcyIsInNyYy9wYXJzZXIvcGFyc2VyLnRzIiwibm9kZV9tb2R1bGVzL21vbmtleS1hcm91bmQvbWpzL2luZGV4LmpzIiwic3JjL3V0aWxzL2NvbnN0YW50cy50cyIsInNyYy91dGlscy91dGlsLnRzIiwic3JjL3JvbGxlci9yb2xsZXIudHMiLCJzcmMvcm9sbGVyL2RpY2UudHMiLCJzcmMvcm9sbGVyL3NlY3Rpb24udHMiLCJzcmMvcm9sbGVyL3RhYmxlLnRzIiwic3JjL3NldHRpbmdzL3NldHRpbmdzLnRzIiwic3JjL21haW4udHMiXSwic291cmNlc0NvbnRlbnQiOm51bGwsIm5hbWVzIjpbIkV2ZW50cyIsInNldEljb24iLCJURmlsZSIsIk5vdGljZSIsIk1hcmtkb3duUmVuZGVyZXIiLCJQbHVnaW5TZXR0aW5nVGFiIiwiU2V0dGluZyIsIlBsdWdpbiIsImFkZEljb24iLCJNYXJrZG93blZpZXciXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUF1REE7QUFDTyxTQUFTLFNBQVMsQ0FBQyxPQUFPLEVBQUUsVUFBVSxFQUFFLENBQUMsRUFBRSxTQUFTLEVBQUU7QUFDN0QsSUFBSSxTQUFTLEtBQUssQ0FBQyxLQUFLLEVBQUUsRUFBRSxPQUFPLEtBQUssWUFBWSxDQUFDLEdBQUcsS0FBSyxHQUFHLElBQUksQ0FBQyxDQUFDLFVBQVUsT0FBTyxFQUFFLEVBQUUsT0FBTyxDQUFDLEtBQUssQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUU7QUFDaEgsSUFBSSxPQUFPLEtBQUssQ0FBQyxLQUFLLENBQUMsR0FBRyxPQUFPLENBQUMsRUFBRSxVQUFVLE9BQU8sRUFBRSxNQUFNLEVBQUU7QUFDL0QsUUFBUSxTQUFTLFNBQVMsQ0FBQyxLQUFLLEVBQUUsRUFBRSxJQUFJLEVBQUUsSUFBSSxDQUFDLFNBQVMsQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsT0FBTyxDQUFDLEVBQUUsRUFBRSxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUMsRUFBRSxFQUFFO0FBQ25HLFFBQVEsU0FBUyxRQUFRLENBQUMsS0FBSyxFQUFFLEVBQUUsSUFBSSxFQUFFLElBQUksQ0FBQyxTQUFTLENBQUMsT0FBTyxDQUFDLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsT0FBTyxDQUFDLEVBQUUsRUFBRSxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUMsRUFBRSxFQUFFO0FBQ3RHLFFBQVEsU0FBUyxJQUFJLENBQUMsTUFBTSxFQUFFLEVBQUUsTUFBTSxDQUFDLElBQUksR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxHQUFHLEtBQUssQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLENBQUMsSUFBSSxDQUFDLFNBQVMsRUFBRSxRQUFRLENBQUMsQ0FBQyxFQUFFO0FBQ3RILFFBQVEsSUFBSSxDQUFDLENBQUMsU0FBUyxHQUFHLFNBQVMsQ0FBQyxLQUFLLENBQUMsT0FBTyxFQUFFLFVBQVUsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLEVBQUUsQ0FBQyxDQUFDO0FBQzlFLEtBQUssQ0FBQyxDQUFDO0FBQ1A7Ozs7Ozs7Ozs7Ozs7Ozs7O0FDN0VzRSxjQUFjLEdBQUcsS0FBSyxDQUFDO0FBQzdGO0FBQ0EsS0FBSyxDQUFDLE9BQU8sR0FBRyxVQUFVLEdBQUcsRUFBRTtBQUMvQixJQUFJLE1BQU0sSUFBSSxLQUFLLENBQUMsZ0NBQWdDLElBQUksSUFBSSxDQUFDLEtBQUssR0FBRyxDQUFDLENBQUMsR0FBRyxJQUFJLEdBQUcsR0FBRyxDQUFDLENBQUM7QUFDdEYsQ0FBQyxDQUFDO0FBQ0Y7QUFDQSxTQUFTLEtBQUssQ0FBQyxPQUFPLEVBQUU7QUFDeEIsSUFBSSxJQUFJLE9BQU8sT0FBTyxLQUFLLFVBQVUsRUFBRSxPQUFPLEdBQUcsS0FBSyxDQUFDLE9BQU8sQ0FBQztBQUMvRDtBQUNBLElBQUksSUFBSSxNQUFNLEdBQUcsRUFBRSxDQUFDO0FBQ3BCLElBQUksSUFBSSxLQUFLLEdBQUcsRUFBRSxDQUFDO0FBQ25CLElBQUksSUFBSSxNQUFNLEdBQUcsQ0FBQyxDQUFDO0FBQ25CLElBQUksSUFBSSxDQUFDLEtBQUssR0FBRyxDQUFDLENBQUM7QUFDbkIsSUFBSSxJQUFJLENBQUMsS0FBSyxHQUFHLENBQUMsQ0FBQztBQUNuQixJQUFJLElBQUksQ0FBQyxLQUFLLEdBQUcsRUFBRSxDQUFDO0FBQ3BCO0FBQ0EsSUFBSSxJQUFJLENBQUMsT0FBTyxHQUFHLFVBQVUsT0FBTyxFQUFFLE1BQU0sRUFBRSxLQUFLLEVBQUU7QUFDckQsUUFBUSxJQUFJLE1BQU0sR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDO0FBQ3BDO0FBQ0EsUUFBUSxJQUFJLENBQUMsTUFBTSxFQUFFO0FBQ3JCLFlBQVksSUFBSSxLQUFLLEdBQUcsR0FBRyxDQUFDO0FBQzVCLFlBQVksSUFBSSxPQUFPLENBQUMsU0FBUyxFQUFFLEtBQUssSUFBSSxHQUFHLENBQUM7QUFDaEQsWUFBWSxJQUFJLE9BQU8sQ0FBQyxVQUFVLEVBQUUsS0FBSyxJQUFJLEdBQUcsQ0FBQztBQUNqRCxZQUFZLE9BQU8sR0FBRyxJQUFJLE1BQU0sQ0FBQyxPQUFPLENBQUMsTUFBTSxFQUFFLEtBQUssQ0FBQyxDQUFDO0FBQ3hELFNBQVM7QUFDVDtBQUNBLFFBQVEsSUFBSSxNQUFNLENBQUMsU0FBUyxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLEtBQUssZ0JBQWdCLEVBQUUsS0FBSyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDcEY7QUFDQSxRQUFRLEtBQUssQ0FBQyxJQUFJLENBQUM7QUFDbkIsWUFBWSxPQUFPLEVBQUUsT0FBTztBQUM1QixZQUFZLE1BQU0sRUFBRSxNQUFNO0FBQzFCLFlBQVksTUFBTSxFQUFFLE1BQU07QUFDMUIsWUFBWSxLQUFLLEVBQUUsS0FBSztBQUN4QixTQUFTLENBQUMsQ0FBQztBQUNYO0FBQ0EsUUFBUSxPQUFPLElBQUksQ0FBQztBQUNwQixLQUFLLENBQUM7QUFDTjtBQUNBLElBQUksSUFBSSxDQUFDLFFBQVEsR0FBRyxVQUFVLEtBQUssRUF