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

    Class CompendiumCollection<TDocument>

    A collection of Document objects contained within a specific compendium pack. Each Compendium pack has its own associated instance of the CompendiumCollection class which contains its contents.

    Type Parameters

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    _source: object[]

    The source data array from which the Documents in the WorldCollection are created

    applicationClass: typeof Application | typeof ApplicationV2 = foundry.applications.sidebar.apps.Compendium

    A reference to the Application class which provides an interface to interact with this compendium content.

    An Array of application references which will be automatically updated when the collection content changes

    index: Collection<string, object>

    A subsidiary collection which contains the more minimal index of the pack

    invalidDocumentIds: Set<string> = ...

    Record the set of document ids where the Document was not initialized because of invalid source data

    metadata: object

    The compendium metadata which defines the compendium content and location

    CACHE_LIFETIME_SECONDS: number = 300

    The amount of time that Document instances within this CompendiumCollection are held in memory. Accessing the contents of the Compendium pack extends the duration of this lifetime.

    CONFIG_SETTING: string = "compendiumConfiguration"

    The named game setting which contains Compendium configurations.

    documentName: string

    The base Document type which is contained within this DocumentCollection

    Accessors

    • get banner(): string | void | null

      The banner image for this Compendium pack, or the default image for the pack type if no image is set.

      Returns string | void | null

    • get collection(): string

      The canonical Compendium name - comprised of the originating package and the pack name

      Returns string

    • get config(): object

      Access the compendium configuration data for this pack

      Returns object

    • get contents(): V[]

      Return an Array of all the entry values in the Collection

      Returns V[]

    • get documentClass(): typeof Document

      A reference to the Document class definition which is contained within this DocumentCollection.

      Returns typeof Document

    • get indexed(): boolean

      Has this compendium pack been fully indexed?

      Returns boolean

    • get indexFields(): Set<string>

      The index fields which should be loaded for this compendium pack

      Returns Set<string>

    • get locked(): boolean

      Track whether the Compendium Collection is locked for editing

      Returns boolean

    • get maxFolderDepth(): number

      Returns number

    • get ownership(): Record<
          "PLAYER"
          | "TRUSTED"
          | "ASSISTANT"
          | "GAMEMASTER",
          "INHERIT" | "NONE" | "LIMITED" | "OBSERVER" | "OWNER",
      >

      The visibility configuration of this compendium pack.

      Returns Record<
          "PLAYER"
          | "TRUSTED"
          | "ASSISTANT"
          | "GAMEMASTER",
          "INHERIT" | "NONE" | "LIMITED" | "OBSERVER" | "OWNER",
      >

    • get sort(): number

      Get the sort order for this Compendium

      Returns number

    • get title(): string

      A convenience reference to the label which should be used as the title for the Compendium pack.

      Returns string

    • get visible(): boolean

      Is this Compendium pack visible to the current game User?

      Returns boolean

    Methods

    • Returns any

    • Internal

      Follow-up actions to take when a database operation modifies Documents in this DocumentCollection.

      Parameters

      • action: any

        The database action performed

      • documents: any

        The array of modified Documents

      • result: any

        The result of the database operation

      • operation: any

        Database operation details

      • user: any

        The User who performed the operation

      Returns void

    • Returns void

    • Assign configuration metadata settings to the compendium pack

      Parameters

      • configuration: object = {}

        The object of compendium settings to define

      Returns Promise<void>

      A Promise which resolves once the setting is updated

    • Prompt the gamemaster with a dialog to configure ownership of this Compendium pack.

      Returns Promise<Record<string, string>>

      The configured ownership for the pack

    • Instantiate a Document for inclusion in the Collection.

      Parameters

      • data: object

        The Document data.

      • Optionalcontext: object = {}

        Document creation context.

      Returns TDocument

    • Delete an existing world-level Compendium Collection. This action may only be performed for world-level packs by a Gamemaster User.

      Returns Promise<CompendiumCollection<any>>

    • Duplicate a compendium pack to the current World.

      Parameters

      • label: string = {}

        A new Compendium label

      Returns Promise<CompendiumCollection<any>>

    • Filter the Collection, returning an Array of entries which match a functional condition.

      Parameters

      • condition: (
            value: TDocument,
            index: number,
            collection: Collection<string, TDocument>,
        ) => unknown

        The functional condition to test.

      Returns TDocument[]

      An Array of matched values

      let c = new Collection([["a", "AA"], ["b", "AB"], ["c", "CC"]]);
      let hasA = c.filters(entry => entry.slice(0) === "A");
    • Find an entry in the Map using a functional condition.

      Parameters

      • condition: (
            value: TDocument,
            index: number,
            collection: Collection<string, TDocument>,
        ) => unknown

        The functional condition to test.

      Returns TDocument | undefined

      The value, if found, otherwise undefined

      let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]);
      c.get("a") === c.find(entry => entry === "A"); // true
    • Apply a function to each element of the collection

      Parameters

      • fn: (value: TDocument, index: number) => void

        A function to apply to each element

      Returns void

      Array#forEach

      let c = new Collection([["a", {active: false}], ["b", {active: false}], ["c", {active: false}]]);
      c.forEach(e => e.active = true);
    • Get an element from the DocumentCollection by its ID.

      Parameters

      • key: any

        The ID of the Document to retrieve.

      • options: any

        Additional options to configure retrieval.

      Returns TDocument

      If strict is true and the Document cannot be found.

    • Get a single Document from this Compendium by ID. The document may already be locally cached, otherwise it is retrieved from the server.

      Parameters

      • id: string

        The requested Document id

      Returns Promise<TDocument> | undefined

      The retrieved Document instance

    • Load multiple documents from the Compendium pack using a provided query object. The available query options are shown below.

      Parameters

      • query: object = {}

        A database query used to retrieve documents from the underlying database

      Returns Promise<TDocument[]>

      The retrieved Document instances

      await pack.getDocuments({ type: "weapon" });
      
      await pack.getDocuments({ type__ne: "weapon" });
      
      await pack.getDocuments({ _id__in: arrayOfIds });
      
      await pack.getDocuments({ type__in: ["weapon", "armor"] });
      
    • Load the Compendium index and cache it as the keys and values of the Collection.

      Parameters

      • Optionaloptions: { fields?: string[] } = {}

        Options which customize how the index is created

        • Optionalfields?: string[]

          An array of fields to return as part of the index

      Returns Promise<Collection>

    • Obtain a temporary Document instance for a document id which currently has invalid source data.

      Parameters

      • id: string

        A document ID with invalid source data.

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

        Additional options to configure retrieval.

        • Optionalstrict?: boolean

          Throw an Error if the requested ID is not in the set of invalid IDs for this collection.

      Returns void | TDocument

      An in-memory instance for the invalid Document

      If strict is true and the requested ID is not in the set of invalid IDs for this collection.

    • Get an entry from the Collection by name. Use of this method assumes that the objects stored in the collection have a "name" attribute.

      Parameters

      • name: string

        The name of the entry to retrieve

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

        Additional options that affect how entries are retrieved

        • Optionalstrict?: boolean

          Throw an Error if the requested name does not exist. Default false.

      Returns TDocument | undefined

      The retrieved entry value, if one was found, otherwise undefined

      let c = new Collection([["a", "Alfred"], ["b", "Bob"], ["c", "Cynthia"]]);
      c.getName("Alfred"); // "Alfred"
      c.getName("D"); // undefined
      c.getName("D", {strict: true}); // throws Error
    • Get the ownership level that a User has for this Compendium pack.

      Parameters

      • user: User = game.user

        The user being tested

      Returns number

      The ownership level in CONST.DOCUMENT_OWNERSHIP_LEVELS

    • Generate a UUID for a given primary document ID within this Compendium pack

      Parameters

      • id: string

        The document ID to generate a UUID for

      Returns string

      The generated UUID, in the form of "Compendium..."

    • Fully import the contents of a Compendium pack into a World folder.

      Parameters

      Returns Promise<TDocument[]>

      The imported Documents, now existing within the World

    • Provide a dialog form that prompts the user to import the full contents of a Compendium pack into the World.

      Parameters

      • Optionaloptions: object = {}

        Additional options passed to the DialogV2.confirm method

      Returns Promise<boolean | TDocument[] | null>

      A promise which resolves in the following ways: an array of imported Documents if the "yes" button was pressed, false if the "no" button was pressed, or null if the dialog was closed without making a choice.

    • Import a Document into this collection, persisting the result. If the document ID already exists in the collection, it should be replaced with an optional confirmation dialog. If the document ID is undefined or does not already exist, a new Document will be created in the collection.

      Parameters

      • document: any

        A source Document to be imported. The document will be safely copied.

      • options: {} = {}

        Options which modify import behavior

      Returns Promise<Document<object, DocumentConstructionContext>>

      The imported Document instance

    • Import a Folder into this Compendium Collection.

      Parameters

      • folder: documents.Folder

        The existing Folder you wish to import

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

        Additional options which modify how the data is imported.

        • OptionalimportParents?: boolean

          Import any parent folders which are not already present in the Compendium.

      Returns Promise<void>

    • Import an array of Folders into this Compendium Collection.

      Parameters

      • folders: documents.Folder[]

        The existing Folders you wish to import

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

        Additional options which modify how the data is imported.

        • OptionalimportParents?: boolean

          Import any parent folders which are not already present in the Compendium.

      Returns Promise<void>

    • Add a Document to the index, capturing its relevant index attributes

      Parameters

      Returns void

    • Transform each element of the Collection into a new form, returning an Array of transformed values

      Type Parameters

      • U

      Parameters

      • transformer: (
            element: TDocument,
            index: number,
            collection: Collection<string, TDocument>,
        ) => U

        A transformation function applied to each entry value.

      Returns U[]

      An Array of transformed values

    • Migrate a compendium pack. This operation re-saves all documents within the compendium pack to disk, applying the current data model. If the document type has system data, the latest system data template will also be applied to all documents.

      Parameters

      • Optionaloptions: { notify?: boolean } = {}
        • Optionalnotify?: boolean

          Display notifications

      Returns Promise<CompendiumCollection<any>>

    • Reduce the Collection by applying an evaluator function and accumulating entries

      Type Parameters

      • U

      Parameters

      • reducer: (
            accum: U,
            element: T,
            index: number,
            collection: Collection<string, TDocument>,
        ) => U

        A reducer function applied to each entry value.

      • initial: U

        An initial value which accumulates with each iteration

      Returns U

      The accumulated result

      let c = new Collection([["a", "A"], ["b", "B"], ["c", "C"]]);
      let letters = c.reduce((s, l) => {
      return s + l;
      }, ""); // "ABC"
    • Render any Applications associated with this DocumentCollection.

      Parameters

      • force: any

        Force rendering

      • options: any

        Optional options

      Returns void

    • Find all Documents which match a given search term using a full-text search against their indexed HTML fields and their name. If filters are provided, results are filtered to only those that match the provided values.

      Parameters

      • search: { exclude?: string[]; filters?: FieldFilter[]; query?: string }

        An object configuring the search

        • Optionalexclude?: string[]

          An array of document IDs to exclude from search results

        • Optionalfilters?: FieldFilter[]

          An array of filters to apply

        • Optionalquery?: string

          A case-insensitive search string

      Returns object[] | TDocument[]

    • Assign this CompendiumCollection to be organized within a specific Folder.

      Parameters

      • folder: string | documents.Folder | null

        The desired Folder within the World or null to clear the folder

      Returns Promise<void>

      A promise which resolves once the transaction is complete

    • Test whether a condition is met by some entry in the Collection.

      Parameters

      • condition: (element: T, index: number, set: Collection<string, TDocument>) => boolean

        The functional condition to test.

      Returns boolean

      Was the test condition passed by at least one entry?

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

      Parameters

      • user: BaseUser

        The User being tested

      • permission: string | number

        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 Compendium pack?

    • Convert the Collection to a primitive array of its contents.

      Returns object[]

      An array of contained values

    • Update all objects in this DocumentCollection with a provided transformation. Conditionally filter to only apply to Entities which match a certain condition.

      Parameters

      • transformation: any

        An object of data or function to apply to all matched objects

      • condition: null = null

        A function which tests whether to target each object

      • options: {} = {}

        Additional options passed to Document.updateDocuments

      Returns Promise<TDocument[]>

      An array of updated data once the operation is complete

    • Protected

      Initialize the DocumentCollection by constructing any initially provided Document instances

      Returns void

    • Internal

      Activate the Socket event listeners used to receive responses to compendium management events.

      Parameters

      • socket: Socket

        The active game socket.

      Returns void

    • Create a new Compendium Collection using provided metadata.

      Parameters

      • metadata: object

        The compendium metadata used to create the new pack

      • options: object = {}

        Additional options which modify the Compendium creation request

      Returns Promise<CompendiumCollection<any>>

    • Get the searchable fields for a given document or index, based on its data model

      Parameters

      • documentName: string

        The document name

      • Optionaltype: string

        A document subtype

      Returns Record<string, SearchableField>

      A record of searchable DataField definitions