The client-side Combat document which extends the common BaseCombat model.

ClientDocumentMixin

Hierarchy (View Summary)

Constructors

Properties

Accessors

Methods

Constructors

Properties

_source: CombatData

The source data object for this DataModel instance. Once constructed, the source object is sealed such that no keys may be added nor removed.

current: CombatHistoryData = ...

Record the current round, turn, and tokenId to understand changes in the encounter state

debounceSetup: Function = ...

Debounce changes to the composition of the Combat encounter to de-duplicate multiple concurrent Combatant changes. If this is the currently viewed encounter, re-render the CombatTracker application.

parent: null | DataModel<object, DataModelConstructionContext>

An immutable reverse-reference to a parent DataModel to which this model belongs.

previous: CombatHistoryData = undefined

Track the previous round, turn, and tokenId to understand changes in the encounter state

turns: documents.Combatant[] = ...

Track the sorted turn order of this combat encounter

_schema: SchemaField

The defined and cached Data Schema for all instances of this DataModel.

CONFIG_SETTING: string = "combatTrackerConfig"

The configuration setting used to record Combat preferences

LOCALIZATION_PREFIXES: string[] = ...
metadata: object = ...

Default metadata which applies to each instance of this Document type.

Accessors

  • get compendium(): any

    A reference to the Compendium Collection containing this Document, if any, and otherwise null.

    Returns any

  • get id(): null | string

    The canonical identifier for this Document.

    Returns null | string

  • get inCompendium(): boolean

    Is this document in a compendium?

    Returns boolean

  • get invalid(): boolean

    Is the current state of this DataModel invalid? The model is invalid if there is any unresolved failure.

    Returns boolean

  • get isActive(): boolean

    Is this combat active in the current scene?

    Returns boolean

  • get isEmbedded(): boolean

    Is this document embedded within a parent document?

    Returns boolean

  • get schema(): SchemaField

    Define the data schema for this document instance.

    Returns SchemaField

  • get settings(): object

    Return the object of settings which modify the Combat Tracker behavior

    Returns object

  • get started(): boolean

    Has this combat encounter been started?

    Returns boolean

  • get uuid(): string

    A Universally Unique Identifier (uuid) for this Document instance.

    Returns string

  • get visible(): boolean

    Returns boolean

  • get baseDocument(): typeof Document

    The base document definition that this document class extends from.

    Returns typeof Document

  • get collectionName(): string

    The named collection to which this Document belongs.

    Returns string

  • get documentName(): string

    The canonical name of this Document type, for example "Actor".

    Returns string

  • get hasTypeData(): boolean

    Does this Document support additional subtypes?

    Returns boolean

  • get hierarchy(): Readonly<Record<string, any>>

    The Embedded Document hierarchy for this Document.

    Returns Readonly<Record<string, any>>

  • get implementation(): typeof Document

    Return a reference to the configured subclass of this base Document type.

    Returns typeof Document

  • get schema(): SchemaField

    Ensure that all Document classes share the same schema of their base declaration.

    Returns SchemaField

  • get TYPES(): string[]

    The allowed types which may exist for this Document class.

    Returns string[]

Methods

  • Parameters

    • __namedParameters: { pack?: null; parentCollection?: null } = {}

    Returns void

  • Internal

    Identify the collection in a parent Document that this Document belongs to, if any.

    Parameters

    • OptionalparentCollection: null | string

      An explicitly provided parent collection name.

    Returns null | string

  • Post-process a creation operation for a single Document instance. Post-operation events occur for all connected clients.

    Parameters

    • data: any

      The initial data object provided to the document creation request

    • options: any

      Additional options which modify the creation request

    • userId: any

      The id of the User requesting the document update

    Returns void

  • Parameters

    • parent: any
    • collection: any
    • documents: any
    • data: any
    • options: any
    • userId: any

    Returns void

  • Post-process a deletion operation for a single Document instance. Post-operation events occur for all connected clients.

    Parameters

    • options: any

      Additional options which modify the deletion request

    • userId: any

      The id of the User requesting the document update

    Returns void

  • Parameters

    • parent: any
    • collection: any
    • documents: any
    • ids: any
    • options: any
    • userId: any

    Returns void

  • Post-process an update operation for a single Document instance. Post-operation events occur for all connected clients.

    Parameters

    • changed: any

      The differential data that was changed relative to the documents prior values

    • options: any

      Additional options which modify the update request

    • userId: any

      The id of the User requesting the document update

    Returns void

  • Parameters

    • parent: any
    • collection: any
    • documents: any
    • changes: any
    • options: any
    • userId: any

    Returns void

  • Pre-process an update operation for a single Document instance. Pre-operation events only occur for the client which requested the operation.

    Parameters

    • changed: any

      The candidate changes to the Document

    • options: any

      Additional options which modify the update request

    • user: any

      The User requesting the document update

    Returns Promise<undefined | false>

    A return value of false indicates the update operation should be cancelled.

  • Test whether a given User has permission to perform some action on this Document

    Parameters

    • user: BaseUser

      The User attempting modification

    • action: string

      The attempted action

    • Optionaldata: object = {}

      Data involved in the attempted action

    Returns boolean

    Does the User have permission?

  • Clear the movement history of all Tokens within this Combat.

    Returns Promise<void>

  • Clear the movement history of the Combatants' Tokens.

    Parameters

    • combatants: Iterable<documents.Combatant>

      The combatants whose movement history is cleared

    Returns Promise<void>

  • Display a dialog querying the GM whether they wish to end the combat encounter and empty the tracker

    Returns Promise<documents.Combat>

  • Obtain a reference to the Array of source data within the data object for a certain embedded Document name

    Parameters

    • embeddedName: string

      The name of the embedded Document type

    Returns DocumentCollection

    The Collection instance of embedded Documents of the requested type

  • Get an embedded document by its id from a named collection in the parent document.

    Parameters

    • embeddedName: string

      The name of the embedded Document type

    • id: string

      The id of the child document to retrieve

    • Optionaloptions: { invalid?: boolean; strict?: boolean } = {}

      Additional options which modify how embedded documents are retrieved

      • Optionalinvalid?: boolean

        Allow retrieving an invalid Embedded Document.

      • Optionalstrict?: boolean

        Throw an Error if the requested id does not exist. See Collection#get

    Returns Document<object, DocumentConstructionContext>

    The retrieved embedded Document instance, or undefined

    If the embedded collection does not exist, or if strict is true and the Embedded Document could not be found.

  • Get the value of a "flag" for this document See the setFlag method for more details on flags

    Parameters

    • scope: string

      The flag scope which namespaces the key

    • key: string

      The flag key

    Returns any

    The flag value

  • Calculate the time delta between two turns.

    Parameters

    • fromRound: number

      The from-round

    • fromTurn: null | number

      The from-turn

    • toRound: number

      The to-round

    • toTurn: null | number

      The to-turn

    Returns number

    The time delta

  • Get the explicit permission level that a User has over this Document, a value in CONST.DOCUMENT_OWNERSHIP_LEVELS. Compendium content ignores the ownership field in favor of User role-based ownership. Otherwise, Documents use granular per-User ownership definitions and Embedded Documents defer to their parent ownership.

    This method returns the value recorded in Document ownership, regardless of the User's role, for example a GAMEMASTER user might still return a result of NONE if they are not explicitly denoted as having a level.

    To test whether a user has a certain capability over the document, testUserPermission should be used.

    Parameters

    • Optionaluser: BaseUser

      The User being tested

    Returns DocumentOwnershipNumber

    A numeric permission level from CONST.DOCUMENT_OWNERSHIP_LEVELS

  • For Documents which include game system data, migrate the system data object to conform to its latest data model. The data model is defined by the template.json specification included by the game system.

    Returns object

    The migrated system data object

  • Returns void

  • Reset the state of this data instance back to mirror the contained source data, erasing any changes.

    Returns void

  • Reset all combatant initiative scores.

    Parameters

    • Optionaloptions: { updateTurn?: boolean } = {}

      Additional options

      • OptionalupdateTurn?: boolean

        Update the Combat turn after resetting initiative scores to keep the turn on the same Combatant.

    Returns Promise<documents.Combat>

  • Roll initiative for all combatants which have not already rolled

    Parameters

    • Optionaloptions: object

      Additional options forwarded to the Combat.rollInitiative method

    Returns Promise<documents.Combat>

  • Roll initiative for one or multiple Combatants within the Combat document

    Parameters

    • ids: string | string[]

      A Combatant id or Array of ids for which to roll

    • Optionaloptions: { formula?: null | string; messageOptions?: object; updateTurn?: boolean } = {}

      Additional options which modify how initiative rolls are created or presented.

      • Optionalformula?: null | string

        A non-default initiative formula to roll. Otherwise, the system default is used.

      • OptionalmessageOptions?: object

        Additional options with which to customize created Chat Messages

      • OptionalupdateTurn?: boolean

        Update the Combat turn after adding new initiative scores to keep the turn on the same Combatant.

    Returns Promise<documents.Combat>

    A promise which resolves to the updated Combat document once updates are complete.

  • Roll initiative for all non-player actors who have not already rolled

    Parameters

    • Optionaloptions: object = {}

      Additional options forwarded to the Combat.rollInitiative method

    Returns Promise<documents.Combat>

  • Assign a "flag" to this document. Flags represent key-value type data which can be used to store flexible or arbitrary data required by either the core software, game systems, or user-created modules.

    Each flag should be set using a scope which provides a namespace for the flag to help prevent collisions.

    Flags set by the core software use the "core" scope. Flags set by game systems or modules should use the canonical name attribute for the module Flags set by an individual world should "world" as the scope.

    Flag values can assume almost any data type. Setting a flag value to null will delete that flag.

    Parameters

    • scope: string

      The flag scope which namespaces the key

    • key: string

      The flag key

    • value: any

      The flag value

    Returns Promise<Document<object, DocumentConstructionContext>>

    A Promise resolving to the updated document

  • Assign initiative for a single Combatant within the Combat encounter. Update the Combat turn order to maintain the same combatant as the current turn.

    Parameters

    • id: string

      The combatant ID for which to set initiative

    • value: number

      A specific initiative value to set

    Returns Promise<void>

  • Test whether a certain User has a requested permission level (or greater) over the Document

    Parameters

    • user: BaseUser

      The User being tested

    • permission: DocumentOwnershipLevel

      The permission level from DOCUMENT_OWNERSHIP_LEVELS to test

    • options: { exact?: boolean } = {}

      Additional options involved in the permission test

      • Optionalexact?: boolean

        Require the exact permission level requested?

    Returns boolean

    Does the user have this permission level over the Document?

  • Toggle whether this combat is linked to the scene or globally available.

    Returns Promise<documents.Combat>

  • Extract the source data for the DataModel into a simple object format that can be serialized.

    Returns object

    The document source data expressed as a plain object

  • Copy and transform the DataModel into a plain object. Draw the values of the extracted object from the data source (by default) otherwise from its transformed values.

    Parameters

    • source: boolean = true

      Draw values from the underlying data source rather than transformed values

    Returns any

    The extracted primitive object

  • Iterate over all embedded Documents that are hierarchical children of this Document.

    Parameters

    • Optional_parentPath: string

      A parent field path already traversed

    Returns Generator<any, void, any>

  • Update active effect durations for all actors present in this Combat encounter.

    Returns void

  • Update the DataModel locally by applying an object of changes to its source data. The provided changes are expanded, cleaned, validated, and stored to the source data object for this model. The provided changes argument is mutated in this process. The source data is then re-initialized to apply those changes to the prepared data. The method returns an object of differential changes which modified the original data.

    Parameters

    • changes: object = {}

      New values which should be applied to the data model

    • options: DataModelUpdateOptions = {}

      Options which determine how the new data is merged

    Returns object

    An object containing differential keys and values that were changed

    An error if the requested data model changes were invalid

  • Validate the data contained in the document to check for type and content. If changes are provided, missing types are added to it before cleaning and validation. This mutates the provided changes. This function throws an error if data within the document is not valid.

    Parameters

    Returns boolean

    Whether the data source or proposed change is reported as valid. A boolean is always returned if validation is non-strict.

    An error thrown if validation is strict and a failure occurs.

  • Protected

    Can a certain User change the Combat round?

    Parameters

    • user: User

      The user attempting to change the round

    Returns boolean

    Is the user allowed to change the round?

  • Protected

    Can a certain User change the Combat turn?

    Parameters

    • user: User

      The user attempting to change the turn

    Returns boolean

    Is the user allowed to change the turn?

  • Protected

    Called after Combat#_onExit and takes care of clearing the movement history of the Combatant's Token. This function is not called for Combatants that don't have a Token. The default implementation clears the movement history always.

    Parameters

    Returns Promise<void>

  • Protected

    Called after Combat#_onStartTurn and takes care of clearing the movement history of the Combatant's Token. This function is not called for Combatants that don't have a Token. The default implementation clears the movement history always.

    Parameters

    Returns Promise<void>

  • Protected

    Initialize the instance by copying data from the source object to instance attributes. This mirrors the workflow of SchemaField#initialize but with some added functionality.

    Parameters

    • Optionaloptions: object = {}

      Options provided to the model constructor

    Returns void

  • Protected

    Initialize the source data for a new DataModel instance. One-time migrations and initial cleaning operations are applied to the source data.

    Parameters

    • data: object | DataModel<object, DataModelConstructionContext>

      The candidate source data from which the model will be constructed

    • Optionaloptions: object = {}

      Options provided to the model constructor

    Returns object

    Migrated and cleaned source data which will be stored to the model instance, which is the same object as the data argument

  • Protected

    Manage the execution of Combat lifecycle events. This method orchestrates the execution of four events in the following order, as applicable:

    1. End Turn
    2. End Round
    3. Begin Round
    4. Begin Turn Each lifecycle event is an async method, and each is awaited before proceeding.

    Returns Promise<void>

  • Protected

    A workflow that occurs at the end of each Combat Round. This workflow occurs after the Combat document update. This can be overridden to implement system-specific combat tracking behaviors. The default implementation of this function does nothing. This method only executes for one designated GM user. If no GM users are present this method will not be called.

    Parameters

    Returns Promise<void>

  • Protected

    A workflow that occurs at the end of each Combat Turn. This workflow occurs after the Combat document update. This can be overridden to implement system-specific combat tracking behaviors. The default implementation of this function does nothing. This method only executes for one designated GM user. If no GM users are present this method will not be called.

    Parameters

    Returns Promise<void>

  • Protected

    This workflow occurs after a Combatant is added to the Combat. This can be overridden to implement system-specific combat tracking behaviors. The default implementation of this function does nothing. This method only executes for one designated GM user. If no GM users are present this method will not be called.

    Parameters

    Returns Promise<void>

  • Protected

    This workflow occurs after a Combatant is removed from the Combat. This can be overridden to implement system-specific combat tracking behaviors. The default implementation of this function does nothing. This method only executes for one designated GM user. If no GM users are present this method will not be called.

    Parameters

    Returns Promise<void>

  • Protected

    A workflow that occurs at the start of each Combat Round. This workflow occurs after the Combat document update. This can be overridden to implement system-specific combat tracking behaviors. The default implementation of this function does nothing. This method only executes for one designated GM user. If no GM users are present this method will not be called.

    Parameters

    Returns Promise<void>

  • Protected

    A workflow that occurs at the start of each Combat Turn. This workflow occurs after the Combat document update. This can be overridden to implement system-specific combat tracking behaviors. The default implementation of this function does nothing. This method only executes for one designated GM user. If no GM users are present this method will not be called.

    Parameters

    Returns Promise<void>

  • Protected

    Loads the registered Combat Theme (if any) and plays the requested type of sound. If multiple exist for that type, one is chosen at random.

    Parameters

    • announcement: string

      The announcement that should be played: "startEncounter", "nextUp", or "yourTurn".

    Returns void

  • Protected

    Pre-process a creation operation for a single Document instance. Pre-operation events only occur for the client which requested the operation.

    Modifications to the pending Document instance must be performed using updateSource.

    Parameters

    • data: object

      The initial data object provided to the document creation request

    • options: object

      Additional options which modify the creation request

    • user: BaseUser

      The User requesting the document creation

    Returns Promise<boolean | void>

    Return false to exclude this Document from the creation operation

  • Protected

    Pre-process a deletion operation for a single Document instance. Pre-operation events only occur for the client which requested the operation.

    Parameters

    • options: object

      Additional options which modify the deletion request

    • user: BaseUser

      The User requesting the document deletion

    Returns Promise<boolean | void>

    A return value of false indicates the deletion operation should be cancelled.

  • Protected

    Refresh the Token HUD under certain circumstances.

    Parameters

    • documents: documents.Combatant[]

      A list of Combatant documents that were added or removed.

    Returns void

  • Protected

    Define how the array of Combatants is sorted in the displayed list of the tracker. This method can be overridden by a system or module which needs to display combatants in an alternative order. The default sorting rules sort in descending order of initiative using combatant IDs for tiebreakers.

    Parameters

    Returns number

  • Protected

    Update display of Token combat turn markers.

    Returns void

  • Internal

    Define a simple migration from one field name to another. The value of the data can be transformed during the migration by an optional application function.

    Parameters

    • data: object

      The data object being migrated

    • oldKey: string

      The old field name

    • newKey: string

      The new field name

    • Optionalapply: (data: object) => any

      An application function, otherwise the old value is applied

    Returns boolean

    Whether a migration was applied.

  • Internal

    A reusable helper for adding a migration shim The value of the data can be transformed during the migration by an optional application function.

    Parameters

    • data: object

      The data object being shimmed

    • oldKey: string

      The old field name

    • newKey: string

      The new field name

    • Optionaloptions: { value?: any; warning?: string } = {}
      • Optionalvalue?: any

        The value of the shim

      • Optionalwarning?: string

        The deprecation message

    Returns void

  • Internal

    A reusable helper for adding migration shims.

    Parameters

    • data: object

      The data object being shimmed

    • shims: { [oldKey: string]: string }

      The mapping of old keys to new keys

    • Optionaloptions: { value?: any; warning?: string }
      • Optionalvalue?: any

        The value of the shim

      • Optionalwarning?: string

        The deprecation message

    Returns void

  • Internal

    Clear the fields from the given Document data recursively.

    Parameters

    • data: object

      The (partial) Document data

    • fieldNames: string[]

      The fields that are cleared

    Returns void

  • Internal

    Log a compatbility warning for the data field migration.

    Parameters

    Returns void

  • Test whether a given User has sufficient permissions to create Documents of this type in general. This does not guarantee that the User is able to create all Documents of this type, as certain document-specific requirements may also be present.

    Generally speaking, this method is used to verify whether a User should be presented with the option to create Documents of this type in the UI.

    Parameters

    Returns boolean

    Does the User have a sufficient role to create?

  • Clean a data source object to conform to a specific provided schema.

    Parameters

    • Optionalsource: object = {}

      The source data object

    • Optionaloptions: object = {}

      Additional options which are passed to field cleaning methods

    Returns object

    The cleaned source data, which is the same object as the source argument

  • Create multiple Documents using provided input data. Data is provided as an array of objects where each individual object becomes one new Document.

    Parameters

    Returns Promise<Document<object, DocumentConstructionContext>[]>

    An array of created Document instances

    const data = [{name: "New Actor", type: "character", img: "path/to/profile.jpg"}];
    const created = await Actor.implementation.createDocuments(data);
    const data = [{name: "Tim", type: "npc"], [{name: "Tom", type: "npc"}];
    const created = await Actor.implementation.createDocuments(data);
    const actor = game.actors.getName("Tim");
    const data = [{name: "Sword", type: "weapon"}, {name: "Breastplate", type: "equipment"}];
    const created = await Item.implementation.createDocuments(data, {parent: actor});
    const data = [{name: "Compendium Actor", type: "character", img: "path/to/profile.jpg"}];
    const created = await Actor.implementation.createDocuments(data, {pack: "mymodule.mypack"});
  • Delete one or multiple existing Documents using an array of provided ids. Data is provided as an array of string ids for the documents to delete.

    Parameters

    • ids: string[] = []

      An array of string ids for the documents to be deleted

    • Optionaloperation: Partial<Omit<DatabaseDeleteOperation, "ids">> = {}

      Parameters of the database deletion operation

    Returns Promise<Document<object, DocumentConstructionContext>[]>

    An array of deleted Document instances

    const tim = game.actors.getName("Tim");
    const deleted = await Actor.implementation.deleteDocuments([tim.id]);
    const tim = game.actors.getName("Tim");
    const tom = game.actors.getName("Tom");
    const deleted = await Actor.implementation.deleteDocuments([tim.id, tom.id]);
    const tim = game.actors.getName("Tim");
    const sword = tim.items.getName("Sword");
    const shield = tim.items.getName("Shield");
    const deleted = await Item.implementation.deleteDocuments([sword.id, shield.id], parent: actor});
    const actor = await pack.getDocument(documentId);
    const deleted = await Actor.implementation.deleteDocuments([actor.id], {pack: "mymodule.mypack"});
  • A compatibility method that returns the appropriate name of an embedded collection within this Document.

    Parameters

    • name: string

      An existing collection name or a document name.

    Returns null | string

    The provided collection name if it exists, the first available collection for the document name provided, or null if no appropriate embedded collection could be found.

    Actor.implementation.getCollectionName("items");
    // returns "items"
    Actor.implementation.getCollectionName("Item");
    // returns "items"
  • Migrate candidate source data for this DataModel which may require initial cleaning or transformations.

    Parameters

    • source: object

      The candidate source data from which the model will be constructed

    Returns object

    Migrated source data, which is the same object as the source argument

  • Wrap data migration in a try/catch which attempts it safely

    Parameters

    • source: object

      The candidate source data from which the model will be constructed

    Returns object

    Migrated source data, which is the same object as the source argument

  • Take data which conforms to the current data schema and add backwards-compatible accessors to it in order to support older code which uses this data.

    Parameters

    • data: object

      Data which matches the current schema

    • Optionaloptions: { embedded?: boolean } = {}

      Additional shimming options

      • Optionalembedded?: boolean

        Apply shims to embedded models?

    Returns object

    Data with added backwards-compatible properties, which is the same object as the data argument

  • Update multiple Document instances using provided differential data. Data is provided as an array of objects where each individual object updates one existing Document.

    Parameters

    • updates: object[] = []

      An array of differential data objects, each used to update a single Document

    • Optionaloperation: Partial<Omit<DatabaseUpdateOperation, "updates">> = {}

      Parameters of the database update operation

    Returns Promise<Document<object, DocumentConstructionContext>[]>

    An array of updated Document instances

    const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}];
    const updated = await Actor.implementation.updateDocuments(updates);
    const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}, {_id: "kj549dk48k34jk34", name: "Thomas"}]};
    const updated = await Actor.implementation.updateDocuments(updates);
    const actor = game.actors.getName("Timothy");
    const updates = [{_id: sword.id, name: "Magic Sword"}, {_id: shield.id, name: "Magic Shield"}];
    const updated = await Item.implementation.updateDocuments(updates, {parent: actor});
    const actor = await pack.getDocument(documentId);
    const updated = await Actor.implementation.updateDocuments([{_id: actor.id, name: "New Name"}],
    {pack: "mymodule.mypack"});
  • Evaluate joint validation rules which apply validation conditions across multiple fields of the model. Field-specific validation rules should be defined as part of the DataSchema for the model. This method allows for testing aggregate rules which impose requirements on the overall model.

    Parameters

    • data: object

      Candidate data for the model

    Returns void

    An error if a validation failure is detected

  • Protected

    Pre-process a creation operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.

    This batch-wise workflow occurs after individual _preCreate workflows and provides a final pre-flight check before a database operation occurs.

    Modifications to pending documents must mutate the documents array or alter individual document instances using updateSource.

    Parameters

    Returns Promise<boolean | void>

    Return false to cancel the creation operation entirely

  • Protected

    Pre-process a deletion operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.

    This batch-wise workflow occurs after individual _preDelete workflows and provides a final pre-flight check before a database operation occurs.

    Modifications to the requested deletions are performed by mutating the operation object. updateSource.

    Parameters

    Returns Promise<boolean | void>

    Return false to cancel the deletion operation entirely

  • Protected

    Pre-process an update operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.

    This batch-wise workflow occurs after individual _preUpdate workflows and provides a final pre-flight check before a database operation occurs.

    Modifications to the requested updates are performed by mutating the data array of the operation.

    Parameters

    Returns Promise<boolean | void>

    Return false to cancel the update operation entirely