[Go to site: main page, start]

Class RegionDocument

The client-side Region document which extends the common BaseRegion model.

CanvasDocumentMixin

Hierarchy (View Summary)

Index

Constructors

Properties

Accessors

Methods

Constructors

Properties

_source: RegionData

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

parent: DataModel<object, DataModelConstructionContext> | null

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

tokens: ReadonlySet<TokenDocument> = ...

The tokens inside this region.

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 area(): number

    The area of this Region.

    Alias for this.polygonTree.area.

    Returns number

  • get bounds(): Rectangle

    The bounds of this Region.

    The value of this property must not be mutated.

    Alias for this.polygonTree.bounds.

    Returns Rectangle

  • get clipperPolyTree(): PolyTree

    The Clipper polygon tree of this Region.

    The value of this property must not be mutated.

    Returns PolyTree

  • get compendium(): any

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

    Returns any

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

    Does this Region have a single shape that is not a hole?

    Returns boolean

  • get polygons(): readonly Polygon[]

    The polygons of this Region.

    The value of this property must not be mutated.

    Alias for this.polygonTree.polygons.

    Returns readonly Polygon[]

  • get polygonTree(): PolygonTree

    The polygon tree of this Region.

    The value of this property must not be mutated.

    Returns PolygonTree

  • get triangulation(): Readonly<
        { indices: Uint16Array
        | Uint32Array; vertices: Float32Array },
    >

    The triangulation of this Region.

    The value of this property must not be mutated.

    Alias for this.polygonTree.triangulation.

    Returns Readonly<{ indices: Uint16Array | Uint32Array; vertices: Float32Array }>

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

  • Internal

    Clear the polygon tree.

    Returns void

  • Internal

    Update the point sources of this Region document.

    Parameters

    • Optionalchanges: object = {}

      The changes that will be applied to this Region.

    Returns number[][] | null

    The computed shape constraint for each shape, if restricted/possible.

  • Parameters

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

    Returns void

  • Internal

    Create the Clipper polygon tree for this Region.

    Parameters

    Returns PolyTree

  • 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

    Handle the Region event.

    Parameters

    Returns Promise<void>

  • 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

  • Internal

    Called when the scene's grid is changed.

    Parameters

    • changed: object

      The changes to the grid.

    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

  • Parameters

    • changes: any
    • options: any
    • user: any

    Returns Promise<void>

  • Returns Promise<void>

  • Internal

    Trigger the Region event.

    Parameters

    • eventName: string

      The event name

    • eventData: object

      The event data

    Returns Promise<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

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

  • Clamp the given elevation (of a token with a depth) to the elevation range of this Region.

    The elevation is clamped such that the head of the token is in the range if possible, but the feet are never outside of the range.

    Parameters

    • elevation: number

      The elevation (of the token)

    • Optionaldepth: number = 0

      The depth of the token

    Returns number

    The clamped elevation

  • 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

  • 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

  • Present a Dialog form to confirm the removal of a shape.

    Parameters

    • shapeOrIndex: number | BaseShapeData

      The shape or shape index.

    • Optionaloptions: object = {}

      Additional options passed to DialogV2.confirm

    Returns Promise<boolean>

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

    Returns void

  • 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

  • Spawn Tokens into this Region.

    The current User must be an owner of the Token Documents and have the TOKEN_CREATE permission in order to spawn them.

    This function can work ephemeral (non-persisted) Region documents.

    Parameters

    • tokenData: Iterable<TokenDocument | Partial<TokenData>, any, any>

      The data of tokens or Token documents to spawn.

    • Optionaloptions: {
          avoidOccupied?: boolean;
          create?: boolean;
          createOptions?: Partial<Omit<DatabaseCreateOperation, "parent">>;
          level?: string;
          offset?: Point;
          placement?: "center" | "relative" | "random";
          snap?: boolean;
      } = {}

      Additional options.

      • OptionalavoidOccupied?: boolean

        Avoid occupied grid spaces when placing randomly with snapping. Default: true.

      • Optionalcreate?: boolean

        Persist the spawned tokens to the database (default true) or otherwise return an array of ephemeral TokenDocument instances.

      • OptionalcreateOptions?: Partial<Omit<DatabaseCreateOperation, "parent">>

        Additional create options.

      • Optionallevel?: string

        The destination Level ID, which must be a Level this Region is in. Default: the Level of the Region if it is in only one Level.

      • Optionaloffset?: Point

        The relative offset position. Default: true.

      • Optionalplacement?: "center" | "relative" | "random"

        The placement. Default: "random".

      • Optionalsnap?: boolean

        Attempt to spawn the tokens to a snapped position. Default: true.

    Returns Promise<TokenDocument[]>

    The array of Token Documents that where created, which might be less than request the creation was disallowed by a preCreate handler

    If the current User doesn't have the necessary permissions, the Token Document could not be created or there's no valid placement.

    ui.notifications.info("Choose the placement for the spawn area.");
    const spawnArea = await canvas.regions.placeRegion({
    name: "Spawn Area",
    shapes: [{
    type: "circle",
    x: 0,
    y: 0,
    radius: canvas.dimensions.distancePixels * 30
    }],
    restriction: {enabled: true},
    levels: [canvas.level.id]
    }, {create: false});
    if ( spawnArea ) {
    const {count: numTokensToSpawn=0} = await foundry.applications.api.DialogV2.input({
    window: {
    title: "How many tokens to you want to spawn?"
    },
    content: `<input type="number" name="count" min="0" step="1" value="10">`
    }) ?? {};
    const actors = game.actors.contents;
    const tokensToSpawn = [];
    for ( let i = 0; i < numTokensToSpawn; i++ ) {
    const actor = actors[Math.floor(Math.random() * actors.length)];
    const token = await actor.getTokenDocument({
    rotation: Math.random() * 360
    }, {parent: spawnArea.parent});
    tokensToSpawn.push(token);
    }
    const spawnedTokens = await spawnArea.spawnTokens(tokensToSpawn);
    }
  • Teleport a Token into this Region.

    The Token may be in the same Scene as this Region, or in a different Scene. The current User must be an owner of the Token Document in order to teleport it. For teleportation to a different Scene the current User requires TOKEN_CREATE and TOKEN_DELETE permissions. If the Token is teleported to different Scene, it is deleted and a new Token Document in the other Scene is created.

    This function can work with ephemeral (non-persisted) Region documents.

    Parameters

    • token: TokenDocument

      An existing Token Document to teleport.

    • Optionaloptions: {
          avoidOccupied?: boolean;
          offset?: Point;
          pan?: boolean | TokenPanningOptions;
          placement?: "center" | "relative" | "random";
          snap?: boolean;
          updateData?: Partial<TokenData>;
      }

      Additional options.

      • OptionalavoidOccupied?: boolean

        Avoid occupied grid spaces when placing randomly with snapping. Default: true.

      • Optionaloffset?: Point

        The relative offset position.

      • Optionalpan?: boolean | TokenPanningOptions

        Pan the canvas (with transition animation) to the destination if the token is controlled? Default: true.

      • Optionalplacement?: "center" | "relative" | "random"

        The placement. Default: "random".

      • Optionalsnap?: boolean

        Attempt to teleport the tokens to a snapped position. Default: true.

      • OptionalupdateData?: Partial<TokenData>

        Additonal Token update data.

    Returns Promise<TokenDocument>

    The same Token Document if teleported within the same Scene, or a new Token Document if teleported to a different Scene

    If failed to teleport the Token document.

    await region.teleportToken(token, {
    updateData: {
    rotation: Math.random() * 360
    }
    });
  • Teleport Tokens into this Region.

    The Tokens may be in the same Scene as this Region, or in a different Scene. The current User must be an owner of the Token Documents in order to teleport them. For teleportation to a different Scene the current User requires TOKEN_CREATE and TOKEN_DELETE permissions. If a Token is teleported to different Scene, it is deleted and a new Token Document in the other Scene is created.

    This function can work ephemeral (non-persisted) Region documents.

    Parameters

    • tokens: Iterable<TokenDocument, any, any>

      Existing Token Documents to teleport.

    • Optionaloptions: {
          avoidOccupied?: boolean;
          level?: string;
          offset?: Point;
          pan?: boolean | TokenPanningOptions;
          placement?: "center" | "relative" | "random";
          snap?: boolean;
          updateData?: Map<TokenDocument, Partial<TokenData>>;
      } = {}

      Additional options.

      • OptionalavoidOccupied?: boolean

        Avoid occupied grid spaces when placing randomly with snapping. Default: true.

      • Optionallevel?: string

        The destination Level ID, which must be a Level this Region is in. Default: the Level of the Region if it is in only one Level.

      • Optionaloffset?: Point

        The relative offset position.

      • Optionalpan?: boolean | TokenPanningOptions

        Pan the canvas (with transition animation) to the destination if the token is controlled? Default: true.

      • Optionalplacement?: "center" | "relative" | "random"

        The placement. Default: "random".

      • Optionalsnap?: boolean

        Attempt to teleport the tokens to a snapped position. Default: true.

      • OptionalupdateData?: Map<TokenDocument, Partial<TokenData>>

        Additonal update data.

    Returns Promise<Map<TokenDocument, TokenDocument>>

    The mapping of deleted to created Token Documents.

    If the current User doesn't have the necessary permissions, Token Documents could not be created/updated/deleted or there's no valid placement.

    const updateData = new Map();
    for ( const token of tokens ) {
    updateData.set(token, {
    rotation: Math.random() * 360
    });
    }
    await region.teleportTokens(tokens, {updateData});
  • Test whether the given point is inside this Region.

    Parameters

    Returns boolean

    Is the point inside this 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?

  • 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 shape constraints of this Region. If save is true, the shape constraints are updated only if the current User is designated for it.

    Parameters

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

      Additional options

      • Optionalsave?: boolean

        Persist the shape constraints changes? Default: false.

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

    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

    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

    Called when the polygon tree of the Region has changed.

    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.

  • Internal

    Activate the Socket event listeners.

    Parameters

    • socket: Socket<DefaultEventsMap, DefaultEventsMap>

      The active game socket

    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

    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>

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

    This batch-wise workflow occurs after individual _onDelete workflows.

    Parameters

    • documents: any

      The Document instances which were deleted

    • operation: any

      Parameters of the database deletion operation

    • user: any

      The User who performed the deletion operation

    Returns Promise<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<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

  • Internal

    Test whether the given elevation is within the elevation range of this Region.

    Parameters

    • elevationRange: { bottom: number; top: number; topInclusive: boolean }

      The elevation range.

    • elevation: number

      The elevation.

    Returns boolean

    Is the elevation within the elevation range of this Region?

  • 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"});
  • Create an emanation Region for the Token and attach it to the Token.

    Parameters

    • token: TokenDocument

      The Token to attach the emanation Region to

    • range: number

      The range of the emanation in grid units

    • regionData: Omit<RegionData, "elevation" | "shapes">

      The Region data of the emanation

    • Optionaloptions: any = {}

      Additional options

    Returns Promise<void | RegionDocument>

    The created Region document unless the creation was prevented

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

    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

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

    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