[Go to site: main page, start]

The client-side Scene document which extends the common BaseScene model.

ClientDocumentMixin

Hierarchy (View Summary)

Index

Constructors

Properties

Accessors

Methods

_configure _configureLevelTextures _getParentCollection _initializationOrder _initialize _invalidateSurfaces _onClickDocumentLink _onCreate _onCreateDescendantDocuments _onDelete _onDeleteDescendantDocuments _onUpdate _onUpdateDescendantDocuments _preCreate _preCreateDescendantDocuments _preDeleteDescendantDocuments _preUpdate _preUpdateDescendantDocuments _resetEdges _updateCommit _updateDiff _updateRegionShapeConstraints activate canUserModify clearMovementHistories clone createEmbeddedDocuments createThumbnail cycleLevel delete deleteEmbeddedDocuments getDimensions getEmbeddedCollection getEmbeddedDocument getFieldForProperty getFlag getSurfaces getUserLevel initializeEdges migrateSystemData moveTokens prepareBaseData prepareDerivedData prepareEmbeddedDocuments pullUsers reset setFlag testSurfaceCollision testUserPermission toCompendium toJSON toObject traverseEmbeddedDocuments unsetFlag unview update updateEmbeddedDocuments updateRegionShapeConstraints updateSource updateTokenRegions validate view _getAvailableLevels _getInnerModel _initializeSource _onActivate _preDelete _preUpdateSource _addDataFieldMigration _addDataFieldShim _addDataFieldShims _clearFieldsRecursively _logDataFieldMigration _onUpdateOperation _preCleanData _preCreateOperation canUserCreate cleanData create createDocuments defineSchema deleteDocuments fromJSON fromSource get getCollectionName migrateData migrateDataSafe shimData updateDocuments validateJoint _cleanData _onCreateOperation _onDeleteOperation _preDeleteOperation _preUpdateOperation

Constructors

Properties

_source: SceneData

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

_view: string | null = null

Track whether the scene is the active view and which level is viewed

_viewPosition: CanvasViewPosition = {}

Track the viewed position of each scene (while in memory only, not persisted) When switching back to a previously viewed scene, we can automatically pan to the previous position.

dimensions: SceneDimensions = ...

Determine the canvas dimensions this Scene would occupy, if rendered

The grid instance.

gridlessGrid: GridlessGrid = ...

The gridless version of the grid instance.

parent: DataModel<object, DataModelConstructionContext> | null

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

_availableLevels: Set<documents.Level> | null = null
_LEVELS_PROPERTY_MAP: readonly string[][] = ...

A mapping of top-level scene properties to their corresponding properties on the child level.

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

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

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

Accessors

  • get availableLevels(): Set<documents.Level>

    The levels that are available to this User. By default GMs and scenes without token vision can access all levels; players can only access levels where they have OBSERVER of a Token. A SceneManager may override this via SceneManager#_getAvailableLevels.

    Returns Set<documents.Level>

  • get compendium(): any

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

    Returns any

  • get firstLevel(): BaseLevel

    A convenience getter for the Scene's first created Level. This should not be relied on in multi-level scenes to mean the first level by sort order.

    Returns BaseLevel

  • get id(): string | null

    The canonical identifier for this Document.

    Returns string | null

  • get inCompendium(): boolean

    Is this document in a compendium?

    Returns boolean

  • get initializedEdges(): boolean

    Have the edges of this Scene been initialized already?

    The property becomes true we moment Scene#initializeEdges is called.

    Returns boolean

  • get initialLevel(): BaseLevel

    The initial Level of the Scene. By default the first Level.

    Returns BaseLevel

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

    A convenience accessor for whether the Scene is currently viewed

    Returns boolean

  • get thumbnail(): string | null

    Provide a thumbnail image path used to represent this document.

    Returns string | null

  • get uuid(): string | null

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

    Returns string | null

  • 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 defaultGrid(): BaseGrid

    The default grid defined by the system.

    Returns BaseGrid

  • get defaultGridlessGrid(): GridlessGrid

    The gridless version of the default grid defined by the system.

    Returns GridlessGrid

  • 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

    • options: {} = {}

    Returns void

  • Internal

    Get textures that should be used for the currently active level.

    Returns (
        LevelTexture & {
            elevation: number;
            isBackground: boolean;
            isUpper: boolean;
            level: documents.Level;
            name: string;
            sort: number;
            zIndex: number;
        }
    )[]

  • 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

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

      Options provided to the model constructor

    Returns void

  • Internal

    Invalidate cached surface data.

    Returns void

  • Parameters

    • event: any

    Returns any

  • 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
    • changes: 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 Promise<any> | undefined

  • 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 | Readonly<Notification> | 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

    Reset the edges of this Scene.

    Returns void

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

    Parameters

    • copy: any

      The prepared copy of source data with changes applied

    • diff: any

      The differential changes that were applied to source

    • options: any

      Options which determine how the new data is merged

    • state: any

      Data cleaning state which might include instructions for final commit

    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

  • Internal

    Update the shape constraints of the given Regions if the current User is designated for it.

    Parameters

    Returns void

  • Set this Scene as currently active.

    Parameters

    • Optionaloptions: {
          pullUsers?: boolean;
          updateData?: Partial<Omit<SceneData, "active">>;
          updateOptions?: Partial<Omit<DatabaseUpdateOperation, "updates">>;
          viewOptions?: SceneViewOptions;
      } = {}

      Additional options

      • OptionalpullUsers?: boolean

        Pull all Users to this Scene if it is already active?

      • OptionalupdateData?: Partial<Omit<SceneData, "active">>

        Additional update data

      • OptionalupdateOptions?: Partial<Omit<DatabaseUpdateOperation, "updates">>

        The update operation options

      • OptionalviewOptions?: SceneViewOptions

        The view options

    Returns Promise<documents.Scene>

    A Promise which resolves to this Scene once it has been successfully activated

  • 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 Scene.

    Returns Promise<void>

  • Create a 300px by 100px thumbnail image for this scene background

    Parameters

    • Optionaloptions: {
          format?: string;
          height?: number;
          level?: string | documents.Level;
          quality?: number;
          width?: number;
      } = {}

      Options which modify thumbnail creation

      • Optionalformat?: string

        Which image format should be used? image/png, image/jpeg, or image/webp. Default is image/webp.

      • Optionalheight?: number

        The desired thumbnail height. Default is 100px;

      • Optionallevel?: string | documents.Level

        The Level to generated the thumbnail for. Defaults to the initial level.

      • Optionalquality?: number

        What compression quality should be used for jpeg or webp, between 0 and 1. Default is 0.8.

      • Optionalwidth?: number

        The desired thumbnail width. Default is 300px

    Returns Promise<
        {
            format: string;
            height: number;
            quality: number;
            thumb: string;
            width: number;
        },
    >

    The created thumbnail data.

  • Cycle the currently viewed Level for this Scene.

    Parameters

    • direction: -1 | 1

    Returns Promise<void>

  • Get the Canvas dimensions which would be used to display this Scene. Apply padding to enlarge the playable space and round to the nearest 2x grid size to ensure symmetry. The rounding accomplishes that the padding buffer around the map always contains whole grid spaces.

    Returns SceneDimensions

  • 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 all surfaces or surfaces matching the filter, ordered by elevation in ascending order.

    Parameters

    • Optionaloptions: {
          culling?: boolean;
          exposure?: boolean;
          level?: string | documents.Level;
          occlusion?: boolean;
          type?: "darkness" | "light" | "sight" | "sound" | "move";
      } = {}

      Additional options

      • Optionalculling?: boolean

        Only return surfaces that have this value as RegionSurface#culling

      • Optionalexposure?: boolean

        Only return surfaces that have this value as RegionSurface#exposure

      • Optionallevel?: string | documents.Level

        Only return surfaces that are included in this Level

      • Optionalocclusion?: boolean

        Only return surfaces that have this value as RegionSurface#occlusion

      • Optionaltype?: "darkness" | "light" | "sight" | "sound" | "move"

        Only return surfaces that restrict this type

    Returns readonly DeepReadonly<RegionSurface>[]

  • 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

  • Initialize the edges of this Scene unless they already have been inititalized.

    Returns void

  • 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

  • Move/resize multiple Tokens.

    Parameters

    Returns Promise<{ [id: string]: boolean }>

    A Promise that resolves once all movement instructions are finished. The resolved value is an object with token IDs as keys and booleans as values that indicate whether the movement the token with the corresponding ID was completed (true) or stopped/prevented (false).

    const results = await scene.moveTokens({
    // Moving the token to new position including additional token data
    "cGYT0rR0YbtFkhzT": {
    destination: {x: 100, y: 200, rotation: 45, texture: {tint: "#ff0000"}},
    showRuler: false, // This overrides `options.showRuler`
    },
    // Moving the token to along a path with multiple waypoints
    "wBFpJuZuleEtVNw1": {
    waypoints: [
    {x: 100, y: 200}, // Move to the position (100, 200)
    {elevation: 5, explicit: true}, // Move to elevation 5 indicating that the user placed this waypoint
    {x: 500, y: 500, checkpoint: true}, // Move to (500, 500): the movement can be stopped/paused here
    {width: 2, height: 2, depth: 2}, // Change size
    {x: 1000, action: "swim"}, // Swim to (1000, 500)
    {x: 0, y: 0, snapped: true}, // Move to (0, 0) indicating that (0, 0) is a snapped position for the token
    {elevation: 10} // Move to elevation 10 (the last waypoint is always a checkpoint automatically)
    ],
    autoRotate: true,
    constrainOptions: {ignoreWalls: true, ignoreCost: true} // Allow the token to move through walls, surfaces, and
    // impassable terrain
    },
    // Resizing the token including additional token data
    "VupAIbzpX6SHqtaH": {
    dimensions: {width: 3, height: 3, depth: 3, rotation: 45, texture: {tint: "#ff0000"}}
    }
    }, {
    showRuler: true // This applies to all instructions that do not define `showRuler`
    })
    if ( results["cGYT0rR0YbtFkhzT"] ) {
    // The movement of Token [cGYT0rR0YbtFkhzT] was completed: it arrived at the destination
    } else {
    // The movement of Token [cGYT0rR0YbtFkhzT] was stopped or prevented
    }
    if ( results["wBFpJuZuleEtVNw1"] ) {
    // The movement of Token [wBFpJuZuleEtVNw1] was completed: it arrived at the destination
    } else {
    // The movement of Token [wBFpJuZuleEtVNw1] was stopped or prevented
    }
    if ( results["VupAIbzpX6SHqtaH"] ) {
    // The resizing of Token [VupAIbzpX6SHqtaH] was completed
    } else {
    // The resizing of Token [VupAIbzpX6SHqtaH] was prevented
    }
  • Returns void

  • Returns void

  • Returns void

  • Pull the specified users to this Scene.

    Parameters

    Returns void

    canvas.scene.pullUsers(game.users);
    
  • 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

  • Test for surface collision for a movement between two points.

    Parameters

    • origin: ElevatedPoint

      The origin.

    • destination: ElevatedPoint

      The destination.

    • config: {
          level: string | documents.Level;
          mode?: "any" | "closest" | "all";
          side?: "below" | "above";
          tMax?: number;
          tMin?: number;
          type?: "darkness" | "light" | "sight" | "sound" | "move";
      }

      Configuration.

      • level: string | documents.Level

        The Level or Level ID to test collision in.

      • Optionalmode?: "any" | "closest" | "all"

        The collision mode. Default: "any".

      • Optionalside?: "below" | "above"

        The side of the surface that counts as colliding when the ray originates on the surface. Default: "below". - "below": Treats the surface as solid in the negative z-direction. Rays originating on the surface will collide if they point downward (z < 0) and will not collide if they point upward. - "above": Treats the surface as solid in the positive z-direction. Rays originating on the surface will collide if they point upward (z > 0) and will not collide if they point downward.

      • OptionaltMax?: number

        Intersections of the ray and a surface with t-value greater than tMax are not considered collisions. Default: 1.

      • OptionaltMin?: number

        Intersections of the ray and a surface with t-value less than tMin are not considered collisions. Default: 0.

      • Optionaltype?: "darkness" | "light" | "sight" | "sound" | "move"

        The restriction type. Default: "move".

    Returns boolean | ElevatedPoint | ElevatedPoint[] | null

    The collision result depends on the mode of the test: - "any": Returns a boolean for whether any collision occurred. - "all": Returns a sorted array of ElevatedPoint instances. - "closest": Returns an ElevatedPoint instance or null.

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

  • Parameters

    • pack: any
    • options: {} = {}

    Returns any

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

  • Unview this Scene, if it is the viewed Scene, clearing the game canvas.

    Returns Promise<documents.Scene | undefined>

  • Update the shape constraints of all Regions the current User is designated for (for the given restriction types).

    Parameters

    • Optionaltypes: Iterable<"darkness" | "light" | "sight" | "sound" | "move", any, any> = CONST.EDGE_RESTRICTION_TYPES

      The types to update. Default: all.

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

      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

  • For the given Tokens in this Scene identify the Regions that each Token is contained in and update the regions of each Token accordingly.

    This function doesn't need to be called by the systems/modules unless foundry.documents.TokenDocument#testInsideRegion is overridden and non-Token properties other than Scene#grid.type and Scene#grid.size change that are used in the override of foundry.documents.TokenDocument#testInsideRegion.

    Parameters

    • Optionaltokens: Iterable<TokenDocument, any, any> = ...

      The Tokens whoses regions should be updates: if not provided, all Tokens will be updated.

    Returns Promise<TokenDocument[]>

    The array of Tokens whose regions changed

  • 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

    The levels that are available to this User in ascending order. By default GMs and scenes without token vision can access all levels; players can only access levels where they have OBSERVER of a Token.

    Parameters

    • Optionaloptions: { manager?: SceneManager | null } = {}
      • Optionalmanager?: SceneManager | null

        A SceneManager whose SceneManager#_getAvailableLevels override should be applied to the base set.

    Returns Set<documents.Level>

  • Protected

    Resolve a previously-initialized embedded DataModel that corresponds to an element being cleaned. Called during recursive data cleaning when a parent field contains EmbeddedDataField elements, or a single nested DataModel field (such as a TypeDataField), in order to propagate the inner DataModel into _state.model for the recursive clean operation. A single (non-collection) inner model resolves to itself; collection elements are matched by stable _id when one is present, otherwise by positional index.

    Subclasses may override when data preparation reshapes the field property in a way that the default cannot interpret, for example wrapping the container in a non-iterable type or replacing it with a derived view.

    Parameters

    • field: DataField

      The schema field being recursed into.

    • element: { index?: number; value: object } = {}
      • Optionalindex?: number

        The positional index of the element within a container, if applicable.

      • value: object

        The cleaned candidate value for the element being processed.

    • Optionaloptions: Readonly<DataModelCleaningOptions> = {}

      The cleaning options in effect for the operation.

    Returns DataModel<object, DataModelConstructionContext> | null

    The corresponding previously-initialized inner DataModel, or null.

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

  • 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

    Log a compatbility warning for the data field migration.

    Parameters

    Returns void

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

    This batch-wise workflow occurs after individual _onUpdate workflows.

    Parameters

    • documents: any

      The Document instances which were updated

    • operation: any

      Parameters of the database update operation

    • user: any

      The User who performed the update operation

    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<void>

    Return false to cancel the creation 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 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

    If an invalid operation is attempted.

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

      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"
  • Migrate candidate source data for this DataModel which may require initial cleaning or transformations.

    Parameters

    • source: any

      Candidate source data for the module, before further cleaning

    • options: any

      Additional options for how the field is cleaned

    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

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

    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