Compare commits

..

62 Commits

Author SHA1 Message Date
Thaum Rystra
e0fc5abe7b Improved invite landing page UI 2020-05-19 00:28:31 +02:00
Thaum Rystra
18c9474570 Separated attacks and actions into two separate cards 2020-05-19 00:19:23 +02:00
Thaum Rystra
4a039e769b Added viewers, tree node viewers and fixed forms for new damage schema 2020-05-19 00:15:05 +02:00
Thaum Rystra
93ab67a91b Fixed failure to recompute creature on tree reorganize 2020-05-18 23:53:34 +02:00
Thaum Rystra
4352ca5f0d Inventory items can now be equipped 2020-05-18 23:03:34 +02:00
Thaum Rystra
fe11c9ec23 Tree nodes are no longer lazy - smoother animations when expanding nodes 2020-05-18 20:22:48 +02:00
Thaum Rystra
37d6b32ea3 Action 'uses' now shows up as the computed value 2020-05-18 20:22:00 +02:00
Thaum Rystra
7592332637 Fixed setDocToLastOrder not working with new ordering design 2020-05-18 20:09:21 +02:00
Thaum Rystra
397ff82c43 Organizing the tree now causes a character recomputation where relevant 2020-05-18 19:58:28 +02:00
Thaum Rystra
7e3815a699 Fixed glitchy reordering of trees 2020-05-18 02:03:31 +02:00
Thaum Rystra
9214529284 rewrote entire ordering structure for ancestor trees 2020-05-18 02:03:14 +02:00
Thaum Rystra
60f5588e7d Prevented description viewers from keeping zombie text after description is deleted 2020-05-17 18:13:06 +02:00
Thaum Rystra
ad3bec3521 Began working on bringing forms and UI in line with data structure overhaul 2020-05-17 00:06:19 +02:00
Thaum Rystra
ca5ded7ded Class levels now recompute properly 2020-05-16 22:51:17 +02:00
Thaum Rystra
5c0a2a4d6c Overhauled computations to allow for toggles :'( that sucked 2020-05-16 22:03:21 +02:00
Thaum Rystra
7024adecaf created a general way to fetch the active properties of an ancestor 2020-05-16 17:08:57 +02:00
Thaum Rystra
9b6f259358 Library node edit form no longer uses stored variants 2020-05-16 14:27:54 +02:00
Thaum Rystra
3642d1d249 Workaround for Firefox not obeying break-inside: avoid; 2020-05-16 14:19:13 +02:00
Thaum Rystra
cd2727b61c Can now link google account 2020-05-16 14:07:22 +02:00
Thaum Rystra
acb9dc342a Improved handling of character avatars, added portraits 2020-05-16 13:40:54 +02:00
Thaum Rystra
d59d8cb54f Library insert forms no longer used stored variants 2020-05-16 12:51:59 +02:00
Thaum Rystra
2c988b8717 Fixed an error where incorrectly targeted effects would cause computation error 2020-05-15 17:27:34 +02:00
Thaum Rystra
3af48649f7 Added some guards against missing properties 2020-05-15 16:51:58 +02:00
Thaum Rystra
79e03e0e63 Separated tool, weapon, armor, and language proficiencies into separate cards 2020-05-15 16:43:37 +02:00
Thaum Rystra
2d788f0c07 ability scores now pass on their skill effects to checks and skills 2020-05-15 16:38:28 +02:00
Thaum Rystra
891fd00b5f Skills now correctly denormalise their passive bonus, conditional benefits, advantage, and fail effects 2020-05-15 16:23:57 +02:00
Thaum Rystra
41b05064c8 login redirects now carry over to the register page 2020-05-15 15:16:59 +02:00
Thaum Rystra
cf110db67d Effect stats input now uses chips 2020-05-15 15:09:46 +02:00
Thaum Rystra
db696574f5 Comboboxes now clear search text when selecting an option 2020-05-15 15:09:34 +02:00
Thaum Rystra
4478628200 Reworked how bare symbols are handled, which should fix simplification 2020-05-15 14:44:08 +02:00
Thaum Rystra
cd8a557120 Let effects autofill skills as well as attributes 2020-05-15 14:29:07 +02:00
Thaum Rystra
5f95471bb6 Added transitions to tree tab property viewer 2020-05-15 14:23:32 +02:00
Thaum Rystra
a62726ae3a Allowed long property viewers in tree tab to scroll 2020-05-15 13:57:09 +02:00
Thaum Rystra
59fa5bcd8c Improved spacing on cards 2020-05-15 13:54:43 +02:00
Thaum Rystra
4b3f068d87 Fixed character sheet tabs not taking up the full screen height 2020-05-15 13:38:31 +02:00
Thaum Rystra
a771d896a8 Prevented dialog titles from overflowing 2020-05-15 13:31:07 +02:00
Thaum Rystra
b439befd47 Stopped tree view overflowing horizontally 2020-05-15 13:23:34 +02:00
Thaum Rystra
b44a18c28c Made tree tab work on mobile. prevented overflow of long titles 2020-05-15 13:18:27 +02:00
Thaum Rystra
bae2f4181a removed old default docs 2020-05-15 11:10:30 +02:00
Thaum Rystra
9b46a91641 Fixed missing Creature imports 2020-05-15 11:10:21 +02:00
Thaum Rystra
fc9467177b hotfix to prevent character sheet going black if DamageMultipliers isn't present 2020-05-14 15:32:54 +02:00
Thaum Rystra
136dd5fd29 Removed stray logging 2020-05-14 15:25:58 +02:00
Thaum Rystra
cb34363a4e Damage multipliers now compute and show up on the character sheet 2020-05-14 15:22:23 +02:00
Thaum Rystra
a4d6adacff Fixed damage multiplier forms and viewers 2020-05-14 13:43:12 +02:00
Thaum Rystra
29588a87d0 Fixed dependency loops causing a stack overflow. Added level variable 2020-05-14 13:32:46 +02:00
Thaum Rystra
97fcb76454 Added if function 2020-05-13 10:42:20 +02:00
Thaum Rystra
9069ee8e35 Improved effect, skill, and attribute viewers 2020-05-13 10:28:39 +02:00
Thaum Rystra
170bac6934 Pruned unused components 2020-05-13 09:43:01 +02:00
Thaum Rystra
809426b183 Improved effect components 2020-05-13 09:42:24 +02:00
Thaum Rystra
e8728166a9 Moved effect components to components folder 2020-05-13 09:34:00 +02:00
Thaum Rystra
5046a847cf Quality pass over all publications, fixed public documents permission error 2020-05-13 09:29:29 +02:00
Thaum Rystra
b6c7ea8c4f Improved handling of tiers, made guest tier funcitonal, improved invites 2020-05-12 15:28:43 +02:00
Thaum Rystra
bbda0ea1b6 Invites can now be managed to some extent 2020-05-12 14:11:43 +02:00
Thaum Rystra
47206ccfc4 Continued implementing sharing 2020-05-12 12:27:24 +02:00
Thaum Rystra
dd213feb0a Added label to username edit field 2020-05-09 13:53:47 +02:00
Thaum Rystra
30ab216dc1 removed redundant publications 2020-05-09 13:45:11 +02:00
Thaum Rystra
ea88a9c41e Libraries can now be shared from the library edit dialog 2020-05-09 13:40:01 +02:00
Thaum Rystra
f0e22dc1ca Made feedback page go to discord 2020-05-09 13:33:33 +02:00
Thaum Rystra
8c608937bb Username can now be changed 2020-05-09 13:15:03 +02:00
Thaum Rystra
c3ed3d55ce Locked friends page since it's not implemented 2020-05-08 17:12:03 +02:00
Thaum Rystra
323cac9405 corrected not implemented page to 'beta' instead of 'alpha' 2020-05-08 16:58:01 +02:00
Thaum Rystra
62689174e2 removed stray console.log 2020-05-08 16:31:58 +02:00
160 changed files with 3972 additions and 3116 deletions

View File

@@ -1,2 +1,3 @@
import "/imports/ui/vueSetup.js"; import '/imports/ui/vueSetup.js';
import "/imports/ui/styles/stylesIndex.js"; import '/imports/ui/styles/stylesIndex.js';
import '/imports/ui/styles/stylesIndex.js';

View File

@@ -1,13 +1,14 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import deathSaveSchema from '/imports/api/properties/subSchemas/DeathSavesSchema.js' import deathSaveSchema from '/imports/api/properties/subSchemas/DeathSavesSchema.js'
import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js'; import ColorSchema from '/imports/api/properties/subSchemas/ColorSchema.js';
import SharingSchema from '/imports/api/sharing/SharingSchema.js'; import SharingSchema from '/imports/api/sharing/SharingSchema.js';
import {assertEditPermission, assertOwnership} from '/imports/api/sharing/sharingPermissions.js'; import {assertEditPermission} from '/imports/api/sharing/sharingPermissions.js';
import '/imports/api/creature/removeCreature.js'; import '/imports/api/creature/removeCreature.js';
//set up the collection for creatures //set up the collection for creatures
Creatures = new Mongo.Collection('creatures'); let Creatures = new Mongo.Collection('creatures');
let CreatureSettingsSchema = new SimpleSchema({ let CreatureSettingsSchema = new SimpleSchema({
//slowed down by carrying too much? //slowed down by carrying too much?
@@ -34,13 +35,6 @@ let CreatureSchema = new SimpleSchema({
defaultValue: '', defaultValue: '',
optional: true, optional: true,
}, },
urlName: {
type: String,
optional: true,
autoValue: function() {
return getSlug(this.field('name').value, {maintainCase: true}) || '-';
},
},
alignment: { alignment: {
type: String, type: String,
optional: true optional: true
@@ -53,6 +47,10 @@ let CreatureSchema = new SimpleSchema({
type: String, type: String,
optional: true optional: true
}, },
avatarPicture: {
type: String,
optional: true,
},
// Mechanics // Mechanics
deathSave: { deathSave: {
@@ -76,6 +74,11 @@ let CreatureSchema = new SimpleSchema({
defaultValue: 'pc', defaultValue: 'pc',
allowedValues: ['pc', 'npc', 'monster'], allowedValues: ['pc', 'npc', 'monster'],
}, },
damageMultipliers: {
type: Object,
blackbox: true,
defaultValue: {}
},
variables: { variables: {
type: Object, type: Object,
blackbox: true, blackbox: true,
@@ -118,10 +121,10 @@ const insertCreature = new ValidatedMethod({
const updateCreature = new ValidatedMethod({ const updateCreature = new ValidatedMethod({
name: 'Creatures.methods.update', name: 'Creatures.methods.update',
validate({_id, path, value}){ validate({_id, path}){
if (!_id) return false; if (!_id) return false;
// Allowed fields // Allowed fields
let allowedFields = ['name', 'alignment', 'gender', 'picture', 'settings']; let allowedFields = ['name', 'alignment', 'gender', 'picture', 'avatarPicture', 'settings'];
if (!allowedFields.includes(path[0])){ if (!allowedFields.includes(path[0])){
throw new Meteor.Error('Creatures.methods.update.denied', throw new Meteor.Error('Creatures.methods.update.denied',
'This field can\'t be updated using this method'); 'This field can\'t be updated using this method');
@@ -137,4 +140,4 @@ const updateCreature = new ValidatedMethod({
}); });
export default Creatures; export default Creatures;
export { CreatureSchema, insertCreature, removeCreature, updateCreature }; export { CreatureSchema, insertCreature, updateCreature };

View File

@@ -1,146 +0,0 @@
// Don't just export a constant, because deep nested objects could be changed
// by code that requires it. Exporting a function that returns the newly created
// object is a little safer.
export default () => ({
"attributes": [
{"name": "Strength", "variableName": "strength", "baseValue": 10, "type": "ability"},
{"name": "Dexterity", "variableName": "dexterity", "baseValue": 10, "type": "ability"},
{"name": "Constitution", "variableName": "constitution", "baseValue": 10, "type": "ability"},
{"name": "Intelligence", "variableName": "intelligence", "baseValue": 10, "type": "ability"},
{"name": "Wisdom", "variableName": "wisdom", "baseValue": 10, "type": "ability"},
{"name": "Charisma", "variableName": "charisma", "baseValue": 10, "type": "ability"},
{"name": "Speed", "variableName": "speed", "baseValue": 30, "type": "stat"},
{"name": "Armor Class", "variableName": "armor", "baseValue": 10, "type": "stat"},
{"name": "d6 Hit Dice", "variableName": "d6HitDice", "type": "hitDice"},
{"name": "d8 Hit Dice", "variableName": "d8HitDice", "type": "hitDice"},
{"name": "d10 Hit Dice", "variableName": "d10HitDice", "type": "hitDice"},
{"name": "d12 Hit Dice", "variableName": "d12HitDice", "type": "hitDice"},
{"name": "Hit Points", "variableName": "hitPoints", "type": "healthBar"},
{"name": "Temporary Hit Points", "variableName": "tempHitPoints", "type": "healthBar"},
{"name": "Ki", "variableName": "ki", "type": "resource"},
{"name": "Rages", "variableName": "rages", "type": "resource"},
{"name": "Sourcery Points", "variableName": "sorceryPoints", "type": "resource"},
{"name": "Superiority Dice", "variableName": "superiorityDice", "type": "resource"},
{"name": "Expertise Dice", "variableName": "expertiseDice", "type": "resource"},
{"name": "Level 1 Spell Slots", "variableName": "level1SpellSlots", "type": "spellSlot"},
{"name": "Level 2 Spell Slots", "variableName": "level2SpellSlots", "type": "spellSlot"},
{"name": "Level 3 Spell Slots", "variableName": "level3SpellSlots", "type": "spellSlot"},
{"name": "Level 4 Spell Slots", "variableName": "level4SpellSlots", "type": "spellSlot"},
{"name": "Level 5 Spell Slots", "variableName": "level5SpellSlots", "type": "spellSlot"},
{"name": "Level 6 Spell Slots", "variableName": "level6SpellSlots", "type": "spellSlot"},
{"name": "Level 7 Spell Slots", "variableName": "level7SpellSlots", "type": "spellSlot"},
{"name": "Level 8 Spell Slots", "variableName": "level8SpellSlots", "type": "spellSlot"},
{"name": "Level 9 Spell Slots", "variableName": "level9SpellSlots", "type": "spellSlot"},
{"name": "Proficiency Bonus", "variableName": "proficiencyBonus", "type": "modifier"},
{"name": "Carry Capacity Multiplier", "variableName": "carryMultiplier", "type": "utility", "baseValue": 1},
{"name": "Rage Damage", "variableName": "rageDamage", "type": "utility"},
],
"skills": [
{"name": "Acrobatics", "variableName": "acrobatics", "ability": "dexterity", "type":"skill"},
{"name": "Animal Handling", "variableName": "animalHandling", "ability": "wisdom", "type":"skill"},
{"name": "Arcana", "variableName": "arcana", "ability": "intelligence", "type":"skill"},
{"name": "Athletics", "variableName": "athletics", "ability": "strength", "type":"skill"},
{"name": "Deception", "variableName": "deception", "ability": "charisma", "type":"skill"},
{"name": "History", "variableName": "history", "ability": "intelligence", "type":"skill"},
{"name": "Insight", "variableName": "insight", "ability": "wisdom", "type":"skill"},
{"name": "Intimidation", "variableName": "intimidation", "ability": "charisma", "type":"skill"},
{"name": "Investigation", "variableName": "investigation", "ability": "intelligence", "type":"skill"},
{"name": "Medicine", "variableName": "medicine", "ability": "wisdom", "type":"skill"},
{"name": "Nature", "variableName": "nature", "ability": "intelligence", "type":"skill"},
{"name": "Perception", "variableName": "perception", "ability": "wisdom", "type":"skill"},
{"name": "Performance", "variableName": "performance", "ability": "charisma", "type":"skill"},
{"name": "Persuasion", "variableName": "persuasion", "ability": "charisma", "type":"skill"},
{"name": "Religion", "variableName": "religion", "ability": "intelligence", "type":"skill"},
{"name": "Sleight of Hand", "variableName": "sleightOfHand", "ability": "dexterity", "type":"skill"},
{"name": "Stealth", "variableName": "stealth", "ability": "dexterity", "type":"skill"},
{"name": "Survival", "variableName": "survival", "ability": "wisdom", "type":"skill"},
{"name": "Strength Save", "variableName": "strengthSave", "ability": "strength", "type":"save"},
{"name": "Dexterity Save", "variableName": "dexteritySave", "ability": "dexterity", "type":"save"},
{"name": "Constitution Save", "variableName": "constitutionSave", "ability": "constitution", "type":"save"},
{"name": "Intelligence Save", "variableName": "intelligenceSave", "ability": "intelligence", "type":"save"},
{"name": "Wisdom Save", "variableName": "wisdomSave", "ability": "wisdom", "type":"save"},
{"name": "Charisma Save", "variableName": "charismaSave", "ability": "charisma", "type":"save"},
{"name": "Initiative", "variableName": "initiative", "ability": "dexterity", "type":"check"},
],
"damageMultipliers": [
{"name": "Acid Multiplier", "variableName":"acidMultiplier"},
{"name": "Bludgeoning Multiplier", "variableName":"bludgeoningMultiplier"},
{"name": "Cold Multiplier", "variableName":"coldMultiplier"},
{"name": "Fire Multiplier", "variableName":"fireMultiplier"},
{"name": "Force Multiplier", "variableName":"forceMultiplier"},
{"name": "Lightning Multiplier", "variableName":"lightningMultiplier"},
{"name": "Necrotic Multiplier", "variableName":"necroticMultiplier"},
{"name": "Piercing Multiplier", "variableName":"piercingMultiplier"},
{"name": "Poison Multiplier", "variableName":"poisonMultiplier"},
{"name": "Psychic Multiplier", "variableName":"psychicMultiplier"},
{"name": "Radiant Multiplier", "variableName":"radiantMultiplier"},
{"name": "Slashing Multiplier", "variableName":"slashingMultiplier"},
{"name": "Thunder Multiplier", "variableName":"thunderMultiplier"},
],
"effects": [
{
"name": "Proficiency bonus by level",
"stat": "proficiencyBonus",
"operation": "add",
"calculation": "floor(level / 4 + 1.75)",
"enabled": true,
},{
"name": "Constitution modifier per level",
"stat": "hitPoints",
"operation": "add",
"calculation": "constitutionMod * level",
"enabled": true,
},
],
"containers": [
{
"name": "Coin Pouch",
"isCarried": true,
"description": "A sturdy pouch for coins",
"items": [
{
"name": "Gold piece",
"plural": "Gold pieces",
"quantity": 0,
"weight": 0.02,
"value": 1,
"settings": {
"showIncrement": true,
},
}, {
"name": "Silver piece",
"plural": "Silver pieces",
"quantity": 0,
"weight": 0.02,
"value": 0.1,
"settings": {
"showIncrement": true,
},
}, {
"name": "Copper piece",
"plural": "Copper pieces",
"quantity": 0,
"weight": 0.02,
"value": 0.01,
"settings": {
"showIncrement": true,
},
},
],
},
],
});

View File

@@ -1,21 +1,46 @@
import { includes, cloneDeep, has } from 'lodash'; import { includes, cloneDeep } from 'lodash';
// The computation memo is an in-memory data structure used only during the
// computation process
export default class ComputationMemo { export default class ComputationMemo {
constructor(props){ constructor(props){
this.statsByVariableName = {}; this.statsByVariableName = {};
this.extraStatsByVariableName = {};
this.statsById = {};
this.originalPropsById = {}; this.originalPropsById = {};
this.propsById = {}; this.propsById = {};
this.skillsByAbility = {}; this.skillsByAbility = {};
this.unassignedEffects = []; this.unassignedEffects = [];
props.filter((prop) => { this.classLevelsById = {};
// skip effects, proficiencies, and class levels for the next pass this.classes = {};
this.togglesById = {};
this.toggleIds = new Set();
// First note all the ids of all the toggles
props.forEach((prop) => {
if ( if (
prop.type === 'effect' || prop.type === 'toggle'
prop.type === 'proficiency' || ) {
prop.type === 'classLevel' this.toggleIds.add(prop._id);
) return true; }
// Add all the stats });
this.addStat(prop); props.filter((prop) => {
if (
prop.type === 'toggle'
) {
this.addToggle(prop);
} else {
return true;
}
}).filter((prop) => {
if (
prop.type === 'attribute' ||
prop.type === 'skill'
) {
// Add all the stats
this.addStat(prop);
} else {
return true;
}
}).forEach((prop) => { }).forEach((prop) => {
// Now add all effects and proficiencies // Now add all effects and proficiencies
if (prop.type === 'effect'){ if (prop.type === 'effect'){
@@ -31,46 +56,97 @@ export default class ComputationMemo {
this.originalPropsById[prop._id] = cloneDeep(prop); this.originalPropsById[prop._id] = cloneDeep(prop);
this.propsById[prop._id] = prop; this.propsById[prop._id] = prop;
prop.computationDetails = propDetails(prop); prop.computationDetails = propDetails(prop);
prop.ancestors.forEach(ancestor => {
if (this.toggleIds.has(ancestor.id)){
prop.computationDetails.toggleAncestors.push(ancestor.id);
}
});
return prop; return prop;
} }
storeHighestClassLevel(name, prop){ /*
storeHighestClassLevel(name, prop, isBaseClass){
// Only store the highest level classLevel // Only store the highest level classLevel
let stat = this.statsByVariableName[name] let stat = this.statsByVariableName[name]
if (!stat){ if (!stat){
this.statsByVariableName[name] = prop; this.statsByVariableName[name] = prop;
if (isBaseClass){
this.classes[name] = prop;
}
} else if (!has(stat, 'level')){ } else if (!has(stat, 'level')){
// Stat is overriden by an attribute // Stat is overriden by an attribute
return; return;
} else if (stat.level < prop.level) { } else if (stat.level < prop.level) {
this.statsByVariableName[name] = prop; this.statsByVariableName[name] = prop;
if (isBaseClass){
this.classes[name] = prop;
}
} }
this.updateLevel();
}
updateLevel(){
let currentLevel = this.statsByVariableName['level'];
if (!currentLevel){
currentLevel = {
value: 0,
computationDetails: {
builtIn: true,
computed: true,
}
};
this.statsByVariableName['level'] = currentLevel;
}
// bail out if overriden by an attribute
if (!currentLevel.computationDetails.builtIn) return;
let level = 0;
for (let name in this.classes){
level += this.classes[name].level || 0;
}
this.statsByVariableName['level'].value = level;
}*/
addToggle(prop){
prop = this.registerProperty(prop);
this.togglesById[prop._id] = prop;
} }
addClassLevel(prop){ addClassLevel(prop){
prop = this.registerProperty(prop); prop = this.registerProperty(prop);
if (prop.variableName){ this.classLevelsById[prop._id] = prop;
this.storeHighestClassLevel(prop.variableName, prop);
}
if (prop.baseClass){
this.storeHighestClassLevel(prop.baseClass, prop);
}
} }
addStat(prop){ addStat(prop){
prop = this.registerProperty(prop);
let variableName = prop.variableName; let variableName = prop.variableName;
if (!variableName) return; if (!variableName) return;
if (this.statsByVariableName[variableName]){ let existingStat = this.statsByVariableName[variableName];
prop.value = NaN; if (existingStat){
prop.computationDetails.error = 'variableNameCollision'; existingStat.computationDetails.idsOfSameName.push(prop._id);
console.warn('variableNameCollision', prop); this.originalPropsById[prop._id] = cloneDeep(prop);
return; if (prop.baseValueCalculation){
} existingStat.computationDetails.effects.push({
this.statsByVariableName[variableName] = prop; operation: 'base',
if ( calculation: prop.baseValueCalculation,
prop.type === 'skill' && stats: [variableName],
isSkillCheck(prop) && computationDetails: propDetailsByType.effect(),
prop.ability statBase: true,
){ });
this.addSkillToAbility(prop, prop.ability) }
if (prop.baseProficiency){
existingStat.computationDetails.proficiencies.push({
value: prop.baseProficiency,
stats: [variableName],
computationDetails: propDetailsByType.proficiency(),
type: 'proficiency',
statBase: true,
});
}
} else {
prop = this.registerProperty(prop);
this.statsById[prop._id] = prop;
this.statsByVariableName[variableName] = prop;
if (
prop.type === 'skill' &&
isSkillCheck(prop) &&
prop.ability
){
this.addSkillToAbility(prop, prop.ability)
}
} }
} }
addSkillToAbility(prop, ability){ addSkillToAbility(prop, ability){
@@ -83,7 +159,9 @@ export default class ComputationMemo {
prop = this.registerProperty(prop); prop = this.registerProperty(prop);
let targets = this.getEffectTargets(prop); let targets = this.getEffectTargets(prop);
targets.forEach(target => { targets.forEach(target => {
target.computationDetails.effects.push(prop); if (target.computationDetails.effects){
target.computationDetails.effects.push(prop);
}
}); });
if (!targets.size){ if (!targets.size){
this.unassignedEffects.push(prop); this.unassignedEffects.push(prop);
@@ -98,7 +176,12 @@ export default class ComputationMemo {
targets.add(target); targets.add(target);
if (isSkillOperation(prop) && isAbility(target)){ if (isSkillOperation(prop) && isAbility(target)){
let extras = this.skillsByAbility[statName] || []; let extras = this.skillsByAbility[statName] || [];
targets.add(...extras) extras.forEach(ex =>{
// Only pass on ability effects to skills and checks
if (ex.skillType === 'skill' || ex.skillType === 'check'){
targets.add(ex)
}
});
} }
}); });
return targets; return targets;
@@ -117,15 +200,29 @@ export default class ComputationMemo {
let target = this.statsByVariableName[statName]; let target = this.statsByVariableName[statName];
if (!target) return; if (!target) return;
targets.add(target); targets.add(target);
if (isAbility(target) && isSkillCheck(prop)) { if (isAbility(target)) {
let extras = this.skillsByAbility[statName] || []; let extras = this.skillsByAbility[statName] || [];
targets.add(...extras) extras.forEach(ex =>{
// Only pass on ability proficiencies to skills and checks
if (ex.skillType === 'skill' || ex.skillType === 'check'){
targets.add(ex)
}
});
} }
}); });
return targets; return targets;
} }
} }
function isAbility(prop){
return prop.type === 'attribute' &&
prop.attributeType === 'ability'
}
function isSkillCheck(prop){
return includes(['skill', 'check', 'save', 'utility'], prop.skillType);
}
const skillOperations = [ const skillOperations = [
'advantage', 'advantage',
'disadvantage', 'disadvantage',
@@ -135,15 +232,6 @@ const skillOperations = [
'rollBonus', 'rollBonus',
]; ];
function isAbility(prop){
return prop.type === 'attribute' &&
prop.attributeType === 'ability'
}
function isSkillCheck(prop){
return includes(['skill', 'check', 'save', 'utility'], prop.skillType);
}
function isSkillOperation(prop){ function isSkillOperation(prop){
return skillOperations.includes(prop.operation); return skillOperations.includes(prop.operation);
} }
@@ -153,11 +241,22 @@ function propDetails(prop){
} }
const propDetailsByType = { const propDetailsByType = {
toggle(){
return {
computed: false,
busyComputing: false,
toggleAncestors: [],
disabledByToggle: false,
};
},
attribute(){ attribute(){
return { return {
computed: false, computed: false,
busyComputing: false, busyComputing: false,
effects: [], effects: [],
toggleAncestors: [],
disabledByToggle: false,
idsOfSameName: [],
}; };
}, },
skill(){ skill(){
@@ -166,22 +265,30 @@ const propDetailsByType = {
busyComputing: false, busyComputing: false,
effects: [], effects: [],
proficiencies: [], proficiencies: [],
toggleAncestors: [],
disabledByToggle: false,
idsOfSameName: [],
}; };
}, },
effect(){ effect(){
return { return {
computed: false, computed: false,
busyComputing: false,
toggleAncestors: [],
disabledByToggle: false,
}; };
}, },
classLevel(){ classLevel(){
return { return {
computed: true, computed: true,
toggleAncestors: [],
disabledByToggle: false,
}; };
}, },
proficiency(){ proficiency(){
return {}; return {
}, toggleAncestors: [],
damageMultiplier(){ disabledByToggle: false,
return {}; };
}, },
} }

View File

@@ -25,6 +25,9 @@ export default class EffectAggregator{
case 'base': case 'base':
// Take the largest base value // Take the largest base value
this.base = result > this.base ? result : this.base; this.base = result > this.base ? result : this.base;
if (effect.statBase){
this.statBaseValue = result > this.statBaseValue ? result : this.statBaseValue;
}
break; break;
case 'add': case 'add':
// Add all adds together // Add all adds together

View File

@@ -1,5 +1,5 @@
import * as math from 'mathjs'; import math from '/imports/math.js';
import replaceBareSymbolsWithValueAccessor from '/imports/api/creature/computation/utility/replaceBareSymbolsWithValueAccessor.js'; import bareSymbolSubtitutor from '/imports/api/creature/computation/utility/bareSymbolSubtitutor.js';
export default function evaluateString(string, scope){ export default function evaluateString(string, scope){
let errors = []; let errors = [];
@@ -20,7 +20,7 @@ export default function evaluateString(string, scope){
} }
// Replace all bare symbols with symbol.value // Replace all bare symbols with symbol.value
let transformedCalc = calc.transform(replaceBareSymbolsWithValueAccessor); let transformedCalc = calc.transform(bareSymbolSubtitutor(scope));
// Evaluate the expression to a number or return with substitutions // Evaluate the expression to a number or return with substitutions
try { try {
@@ -29,11 +29,11 @@ export default function evaluateString(string, scope){
} catch (e1){ } catch (e1){
errors.push(e1); errors.push(e1);
try { try {
let result = simplifyWithAccessors(calc, scope).toHTML(); let result = simplifyWithAccessors(transformedCalc, scope).toHTML();
return {result, errors}; return {result, errors};
} catch (e2){ } catch (e2){
errors.push(e2); errors.push(e2);
return {result: calc.toHTML(), errors}; return {result: transformedCalc.toHTML(), errors};
} }
} }
} }

View File

@@ -0,0 +1,11 @@
import computeToggle from '/imports/api/creature/computation/computeToggle.js';
export default function applyToggles(prop, memo){
prop.computationDetails.toggleAncestors.forEach(toggleId => {
let toggle = memo.togglesById[toggleId];
computeToggle(toggle, memo);
if (!toggle.toggleResult){
prop.computationDetails.disabledByToggle = true;
}
});
}

View File

@@ -1,5 +1,5 @@
import computeStat from '/imports/api/creature/computation/computeStat.js'; import computeStat from '/imports/api/creature/computation/computeStat.js';
import applyToggles from '/imports/api/creature/computation/applyToggles.js';
export default function combineStat(stat, aggregator, memo){ export default function combineStat(stat, aggregator, memo){
if (stat.type === 'attribute'){ if (stat.type === 'attribute'){
@@ -37,17 +37,22 @@ function combineSkill(stat, aggregator, memo){
stat.proficiency = stat.baseProficiency || 0; stat.proficiency = stat.baseProficiency || 0;
for (let i in stat.computationDetails.proficiencies){ for (let i in stat.computationDetails.proficiencies){
let prof = stat.computationDetails.proficiencies[i]; let prof = stat.computationDetails.proficiencies[i];
if (prof.value > stat.proficiency) stat.proficiency = prof.value; applyToggles(prof, memo);
if (
!prof.computationDetails.disabledByToggle &&
prof.value > stat.proficiency
){
stat.proficiency = prof.value;
}
} }
// Get the character's proficiency bonus to apply // Get the character's proficiency bonus to apply
let profBonusStat = memo.statsByVariableName['proficiencyBonus']; let profBonusStat = memo.statsByVariableName['proficiencyBonus'];
let profBonus = profBonusStat && profBonusStat.value; let profBonus = profBonusStat && profBonusStat.value;
/** TODO level needs to be on the memo somewhere if (typeof profBonus !== 'number' && memo.statsByVariableName['level']){
if (typeof profBonus !== "number"){ let level = memo.statsByVariableName['level'].value;
profBonus = Math.floor(char.level / 4 + 1.75); profBonus = Math.floor(level / 4 + 1.75);
} }
*/
// Multiply the proficiency bonus by the actual proficiency // Multiply the proficiency bonus by the actual proficiency
profBonus *= stat.proficiency; profBonus *= stat.proficiency;
// Combine everything to get the final result // Combine everything to get the final result
@@ -55,8 +60,26 @@ function combineSkill(stat, aggregator, memo){
if (result < aggregator.min) result = aggregator.min; if (result < aggregator.min) result = aggregator.min;
if (result > aggregator.max) result = aggregator.max; if (result > aggregator.max) result = aggregator.max;
result = Math.floor(result); result = Math.floor(result);
if (stat.base > result) result = stat.base; if (aggregator.base > result) result = aggregator.base;
stat.value = result; stat.value = result;
// Advantage/disadvantage
if (aggregator.advantage && !aggregator.disadvantage){
stat.advantage = 1;
} else if (aggregator.disadvantage && !aggregator.advantage){
stat.advantage = -1;
} else {
stat.advantage = 0;
}
// Passive bonus
stat.passiveBonus = aggregator.passiveAdd;
// conditional benefits
stat.conditionalBenefits = aggregator.conditional;
// Roll bonuses
stat.rollBonus = aggregator.rollBonus;
// Forced to fail
stat.fail = aggregator.fail;
// Rollbonus
stat.rollBonuses = aggregator.rollBonus;
} }
function combineDamageMultiplier(stat){ function combineDamageMultiplier(stat){

View File

@@ -1,15 +1,38 @@
import evaluateCalculation from '/imports/api/creature/computation/evaluateCalculation.js'; import evaluateCalculation from '/imports/api/creature/computation/evaluateCalculation.js';
import applyToggles from '/imports/api/creature/computation/applyToggles.js';
export default function computeEffect(effect, memo){ export default function computeEffect(effect, memo){
if (effect.computationDetails.computed) return; if (effect.computationDetails.computed) return;
if (_.isFinite(effect.calculation)){ if (effect.computationDetails.busyComputing){
// Trying to compute this effect again while it is already computing.
// We must be in a dependency loop.
effect.computationDetails.computed = true;
effect.result = NaN;
effect.computationDetails.busyComputing = false;
effect.computationDetails.error = 'dependencyLoop';
if (Meteor.isClient) console.warn('dependencyLoop', effect);
return;
}
// Before doing any work, mark this effect as busy
effect.computationDetails.busyComputing = true;
// Apply any toggles
applyToggles(effect, memo);
// Determine result of effect calculation
if (!effect.calculation){
if(effect.operation === 'add' || effect.operation === 'base'){
effect.result = 0;
}
} else if (Number.isFinite(+effect.calculation)){
effect.result = +effect.calculation; effect.result = +effect.calculation;
} else if(effect.operation === "conditional" || effect.operation === "rollBonus"){ } else if(effect.operation === 'conditional' || effect.operation === 'rollBonus'){
effect.result = effect.calculation; effect.result = effect.calculation;
} else if(_.contains(["advantage", "disadvantage", "fail"], effect.operation)){ } else if(_.contains(['advantage', 'disadvantage', 'fail'], effect.operation)){
effect.result = 1; effect.result = 1;
} else { } else {
effect.result = evaluateCalculation(effect.calculation, memo); effect.result = evaluateCalculation(effect.calculation, memo);
} }
effect.computationDetails.computed = true; effect.computationDetails.computed = true;
effect.computationDetails.busyComputing = false;
} }

View File

@@ -0,0 +1,44 @@
import { forOwn, has } from 'lodash';
export default function computeLevels(memo){
computeClassLevels(memo);
computeTotalLevel(memo);
}
function computeClassLevels(memo){
forOwn(memo.classLevelsById, classLevel => {
let name = classLevel.variableName;
let stat = memo.statsByVariableName[name];
if (!stat){
memo.statsByVariableName[name] = classLevel;
memo.classes[name] = classLevel;
} else if (!has(stat, 'level')){
// Stat is overriden by an attribute
return;
} else if (stat.level < classLevel.level) {
memo.statsByVariableName[name] = classLevel;
memo.classes[name] = classLevel;
}
});
}
function computeTotalLevel(memo){
let currentLevel = memo.statsByVariableName['level'];
if (!currentLevel){
currentLevel = {
value: 0,
computationDetails: {
builtIn: true,
computed: true,
}
};
memo.statsByVariableName['level'] = currentLevel;
}
// bail out if overriden by an attribute
if (!currentLevel.computationDetails.builtIn) return;
let level = 0;
for (let name in memo.classes){
level += memo.classes[name].level || 0;
}
memo.statsByVariableName['level'].value = level;
}

View File

@@ -1,12 +1,22 @@
import { each, forOwn } from 'lodash'; import { each, forOwn } from 'lodash';
import computeLevels from '/imports/api/creature/computation/computeLevels.js';
import computeStat from '/imports/api/creature/computation/computeStat.js'; import computeStat from '/imports/api/creature/computation/computeStat.js';
import computeEffect from '/imports/api/creature/computation/computeEffect.js'; import computeEffect from '/imports/api/creature/computation/computeEffect.js';
import computeToggle from '/imports/api/creature/computation/computeToggle.js';
export default function computeMemo(memo){ export default function computeMemo(memo){
forOwn(memo.statsByVariableName, (stat) => { // Compute level
computeLevels(memo);
// Compute all stats, even if they are overriden
forOwn(memo.statsById, stat => {
computeStat (stat, memo); computeStat (stat, memo);
}); });
each(memo.unassignedEffects, (effect) => { // Compute effects which didn't end up targeting a stat
each(memo.unassignedEffects, effect => {
computeEffect(effect, memo); computeEffect(effect, memo);
}); });
forOwn(memo.togglesById, toggle => {
computeToggle(toggle, memo);
});
// Compute class levels
} }

View File

@@ -1,6 +1,7 @@
import combineStat from '/imports/api/creature/computation/combineStat.js'; import combineStat from '/imports/api/creature/computation/combineStat.js';
import computeEffect from '/imports/api/creature/computation/computeEffect.js'; import computeEffect from '/imports/api/creature/computation/computeEffect.js';
import EffectAggregator from '/imports/api/creature/computation/EffectAggregator.js'; import EffectAggregator from '/imports/api/creature/computation/EffectAggregator.js';
import applyToggles from '/imports/api/creature/computation/applyToggles.js';
import { each } from 'lodash'; import { each } from 'lodash';
export default function computeStat(stat, memo){ export default function computeStat(stat, memo){
@@ -13,17 +14,26 @@ export default function computeStat(stat, memo){
stat.value = NaN; stat.value = NaN;
stat.computationDetails.busyComputing = false; stat.computationDetails.busyComputing = false;
stat.computationDetails.error = 'dependencyLoop'; stat.computationDetails.error = 'dependencyLoop';
console.warn('dependencyLoop', stat); if (Meteor.isClient) console.warn('dependencyLoop', stat);
return; return;
} }
// Compute and aggregate all the effects // Before doing any work, mark this stat as busy
let aggregator = new EffectAggregator(stat, memo) stat.computationDetails.busyComputing = true;
each(stat.computationDetails.effects, (effect) => { // Apply any toggles
computeEffect(effect, memo); applyToggles(stat, memo);
aggregator.addEffect(effect);
}); if (!stat.computationDetails.disabledByToggle){
// Conglomerate all the effects to compute the final stat values // Compute and aggregate all the effects
combineStat(stat, aggregator, memo); let aggregator = new EffectAggregator(stat, memo)
each(stat.computationDetails.effects, (effect) => {
computeEffect(effect, memo);
if (!effect.computationDetails.disabledByToggle){
aggregator.addEffect(effect);
}
});
// Conglomerate all the effects to compute the final stat values
combineStat(stat, aggregator, memo);
}
// Mark the attribute as computed // Mark the attribute as computed
stat.computationDetails.computed = true; stat.computationDetails.computed = true;
stat.computationDetails.busyComputing = false; stat.computationDetails.busyComputing = false;

View File

@@ -0,0 +1,32 @@
import evaluateCalculation from '/imports/api/creature/computation/evaluateCalculation.js';
export default function computeToggle(toggle, memo){
if (toggle.computationDetails.computed) return;
if (toggle.computationDetails.busyComputing){
// Trying to compute this effect again while it is already computing.
// We must be in a dependency loop.
toggle.computationDetails.computed = true;
toggle.result = false;
toggle.computationDetails.busyComputing = false;
toggle.computationDetails.error = 'dependencyLoop';
if (Meteor.isClient) console.warn('dependencyLoop', toggle);
return;
}
// Before doing any work, mark this toggle as busy
toggle.computationDetails.busyComputing = true;
// Do work
if (toggle.enabled){
toggle.toggleResult = true;
} else if (toggle.disabled){
toggle.toggleResult = false;
} else if (!toggle.condition){
toggle.toggleResult = false;
} else if (Number.isFinite(+toggle.condition)){
toggle.toggleResult = !!+toggle.condition;
} else {
toggle.toggleResult = evaluateCalculation(toggle.condition, memo);
}
toggle.computationDetails.computed = true;
toggle.computationDetails.busyComputing = false;
}

View File

@@ -1,6 +1,6 @@
import replaceBareSymbolsWithValueAccessor from '/imports/api/creature/computation/utility/replaceBareSymbolsWithValueAccessor.js'; import bareSymbolSubtitutor from '/imports/api/creature/computation/utility/bareSymbolSubtitutor.js';
import computeStat from '/imports/api/creature/computation/computeStat.js'; import computeStat from '/imports/api/creature/computation/computeStat.js';
import * as math from 'mathjs'; import math from '/imports/math.js';
export default function evaluateCalculation(string, memo){ export default function evaluateCalculation(string, memo){
if (!string) return string; if (!string) return string;
@@ -9,7 +9,6 @@ export default function evaluateCalculation(string, memo){
try { try {
calc = math.parse(string); calc = math.parse(string);
} catch (e) { } catch (e) {
console.error(e);
return string; return string;
} }
// Ensure all symbol nodes are defined and coputed // Ensure all symbol nodes are defined and coputed
@@ -22,7 +21,7 @@ export default function evaluateCalculation(string, memo){
} }
}); });
// Ensure any bare symbols are value accessors instead // Ensure any bare symbols are value accessors instead
let substitutedCalc = calc.transform(replaceBareSymbolsWithValueAccessor); let substitutedCalc = calc.transform(bareSymbolSubtitutor(memo.statsByVariableName));
// Evaluate the expression to a number or return with substitutions // Evaluate the expression to a number or return with substitutions
try { try {
return substitutedCalc.evaluate(memo.statsByVariableName); return substitutedCalc.evaluate(memo.statsByVariableName);

View File

@@ -1,42 +0,0 @@
import Creatures from '/imports/api/creature/Creatures.js';
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
export default function getCalculationProperties(creatureId){
// First get ids of disabled properties and unequiped items
let disabledAncestorIds = CreatureProperties.find({
'ancestors.id': creatureId,
$or: [
{disabled: true},
{equipped: false},
],
}, {
fields: {_id: 1},
}).map(prop => prop._id);
// Then get the ids of creatures that are children of this creature
// to isolate their decendent properties from this calculation
Creatures.find({
'ancestors.id': creatureId,
}, {
fields: {_id: 1},
}).forEach(prop => {
disabledAncestorIds.push(prop._id);
});
// Get all the properties that aren't from the excluded decendents
return CreatureProperties.find({
'ancestors.id': {
$eq: creatureId,
$nin: disabledAncestorIds,
},
removed: {$ne: true},
type: {$in: [
'attribute',
'skill',
'damageMultiplier',
'effect',
'proficiency',
'classLevel',
]},
}).fetch();
}

View File

@@ -1,12 +1,12 @@
import { Meteor } from 'meteor/meteor'
import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { ValidatedMethod } from 'meteor/mdg:validated-method';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js'; import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
import ComputationMemo from '/imports/api/creature/computation/ComputationMemo.js'; import ComputationMemo from '/imports/api/creature/computation/ComputationMemo.js';
import computeMemo from '/imports/api/creature/computation/computeMemo.js'; import computeMemo from '/imports/api/creature/computation/computeMemo.js';
import getCalculationProperties from '/imports/api/creature/computation/getCalculationProperties.js'; import getActiveProperties from '/imports/api/creature/getActiveProperties.js';
import writeAlteredProperties from '/imports/api/creature/computation/writeAlteredProperties.js'; import writeAlteredProperties from '/imports/api/creature/computation/writeAlteredProperties.js';
import writeCreatureVariables from '/imports/api/creature/computation/writeCreatureVariables.js'; import writeCreatureVariables from '/imports/api/creature/computation/writeCreatureVariables.js';
import { recomputeDamageMultipliersById } from '/imports/api/creature/damageMultiplierDenormalise/recomputeDamageMultipliers.js'
export const recomputeCreature = new ValidatedMethod({ export const recomputeCreature = new ValidatedMethod({
@@ -26,6 +26,15 @@ export const recomputeCreature = new ValidatedMethod({
}); });
const calculationPropertyTypes = [
'attribute',
'skill',
'effect',
'proficiency',
'classLevel',
'toggle',
];
/** /**
* This function is the heart of DiceCloud. It recomputes a creature's stats, * This function is the heart of DiceCloud. It recomputes a creature's stats,
* distilling down effects and proficiencies into the final stats that make up * distilling down effects and proficiencies into the final stats that make up
@@ -63,11 +72,16 @@ export const recomputeCreature = new ValidatedMethod({
* - Write the computed results back to the database * - Write the computed results back to the database
*/ */
export function recomputeCreatureById(creatureId){ export function recomputeCreatureById(creatureId){
let props = getCalculationProperties(creatureId); let props = getActiveProperties({
ancestorId: creatureId,
filter: {type: {$in: calculationPropertyTypes}},
includeUntoggled: true,
});
let computationMemo = new ComputationMemo(props); let computationMemo = new ComputationMemo(props);
computeMemo(computationMemo); computeMemo(computationMemo);
writeAlteredProperties(computationMemo); writeAlteredProperties(computationMemo);
writeCreatureVariables(computationMemo, creatureId); writeCreatureVariables(computationMemo, creatureId);
// if(Meteor.isClient) console.log(computationMemo); // if(Meteor.isClient) console.log(computationMemo);
recomputeDamageMultipliersById(creatureId);
return computationMemo; return computationMemo;
} }

View File

@@ -0,0 +1,24 @@
import math from '/imports/math.js';
export default function bareSymbolSubtitutor(scope){
return function(node, path){
if (!scope) return node;
if (node.isFunctionNode){
let fn = node.fn;
if (fn && fn.isSymbolNode){
fn.skipReplacement = true;
}
return node;
} else if (
node.isSymbolNode &&
path !== 'object' &&
node.skipReplacement !== true
) {
let stat = scope[node.name];
if (!stat) return node;
return new math.ConstantNode(stat.value);
} else {
return node;
}
}
}

View File

@@ -1,22 +0,0 @@
import * as math from 'mathjs';
export default function replaceBareSymbolsWithValueAccessor(node, path) {
if (node.isFunctionNode){
let fn = node.fn;
if (fn && fn.isSymbolNode){
fn.skipReplacement = true;
}
return node;
} else if (
node.isSymbolNode &&
path !== 'object' &&
node.skipReplacement !== true
) {
const object = new math.SymbolNode(node.name);
const address = new math.ConstantNode('value');
const index = new math.IndexNode([address]);
return new math.AccessorNode(object, index);
} else {
return node;
}
}

View File

@@ -3,51 +3,60 @@ import { isEqual, forOwn } from 'lodash';
import { ComputedOnlySkillSchema } from '/imports/api/properties/Skills.js'; import { ComputedOnlySkillSchema } from '/imports/api/properties/Skills.js';
import { ComputedOnlyAttributeSchema } from '/imports/api/properties/Attributes.js'; import { ComputedOnlyAttributeSchema } from '/imports/api/properties/Attributes.js';
import { ComputedOnlyEffectSchema } from '/imports/api/properties/Effects.js'; import { ComputedOnlyEffectSchema } from '/imports/api/properties/Effects.js';
import { ComputedOnlyToggleSchema } from '/imports/api/properties/Toggles.js';
import CreatureProperties from '/imports/api/creature/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
const schemasByType = {
'skill': ComputedOnlySkillSchema,
'attribute': ComputedOnlyAttributeSchema,
'effect': ComputedOnlyEffectSchema,
'toggle': ComputedOnlyToggleSchema,
};
export default function writeAlteredProperties(memo){ export default function writeAlteredProperties(memo){
let bulkWriteOperations = []; let bulkWriteOperations = [];
// Loop through all properties on the memo // Loop through all properties on the memo
forOwn(memo.originalPropsById, (original, _id) => { forOwn(memo.propsById, changed => {
let changed = memo.propsById[_id]; let schema = schemasByType[changed.type];
if (!schema) return;
let schema; let extraIds = changed.computationDetails.idsOfSameName;
switch (changed.type){ let ids;
case 'skill': if (extraIds && extraIds.length){
schema = ComputedOnlySkillSchema; ids = [changed._id, ...extraIds];
break; } else {
case 'attribute': ids = [changed._id];
schema = ComputedOnlyAttributeSchema;
break;
case 'effect':
schema = ComputedOnlyEffectSchema;
break;
default:
return;
} }
let op = undefined; ids.forEach(id => {
// Loop through all keys that can be changed by computation let op = undefined;
// and compile an operation that sets all those keys let original = memo.originalPropsById[id];
for (let key of schema.objectKeys()){ op = addChangedKeysToOp(op, schema.objectKeys(), original, changed);
if (!isEqual(original[key], changed[key])){ if (op){
if (!op) op = newOperation(_id, changed.type); bulkWriteOperations.push(op);
let value = changed[key];
if (value === undefined){
// Unset values that become undefined
addUnsetOp(op, key);
} else {
// Set values that changed to something else
addSetOp(op, key, value);
}
} }
} });
if (op){
bulkWriteOperations.push(op);
}
}); });
bulkWriteProperties(bulkWriteOperations); bulkWriteProperties(bulkWriteOperations);
} }
function addChangedKeysToOp(op, keys, original, changed) {
// Loop through all keys that can be changed by computation
// and compile an operation that sets all those keys
for (let key of keys){
if (!isEqual(original[key], changed[key])){
if (!op) op = newOperation(original._id, changed.type);
let value = changed[key];
if (value === undefined){
// Unset values that become undefined
addUnsetOp(op, key);
} else {
// Set values that changed to something else
addSetOp(op, key, value);
}
}
}
return op;
}
function newOperation(_id, type){ function newOperation(_id, type){
let newOp = { let newOp = {
updateOne: { updateOne: {
@@ -84,12 +93,16 @@ function bulkWriteProperties(bulkWriteOps){
bulkWriteOps, bulkWriteOps,
{ordered : false}, {ordered : false},
function(e){ function(e){
if (e) console.error(e); if (e) {
console.error('Bulk write failed: ');
console.error(e);
}
} }
); );
} else { } else {
bulkWriteOps.forEach(op => { bulkWriteOps.forEach(op => {
CreatureProperties.update(op.updateOne.filter, op.updateOne.update, { let updateOneOrMany = op.updateOne || op.updateMany;
CreatureProperties.update(updateOneOrMany.filter, updateOneOrMany.update, {
// The server code is bypassing collection 2 validation, so do the same // The server code is bypassing collection 2 validation, so do the same
// on the client // on the client
// include this if bypass is off: // include this if bypass is off:

View File

@@ -1,3 +1,4 @@
import Creatures from '/imports/api/creature/Creatures.js';
import { import {
assertEditPermission as editPermission, assertEditPermission as editPermission,
assertViewPermission as viewPermission, assertViewPermission as viewPermission,

View File

@@ -0,0 +1,67 @@
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import SimpleSchema from 'simpl-schema';
import { assertEditPermission } from '/imports/api/creature/creaturePermissions.js';
import Creatures from '/imports/api/creature/Creatures.js';
import getActiveProperties from '/imports/api/creature/getActiveProperties.js';
export const recomputeDamageMultipliers = new ValidatedMethod({
name: 'Creatures.methods.recomputeDamageMultipliers',
validate: new SimpleSchema({
creatureId: { type: String }
}).validator(),
run({creatureId}) {
// Permission
assertEditPermission(creatureId, this.userId);
// Work, call this direcly if you are already in a method that has checked
// for permission to edit a given character
recomputeDamageMultipliersById(creatureId);
},
});
export function recomputeDamageMultipliersById(creatureId){
if (!creatureId) throw 'Creature ID is required';
let props = getActiveProperties({
ancestorId: creatureId,
filter: {type: 'damageMultiplier'},
});
// Count of how many weakness, resistances and immunities each damage type has
let multipliersByName = {};
props.forEach(dm => {
dm.damageTypes.forEach(damageType => {
if (!multipliersByName[damageType]){
multipliersByName[damageType] = {
weaknesses: 0,
resistances: 0,
immunities: 0,
};
}
if (dm.value === 0){
multipliersByName[damageType].immunities++;
} else if (dm.value === 0.5){
multipliersByName[damageType].resistances++;
} else if (dm.value === 2){
multipliersByName[damageType].weaknesses++;
}
});
});
// Make an Object with keys of all the damage types that have a resulting
// immunity, weakness, or resistance
let damageMultipliers = {};
for (let damageType in multipliersByName){
let multiplier = multipliersByName[damageType];
if (multiplier.immunities){
damageMultipliers[damageType] = 0;
} else if (multiplier.resistances && !multiplier.weaknesses){
damageMultipliers[damageType] = 0.5;
} else if (multiplier.weaknesses && !multiplier.resistances){
damageMultipliers[damageType] = 2;
}
}
// Store the Object on the creature document
Creatures.update(creatureId, {$set: {damageMultipliers}});
}

View File

@@ -0,0 +1,52 @@
import Creatures from '/imports/api/creature/Creatures.js';
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
export default function getActiveProperties({
ancestorId,
filter = {},
options,
includeUntoggled = false
}){
if (!ancestorId){
throw 'Ancestor Id is required to get active properties'
}
// First get ids of disabled properties, unequiped items, unapplied buffs
let disabledAncestorsFilter = {
'ancestors.id': ancestorId,
$or: [
{disabled: true},
{equipped: false},
{applied: false},
],
};
if (!includeUntoggled){
disabledAncestorsFilter.$or.push({toggleResult: false});
}
let disabledAncestorIds = CreatureProperties.find(disabledAncestorsFilter, {
fields: {_id: 1},
}).map(prop => prop._id);
// Then get the ids of creatures that are children of this creature
// to isolate their decendent properties
Creatures.find({
'ancestors.id': ancestorId,
}, {
fields: {_id: 1},
}).forEach(subCreature => {
disabledAncestorIds.push(subCreature._id);
});
// Get all the properties that are decendents of the ancestor of interest but
// aren't from the excluded decendents
filter['ancestors.id'] = {
$eq: ancestorId,
$nin: disabledAncestorIds,
};
// Get properties that aren't removed
filter.removed = {$ne: true};
// Don't include the disabled ancestors themselves either
filter._id = {
$nin: disabledAncestorIds,
}
return CreatureProperties.find(filter, options).fetch();
}

View File

@@ -1,181 +0,0 @@
import DEFAULT_CHARACTER_DOCS from '/imports/api/creature/DEFAULT_CHARACTER_DOCS.js';
import { Random } from 'meteor/random';
const setParent = function(charId){
let parent = {
collection: "Creatures",
id: charId,
group: "default",
};
return doc => {
doc.parent = doc.parent || parent;
doc.charId = charId;
};
};
const getRacialBonusEffect = function(charId, attribute, bonus){
return {
name: "Race Bonus",
stat: attribute,
operation: "add",
calculation: bonus.toString(),
enabled: true,
parent: {
collection: "Creatures",
id: charId,
group: "race",
},
charId: charId,
};
};
const giveDocsOrderAndIds = function(docArray){
for (i in docArray){
docArray[i].order = +i;
if (!docArray[i]._id){
docArray[i]._id = Random.id();
}
}
};
const getDefaultCharacterDocs = function(charId, {
// Character form data
baseStrength = 10,
baseDexterity = 10,
baseConstitution = 10,
baseIntelligence = 10,
baseWisdom = 10,
baseCharisma = 10,
strengthBonus = 0,
dexterityBonus = 0,
constitutionBonus = 0,
intelligenceBonus = 0,
wisdomBonus = 0,
charismaBonus = 0,
hitDice = "d8",
cls = "Class",
level = 1,
}){
let docs = DEFAULT_CHARACTER_DOCS();
// Setup the base ability scores
docs.attributes[0].baseValue = baseStrength;
docs.attributes[1].baseValue = baseDexterity;
docs.attributes[2].baseValue = baseConstitution;
docs.attributes[3].baseValue = baseIntelligence;
docs.attributes[4].baseValue = baseWisdom;
docs.attributes[5].baseValue = baseCharisma;
// Set up racial bonuses
if (strengthBonus) {
docs.effects.push(
getRacialBonusEffect(charId, 'strength', strengthBonus)
);
}
if (dexterityBonus) {
docs.effects.push(
getRacialBonusEffect(charId, 'dexterity', dexterityBonus)
);
}
if (constitutionBonus) {
docs.effects.push(
getRacialBonusEffect(charId, 'constitution', constitutionBonus)
);
}
if (intelligenceBonus) {
docs.effects.push(
getRacialBonusEffect(charId, 'intelligence', intelligenceBonus)
);
}
if (wisdomBonus) {
docs.effects.push(
getRacialBonusEffect(charId, 'wisdom', wisdomBonus)
);
}
if (charismaBonus) {
docs.effects.push(
getRacialBonusEffect(charId, 'charisma', charismaBonus)
);
}
// Set up Class
const strippedCls = cls.replace(/\s+/g, '')
const classId = Random.id();
docs.classes = [{
_id: classId,
charId,
level,
name: cls,
}];
// Setup hit dice
docs.effects.push({
name: cls,
stat: `${hitDice}HitDice`,
operation: "add",
calculation: `${strippedCls}Level`,
enabled: true,
parent: {
collection: "Classes",
id: classId,
},
charId: charId,
});
// Setup health for all class levels
let healthPerLevel = 4;
if (hitDice == "d6"){
healthPerLevel = 4;
} else if (hitDice == "d8"){
healthPerLevel = 5;
} else if (hitDice == "d10"){
healthPerLevel = 6;
} else if (hitDice == "d12"){
healthPerLevel = 7;
}
docs.effects.push({
name: cls,
stat: `hitPoints`,
operation: "add",
calculation: `${healthPerLevel - 2} + ${healthPerLevel} * ${strippedCls}Level`,
enabled: true,
parent: {
collection: "Classes",
id: classId,
},
charId: charId,
});
// Set the parents for base items
docs.attributes.forEach(setParent(charId));
docs.skills.forEach(setParent(charId));
docs.damageMultipliers.forEach(setParent(charId));
docs.effects.forEach(setParent(charId));
docs.containers.forEach(setParent(charId));
// Set up parenting on items and move them to the top level items object
docs.items = [];
docs.containers.forEach(container => {
container._id = Random.id();
const parent = {
collection: "Containers",
id: container._id,
};
container.items.forEach(item => {
item.parent = parent;
item.charId = charId;
});
// Move the items to the top level array
docs.items.push(...container.items);
delete container.items;
});
// Order the docs
for (collection in docs){
giveDocsOrderAndIds(docs[collection]);
}
return docs
};
export default getDefaultCharacterDocs;

View File

@@ -14,7 +14,6 @@ const RefSchema = new SimpleSchema({
let ChildSchema = new SimpleSchema({ let ChildSchema = new SimpleSchema({
order: { order: {
type: Number, type: Number,
min: 0,
}, },
parent: { parent: {
type: RefSchema, type: RefSchema,

View File

@@ -0,0 +1,27 @@
import { nodesToTree } from '/imports/api/parenting/parenting.js';
export default function getDescendantsInDepthFirstOrder({
collection,
ancestorId,
filter,
options = {fields: {order: 1, ancestors: 1}},
}){
let forest = nodesToTree({collection, ancestorId, filter, options});
let orderMemo = getDocsInDepthFirstOrder(forest);
return orderMemo;
}
export function getDocsInDepthFirstOrder(forest){
let docs = [];
forest.forEach(node => {
addNodeAndTraverse(node, docs)
});
return docs;
}
function addNodeAndTraverse(node, docs){
docs.push(node.node);
node.children.forEach(child => {
addNodeAndTraverse(child, docs)
});
}

View File

@@ -1,53 +1,24 @@
import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js'; import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js';
import getCollectionByName from '/imports/api/parenting/getCollectionByName.js'; import getCollectionByName from '/imports/api/parenting/getCollectionByName.js';
import getDescendantsInDepthFirstOrder from '/imports/api/parenting/getDescendantsInDepthFirstOrder.js'
// Docs keep track of their order amongst their siblings and keep a copy of the // Docs keep track of their depth-first order amongst their entire ancestor tree
// order of their ancestors. Order is first compared between oldest non-shared
// ancestors, then by ancestors before children, then between order of siblings.
export function compareOrder(docA, docB){ export function compareOrder(docA, docB){
// < 0 if A comes before B // < 0 if A comes before B
// = 0 if A and B are the same order // = 0 if A and B are the same order
// > 0 if B comes before A // > 0 if B comes before A
// Documents are equal order to themselves
if (docA._id && docB._id && docA._id === docB._id){
return 0;
}
// If they are siblings, just compare order
if (docA.parent.id === docB.parent.id){
return docA.order - docB.order;
}
// They must share a root ancestor to be meaningfully sorted // They must share a root ancestor to be meaningfully sorted
if (docA.ancestors[0].id !== docB.ancestors[0].id){ if (docA.ancestors[0].id !== docB.ancestors[0].id){
return 0; return 0;
} else {
return docA.order - docB.order;
} }
// Go through their ancestors after the root, and find the first order
// difference
// TODO ancestors don't store order yet
let i, difference;
const length = Math.min(docA.ancestors.length, docB.ancestors.length);
for (i = 1; i < length; i++){
difference = docA.ancestors[i].order - docB.ancestors[i].order;
if (difference){
return difference;
} else if (docA.ancestors[i].id !== docB.ancestors[i].id) {
throw new Meteor.Error('Sibling order clash',
'Sibling docs share the same order, sort failed');
}
}
// We haven't returned yet, all ancestors up to this point are shared and one
// doc has no more ancestors implying one is an ancestor of the other,
// return the difference in their ancestor list lengths, shorter comes first
return docA.ancestors.length - docB.ancestors.length
} }
export function getHighestOrder({collection, parentId}){ export function getHighestOrder({collection, ancestorId}){
const highestOrderedDoc = collection.findOne({ const highestOrderedDoc = collection.findOne({
'parent.id': parentId, 'ancestors.id': ancestorId,
}, { }, {
fields: {order: 1}, fields: {order: 1},
sort: {order: -1}, sort: {order: -1},
@@ -58,13 +29,13 @@ export function getHighestOrder({collection, parentId}){
export function setDocToLastOrder({collection, doc}){ export function setDocToLastOrder({collection, doc}){
doc.order = getHighestOrder({ doc.order = getHighestOrder({
collection, collection,
parentId: doc.parent.id, ancestorId: doc.ancestors[0].id,
}) + 1; }) + 1;
} }
// update the order of a doc, and shift the siblings around to suit the new // update the order of a doc, and shift the related docs around to suit the new
// order // order
export function updateDocOrder({docRef, order}){ function cheapUpdateDocOrder({docRef, order}){
let doc = fetchDocByRef(docRef, {fields: { let doc = fetchDocByRef(docRef, {fields: {
order: 1, order: 1,
parent: 1, parent: 1,
@@ -92,7 +63,7 @@ export function updateDocOrder({docRef, order}){
increment = 1; increment = 1;
} }
collection.update({ collection.update({
'parent.id': doc.parent.id, 'ancestors.id': doc.ancestors[0].id,
order: inBetweenSelector, order: inBetweenSelector,
}, { }, {
$inc: {order: increment}, $inc: {order: increment},
@@ -105,10 +76,10 @@ export function updateDocOrder({docRef, order}){
} }
} }
export function removedDocAtOrder({collection, doc}){ export function cheapRemovedDocAtOrder({collection, doc}){
// Decrement the order of all docs after the removed doc // Decrement the order of all docs after the removed doc
collection.update({ collection.update({
'parent.id': doc.parent.id, 'ancestors.id': doc.ancestors[0].id,
order: {$gt: doc.order}, order: {$gt: doc.order},
}, { }, {
$inc: {order: -1}, $inc: {order: -1},
@@ -118,10 +89,10 @@ export function removedDocAtOrder({collection, doc}){
}); });
} }
export function insertedDocAtOrder({collection, parentId, order}){ export function cheapInsertedDocAtOrder({collection, ancestorId, order}){
// Increment the order of all docs after the inserted doc // Increment the order of all docs after the inserted doc
collection.update({ collection.update({
'parent.id': parentId, 'ancestors.id': ancestorId,
order: {$gte: order}, order: {$gte: order},
}, { }, {
$inc: {order: 1}, $inc: {order: 1},
@@ -131,54 +102,28 @@ export function insertedDocAtOrder({collection, parentId, order}){
}); });
} }
// Update the order a single doc and re-order the entire sibling list // Update the order a single doc and re-order the entire related doc list
// with the change // with the change
export function safeUpdateDocOrder({docRef, order}){ export function safeUpdateDocOrder({docRef, order}){
let collection = getCollectionByName(docRef.collection); let collection = getCollectionByName(docRef.collection);
let movedDoc = fetchDocByRef(docRef, {fields: { // Put the new doc half a step in front of its new order
parent: 1, name: 1 // to ensure it's in front of whichever doc was there before
}}); collection.update(docRef.id, {
let parentId = movedDoc.parent.id; $set: {order}
let bulkWrite = [];
let docs = collection.find({
'parent.id': parentId,
'_id': {$ne: movedDoc._id},
}, { }, {
fields: {order: 1, name: 1}, selector: {type: 'any'}
sort: {order: 1}
}).fetch();
docs.splice(order, 0, movedDoc);
docs.forEach((doc, index) => {
if (doc.order !== index){
bulkWrite.push({
updateOne: {
filter: {_id: doc._id},
update: {$set: {order: index}},
},
});
}
}); });
if (Meteor.isServer){ // reorder all related docs so that order is back to being a continous
collection.rawCollection().bulkWrite(bulkWrite); // set of whole numbers
} else { let movedDoc = fetchDocByRef(docRef, {fields: {ancestors: 1}});
bulkWrite.forEach(op => { let ancestorId = movedDoc.ancestors[0].id;
collection.update( reorderDocs({collection, ancestorId});
op.updateOne.filter, }
op.updateOne.update,
{selector: {type: 'any'}}
);
});
}
};
export function reorderDocs({collection, parentId}){ export function reorderDocs({collection, ancestorId}){
let orderedDocs = getDescendantsInDepthFirstOrder({collection, ancestorId});
let bulkWrite = []; let bulkWrite = [];
collection.find({ orderedDocs.forEach((doc, index) => {
'parent.id': parentId,
}, {
fields: {order: 1},
sort: {order: 1}
}).forEach((doc, index) => {
if (doc.order !== index){ if (doc.order !== index){
bulkWrite.push({ bulkWrite.push({
updateOne : { updateOne : {
@@ -189,10 +134,23 @@ export function reorderDocs({collection, parentId}){
} }
}); });
if (Meteor.isServer){ if (Meteor.isServer){
collection.rawCollection().bulkWrite(bulkWrite); collection.rawCollection().bulkWrite(
bulkWrite,
{ordered : false},
function(e){
if (e) {
console.error('Bulk write failed: ');
console.error(e);
}
}
);
} else { } else {
bulkWrite.forEach(op => { bulkWrite.forEach(op => {
collection.update(op.updateOne.filter, op.updateOne.update); collection.update(
op.updateOne.filter,
op.updateOne.update,
{selector: {type: 'any'}}
);
}); });
} }
} }

View File

@@ -1,10 +1,13 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { union } from 'lodash';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { updateParent } from '/imports/api/parenting/parenting.js'; import { updateParent } from '/imports/api/parenting/parenting.js';
import { insertedDocAtOrder, removedDocAtOrder, safeUpdateDocOrder } from '/imports/api/parenting/order.js'; import { reorderDocs, safeUpdateDocOrder } from '/imports/api/parenting/order.js';
import { RefSchema } from '/imports/api/parenting/ChildSchema.js'; import { RefSchema } from '/imports/api/parenting/ChildSchema.js';
import { assertDocEditPermission } from '/imports/api/sharing/sharingPermissions.js'; import { assertDocEditPermission } from '/imports/api/sharing/sharingPermissions.js';
import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js'; import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js';
import getCollectionByName from '/imports/api/parenting/getCollectionByName.js'; import getCollectionByName from '/imports/api/parenting/getCollectionByName.js';
import { recomputeCreatureById } from '/imports/api/creature/computation/recomputeCreature.js';
const organizeDoc = new ValidatedMethod({ const organizeDoc = new ValidatedMethod({
name: 'organize.methods.organizeDoc', name: 'organize.methods.organizeDoc',
@@ -13,7 +16,7 @@ const organizeDoc = new ValidatedMethod({
parentRef: RefSchema, parentRef: RefSchema,
order: { order: {
type: Number, type: Number,
min: 0, // Should end in 0.5 to place it reliably between two existing documents
}, },
}).validator(), }).validator(),
run({docRef, parentRef, order}) { run({docRef, parentRef, order}) {
@@ -25,14 +28,28 @@ const organizeDoc = new ValidatedMethod({
let parent = fetchDocByRef(parentRef); let parent = fetchDocByRef(parentRef);
assertDocEditPermission(parent, this.userId); assertDocEditPermission(parent, this.userId);
// Reorder the documents in the doc's old parent
removedDocAtOrder({collection, doc});
// Reorder the docs in the destination parent
insertedDocAtOrder({collection, parentId: parentRef.id, order});
// Change the doc's parent // Change the doc's parent
updateParent({docRef, parentRef}); updateParent({docRef, parentRef});
// Change the doc's order // Change the doc's order to be a half step ahead of its target location
collection.update(doc._id, {$set: {order}}, {selector: {type: 'any'}}); collection.update(doc._id, {$set: {order}}, {selector: {type: 'any'}});
// Reorder both ancestors' documents
let oldAncestorId = doc.ancestors[0].id;
reorderDocs({collection, ancestorId: oldAncestorId});
let newAncestorId = getRootId(parent);
if (newAncestorId !== oldAncestorId){
reorderDocs({collection, ancestorId: newAncestorId});
}
// Figure out which creatures need to be recalculated after this move
let docCreatures = getCreatureAncestors(doc);
let parentCreatures = getCreatureAncestors(parent);
let creaturesToRecompute = union(docCreatures, parentCreatures);
// Recompute the creatures
creaturesToRecompute.forEach(id => {
recomputeCreatureById(id);
});
}, },
}); });
@@ -42,14 +59,41 @@ const reorderDoc = new ValidatedMethod({
docRef: RefSchema, docRef: RefSchema,
order: { order: {
type: Number, type: Number,
min: 0, // Should end in 0.5 to place it reliably between two existing documents
}, },
}).validator(), }).validator(),
run({docRef, order}) { run({docRef, order}) {
let doc = fetchDocByRef(docRef); let doc = fetchDocByRef(docRef);
assertDocEditPermission(doc, this.userId); assertDocEditPermission(doc, this.userId);
safeUpdateDocOrder({docRef, order}) safeUpdateDocOrder({docRef, order});
// Recompute the affected creatures
getCreatureAncestors(doc).forEach(id => {
recomputeCreatureById(id);
});
}, },
}); });
function getRootId(doc){
if (doc.ancestors && doc.ancestors.length && doc.ancestors[0]){
return doc.ancestors[0].id;
} else {
return doc._id;
}
}
function getCreatureAncestors(doc){
let ids = [];
if(doc.type === 'pc' || doc.type === 'npc' || doc.type === 'monster'){
ids.push(doc._id);
}
if (doc.ancestors){
doc.ancestors.forEach(ancestorRef => {
if (ancestorRef.collection === 'creatures'){
ids.push(ancestorRef.id);
}
});
}
return ids;
}
export { organizeDoc, reorderDoc }; export { organizeDoc, reorderDoc };

View File

@@ -48,38 +48,38 @@ export function fetchParent({id, collection}){
} }
export function fetchChildren({ collection, parentId, filter = {}, options = {sort: {order: 1}} }){ export function fetchChildren({ collection, parentId, filter = {}, options = {sort: {order: 1}} }){
filter["parent.id"] = parentId; filter['parent.id'] = parentId;
let children = []; let children = [];
children.push( children.push(
...collection.find({ ...collection.find({
"parent.id": parentId 'parent.id': parentId
}, options).fetch() }, options).fetch()
); );
return children; return children;
} }
export function updateChildren({collection, parentId, filter = {}, modifier, options={}}){ export function updateChildren({collection, parentId, filter = {}, modifier, options={}}){
filter["parent.id"] = parentId; filter['parent.id'] = parentId;
options.multi = true; options.multi = true;
collection.update(filter, modifier, options); collection.update(filter, modifier, options);
} }
export function fetchDescendants({ collection, ancestorId, filter = {}, options}){ export function fetchDescendants({ collection, ancestorId, filter = {}, options}){
filter["ancestors.id"] = ancestorId; filter['ancestors.id'] = ancestorId;
let descendants = []; let descendants = [];
descendants.push(...collection.find(filter, options).fetch()); descendants.push(...collection.find(filter, options).fetch());
return descendants; return descendants;
} }
export function updateDescendants({collection, ancestorId, filter = {}, modifier, options={}}){ export function updateDescendants({collection, ancestorId, filter = {}, modifier, options={}}){
filter["ancestors.id"] = ancestorId; filter['ancestors.id'] = ancestorId;
options.multi = true; options.multi = true;
options.selector = {type: 'any'}; options.selector = {type: 'any'};
collection.update(filter, modifier, options); collection.update(filter, modifier, options);
} }
export function forEachDescendant({collection, ancestorId, filter = {}, options}, callback){ export function forEachDescendant({collection, ancestorId, filter = {}, options}, callback){
filter["ancestors.id"] = ancestorId; filter['ancestors.id'] = ancestorId;
collection.find(filter, options).forEach(callback); collection.find(filter, options).forEach(callback);
} }
@@ -200,21 +200,21 @@ export function getName(doc){
if (doc.name) return name; if (doc.name) return name;
var i = doc.ancestors.length; var i = doc.ancestors.length;
while(i--) { while(i--) {
if (ancestors[i].name) return ancestors[i].name; if (doc.ancestors[i].name) return doc.ancestors[i].name;
} }
} }
export function nodesToTree({collection, ancestorId, filter}){ export function nodesToTree({collection, ancestorId, filter, options}){
// Store a dict of all the nodes // Store a dict of all the nodes
let nodeIndex = {}; let nodeIndex = {};
let nodeList = []; let nodeList = [];
if (!options) options = {};
options.sort = {order: 1};
collection.find({ collection.find({
'ancestors.id': ancestorId, 'ancestors.id': ancestorId,
removed: {$ne: true}, removed: {$ne: true},
...filter, ...filter,
}, { }, options).forEach( node => {
sort: {order: 1}
}).forEach( node => {
let treeNode = { let treeNode = {
node: node, node: node,
children: [], children: [],

View File

@@ -1,6 +1,5 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import ResourcesSchema from '/imports/api/properties/subSchemas/ResourcesSchema.js' import ResourcesSchema from '/imports/api/properties/subSchemas/ResourcesSchema.js'
import ResultsSchema from '/imports/api/properties/subSchemas/ResultsSchema.js';
/* /*
* Actions are things a character can do * Actions are things a character can do
@@ -41,10 +40,6 @@ let ActionSchema = new SimpleSchema({
'tags.$': { 'tags.$': {
type: String, type: String,
}, },
results: {
type: ResultsSchema,
defaultValue: {},
},
resources: { resources: {
type: ResourcesSchema, type: ResourcesSchema,
defaultValue: {}, defaultValue: {},

View File

@@ -0,0 +1,27 @@
import SimpleSchema from 'simpl-schema';
const AdjustmentSchema = new SimpleSchema({
// The roll that determines how much to change the attribute
amount: {
type: String,
optional: true,
defaultValue: '1',
},
// Who this adjustment applies to
target: {
type: String,
defaultValue: 'every',
allowedValues: [
'self', // the character who took the action
'each', // rolled once for `each` target
'every', // rolled once and applied to `every` target
],
},
// The stat this rolls applies to
stat: {
type: String,
optional: true,
},
});
export { AdjustmentSchema };

View File

@@ -1,6 +1,4 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { Random } from 'meteor/random';
import { StoredEffectSchema } from '/imports/api/properties/Effects.js';
let BuffSchema = new SimpleSchema({ let BuffSchema = new SimpleSchema({
name: { name: {
@@ -15,20 +13,12 @@ let BuffSchema = new SimpleSchema({
type: String, type: String,
optional: true, optional: true,
}, },
}); applied: {
type: Boolean,
// The effects in the stored buff need to be resolved to a number before being defaultValue: false,
// placed on other characters, if they are applied to self, they can remain as index: 1,
// calculations, provided they don't contain any rolls },
let StoredBuffSchema = new SimpleSchema({ target: {
effects: {
type: Array,
defaultValue: [],
},
'effects.$': {
type: StoredEffectSchema,
},
target: {
type: String, type: String,
allowedValues: [ allowedValues: [
'self', // the character who took the buff 'self', // the character who took the buff
@@ -37,21 +27,14 @@ let StoredBuffSchema = new SimpleSchema({
], ],
defaultValue: 'every', defaultValue: 'every',
}, },
}).extend(BuffSchema); });
let StoredBuffWithIdSchema = new SimpleSchema({
_id: {
type: String,
regEx: SimpleSchema.RegEx.Id,
autoValue(){
if (!this.isSet){
return Random.id();
}
},
},
}).extend(StoredBuffSchema);
let AppliedBuffSchema = new SimpleSchema({ let AppliedBuffSchema = new SimpleSchema({
applied: {
type: Boolean,
defaultValue: true,
index: 1,
},
durationSpent: { durationSpent: {
type: Number, type: Number,
optional: true, optional: true,
@@ -73,4 +56,4 @@ let AppliedBuffSchema = new SimpleSchema({
}, },
}).extend(BuffSchema); }).extend(BuffSchema);
export { AppliedBuffSchema, StoredBuffSchema, StoredBuffWithIdSchema }; export { AppliedBuffSchema, BuffSchema };

View File

@@ -11,12 +11,6 @@ let ClassLevelSchema = new SimpleSchema({
type: String, type: String,
regEx: VARIABLE_NAME_REGEX, regEx: VARIABLE_NAME_REGEX,
}, },
// The variable name of the base class this level is attached to
baseClass: {
type: String,
regEx: VARIABLE_NAME_REGEX,
optional: true,
},
level: { level: {
type: SimpleSchema.Integer, type: SimpleSchema.Integer,
defaultValue: 1, defaultValue: 1,

View File

@@ -1,22 +1,14 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { Random } from 'meteor/random';
import DAMAGE_TYPES from '/imports/constants/DAMAGE_TYPES.js'; import DAMAGE_TYPES from '/imports/constants/DAMAGE_TYPES.js';
const DamageSchema = new SimpleSchema({ const DamageSchema = new SimpleSchema({
_id: {
type: String,
regEx: SimpleSchema.RegEx.Id,
autoValue(){
if (!this.isSet) return Random.id();
}
},
// The roll that determines how much to damage the attribute // The roll that determines how much to damage the attribute
damage: { amount: {
type: String, type: String,
optional: true, optional: true,
defaultValue: '1d8 + strength.modifier', defaultValue: '1d8 + strength.modifier',
}, },
// Who this adjustment applies to // Who this damage applies to
target: { target: {
type: String, type: String,
defaultValue: 'every', defaultValue: 'every',
@@ -33,4 +25,4 @@ const DamageSchema = new SimpleSchema({
}, },
}); });
export default DamageSchema; export { DamageSchema };

View File

@@ -1,5 +1,4 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { Random } from 'meteor/random';
/* /*
* Effects are reason-value attached to skills and abilities * Effects are reason-value attached to skills and abilities
@@ -42,16 +41,6 @@ let EffectSchema = new SimpleSchema({
}, },
}); });
const StoredEffectSchema = new SimpleSchema({
_id: {
type: String,
regEx: SimpleSchema.RegEx.Id,
autoValue(){
if (!this.isSet) return Random.id();
}
},
}).extend(EffectSchema);
const ComputedOnlyEffectSchema = new SimpleSchema({ const ComputedOnlyEffectSchema = new SimpleSchema({
// The computed result of the effect // The computed result of the effect
result: { result: {
@@ -64,4 +53,4 @@ const ComputedEffectSchema = new SimpleSchema()
.extend(ComputedOnlyEffectSchema) .extend(ComputedOnlyEffectSchema)
.extend(EffectSchema); .extend(EffectSchema);
export { EffectSchema, StoredEffectSchema, ComputedEffectSchema, ComputedOnlyEffectSchema }; export { EffectSchema, ComputedEffectSchema, ComputedOnlyEffectSchema };

View File

@@ -1,5 +1,4 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import RollResultsSchema from '/imports/api/properties/subSchemas/RollResultsSchema.js'
/** /**
* Rolls are children to actions or other rolls, they are triggered with 0 or * Rolls are children to actions or other rolls, they are triggered with 0 or
@@ -34,13 +33,6 @@ let RollSchema = new SimpleSchema({
'tags.$': { 'tags.$': {
type: String, type: String,
}, },
rollResults: {
type: Array,
defaultValue: [],
},
'rollResults.$': {
type: RollResultsSchema,
},
}); });
export { RollSchema }; export { RollSchema };

View File

@@ -1,5 +1,4 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import ResultsSchema from '/imports/api/properties/subSchemas/ResultsSchema.js';
// These are the rolls made when saves are called for // These are the rolls made when saves are called for
// For the saving throw bonus or proficiency, see ./Skills.js // For the saving throw bonus or proficiency, see ./Skills.js
@@ -8,18 +7,10 @@ let SavingThrowSchema = new SimpleSchema ({
type: String, type: String,
optional: true, optional: true,
}, },
// The variable name of ability the saving throw relies on // The variable name of ability the save to roll
ability: { stat: {
type: String, type: String,
optional: true, optional: true,
},
passResults: {
type: ResultsSchema,
defaultValue: {},
},
failResults: {
type: ResultsSchema,
defaultValue: {},
}, },
}); });

View File

@@ -0,0 +1,36 @@
import SimpleSchema from 'simpl-schema';
const ToggleSchema = new SimpleSchema({
name: {
type: String,
optional: true,
},
disabled: {
type: Boolean,
optional: true,
},
enabled: {
type: Boolean,
optional: true,
},
// if neither disabled or enabled, the condition will be run to determine
// if the children of the toggle should be active
condition: {
type: String,
optional: true,
},
});
const ComputedOnlyToggleSchema = new SimpleSchema({
// The computed result of the effect
toggleResult: {
type: SimpleSchema.oneOf(Number, String, Boolean),
optional: true,
},
});
const ComputedToggleSchema = new SimpleSchema()
.extend(ComputedOnlyToggleSchema)
.extend(ToggleSchema);
export { ToggleSchema, ComputedOnlyToggleSchema, ComputedToggleSchema };

View File

@@ -1,31 +1,36 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ActionSchema } from '/imports/api/properties/Actions.js'; import { ActionSchema } from '/imports/api/properties/Actions.js';
import { AdjustmentSchema } from '/imports/api/properties/Adjustments.js';
import { AttackSchema } from '/imports/api/properties/Attacks.js'; import { AttackSchema } from '/imports/api/properties/Attacks.js';
import { ComputedAttributeSchema } from '/imports/api/properties/Attributes.js'; import { ComputedAttributeSchema } from '/imports/api/properties/Attributes.js';
import { AppliedBuffSchema } from '/imports/api/properties/Buffs.js'; import { BuffSchema } from '/imports/api/properties/Buffs.js';
import { ClassLevelSchema } from '/imports/api/properties/ClassLevels.js'; import { ClassLevelSchema } from '/imports/api/properties/ClassLevels.js';
import { ContainerSchema } from '/imports/api/properties/Containers.js';
import { DamageSchema } from '/imports/api/properties/Damages.js';
import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js'; import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js';
import { ComputedEffectSchema } from '/imports/api/properties/Effects.js'; import { ComputedEffectSchema } from '/imports/api/properties/Effects.js';
import { ExperienceSchema } from '/imports/api/properties/Experiences.js'; import { ExperienceSchema } from '/imports/api/properties/Experiences.js';
import { FeatureSchema } from '/imports/api/properties/Features.js'; import { FeatureSchema } from '/imports/api/properties/Features.js';
import { FolderSchema } from '/imports/api/properties/Folders.js'; import { FolderSchema } from '/imports/api/properties/Folders.js';
import { ItemSchema } from '/imports/api/properties/Items.js';
import { NoteSchema } from '/imports/api/properties/Notes.js'; import { NoteSchema } from '/imports/api/properties/Notes.js';
import { ProficiencySchema } from '/imports/api/properties/Proficiencies.js'; import { ProficiencySchema } from '/imports/api/properties/Proficiencies.js';
import { RollSchema } from '/imports/api/properties/Rolls.js'; import { RollSchema } from '/imports/api/properties/Rolls.js';
import { SavingThrowSchema } from '/imports/api/properties/SavingThrows.js'; import { SavingThrowSchema } from '/imports/api/properties/SavingThrows.js';
import { ComputedSkillSchema } from '/imports/api/properties/Skills.js'; import { ComputedSkillSchema } from '/imports/api/properties/Skills.js';
import { SlotSchema } from '/imports/api/properties/Slots.js'; import { SlotSchema } from '/imports/api/properties/Slots.js';
import { SpellListSchema } from '/imports/api/properties/SpellLists.js';
import { SpellSchema } from '/imports/api/properties/Spells.js'; import { SpellSchema } from '/imports/api/properties/Spells.js';
import { ContainerSchema } from '/imports/api/properties/Containers.js'; import { SpellListSchema } from '/imports/api/properties/SpellLists.js';
import { ItemSchema } from '/imports/api/properties/Items.js'; import { ToggleSchema } from '/imports/api/properties/Toggles.js';
const propertySchemasIndex = { const propertySchemasIndex = {
action: ActionSchema, action: ActionSchema,
adjustment: AdjustmentSchema,
attack: AttackSchema, attack: AttackSchema,
attribute: ComputedAttributeSchema, attribute: ComputedAttributeSchema,
buff: AppliedBuffSchema, buff: BuffSchema,
classLevel: ClassLevelSchema, classLevel: ClassLevelSchema,
damage: DamageSchema,
damageMultiplier: DamageMultiplierSchema, damageMultiplier: DamageMultiplierSchema,
effect: ComputedEffectSchema, effect: ComputedEffectSchema,
experience: ExperienceSchema, experience: ExperienceSchema,
@@ -39,6 +44,7 @@ const propertySchemasIndex = {
slot: SlotSchema, slot: SlotSchema,
spellList: SpellListSchema, spellList: SpellListSchema,
spell: SpellSchema, spell: SpellSchema,
toggle: ToggleSchema,
container: ContainerSchema, container: ContainerSchema,
item: ItemSchema, item: ItemSchema,
any: new SimpleSchema({}), any: new SimpleSchema({}),

View File

@@ -1,9 +1,11 @@
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { ActionSchema } from '/imports/api/properties/Actions.js'; import { ActionSchema } from '/imports/api/properties/Actions.js';
import { AdjustmentSchema } from '/imports/api/properties/Adjustments.js';
import { AttackSchema } from '/imports/api/properties/Attacks.js'; import { AttackSchema } from '/imports/api/properties/Attacks.js';
import { AttributeSchema } from '/imports/api/properties/Attributes.js'; import { AttributeSchema } from '/imports/api/properties/Attributes.js';
import { StoredBuffSchema } from '/imports/api/properties/Buffs.js'; import { BuffSchema } from '/imports/api/properties/Buffs.js';
import { ClassLevelSchema } from '/imports/api/properties/ClassLevels.js'; import { ClassLevelSchema } from '/imports/api/properties/ClassLevels.js';
import { DamageSchema } from '/imports/api/properties/Damages.js';
import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js'; import { DamageMultiplierSchema } from '/imports/api/properties/DamageMultipliers.js';
import { EffectSchema } from '/imports/api/properties/Effects.js'; import { EffectSchema } from '/imports/api/properties/Effects.js';
import { ExperienceSchema } from '/imports/api/properties/Experiences.js'; import { ExperienceSchema } from '/imports/api/properties/Experiences.js';
@@ -17,15 +19,18 @@ import { SkillSchema } from '/imports/api/properties/Skills.js';
import { SlotSchema } from '/imports/api/properties/Slots.js'; import { SlotSchema } from '/imports/api/properties/Slots.js';
import { SpellListSchema } from '/imports/api/properties/SpellLists.js'; import { SpellListSchema } from '/imports/api/properties/SpellLists.js';
import { SpellSchema } from '/imports/api/properties/Spells.js'; import { SpellSchema } from '/imports/api/properties/Spells.js';
import { ToggleSchema } from '/imports/api/properties/Toggles.js';
import { ContainerSchema } from '/imports/api/properties/Containers.js'; import { ContainerSchema } from '/imports/api/properties/Containers.js';
import { ItemSchema } from '/imports/api/properties/Items.js'; import { ItemSchema } from '/imports/api/properties/Items.js';
const propertySchemasIndex = { const propertySchemasIndex = {
action: ActionSchema, action: ActionSchema,
adjustment: AdjustmentSchema,
attack: AttackSchema, attack: AttackSchema,
attribute: AttributeSchema, attribute: AttributeSchema,
buff: StoredBuffSchema, buff: BuffSchema,
classLevel: ClassLevelSchema, classLevel: ClassLevelSchema,
damage: DamageSchema,
damageMultiplier: DamageMultiplierSchema, damageMultiplier: DamageMultiplierSchema,
effect: EffectSchema, effect: EffectSchema,
experience: ExperienceSchema, experience: ExperienceSchema,
@@ -39,6 +44,7 @@ const propertySchemasIndex = {
slot: SlotSchema, slot: SlotSchema,
spellList: SpellListSchema, spellList: SpellListSchema,
spell: SpellSchema, spell: SpellSchema,
toggle: ToggleSchema,
container: ContainerSchema, container: ContainerSchema,
item: ItemSchema, item: ItemSchema,
any: new SimpleSchema({}), any: new SimpleSchema({}),

View File

@@ -1,36 +0,0 @@
import SimpleSchema from 'simpl-schema';
import AdjustmentSchema from '/imports/api/properties/subSchemas/AdjustmentSchema.js';
import DamageSchema from '/imports/api/properties/subSchemas/DamageSchema.js';
import { StoredBuffWithIdSchema } from '/imports/api/properties/Buffs.js';
let ResultsSchema = new SimpleSchema({
// Adjustments applied when taking this action
// Ideally, if these adjustments can't be made, the action should be unusable
adjustments: {
type: Array,
defaultValue: [],
},
'adjustments.$': {
type: AdjustmentSchema,
},
// Damage is done to hitpoints or hitpoint-like stats
// has a damage type, can be mitigated by resistances, etc.
damages: {
type: Array,
defaultValue: [],
},
'damages.$': {
type: DamageSchema,
},
// Buffs applied when taking this action
buffs: {
type: Array,
defaultValue: [],
},
'buffs.$': {
type: StoredBuffWithIdSchema,
},
});
export default ResultsSchema;

View File

@@ -3,18 +3,64 @@ import { assertOwnership } from '/imports/api/sharing/sharingPermissions.js';
import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js'; import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js';
import getCollectionByName from '/imports/api/parenting/getCollectionByName.js'; import getCollectionByName from '/imports/api/parenting/getCollectionByName.js';
import { RefSchema } from '/imports/api/parenting/ChildSchema.js'; import { RefSchema } from '/imports/api/parenting/ChildSchema.js';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
const setPublic = new ValidatedMethod({ const setPublic = new ValidatedMethod({
name: 'sharing.methods.setPublic', name: 'sharing.methods.setPublic',
validate: new SimpleSchema({ validate: new SimpleSchema({
docRef: RefSchema, docRef: RefSchema,
public: { type: Boolean }, isPublic: { type: Boolean },
}).validator(), }).validator(),
run({docRef, public}){ run({docRef, isPublic}){
let doc = fetchDocByRef(docRef); let doc = fetchDocByRef(docRef);
assertOwnership(doc, this.userId); assertOwnership(doc, this.userId);
getCollectionByName(docRef.collection).update(docRef.id, {$set: {public}}); return getCollectionByName(docRef.collection).update(docRef.id, {
$set: {public: isPublic},
});
}, },
}); });
export { setPublic }; const updateUserSharePermissions = new ValidatedMethod({
name: 'sharing.methods.updateUserSharePermissions',
validate: new SimpleSchema({
docRef: RefSchema,
userId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
role: {
type: String,
allowedValues: ['reader', 'writer', 'none'],
},
}).validator(),
run({docRef, userId, role}){
let doc = fetchDocByRef(docRef);
if (role === 'none'){
// only asser ownership if you aren't removing yourself
if (this.userId !== userId){
assertOwnership(doc, this.userId);
}
return getCollectionByName(docRef.collection).update(docRef.id, {
$pullAll: { readers: userId, writers: userId },
});
}
if (doc.owner === userId){
throw new Meteor.Error('Sharing update failed',
'User is already the owner of this document');
}
assertOwnership(doc, this.userId);
if (role === 'reader'){
return getCollectionByName(docRef.collection).update(docRef.id, {
$addToSet: { readers: userId },
$pullAll: { writers: userId },
});
} else if (role === 'writer'){
return getCollectionByName(docRef.collection).update(docRef.id, {
$addToSet: { writers: userId },
$pullAll: { readers: userId },
});
}
},
});
export { setPublic, updateUserSharePermissions };

View File

@@ -15,6 +15,7 @@ let InviteSchema = new SimpleSchema({
regEx: SimpleSchema.RegEx.Id, regEx: SimpleSchema.RegEx.Id,
optional: true, optional: true,
index: 1, index: 1,
unique: 1,
}, },
inviteToken: { inviteToken: {
type: String, type: String,
@@ -25,10 +26,6 @@ let InviteSchema = new SimpleSchema({
isFunded: { isFunded: {
type: Boolean, type: Boolean,
}, },
isRedundant: {
type: Boolean,
optional: true,
},
// The timestamp of when the invitee was confirmed // The timestamp of when the invitee was confirmed
// Older invites have priority over newer ones // Older invites have priority over newer ones
dateConfirmed: { dateConfirmed: {
@@ -119,14 +116,15 @@ const acceptInviteToken = new ValidatedMethod({
}, },
}).validator(), }).validator(),
run({inviteToken}) { run({inviteToken}) {
if (this.userId) { if (!this.userId) {
throw new Meteor.Error('Invites.methods.acceptToken.denied', throw new Meteor.Error('Invites.methods.acceptToken.denied',
'You need to be the logged in to accept a token'); 'You need to be the logged in to accept a token');
} }
if (Meteor.isClient) return;
let invite = Invites.findOne({inviteToken}); let invite = Invites.findOne({inviteToken});
if (!invite){ if (!invite){
throw new Meteor.Error('Invites.methods.acceptToken.notFound', throw new Meteor.Error('Invites.methods.acceptToken.notFound',
'No invite could be found for this token'); 'No invite could be found for this link, maybe it has already been claimed');
} }
// If the invitee is already filled, fix unexpected case by deleting the token // If the invitee is already filled, fix unexpected case by deleting the token
if (invite.invitee){ if (invite.invitee){
@@ -134,7 +132,7 @@ const acceptInviteToken = new ValidatedMethod({
$unset: {inviteToken: 1} $unset: {inviteToken: 1}
}); });
throw new Meteor.Error('Invites.methods.acceptToken.alreadyAccepted', throw new Meteor.Error('Invites.methods.acceptToken.alreadyAccepted',
'This invite already has an invitee, and shouldn\'t have a token'); 'This invite has already been claimed');
} }
if (this.userId === invite.inviter){ if (this.userId === invite.inviter){
throw new Meteor.Error('Invites.methods.acceptToken.ownToken', throw new Meteor.Error('Invites.methods.acceptToken.ownToken',
@@ -147,7 +145,41 @@ const acceptInviteToken = new ValidatedMethod({
}, },
}); });
const revokeInvite = new ValidatedMethod({
name: 'Invites.methods.revokeInvite',
validate: new SimpleSchema({
inviteId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
}).validator(),
run({inviteId}) {
if (!this.userId) {
throw new Meteor.Error('Invites.methods.revokeInvite.denied',
'You need to be the logged in to revoke a token');
}
if (Meteor.isClient) return;
let invite = Invites.findOne(inviteId);
if (!invite){
throw new Meteor.Error('Invites.methods.revokeInvite.notFound',
'No invite could be found for this id');
}
if (this.userId !== invite.inviter) {
throw new Meteor.Error('Invites.methods.revokeInvite.denied',
'You are not the owner of this invite');
}
// If the invitee is empty, the token has already been revoked
if (!invite.invitee){
return;
}
Invites.update(invite._id, {
$unset: {invitee: 1, dateConfirmed: 1},
});
},
});
Invites.attachSchema(InviteSchema); Invites.attachSchema(InviteSchema);
export default Invites; export default Invites;
export { alignInvitesWithPatreonTier, getInviteToken, acceptInviteToken }; export { alignInvitesWithPatreonTier, getInviteToken, acceptInviteToken, revokeInvite };

View File

@@ -66,7 +66,21 @@ const userSchema = new SimpleSchema({
}, },
'subscribedLibraries.$': { 'subscribedLibraries.$': {
type: String, type: String,
regEx: SimpleSchema.RegEx.Id,
}, },
subscribedCharacters: {
type: Array,
defaultValue: [],
max: 100,
},
'subscribedCharacters.$': {
type: String,
regEx: SimpleSchema.RegEx.Id,
},
profile: {
type: Object,
blackbox: true,
},
}); });
Meteor.users.attachSchema(userSchema); Meteor.users.attachSchema(userSchema);
@@ -127,6 +141,55 @@ Meteor.users.isAdmin = function(userId){
return user && user.roles.includes('admin'); return user && user.roles.includes('admin');
} }
Meteor.users.canPickUsername = new ValidatedMethod({
name: 'Users.methods.canPickUsername',
validate: userSchema.pick('username').validator(),
run({username}){
if (Meteor.isClient) return;
let user = Accounts.findUserByUsername(username);
// You can pick your own username
if (user && user._id === this.userId){
return false;
}
return !!user;
}
});
Meteor.users.setUsername = new ValidatedMethod({
name: 'Users.methods.setUsername',
validate: userSchema.pick('username').validator(),
run({username}){
if (!this.userId) throw 'Can only set your username if logged in';
if (Meteor.isClient) return;
return Accounts.setUsername(this.userId, username)
}
});
Meteor.users.subscribeToLibrary = new ValidatedMethod({
name: 'Users.methods.subscribeToLibrary',
validate: new SimpleSchema({
libraryId:{
type: String,
regEx: SimpleSchema.RegEx.Id,
},
subscribe: {
type: Boolean,
},
}).validator(),
run({libraryId, subscribe}){
if (!this.userId) throw 'Can only subscribe if logged in';
if (subscribe){
return Meteor.users.update(this.userId, {
$addToSet: {subscribedLibraries: libraryId},
});
} else {
return Meteor.users.update(this.userId, {
$pullAll: {subscribedLibraries: libraryId},
});
}
}
});
Meteor.users.findUserByUsernameOrEmail = new ValidatedMethod({ Meteor.users.findUserByUsernameOrEmail = new ValidatedMethod({
name: 'Users.methods.findUserByUsernameOrEmail', name: 'Users.methods.findUserByUsernameOrEmail',
validate: new SimpleSchema({ validate: new SimpleSchema({

View File

@@ -1,5 +1,6 @@
import { findLast } from 'lodash'; import { findLast } from 'lodash';
import getEntitledCents from '/imports/api/users/patreon/getEntitledCents.js'; import getEntitledCents from '/imports/api/users/patreon/getEntitledCents.js';
import Invites from '/imports/api/users/Invites.js';
const TIERS = [ const TIERS = [
{ {
@@ -62,7 +63,14 @@ export function getUserTier(user){
if (!user) throw 'User not found'; if (!user) throw 'User not found';
} }
const entitledCents = getEntitledCents(user); const entitledCents = getEntitledCents(user);
return getTierByEntitledCents(entitledCents); const tier = getTierByEntitledCents(entitledCents);
if (tier.paidBenefits) return tier;
let invite = Invites.findOne({invitee: user._id, isFunded: true});
if (invite){
return GUEST_TIER;
} else {
return tier;
}
} }
export default TIERS; export default TIERS;

View File

@@ -3,6 +3,10 @@ const PROPERTIES = Object.freeze({
icon: 'offline_bolt', icon: 'offline_bolt',
name: 'Action' name: 'Action'
}, },
adjustment: {
icon: 'warning',
name: 'Attribute damage'
},
attack: { attack: {
icon: 'bolt', icon: 'bolt',
name: 'Attack' name: 'Attack'
@@ -19,6 +23,10 @@ const PROPERTIES = Object.freeze({
icon: 'school', icon: 'school',
name: 'Class level' name: 'Class level'
}, },
damage: {
icon: 'report',
name: 'Damage'
},
damageMultiplier: { damageMultiplier: {
icon: 'layers', icon: 'layers',
name: 'Damage multiplier' name: 'Damage multiplier'
@@ -75,6 +83,10 @@ const PROPERTIES = Object.freeze({
icon: 'category', icon: 'category',
name: 'Item' name: 'Item'
}, },
toggle: {
icon: 'power_settings_new',
name: 'Toggle'
},
}); });
export default PROPERTIES; export default PROPERTIES;

9
app/imports/math.js Normal file
View File

@@ -0,0 +1,9 @@
import { create, all } from 'mathjs';
const math = create(all);
math.import({
'if': function(pred, a, b) {
return pred ? a : b;
}
});
export default math;

View File

@@ -1,37 +1,38 @@
import Creatures from "/imports/api/creature/Creatures.js"; import Creatures from '/imports/api/creature/Creatures.js';
import Parties from '/imports/api/campaign/Parties.js'; import Parties from '/imports/api/campaign/Parties.js';
Meteor.publish("characterList", function(){ Meteor.publish('characterList', function(){
var userId = this.userId; var userId = this.userId;
if (!userId) { if (!userId) {
this.ready(); return [];
return;
} }
const user = Meteor.user();
const subs = user && user.subscribedCharacters || [];
return [ return [
Creatures.find( Creatures.find({
{$or: [{readers: userId}, {writers: userId}, {owner: userId}], type: "pc"}, $or: [
{ {readers: userId},
{writers: userId},
{owner: userId},
{_id: {$in: subs}},
],
type: 'pc',
}, {
fields: { fields: {
name: 1, name: 1,
urlName: 1, initial: 1,
race: 1,
alignment: 1, alignment: 1,
gender: 1, gender: 1,
readers: 1, readers: 1,
writers:1, writers:1,
owner: 1, owner: 1,
color: 1, color: 1,
picture: 1, picture: 1,
avatarPicture: 1,
public: 1,
} }
} }
), ),
Parties.find({owner: userId}), Parties.find({owner: userId}),
]; ];
}); });
DDPRateLimiter.addRule({
name: "characterList",
type: "subscription",
userId(){ return true; },
connectionId(){ return true; },
}, 8, 5000);

View File

@@ -1,11 +1,10 @@
import Icons from '/imports/api/icons/Icons.js'; import Icons from '/imports/api/icons/Icons.js';
Meteor.publish("sampleIcons", function(){ Meteor.publish('sampleIcons', function(){
return Icons.find({}, {limit: 50}); return Icons.find({}, {limit: 50});
}); });
Meteor.publish('searchIcons', function(searchValue) {
Meteor.publish("searchIcons", function(searchValue) {
// Don't publish anything if there's no search value // Don't publish anything if there's no search value
if (!searchValue) { if (!searchValue) {
return []; return [];
@@ -15,11 +14,11 @@ Meteor.publish("searchIcons", function(searchValue) {
{ {
// relevant documents have a higher score. // relevant documents have a higher score.
fields: { fields: {
score: { $meta: "textScore" } score: { $meta: 'textScore' }
}, },
// `score` property specified in the projection fields above. // `score` property specified in the projection fields above.
sort: { sort: {
score: { $meta: "textScore" } score: { $meta: 'textScore' }
} }
} }
); );

View File

@@ -1,5 +1,5 @@
import './characterList.js'; import '/imports/server/publications/characterList.js';
import './library.js'; import '/imports/server/publications/library.js';
import './singleCharacter.js'; import '/imports/server/publications/singleCharacter.js';
import './users.js'; import '/imports/server/publications/users.js';
import './icons.js'; import '/imports/server/publications/icons.js';

View File

@@ -9,51 +9,29 @@ Meteor.publish('standardLibraries', function(){
return Libraries.find({_id: {$in: standardLibraryIds}}); return Libraries.find({_id: {$in: standardLibraryIds}});
}); });
Meteor.publish('standardLibraryItems', function(categoryKey){
return LibraryItems.find({
library: {$in: standardLibraryIds},
'settings.category': categoryKey,
}, {
sort: {name: 1},
});
});
Meteor.publish('standardLibrarySpells', function(level){
return LibrarySpells.find({
library: {$in: standardLibraryIds},
level,
}, {
sort: {name: 1},
});
});
Meteor.publish('libraries', function(){ Meteor.publish('libraries', function(){
if (!this.userId) return [];
const user = Meteor.user(); const user = Meteor.user();
const userId = user && user._id;
if (!userId) return [];
const subs = user && user.subscribedLibraries || []; const subs = user && user.subscribedLibraries || [];
return Libraries.find({ return Libraries.find({
$or: [ $or: [
{owner: userId}, {owner: this.userId},
{writers: userId}, {writers: this.userId},
{readers: userId}, {readers: this.userId},
{_id: {$in: subs}}, {_id: {$in: subs}},
] ]
}); });
}); });
Meteor.publish('library', function(libraryId){ Meteor.publish('library', function(libraryId){
const user = Meteor.user(); if (!this.userId) return [];
const userId = user && user._id;
if (!userId) return [];
const subs = user && user.subscribedLibraries || [];
let libraryCursor = Libraries.find({ let libraryCursor = Libraries.find({
_id: libraryId, _id: libraryId,
$or: [ $or: [
{owner: userId}, {owner: this.userId},
{writers: userId}, {writers: this.userId},
{readers: userId}, {readers: this.userId},
{_id: {$in: subs}}, {public: true},
], ],
}); });
if (!libraryCursor.count()) return []; if (!libraryCursor.count()) return [];

View File

@@ -2,14 +2,14 @@ import Creatures from '/imports/api/creature/Creatures.js';
import CreatureProperties from '/imports/api/creature/CreatureProperties.js'; import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
Meteor.publish('singleCharacter', function(charId){ Meteor.publish('singleCharacter', function(charId){
userId = this.userId; let userId = this.userId;
var char = Creatures.findOne({ var char = Creatures.findOne({
_id: charId, _id: charId,
$or: [ $or: [
{readers: userId}, {readers: userId},
{writers: userId}, {writers: userId},
{owner: userId}, {owner: userId},
{'settings.viewPermission': 'public'}, {public: true},
], ],
}); });
if (char){ if (char){
@@ -23,29 +23,3 @@ Meteor.publish('singleCharacter', function(charId){
return []; return [];
} }
}); });
DDPRateLimiter.addRule({
name: 'singleCharacter',
type: 'subscription',
userId: null,
connectionId(){ return true; },
}, 8, 10000, function(reply, ruleInput){
if(!reply.allowed){
logRateError(reply, ruleInput);
}
});
Meteor.publish('singleCharacterName', function(charId){
userId = this.userId;
return Creatures.find({
_id: charId,
$or: [
{readers: userId},
{writers: userId},
{owner: userId},
{'settings.viewPermission': 'public'},
],
}, {
fields:{'name': 1}
});
});

View File

@@ -8,15 +8,26 @@ Meteor.publish('user', function(){
username: 1, username: 1,
apiKey: 1, apiKey: 1,
darkMode: 1, darkMode: 1,
subscribedLibraries: 1,
profile: 1,
'services.patreon.id': 1, 'services.patreon.id': 1,
'services.patreon.entitledCents': 1, 'services.patreon.entitledCents': 1,
'services.patreon.entitledCentsOverride': 1, 'services.patreon.entitledCentsOverride': 1,
'services.google.id': 1,
'services.google.picture': 1,
'services.google.name': 1,
'services.google.email': 1,
'services.google.locale': 1,
}}), }}),
Invites.find({ Invites.find({
$or: [ $or: [
{inviter: this.userId}, {inviter: this.userId},
{invitee: this.userId} {invitee: this.userId}
], ],
}, {
fields: {
inviteToken: 0,
}
}), }),
]; ];
}); });

View File

@@ -36,6 +36,11 @@ export default {
padding: 4px; padding: 4px;
} }
.column-layout >>> > div { .column-layout >>> > div {
/*
Table and width set because firefox does not support break-inside: avoid
*/
display: table;
width: 100%;
-webkit-backface-visibility: hidden; -webkit-backface-visibility: hidden;
-webkit-transform: translateX(0); -webkit-transform: translateX(0);
-webkit-column-break-inside: avoid; -webkit-column-break-inside: avoid;

View File

@@ -17,7 +17,6 @@
* Because speed dials only work well with v-btn's as children, this hacky * Because speed dials only work well with v-btn's as children, this hacky
* component creates a v-btn with a label. * component creates a v-btn with a label.
*/ */
console.log('labeled fab reporting for duty')
export default { export default {
props: ['icon', 'label'], props: ['icon', 'label'],
} }

View File

@@ -1,18 +1,21 @@
<template lang="html"> <template lang="html">
<v-card :hover="hasClickListener" @click="$emit('click')"> <v-card
<v-toolbar :hover="hasClickListener"
flat class="toolbar-card"
:style="`transform: none; ${hasToolbarClickListener ? 'cursor: pointer;' : ''}`" @click="$emit('click')"
:color="color" >
:dark="isDark" <v-toolbar
@click="$emit('toolbarclick')" flat
> :style="`transform: none; ${hasToolbarClickListener ? 'cursor: pointer;' : ''}`"
<slot name="toolbar"/> :color="color"
</v-toolbar> :dark="isDark"
<div @click="$emit('toolbarclick')"
> >
<slot/> <slot name="toolbar" />
</div> </v-toolbar>
<div>
<slot />
</div>
</v-card> </v-card>
</template> </template>
@@ -41,5 +44,8 @@
}; };
</script> </script>
<style lang="css" scoped> <style lang="css">
.toolbar-card .v-toolbar__title {
font-size: 14px;
}
</style> </style>

View File

@@ -79,6 +79,9 @@ export default {
</script> </script>
<style lang="css"> <style lang="css">
.computed {
display: inline-block;
}
.computed.symbols-are-errors .math-symbol { .computed.symbols-are-errors .math-symbol {
color: red; color: red;
} }

View File

@@ -5,8 +5,9 @@
:error-messages="errors" :error-messages="errors"
:value="safeValue" :value="safeValue"
:menu-props="{auto: true, lazy: true}" :menu-props="{auto: true, lazy: true}"
:search-input.sync="searchInput"
box box
@change="change" @change="customChange"
@focus="focused = true" @focus="focused = true"
@blur="focused = false" @blur="focused = false"
> >
@@ -22,5 +23,14 @@
export default { export default {
mixins: [SmartInput], mixins: [SmartInput],
data(){ return {
searchInput: '',
}},
methods: {
customChange(val){
this.change(val);
this.searchInput = '';
},
}
}; };
</script> </script>

View File

@@ -1,61 +1,64 @@
<template lang="html"> <template lang="html">
<v-sheet <v-sheet
class="tree-node" class="tree-node"
:class="!hasChildren ? 'empty' : null" :class="!hasChildren ? 'empty' : null"
:data-id="`tree-node-${node._id}`" :data-id="`tree-node-${node._id}`"
> >
<div <div
class="layout row align-center justify-start tree-node-title" class="layout row align-center justify-start tree-node-title"
style="cursor: pointer;" style="cursor: pointer;"
:class="selected && 'primary--text'" :class="selected && 'primary--text'"
@click.stop="$emit('selected', node._id)" @click.stop="$emit('selected', node._id)"
> >
<v-btn <v-btn
small icon small
:class="showExpanded ? 'rotate-90' : null" icon
@click.stop="expanded = !expanded" :class="showExpanded ? 'rotate-90' : null"
:disabled="!hasChildren && !organize || !canExpand" :disabled="!hasChildren && !organize || !canExpand"
> @click.stop="expanded = !expanded"
<v-icon v-if="canExpand && (hasChildren || organize)">chevron_right</v-icon> >
</v-btn> <v-icon v-if="canExpand && (hasChildren || organize)">
<div chevron_right
class="layout row align-center justify-start" </v-icon>
style="flex-grow: 0;" </v-btn>
> <div
<v-icon class="layout row align-center justify-start pr-1"
class="handle mr-2" style="flex-grow: 0;"
v-if="organize" >
:class="selected && 'primary--text'" <v-icon
:disabled="expanded" v-if="organize"
>drag_handle</v-icon> class="handle mr-2"
<property-icon :class="selected && 'primary--text'"
v-if="node.type" :disabled="expanded"
class="mr-2" >
:type="node.type" drag_handle
:class="selected && 'primary--text'" </v-icon>
/> <!--{{node && node.order}}-->
<div class="text-no-wrap text-truncate"> <component
<!--{{node && node.order}}--> :is="treeNodeView"
{{getTitle}} :model="node"
</div> :selected="selected"
</div> />
</div> </div>
<v-expand-transition> </div>
<div v-if="showExpanded" class="pl-3"> <v-expand-transition>
<tree-node-list <div
v-if="showExpanded" v-show="showExpanded"
:node="node" class="pl-3"
:children="computedChildren" >
:group="group" <tree-node-list
:organize="organize" :node="node"
:selected-node-id="selectedNodeId" :children="computedChildren"
@reordered="e => $emit('reordered', e)" :group="group"
@reorganized="e => $emit('reorganized', e)" :organize="organize"
@selected="e => $emit('selected', e)" :selected-node-id="selectedNodeId"
/> @reordered="e => $emit('reordered', e)"
</div> @reorganized="e => $emit('reorganized', e)"
</v-expand-transition> @selected="e => $emit('selected', e)"
</v-sheet> />
</div>
</v-expand-transition>
</v-sheet>
</template> </template>
<script> <script>
@@ -65,21 +68,15 @@
* the tree view shows off the full character structure, and where each part of * the tree view shows off the full character structure, and where each part of
* character comes from. * character comes from.
**/ **/
import PropertyIcon from '/imports/ui/properties/shared/PropertyIcon.vue';
import { canBeParent } from '/imports/api/parenting/parenting.js'; import { canBeParent } from '/imports/api/parenting/parenting.js';
import PROPERTIES from '/imports/constants/PROPERTIES.js' import { getPropertyIcon } from '/imports/constants/PROPERTIES.js';
import treeNodeViewIndex from '/imports/ui/properties/treeNodeViews/treeNodeViewIndex.js';
export default { export default {
name: 'tree-node', name: 'TreeNode',
beforeCreate() {
this.$options.components.TreeNodeList = require('./TreeNodeList.vue').default
},
components: { components: {
PropertyIcon, ...treeNodeViewIndex
}, },
data(){ return {
expanded: false,
}},
props: { props: {
node: Object, node: Object,
group: String, group: String,
@@ -89,7 +86,14 @@
selectedNodeId: String, selectedNodeId: String,
selected: Boolean, selected: Boolean,
}, },
data(){ return {
expanded: false,
}},
computed: { computed: {
treeNodeView(){
let type = this.node.type;
return treeNodeViewIndex[type] || treeNodeViewIndex.default;
},
hasChildren(){ hasChildren(){
return this.children && this.children.length || this.lazy && !this.expanded; return this.children && this.children.length || this.lazy && !this.expanded;
}, },
@@ -109,17 +113,13 @@
canExpand(){ canExpand(){
return canBeParent(this.node.type); return canBeParent(this.node.type);
}, },
getTitle(){ },
let node = this.node; beforeCreate() {
if (!node) return; this.$options.components.TreeNodeList = require('./TreeNodeList.vue').default
if (node.name) return node.name;
let prop = PROPERTIES[this.node.type]
return prop && prop.name;
}
}, },
methods: { methods: {
icon(type){ icon(type){
return PROPERTY_ICONS[type]; return getPropertyIcon(type);
}, },
} }
}; };
@@ -144,12 +144,15 @@
opacity: 0.4; opacity: 0.4;
} }
.ghost { .ghost {
opacity: 0.5; opacity: 0.5;
background: #c8ebfb; background: #fbc8c8;
} }
.v-icon.v-icon--disabled { .v-icon.v-icon--disabled {
opacity: 0; opacity: 0;
} }
.v-icon {
transition: none !important;
}
.theme--light .tree-node-title:hover { .theme--light .tree-node-title:hover {
background: rgba(0,0,0,.04); background: rgba(0,0,0,.04);
} }

View File

@@ -1,33 +1,33 @@
<template lang="html"> <template lang="html">
<!--use value for immutable, list for auto-updating children --> <!--use value for immutable, list for auto-updating children -->
<draggable <draggable
class="drag-area" v-model="displayedChildren"
:value="children" class="drag-area"
:group="group" :group="group"
:animation="200" :move="move"
:move="move" :animation="200"
@change="change" ghost-class="ghost"
ghost-class="ghost" draggable=".item"
draggable=".item" handle=".handle"
handle=".handle" @change="change"
> >
<tree-node <tree-node
class="item" v-for="child in displayedChildren"
v-for="child in children" :key="child.node._id"
:node="child.node" class="item"
:children="child.children" :node="child.node"
:group="group" :children="child.children"
:key="child.node._id" :group="group"
:selected-node-id="selectedNodeId" :selected-node-id="selectedNodeId"
:selected="selectedNodeId === child.node._id" :selected="selectedNodeId === child.node._id"
:organize="organize" :organize="organize"
:lazy="lazy" :lazy="lazy"
@selected="e => $emit('selected', e)" @selected="e => $emit('selected', e)"
@reordered="e => $emit('reordered', e)" @reordered="e => $emit('reordered', e)"
@reorganized="e => $emit('reorganized', e)" @reorganized="e => $emit('reorganized', e)"
@dragstart.native="e => e.dataTransfer.setData('cow', child.node && child.node.name)" @dragstart.native="e => e.dataTransfer.setData('cow', child.node && child.node.name)"
/> />
</draggable> </draggable>
</template> </template>
<script> <script>
@@ -40,9 +40,6 @@
draggable, draggable,
TreeNode, TreeNode,
}, },
data(){ return {
expanded: false,
}},
props: { props: {
node: Object, node: Object,
group: String, group: String,
@@ -50,10 +47,14 @@
lazy: Boolean, lazy: Boolean,
children: { children: {
type: Array, type: Array,
required: true, default: () => [],
}, },
selectedNodeId: String, selectedNodeId: String,
}, },
data(){ return {
expanded: false,
displayedChildren: [],
}},
computed: { computed: {
hasChildren(){ hasChildren(){
return this.children && this.children.length; return this.children && this.children.length;
@@ -62,17 +63,35 @@
return this.expanded && (this.organize || this.hasChildren) return this.expanded && (this.organize || this.hasChildren)
}, },
}, },
watch: {
children(value){
this.displayedChildren = value;
}
},
mounted(){
this.displayedChildren = this.children;
},
methods: { methods: {
change({added, moved, removed}){ change({added, moved}){
let event = moved || added; let event = moved || added;
if (event){ if (event){
let doc = event.element.node; let doc = event.element.node;
let newIndex; let newIndex;
if (event.newIndex === 0){ if (event.newIndex === 0){
newIndex = 0; newIndex = -0.5;
} else { } else {
childBeforeNewIndex = this.children[event.newIndex - 1]; if (event.newIndex < this.children.length){
newIndex = childBeforeNewIndex.node.order + 1; let childAtNewIndex = this.children[event.newIndex];
let indexOrder = childAtNewIndex.node.order;
if (event.newIndex > event.oldIndex){
newIndex = indexOrder + 0.5;
} else {
newIndex = indexOrder - 0.5;
}
} else {
let childBeforeNewIndex = this.children[event.newIndex - 1];
newIndex = childBeforeNewIndex.node.order + 0.5;
}
} }
if (moved){ if (moved){
this.$emit('reordered', {doc, newIndex}); this.$emit('reordered', {doc, newIndex});
@@ -88,9 +107,19 @@
let allowed = isParentAllowed({parentType, childType}); let allowed = isParentAllowed({parentType, childType});
return allowed; return allowed;
}, },
log: console.log,
}, },
}; };
</script> </script>
<style lang="css" scoped> <style lang="css" scoped>
.flip-list-leave-active {
display: none;
}
.flip-list-move {
transition: transform 0.5s;
}
.no-move {
transition: transform 0s;
}
</style> </style>

View File

@@ -23,11 +23,20 @@
/> />
<text-field <text-field
label="Picture URL" label="Picture URL"
hint="A link to a high resolution image"
:value="model.picture" :value="model.picture"
:error-messages="errors.picture" :error-messages="errors.picture"
:debounce-time="debounceTime" :debounce-time="debounceTime"
@change="(value, ack) => $emit('change', {path: ['picture'], value, ack})" @change="(value, ack) => $emit('change', {path: ['picture'], value, ack})"
/> />
<text-field
label="Avatar picture URL"
hint="A link to a smaller, square image to use as an avatar"
:value="model.avatarPicture"
:error-messages="errors.avatarPicture"
:debounce-time="debounceTime"
@change="(value, ack) => $emit('change', {path: ['avatarPicture'], value, ack})"
/>
<!-- <!--
<form-sections> <form-sections>
<form-section name="settings"> <form-section name="settings">

View File

@@ -1,21 +1,27 @@
<template lang="html"> <template lang="html">
<dialog-base> <dialog-base>
<div slot="toolbar"> <v-toolbar-title slot="toolbar">
Creature Form Dialog Creature Form Dialog
</v-toolbar-title>
<div>
<creature-form
:model="model"
@change="change"
/>
</div> </div>
<div> <v-spacer slot="actions" />
<creature-form :model="model" @change="change"/> <v-btn
</div> slot="actions"
<v-spacer slot="actions"/> flat
<v-btn @click="$store.dispatch('popDialogStack')"
slot="actions" >
flat Done
@click="$store.dispatch('popDialogStack')" </v-btn>
>Done</v-btn>
</dialog-base> </dialog-base>
</template> </template>
<script> <script>
import Creatures from '/imports/api/creature/Creatures.js';
import {updateCreature} from '/imports/api/creature/Creatures.js'; import {updateCreature} from '/imports/api/creature/Creatures.js';
import DialogBase from '/imports/ui/dialogStack/DialogBase.vue'; import DialogBase from '/imports/ui/dialogStack/DialogBase.vue';
import CreatureForm from '/imports/ui/creature/CreatureForm.vue' import CreatureForm from '/imports/ui/creature/CreatureForm.vue'

View File

@@ -1,192 +1,269 @@
<template> <template>
<dialog-base> <dialog-base>
<template slot="toolbar">New Character</template> <v-toolbar-title slot="toolbar">
<v-stepper v-model="step" class="no-shadow"> New Character
</v-toolbar-title>
<v-stepper
v-model="step"
class="no-shadow"
>
<v-stepper-header class="no-shadow"> <v-stepper-header class="no-shadow">
<v-stepper-step :complete="step > 1" step="1"> <v-stepper-step
Name :complete="step > 1"
</v-stepper-step> step="1"
<v-divider></v-divider> >
<v-stepper-step :complete="step > 2" step="2"> Name
</v-stepper-step>
<v-divider />
<v-stepper-step
:complete="step > 2"
step="2"
>
Ability Scores Ability Scores
</v-stepper-step> </v-stepper-step>
<v-divider></v-divider> <v-divider />
<v-stepper-step :complete="step > 3" step="3"> <v-stepper-step
:complete="step > 3"
step="3"
>
Class Class
</v-stepper-step> </v-stepper-step>
</v-stepper-header> </v-stepper-header>
<v-stepper-items> <v-stepper-items>
<v-stepper-content step="1"> <v-stepper-content step="1">
<v-text-field label="Name" v-model="name"></v-text-field> <v-text-field
<v-text-field label="Gender" v-model="gender"></v-text-field> v-model="name"
<v-text-field label="Alignment" v-model="alignment" @keydown.tab="step++"></v-text-field> label="Name"
/>
<v-text-field
v-model="gender"
label="Gender"
/>
<v-text-field
v-model="alignment"
label="Alignment"
@keydown.tab="step++"
/>
</v-stepper-content> </v-stepper-content>
<v-stepper-content step="2"> <v-stepper-content step="2">
<v-text-field label="Race" v-model="race"></v-text-field> <v-text-field
<v-layout row justify-center align-center> v-model="race"
<h3>Point Cost:</h3> label="Race"
<h1 class="ml-2" :class="cost > 27 ? 'error--text' : ''">{{cost}}</h1> />
<span class="ml-1">/27</span> <v-layout
</v-layout> row
<table class="point-buy-table mt-2"> justify-center
<thead> align-center
<tr class="font-weight-bold"> >
<td></td> <h3>Point Cost:</h3>
<td>Base Values</td> <h1
<td>Race Bonus</td> class="ml-2"
<td>Score</td> :class="cost > 27 ? 'error--text' : ''"
<td>Modifier</td> >
</tr> {{ cost }}
</thead> </h1>
<tr> <span class="ml-1">/27</span>
<td>Strength</td> </v-layout>
<td><v-text-field <table class="point-buy-table mt-2">
type="number" <thead>
height="20" <tr class="font-weight-bold">
reverse <td />
v-model.number="baseStrength" <td>Base Values</td>
min="8" <td>Race Bonus</td>
max="15"> <td>Score</td>
</v-text-field></td> <td>Modifier</td>
<td><v-text-field </tr>
type="number" </thead>
height="20" <tr>
reverse <td>Strength</td>
v-model.number="strengthBonus"> <td>
</v-text-field></td> <v-text-field
<td>{{baseStrength + strengthBonus}}</td> v-model.number="baseStrength"
<td>{{mod(baseStrength + strengthBonus)}}</td> type="number"
</tr> height="20"
<tr> reverse
<td>Dexterity</td> min="8"
<td><v-text-field max="15"
type="number" />
height="20" </td>
reverse <td>
v-model.number="baseDexterity" <v-text-field
min="8" v-model.number="strengthBonus"
max="15"> type="number"
</v-text-field></td> height="20"
<td><v-text-field reverse
type="number" />
height="20" </td>
reverse <td>{{ baseStrength + strengthBonus }}</td>
v-model.number="dexterityBonus"> <td>{{ mod(baseStrength + strengthBonus) }}</td>
</v-text-field></td> </tr>
<td>{{baseDexterity + dexterityBonus}}</td> <tr>
<td>{{mod(baseDexterity + dexterityBonus)}}</td> <td>Dexterity</td>
</tr> <td>
<tr> <v-text-field
<td>Constitution</td> v-model.number="baseDexterity"
<td><v-text-field type="number"
type="number" height="20"
height="20" reverse
reverse min="8"
v-model.number="baseConstitution" max="15"
min="8" />
max="15"> </td>
</v-text-field></td> <td>
<td><v-text-field <v-text-field
type="number" v-model.number="dexterityBonus"
height="20" type="number"
reverse height="20"
v-model.number="constitutionBonus"> reverse
</v-text-field></td> />
<td>{{baseConstitution + constitutionBonus}}</td> </td>
<td>{{mod(baseConstitution + constitutionBonus)}}</td> <td>{{ baseDexterity + dexterityBonus }}</td>
</tr> <td>{{ mod(baseDexterity + dexterityBonus) }}</td>
<tr> </tr>
<td>Intelligence</td> <tr>
<td><v-text-field <td>Constitution</td>
type="number" <td>
height="20" <v-text-field
reverse v-model.number="baseConstitution"
v-model.number="baseIntelligence" type="number"
min="8" height="20"
max="15"> reverse
</v-text-field></td> min="8"
<td><v-text-field max="15"
type="number" />
height="20" </td>
reverse <td>
v-model.number="intelligenceBonus"> <v-text-field
</v-text-field></td> v-model.number="constitutionBonus"
<td>{{baseIntelligence + intelligenceBonus}}</td> type="number"
<td>{{mod(baseIntelligence + intelligenceBonus)}}</td> height="20"
</tr> reverse
<tr> />
<td>Wisdom</td> </td>
<td><v-text-field <td>{{ baseConstitution + constitutionBonus }}</td>
type="number" <td>{{ mod(baseConstitution + constitutionBonus) }}</td>
height="20" </tr>
reverse <tr>
v-model.number="baseWisdom" <td>Intelligence</td>
min="8" <td>
max="15"> <v-text-field
</v-text-field></td> v-model.number="baseIntelligence"
<td><v-text-field type="number"
type="number" height="20"
height="20" reverse
reverse min="8"
v-model.number="wisdomBonus"> max="15"
</v-text-field></td> />
<td>{{baseWisdom + wisdomBonus}}</td> </td>
<td>{{mod(baseWisdom + wisdomBonus)}}</td> <td>
</tr> <v-text-field
<tr> v-model.number="intelligenceBonus"
<td>Charisma</td> type="number"
<td><v-text-field height="20"
type="number" reverse
height="20" />
reverse </td>
v-model.number="baseCharisma" <td>{{ baseIntelligence + intelligenceBonus }}</td>
min="8" <td>{{ mod(baseIntelligence + intelligenceBonus) }}</td>
max="15"> </tr>
</v-text-field></td> <tr>
<td><v-text-field <td>Wisdom</td>
type="number" <td>
height="20" <v-text-field
reverse v-model.number="baseWisdom"
v-model.number="charismaBonus"> type="number"
</v-text-field></td> height="20"
<td>{{baseCharisma + charismaBonus}}</td> reverse
<td>{{mod(baseCharisma + charismaBonus)}}</td> min="8"
</tr> max="15"
</table> />
</td>
<td>
<v-text-field
v-model.number="wisdomBonus"
type="number"
height="20"
reverse
/>
</td>
<td>{{ baseWisdom + wisdomBonus }}</td>
<td>{{ mod(baseWisdom + wisdomBonus) }}</td>
</tr>
<tr>
<td>Charisma</td>
<td>
<v-text-field
v-model.number="baseCharisma"
type="number"
height="20"
reverse
min="8"
max="15"
/>
</td>
<td>
<v-text-field
v-model.number="charismaBonus"
type="number"
height="20"
reverse
/>
</td>
<td>{{ baseCharisma + charismaBonus }}</td>
<td>{{ mod(baseCharisma + charismaBonus) }}</td>
</tr>
</table>
</v-stepper-content> </v-stepper-content>
<v-stepper-content step="3"> <v-stepper-content step="3">
<v-text-field <v-text-field
label="Class" v-model="cls"
v-model="cls" label="Class"
> />
<v-select
v-model="hitDice"
:items="hitDiceItems"
label="Hit Dice"
/>
</v-text-field> </v-text-field>
<v-select
:items="hitDiceItems"
label="Hit Dice"
v-model="hitDice">
</v-select>
</v-text-field>
</v-stepper-content> </v-stepper-content>
</v-stepper-items> </v-stepper-items>
</v-stepper> </v-stepper>
<template slot="actions"> <template slot="actions">
<v-btn flat @click="$emit('pop')">Cancel</v-btn>
<v-btn flat @click="step--" v-if="step > 1">Back</v-btn>
<v-spacer></v-spacer>
<v-btn color="accent" @click="step++" v-if="step < 3">Next</v-btn>
<v-btn <v-btn
:flat="step < 3" flat
:color="step < 3? '' : 'accent'" @click="$emit('pop')"
@click="submit"> >
Create Cancel
</v-btn> </v-btn>
<v-btn
v-if="step > 1"
flat
@click="step--"
>
Back
</v-btn>
<v-spacer />
<v-btn
v-if="step < 3"
color="accent"
@click="step++"
>
Next
</v-btn>
<v-btn
:flat="step < 3"
:color="step < 3? '' : 'accent'"
@click="submit"
>
Create
</v-btn>
</template> </template>
</dialog-base> </dialog-base>
</template> </template>
<script> <script>
import DialogBase from "/imports/ui/dialogStack/DialogBase.vue"; import DialogBase from '/imports/ui/dialogStack/DialogBase.vue';
const getCost = function(score){ const getCost = function(score){
const costs = { const costs = {
8: 0, 8: 0,
@@ -205,12 +282,15 @@
} }
}; };
export default { export default {
components: {
DialogBase,
},
data(){return { data(){return {
step: 1, step: 1,
name: "New Character", name: 'New Character',
gender: "", gender: '',
alignment: "", alignment: '',
race: "Race", race: 'Race',
baseStrength: 10, baseStrength: 10,
baseDexterity: 10, baseDexterity: 10,
baseConstitution: 10, baseConstitution: 10,
@@ -223,10 +303,23 @@
intelligenceBonus: 0, intelligenceBonus: 0,
wisdomBonus: 0, wisdomBonus: 0,
charismaBonus: 0, charismaBonus: 0,
hitDiceItems: ["d6", "d8", "d10", "d12"], hitDiceItems: ['d6', 'd8', 'd10', 'd12'],
hitDice: "d8", hitDice: 'd8',
cls: "Class", cls: 'Class',
}}, }},
computed: {
cost(){
return [
this.baseStrength,
this.baseDexterity,
this.baseConstitution,
this.baseIntelligence,
this.baseWisdom,
this.baseCharisma,
].map(getCost)
.reduce((memo, score) => memo + score, 0);
},
},
methods: { methods: {
mod(score){ mod(score){
let mod = Math.floor((score - 10) / 2); let mod = Math.floor((score - 10) / 2);
@@ -257,25 +350,9 @@
hitDice: this.hitDice, hitDice: this.hitDice,
cls: this.cls, cls: this.cls,
}; };
this.$emit("pop", char); this.$emit('pop', char);
}, },
}, },
computed: {
cost(){
return [
this.baseStrength,
this.baseDexterity,
this.baseConstitution,
this.baseIntelligence,
this.baseWisdom,
this.baseCharisma,
].map(getCost)
.reduce((memo, score) => memo + score, 0);
},
},
components: {
DialogBase,
},
}; };
</script> </script>

View File

@@ -1,25 +1,37 @@
<template lang="html"> <template lang="html">
<dialog-base> <dialog-base>
<div slot="toolbar"> <v-toolbar-title slot="toolbar">
Delete Character Delete Character
</div> </v-toolbar-title>
<div> <div>
<p v-if="name"> <p v-if="name">
Type "{{name}}" to permanenetly delete the character Type "{{ name }}" to permanenetly delete the character
</p> </p>
<v-text-field v-if="name" v-model="inputName"/> <v-text-field
<v-btn v-show="nameMatch" class="primary" @click="remove">Delete forever</v-btn> v-if="name"
</div> v-model="inputName"
<v-spacer slot="actions"/> />
<v-btn <v-btn
slot="actions" v-show="nameMatch"
flat class="primary"
@click="$store.dispatch('popDialogStack')" @click="remove"
>Cancel</v-btn> >
</dialog-base> Delete forever
</v-btn>
</div>
<v-spacer slot="actions" />
<v-btn
slot="actions"
flat
@click="$store.dispatch('popDialogStack')"
>
Cancel
</v-btn>
</dialog-base>
</template> </template>
<script> <script>
import Creatures from '/imports/api/creature/Creatures.js';
import DialogBase from '/imports/ui/dialogStack/DialogBase.vue'; import DialogBase from '/imports/ui/dialogStack/DialogBase.vue';
import removeCreature from '/imports/api/creature/removeCreature.js'; import removeCreature from '/imports/api/creature/removeCreature.js';
@@ -49,7 +61,7 @@ export default {
}, },
methods: { methods: {
remove(){ remove(){
removeCreature.call({charId: this.id}, (error, result) => { removeCreature.call({charId: this.id}, (error) => {
if (error) { if (error) {
console.error(error); console.error(error);
} else { } else {

View File

@@ -103,3 +103,10 @@
}, },
} }
</script> </script>
<style>
.character-sheet .v-window-item {
min-height: calc(100vh - 96px);
overflow: hidden;
}
</style>

View File

@@ -1,47 +1,41 @@
<template lang="html"> <template lang="html">
<div class="inventory"> <div class="inventory">
<column-layout> <column-layout>
<v-card> <div>
<v-switch <toolbar-card color="">
v-model="organize" <v-spacer slot="toolbar" />
label="Organize" <v-switch
class="justify-end" slot="toolbar"
style="margin: 16px 24px -16px;" v-model="organize"
/> label="Organize"
<!-- Equipping things isn't implemented yet class="justify-end"
<creature-properties-tree />
:root="{collection: 'creatures', id: creatureId}" <v-card-text class="px-0">
:filter="{ <creature-properties-tree
equipped: true, :root="{collection: 'creatures', id: creatureId}"
type: {$in: ['item']}, :filter="{
'ancestors.id': {$nin: containerIds} type: {$in: ['item']},
}" 'ancestors.id': {$nin: containerIds}
@selected="e => clickProperty(e)" }"
:organize="organize" :organize="organize"
group="inventory" group="inventory"
/> @selected="e => clickProperty(e)"
<v-divider/> @reorganized="({doc}) => setEquipped(doc, false)"
--> />
<creature-properties-tree </v-card-text>
:root="{collection: 'creatures', id: creatureId}" </toolbar-card>
:filter="{ </div>
equipped: {$ne: true}, <div
type: {$in: ['item']}, v-for="container in containersWithoutAncestorContainers"
'ancestors.id': {$nin: containerIds} :key="container._id"
}" >
@selected="e => clickProperty(e)" <container-card
:organize="organize" :model="container"
group="inventory" :organize="organize"
/> />
</v-card> </div>
<div v-for="container in containersWithoutAncestorContainers" :key="container._id"> </column-layout>
<container-card </div>
:model="container"
:organize="organize"
/>
</div>
</column-layout>
</div>
</template> </template>
<script> <script>
@@ -49,19 +43,22 @@ import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
import ColumnLayout from '/imports/ui/components/ColumnLayout.vue'; import ColumnLayout from '/imports/ui/components/ColumnLayout.vue';
import CreaturePropertiesTree from '/imports/ui/creature/creatureProperties/CreaturePropertiesTree.vue'; import CreaturePropertiesTree from '/imports/ui/creature/creatureProperties/CreaturePropertiesTree.vue';
import ContainerCard from '/imports/ui/properties/components/inventory/ContainerCard.vue'; import ContainerCard from '/imports/ui/properties/components/inventory/ContainerCard.vue';
import ToolbarCard from '/imports/ui/components/ToolbarCard.vue';
import { updateProperty } from '/imports/api/creature/CreatureProperties.js';
export default { export default {
components: {
ColumnLayout,
CreaturePropertiesTree,
ContainerCard,
ToolbarCard,
},
props: { props: {
creatureId: String, creatureId: String,
}, },
data(){ return { data(){ return {
organize: false, organize: false,
}}, }},
components: {
ColumnLayout,
CreaturePropertiesTree,
ContainerCard,
},
meteor: { meteor: {
containers(){ containers(){
return CreatureProperties.find({ return CreatureProperties.find({
@@ -98,6 +95,13 @@ export default {
data: {_id}, data: {_id},
}); });
}, },
setEquipped(doc, equipped){
updateProperty.call({
_id: doc._id,
path: ['equipped'],
value: equipped
});
}
}, },
} }
</script> </script>

View File

@@ -7,6 +7,10 @@
data-id="creature-summary" data-id="creature-summary"
@click="showCharacterForm" @click="showCharacterForm"
> >
<v-img
v-if="creature.picture"
:src="creature.picture"
/>
<v-card-title class="title"> <v-card-title class="title">
{{ creature.name }} {{ creature.name }}
</v-card-title> </v-card-title>

View File

@@ -1,47 +1,39 @@
<template lang="html"> <template lang="html">
<div class="spells"> <div class="spells">
<column-layout> <column-layout>
<v-card> <div>
<v-switch <v-card>
v-model="organize" <v-card-text>
label="Organize" <v-switch
class="justify-end" v-model="organize"
style="margin: 16px 24px -16px;" label="Organize"
/> class="justify-end"
<!-- Equipping things isn't implemented yet />
<creature-properties-tree <creature-properties-tree
:root="{collection: 'creatures', id: creatureId}" :root="{collection: 'creatures', id: creatureId}"
:filter="{ :filter="{
equipped: true, equipped: {$ne: true},
type: 'spell', type: 'spell',
'ancestors.id': {$nin: spellListIds} 'ancestors.id': {$nin: spellListIds}
}" }"
@selected="e => clickProperty(e)" :organize="organize"
:organize="organize" group="spells"
group="spells" @selected="e => clickProperty(e)"
/> />
<v-divider/> </v-card-text>
--> </v-card>
<creature-properties-tree </div>
:root="{collection: 'creatures', id: creatureId}" <div
:filter="{ v-for="spellList in spellListsWithoutAncestorSpellLists"
equipped: {$ne: true}, :key="spellList._id"
type: 'spell', >
'ancestors.id': {$nin: spellListIds} <spellList-card
}" :model="spellList"
@selected="e => clickProperty(e)" :organize="organize"
:organize="organize" />
group="spells" </div>
/> </column-layout>
</v-card> </div>
<div v-for="spellList in spellListsWithoutAncestorSpellLists" :key="spellList._id">
<spellList-card
:model="spellList"
:organize="organize"
/>
</div>
</column-layout>
</div>
</template> </template>
<script> <script>
@@ -51,17 +43,20 @@ import CreaturePropertiesTree from '/imports/ui/creature/creatureProperties/Crea
import SpellListCard from '/imports/ui/properties/components/spells/SpellListCard.vue'; import SpellListCard from '/imports/ui/properties/components/spells/SpellListCard.vue';
export default { export default {
props: {
creatureId: String,
},
data(){ return {
organize: false,
}},
components: { components: {
ColumnLayout, ColumnLayout,
CreaturePropertiesTree, CreaturePropertiesTree,
SpellListCard, SpellListCard,
}, },
props: {
creatureId: {
type: String,
required: true,
}
},
data(){ return {
organize: false,
}},
meteor: { meteor: {
spellLists(){ spellLists(){
return CreatureProperties.find({ return CreatureProperties.find({

View File

@@ -97,7 +97,7 @@
</div> </div>
<div <div
v-if="spellSlots.length" v-if="spellSlots && spellSlots.length"
class="spell-slots" class="spell-slots"
> >
<v-card> <v-card>
@@ -115,6 +115,10 @@
</v-card> </v-card>
</div> </div>
<div v-if="numKeys(creature.damageMultipliers)">
<damage-multiplier-card :model="creature.damageMultipliers" />
</div>
<div class="saving-throws"> <div class="saving-throws">
<v-card> <v-card>
<v-list> <v-list>
@@ -146,12 +150,12 @@
</div> </div>
<div <div
v-if="weapons.length || tools.length || languages.length" v-if="weapons && weapons.length"
class="proficiencies" class="weapon-proficiencies"
> >
<v-card> <v-card>
<v-list> <v-list>
<v-subheader v-if="weapons.length"> <v-subheader>
Weapons Weapons
</v-subheader> </v-subheader>
<skill-list-tile <skill-list-tile
@@ -162,7 +166,16 @@
:data-id="weapon._id" :data-id="weapon._id"
@click="clickProperty({_id: weapon._id})" @click="clickProperty({_id: weapon._id})"
/> />
<v-subheader v-if="armors.length"> </v-list>
</v-card>
</div>
<div
v-if="armors && armors.length"
class="weapon-proficiencies"
>
<v-card>
<v-list>
<v-subheader>
Armor Armor
</v-subheader> </v-subheader>
<skill-list-tile <skill-list-tile
@@ -173,7 +186,16 @@
:data-id="armor._id" :data-id="armor._id"
@click="clickProperty({_id: armor._id})" @click="clickProperty({_id: armor._id})"
/> />
<v-subheader v-if="tools.length"> </v-list>
</v-card>
</div>
<div
v-if="tools && tools.length"
class="weapon-proficiencies"
>
<v-card>
<v-list>
<v-subheader>
Tools Tools
</v-subheader> </v-subheader>
<skill-list-tile <skill-list-tile
@@ -184,7 +206,16 @@
:data-id="tool._id" :data-id="tool._id"
@click="clickProperty({_id: tool._id})" @click="clickProperty({_id: tool._id})"
/> />
<v-subheader v-if="languages.length"> </v-list>
</v-card>
</div>
<div
v-if="languages && languages.length"
class="language-proficiencies"
>
<v-card>
<v-list>
<v-subheader>
Languages Languages
</v-subheader> </v-subheader>
<skill-list-tile <skill-list-tile
@@ -200,7 +231,7 @@
</div> </div>
<div <div
v-if="actions.length || attacks.length" v-if="actions.length"
class="actions" class="actions"
> >
<v-card> <v-card>
@@ -216,6 +247,18 @@
:data-id="action._id" :data-id="action._id"
@click="clickProperty({_id: action._id})" @click="clickProperty({_id: action._id})"
/> />
</v-list>
</v-card>
</div>
<div
v-if="attacks.length"
class="actions"
>
<v-card>
<v-list
two-line
subheader
>
<v-subheader>Attacks</v-subheader> <v-subheader>Attacks</v-subheader>
<attack-list-tile <attack-list-tile
v-for="attack in attacks" v-for="attack in attacks"
@@ -232,24 +275,27 @@
</template> </template>
<script> <script>
import Creatures from '/imports/api/creature/Creatures.js';
import CreatureProperties, { damageProperty } from '/imports/api/creature/CreatureProperties.js'; import CreatureProperties, { damageProperty } from '/imports/api/creature/CreatureProperties.js';
import AttributeCard from '/imports/ui/properties/components/attributes/AttributeCard.vue'; import AttributeCard from '/imports/ui/properties/components/attributes/AttributeCard.vue';
import AbilityListTile from '/imports/ui/properties/components/attributes/AbilityListTile.vue'; import AbilityListTile from '/imports/ui/properties/components/attributes/AbilityListTile.vue';
import ColumnLayout from '/imports/ui/components/ColumnLayout.vue'; import ColumnLayout from '/imports/ui/components/ColumnLayout.vue';
import HealthBarCardContainer from '/imports/ui/properties/components/attributes/HealthBarCardContainer.vue'; import DamageMultiplierCard from '/imports/ui/properties/components/damageMultipliers/DamageMultiplierCard.vue';
import HealthBarCardContainer from '/imports/ui/properties/components/attributes/HealthBarCardContainer.vue';
import HitDiceListTile from '/imports/ui/properties/components/attributes/HitDiceListTile.vue'; import HitDiceListTile from '/imports/ui/properties/components/attributes/HitDiceListTile.vue';
import SkillListTile from '/imports/ui/properties/components/skills/SkillListTile.vue'; import SkillListTile from '/imports/ui/properties/components/skills/SkillListTile.vue';
import ResourceCard from '/imports/ui/properties/components/attributes/ResourceCard.vue'; import ResourceCard from '/imports/ui/properties/components/attributes/ResourceCard.vue';
import SpellSlotListTile from '/imports/ui/properties/components/attributes/SpellSlotListTile.vue'; import SpellSlotListTile from '/imports/ui/properties/components/attributes/SpellSlotListTile.vue';
import ActionListTile from '/imports/ui/properties/components/actions/ActionListTile.vue'; import ActionListTile from '/imports/ui/properties/components/actions/ActionListTile.vue';
import AttackListTile from '/imports/ui/properties/components/actions/AttackListTile.vue'; import AttackListTile from '/imports/ui/properties/components/actions/AttackListTile.vue';
import getActiveProperties from '/imports/api/creature/getActiveProperties.js';
const getProperties = function(creatureId, filter = {}){ const getProperties = function(creatureId, filter){
filter['ancestors.id'] = creatureId; return getActiveProperties({
filter.removed = {$ne: true}; ancestorId: creatureId,
return CreatureProperties.find(filter, { filter,
sort: {order: 1} options: {sort: {order: 1}},
}); });
}; };
const getAttributeOfType = function(creatureId, type){ const getAttributeOfType = function(creatureId, type){
@@ -271,6 +317,7 @@
AbilityListTile, AbilityListTile,
AttributeCard, AttributeCard,
ColumnLayout, ColumnLayout,
DamageMultiplierCard,
HealthBarCardContainer, HealthBarCardContainer,
HitDiceListTile, HitDiceListTile,
SkillListTile, SkillListTile,
@@ -286,6 +333,9 @@
}, },
}, },
meteor: { meteor: {
creature(){
return Creatures.findOne(this.creatureId);
},
abilities(){ abilities(){
return getAttributeOfType(this.creatureId, 'ability'); return getAttributeOfType(this.creatureId, 'ability');
}, },
@@ -345,6 +395,10 @@
damageProperty.call({_id, operation: 'increment' ,value: -value}); damageProperty.call({_id, operation: 'increment' ,value: -value});
} }
}, },
numKeys(obj){
if (!obj) return 0;
return Object.keys(obj).length;
},
}, },
}; };
</script> </script>

View File

@@ -1,10 +1,20 @@
<template lang="html"> <template lang="html">
<div class="tree-tab"> <div
class="tree-tab pa-4"
style="height: calc(100vh - 96px); display: flex;"
>
<v-card <v-card
class="ma-4 layout row" class="layout row"
style="height: 100%;"
data-id="creature-tree-card" data-id="creature-tree-card"
> >
<div> <div
class="layout column justify-start"
:style="
$vuetify.breakpoint.mdAndUp &&
'width: 320px; flex-shrink: 0; flex-grow: 0;'
"
>
<v-toolbar <v-toolbar
flat flat
dense dense
@@ -17,60 +27,79 @@
:disabled="organizeDisabled" :disabled="organizeDisabled"
style="flex-grow: 0; height: 32px;" style="flex-grow: 0; height: 32px;"
/> />
<v-combobox
ref="searchBox"
slot="extension"
v-model="filterString"
:items="filterOptions"
prepend-inner-icon="search"
class="mx-4"
hide-no-data
hide-selected
multiple
clearable
small-chips
deletable-chips
/>
</v-toolbar> </v-toolbar>
<v-combobox
ref="searchBox"
v-model="filterString"
:items="filterOptions"
prepend-inner-icon="search"
class="mx-4"
hide-no-data
hide-selected
multiple
clearable
small-chips
deletable-chips
/>
<creature-properties-tree <creature-properties-tree
class="pt-0" class="pt-2 flex"
style="overflow-y: auto;"
:root="{collection: 'creatures', id: creatureId}" :root="{collection: 'creatures', id: creatureId}"
:organize="organize" :organize="organize"
:selected-node-id="selected" :selected-node-id="selected"
:filter="filter" :filter="filter"
style="min-width: 320px;" @selected="clickNode"
@selected="e => selected = e"
/> />
</div> </div>
<v-divider vertical /> <template v-if="$vuetify.breakpoint.mdAndUp">
<div <v-divider vertical />
style="width: 100%; background-color: inherit;" <div
data-id="selected-node-card" class="flex layout column"
> style="background-color: inherit; overflow: hidden;"
<v-toolbar data-id="selected-node-card"
dense
flat
> >
<property-icon <v-toolbar
:type="selectedProperty && selectedProperty.type" dense
class="mr-2"
/>
<div class="title">
{{ getPropertyName(selectedProperty && selectedProperty.type) }}
</div>
<v-spacer />
<v-btn
v-if="selectedProperty"
flat flat
icon extended
@click="editCreatureProperty"
> >
<v-icon>create</v-icon> <v-fade-transition mode="out-in">
</v-btn> <div
</v-toolbar> :key="selectedProperty && selectedProperty._id"
<v-card-text> class="title"
<property-viewer :model="selectedProperty" /> >
</v-card-text> <property-icon
</div> :key="selectedProperty && selectedProperty._id"
:type="selectedProperty && selectedProperty.type"
class="mr-2"
/>
{{ getPropertyName(selectedProperty && selectedProperty.type) }}
</div>
</v-fade-transition>
<v-spacer />
<v-btn
v-if="selectedProperty"
flat
icon
@click="editCreatureProperty"
>
<v-icon>create</v-icon>
</v-btn>
</v-toolbar>
<v-card-text
class="flex"
style="overflow-y: auto"
>
<v-fade-transition mode="out-in">
<property-viewer
:key="selectedProperty && selectedProperty._id"
:model="selectedProperty"
/>
</v-fade-transition>
</v-card-text>
</div>
</template>
</v-card> </v-card>
<v-speed-dial <v-speed-dial
v-model="fab" v-model="fab"
@@ -107,138 +136,157 @@
<script> <script>
import CreaturePropertiesTree from '/imports/ui/creature/creatureProperties/CreaturePropertiesTree.vue'; import CreaturePropertiesTree from '/imports/ui/creature/creatureProperties/CreaturePropertiesTree.vue';
import CreatureProperties, { import CreatureProperties, {
insertProperty, insertProperty,
insertPropertyFromLibraryNode insertPropertyFromLibraryNode
} from '/imports/api/creature/CreatureProperties.js'; } from '/imports/api/creature/CreatureProperties.js';
import PropertyViewer from '/imports/ui/properties/shared/PropertyViewer.vue'; import PropertyViewer from '/imports/ui/properties/shared/PropertyViewer.vue';
import { setDocToLastOrder } from '/imports/api/parenting/order.js'; import { setDocToLastOrder } from '/imports/api/parenting/order.js';
import PropertyIcon from '/imports/ui/properties/shared/PropertyIcon.vue'; import PropertyIcon from '/imports/ui/properties/shared/PropertyIcon.vue';
import { getPropertyName } from '/imports/constants/PROPERTIES.js'; import { getPropertyName } from '/imports/constants/PROPERTIES.js';
import LabeledFab from '/imports/ui/components/LabeledFab.vue'; import LabeledFab from '/imports/ui/components/LabeledFab.vue';
export default { export default {
components: { components: {
CreaturePropertiesTree, CreaturePropertiesTree,
PropertyViewer, PropertyViewer,
PropertyIcon, PropertyIcon,
LabeledFab, LabeledFab,
}, },
props: { props: {
creatureId: { creatureId: {
type: String, type: String,
}, required: true,
}, },
data(){ return { },
organize: false, data(){ return {
organizeDisabled: false, organize: false,
selected: undefined, organizeDisabled: false,
fab: false, selected: undefined,
filterString: '', fab: false,
filterOptions: [ filterString: '',
{text: 'Actions', value: 'action'}, filterOptions: [
{text: 'Attacks', value: 'attack'}, {text: 'Actions', value: 'action'},
{text: 'Attributes', value: 'attribute'}, {text: 'Attacks', value: 'attack'},
{text: 'Buffs', value: 'buff'}, {text: 'Attributes', value: 'attribute'},
{text: 'Class Levels', value: 'classLevel'}, {text: 'Buffs', value: 'buff'},
{text: 'Damage Multipliers', value: 'damageMultiplier'}, {text: 'Class Levels', value: 'classLevel'},
{text: 'Effects', value: 'effect'}, {text: 'Damage Multipliers', value: 'damageMultiplier'},
{text: 'Experiences', value: 'experience'}, {text: 'Effects', value: 'effect'},
{text: 'Features', value: 'feature'}, {text: 'Experiences', value: 'experience'},
{text: 'Folders', value: 'folder'}, {text: 'Features', value: 'feature'},
{text: 'Notes', value: 'note'}, {text: 'Folders', value: 'folder'},
{text: 'Proficiencies', value: 'proficiency'}, {text: 'Notes', value: 'note'},
{text: 'Rolls', value: 'roll'}, {text: 'Proficiencies', value: 'proficiency'},
{text: 'Saving Throws', value: 'savingThrow'}, {text: 'Rolls', value: 'roll'},
{text: 'Skills', value: 'skill'}, {text: 'Saving Throws', value: 'savingThrow'},
{text: 'Spell Lists', value: 'spellList'}, {text: 'Skills', value: 'skill'},
{text: 'Spells', value: 'spell'}, {text: 'Spell Lists', value: 'spellList'},
{text: 'Containers', value: 'container'}, {text: 'Spells', value: 'spell'},
{text: 'Items', value: 'item'}, {text: 'Containers', value: 'container'},
], {text: 'Items', value: 'item'},
};}, ],
computed: { };},
filter(){ computed: {
if (!this.filterString.length) return; filter(){
let typeFilters = []; if (!this.filterString.length) return;
let nameFilters = []; let typeFilters = [];
this.filterString.forEach(filter => { let nameFilters = [];
if (filter.value){ this.filterString.forEach(filter => {
typeFilters.push(filter.value); if (filter.value){
} else { typeFilters.push(filter.value);
// escape string } else {
let term = filter.replace( /[-/\\^$*+?.()|[\]{}]/g, '\\$&' ); // escape string
let term = filter.replace( /[-/\\^$*+?.()|[\]{}]/g, '\\$&' );
var reg = new RegExp( '.*' + term + '.*', 'i' ); var reg = new RegExp( '.*' + term + '.*', 'i' );
nameFilters.push(reg) nameFilters.push(reg)
} }
}); });
return {$or: [ return {$or: [
{type: {$in: typeFilters}}, {type: {$in: typeFilters}},
{name: {$in: nameFilters}}, {name: {$in: nameFilters}},
]}; ]};
}, },
}, },
watch: { watch: {
filter(filter){ filter(filter){
if (filter) { if (filter) {
this.organize = false; this.organize = false;
this.organizeDisabled = true; this.organizeDisabled = true;
} else { } else {
this.organizeDisabled = false; this.organizeDisabled = false;
} }
}, },
}, '$vuetify.breakpoint.mdAndUp'(mdAndUp){
methods: { if (!mdAndUp){
insertCreatureProperty(){ this.selected = undefined;
let that = this; }
this.$store.commit('pushDialogStack', { },
component: 'creature-property-creation-dialog', },
elementId: 'insert-creature-property-fab', methods: {
callback(creatureProperty){ clickNode(id){
if (!creatureProperty) return; if (this.$vuetify.breakpoint.mdAndUp){
creatureProperty.parent = {collection: 'creatures', id: that.creatureId}; this.selected = id;
creatureProperty.ancestors = [ {collection: 'creatures', id: that.creatureId}]; } else {
setDocToLastOrder({collection: CreatureProperties, doc: creatureProperty}); this.$store.commit('pushDialogStack', {
let creaturePropertyId = insertProperty.call({creatureProperty}); component: 'creature-property-dialog',
return creaturePropertyId; elementId: `tree-node-${id}`,
} data: {
}); _id: id,
}, },
propertyFromLibrary(){ });
let that = this; }
this.$store.commit('pushDialogStack', { },
component: 'creature-property-from-library-dialog', insertCreatureProperty(){
elementId: 'insert-creature-property-fab', let that = this;
callback(libraryNode){ this.$store.commit('pushDialogStack', {
if (!libraryNode) return; component: 'creature-property-creation-dialog',
insertPropertyFromLibraryNode.call({ elementId: 'insert-creature-property-fab',
nodeId: libraryNode._id, callback(creatureProperty){
parentRef: {collection: 'creatures', id: that.creatureId}, if (!creatureProperty) return;
}); creatureProperty.parent = {collection: 'creatures', id: that.creatureId};
} creatureProperty.ancestors = [ {collection: 'creatures', id: that.creatureId}];
}); setDocToLastOrder({collection: CreatureProperties, doc: creatureProperty});
}, let creaturePropertyId = insertProperty.call({creatureProperty});
editCreatureProperty(){ return creaturePropertyId;
this.$store.commit('pushDialogStack', { }
component: 'creature-property-dialog', });
elementId: 'selected-node-card', },
data: { propertyFromLibrary(){
_id: this.selected, let that = this;
startInEditTab: true, this.$store.commit('pushDialogStack', {
}, component: 'creature-property-from-library-dialog',
}); elementId: 'insert-creature-property-fab',
}, callback(libraryNode){
getPropertyName, if (!libraryNode) return;
}, insertPropertyFromLibraryNode.call({
meteor: { nodeId: libraryNode._id,
selectedProperty(){ parentRef: {collection: 'creatures', id: that.creatureId},
return CreatureProperties.findOne({ });
_id: this.selected, }
removed: {$ne: true} });
}); },
} editCreatureProperty(){
} this.$store.commit('pushDialogStack', {
}; component: 'creature-property-dialog',
elementId: 'selected-node-card',
data: {
_id: this.selected,
startInEditTab: true,
},
});
},
getPropertyName,
},
meteor: {
selectedProperty(){
return CreatureProperties.findOne({
_id: this.selected,
removed: {$ne: true}
});
}
}
};
</script> </script>
<style lang="css" scoped> <style lang="css" scoped>

View File

@@ -1,16 +1,14 @@
<template lang="html"> <template lang="html">
<v-card-text style="width: initial; max-width: 100%;"> <tree-node-list
<tree-node-list v-if="root"
v-if="root" :children="children"
:children="children" :group="group"
:group="group" :organize="organize"
:organize="organize" :selected-node-id="selectedNodeId"
:selected-node-id="selectedNodeId" @selected="e => $emit('selected', e)"
@selected="e => $emit('selected', e)" @reordered="reordered"
@reordered="reordered" @reorganized="reorganized"
@reorganized="reorganized" />
/>
</v-card-text>
</template> </template>
<script> <script>

View File

@@ -5,9 +5,9 @@
:type="model.type" :type="model.type"
class="mr-2" class="mr-2"
/> />
<div class="title"> <v-toolbar-title>
{{ model.name || getPropertyName(model.type) }} {{ model.name || getPropertyName(model.type) }}
</div> </v-toolbar-title>
<v-spacer /> <v-spacer />
<v-menu <v-menu
v-if="editing" v-if="editing"

View File

@@ -1,20 +1,24 @@
<template lang="html"> <template lang="html">
<dialog-base> <dialog-base>
<div slot="toolbar">Add from library</div> <v-toolbar-title slot="toolbar">
<library-and-node Add from library
slot="unwrapped-content" </v-toolbar-title>
@selected="val => node = val" <library-and-node
style="height: 100%;" slot="unwrapped-content"
/> style="height: 100%;"
<template slot="actions"> @selected="val => node = val"
<v-spacer/> />
<v-btn <template slot="actions">
flat <v-spacer />
@click="$store.dispatch('popDialogStack', node)" <v-btn
color="primary" flat
>Insert</v-btn> color="primary"
</template> @click="$store.dispatch('popDialogStack', node)"
</dialog-base> >
Insert
</v-btn>
</template>
</dialog-base>
</template> </template>
<script> <script>

View File

@@ -1,27 +1,31 @@
<template lang="html"> <template lang="html">
<dialog-base :override-back-button="() => $emit('back')"> <dialog-base :override-back-button="() => $emit('back')">
<div slot="toolbar">Add {{propertyName}}</div> <v-toolbar-title slot="toolbar">
<component Add {{ propertyName }}
v-if="type" </v-toolbar-title>
:is="type" <component
class="creature-property-form" :is="type"
:model="model" v-if="type"
:errors="errors" class="creature-property-form"
@change="change" :model="model"
@push="push" :errors="errors"
@pull="pull" @change="change"
/> @push="push"
<div @pull="pull"
slot="actions" />
class="layout row justify-end" <div
> slot="actions"
<v-btn class="layout row justify-end"
flat >
:disabled="!valid" <v-btn
@click="$store.dispatch('popDialogStack', model)" flat
>Insert</v-btn> :disabled="!valid"
</div> @click="$store.dispatch('popDialogStack', model)"
</dialog-base> >
Insert
</v-btn>
</div>
</dialog-base>
</template> </template>
<script> <script>
@@ -35,6 +39,10 @@ export default {
DialogBase, DialogBase,
}, },
mixins: [schemaFormMixin], mixins: [schemaFormMixin],
props: {
propertyName: String,
type: String,
},
data(){return { data(){return {
model: { model: {
type: this.type, type: this.type,
@@ -42,10 +50,6 @@ export default {
schema: undefined, schema: undefined,
validationContext: undefined, validationContext: undefined,
};}, };},
props: {
propertyName: String,
type: String,
},
watch: { watch: {
type(newType){ type(newType){
if (!newType) return; if (!newType) return;

View File

@@ -1,28 +1,35 @@
<template lang="html"> <template lang="html">
<dialog-base> <dialog-base>
<div slot="toolbar"> <v-toolbar-title slot="toolbar">
Delete {{typeName}} Delete {{ typeName }}
</div> </v-toolbar-title>
<div> <div>
<p v-if="name"> <p v-if="name">
Type "{{name}}" to permanenetly delete Type "{{ name }}" to permanenetly delete
</p> </p>
<v-text-field v-if="name" v-model="inputName"/> <v-text-field
<div class="layout row justify-center"> v-if="name"
<v-btn v-model="inputName"
v-show="nameMatch" />
class="primary" <div class="layout row justify-center">
@click="$store.dispatch('popDialogStack', true);" <v-btn
>Delete forever</v-btn> v-show="nameMatch"
</div> class="primary"
</div> @click="$store.dispatch('popDialogStack', true);"
<v-spacer slot="actions"/> >
<v-btn Delete forever
slot="actions" </v-btn>
flat </div>
@click="$store.dispatch('popDialogStack')" </div>
>Cancel</v-btn> <v-spacer slot="actions" />
</dialog-base> <v-btn
slot="actions"
flat
@click="$store.dispatch('popDialogStack')"
>
Cancel
</v-btn>
</dialog-base>
</template> </template>
<script> <script>

View File

@@ -1,22 +1,34 @@
<template> <template>
<dialog-base> <dialog-base>
<div slot="toolbar"> <v-toolbar-title slot="toolbar">
Test Dialog Test Dialog
</div> </v-toolbar-title>
<div> <div>
<v-btn @click="openDialog('btn')" data-id="btn">Open Dialog</v-btn> <v-btn
<v-btn fab @click="openDialog('fab')" data-id="fab" color="green">Open Dialog</v-btn> data-id="btn"
@click="openDialog('btn')"
>
Open Dialog
</v-btn>
<v-btn
fab
data-id="fab"
color="green"
@click="openDialog('fab')"
>
Open Dialog
</v-btn>
</div> </div>
</dialog-base> </dialog-base>
</template> </template>
<script> <script>
import store from "/imports/ui/vuexStore.js"; import store from '/imports/ui/vuexStore.js';
import DialogBase from "/imports/ui/dialogStack/DialogBase.vue"; import DialogBase from '/imports/ui/dialogStack/DialogBase.vue';
const component = { const component = {
methods: { methods: {
openDialog(elementId){ openDialog(elementId){
store.commit("pushDialogStack", { store.commit('pushDialogStack', {
component, component,
elementId, elementId,
}); });

View File

@@ -3,11 +3,13 @@ import CreaturePropertyCreationDialog from '/imports/ui/creature/creaturePropert
import CreaturePropertyDialog from '/imports/ui/creature/creatureProperties/CreaturePropertyDialog.vue' import CreaturePropertyDialog from '/imports/ui/creature/creatureProperties/CreaturePropertyDialog.vue'
import CreaturePropertyFromLibraryDialog from '/imports/ui/creature/creatureProperties/CreaturePropertyFromLibraryDialog.vue' import CreaturePropertyFromLibraryDialog from '/imports/ui/creature/creatureProperties/CreaturePropertyFromLibraryDialog.vue'
import DeleteConfirmationDialog from '/imports/ui/dialogStack/DeleteConfirmationDialog.vue'; import DeleteConfirmationDialog from '/imports/ui/dialogStack/DeleteConfirmationDialog.vue';
import InviteDialog from '/imports/ui/user/InviteDialog.vue';
import LibraryCreationDialog from '/imports/ui/library/LibraryCreationDialog.vue'; import LibraryCreationDialog from '/imports/ui/library/LibraryCreationDialog.vue';
import LibraryEditDialog from '/imports/ui/library/LibraryEditDialog.vue'; import LibraryEditDialog from '/imports/ui/library/LibraryEditDialog.vue';
import LibraryNodeCreationDialog from '/imports/ui/library/LibraryNodeCreationDialog.vue'; import LibraryNodeCreationDialog from '/imports/ui/library/LibraryNodeCreationDialog.vue';
import LibraryNodeEditDialog from '/imports/ui/library/LibraryNodeEditDialog.vue'; import LibraryNodeEditDialog from '/imports/ui/library/LibraryNodeEditDialog.vue';
import ShareDialog from '/imports/ui/sharing/ShareDialog.vue'; import ShareDialog from '/imports/ui/sharing/ShareDialog.vue';
import UsernameDialog from '/imports/ui/user/UsernameDialog.vue';
export default { export default {
CreatureFormDialog, CreatureFormDialog,
@@ -15,9 +17,11 @@ export default {
CreaturePropertyDialog, CreaturePropertyDialog,
CreaturePropertyFromLibraryDialog, CreaturePropertyFromLibraryDialog,
DeleteConfirmationDialog, DeleteConfirmationDialog,
InviteDialog,
LibraryCreationDialog, LibraryCreationDialog,
LibraryEditDialog, LibraryEditDialog,
LibraryNodeCreationDialog, LibraryNodeCreationDialog,
LibraryNodeEditDialog, LibraryNodeEditDialog,
ShareDialog, ShareDialog,
UsernameDialog,
}; };

View File

@@ -49,12 +49,24 @@
</v-list-tile> </v-list-tile>
<v-divider /> <v-divider />
</v-list> </v-list>
<v-list dense> <v-list
avatar
>
<v-list-tile <v-list-tile
v-for="character in CreaturesWithNoParty" v-for="character in CreaturesWithNoParty"
:key="character._id" :key="character._id"
:to="character.url" :to="character.url"
> >
<v-list-tile-avatar :color="character.color || 'grey'">
<img
v-if="character.avatarPicture"
:src="character.avatarPicture"
:alt="character.name"
>
<template v-else>
{{ character.initial }}
</template>
</v-list-tile-avatar>
<v-list-tile-title> <v-list-tile-title>
{{ character.name }} {{ character.name }}
</v-list-tile-title> </v-list-tile-title>
@@ -73,6 +85,16 @@
:key="character._id" :key="character._id"
:to="character.url" :to="character.url"
> >
<v-list-tile-avatar :color="character.color || 'grey'">
<img
v-if="character.avatarPicture"
:src="character.avatarPicture"
:alt="character.name"
>
<template v-else>
{{ character.initial }}
</template>
</v-list-tile-avatar>
<v-list-tile-title> <v-list-tile-title>
{{ character.name }} {{ character.name }}
</v-list-tile-title> </v-list-tile-title>
@@ -127,6 +149,7 @@
} }
).map(char => { ).map(char => {
char.url = `/character/${char._id}/${char.urlName || '-'}`; char.url = `/character/${char._id}/${char.urlName || '-'}`;
char.initial = char.name && char.name[0] || '?';
return char; return char;
}); });
return party; return party;
@@ -144,6 +167,7 @@
{sort: {name: 1}} {sort: {name: 1}}
).map(char => { ).map(char => {
char.url = `/character/${char._id}/${char.urlName || '-'}`; char.url = `/character/${char._id}/${char.urlName || '-'}`;
char.initial = char.name && char.name[0] || '?';
return char; return char;
}); });
}, },

View File

@@ -1,39 +1,44 @@
<template lang="html"> <template lang="html">
<dialog-base> <dialog-base>
<template slot="toolbar"> <template slot="toolbar">
<div> <v-toolbar-title>
New Library New Library
</div> </v-toolbar-title>
</template> </template>
<template> <template>
<text-field label="name" :value="library.name" @change="nameChanged" :debounce-time="0"/> <text-field
</template> label="name"
<template slot="actions"> :value="library.name"
<v-spacer/> :debounce-time="0"
<v-btn @change="nameChanged"
flat />
:disabled="!valid" </template>
@click="$store.dispatch('popDialogStack', library)" <template slot="actions">
> <v-spacer />
Insert Library <v-btn
</v-btn> flat
</template> :disabled="!valid"
</dialog-base> @click="$store.dispatch('popDialogStack', library)"
>
Insert Library
</v-btn>
</template>
</dialog-base>
</template> </template>
<script> <script>
import DialogBase from '/imports/ui/dialogStack/DialogBase.vue'; import DialogBase from '/imports/ui/dialogStack/DialogBase.vue';
export default { export default {
components: {
DialogBase,
},
data(){ return { data(){ return {
library: { library: {
name: 'New Library', name: 'New Library',
}, },
valid: true, valid: true,
}}, }},
components: {
DialogBase,
},
methods: { methods: {
nameChanged(val, ack){ nameChanged(val, ack){
if (val){ if (val){

View File

@@ -1,28 +1,45 @@
<template lang="html"> <template lang="html">
<dialog-base> <dialog-base>
<template slot="toolbar"> <template slot="toolbar">
<div> <v-toolbar-title>
{{model && model.name}} {{ model && model.name }}
</div> </v-toolbar-title>
<v-spacer/> <v-spacer />
<v-btn flat icon @click="remove"> <v-btn
<v-icon>delete</v-icon> flat
</v-btn> icon
</template> data-id="share-library-button"
<template v-if="model"> @click="share"
<text-field label="name" :value="model.name" @change="updateName"/> >
</template> <v-icon>share</v-icon>
<template slot="actions"> </v-btn>
<v-spacer/> <v-btn
<v-btn flat
flat icon
@click="$store.dispatch('popDialogStack')" data-id="delete-library-button"
data-id="delete-library-button" @click="remove"
> >
Done <v-icon>delete</v-icon>
</v-btn> </v-btn>
</template> </template>
</dialog-base> <template v-if="model">
<text-field
label="name"
:value="model.name"
@change="updateName"
/>
</template>
<template slot="actions">
<v-spacer />
<v-btn
flat
data-id="delete-library-button"
@click="$store.dispatch('popDialogStack')"
>
Done
</v-btn>
</template>
</dialog-base>
</template> </template>
<script> <script>
@@ -38,7 +55,7 @@ export default {
}, },
methods: { methods: {
updateName(value, ack){ updateName(value, ack){
updateLibraryName.call({_id: this._id, name: value}, (error, result) =>{ updateLibraryName.call({_id: this._id, name: value}, (error) =>{
ack(error && error.reason || error); ack(error && error.reason || error);
}); });
}, },
@@ -53,7 +70,7 @@ export default {
}, },
callback(confirmation){ callback(confirmation){
if(!confirmation) return; if(!confirmation) return;
removeLibrary.call({_id: that._id}, (error, result) => { removeLibrary.call({_id: that._id}, (error) => {
if (error) { if (error) {
console.error(error); console.error(error);
} else { } else {
@@ -63,6 +80,18 @@ export default {
} }
}); });
}, },
share(){
this.$store.commit('pushDialogStack', {
component: 'share-dialog',
elementId: 'share-library-button',
data: {
docRef: {
id: this._id,
collection: 'libraries',
}
},
});
},
}, },
meteor: { meteor: {
model(){ model(){

View File

@@ -1,35 +1,43 @@
<template lang="html"> <template lang="html">
<dialog-base> <dialog-base>
<template slot="toolbar"> <template slot="toolbar">
<property-icon :type="model.type" class="mr-2"/> <property-icon
<div class="title"> :type="model.type"
{{getPropertyName(model.type)}} class="mr-2"
</div> />
<v-spacer/> <v-toolbar-title>
<v-btn icon flat @click="remove"> {{ getPropertyName(model.type) }}
<v-icon>delete</v-icon> </v-toolbar-title>
</v-btn> <v-spacer />
</template> <v-btn
<component icon
v-if="model" flat
class="library-node-form" @click="remove"
stored >
:is="model.type" <v-icon>delete</v-icon>
:model="model" </v-btn>
@change="change" </template>
@push="push" <component
@pull="pull" :is="model.type"
/> v-if="model"
<div class="library-node-form"
slot="actions" :model="model"
class="layout row justify-end" @change="change"
> @push="push"
<v-btn @pull="pull"
flat />
@click="$store.dispatch('popDialogStack')" <div
>Done</v-btn> slot="actions"
</div> class="layout row justify-end"
</dialog-base> >
<v-btn
flat
@click="$store.dispatch('popDialogStack')"
>
Done
</v-btn>
</div>
</dialog-base>
</template> </template>
<script> <script>

View File

@@ -1,28 +1,31 @@
<template lang="html"> <template lang="html">
<dialog-base :override-back-button="() => $emit('back')"> <dialog-base :override-back-button="() => $emit('back')">
<div slot="toolbar">Add {{propertyName}}</div> <v-toolbar-title slot="toolbar">
<component Add {{ propertyName }}
v-if="type" </v-toolbar-title>
stored <component
:is="type" :is="type"
class="library-node-form" v-if="type"
:model="model" class="library-node-form"
:errors="errors" :model="model"
@change="change" :errors="errors"
@push="push" @change="change"
@pull="pull" @push="push"
/> @pull="pull"
<div />
slot="actions" <div
class="layout row justify-end" slot="actions"
> class="layout row justify-end"
<v-btn >
flat <v-btn
:disabled="!valid" flat
@click="$store.dispatch('popDialogStack', model)" :disabled="!valid"
>Insert</v-btn> @click="$store.dispatch('popDialogStack', model)"
</div> >
</dialog-base> Insert
</v-btn>
</div>
</dialog-base>
</template> </template>
<script> <script>
@@ -37,6 +40,10 @@ export default {
DialogBase, DialogBase,
}, },
mixins: [schemaFormMixin], mixins: [schemaFormMixin],
props: {
propertyName: String,
type: String,
},
data(){return { data(){return {
model: { model: {
type: this.type, type: this.type,
@@ -44,10 +51,6 @@ export default {
schema: undefined, schema: undefined,
validationContext: undefined, validationContext: undefined,
};}, };},
props: {
propertyName: String,
type: String,
},
watch: { watch: {
type(newType){ type(newType){
if (!newType) return; if (!newType) return;

View File

@@ -0,0 +1,121 @@
<template lang="html">
<div
class="layout row"
style="background-color: inherit;"
>
<div
class="layout column"
style="
background-color: inherit;
width: initial;
max-width: 100%;
min-width: 320px;
"
>
<v-toolbar
dense
flat
>
<v-spacer />
<v-switch
v-model="organize"
label="Organize"
class="mx-3"
style="flex-grow: 0; height: 32px;"
/>
</v-toolbar>
<library-contents-container
:library-id="$route.params.id"
:organize-mode="organize"
:selected-node-id="selected"
@selected="e => selected = e"
/>
</div>
<v-divider vertical />
<div
style="width: 100%; background-color: inherit;"
data-id="selected-node-card"
>
<v-toolbar
dense
flat
>
<property-icon
:type="selectedNode && selectedNode.type"
class="mr-2"
/>
<div class="title">
{{ getPropertyName(selectedNode && selectedNode.type) }}
</div>
<v-spacer />
<v-btn
v-if="selectedNode"
flat
icon
@click="editLibraryNode"
>
<v-icon>create</v-icon>
</v-btn>
</v-toolbar>
<v-card-text style="overflow-y: auto;">
<property-viewer :model="selectedNode" />
</v-card-text>
</div>
</div>
</template>
<script>
import PropertyViewer from '/imports/ui/properties/shared/PropertyViewer.vue';
import LibraryNodes from '/imports/api/library/LibraryNodes.js';
import Libraries from '/imports/api/library/Libraries.js';
import PropertyIcon from '/imports/ui/properties/shared/PropertyIcon.vue';
import { getPropertyName } from '/imports/constants/PROPERTIES.js';
import LibraryContentsContainer from '/imports/ui/library/LibraryContentsContainer.vue';
export default {
components: {
LibraryContentsContainer,
PropertyViewer,
PropertyIcon,
},
data(){ return {
organize: false,
selected: undefined,
};},
watch:{
selectedNode(val){
this.$emit('selected', val)
},
'library.name'(value){
this.$store.commit('setPageTitle', value || 'Library');
},
},
methods: {
editLibraryNode(){
this.$store.commit('pushDialogStack', {
component: 'library-node-edit-dialog',
elementId: 'selected-node-card',
data: {_id: this.selected},
});
},
getPropertyName,
},
meteor: {
$subscribe: {
'libraries': [],
},
library(){
return Libraries.findOne(this.$route.params.id);
},
selectedNode(){
return LibraryNodes.findOne({
_id: this.selected,
removed: {$ne: true}
});
}
}
};
</script>
<style lang="css" scoped>
</style>

View File

@@ -0,0 +1,88 @@
<template lang="html">
<v-toolbar-items>
<v-btn
v-if="showSubscribeButton"
flat
:loading="loading"
@click="subscribe(!subscribed)"
>
{{ subscribed ? 'Unsubscribe' : 'Subscribe' }}
</v-btn>
<v-btn
v-if="canEdit"
flat
icon
data-id="library-edit-button"
@click="editLibrary(library._id)"
>
<v-icon>create</v-icon>
</v-btn>
</v-toolbar-items>
</template>
<script>
import Libraries from '/imports/api/library/Libraries.js';
import { assertDocEditPermission } from '/imports/api/sharing/sharingPermissions.js';
export default {
data(){ return {
loading: false,
}},
meteor: {
library(){
console.log(this.$route);
return Libraries.findOne(this.$route.params.id);
},
subscribed(){
let libraryId = this.$route.params.id;
let subs = Meteor.user().subscribedLibraries;
return subs.includes(libraryId);
},
showSubscribeButton(){
let userId = Meteor.userId();
let library = this.library;
if (!library) return;
console.log({library, userId});
if (
library.readers.includes(userId) ||
library.writers.includes(userId) ||
library.owner === userId
) {
return false
} else {
return true;
}
},
canEdit(){
try {
assertDocEditPermission(this.library, Meteor.userId());
console.log('can edit');
return true
} catch (e) {
console.log(e);
return false;
}
}
},
methods: {
subscribe(value){
this.loading = true;
Meteor.users.subscribeToLibrary.call({
libraryId: this.$route.params.id,
subscribe: value,
}, () => {
this.loading = false;
});
},
editLibrary(){
this.$store.commit('pushDialogStack', {
component: 'library-edit-dialog',
elementId: 'library-edit-button',
data: {_id: this.$route.params.id},
});
},
},
}
</script>
<style lang="css" scoped>
</style>

View File

@@ -16,7 +16,7 @@
<v-subheader> <v-subheader>
Username Username
</v-subheader> </v-subheader>
<v-list-tile> <v-list-tile data-id="username">
<v-list-tile-action> <v-list-tile-action>
<v-tooltip right> <v-tooltip right>
<span>Change Username</span> <span>Change Username</span>
@@ -24,6 +24,7 @@
slot="activator" slot="activator"
icon icon
flat flat
@click="changeUsername"
> >
<v-icon>create</v-icon> <v-icon>create</v-icon>
</v-btn> </v-btn>
@@ -48,39 +49,70 @@
<v-subheader> <v-subheader>
Patreon Patreon
</v-subheader> </v-subheader>
<template v-if="user.services.patreon"> <v-list-tile>
<v-list-tile> <v-list-tile-title>
<v-list-tile-title> Tier: {{ tier.name }}
Pledged amount: ${{ entitledCents/100 }} </v-list-tile-title>
</v-list-tile-title> </v-list-tile>
<v-list-tile-action> <v-list-tile v-if="!user.services.google">
<v-btn icon> <v-btn
<v-icon>refresh</v-icon> color="primary"
</v-btn> @click="linkWithGoogle"
</v-list-tile-action> >
</v-list-tile> Link Google Account
<v-list-tile> </v-btn>
<v-list-tile-title> </v-list-tile>
Tier: {{ tier.name }} <v-list-tile v-if="!user.services.patreon">
</v-list-tile-title> <v-btn
</v-list-tile> color="primary"
</template> @click="linkWithPatreon"
<v-list-tile v-else> >
<v-btn @click="linkWithPatreon"> Link Patreon Account
Link Patreon
</v-btn> </v-btn>
</v-list-tile> </v-list-tile>
</v-list> </v-list>
<v-card-actions> <v-layout
<v-spacer /> row
justify-end
>
<v-btn <v-btn
flat
color="accent" color="accent"
@click="signOut" @click="signOut"
> >
Sign Out Sign Out
</v-btn> </v-btn>
</v-card-actions> </v-layout>
<template v-if="invites.length">
<v-divider class="mt-3 mb-3" />
<v-subheader>
<h1>
Invites
</h1>
</v-subheader>
<v-list>
<template
v-for="(invite, index) in invites"
>
<v-list-tile
:key="invite._id"
:data-id="invite._id"
@click="clickInvite(invite)"
>
<v-list-tile-content>
<v-list-tile-title>
{{ invite.inviteeName || invite.invitee || 'Available' }}
</v-list-tile-title>
</v-list-tile-content>
<v-list-tile-action>
<v-icon>mail_outline</v-icon>
</v-list-tile-action>
</v-list-tile>
<v-divider
:key="index"
/>
</template>
</v-list>
</template>
</v-card> </v-card>
</div> </div>
</template> </template>
@@ -95,7 +127,10 @@
export default { export default {
meteor: { meteor: {
$subscribe: { $subscribe: {
'user': [], 'userPublicProfiles'(){
if (!this.invites) return false;
return [this.invites.map(i => i.invitee).filter(i => !!i)];
},
}, },
user(){ user(){
return Meteor.user(); return Meteor.user();
@@ -108,9 +143,23 @@
const user = Meteor.user(); const user = Meteor.user();
return user && user.emails; return user && user.emails;
}, },
darkMode(){ darkMode(){
return this.user && this.user.darkMode; return this.user && this.user.darkMode;
}, },
invites(){
let usernames = {};
Meteor.users.find({}).forEach(user => {
usernames[user._id] = user.username;
});
return Invites.find({
inviter: Meteor.userId(),
}, {
sort: {dateConfirmed: 1, invitee: -1},
}).map(invite => {
invite.inviteeName = usernames[invite.invitee];
return invite;
});
},
}, },
data(){ return { data(){ return {
showApiKey: false, showApiKey: false,
@@ -127,13 +176,19 @@
}, },
}, },
methods: { methods: {
changeUsername(){
this.$store.commit('pushDialogStack', {
component: 'username-dialog',
elementId: 'username',
});
},
signOut(){ signOut(){
Meteor.logout(); Meteor.logout();
router.push('/'); router.push('/');
}, },
setDarkMode(value){ setDarkMode(value){
Meteor.users.setDarkMode.call({darkMode: !!value}); Meteor.users.setDarkMode.call({darkMode: !!value});
}, },
generateKey(){ generateKey(){
Meteor.users.gnerateApiKey.call(error => { Meteor.users.gnerateApiKey.call(error => {
if(error) this.apiKeyGenerationError = error.reason; if(error) this.apiKeyGenerationError = error.reason;
@@ -145,6 +200,18 @@
if(error) this.emailVerificationError = error.reason; if(error) this.emailVerificationError = error.reason;
}); });
}, },
clickInvite(invite){
this.$store.commit('pushDialogStack', {
component: 'invite-dialog',
elementId: invite._id,
data: {inviteId: invite._id},
});
},
linkWithGoogle(){
Meteor.linkWithGoogle(error => {
if (error) console.error(error);
});
},
linkWithPatreon, linkWithPatreon,
}, },
} }

View File

@@ -7,11 +7,11 @@
:key="character._id" :key="character._id"
:to="character.url" :to="character.url"
> >
<v-list-tile-avatar :color="character.color"> <v-list-tile-avatar :color="character.color || 'grey'">
<img <img
v-if="character.picture" v-if="character.avatarPicture"
:src="character.picture" :src="character.avatarPicture"
alt="character.name" :alt="character.name"
> >
<template v-else> <template v-else>
{{ character.initial }} {{ character.initial }}

View File

@@ -0,0 +1,44 @@
<template lang="html">
<div
class="layout column align-center pa-2"
>
<v-card>
<iframe
src="https://discordapp.com/widget?id=120762305087668224&theme=dark"
width="100%"
height="500"
allowtransparency="true"
frameborder="0"
/>
<v-card-title primary-title>
<div>
<h3 class="headline mb-0">
DiceCloud Discord server
</h3>
<div>
To give feedback or get support using DiceCloud,
join the official Discord server
</div>
</div>
</v-card-title>
<v-card-actions>
<v-spacer />
<v-btn
flat
color="primary"
href="https://discord.gg/qEvdfeB"
>
Join
</v-btn>
</v-card-actions>
</v-card>
</div>
</template>
<script>
export default {
}
</script>
<style lang="css" scoped>
</style>

View File

@@ -1,8 +1,5 @@
<template> <template>
<div> <div>
<div slot="toolbar">
Friends
</div>
<v-sheet> <v-sheet>
<h1> <h1>
Friends Friends

View File

@@ -100,7 +100,7 @@
large large
to="/sign-in" to="/sign-in"
> >
Sign up Sign In
</v-btn> </v-btn>
</v-layout> </v-layout>
</section> </section>

View File

@@ -0,0 +1,30 @@
<template lang="html">
<div>
<v-layout
column
align-center
justify-center
>
<h2 style="margin: 48px 28px 16px">
Invite Error
</h2>
<h3>
{{ error.reason || error.message || error }}
</h3>
</v-layout>
</div>
</template>
<script>
export default {
props: {
error: {
type: [Object, String],
default: '',
}
}
}
</script>
<style lang="css" scoped>
</style>

View File

@@ -0,0 +1,24 @@
<template lang="html">
<div>
<v-layout
column
align-center
justify-center
>
<h2 style="margin: 48px 28px 16px">
Invite Success
</h2>
<h3>
You can now use DiceCloud
</h3>
</v-layout>
</div>
</template>
<script>
export default {
}
</script>
<style lang="css" scoped>
</style>

View File

@@ -4,7 +4,7 @@
:value="true" :value="true"
type="info" type="info"
> >
This page is not available in this version of the alpha. This page is not available in this version of the beta.
</v-alert> </v-alert>
</div> </div>
</template> </template>

View File

@@ -6,25 +6,26 @@
justify-center justify-center
> >
<h2 style="margin: 48px 28px 16px"> <h2 style="margin: 48px 28px 16px">
Your current patreon support is ${{ entitledDollars }}. Your current Patreon tier is {{ tier.name }}
</h2>
<h2 style="margin: 16px 28px">
You need to pledge at least $5 to use this beta.
</h2> </h2>
<h3>
You need to be at least Adventurer tier (or be invited by a Patron of
a higher tier) to access this beta
</h3>
</v-layout> </v-layout>
</div> </div>
</template> </template>
<script> <script>
import TIERS, { getUserTier } from '/imports/api/users/patreon/tiers.js';
export default { export default {
meteor: { meteor: {
entitledDollars(){ tier(){
let user = Meteor.user(); let user = Meteor.user();
if (!user) return 0; if (!user) return TIERS[0];
let entitledCents = user.services.patreon.entitledCents || 0; return getUserTier(user);
let overrideCents = user.services.patreon.entitledCentsOverride || 0;
return Math.max(entitledCents, overrideCents)/100;
} }
} },
} }
</script> </script>

View File

@@ -1,8 +1,5 @@
<template> <template>
<div> <div>
<div slot="toolbar">
Sign Up
</div>
<v-form <v-form
ref="form" ref="form"
class="mt-4" class="mt-4"
@@ -81,7 +78,6 @@
</template> </template>
<script> <script>
import router from '/imports/ui/router.js';
export default{ export default{
data() { data() {
return { return {
@@ -119,7 +115,7 @@
if (error){ if (error){
this.error = error.reason; this.error = error.reason;
} else { } else {
router.push('characterList'); this.$router.push(this.$route.query.redirect || 'characterList');
} }
}); });
} }

View File

@@ -13,7 +13,6 @@
width="120px" width="120px"
class="ma-3" class="ma-3"
/> />
<!--
<v-text-field <v-text-field
v-model="name" v-model="name"
type="text" type="text"
@@ -46,12 +45,11 @@
</v-btn> </v-btn>
<v-btn <v-btn
color="accent" color="accent"
to="/register" :to="{ name: 'register', query: { redirect: this.$route.query.redirect} }"
> >
Register Register
</v-btn> </v-btn>
</v-layout> </v-layout>
-->
</v-layout> </v-layout>
</v-form> </v-form>
<v-divider class="ma-4" /> <v-divider class="ma-4" />
@@ -59,7 +57,6 @@
column column
align-center align-center
> >
<!--
<div class="error--text"> <div class="error--text">
{{ googleError }} {{ googleError }}
</div> </div>
@@ -69,7 +66,6 @@
> >
Sign in with Google Sign in with Google
</v-btn> </v-btn>
-->
<div class="error--text"> <div class="error--text">
{{ patreonError }} {{ patreonError }}
</div> </div>
@@ -85,7 +81,6 @@
<script> <script>
import { Meteor } from 'meteor/meteor' import { Meteor } from 'meteor/meteor'
import router from '/imports/ui/router.js';
export default{ export default{
data: () => ({ data: () => ({
valid: true, valid: true,
@@ -108,7 +103,7 @@
if (error){ if (error){
this.error = error.reason; this.error = error.reason;
} else { } else {
router.push('characterList'); this.$router.push(this.$route.query.redirect || 'characterList');
} }
}); });
} }
@@ -119,7 +114,7 @@
console.error(error); console.error(error);
this.googleError = error.message; this.googleError = error.message;
} else { } else {
router.push('characterList'); this.$router.push(this.$route.query.redirect || 'characterList');
} }
}); });
}, },
@@ -129,7 +124,7 @@
console.error(error); console.error(error);
this.patreonError = error.message; this.patreonError = error.message;
} else { } else {
router.push('characterList'); this.$router.push(this.$route.query.redirect || 'characterList');
} }
}); });
} }

View File

@@ -0,0 +1,16 @@
<template lang="html">
<div>
<v-card class="ma-4">
<single-library />
</v-card>
</div>
</template>
<script>
import SingleLibrary from '/imports/ui/library/SingleLibrary.vue';
export default {
components: {
SingleLibrary,
},
};
</script>

View File

@@ -7,20 +7,12 @@
<v-list-tile-title> <v-list-tile-title>
{{ model.name }} {{ model.name }}
</v-list-tile-title> </v-list-tile-title>
<v-list-tile-sub-title>
<results :model="model.results" />
</v-list-tile-sub-title>
</v-list-tile-content> </v-list-tile-content>
</v-list-tile> </v-list-tile>
</template> </template>
<script> <script>
import Results from '/imports/ui/properties/components/results/Results.vue';
export default { export default {
components: {
Results,
},
props: { props: {
model: { model: {
type: Object, type: Object,

View File

@@ -15,20 +15,15 @@
<v-list-tile-title> <v-list-tile-title>
{{ model.name }} {{ model.name }}
</v-list-tile-title> </v-list-tile-title>
<v-list-tile-sub-title>
<results :model="model.results" />
</v-list-tile-sub-title>
</v-list-tile-content> </v-list-tile-content>
</v-list-tile> </v-list-tile>
</template> </template>
<script> <script>
import Results from '/imports/ui/properties/components/results/Results.vue';
import ComputedForCreature from '/imports/ui/components/computation/ComputedForCreature.vue'; import ComputedForCreature from '/imports/ui/components/computation/ComputedForCreature.vue';
export default { export default {
components: { components: {
Results,
Computed: ComputedForCreature, Computed: ComputedForCreature,
}, },
props: { props: {

View File

@@ -0,0 +1,74 @@
<template lang="html">
<v-card>
<v-list
three-line
>
<v-list-tile v-if="weaknesses.length">
<v-list-tile-content>
<v-list-tile-title>
Vulnerabilities
</v-list-tile-title>
<v-list-tile-sub-title>
{{ weaknesses }}
</v-list-tile-sub-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile v-if="resistances.length">
<v-list-tile-content>
<v-list-tile-title>
Resistances
</v-list-tile-title>
<v-list-tile-sub-title>
{{ resistances }}
</v-list-tile-sub-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile v-if="immunities.length">
<v-list-tile-content>
<v-list-tile-title>
Immunities
</v-list-tile-title>
<v-list-tile-sub-title>
{{ immunities }}
</v-list-tile-sub-title>
</v-list-tile-content>
</v-list-tile>
</v-list>
</v-card>
</template>
<script>
export default {
props: {
model:{
type: Object,
required: true,
}
},
computed: {
weaknesses(){
return getKeysOfValue(this.model, 2).join(', ');
},
resistances(){
return getKeysOfValue(this.model, 0.5).join(', ');
},
immunities(){
return getKeysOfValue(this.model, 0).join(', ');
},
}
}
function getKeysOfValue(object, value){
let keys = [];
for (let key in object){
if (object[key] === value){
keys.push(key);
}
}
return keys;
}
</script>
<style lang="css" scoped>
</style>

View File

@@ -5,9 +5,9 @@
@click="$emit('click')" @click="$emit('click')"
> >
<template slot="toolbar"> <template slot="toolbar">
<span> <v-toolbar-title>
{{ model.name }} {{ model.name }}
</span> </v-toolbar-title>
<v-spacer /> <v-spacer />
</template> </template>
<v-card-text v-if="model.summary"> <v-card-text v-if="model.summary">

View File

@@ -1,35 +1,40 @@
<template lang="html"> <template lang="html">
<toolbar-card :color="model.color" @toolbarclick="clickContainer(model._id)" :data-id="model._id"> <toolbar-card
<template slot="toolbar"> :color="model.color"
<span> :data-id="model._id"
{{model.name}} @toolbarclick="clickContainer(model._id)"
</span> >
<v-spacer/> <template slot="toolbar">
</template> <v-toolbar-title>
<creature-properties-tree {{ model.name }}
:root="{collection: 'creatureProperties', id: model._id}" </v-toolbar-title>
:filter="{type: {$in: ['container', 'item', 'folder']}}" <v-spacer />
@selected="e => clickProperty(e)" </template>
:organize="organize" <v-card-text class="px-0">
group="inventory" <creature-properties-tree
/> :root="{collection: 'creatureProperties', id: model._id}"
:filter="{type: {$in: ['container', 'item', 'folder']}}"
:organize="organize"
group="inventory"
@selected="e => clickProperty(e)"
/>
</v-card-text>
</toolbar-card> </toolbar-card>
</template> </template>
<script> <script>
import CreatureProperties from '/imports/api/creature/CreatureProperties.js';
import ToolbarCard from '/imports/ui/components/ToolbarCard.vue'; import ToolbarCard from '/imports/ui/components/ToolbarCard.vue';
import CreaturePropertiesTree from '/imports/ui/creature/creatureProperties/CreaturePropertiesTree.vue'; import CreaturePropertiesTree from '/imports/ui/creature/creatureProperties/CreaturePropertiesTree.vue';
export default { export default {
props: {
model: Object,
organize: Boolean,
},
components: { components: {
ToolbarCard, ToolbarCard,
CreaturePropertiesTree, CreaturePropertiesTree,
}, },
props: {
model: Object,
organize: Boolean,
},
methods: { methods: {
clickContainer(_id){ clickContainer(_id){
this.$store.commit('pushDialogStack', { this.$store.commit('pushDialogStack', {

Some files were not shown because too many files have changed in this diff Show More