Files
2025-07-24 01:51:44 +01:00

1757 lines
92 KiB
HTML

<button name="act_k-network-call" hidden="" type="action">
</button>
<header class="sheet-header flexrow">
<div class="portrait-container"><img class="portrait" name="attr_character_avatar" data-i18n-alt="character_avatar" title="@{character_avatar}"/>
<div class="placeholder-avatar"></div>
</div>
<div class="header-data-container flexcol">
<!-- Character Name-->
<h1 class="document-name flexrow">
<div class="adaptive adaptive--input"><span class="adaptive--input__span" name="attr_character_name" title="@{character_name}"></span>
<input class="document-name-input adaptive--input__input" name="attr_character_name" type="text" data-i18n-placeholder="character-name" title="@{character_name}"/>
</div>
</h1>
<!-- Luck & Pronouns Section-->
<div class="document-details flexrow">
<div class="detail-left luck-container flexrow">
<label class="input-label"><span class="input-label__text" data-i18n="character-luck">Luck</span></label>
<div class="number-input-container">
<input class="luck-input" name="attr_luck" type="number" value="4" title="@{luck}"/>
<div class="number-input-controls">
<button class="arrow-button" type="action" name="act_act-luck-up">
</button>
<button class="arrow-button" type="action" name="act_act-luck-down">
</button>
</div><span>/</span>
<input class="luck-input" name="attr_luck_max" type="number" value="4" title="@{luck|max}"/>
<div class="number-input-controls">
<button class="arrow-button" type="action" name="act_act-luck-up-max">
</button>
<button class="arrow-button" type="action" name="act_act-luck-down-max">
</button>
</div>
</div>
</div>
<div class="detail-right pronouns">
<input name="attr_pronouns" type="text" data-i18n-placeholder="character-pronouns" title="@{pronouns}"/>
</div>
</div>
</div>
</header>
<!--include ./sections/_index.pug-->
<input name="attr_sheet_version" value="0" type="hidden" title="@{sheet_version}"/>
<main id="main">
<!-- Overlay container to hold all corner images-->
<div class="overlay-container">
<div class="corner top-left">
</div>
<div class="logo-container">
</div>
<div class="corner top-right">
</div>
<div class="corner bottom-right">
</div>
</div><!-- sectionName:discworld -->
<input name="attr_discworld_tab" value="nav-tabs-discworld--traits" type="hidden" title="@{discworld_tab}"/>
<div class="tabs tabs--discworld flex-box tiny-gap">
<nav class="tabs__header tabs--discworld__header">
<ul class="tabs__nav-list">
<li class="tabs__nav-item">
<button class="tabs__button tabs--discworld__button tabs--discworld__button--traits" data-i18n="tabs-traits" name="act_nav-tabs-discworld--traits" data-container-button="discworld" data-button="traits" type="action" data-container-tab="discworld" data-tab="traits">
</button>
</li>
<li class="tabs__nav-item">
<button class="tabs__button tabs--discworld__button tabs--discworld__button--description" data-i18n="tabs-description" name="act_nav-tabs-discworld--description" data-container-button="discworld" data-button="description" type="action" data-container-tab="discworld" data-tab="description">
</button>
</li>
</ul>
</nav>
<div class="tabs__body tabs--discworld__body">
<section class="tabs__container tabs--discworld__container tabs--discworld__container--traits" data-container-tab="discworld" data-tab="traits">
<div class="traits-header flexrow justify-space-between"><span></span>
<label class="input-label"><span class="input-label__text" data-i18n="whisper"></span>
<select class="input-label__input" name="attr_whisper" title="@{whisper}">
<option value="" data-i18n="public">
</option>
<option value="/w gm " data-i18n="gm">
</option>
</select>
</label>
</div>
<div class="trait-type flexrow">
<div class="trait-category" data-trait-type="organization">
<label data-i18n="trait-type-organization"></label>
</div>
<div class="trait-list">
<button class="repcontrol-button repcontrol-button--add" name="act_add-traits-organization" type="action">
</button>
<fieldset class="repeating_traits-organization">
<div class="trait-item">
<input class="collapse" name="attr_collapse" value="1" type="checkbox" title="@{repeating_traits-organization_$X_collapse}"/>
<div class="flexrow trait-name">
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_name" title="@{repeating_traits-organization_$X_name}"></span>
<textarea class="trait-name adaptive--text__textarea" name="attr_name" data-i18n-placeholder="trait-name" title="@{repeating_traits-organization_$X_name}"></textarea>
</div>
<button class="trait-roll-button roller" name="roll_trait" value="@{trait_action}" type="roll">
</button>
<button name="act_trait-action" hidden="" type="action">
</button>
<input name="attr_trait_action" type="hidden" title="@{repeating_traits-organization_$X_trait_action}"/>
</div>
<div class="expanded">
<div class="flexcol">
<hr/>
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_description" title="@{repeating_traits-organization_$X_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_description" label="character-description" data-i18n-placeholder="character-description" title="@{repeating_traits-organization_$X_description}"></textarea>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<hr/>
<div class="trait-type flexrow">
<div class="trait-category" data-trait-type="background">
<label data-i18n="trait-type-background"></label>
</div>
<div class="trait-list">
<button class="repcontrol-button repcontrol-button--add" name="act_add-traits-background" type="action">
</button>
<fieldset class="repeating_traits-background">
<div class="trait-item">
<input class="collapse" name="attr_collapse" value="1" type="checkbox" title="@{repeating_traits-background_$X_collapse}"/>
<div class="flexrow trait-name">
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_name" title="@{repeating_traits-background_$X_name}"></span>
<textarea class="trait-name adaptive--text__textarea" name="attr_name" data-i18n-placeholder="trait-name" title="@{repeating_traits-background_$X_name}"></textarea>
</div>
<button class="trait-roll-button roller" name="roll_trait" value="@{trait_action}" type="roll">
</button>
<button name="act_trait-action" hidden="" type="action">
</button>
<input name="attr_trait_action" type="hidden" title="@{repeating_traits-background_$X_trait_action}"/>
</div>
<div class="expanded">
<div class="flexcol">
<hr/>
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_description" title="@{repeating_traits-background_$X_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_description" label="character-description" data-i18n-placeholder="character-description" title="@{repeating_traits-background_$X_description}"></textarea>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<hr/>
<div class="trait-type flexrow">
<div class="trait-category" data-trait-type="niche">
<label data-i18n="trait-type-niche"></label>
</div>
<div class="trait-list">
<button class="repcontrol-button repcontrol-button--add" name="act_add-traits-niche" type="action">
</button>
<fieldset class="repeating_traits-niche">
<div class="trait-item">
<input class="collapse" name="attr_collapse" value="1" type="checkbox" title="@{repeating_traits-niche_$X_collapse}"/>
<div class="flexrow trait-name">
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_name" title="@{repeating_traits-niche_$X_name}"></span>
<textarea class="trait-name adaptive--text__textarea" name="attr_name" data-i18n-placeholder="trait-name" title="@{repeating_traits-niche_$X_name}"></textarea>
</div>
<button class="trait-roll-button roller" name="roll_trait" value="@{trait_action}" type="roll">
</button>
<button name="act_trait-action" hidden="" type="action">
</button>
<input name="attr_trait_action" type="hidden" title="@{repeating_traits-niche_$X_trait_action}"/>
</div>
<div class="expanded">
<div class="flexcol">
<hr/>
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_description" title="@{repeating_traits-niche_$X_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_description" label="character-description" data-i18n-placeholder="character-description" title="@{repeating_traits-niche_$X_description}"></textarea>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<hr/>
<div class="trait-type flexrow">
<div class="trait-category" data-trait-type="core">
<label data-i18n="trait-type-core"></label>
</div>
<div class="trait-list">
<button class="repcontrol-button repcontrol-button--add" name="act_add-traits-core" type="action">
</button>
<fieldset class="repeating_traits-core">
<div class="trait-item">
<input class="collapse" name="attr_collapse" value="1" type="checkbox" title="@{repeating_traits-core_$X_collapse}"/>
<div class="flexrow trait-name">
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_name" title="@{repeating_traits-core_$X_name}"></span>
<textarea class="trait-name adaptive--text__textarea" name="attr_name" data-i18n-placeholder="trait-name" title="@{repeating_traits-core_$X_name}"></textarea>
</div>
<button class="trait-roll-button roller" name="roll_trait" value="@{trait_action}" type="roll">
</button>
<button name="act_trait-action" hidden="" type="action">
</button>
<input name="attr_trait_action" type="hidden" title="@{repeating_traits-core_$X_trait_action}"/>
</div>
<div class="expanded">
<div class="flexcol">
<hr/>
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_description" title="@{repeating_traits-core_$X_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_description" label="character-description" data-i18n-placeholder="character-description" title="@{repeating_traits-core_$X_description}"></textarea>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<hr/>
<div class="trait-type flexrow">
<div class="trait-category" data-trait-type="quirks">
<label data-i18n="trait-type-quirks"></label>
</div>
<div class="trait-list">
<button class="repcontrol-button repcontrol-button--add" name="act_add-traits-quirks" type="action">
</button>
<fieldset class="repeating_traits-quirks">
<div class="trait-item">
<input class="collapse" name="attr_collapse" value="1" type="checkbox" title="@{repeating_traits-quirks_$X_collapse}"/>
<div class="flexrow trait-name">
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_name" title="@{repeating_traits-quirks_$X_name}"></span>
<textarea class="trait-name adaptive--text__textarea" name="attr_name" data-i18n-placeholder="trait-name" title="@{repeating_traits-quirks_$X_name}"></textarea>
</div>
<button class="trait-roll-button roller" name="roll_trait" value="@{trait_action}" type="roll">
</button>
<button name="act_trait-action" hidden="" type="action">
</button>
<input name="attr_trait_action" type="hidden" title="@{repeating_traits-quirks_$X_trait_action}"/>
</div>
<div class="expanded">
<div class="flexcol">
<hr/>
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_description" title="@{repeating_traits-quirks_$X_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_description" label="character-description" data-i18n-placeholder="character-description" title="@{repeating_traits-quirks_$X_description}"></textarea>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<hr/>
<div class="trait-type flexrow">
<div class="trait-category" data-trait-type="consequences">
<label data-i18n="trait-type-consequences"></label>
</div>
<div class="trait-list">
<button class="repcontrol-button repcontrol-button--add" name="act_add-traits-consequences" type="action">
</button>
<fieldset class="repeating_traits-consequences">
<div class="trait-item">
<input class="collapse" name="attr_collapse" value="1" type="checkbox" title="@{repeating_traits-consequences_$X_collapse}"/>
<div class="flexrow trait-name">
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_name" title="@{repeating_traits-consequences_$X_name}"></span>
<textarea class="trait-name adaptive--text__textarea" name="attr_name" data-i18n-placeholder="trait-name" title="@{repeating_traits-consequences_$X_name}"></textarea>
</div>
<button class="trait-roll-button roller" name="roll_trait" value="@{trait_action}" type="roll">
</button>
<button name="act_trait-action" hidden="" type="action">
</button>
<input name="attr_trait_action" type="hidden" title="@{repeating_traits-consequences_$X_trait_action}"/>
</div>
<div class="expanded">
<div class="flexcol">
<hr/>
<div class="severity-row flexrow">
<label class="severity-label" data-i18n="trait-severity-label">Severity</label>
<select name="attr_severity" label="trait-severity-label" title="@{repeating_traits-consequences_$X_severity}">
<option value="inconsequential" data-i18n="trait-severity-inconsequential" selected="selected">
</option>
<option value="minor" data-i18n="trait-severity-minor" selected="">
</option>
<option value="major" data-i18n="trait-severity-major" selected="">
</option>
<option value="exceptional" data-i18n="trait-severity-exceptional" selected="">
</option>
</select>
</div>
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_description" title="@{repeating_traits-consequences_$X_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_description" label="character-description" data-i18n-placeholder="character-description" title="@{repeating_traits-consequences_$X_description}"></textarea>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<hr/>
<div class="trait-type flexrow">
<div class="trait-category" data-trait-type="other">
<label data-i18n="trait-type-other"></label>
</div>
<div class="trait-list">
<button class="repcontrol-button repcontrol-button--add" name="act_add-traits-other" type="action">
</button>
<fieldset class="repeating_traits-other">
<div class="trait-item">
<input class="collapse" name="attr_collapse" value="1" type="checkbox" title="@{repeating_traits-other_$X_collapse}"/>
<div class="flexrow trait-name">
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_name" title="@{repeating_traits-other_$X_name}"></span>
<textarea class="trait-name adaptive--text__textarea" name="attr_name" data-i18n-placeholder="trait-name" title="@{repeating_traits-other_$X_name}"></textarea>
</div>
<button class="trait-roll-button roller" name="roll_trait" value="@{trait_action}" type="roll">
</button>
<button name="act_trait-action" hidden="" type="action">
</button>
<input name="attr_trait_action" type="hidden" title="@{repeating_traits-other_$X_trait_action}"/>
</div>
<div class="expanded">
<div class="flexcol">
<hr/>
<div class="adaptive adaptive--text"><span class="adaptive--text__span" name="attr_description" title="@{repeating_traits-other_$X_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_description" label="character-description" data-i18n-placeholder="character-description" title="@{repeating_traits-other_$X_description}"></textarea>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<hr/>
</section>
<section class="tabs__container tabs--discworld__container tabs--discworld__container--description" data-container-tab="discworld" data-tab="description">
<div class="adaptive adaptive--text description-textarea"><span class="adaptive--text__span" name="attr_character_description" title="@{character_description}"></span>
<textarea class="adaptive--text__textarea" name="attr_character_description" data-i18n-placeholder="character-description-tab" title="@{character_description}"></textarea>
</div>
</section>
</div>
</div>
</main>
<input name="attr_template_start" value="@{whisper}&{template:discworld} {{character_name=@{character_name}}} {{character_id=@{character_id}}}" type="hidden" title="@{template_start}"/>
<button class="narrativium-button" name="act_roll-narrativium" style="display: none;" type="action">
</button>
<rolltemplate class="sheet-rolltemplate-discworld">
<div class="discworld-roll">{{#playerRoll}}
<div class="trait-container">
<h4 class="divider" data-i18n="roll-traitRoll"></h4>
<div class="trait-quote"><span class="quote-text">{{title}}</span>
<cite>{{character_name}}</cite>
</div>
</div>{{/playerRoll}}{{#gmRoll}}
<div class="trait-container">
<h4 class="divider" data-i18n="roll-narrativiumRoll"></h4>
</div>{{/gmRoll}}
<div class="dice-rolls flexcol">{{#playerRoll}}
<div class="outcome-container">
<!-- Help Button here?-->
<ol class="result">
<li class="{{die}}"><span>{{roll}}</span></li>
</ol><span class="roll-link">{{rerollLink}}</span>
</div>{{/playerRoll}}{{#gmRoll}}
<div class="outcome-container">
<ol class="result gmroll">
<li class="d8"><span>{{roll}}</span></li>
</ol>
</div>{{/gmRoll}}
</div>
</div>
</rolltemplate>
<script type="text/worker">//# sourceURL=discworld.js
const k = (function(){
const kFuncs = {};
const cascades = {"attr_character_name":{"name":"character_name","type":"text","defaultValue":"","affects":[],"triggeredFuncs":["setActionCalls"],"listenerFunc":"accessSheet","listener":"change:character_name"},"act_k-network-call":{"name":"k-network-call","type":"action","triggeredFuncs":["kReceive"],"affects":[],"addFuncs":[],"listener":"clicked:k-network-call","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_character_avatar":{"name":"character_avatar","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:character_avatar","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_luck":{"name":"luck","type":"number","triggeredFuncs":["adjustLuck"],"affects":[],"addFuncs":[],"listener":"change:luck","listenerFunc":"accessSheet","defaultValue":"4","calculation":"","initialFunc":"","formula":""},"act_act-luck-up":{"name":"act-luck-up","type":"action","triggeredFuncs":["upLuck"],"affects":[],"addFuncs":[],"listener":"clicked:act-luck-up","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_act-luck-down":{"name":"act-luck-down","type":"action","triggeredFuncs":["downLuck"],"affects":[],"addFuncs":[],"listener":"clicked:act-luck-down","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_luck_max":{"name":"luck_max","type":"number","triggeredFuncs":["adjustLuck"],"affects":[],"addFuncs":[],"listener":"change:luck_max","listenerFunc":"accessSheet","defaultValue":"4","calculation":"","initialFunc":"","formula":""},"act_act-luck-up-max":{"name":"act-luck-up-max","type":"action","triggeredFuncs":["upLuckMax"],"affects":[],"addFuncs":[],"listener":"clicked:act-luck-up-max","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_act-luck-down-max":{"name":"act-luck-down-max","type":"action","triggeredFuncs":["downLuckMax"],"affects":[],"addFuncs":[],"listener":"clicked:act-luck-down-max","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_pronouns":{"name":"pronouns","type":"text","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:pronouns","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_sheet_version":{"name":"sheet_version","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:sheet_version","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_discworld_tab":{"name":"discworld_tab","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:discworld_tab","listenerFunc":"accessSheet","defaultValue":"nav-tabs-discworld--traits","calculation":"","initialFunc":"","formula":""},"act_nav-tabs-discworld--traits":{"name":"nav-tabs-discworld--traits","type":"action","triggeredFuncs":["kSwitchTab"],"affects":[],"addFuncs":[],"listener":"clicked:nav-tabs-discworld--traits","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_nav-tabs-discworld--description":{"name":"nav-tabs-discworld--description","type":"action","triggeredFuncs":["kSwitchTab"],"affects":[],"addFuncs":[],"listener":"clicked:nav-tabs-discworld--description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_whisper":{"name":"whisper","type":"select","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:whisper","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_add-traits-organization":{"name":"add-traits-organization","type":"action","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"clicked:add-traits-organization","listenerFunc":"addItem","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-organization_$x_collapse":{"name":"repeating_traits-organization_$x_collapse","type":"checkbox","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-organization:collapse","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-organization_$x_name":{"name":"repeating_traits-organization_$x_name","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-organization:name","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_repeating_traits-organization_$x_trait-action":{"name":"repeating_traits-organization_$x_trait-action","type":"action","triggeredFuncs":["rollTrait"],"affects":[],"addFuncs":[],"listener":"clicked:repeating_traits-organization:trait-action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-organization_$x_trait_action":{"name":"repeating_traits-organization_$x_trait_action","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-organization:trait_action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-organization_$x_description":{"name":"repeating_traits-organization_$x_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-organization:description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_add-traits-background":{"name":"add-traits-background","type":"action","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"clicked:add-traits-background","listenerFunc":"addItem","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-background_$x_collapse":{"name":"repeating_traits-background_$x_collapse","type":"checkbox","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-background:collapse","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-background_$x_name":{"name":"repeating_traits-background_$x_name","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-background:name","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_repeating_traits-background_$x_trait-action":{"name":"repeating_traits-background_$x_trait-action","type":"action","triggeredFuncs":["rollTrait"],"affects":[],"addFuncs":[],"listener":"clicked:repeating_traits-background:trait-action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-background_$x_trait_action":{"name":"repeating_traits-background_$x_trait_action","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-background:trait_action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-background_$x_description":{"name":"repeating_traits-background_$x_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-background:description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_add-traits-niche":{"name":"add-traits-niche","type":"action","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"clicked:add-traits-niche","listenerFunc":"addItem","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-niche_$x_collapse":{"name":"repeating_traits-niche_$x_collapse","type":"checkbox","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-niche:collapse","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-niche_$x_name":{"name":"repeating_traits-niche_$x_name","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-niche:name","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_repeating_traits-niche_$x_trait-action":{"name":"repeating_traits-niche_$x_trait-action","type":"action","triggeredFuncs":["rollTrait"],"affects":[],"addFuncs":[],"listener":"clicked:repeating_traits-niche:trait-action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-niche_$x_trait_action":{"name":"repeating_traits-niche_$x_trait_action","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-niche:trait_action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-niche_$x_description":{"name":"repeating_traits-niche_$x_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-niche:description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_add-traits-core":{"name":"add-traits-core","type":"action","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"clicked:add-traits-core","listenerFunc":"addItem","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-core_$x_collapse":{"name":"repeating_traits-core_$x_collapse","type":"checkbox","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-core:collapse","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-core_$x_name":{"name":"repeating_traits-core_$x_name","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-core:name","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_repeating_traits-core_$x_trait-action":{"name":"repeating_traits-core_$x_trait-action","type":"action","triggeredFuncs":["rollTrait"],"affects":[],"addFuncs":[],"listener":"clicked:repeating_traits-core:trait-action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-core_$x_trait_action":{"name":"repeating_traits-core_$x_trait_action","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-core:trait_action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-core_$x_description":{"name":"repeating_traits-core_$x_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-core:description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_add-traits-quirks":{"name":"add-traits-quirks","type":"action","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"clicked:add-traits-quirks","listenerFunc":"addItem","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-quirks_$x_collapse":{"name":"repeating_traits-quirks_$x_collapse","type":"checkbox","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-quirks:collapse","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-quirks_$x_name":{"name":"repeating_traits-quirks_$x_name","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-quirks:name","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_repeating_traits-quirks_$x_trait-action":{"name":"repeating_traits-quirks_$x_trait-action","type":"action","triggeredFuncs":["rollTrait"],"affects":[],"addFuncs":[],"listener":"clicked:repeating_traits-quirks:trait-action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-quirks_$x_trait_action":{"name":"repeating_traits-quirks_$x_trait_action","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-quirks:trait_action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-quirks_$x_description":{"name":"repeating_traits-quirks_$x_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-quirks:description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_add-traits-consequences":{"name":"add-traits-consequences","type":"action","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"clicked:add-traits-consequences","listenerFunc":"addItem","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-consequences_$x_collapse":{"name":"repeating_traits-consequences_$x_collapse","type":"checkbox","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-consequences:collapse","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-consequences_$x_name":{"name":"repeating_traits-consequences_$x_name","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-consequences:name","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_repeating_traits-consequences_$x_trait-action":{"name":"repeating_traits-consequences_$x_trait-action","type":"action","triggeredFuncs":["rollTrait"],"affects":[],"addFuncs":[],"listener":"clicked:repeating_traits-consequences:trait-action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-consequences_$x_trait_action":{"name":"repeating_traits-consequences_$x_trait_action","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-consequences:trait_action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-consequences_$x_severity":{"name":"repeating_traits-consequences_$x_severity","type":"select","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-consequences:severity","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-consequences_$x_description":{"name":"repeating_traits-consequences_$x_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-consequences:description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_add-traits-other":{"name":"add-traits-other","type":"action","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"clicked:add-traits-other","listenerFunc":"addItem","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-other_$x_collapse":{"name":"repeating_traits-other_$x_collapse","type":"checkbox","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-other:collapse","listenerFunc":"accessSheet","defaultValue":0,"calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-other_$x_name":{"name":"repeating_traits-other_$x_name","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-other:name","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"act_repeating_traits-other_$x_trait-action":{"name":"repeating_traits-other_$x_trait-action","type":"action","triggeredFuncs":["rollTrait"],"affects":[],"addFuncs":[],"listener":"clicked:repeating_traits-other:trait-action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-other_$x_trait_action":{"name":"repeating_traits-other_$x_trait_action","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-other:trait_action","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_repeating_traits-other_$x_description":{"name":"repeating_traits-other_$x_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:repeating_traits-other:description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_character_description":{"name":"character_description","type":"span","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:character_description","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""},"attr_template_start":{"name":"template_start","type":"hidden","triggeredFuncs":[],"affects":[],"addFuncs":[],"listener":"change:template_start","listenerFunc":"accessSheet","defaultValue":"@{whisper}&{template:discworld} {{character_name=@{character_name}}} {{character_id=@{character_id}}}","calculation":"","initialFunc":"","formula":""},"act_roll-narrativium":{"name":"roll-narrativium","type":"action","triggeredFuncs":["rollNarrativium"],"affects":[],"addFuncs":[],"listener":"clicked:roll-narrativium","listenerFunc":"accessSheet","defaultValue":"","calculation":"","initialFunc":"","formula":""}};
kFuncs.cascades = cascades;
const repeatingSectionDetails = [{"section":"repeating_traits-organization","fields":["collapse","name","trait_action","description"]},{"section":"repeating_traits-background","fields":["collapse","name","trait_action","description"]},{"section":"repeating_traits-niche","fields":["collapse","name","trait_action","description"]},{"section":"repeating_traits-core","fields":["collapse","name","trait_action","description"]},{"section":"repeating_traits-quirks","fields":["collapse","name","trait_action","description"]},{"section":"repeating_traits-consequences","fields":["collapse","name","trait_action","severity","description"]},{"section":"repeating_traits-other","fields":["collapse","name","trait_action","description"]}];
kFuncs.repeatingSectionDetails = repeatingSectionDetails;
const persistentTabs = ["discworld_tab"];
kFuncs.persistentTabs = persistentTabs;
/**
* The K-scaffold provides several variables to allow your scripts to tap into its information flow.
* @namespace Sheetworkers.Variables
*/
/**
* This stores the name of your sheet for use in the logging functions {@link log} and {@link debug}. Accessible by `k.sheetName`
* @memberof Variables
* @var
* @type {string}
*/
let sheetName = 'kScaffold Powered Sheet';
kFuncs.sheetName = sheetName;
/**
* This stores the version of your sheet for use in the logging functions{@link log} and {@link debug}. It is also stored in the sheet_version attribute on your character sheet. Accessible via `k.version`
* @memberof Variables
* @var
* @type {number}
*/
let version = 0;
kFuncs.version = version;
/**
* A boolean flag that tells the script whether to enable or disable {@link debug} calls. If the version of the sheet is `0`, or an attribute named `debug_mode` is found on opening this is set to true for your entire session. Otherwise, it remains false.
* @memberof Variables
* @var
* @type {boolean}
*/
let debugMode = false;
kFuncs.debugMode = debugMode;
const funcs = {};
kFuncs.funcs = funcs;
const updateHandlers = {};
const openHandlers = {};
const initialSetups = {};
const allHandlers = {};
const addFuncs = {};
const kscaffoldJSVersion = '1.0.0';
const kscaffoldPUGVersion = '1.0.0';
/**
* Defines the rollstring that rolls made using k.startRoll begin with. Defaults to "&{template:default}".
* @memberof Variables
* @var
* @type {string}
*/
let defaultRollStart = '&{template:default}';
kFuncs.defaultRollStart = defaultRollStart;/*jshint esversion: 11, laxcomma:true, eqeqeq:true*/
/*jshint -W014,-W084,-W030,-W033*/
/**
* These are utility functions that are not directly related to Roll20 systems. They provide easy methods for everything from processing text and numbers to querying the user for input.
* @namespace Sheetworkers.Utilities
* @alias Utilities
*/
/**
* Replaces problem characters to use a string as a regex
* @memberof Utilities
* @param {string} text - The text to replace characters in
* @returns {string}
* @example
* const textForRegex = k.sanitizeForRegex('.some thing[with characters]');
* console.log(textForRegex);// => "\.some thing\[with characters\]"
*/
const sanitizeForRegex = function(text){
return text.replace(/\.|\||\(|\)|\[|\]|\-|\+|\?|\/|\{|\}|\^|\$|\*/g,'\\$&');
};
kFuncs.sanitizeForRegex = sanitizeForRegex;
/**
* Converts a value to a number, it\'s default value, or `0` if no default value passed.
* @memberof Utilities
* @param {string|number} val - Value to convert to a number
* @param {number} def - The default value, uses 0 if not passed
* @returns {number|undefined}
* @example
* const num = k.value('100');
* console.log(num);// => 100
*/
const value = function(val,def){
const convertVal = +val;
if(def !== undefined && isNaN(def)){
throw(`K-scaffold Error: invalid default for value(). Default: ${def}`);
}
return convertVal === 0 ?
convertVal :
(+val||def||0);
};
kFuncs.value = value;
/**
* Extracts the section (e.g. `repeating_equipment`), rowID (e.g `-;lkj098J:LKj`), and field name (e.g. `bulk`) from a repeating attribute name.
* @memberof Utilities
* @param {string} string - The string to parse
* @returns {array} - Array of matches. Index 0: the section name, e.g. repeating_equipment | Index 1:the row ID | index 2: The name of the attribute
* @returns {string[]}
* @example
* //Extract info from a full repeating name
* const [section,rowID,attrName] = k.parseRepeatName('repeating_equipment_-8908asdflkjZlkj23_name');
* console.log(section);// => "repeating_equipment"
* console.log(rowID);// => "-8908asdflkjZlkj23"
* console.log(attrName);// => "name"
*
* //Extract info from just a row name
* const [section,rowID,attrName] = k.parseRepeatName('repeating_equipment_-8908asdflkjZlkj23');
* console.log(section);// => "repeating_equipment"
* console.log(rowID);// => "-8908asdflkjZlkj23"
* console.log(attrName);// => undefined
*/
const parseRepeatName = function(string){
let match = string.match(/(repeating_[^_]+)_([^_]+)(?:_(.+))?/);
match.shift();
return match;
};
kFuncs.parseRepeatName = parseRepeatName;
/**
* Parses out the components of a trigger name similar to [parseRepeatName](#parserepeatname). Aliases: parseClickTrigger.
*
* Aliases: `k.parseClickTrigger`
* @memberof Utilities
* @param {string} string The triggerName property of the
* @returns {array} - For a repeating button named `repeating_equipment_-LKJhpoi98;lj_roll`, the array will be `['repeating_equipment','-LKJhpoi98;lj','roll']`. For a non repeating button named `roll`, the array will be `[undefined,undefined,'roll']`
* @returns {string[]}
* @example
* //Parse a non repeating trigger
* const [section,rowID,attrName] = k.parseTriggerName('clicked:some-button');
* console.log(section);// => undefined
* console.log(rowID);// => undefined
* console.log(attrName);// => "some-button"
*
* //Parse a repeating trigger
* const [section,rowID,attrName] = k.parseTriggerName('clicked:repeating_attack_-234lkjpd8fu8usadf_some-button');
* console.log(section);// => "repeating_attack"
* console.log(rowID);// => "-234lkjpd8fu8usadf"
* console.log(attrName);// => "some-button"
*
* //Parse a repeating name
* const [section,rowID,attrName] = k.parseTriggerName('repeating_attack_-234lkjpd8fu8usadf_some-button');
* console.log(section);// => "repeating_attack"
* console.log(rowID);// => "-234lkjpd8fu8usadf"
* console.log(attrName);// => "some-button"
*/
const parseTriggerName = function(string){
let match = string.replace(/^clicked:/,'').match(/(?:(repeating_[^_]+)_([^_]+)_)?(.+)/);
match.shift();
return match;
};
kFuncs.parseTriggerName = parseTriggerName;
const parseClickTrigger = parseTriggerName;
kFuncs.parseClickTrigger = parseClickTrigger;
/**
* Parses out the attribute name from the htmlattribute name.
* @memberof Utilities
* @param {string} string - The triggerName property of the [event](https://wiki.roll20.net/Sheet_Worker_Scripts#eventInfo_Object).
* @returns {string}
* @example
* //Parse a name
* const attrName = k.parseHtmlName('attr_attribute_1');
* console.log(attrName);// => "attribute_1"
*/
const parseHTMLName = function(string){
let match = string.match(/(?:attr|act|roll)_(.+)/);
match.shift();
return match[0];
};
kFuncs.parseHTMLName = parseHTMLName;
/**
* Capitalize each word in a string
* @memberof Utilities
* @param {string} string - The string to capitalize
* @returns {string}
* @example
* const capitalized = k.capitalize('a word');
* console.log(capitalized);// => "A Word"
*/
const capitalize = function(string){
return string.replace(/(?:^|\s+|\/)[a-z]/ig,(letter)=>letter.toUpperCase());
};
kFuncs.capitalize = capitalize;
/**
* Extracts a roll query result for use in later functions. Must be awaited as per [startRoll documentation](https://wiki.roll20.net/Sheet_Worker_Scripts#Roll_Parsing.28NEW.29). Stolen from [Oosh\'s Adventures with Startroll thread](https://app.roll20.net/forum/post/10346883/adventures-with-startroll).
* @memberof Utilities
* @param {string} query - The query should be just the text as the `?{` and `}` at the start/end of the query are added by the function.
* @returns {Promise} - Resolves to the selected value from the roll query
* @example
* const rollFunction = async function(){
* //Get the result of a choose from list query
* const queryResult = await extractQueryResult('Prompt Text Here|Option 1|Option 2');
* console.log(queryResult);//=> "Option 1" or "Option 2" depending on what the user selects
*
* //Get free form input from the user
* const freeResult = await extractQueryResult('Prompt Text Here');
* consoel.log(freeResult);// => Whatever the user entered
* }
*/
const extractQueryResult = async function(query){
debug('entering extractQueryResult');
const rollObj = {
query:`[[0[response=?{${query}}]]]`
};
let {roll} = await _startRoll(rollObj,'!');
roll.finish();
return roll.results.query.expression.replace(/^.+?response=|\]$/g,'');
};
kFuncs.extractQueryResult = extractQueryResult;
/**
* Simulates a query for ensuring that async/await works correctly in the sheetworker environment when doing conditional startRolls. E.g. if you have an if/else and only one of the conditions results in `startRoll` being called (and thus an `await`), the sheetworker environment would normally crash. Awaiting this in the condition that does not actually need to call `startRoll` will keep the environment in sync.
* @memberof Utilities
* @param {string|number} [value] - The value to return. Optional.
* @returns {Promise} - Resolves to the value passed to the function
* @example
* const rollFunction = async function(){
* //Get the result of a choose from list query
* const queryResult = await pseudoQuery('a value');
* console.log(queryResult);//=> "a value"
* }
*/
const pseudoQuery = async function(value){
const rollObj = {
query:`[[0[response=${value}]]]`
};
let {roll} = await _startRoll(rollObj,'!');
roll.finish();
return roll.results.query.expression.replace(/^.+?response=|\]$/g,'');
};
kFuncs.pseudoQuery = pseudoQuery;
/**
* An alias for console.log.
* @memberof Utilities
* @param {any} msg - The message can be a straight string, an object, or an array. If it is an object or array, the object will be broken down so that each key is used as a label to output followed by the value of that key. If the value of the key is an object or array, it will be output via `console.table`.
*/
const log = function(msg){
if(typeof msg === 'string'){
console.log(`%c${kFuncs.sheetName} log| ${msg}`,"background-color:#159ccf");
}else if(typeof msg === 'object'){
Object.keys(msg).forEach((m)=>{
if(typeof msg[m] === 'string'){
console.log(`%c${kFuncs.sheetName} log| ${m}: ${msg[m]}`,"background-color:#159ccf");
}else{
console.log(`%c${kFuncs.sheetName} log| ${typeof msg[m]} ${m}`,"background-color:#159ccf");
console.table(msg[m]);
}
});
}
};
kFuncs.log = log;
/**
* Alias for console.log that only triggers when debug mode is enabled or when the sheet\'s version is `0`. Useful for entering test logs that will not pollute the console on the live sheet.
* @memberof Utilities
* @param {any} msg - 'See {@link k.log}
* @param {boolean} force - Pass as a truthy value to force the debug output to be output to the console regardless of debug mode.
* @returns {void}
*/
const debug = function(msg,force){
if(!kFuncs.debugMode && !force && kFuncs.version > 0) return;
if(typeof msg === 'string'){
console.warn(`%c${kFuncs.sheetName} DEBUG| ${msg}`,"background-color:tan;color:red;");
}else if(typeof msg === 'object'){
Object.keys(msg).forEach((m)=>{
if(typeof msg[m] === 'string'){
console.warn(`%c${kFuncs.sheetName} DEBUG| ${m}: ${msg[m]}`,"background-color:tan;color:red;");
}else{
console.warn(`%c${kFuncs.sheetName} DEBUG| ${typeof msg[m]} ${m}`,"background-color:tan;color:red;font-weight:bold;");
console.table(msg[m]);
}
});
}
};
kFuncs.debug = debug;
/**
* Orders the section id arrays for all sections in the `sections` object to match the repOrder attribute.
* @memberof Utilities
* @param {attributesProxy} attributes - The attributes object that must have a value for the reporder for each section.
* @param {object[]} sections - Object containing the IDs for the repeating sections, indexed by repeating section name.
*/
const orderSections = function(attributes,sections,casc){
Object.keys(sections).forEach((section)=>{
attributes.attributes[`_reporder_${section}`] = commaArray(attributes[`_reporder_${section}`]);
sections[section] = orderSection(attributes.attributes[`_reporder_${section}`],sections[section],attributes,section,casc);
});
};
kFuncs.orderSections = orderSections;
/**
* Orders a single ID array.
* @memberof Utilities
* @param {string[]} repOrder - Array of IDs in the order they are in on the sheet.
* @param {string[]} IDs - Array of IDs to be ordered. Aka the default ID Array passed to the getSectionIDs callback
* @param {AttributesProxy} [attributes] - The Kscaffold attributes object
* @param {string} [section] - the name of the section being ordered. If section and attributes are passed, will return an ordered array that does not include IDs for rows that do not exist.
* @param {object} [casc] - the object describing the default state of the sheet.
* @returns {string[]} - The ordered id array
*/
const orderSection = function(repOrder,IDs=[], attributes, section,casc){
const idArr = [...repOrder.filter(v => v),...IDs.filter(id => !repOrder.includes(id.toLowerCase()))]
.filter(id => {
const testAttr = Object.keys(casc).find(a => a.toLowerCase().startsWith(`attr_${section}_${id}`));
const testName = testAttr?.replace(/attr_/,'');
const idName = testName?.replace(/\$x/,id);
return (!section && !casc) ||
(
idName &&
(
attributes.attributes.hasOwnProperty(idName) ||
attributes.updates.hasOwnProperty(idName)
)
);
});
return idArr;
};
kFuncs.orderSection = orderSection;
/**
* Splits a comma delimited string into an array
* @memberof Utilities
* @param {string} string - The string to split.
* @returns {array} - The string segments of the comma delimited list.
*/
const commaArray = function(string=''){
return string.toLowerCase().split(/\s*,\s*/);
};
kFuncs.commaArray = commaArray;
// Roll escape functions for passing data in action button calls. Base64 encodes/decodes the data.
const RE = {
chars: {
'"': '%quot;',
',': '%comma;',
':': '%colon;',
'}': '%rcub;',
'{': '%lcub;',
},
escape(data) {
return typeof data === 'object' ?
`KDATA${btoa(JSON.stringify(data))}` :
`KSTRING${btoa(data)}`;
},
unescape(string) {
const isData = typeof string === 'string' &&
(
string.startsWith('KDATA') ||
string.startsWith('KSTRING')
);
return isData ?
(
string.startsWith('KDATA') ?
JSON.parse(atob(string.replace(/^KDATA/,''))) :
atob(string.replace(/^KSTRING/,''))
) :
string;
}
};
/**
* Encodes data in Base64. This is useful for passing roll information to action buttons called from roll buttons.
* @function
* @param {string|object|any[]} data - The data that you want to Base64 encode
* @returns {string} - The encoded data
* @memberof! Utilities
*/
const escape = RE.escape;
/**
* Decodes Base64 encoded strings that were created by the K-scaffold
* @function
* @param {string|object|any[]} string - The string of encoded data to decode. If this is not a string, or is not a string that was encoded by the K-scaffold, it will be returned as is.
* @returns {string|object|any[]}
* @memberof! Utilities
*/
const unescape = RE.unescape;
Object.assign(kFuncs,{escape,unescape});
/**
* Parses a macro so that it is reduced to the final values of all attributes contained in the macro. Will drill down up to 99 levels deep. If the string was not parseable, string will be returned with as much parsed as possible.
* @memberof Utilities
* @param {string} mutStr - The string macro to parse
* @param {AttributesProxy} attributes - The K-scaffold Attributes Proxy
* @param {Object} sections - The K-scaffold sections object
* @returns {string} - The string with all attributes replaced by their values (if possible).
*/
const parseMacro = (str,attributes,sections) => {
let iter = 0;
let mutStr = str;
while(mutStr.match(/@{.+?}/) && iter < 99){
mutStr = mutStr.replace(/@{(.+?)}/g,(match,name) => {
name = name.replace(/\|/,'_');
return attributes[name] !== null && attributes[name] !== undefined ?
attributes[name] :
`@(${name})`;
})
iter++;
}
mutStr = mutStr.replace(/@\((.+?)\)/g,'@{$1}');
return mutStr;
}
kFuncs.parseMacro = parseMacro;
/**
* Sends data to another character sheet to cause a change on that sheet. WARNING, this function should not be used in response to an attribute change to avoid spamming the chat with api messages.
*
* ![k.send.gif](/k-scaffold/k.send.gif)
* @memberof Utilities
* @param {string} characterName - The character to connect to
* @param {string} funcName - Name of the function to call similar to function name used in {@link callFunc}.
* @param {...any} args - The arguments to pass to the function call no the other sheet. These are passed after the normal destructure object for a K-scaffold function call.
* @example
* //Function that is called by the source sheet
* const dispatchPartner = async function({trigger,attributes,sections,casc}){
* const partnerName = await (
* attributes.partner_name ?
* k.pseudoQuery(attributes.partner_name) :
* k.extractQueryResult('Partner name')
* );
* attributes.partner_name = partnerName;
* //passing the attributes of the source sheet
* k.send(partnerName,'receivePartner',attributes);
* attributes.set();
* };
* k.registerFuncs({dispatchPartner});
*
* //Function called on target sheet. Partner is the attributes from the source sheet
* const receivePartner = function({trigger,attributes,sections,casc},partner){
* attributes.from_partner = partner.for_partner;
* attributes.partner_name = partner.character_name;
* };
* k.registerFuncs({receivePartner });
*/
const send = async function(characterName,funcName,...args){
const data = RE.escape({
funcName,
args
});
const roll = await startRoll(`!@{${characterName}|character_name}%{${characterName}|k-network-call||${data}}&{noerror}`);
finishRoll(roll.rollId);
};
kFuncs.send = send;
const kReceive = function({trigger,attributes,sections,casc}) {
const data = trigger.rollData;
callFunc(data.funcName,{attributes,sections,casc},...data.args);
};
funcs.kReceive = kReceive;/*jshint esversion: 11, laxcomma:true, eqeqeq:true*/
/*jshint -W014,-W084,-W030,-W033*/
//# Attribute Obj Proxy handler
const createAttrProxy = function(attrs,sections,casc){
//creates a proxy for the attributes object so that values can be worked with more easily.
const getCascObj = function(event){
const eventName = event.triggerName || event.sourceAttribute;
let typePrefix = eventName.startsWith('clicked:') ?
'act_' :
event.removedInfo ?
'fieldset_' :
'attr_';
let cascName = `${typePrefix}${eventName.replace(/(?:removed?|clicked):/,'')}`;
let cascObj = casc[cascName];
k.debug({[cascName]:cascObj});
if(event && cascObj){
Object.assign(cascObj,event);
if(event.originalRollId){
cascObj.rollData = RE.unescape(event.originalRollId);
}
}
return cascObj || {};
};
const triggerFunctions = function(obj){
if(obj.triggeredFuncs && obj.triggeredFuncs.length){
debug(`triggering functions for ${obj.name}`);
obj.triggeredFuncs && obj.triggeredFuncs.forEach(func=>funcs[func] ?
funcs[func]({trigger:obj,attributes,sections,casc}) :
debug(`!!!Warning!!! no function named ${func} found. Triggered function not called for ${obj.name}`,true));
}
};
const initialFunction = function(obj){
if(obj.initialFunc){
debug(`initial functions for ${obj.name}`);
funcs[obj.initialFunc] ?
funcs[obj.initialFunc]({trigger:obj,attributes,sections}) :
debug(`!!!Warning!!! no function named ${obj.initialFunc} found. Initial function not called for ${obj.name}`,true);
}
};
const alwaysFunctions = function(trigger){
Object.values(allHandlers).forEach((handler)=>{
handler({trigger,attributes,sections,casc});
});
};
const processChange = function({event,trigger}){
if(event && !trigger){
debug(`${event.sourceAttribute} change detected. No trigger found`);
return;
}
if(!attributes || !sections || !casc){
debug(`!!! Insufficient arguments || attributes > ${!!attributes} | sections > ${!!sections} | casc > ${!!casc} !!!`);
return;
}
debug({trigger});
if(event){
debug('checking for initial & always functions');
if(Array.isArray(trigger.affects)){
attributes.queue.push(...trigger.affects);
}
alwaysFunctions(trigger,attributes,sections,casc);//Functions that should be run for all events.
initialFunction(trigger,attributes,sections,casc);//functions that should only be run if the attribute was the thing changed by the user
}
if(trigger){
debug(`processing ${trigger.name}`);
triggerFunctions(trigger,attributes,sections,casc);
if(!event){
// Handle autocalc formula
if(trigger.formula){
attributes[trigger.name] = parseKFormula({trigger,attributes,sections,casc});
}
// handle calculation of element
if(
trigger.calculation &&
funcs[trigger.calculation]
){
attributes[trigger.name] = funcs[trigger.calculation]({trigger,attributes,sections,casc});
}else if(trigger.calculation && !funcs[trigger.calculation]){
debug(`K-Scaffold Error: No function named ${trigger.calculation} found`);
}
}
}
attributes.set();
};
const attrTarget = {
updates:{},
attributes:{...attrs},
repOrders:{},
queue: [],
casc:{},
alwaysFunctions,
processChange,
triggerFunctions,
initialFunction,
getCascObj
};
const attrHandler = {
get:function(obj,prop){//gets the most value of the attribute.
//If it is a repeating order, returns the array, otherwise returns the update value or the original value
if(prop === 'toJSON'){
return () => ({...obj.attributes,...obj.updates});
} else if(prop === 'set'){
return function(){
let {callback,vocal} = arguments[0] ? arguments[0] : {};
if(sections && casc && attributes.queue.length){
const triggerName = attributes.queue.shift();
const trigger = getCascObj({sourceAttribute:triggerName});
processChange({trigger,attributes,sections,casc});
}else{
debug({updates:obj.updates});
const trueCallback = Object.keys(obj.repOrders).length ?
function(){
Object.entries(obj.repOrders).forEach(([section,order])=>{
_setSectionOrder(section,order)
});
callback && callback();
}:
callback;
Object.keys(obj.updates).forEach((key)=>obj.attributes[key] = obj.updates[key]);
const update = obj.updates;
obj.updates = {};
set(update,vocal,trueCallback);
}
}
}else if(Object.keys(obj).some(key=>key===prop)){
return Reflect.get(...arguments)
}else{
let retValue;
switch(true){
case obj.repOrders.hasOwnProperty(prop):
retValue = obj.repOrders[prop];
break;
case obj.updates.hasOwnProperty(prop):
retValue = obj.updates[prop];
break;
default:
retValue = obj.attributes[prop];
break;
}
let cascRef = `attr_${prop.replace(/(repeating_[^_]+_)[^_]+/,'$1\$X')}`.toLowerCase();
let numRetVal = +retValue;
if(!Number.isNaN(numRetVal) && retValue !== ''){
retValue = numRetVal;
}else if(cascades[cascRef] && (typeof cascades[cascRef].defaultValue === 'number' || cascades[cascRef].type === 'number')){
retValue = cascades[cascRef].defaultValue;
}
return retValue;
}
},
set:function(obj,prop,value){
//Sets the value. Also verifies that the value is a valid attribute value
//e.g. not undefined, null, or NaN
if(value || value===0 || value===''){
if(/reporder|^repeating_[^_]+$/.test(prop)){
let section = prop.replace(/_reporder_/,'');
obj.repOrders[section] = value;
}else if(`${obj.attributes}` !== `${value}` ||
(obj.updates[prop] && `${obj.updates}` !== `${value}`)
){
if(sections && casc){
const trigger = getCascObj({sourceAttribute:prop});
if(Array.isArray(trigger.affects)){
attributes.queue.push(...trigger.affects);
}
}
obj.updates[prop] = value;
}
}else{
debug(`!!!Warning: Attempted to set ${prop} to an invalid value:${value}; value not stored!!!`);
}
return true;
},
deleteProperty(obj,prop){
//removes the property from the original attributes, updates, and the reporders
Object.keys(obj).forEach((key)=>{
delete obj[key][prop.toLowerCase()];
});
}
};
const attributes = new Proxy(attrTarget,attrHandler);
return attributes;
};
/**
* Function that registers a function for being called via the funcs object. Returns true if the function was successfully registered, and false if it could not be registered for any reason.
* @memberof Utilities
* @param {object} funcObj - Object with keys that are names to register functions under and values that are functions.
* @param {object} optionsObj - Object that contains options to use for this registration.
* @param {string[]} optionsObj.type - Array that contains the types of specialized functions that apply to the functions being registered. Valid types are `"opener"`, `"updater"`, and `"default"`. `"default"` is always used, and never needs to be passed.
* @returns {boolean} - True if the registration succeeded, false if it failed.
* @example
* //Basic Registration
* const myFunc = function({trigger,attributes,sections,casc}){};
* k.registerFuncs({myFunc});
*
* //Register a function to run on sheet open
* const openFunc = function({trigger,attributes,sections,casc}){};
* k.registerFuncs({openFunc},{type:['opener']})
*
* //Register a function to run on all events
* const allFunc = function({trigger,attributes,sections,casc}){};
* k.registerFuncs({allFunc},{type:['all']})
*/
const registerFuncs = function(funcObj,optionsObj = {}){
if(typeof funcObj !== 'object' || typeof optionsObj !== 'object'){
debug(`!!!! K-scaffold error: Improper arguments to register functions !!!!`);
return false;
}
const typeArr = optionsObj.type ? ['default',...optionsObj.type] : ['default'];
const typeSwitch = {
'opener':openHandlers,
'updater':updateHandlers,
'new':initialSetups,
'all':allHandlers,
'default':funcs
};
let setState;
Object.entries(funcObj).map(([prop,value])=>{
typeArr.forEach((type)=>{
if(typeSwitch[type][prop]){
debug(`!!! Duplicate function name for ${prop} as ${type}!!!`);
setState = false;
}else if(typeof value === 'function'){
typeSwitch[type][prop] = value;
setState = setState !== false ? true : false;
}else{
debug(`!!! K-scaffold error: Function registration requires a function. Invalid value to register as ${type} !!!`);
setState = false;
}
});
});
return setState;
};
kFuncs.registerFuncs = registerFuncs;
/**
* Function that sets up the action calls used in the roller mixin.
* @memberof Sheetworkers
* @param {object} attributes - The attribute values of the character
* @param {object[]} sections - All the repeating section IDs
*/
const setActionCalls = function({attributes,sections}){
actionAttributes.forEach((base)=>{
let [section,,field] = k.parseTriggerName(base);
let fieldAction = field.replace(/_/g,'-');
if(section){
sections[section].forEach((id)=>{
attributes[`${section}_${id}_${field}`] = `%{${attributes.character_name}|${section}_${id}_${fieldAction}}`;
});
}else{
attributes[`${field}`] = `%{${attributes.character_name}|${fieldAction}}`;
}
});
};
funcs.setActionCalls = setActionCalls;
kFuncs.setActionCalls = setActionCalls;
/**
* Function that reduces Roll20 macro syntax formulas down to their calculated value.
* @memberof Sheetworkers
* @param {object} attributes - The attribute values of the character
* @param {object[]} sections - All the repeating section IDs
*/
const parseKFormula = ({trigger,attributes,sections,casc}) => {
const [baseSection,rowID,attrName] = parseTriggerName(trigger.name);
const repeatBlockRx = baseSection ?
/(@{repeating_.+?_\$X_.+?})/g :
/={([^)]*repeating_[^_]+[^)]*)}=/g;
let mutFormula = trigger.formula;
mutFormula = mutFormula.replace(repeatBlockRx,(match,repeatMacro) => {
const [section] = repeatMacro.match(/repeating_[^_]+/);
const idArray = baseSection ?
[rowID] :
sections[section];
return idArray.map(id => {
return `(${repeatMacro.replace(/repeating_[^_]+?_[^_]+?_([^}]+)/g,`${section}_${id}_$1`)})`;
}).join(
trigger.type === 'number' ?
' + ' :
''
);
});
mutFormula = parseMacro(mutFormula,attributes)
.replace(/@{.+?}/g,'0');
const mathKeys = ['floor','ceil','round','abs'];
mathKeys.forEach(func => mutFormula = mutFormula.replace(new RegExp(`${func}\\(`,'g'),`Math.${func}(`));
const mathRx = new RegExp(`Math\\.(?:${mathKeys.join('|')})`,'g');
let noAlphaStr = mutFormula
.replace(mathRx,'');
return trigger.type !== 'text' ?
(
!noAlphaStr.match(/[a-z]/i) ?
eval(mutFormula) :
undefined
) :
mutFormula;
};
funcs.parseKFormula = parseKFormula;
kFuncs.parseKFormula = parseKFormula;
/**
* Function to call a function previously registered to the funcs object. May not be used that much in actual sheets, but very useful when writing unit tests for your sheet. Either returns the function or null if no function exists.
* @memberof Sheetworkers
* @param {string} funcName - The name of the function to invoke.
* @param {...any} args - The arguments to call the function with.
* @returns {function|null}
* @example
* //Call myFunc with two arguments
* k.callFunc('myFunc','an argument','another argument');
*/
const callFunc = function(funcName,...args){
if(funcs[funcName]){
debug(`calling ${funcName}`);
return funcs[funcName](...args);
}else{
debug(`Invalid function name: ${funcName}`);
return null;
}
};
kFuncs.callFunc = callFunc;/**@namespace Sheetworkers */
/*jshint esversion: 11, laxcomma:true, eqeqeq:true*/
/*jshint -W014,-W084,-W030,-W033*/
//Sheet Updaters and styling functions
/**
* Function that calls the K-scaffold's update and sheet initialization routines.
*/
const updateSheet = function(){
log('updating sheet');
getAllAttrs({props:['debug_mode',...baseGet],callback:(attributes,sections,casc)=>{
kFuncs.debugMode = kFuncs.debugMode || !!attributes.debug_mode;
debug({sheet_version:attributes.sheet_version});
if(!attributes.sheet_version){
Object.entries(initialSetups).forEach(([funcName,handler])=>{
if(typeof funcs[funcName] === 'function'){
debug(`running ${funcName}`);
funcs[funcName]({attributes,sections,casc});
}else{
debug(`!!!Warning!!! no function named ${funcName} found. Initial sheet setup not performed.`);
}
});
}else{
Object.entries(updateHandlers).forEach(([ver,handler])=>{
if(attributes.sheet_version < +ver){
handler({attributes,sections,casc});
}
});
}
k.debug({openHandlers});
Object.entries(openHandlers).forEach(([funcName,func])=>{
if(typeof funcs[funcName] === 'function'){
debug(`running ${funcName}`);
funcs[funcName]({attributes,sections,casc});
}else{
debug(`!!!Warning!!! no function named ${funcName} found. Sheet open handling not performed.`);
}
});
setActionCalls({attributes,sections});
attributes.sheet_version = kFuncs.version;
log(`Sheet Update applied. Current Sheet Version ${kFuncs.version}`);
attributes.set();
log('Sheet ready for use');
}});
};
kFuncs.updateSheet = updateSheet;
const initialSetup = function(attributes,sections){
debug('Initial sheet setup');
};
/**
* This is the default listener function for attributes that the K-Scaffold uses. It utilizes the `triggerFuncs`, `listenerFunc`, `calculation`, and `affects` properties of the K-scaffold trigger object (see the Pug section of the scaffold for more details).
* @memberof Sheetworkers
* @param {Roll20Event} event - The Roll20 event object
* @returns {void}
* @example
* //Call from an attribute change
* on('change:an_attribute',k.accessSheet);
*/
const accessSheet = function(event){
debug({funcs:Object.keys(funcs)});
debug({event});
getAllAttrs({callback:(attributes,sections,casc)=>{
let trigger = attributes.getCascObj(event,casc);
attributes.processChange({event,trigger,attributes,sections,casc});
}});
};
funcs.accessSheet = accessSheet;/*jshint esversion: 11, laxcomma:true, eqeqeq:true*/
/*jshint -W014,-W084,-W030,-W033*/
/*
Cascade Expansion functions
*/
//Expands the repeating section templates in cascades to reflect the rows actually available
const expandCascade = function(cascade,sections){
return _.keys(cascade).reduce((memo,key)=>{//iterate through cascades and replace references to repeating attributes with correct row ids.
if(/^(?:act|attr)_repeating_/.test(key)){//If the attribute is a repeating attribute, do special logic
expandRepeating(memo,key,cascade,sections);
}else if(key){//for non repeating attributes do this logic
expandNormal(memo,key,cascade,sections);
}
return memo;
},{});
};
kFuncs.expandCascade = (sections) => expandCascade(cascades,sections);
const expandRepeating = function(memo,key,cascade,sections){
key.replace(/((?:attr|act)_)(repeating_[^_]+)_[^_]+?_(.+)/,(match,type,section,field)=>{
(sections[section]||[]).forEach((id)=>{
memo[`${type}${section}_${id}_${field}`]=_.clone(cascade[key]);//clone the details so that each row's attributes have correct ids
memo[`${type}${section}_${id}_${field}`].name = `${section}_${id}_${field}`;
if(key.startsWith('attr_')){
memo[`${type}${section}_${id}_${field}`].affects = memo[`${type}${section}_${id}_${field}`].affects.reduce((m,affected)=>{
if(affected.startsWith(section)){//otherwise if the affected attribute is in the same section, simply set the affected attribute to have the same row id.
m.push(applyID(affected,id));
}else if(/repeating/.test(affected)){//If the affected attribute isn't in the same repeating section but is still a repeating attribute, add all the rows of that section
addAllRows(affected,m,sections);
}else{//otherwise the affected attribute is a non repeating attribute. Simply add it to the computed affected array
m.push(affected);
}
return m;
},[]);
}
});
});
};
const applyID = function(affected,id){
return affected.replace(/(repeating_[^_]+_)[^_]+(.+)/,`$1${id}$2`);
};
const expandNormal = function(memo,key,cascade,sections){
memo[key] = _.clone(cascade[key]);
if(key.startsWith('attr_')){
memo[key].affects = memo[key].affects || [];
memo[key].affects = memo[key].affects.reduce((m,a)=>{
if(/^repeating/.test(a)){
addAllRows(a,m,sections);
}else{
m.push(a);
}
return m;
},[]);
}
};
const addAllRows = function(affected,memo,sections){
affected.replace(/(repeating_[^_]+?)_[^_]+?_(.+)/,(match,section,field)=>{
sections[section].forEach(id=>memo.push(`${section}_${id}_${field}`));
});
};/*jshint esversion: 11, laxcomma:true, eqeqeq:true*/
/*jshint -W014,-W084,-W030,-W033*/
/**
* These are functions that provide K-scaffold aliases for the basic Roll20 sheetworker functions. These functions also provide many additional features on top of the standard Roll20 sheetworkers.
* @namespace Sheetworkers.Sheetworker Aliases
*/
/**
* Alias for [setSectionOrder()](https://wiki.roll20.net/Sheet_Worker_Scripts#setSectionOrder.28.3CRepeating_Section_Name.3E.2C_.3CSection_Array.3E.2C_.3CCallback.3E.29) that allows you to use the section name in either `repeating_section` or `section` formats. Note that the Roll20 sheetworker [setSectionOrder](https://wiki.roll20.net/Sheet_Worker_Scripts#setSectionOrder.28.3CRepeating_Section_Name.3E.2C_.3CSection_Array.3E.2C_.3CCallback.3E.29) currently causes some display issues on sheets.
* @memberof Sheetworker Aliases
* @name setSectionOrder
* @param {string} section - The name of the section, with or without `repeating_`
* @param {string[]} order - Array of ids describing the desired order of the section.
* @returns {void}
* @example
* //Set the order of a repeating_weapon section
* k.setSectionOrder('repeating_equipment',['id1','id2','id3']);
* //Can also specify the section name without the repeating_ prefix
* k.setSectionOrder('equipment',['id1','id2','id3']);
*/
const _setSectionOrder = function(section,order){
let trueSection = section.replace(/repeating_/,'');
setSectionOrder(trueSection,order);
};
kFuncs.setSectionOrder = _setSectionOrder;
/**
* Alias for [removeRepeatingRow](https://wiki.roll20.net/Sheet_Worker_Scripts#removeRepeatingRow.28_RowID_.29) that also removes the row from the current object of attribute values and array of section IDs to ensure that erroneous updates are not issued.
* @memberof Sheetworker Aliases
* @name removeRepeatingRow
* @param {string} row - The row id to be removed
* @param {attributesProxy} attributes - The attribute values currently in memory
* @param {object} sections - Object that contains arrays of all the IDs in sections on the sheet indexed by repeating name.
* @returns {void}
* @example
* //Remove a repeating Row
* k.getAllAttrs({
* callback:(attributes,sections)=>{
* const rowID = sections.repeating_equipment[0];
* k.removeRepeatingRow(`repeating_equipment_${rowID}`,attributes,sections);
* console.log(sections.repeating_equipment); // => rowID no longer exists in the array.
* console.log(attributes[`repeating_equipment_${rowID}_name`]); // => undefined
* }
* })
*/
const _removeRepeatingRow = function(row,attributes,sections){
debug(`removing ${row}`);
Object.keys(attributes.attributes).forEach((key)=>{
if(key.startsWith(row)){
delete attributes[key];
}
});
let [,section,rowID] = row.match(/(repeating_[^_]+)_(.+)/,'');
sections[section] = sections[section].filter((id)=>id!==rowID);
removeRepeatingRow(row);
};
kFuncs.removeRepeatingRow = _removeRepeatingRow;
/**
* Alias for [getAttrs()](https://wiki.roll20.net/Sheet_Worker_Scripts#getAttrs.28attributeNameArray.2C_callback.29) that converts the default object of attribute values into an {@link attributesProxy} and passes that back to the callback function.
* @memberof Sheetworker Aliases
* @name getAttrs
* @param {string[]} [props=baseGet] - Array of attribute names to get the value of. Defaults to {@link baseGet} if not passed.
* @param {function(attributesProxy)} callback - The function to call after the attribute values have been gotten. An {@link attributesProxy} is passed to the callback.
* @example
* //Gets the attributes named in props.
* k.getAttrs({
* props:['attribute_1','attribute_2'],
* callback:(attributes)=>{
* //Work with the attributes as you would in a normal getAttrs, or use the superpowers of the K-scaffold attributes object like so:
* attributes.attribute_1 = 'new value';
* attributes.set();
* }
* })
*/
const _getAttrs = function({props=baseGet,callback}){
getAttrs(props,(values)=>{
const attributes = createAttrProxy(values);
callback(attributes);
});
};
kFuncs.getAttrs = _getAttrs;
/**
* Alias for [getAttrs()](https://wiki.roll20.net/Sheet_Worker_Scripts#getAttrs.28attributeNameArray.2C_callback.29) and [getSectionIDs](https://wiki.roll20.net/Sheet_Worker_Scripts#getSectionIDs.28section_name.2Ccallback.29) that combines the actions of both sheetworker functions and converts the default object of attribute values into an {@link attributesProxy}. Also gets the details on how to handle all attributes from the master {@link cascades} object and.
* @memberof Sheetworker Aliases
* @param {Object} args
* @param {string[]} [args.props=baseGet] - Array of attribute names to get the value of. Defaults to {@link baseGet} if not passed.
* @param {repeatingSectionDetails} sectionDetails - Array of details about a section to get the IDs for and attributes that need to be gotten.
* @param {function(attributesProxy,sectionObj,expandedCascade):void} args.callback - The function to call after the attribute values have been gotten. An {@link attributesProxy} is passed to the callback along with a {@link sectionObj} and {@link expandedCascade}.
* @example
* //Get every K-scaffold linked attribute on the sheet
* k.getAllAttrs({
* callback:(attributes,sections,casc)=>{
* //Work with the attributes as you please.
* attributes.some_attribute = 'a value';
* attributes.set();//Apply our change
* }
* })
*/
const getAllAttrs = function({props=baseGet,sectionDetails=repeatingSectionDetails,callback}){
getSections(sectionDetails,(repeats,sections)=>{
getAttrs([...props,...repeats],(values)=>{
const casc = expandCascade(cascades,sections);
const attributes = createAttrProxy(values,sections,casc);
orderSections(attributes,sections,casc);
callback(attributes,sections,casc);
})
});
};
kFuncs.getAllAttrs = getAllAttrs;
/**
* Alias for [getSectionIDs()](https://wiki.roll20.net/Sheet_Worker_Scripts#getSectionIDs.28section_name.2Ccallback.29) that allows you to iterate through several functions at once. Also assembles an array of repeating attributes to get.
* @memberof Sheetworker Aliases
* @param {object[]} sectionDetails - Array of details about a section to get the IDs for and attributes that need to be gotten.
* @param {string} sectionDetails.section - The full name of the repeating section including the `repeating_` prefix.
* @param {string[]} sectionDetails.fields - Array of field names that need to be gotten from the repeating section
* @param {function(string[],sectionObj)} callback - The function to call once all IDs have been gotten and the array of repating attributes to get has been assembled. The callback is passed the array of repating attributes to get and a {@link sectionObj}.
* @example
* // Get some section details
* const sectionDetails = {
* {section:'repeating_equipment',fields:['name','weight','cost']},
* {section:'repeating_weapon',fields:['name','attack','damage']}
* };
* k.getSections(sectionDetails,(attributeNames,sections)=>{
* console.log(attributeNames);// => Array containing all row specific attribute names
* console.log(sections);// => Object with arrays containing the row ids. Indexed by section name (e.g. repeating_eqiupment)
* })
*/
const getSections = function(sectionDetails,callback){
let queueClone = _.clone(sectionDetails);
const worker = (queue,repeatAttrs=[],sections={})=>{
let detail = queue.shift();
getSectionIDs(detail.section,(IDs)=>{
sections[detail.section] = IDs;
IDs.forEach((id)=>{
detail.fields.forEach((f)=>{
repeatAttrs.push(`${detail.section}_${id}_${f}`);
});
});
repeatAttrs.push(`_reporder_${detail.section}`);
if(queue.length){
worker(queue,repeatAttrs,sections);
}else{
callback(repeatAttrs,sections);
}
});
};
if(!queueClone[0]){
callback([],{});
}else{
worker(queueClone);
}
};
kFuncs.getSections = getSections;
// Sets the attributes while always calling with {silent:true}
// Can be awaited to get the values returned from _setAttrs
/**
* Alias for [setAttrs()](https://wiki.roll20.net/Sheet_Worker_Scripts#setAttrs.28values.2Coptions.2Ccallback.29) that sets silently by default.
* @memberof Sheetworker Aliases
* @alias setAttrs
* @param {object} obj - The object containting attributes to set
* @param {boolean} [vocal=false] - Whether to set silently (default value) or not.
* @param {function()} [callback] - The callback function to invoke after the setting has been completed. No arguments are passed to the callback function.
* @example
* //Set some attributes silently
* k.setAttrs({attribute_1:'new value'})
* //Set some attributes and triggers listeners
* k.setAttrs({attribute_1:'new value',true})
* //Set some attributes and call a callback function
* k.setAttrs({attribute_1:'new value'},null,()=>{
* //Do something after the attribute is set
* })
*/
const set = function(obj,vocal=false,callback){
setAttrs(obj,{silent:!vocal},callback);
};
kFuncs.setAttrs = set;
const generateCustomID = function(string){
if(!string.startsWith('-')){
string = `-${string}`;
}
rowID = generateRowID();
let re = new RegExp(`^.{${string.length}}`);
return `${string}${rowID.replace(re,'')}`;
};
/**
* Alias for generateRowID that adds the new id to the {@link sectionObj}. Also allows for creation of custom IDs that conform to the section ID requirements.
* @memberof Sheetworker Aliases
* @name generateRowID
* @param {sectionObj} sections
* @param {string} [customText] - Custom text to start the ID with. This text should not be longer than the standard repeating section ID format.
* @returns {string} - The created ID
* @example
* k.getAllAttrs({
* callback:(attributes,sections,casc)=>{
* //Create a new row ID
* const rowID = k.generateRowID('repeating_equipment',sections);
* console.log(rowID);// => repeating_equipment_-p8rg908ug0suzz
* //Create a custom row ID
* const customID = k.generateRowID('repeating_equipment',sections,'custom');
* console.log(customID);// => repeating_equipment_-custom98uadj89kj
* }
* });
*/
const _generateRowID = function(section,sections,customText){
let rowID = customText ?
generateCustomID(customText) :
generateRowID();
section = section.match(/^repeating_[^_]+$/) ?
section :
`repeating_${section}`;
sections[section] = sections[section] || [];
sections[section].push(rowID);
return `${section}_${rowID}`;
};
kFuncs.generateRowID = _generateRowID;
/**
* An alias for [Roll20's getTranslationByKey](https://wiki.roll20.net/Sheet_Worker_Scripts#getTranslationByKey.28.5Bkey.5D.29) that also supports data-i18n-vars syntax replacement and returns the translation key if no value is found instead of `false`.
* @memberof Sheetworker Aliases
* @name getTranslationByKey
* @param {string} key - The translation key to look up.
* @param {string[]} [variables = []] - An array of variable values to replace variable indexes with.
* @returns {string}
*/
const _getTranslationByKey = (key,variables = []) => {
let translate = getTranslationByKey(key) || key;
console.warn('getTranslationByKey',getTranslationByKey(key));
console.warn('translate:',translate);
variables.forEach((v,i) => {
translate = translate.replace(new RegExp(`\\{\\{${i}\\}\\}`,'g'),v);
});
return translate;
}
kFuncs.getTranslationByKey = _getTranslationByKey;
/**
* Assembles the roll string from the roll object
* @param {object} rollObj - object describing the roll
* @param {string} [rollStart = '@{template_start}'] - The string to start the roll with.
* @returns {string}
*/
const assembleRoll = (rollObj,rollStart = kFuncs.defaultRollStart) => {
return Object.entries(rollObj).reduce((str,[field,content])=>{
return str += content ?
` {{${field}=${content}}}` :
'';
},`${rollStart}`);
};
/**
* @typedef {Object} kRoll
* @property {Object} roll - The roll object returned by [Roll20's startRoll](https://wiki.roll20.net/Custom_Roll_Parsing#Sheetworker_Functions).
* @property {Function} roll.finish - Finishes the associated roll passing it the computeObj and rollId.
* @property {Object} computeObj - object for storing manipulations to the roll. Assign manipulations to this, DO NOT reassign it to a new object.
*/
/**
*
* @param {object} rollObj - Object specifying the fields to pass to the rolltemplate. Object keys are field names. Object values are the field values.
* @param {string} [startString = '@{template_start}'] - Text that should be prepended to the roll string that results from rollObj.
* @returns {kRoll}
*/
const _startRoll = async (rollObj,startString) => {
const rollString = assembleRoll(rollObj,startString);
const roll = await startRoll(rollString);
const computeObj = {};
roll.finish = () => {
finishRoll(roll.rollId,computeObj);
};
return {roll, computeObj};
};
kFuncs.startRoll = _startRoll;/*jshint esversion: 11, laxcomma:true, eqeqeq:true*/
/*jshint -W014,-W084,-W030,-W033*/
const listeners = {};
/**
* The array of attribute names that the k-scaffold gets by default. Does not incude repeating attributes.
* @memberof Variables
* @var
* @type {array}
*/
const baseGet = Object.entries(cascades).reduce((memo,[attrName,detailObj])=>{
if(!/repeating/.test(attrName) && detailObj.type !== 'action'){
memo.push(detailObj.name);
}
if(detailObj.listener){
listeners[detailObj.listener] = detailObj.listenerFunc;
}
return memo;
},[]);
kFuncs.baseGet = baseGet;
const registerEventHandlers = function(){
on('sheet:opened',updateSheet);
debug({funcKeys:Object.keys(funcs),funcs});
//Roll20 change and click listeners
Object.entries(listeners).forEach(([event,funcName])=>{
if(funcs[funcName]){
on(event,funcs[funcName]);
}else{
debug(`!!!Warning!!! no function named ${funcName} found. No listener created for ${event}`,true);
}
});
log(`kScaffold Loaded`);
};
setTimeout(registerEventHandlers,0);//Delay the execution of event registration to ensure all event properties are present.
/**
* Function to add a repeating section when the add button of a customControlFieldset or inlineFieldset is clicked.
* @memberof Sheetworkers
* @param {object} event - The R20 event object
*/
const addItem = function(event){
let [,,section] = parseClickTrigger(event.triggerName);
section = section.replace(/add-/,'');
getAllAttrs({
callback:(attributes,sections,casc) => {
let row = _generateRowID(section,sections);
debug({row});
attributes[`${row}_name`] = '';
setActionCalls({attributes,sections});
const trigger = cascades[`fieldset_repeating_${section}`];
if(trigger){
if(trigger.addFuncs){
trigger.addFuncs.forEach((funcName) => {
if(funcs[funcName]){
funcs[funcName]({attributes,sections,casc,trigger,newRow:row});
}
});
}
if(Array.isArray(trigger.affects)){
attributes.queue.push(...trigger.affects);
}
}
attributes.set({attributes,sections,casc});
}
});
};
funcs.addItem = addItem;/**
* The default tab navigation function of the K-scaffold. Courtesy of Riernar. It will add `k-active-tab` to the active tab-container and `k-active-button` to the active button. You can either write your own CSS to control display of these, or use the default CSS included in `scaffold/_k.scss`. Note that `k-active-button` has no default CSS as it is assumed that you will want to style the active button to match your system.
* @memberof Sheetworkers
* @param {Object} trigger - The trigger object
* @param {object} attributes - The attribute values of the character
*/
const kSwitchTab = function ({ trigger, attributes }) {
const [container, tab] = (
trigger.name.match(/nav-tabs-(.+)--(.+)/) ||
[]
).slice(1);
$20(`[data-container-tab="${container}"]`).removeClass('k-active-tab');
$20(`[data-container-tab="${container}"][data-tab="${tab}"]`).addClass('k-active-tab');
$20(`[data-container-button="${container}"]`).removeClass('k-active-button');
$20(`[data-container-button="${container}"][data-button="${tab}"]`).addClass('k-active-button');
const tabInputName = `${container.replace(/\-/g,'_')}_tab`;
if(persistentTabs.indexOf(tabInputName) > -1){
attributes[tabInputName] = trigger.name;
}
}
registerFuncs({ kSwitchTab });
/**
* Sets persistent tabs to their last active state
* @memberof Sheetworkers
* @param {object} attributes - The attribute values of the character
*/
const kTabOnOpen = function({trigger,attributes,sections,casc}){
if(typeof persistentTabs === 'undefined') return;
persistentTabs.forEach((tabInput) => {
const pseudoTrigger = {name:attributes[tabInput]};
kSwitchTab({trigger:pseudoTrigger, attributes});
});
};
registerFuncs({ kTabOnOpen },{type:['opener']});
return kFuncs;
}());
const actionAttributes = ["repeating_traits-organization_$X_trait_action","repeating_traits-background_$X_trait_action","repeating_traits-niche_$X_trait_action","repeating_traits-core_$X_trait_action","repeating_traits-quirks_$X_trait_action","repeating_traits-consequences_$X_trait_action","repeating_traits-other_$X_trait_action"];const traits = {"values":[{"name":"name","type":"text","class":"trait-name","label":"trait-name","placeholder":"trait-name"},{"name":"severity","type":"select","label":"trait-severity-label","default":"inconsequential","options":[{"value":"inconsequential","text":"trait-severity-inconsequential"},{"value":"minor","text":"trait-severity-minor"},{"value":"major","text":"trait-severity-major"},{"value":"exceptional","text":"trait-severity-exceptional"}]},{"name":"description","type":"textarea","label":"character-description","placeholder":"character-description"}]};const trait_types = {"organization":"trait-type-organization","background":"trait-type-background","niche":"trait-type-niche","core":"trait-type-core","quirks":"trait-type-quirks","consequences":"trait-type-consequences","other":"trait-type-other"};k.version = 0;
k.defaultRollStart = '';
const upLuck = (eventInfo) => {
getAttrs(["luck", "luck_max"], function (values) {
let luck = parseInt(values.luck) || 0;
let luckMax = parseInt(values.luck_max) || 0;
if (luck < luckMax) {
setAttrs({
luck: luck + 1,
});
}
});
};
const downLuck = (eventInfo) => {
getAttrs(["luck"], function (values) {
let luck = parseInt(values.luck) || 0;
if (luck > 0) {
setAttrs({
luck: luck - 1,
});
}
});
};
const upLuckMax = (eventInfo) => {
getAttrs(["luck_max"], function (values) {
let luck = parseInt(values.luck_max) || 0;
setAttrs({
luck_max: luck + 1,
});
});
};
const downLuckMax = (eventInfo) => {
getAttrs(["luck_max"], function (values) {
let luck = parseInt(values.luck_max) || 0;
if (luck > 0) {
setAttrs({
luck_max: luck - 1,
});
}
});
};
const adjustLuck = (eventInfo) => {
getAttrs(["luck", "luck_max"], (values) => {
const luck = parseInt(values.luck) || 0;
const luckMax = parseInt(values.luck_max) || 0;
if (luck > luckMax) {
setAttrs({ luck: luckMax });
}
});
};
k.registerFuncs({ adjustLuck });
k.registerFuncs({ downLuck });
k.registerFuncs({ upLuck });
k.registerFuncs({ downLuckMax });
k.registerFuncs({ upLuckMax });
const rollTrait = async ({ trigger, attributes }) => {
const [section, id] = k.parseTriggerName(trigger.name);
const prefix = `${section}_${id}`;
console.log(prefix);
const name = attributes[`${prefix}_name`];
const templateStart = attributes['template_start'] || '';
const rerollLink = `[Roll Narrativium](~roll-narrativium)`;
const playerRoll = 'playerRoll'
const die = await k.extractQueryResult('Roll which die?|d4|d6|d8|d10|d12');
const roll = await startRoll(
`${templateStart} {{title=${name}}} {{die=${die}}} {{roll=[[1${die}]]}} {{rerollLink=${rerollLink}}} {{playerRoll=${playerRoll}}}`
);
finishRoll(roll.rollId);
};
k.registerFuncs({rollTrait});const rollNarrativium = async ({ attributes, trigger }) => {
const templateStart = attributes['template_start'] || '';
const gmRoll = 'gmRoll';
const roll = await startRoll(`${templateStart} {{gmRoll=${gmRoll}}} {{roll=[[1d8]]}}`);
finishRoll(roll.rollId);
}
k.registerFuncs({ rollNarrativium });
</script>