Foundry Virtual Tabletop - API Documentation - Version 14
    Preparing search index...

    The client-side Token document which extends the common BaseToken document model.

    The following fields must no be altered from source during data preparation: x, y, elevation, width, height, depth, shape, level.

    CanvasDocumentMixin

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    Accessors

    Methods

    _configure _getParentCollection _gridOffsetToPosition _identifyRegions _initializationOrder _initialize _initializeSource _onCreate _onCreateDescendantDocuments _onDelete _onDeleteDescendantDocuments _onUpdate _onUpdateBaseActor _onUpdateDescendantDocuments _positionToGridOffset _preCreate _preCreateDescendantDocuments _preDeleteDescendantDocuments _prepareDeltaUpdate _preUpdate _preUpdateDescendantDocuments _stopMovementOnDisconnect _updateDiff applyActiveEffects canUserModify clearMovementHistory clone createEmbeddedDocuments delete deleteEmbeddedDocuments getBarAttribute getCenterPoint getCompleteMovementPath getContainmentTestPoints getEmbeddedCollection getEmbeddedDocument getFieldForProperty getFlag getGridSpacePolygon getLightOrigin getListenerPosition getMovementOrigin getOcclusionTestPoints getOccupiedGridSpaceOffsets getSize getSnappedPosition getSoundOrigin getUserLevel getVisibilityTestPoints getVisionOrigin hasStatusEffect includedInLevel measureMovementPath migrateSystemData move pauseMovement prepareBaseData prepareData prepareDerivedData prepareEmbeddedDocuments reset resize resumeMovement revertRecordedMovement segmentizeRegionMovementPath setFlag startMovement stopMovement testInsideRegion testUserPermission toggleCombatant toJSON toObject traverseEmbeddedDocuments unsetFlag update updateEmbeddedDocuments updateSource updateVisionMode validate _constrainTestPoints _couldRegionsChange _getReplacementData _inferMovementAction _inferRingSubjectTexture _onMovementPaused _onMovementPlanned _onMovementRecorded _onMovementStopped _onOverrideSize _onRelatedUpdate _onUpdateMovement _preDelete _prepareBars _prepareDetectionModes _preUpdateMovement _preUpdateSource _renderActiveEffectChanges _shouldRecordMovementHistory _updateCommit _addDataFieldMigration _addDataFieldShim _addDataFieldShims _addTeleportAndForcedShims _clearFieldsRecursively _getHexagonalOffsets _getHexagonalShape _isMovementUpdate _logDataFieldMigration _onCreateOperation _onDeleteOperation _onUpdateOperation _preCleanData _preCreateOperation _preUpdateOperation arePositionsEqual canUserCreate cleanData create createCombatants createDocuments defineSchema deleteCombatants deleteDocuments fromJSON fromSource get getCollectionName getTrackedAttributeChoices getTrackedAttributes migrateData migrateDataSafe shimData updateDocuments validateJoint _cleanData _getConfiguredTrackedAttributes _getTrackedAttributesFromObject _getTrackedAttributesFromSchema _preDeleteOperation

    Constructors

    Properties

    _movementContinuation: TokenMovementContinuationData = ...

    The movement continuation state of this Token document.

    _returnedMovementPromises: Map<string, Promise<boolean>> = ...

    The movement promises with their resolvers.

    _source: TokenData

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

    actors: Collection<string, documents.Actor> = ...

    A singleton collection which holds a reference to the synthetic token actor by its base actor's ID.

    attachments: Readonly<{ regions: ReadonlySet<RegionDocument> }> = ...

    The attachments of this Token.

    parent: DataModel<object, DataModelConstructionContext> | null

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

    regions: Set<RegionDocument> = ...

    The Regions this Token is currently in.

    overrides: Record<string, unknown>

    Property overrides copied from this TokenDocument's associated Actor

    _ACTIVE_EFFECT_TARGETABLE_KEYS: readonly [
        "name",
        "width",
        "height",
        "depth",
        "texture",
        "alpha",
        "disposition",
        "light",
        "sight",
        "detectionModes",
        "ring",
        "turnMarker",
        "movementAction",
        "flags",
    ] = ...

    Keys targetable by a ActiveEffectChanges. Width, height, and depth are included but not automatically applied to Token data.

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

    DEFAULT_ICON: string = CONST.DEFAULT_TOKEN

    The default icon used for newly created Token documents

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

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

    MOVEMENT_FIELDS: readonly [
        "x",
        "y",
        "elevation",
        "width",
        "height",
        "depth",
        "shape",
        "level",
    ] = ...

    The fields of the data model for which changes count as a movement action.

    Accessors

    • get actor(): documents.Actor | null

      A reference to the Actor this Token modifies. If actorLink is true, then the document is the primary Actor document. Otherwise, the Actor document is a synthetic (ephemeral) document constructed using the Token's ActorDelta.

      Returns documents.Actor | null

    • get combatant(): documents.Combatant | null

      Return a reference to a Combatant that represents this Token, if one is present in the current encounter.

      Returns documents.Combatant | null

    • get compendium(): any

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

      Returns any

    • get hasDistinctSubjectTexture(): boolean

      Check if the document has a distinct subject texture (inferred or explicit).

      Returns boolean

    • get id(): string | null

      The canonical identifier for this Document.

      Returns string | null

    • get inCombat(): boolean

      An indicator for whether this Token is currently involved in the active combat encounter.

      Returns boolean

    • 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 isEmbedded(): boolean

      Is this document embedded within a parent document?

      Returns boolean

    • get isLinked(): boolean

      A convenient reference for whether this TokenDocument is linked to the Actor it represents, or is a synthetic copy

      Returns boolean

    • get isOwner(): boolean

      An indicator for whether the current User has full control over this Token document.

      Returns boolean

    • get isSecret(): boolean

      Does this TokenDocument have the SECRET disposition and is the current user lacking the necessary permissions that would reveal this secret?

      Returns boolean

    • get uuid(): string

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

      Returns string

    • 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 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: string | null

        An explicitly provided parent collection name.

      Returns string | null

    • Internal

      Identify the Regions the Token currently is or is going to be in after the changes are applied.

      Parameters

      • Optionalchanges: object = {}

        The changes that will be applied to this Token

      Returns string[]

      The Region IDs this Token is in after the changes are applied (sorted)

    • 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

      • options: {} = {}

        Options provided to the model constructor

      Returns void

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

      Parameters

      • data: any

        The candidate source data from which the model will be constructed

      • options: any

        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

    • 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

    • Internal

      When the base Actor for a TokenDocument changes, we may need to update its Actor instance

      Parameters

      • Optionalupdate: object = {}

        The update delta

      • Optionaloptions: Partial<DatabaseUpdateOperation> = {}

        The database operation that was performed

      Returns void

    • Parameters

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

      Returns void

    • 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: any

        The initial data object provided to the document creation request

      • options: any

        Additional options which modify the creation request

      • user: any

        The User requesting the document creation

      Returns Promise<false | undefined>

      Return false to exclude this Document from the creation operation

    • Parameters

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

      Returns void

    • Parameters

      • parent: any
      • collection: any
      • ids: 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<false | undefined>

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

    • Parameters

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

      Returns void

    • Internal

      This function is called on Token documents that are still being moved by a User that just disconnected.

      Returns void

    • Perform the first step of the DataModel#_updateSource workflow which applies changes to a copy of model source data and records the resulting diff.

      Parameters

      • copy: any

        A mutable copy of model source data

      • changes: any

        New values which should be applied to the data model

      • options: any

        Options which determine how the new data is merged

      • _state: any

        Data cleaning state

      Returns object

      The resulting difference applied to source data

      A failure if the proposed change is invalid

    • Refresh this TokenDocument's overrides and transmit changes, if any, to its PlaceableObject for rendering.

      Parameters

      • Optionalphase: string

        The application phase under which changes are to be applied

      Returns void

    • 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 this Token.

      Returns Promise<void>

    • A helper method to retrieve the underlying data behind one of the Token's attribute bars

      Parameters

      • barName: string

        The named bar to retrieve the attribute for

      • Optionaloptions: { alternative?: string } = {}
        • Optionalalternative?: string

          An alternative attribute path to get instead of the default one

      Returns object | null

      The attribute displayed on the Token bar, if any

    • Get the points that are used to test region containment/segmentation (unless overridden) for this Token. The test points are within the shape of the Token.

      Implementations of this function must use the prepared position and dimensions of this Token.

      Parameters

      • Optionaldata: Partial<ElevatedPoint & TokenPosition> = {}

        The position and dimensions. Defaults to the values of the prepared document, not the document source.

      Returns Point[]

      The test points.

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

      Parameters

      • embeddedName: any

        The name of the embedded Document type

      Returns any

      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.

    • Traverse the data model instance, obtaining the DataField definition for a field of a particular property.

      Parameters

      • key: string | string[]

        A property key like ["abilities", "strength"] or "abilities.strength"

      Returns DataField | undefined

      The corresponding DataField definition for that field, or undefined

    • 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

    • Get the grid space polygon of the Token. Returns undefined in gridless grids because there are no grid spaces.

      Parameters

      Returns void | Point[]

      The grid space polygon or undefined if gridless

    • Get the points that are used to test occlusion for this Token. The test points are within the shape of the Token.

      Implementations of this function must use the prepared position and dimensions of this Token.

      Parameters

      • Optionaldata: Partial<ElevatedPoint & TokenPosition> = {}

        The position and dimensions. Defaults to the values of the prepared document, not the document source.

      Returns Point[]

      The test points.

    • Get the offsets of grid spaces that are occupied by this Token at the current or given position. The grid spaces the Token occupies are those that are covered by the Token's shape in the snapped position. Returns an empty array in gridless grids.

      Parameters

      Returns GridOffset3D[]

      The offsets of occupied grid spaces

    • Get the width and height of the Token in pixels.

      Parameters

      • Optionaldata: Partial<{ height: number; width: number }> = {}

        The width and/or height in grid units (must be positive)

      Returns { height: number; width: number }

      The width and height in pixels

    • Get the points that are used to test visibility for this Token. The test points are within the shape of the Token.

      Implementations of this function must use the prepared position and dimensions of this Token.

      Parameters

      • Optionaldata: Partial<ElevatedPoint & TokenPosition> = {}

        The position and dimensions. Defaults to the values of the prepared document, not the document source.

      Returns ElevatedPoint[]

      The test points.

    • Test whether a Token has a specific status effect.

      Parameters

      • statusId: string

        The status effect ID as defined in CONFIG.statusEffects

      Returns boolean

      Does the Actor of the Token have this status effect?

    • Parameters

      • level: any

      Returns any

    • 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

    • Pause the movement of this Token document. The movement can be resumed after being paused. Only the User that initiated the movement can pause it. Returns a callback that can be used to resume the movement later. Only after all callbacks and keys have been called the movement of the Token is resumed. If the callback is called within the update operation workflow, the movement is resumed after the workflow.

      Returns TokenResumeMovementCallback | null

      The callback to resume movement if the movement was or is paused, otherwise null

      // On TOKEN_MOVE_IN...
      if ( !event.user.isSelf ) return;
      const resumeMovement = event.data.token.pauseMovement();
      if ( event.data.token.rendered ) await event.data.token.object.movementAnimationPromise;
      await event.data.token.actor.toggleStatusEffect("invisible", {active: true});
      const resumed = await resumeMovement();
    • Pause the movement of this Token document. The movement can be resumed after being paused. Only the User that initiated the movement can pause it. Returns a promise that resolves to true if the movement was resumed by TokenDocument#resumeMovement with the same key that was passed to this function. Only after all callbacks and keys have been called the movement of the Token is resumed. If the callback is called within the update operation workflow, the movement is resumed after the workflow.

      Parameters

      Returns Promise<boolean> | null

      The continuation promise if the movement was paused, otherwise null

      // On TOKEN_MOVE_IN...
      if ( event.user.isSelf ) {
      event.data.token.pauseMovement(this.parent.uuid);
      }
      if ( game.user.isActiveGM ) {
      if ( event.data.token.rendered ) await event.data.token.object.movementAnimationPromise;
      const trapUuid; // The Region Behavior UUID of the trap
      const trapBehavior = await fromUuid(trapUuid);
      await trapBehavior.update({disabled: false});
      event.data.token.resumeMovement(event.data.movement.id, this.parent.uuid);
      }
    • Returns void

    • Returns void

    • Returns void

    • Returns void

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

      Returns void

    • Resize the Token such that its center point remains (almost) unchanged. The center point might change slightly because the new (x, y) position is rounded.

      Parameters

      • dimensions: Partial<Omit<TokenData & TokenMovementWaypoint, "x" | "y" | "elevation">>

        The new dimensions and additional data.

      • Optionaloptions: Partial<
            Omit<DatabaseUpdateOperation, "updates"> & Omit<
                TokenMovementOptions,
                | "measureOptions"
                | "autoRotate"
                | "showRuler"
                | "terrainOptions"
                | "constrainOptions",
            >,
        >

        Parameters of the update operation.

      Returns Promise<boolean>

      A Promise that resolves to true if the Token was resized, otherwise resolves to false.

    • Undo all recorded movement or the recorded movement corresponding to given movement ID up to the last movement. The token is displaced to the prior recorded position and the movement history it rolled back accordingly.

      Parameters

      • OptionalmovementId: string

        The ID of the recorded movement to undo

      Returns Promise<boolean>

      True if the movement was undone, otherwise false

    • Split the Token movement path through the Region into its segments. The Token and the Region must be in the same Scene.

      Implementations of this function are restricted in the following ways:

      • The segments must go through the waypoints.
      • The from position matches the to position of the succeeding segment.
      • The Token must be contained (w.r.t. TokenDocument#testInsideRegion) within the Region at the from and to of MOVE segments.
      • The Token must be contained (w.r.t. TokenDocument#testInsideRegion) within the Region at the to position of ENTER segments.
      • The Token must be contained (w.r.t. TokenDocument#testInsideRegion) within the Region at the from position of EXIT segments.
      • The Token must not be contained (w.r.t. TokenDocument#testInsideRegion) within the Region at the from position of ENTER segments.
      • The Token must not be contained (w.r.t. TokenDocument#testInsideRegion) within the Region at the to position of EXIT segments.
      • This function must not use prepared field values that are animated. In particular, it must use the source instead of prepared values of the following fields: x, y, elevation, width, height, and shape.

      Parameters

      Returns TokenRegionMovementSegment[]

      The movement split into its segments

    • 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

    • Start the currently planned movement of this Token. Only owners of the Token can start the movement.

      Returns Promise<boolean>

      True if the movement was started, false otherwise

    • Start the planned movement of this Token given the movement ID. Only owners of the Token can start the movement.

      Parameters

      • movementId: string

        The movement ID

      Returns Promise<boolean>

      True if the movement was started, false otherwise

    • Stop the movement of this Token document. The movement cannot be continued after being stopped. Only the User that initiated the movement can stop it.

      Returns boolean

      True if the movement was or is stopped, otherwise false

    • Test whether the Token is inside the Region. This function determines the state of TokenDocument#regions and foundry.documents.RegionDocument#tokens. The Token and the Region must be in the same Scene.

      Implementations of this function are restricted in the following ways:

      • If the bounds (given by TokenDocument#getSize) of the Token do not intersect the Region, then the Token is not contained within the Region.
      • If the Token is inside the Region a particular elevation, then the Token is inside the Region at any elevation within the elevation range of the Region.
      • This function must not use prepared field values that are animated. In particular, it must use the source instead of prepared values of the following fields: x, y, elevation, width, height, and shape.

      If this function is overridden, then TokenDocument#segmentizeRegionMovementPath must be overridden too.

      If an override of this function uses Token document fields other than x, y, elevation, width, height, and shape, TokenDocument#_couldRegionsChange must be overridden to return true for changes of these fields. If an override of this function uses non-Token properties other than Scene#grid.type and Scene#grid.size, foundry.documents.Scene#updateTokenRegions must be called when any of those properties change.

      Parameters

      Returns boolean

      Is inside the Region?

    • Parameters

      Returns boolean

      Is inside the Region?

    • 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?

    • Add or remove this Token from a Combat encounter.

      Parameters

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

        Additional options passed to TokenDocument.createCombatants or TokenDocument.deleteCombatants

        • Optionalactive?: boolean

          Require this token to be an active Combatant or to be removed. Otherwise, the current combat state of the Token is toggled.

      Returns Promise<boolean>

      Is this Token now an active Combatant?

    • 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 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: {} = {}

        New values which should be applied to the data model

      • options: {} = {}

        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

    • Convenience method to change a token vision mode.

      Parameters

      • visionMode: string

        The vision mode to apply to this token.

      • Optionaldefaults: boolean = true

        If the vision mode should be updated with its defaults.

      Returns Promise<TokenDocument | undefined>

      The updated Document instance, or undefined not updated.

    • Validate the data contained in the document to check for type and content. This method is intended to validate complete model records, verifying both individual field validation as well as joint model validity.

      For validating sets of partial model changes, it is preferred to call DataModel#updateSource as a dryRun. This method provides a convenience alias for such a workflow if changes are provided.

      Warning: if fallback handling is allowed, this process will mutate provided changes or model source data.

      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

      Constrain the test points by walls and surfaces. The passed array of test points are modified in place. If all points are discarded, the movement origin is added to the array of test points.

      Parameters

      • points: (Point | ElevatedPoint)[]

        The test points, which are modified in place.

      • Optionaldata: Partial<ElevatedPoint & TokenPosition>

        The position and dimensions. Defaults to the values of the prepared document, not the document source.

      Returns (Point | ElevatedPoint)[] | undefined

    • Protected

      Is the Token document updated such that the Regions the Token is contained in may change? Called as part of the preUpdate workflow.

      Parameters

      • changes: object

        The changes.

      Returns boolean

      Could this Token update change Region containment?

    • Protected

      Get replacement data for ActiveEffect change application to this Token.

      Returns object

    • Protected

      Infer the movement action. The default implementation returns CONFIG.Token.movement.defaultAction.

      Returns string

    • Protected

      Infer the subject texture path to use for a token ring.

      Returns string

    • Protected

      Called when the current movement is paused.

      Returns void

    • Protected

      Called when the current movement is planned.

      Returns void

    • Protected

      Called when the movement is recorded or cleared.

      Returns void

    • Protected

      Called when the current movement is stopped.

      Returns void

    • Protected

      Callback invoked when _onRelatedUpdate detects overrides of at least one Token dimension. Enacting such changes requires a server update and may involve nuances particular to a given system. While this method is async, it is not awaited by the caller.

      Parameters

      • changes: { depth?: number; height?: number; width?: number }

      Returns Promise<void>

    • Protected

      Whenever the token's actor delta changes, or the base actor changes, perform associated refreshes.

      Parameters

      • Optionalupdate: object | object[] = {}

        The update delta

      • Optionaloperation: Partial<DatabaseWriteOperation> = {}

        The database operation that was performed

      Returns void

    • 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

      Extend data in attribute-bar properties.

      Returns void

    • Protected

      Prepare detection modes which are available to the Token. Ensure that every Token has the basic sight detection mode configured.

      Returns void

    • Protected

      Reject the movement or modify the update operation as needed based on the movement. Called after the movement for this document update has been determined. The waypoints of movement are final and cannot be changed. The movement can only be rejected entirely.

      Parameters

      Returns Promise<boolean | void>

      If false, the movement is prevented

    • Protected

      Send emulated update data to the Token PlaceableObject

      Parameters

      • oldOverrides: object

        Overrides prior to data reinitialization

      Returns void

    • Protected

      Should the movement of this Token update be recorded in the movement history? Called as part of the preUpdate workflow if the Token is moved.

      Returns boolean

      Should the movement of this Token update be recorded in the movement history?

    • Protected

      Perform the second step of the DataModel#_updateSource workflow which applies the prepared diff to the model.

      Parameters

      • copy: object

        The prepared copy of source data with changes applied

      • diff: object

        The differential changes that were applied to source

      • options: DataModelUpdateOptions

        Options which determine how the new data is merged

      • _state: data.types.DataModelUpdateState

        Data cleaning state which might include instructions for final commit

      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

      Are these changes moving the Token?

      Parameters

      • changes: object

        The (candidate) changes

      Returns boolean

      Is movement?

    • Internal

      Are these changes moving the Token from the given origin?

      Parameters

      • changes: object

        The (candidate) changes

      • origin: TokenPosition

        The origin

      Returns boolean

      Is movement?

    • Internal

      Log a compatbility warning for the data field migration.

      Parameters

      Returns void

    • Post-process a creation operation, reacting to database changes which have occurred. Post-operation events occur for all connected clients.

      This batch-wise workflow occurs after individual _onCreate workflows.

      Parameters

      • documents: any

        The Document instances which were created

      • operation: any

        Parameters of the database creation operation

      • user: any

        The User who performed the creation operation

      Returns Promise<void>

    • Parameters

      • documents: any
      • operation: any
      • user: any

      Returns Promise<void>

    • Parameters

      • documents: any
      • operation: any
      • user: any

      Returns Promise<void>

    • Apply preliminary model-specific cleaning rules or alter cleaning options or initial state. Subclass models may implement this function to configure the cleaning workflow. Any mutations to data, options, or _state parameters are performed inplace.

      Parameters

      • data: any

        The provided input data for cleaning

      • options: any

        Options which define how cleaning should be performed

      • _state: any

        The data cleaning state

      Returns void

    • 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

      • documents: any

        Pending document instances to be created

      • operation: any

        Parameters of the database creation operation

      • user: any

        The User requesting the creation operation

      Returns Promise<false | undefined>

      Return false to cancel the creation operation entirely

    • 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

      • documents: any

        Document instances to be updated

      • operation: any

        Parameters of the database update operation

      • user: any

        The User requesting the update operation

      Returns Promise<false | undefined>

      Return false to cancel the update operation entirely

    • 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?

    • Create or remove Combatants for an array of provided Token objects.

      Parameters

      • tokens: TokenDocument[]

        The tokens which should be added to the Combat

      • Optionaloptions: { combat?: documents.Combat } = {}

        Options which modify the toggle operation

        • Optionalcombat?: documents.Combat

          A specific Combat instance which should be modified. If undefined, the current active combat will be modified if one exists. Otherwise, a new Combat encounter will be created if the requesting user is a Gamemaster.

      Returns Promise<documents.Combatant[]>

      An array of created Combatant documents

    • 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 string | null

      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"
    • Inspect the Actor data model and identify the set of attributes which could be used for a Token Bar.

      Parameters

      • attributes: object

        The tracked attributes which can be chosen from

      Returns object

      A nested object of attribute choices to display

    • Migrate candidate source data for this DataModel which may require initial cleaning or transformations.

      Parameters

      • data: any

        Candidate source data for the module, before further cleaning

      Returns object

      Migrated source data, ready for further cleaning

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

      Parameters

      • source: object

        Candidate source data for the module, before further cleaning

      • Optionaloptions: Readonly<DataModelCleaningOptions> = {}

        Additional options for how the field is cleaned

      Returns object

      Migrated source data, ready for further cleaning

    • 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: any

        Data which matches the current schema

      • options: any

        Additional shimming options

      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

      Apply final custom model-specific cleaning rules after data schema fields are cleaned. Subclass models can implement this function as an ideal place to apply custom imputation or cleaning. Cleaning must be done in-place rather than returning a different object.

      Parameters

      Returns object

      The original data object, with cleaning performed inplace

    • Protected

      Retrieve an Array of attribute choices from a plain object.

      Parameters

      • data: object

        The object to explore for attributes.

      • _path: string[] = []

      Returns TrackedAttributesDescription

    • 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