From e6820b6b18f860fbbd0efadcb6b0c7373a120081 Mon Sep 17 00:00:00 2001 From: derikb Date: Mon, 27 Dec 2021 11:37:09 -0500 Subject: [PATCH] feat(docs): Add updating info BREAKING CHANGE: See README for breaking change information for v1 --- README.md | 79 ++++++++++++++++++++++------- docs/tableformat.md | 6 ++- src/NPC.js | 2 +- src/index.js | 8 +-- types/src/DisplayOptions.d.ts | 2 +- types/src/NPCSchema.d.ts | 3 +- types/src/NPCSchemaField.d.ts | 2 +- types/src/RandomTable.d.ts | 35 +++++-------- types/src/RandomTableEntry.d.ts | 2 +- types/src/RandomTableResult.d.ts | 2 +- types/src/RandomTableResultSet.d.ts | 8 ++- types/src/TableErrorResult.d.ts | 6 +++ types/src/TableRoller.d.ts | 9 +++- types/src/index.d.ts | 11 ++-- types/src/npc.d.ts | 4 +- types/src/npc_generator.d.ts | 4 +- 16 files changed, 123 insertions(+), 60 deletions(-) create mode 100644 types/src/TableErrorResult.d.ts diff --git a/README.md b/README.md index 20800f4..e8c0548 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ Modules for randomization focused on tables used in roleplaying games. These are models and logic only, there is no ui and only the most limited of view data. No functions are provided for the organization or storage of table data. +**If you were using pre-v1 release see the upgrading notes at the bottom of this file.** + ## Code Example A simple example setting up a very basic unweighted table (with no subtables), then "rolling" on it, and also generating a dice roll and two random names: @@ -107,6 +109,29 @@ console.log(result.die); // '1d6' ``` +Add the name token to a table roller: + +``` +import TableRoller from './TableRoller.js'; +import RandomNameGenerator from './RandomNameGenerator.js'; +import names from '../sample/names.js'; + +// Instantiate the TableRoller +const tableRoller = new TableRoller({}); + +// Format name data +const nameTypes = []; +names.forEach((data) => { + nameTypes.push(new RandomNameType(data)); +}); +// Create a default name generator. +const defaultNameGenerator = new RandomNameGenerator({ namedata: nameTypes }); +// Assign it to the name token of the table roller. +// Bind it to the name generator (else it won't work) +tableRoller.registerTokenType('name', defaultNameGenerator.nameTokenCallback.bind(defaultNameGenerator)); + +``` + Other more complicated (and useful) operations are possible. See below. ## Motivation @@ -134,13 +159,11 @@ The `sample` directory includes a few example data sources. A simple way to hand ## API Reference -The module exposes a few objects and constructors. - -**This is under construction as I refactor.** +The module includes a number of classes and functions. In general files with CamelCasing are exporting a single class, while those with snake_case are exporting one or more functions. ### randomizer -Utility classes for random selection/generation. +Utility classes for random selection/generation. Mostly used internally by the other classes. #### randomInteger (min, max) @@ -155,7 +178,7 @@ Utility classes for random selection/generation. - @param {Array} _weights_ array of weighted numbers to correspond to the values array - @return {String|Number|Object} a randomly selected element from the values array -This is mostly used internally. Returns a randomly selected element from the values array, where the randomization is weighted based on the weights array. +Returns a randomly selected element from the values array, where the randomization is weighted based on the weights array. ``` //a classic bell curve reaction table @@ -182,7 +205,7 @@ getWeightedRandom(values, weights); // returns a reaction from the value array - @param {String[]} _data_ Array of strings to select from. - @returns {String} the randomly selected string -Takes an array of strings and returns one of the element's value randomly. +Takes an array of strings and returns one of the strings randomly. ``` const data = [ @@ -198,6 +221,8 @@ randomString(data); // returns one of the reactions ### dice_roller +Some simple dice like randomization functions. + #### rollDie (string) * @params {String} string a die roll notation @@ -230,10 +255,7 @@ Get a DiceResult object. ### TableRoller -Exported from the TableRoller.js file. - -A class used for generating random results from tables. - +A class used for generating random results from RandomTable objects. Also handling for tokens in the results. #### getTableResultSetByKey (tableKey, table) @@ -259,7 +281,7 @@ This is one of two primary ways to generate results from the RandomTable objects - @param {String} _[start='']_ subtable to roll on - @return {RandomTableResult[]} -Takes a RandomTable object and returns an array of results. If RandomTable.sequence is set, multiple results may be returned. Optionally a specific subtable can be selected to select from. This is basically a wrapper for selectFromTable() that may, depending on the RandomTable's properties, concatenate multiple selectFromTable() results. +Takes a RandomTable object and returns an array of results. If RandomTable.sequence is set, multiple results may be returned. Optionally a specific subtable can be selected to select from. ``` const table_config = { @@ -320,6 +342,12 @@ Will throw TableError if key is empty or a RandomTable object is not found. Register a custom token type for use in tables. ``` +/** + * @param {Array} token_parts Parts of token when brackets are removed and it is then split by the colon + * @param {String} full_token Full original token. If the token fails generally just return the full_token back. + * @param {RandomTable|null} current_table The table the currently processed entry/token came from (or null). + * @returns {Any} Always return something that has a toString() method. + */ const footoken = function (token_parts, full_token, current_table) { return token_parts[1] + ' with big red eyes'; } @@ -349,6 +377,8 @@ In most cases it is not necessary to call this method directly, getTableResult() Takes a result value, finds, and replaces any tokens in it. +Unlike convertToken this will find multiple tokens in a string and will always return the original entryLabel with tokens replaced by strings (or the original token if an error occurs). + ### RandomTable @@ -402,14 +432,13 @@ Return entries for a subtable Get an entry in case we only have the label and need other data from it. +Warning: if your label had tokens you need to base on the original token, not a replaced version. + #### findDependencies * @returns {Array} array of table keys that the current table calls on (via tokens) -This method returns an array of table keys that the current table refers to in `{{table:SOMETABLE}}` tokens. Can be useful for making sure you have all the tables necessary to return full results from the current table. - - - +This method returns an array of table keys that the current table refers to in `{{table:SOMETABLE}}` tokens. Can be useful for making sure you have all the tables necessary to return full results from the current table. This will also look in the macros property. ### DisplayOptions @@ -458,7 +487,7 @@ If it's the default (sub)table. #### isError -If it's an error result. +If it's an error result, this will be an instance of the TableErrorResult class (which is otherwise identical to the parent class). ### RandomTableResultSet @@ -798,9 +827,25 @@ I'm not going to document these now, but the methods are: - This is a custom toJSON function for classes that handles Maps and converts them to objects. +## Upgrading to v1 + +There are a number of breaking changes in the v1 release. I think/hope these changes make things a little more consistent and versatile. + +Here are at least some of the changes to note: + +- More classes added and all existing classes have been moved to their own file/export (they are all in CamelCase). +- Dice functions have been revamped and moved to their own export (dice_roller.js) (The old roll method on the randomizer has been removed.) +- The random name generator is now a class (RandomNameGenerator) and no longer requires the old randomizer class. (This way you could have different name generators and give them different tokens for use in a TableRoller.) +- Name data is now used via the RandomNameType class. See index.js for how that works. +- The old Randomizer class is now TableRoller class. A number of lower level methods have been moved out of that class (to the randomizer.js file). +- The basic format for random table data should not have changed. +- NPCs will now generate their own UUID. +- A number of Error classes have been added, most of the time they will be thrown and caught internally (generator a TableErrorResult), but note there are places where a method may throw something specific (the docblocks should specify this). + + ## Contributors -I'd be happy to accept feature requests, bug reports, and pull requests via the github repository. There is an eslint config file for style, which can be run on the code via `npm run eslint:src` +I'd be happy to accept feature requests, bug reports, and pull requests via the github repository. There is an eslint config file for style, and tests (via mocha) are in the test directory. ## License diff --git a/docs/tableformat.md b/docs/tableformat.md index 186b282..b2521f4 100644 --- a/docs/tableformat.md +++ b/docs/tableformat.md @@ -41,7 +41,7 @@ To roll on subtables of the current table use `{{table:this:SUBTABLE_NAME}}` ### Generate a Name -`{{name:NAMETYPE:GENDER:STYLE}}` will insert a name into the table. `nametype` is required and should be one of the name lists keys ('flemish', 'dutch', etc. from RandomNameGenerator::getValidNameTypes) or "random". `gender` is optional and can be male, female, or random. If left blank, only a surname will be generated. `style` is optional and only accepts the value "first", in which case only a first name will be generated. +`{{name:NAMETYPE:GENDER:STYLE}}` will insert a name into the table. `nametype` is required and should be one of the name lists keys ('flemish', 'dutch', etc. from RandomNameGenerator::getValidNameTypes) or "random". `gender` is optional and can be "mixed", "male", "female", or "random". If left blank, it will default to "mixed". `style` is optional and only accepts the value "first", in which case only a first name will be generated. ### Custom token @@ -56,6 +56,8 @@ I've tried to build in an escalating scale of complexity. Simple tables can be f I've tried to build in as much forgiveness as possible into the format. +The RandomTable class will convert any entries on the table/subtables to RandomTableEntry objects on initialization. + ### Simple unweighted table A basic list of options with no extra information. @@ -110,7 +112,7 @@ The `subtable` property in a result can have a number of properties that effect * @property {String} _description_ an elaboration on the label that can be used when outputting/displaying results * @property {Boolean} _print_ should this result be included in various result outputs (good for use with the subtable property where you only want the result on the subtable to be displayed/output) -Here's an example using these various properties. The default table is rolled on first (it is weighted so in this case humanoids are most common). The result of the default table decides what subtable should be rolled on next. Some of the subtables then have further subtables to be rolled on (so the "human" subtable will often cause a roll on the "actions_human" subtable). +Here's an example using these various properties. The default table is rolled on first (it is weighted, so in this case humanoids are most common). The result of the default table decides what subtable should be rolled on next. Some of the subtables then have further subtables to be rolled on (so the "human" subtable will often cause a roll on the "actions_human" subtable). ``` "tables": { diff --git a/src/NPC.js b/src/NPC.js index 483b12d..2fb3768 100644 --- a/src/NPC.js +++ b/src/NPC.js @@ -1,5 +1,5 @@ import { defaultToJSON, isObject } from './r_helpers.js'; -import { v4 as uuidv4 } from 'uuid/dist/esm-browser'; +import uuidv4 from '../node_modules/uuid/dist/esm-browser/v4.js'; /** * Class for NPCs diff --git a/src/index.js b/src/index.js index 995e7e1..ca85a12 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,6 @@ import TableRoller from './TableRoller.js'; import RandomTable from './RandomTable.js'; -import normalizeData from './table_normalizer.js'; -import * as r_helpers from './r_helpers.js'; +import RandomTableEntry from './RandomTableEntry.js'; import RandomNameGenerator from './RandomNameGenerator.js'; import names from '../sample/names.js'; import * as npc_generator from './npc_generator.js'; @@ -9,6 +8,7 @@ import NPCSchema from './NPCSchema.js'; import NPCSchemaField from './NPCSchemaField.js'; import * as dice_roller from './dice_roller.js'; import RandomNameType from './RandomNameType.js'; +import NPC from './NPC.js'; // Instantiate the TableRoller and set it up with the random name generator. const tableRoller = new TableRoller({}); @@ -26,12 +26,12 @@ tableRoller.registerTokenType('name', defaultNameGenerator.nameTokenCallback.bin export default { tableRoller, RandomTable, - normalizeData, + RandomTableEntry, defaultNameGenerator, RandomNameGenerator, RandomNameType, - r_helpers, npc_generator, + NPC, NPCSchema, NPCSchemaField, dice_roller diff --git a/types/src/DisplayOptions.d.ts b/types/src/DisplayOptions.d.ts index 4401807..ef92eb8 100644 --- a/types/src/DisplayOptions.d.ts +++ b/types/src/DisplayOptions.d.ts @@ -1,7 +1,7 @@ /** * Display options for subtable results. Used in RandomTable and RandomTableResultSet */ -export class DisplayOptions { +export default class DisplayOptions { /** * * @property {String} table Subtable name. diff --git a/types/src/NPCSchema.d.ts b/types/src/NPCSchema.d.ts index 304c111..789b41c 100644 --- a/types/src/NPCSchema.d.ts +++ b/types/src/NPCSchema.d.ts @@ -1,7 +1,7 @@ /** * Schema for creating NPCs. */ -export class NPCSchema { +export default class NPCSchema { /** * @property {String} key Identifying key * @property {String} name Name of schema. @@ -36,3 +36,4 @@ export class NPCSchema { */ toJSON(): any; } +import NPCSchemaField from "./NPCSchemaField.js"; diff --git a/types/src/NPCSchemaField.d.ts b/types/src/NPCSchemaField.d.ts index ee5108b..ca32006 100644 --- a/types/src/NPCSchemaField.d.ts +++ b/types/src/NPCSchemaField.d.ts @@ -1,7 +1,7 @@ /** * Specific field in NPC Schema. */ -export class NPCSchemaField { +export default class NPCSchemaField { /** * * @property {String} key Identifying key diff --git a/types/src/RandomTable.d.ts b/types/src/RandomTable.d.ts index b8ab8cf..985fe19 100644 --- a/types/src/RandomTable.d.ts +++ b/types/src/RandomTable.d.ts @@ -2,7 +2,7 @@ * RandomTable: Model for tables used by TableRoller * @param {Object} config the tables non-default attributes */ -export class RandomTable { +export default class RandomTable { /** * The primary attributes of this table * @property {String} id id for the table, primary key for database if used @@ -16,14 +16,13 @@ export class RandomTable { * @property {String[]|Object[]} [table] default table. array of strings or objects. removed after initialization. * @property {Object} [tables] a property for each subtables. * @property {RandomTableEntries[]} tables[subtablename] Entries for subtables. - * @property {String[]} [macro] for tables that are only used to aggregate result from other tables, this array consists of table keys to be rolled on in order + * @property {String[]} [macro] for tables that are only used to aggregate result from other tables, this array consists of table keys and optionsl subtables to be rolled on in order * @property {Map[DisplayOptions]} [display_opt] Display options for the subtables. - * @property @deprecated {Object} [print] Backwards compatible. Key => Object data for display options. * @property {Array} [dependencies] table keys that are needed to get full results from this table * * Note the Constructor args are not exactly the same as the properties. Some type changes are made to convert data. */ - constructor({ id, key, title, author, description, source, tags, sequence, tables, macro, print, dependencies, table, display_opt }: { + constructor({ id, key, title, author, description, source, tags, sequence, tables, macro, dependencies, table, display_opt }: { id?: number; key?: any; title?: string; @@ -34,7 +33,6 @@ export class RandomTable { sequence?: any[]; tables?: {}; macro?: any[]; - print?: {}; dependencies?: any; table?: any; display_opt?: any[]; @@ -71,6 +69,13 @@ export class RandomTable { * @returns {Object} error information */ validate(properties: any): any; + /** + * Basic sequence of table rolls. + * Either the start, the default sequence, the default table, or just the first one. + * @param {String} start Subtable name to start with. + * @returns {String[]} + */ + getSequence(start?: string): string[]; /** * All the subtable names. * @returns {String[]} @@ -82,25 +87,12 @@ export class RandomTable { * @returns {RandomTableEntry[]} */ getSubtableEntries(name?: string): RandomTableEntry[]; - /** - * outputs the json data for the table (import/export) - * @param {Boolean} [editmode=false] if false empty properties will be stripped out - * @returns {Object} table attributes - */ - outputObject(editmode?: boolean): any; - /** - * outputs the json data for the table (import/export) - * @param {Boolean} [editmode=false] if false empty properties will be stripped out - * @param {Boolean} [compress=false] if true JSON will not have indentation, etc. - * @returns {String} table properties in JSON - */ - outputCode(editmode?: boolean, compress?: boolean): string; /** * Get a random entry from a subtable. - * @param {String} subtableNames + * @param {String} subtableName * @returns {RandomTableEntry|null} */ - getRandomEntry(subtableNames: string): RandomTableEntry | null; + getRandomEntry(subtableName: string): RandomTableEntry | null; /** * Get an entry in case we only have the label and need other data from it * @param {String} label The item we are looking for @@ -109,7 +101,7 @@ export class RandomTable { */ findEntry(label: string, table?: string): RandomTableEntry | null; /** - * find the dependent tables to get full results for this table + * Find the dependent tables to get full results for this table * @return {Array} table keys */ findDependencies(): any[]; @@ -119,3 +111,4 @@ export class RandomTable { */ toJSON(): any; } +import RandomTableEntry from "./RandomTableEntry.js"; diff --git a/types/src/RandomTableEntry.d.ts b/types/src/RandomTableEntry.d.ts index 00fd44e..d12fc48 100644 --- a/types/src/RandomTableEntry.d.ts +++ b/types/src/RandomTableEntry.d.ts @@ -2,7 +2,7 @@ * Class for entries in a random (sub)table. * This normalizes the various options into a class that makes the other code simpler. */ -export class RandomTableEntry { +export default class RandomTableEntry { /** * * @property {String} label Basic string label. Only required field. Can include tokens. diff --git a/types/src/RandomTableResult.d.ts b/types/src/RandomTableResult.d.ts index 9324f05..a4521dc 100644 --- a/types/src/RandomTableResult.d.ts +++ b/types/src/RandomTableResult.d.ts @@ -1,7 +1,7 @@ /** * Class for results from RandomTable */ -export class RandomTableResult { +export default class RandomTableResult { /** * @property {String} table Title of subtable. * @property {String} result Randomized result label. diff --git a/types/src/RandomTableResultSet.d.ts b/types/src/RandomTableResultSet.d.ts index c396d5c..af70073 100644 --- a/types/src/RandomTableResultSet.d.ts +++ b/types/src/RandomTableResultSet.d.ts @@ -1,7 +1,7 @@ /** * Set of table results. */ -export class RandomTableResultSet { +export default class RandomTableResultSet { /** * @property {String} title Title from the RandomTable parent * @property {RandomTableResult[]} results Randomized results. @@ -28,6 +28,11 @@ export class RandomTableResultSet { * @returns {RandomTableResult|null} */ findResultByTable(table?: string): RandomTableResult | null; + /** + * Output the set as a string. + * @param {Boolean} simple Simplify the output (just the result labels) + * @returns + */ niceString(simple?: boolean): string; /** * Simple base output of result set. @@ -39,3 +44,4 @@ export class RandomTableResultSet { */ toJSON(): any; } +import RandomTableResult from "./RandomTableResult.js"; diff --git a/types/src/TableErrorResult.d.ts b/types/src/TableErrorResult.d.ts new file mode 100644 index 0000000..bc291c2 --- /dev/null +++ b/types/src/TableErrorResult.d.ts @@ -0,0 +1,6 @@ +/** + * Class for results from RandomTable + */ +export default class TableErrorResult extends RandomTableResult { +} +import RandomTableResult from "./RandomTableResult.js"; diff --git a/types/src/TableRoller.d.ts b/types/src/TableRoller.d.ts index 5477c1b..95bbd1e 100644 --- a/types/src/TableRoller.d.ts +++ b/types/src/TableRoller.d.ts @@ -15,9 +15,10 @@ declare class TableRoller { /** * Return an error result * @param {String} error Error message - * @returns {RandomTableResult} + * @param {String} table Sub/table name if relevant. + * @returns {TableErrorResult} */ - _getErrorResult(error?: string): RandomTableResult; + _getErrorResult(error?: string, table?: string): TableErrorResult; /** * Return a result set with an error. * @param {String} error Error message @@ -115,3 +116,7 @@ declare class TableRoller { */ _defaultTableToken(token_parts: string[], full_token: string, curtable?: RandomTable | null): RandomTableResultSet | RandomTableResultSet[]; } +import TableErrorResult from "./TableErrorResult.js"; +import RandomTableResultSet from "./RandomTableResultSet.js"; +import RandomTable from "./RandomTable.js"; +import RandomTableResult from "./RandomTableResult.js"; diff --git a/types/src/index.d.ts b/types/src/index.d.ts index c575d3c..85fbada 100644 --- a/types/src/index.d.ts +++ b/types/src/index.d.ts @@ -1,23 +1,26 @@ declare namespace _default { export { tableRoller }; export { RandomTable }; - export { normalizeData }; + export { RandomTableEntry }; export { defaultNameGenerator }; export { RandomNameGenerator }; export { RandomNameType }; - export { r_helpers }; export { npc_generator }; + export { NPC }; export { NPCSchema }; export { NPCSchemaField }; export { dice_roller }; } export default _default; declare const tableRoller: TableRoller; -import normalizeData from "./table_normalizer.js"; +import RandomTable from "./RandomTable.js"; +import RandomTableEntry from "./RandomTableEntry.js"; declare const defaultNameGenerator: RandomNameGenerator; import RandomNameGenerator from "./RandomNameGenerator.js"; import RandomNameType from "./RandomNameType.js"; -import * as r_helpers from "./r_helpers.js"; import * as npc_generator from "./npc_generator.js"; +import NPC from "./NPC.js"; +import NPCSchema from "./NPCSchema.js"; +import NPCSchemaField from "./NPCSchemaField.js"; import * as dice_roller from "./dice_roller.js"; import TableRoller from "./TableRoller.js"; diff --git a/types/src/npc.d.ts b/types/src/npc.d.ts index 7640fb4..0bb4b20 100644 --- a/types/src/npc.d.ts +++ b/types/src/npc.d.ts @@ -1,10 +1,10 @@ /** - * Class for NPCs. + * Class for NPCs * @param {String} id Some kind of indentifier. * @param {String} schema Key for a NPCSchema used for this NPC. * @param {Map} fields Field values indexed by NPCSchemaField key. */ -export class NPC { +export default class NPC { constructor({ id, schema, fields }: { id?: any; schema?: string; diff --git a/types/src/npc_generator.d.ts b/types/src/npc_generator.d.ts index 94c299b..3021ff3 100644 --- a/types/src/npc_generator.d.ts +++ b/types/src/npc_generator.d.ts @@ -21,5 +21,7 @@ export function getSchemaByKey(key: string): NPCSchema | null; * @param {Boolean} generateId Should the npc get a uuid. * @returns NPC */ -export function initializeNewNPC(schemaKey: string, tableRoller: TableRoller, generateId?: boolean): any; +export function initializeNewNPC(schemaKey: string, tableRoller: TableRoller, generateId?: boolean): NPC; +import NPCSchema from "./NPCSchema.js"; import TableRoller from "./TableRoller.js"; +import NPC from "./NPC.js";