Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move detachSubitem method to helper function #13204

Merged
merged 1 commit into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Move detachSubitem method to helper function
  • Loading branch information
stwlam committed Jan 23, 2024
commit c31bf04cb830f11d9d7cbc7c2bb9e229801f9c60
2 changes: 1 addition & 1 deletion build/lib/extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ class PackExtractor {
delete (source.system as { specific?: unknown }).specific;
}

if ("subitems" in source.system && source.system.subitems.length === 0) {
if (source.system.subitems?.length === 0) {
delete (source.system as { subitems?: unknown[] }).subitems;
}

Expand Down
12 changes: 10 additions & 2 deletions src/module/actor/sheet/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import type { ActorPF2e } from "@actor";
import type { StrikeData } from "@actor/data/base.ts";
import type { InitiativeRollResult } from "@actor/initiative.ts";
import type { PhysicalItemPF2e } from "@item";
import { AbstractEffectPF2e, ItemPF2e, ItemProxyPF2e, SpellPF2e } from "@item";
import { AbstractEffectPF2e, ItemPF2e, SpellPF2e } from "@item";
import type { ActionCategory, ActionTrait } from "@item/ability/types.ts";
import { isPhysicalData } from "@item/base/data/helpers.ts";
import type { ActionType, ItemSourcePF2e } from "@item/base/data/index.ts";
import { createConsumableFromSpell } from "@item/consumable/spell-consumables.ts";
import { isContainerCycle } from "@item/container/helpers.ts";
import { itemIsOfType } from "@item/helpers.ts";
import { Coins } from "@item/physical/data.ts";
import { detachSubitem } from "@item/physical/helpers.ts";
import { DENOMINATIONS, PHYSICAL_ITEM_TYPES } from "@item/physical/values.ts";
import { DropCanvasItemDataPF2e } from "@module/canvas/drop-canvas-data.ts";
import { createSelfEffectMessage } from "@module/chat-message/helpers.ts";
Expand Down Expand Up @@ -460,6 +461,13 @@ abstract class ActorSheetPF2e<TActor extends ActorPF2e> extends ActorSheet<TActo
}
return this.deleteItem(item, event);
},
"detach-item": (event) => {
const itemId = htmlClosest(event.target, "[data-item-id]")?.dataset.itemId;
const subitemId = htmlClosest(event.target, "[data-subitem-id]")?.dataset.subitemId;
const item = this.actor.inventory.get(itemId, { strict: true });
const subitem = item.subitems.get(subitemId, { strict: true });
return detachSubitem(item, subitem, event.ctrlKey);
},
"item-to-chat": (event, anchor): Promise<unknown> | void => {
const itemEl = htmlClosest(anchor, "[data-item-id]");
const itemId = itemEl?.dataset.itemId;
Expand Down Expand Up @@ -1067,7 +1075,7 @@ abstract class ActorSheetPF2e<TActor extends ActorPF2e> extends ActorSheet<TActo
}

// Creating a new item: clear the _id via cloning it
return this._onDropItemCreate(new ItemProxyPF2e(itemSource).clone().toObject());
return this._onDropItemCreate(new Item.implementation(itemSource).clone().toObject());
}

protected override async _onDropFolder(
Expand Down
9 changes: 6 additions & 3 deletions src/module/item/book/data.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { EquipmentTrait } from "@item/equipment/data.ts";
import {
import type { EquipmentTrait } from "@item/equipment/data.ts";
import type {
BasePhysicalItemSource,
PhysicalItemTraits,
PhysicalSystemData,
Expand All @@ -14,9 +14,12 @@ interface BookSystemSource extends PhysicalSystemSource {
category: "formula" | "spell";
capacity: number;
contents: ItemUUID[];
subitems?: never;
}

interface BookSystemData extends Omit<BookSystemSource, SourceOmission>, Omit<PhysicalSystemData, "traits"> {}
interface BookSystemData
extends Omit<BookSystemSource, SourceOmission>,
Omit<PhysicalSystemData, "subitems" | "traits"> {}

type SourceOmission =
| "apex"
Expand Down
3 changes: 2 additions & 1 deletion src/module/item/consumable/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ interface ConsumableSystemSource extends PhysicalSystemSource {
spell: SpellSource | null;
usage: { value: string };
stackGroup: AmmoStackGroup | null;
subitems?: never;
}

type ConsumableUses = {
Expand All @@ -41,7 +42,7 @@ type ConsumableDamageHealing = {

interface ConsumableSystemData
extends Omit<ConsumableSystemSource, SourceOmission>,
Omit<PhysicalSystemData, "traits"> {
Omit<PhysicalSystemData, "subitems" | "traits"> {
apex?: never;
stackGroup: AmmoStackGroup | null;
}
Expand Down
3 changes: 2 additions & 1 deletion src/module/item/container/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ interface ContainerSystemSource extends Investable<PhysicalSystemSource> {
bulk: ContainerBulkSource;
collapsed: boolean;
usage: { value: string };
subitems?: never;
}

interface ContainerBulkSource {
Expand All @@ -29,7 +30,7 @@ interface ContainerBulkSource {

interface ContainerSystemData
extends Omit<ContainerSystemSource, SourceOmission>,
Omit<Investable<PhysicalSystemData>, "traits"> {
Omit<Investable<PhysicalSystemData>, "subitems" | "traits"> {
bulk: ContainerBulkData;
stackGroup: null;
}
Expand Down
12 changes: 7 additions & 5 deletions src/module/item/index.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,40 @@
// Base
export * from "./base/document.ts";

// Effects
// Abstract subclasses
export { ABCItemPF2e } from "./abc/document.ts";
export { AbstractEffectPF2e } from "./abstract-effect/document.ts";
export { PhysicalItemPF2e } from "./physical/document.ts";

// Effects
export { AfflictionPF2e } from "./affliction/document.ts";
export { ConditionPF2e } from "./condition/document.ts";
export { EffectPF2e } from "./effect/document.ts";

// Physical Items
export { ArmorPF2e } from "./armor/document.ts";
export { BookPF2e } from "./book/document.ts";
export { ConsumablePF2e } from "./consumable/document.ts";
export { ContainerPF2e } from "./container/document.ts";
export { EquipmentPF2e } from "./equipment/document.ts";
export { PhysicalItemPF2e } from "./physical/document.ts";
export { ShieldPF2e } from "./shield/document.ts";
export { TreasurePF2e } from "./treasure/document.ts";
export { WeaponPF2e } from "./weapon/document.ts";

// ABC items
export { ABCItemPF2e } from "./abc/document.ts";
export { AncestryPF2e } from "./ancestry/document.ts";
export { BackgroundPF2e } from "./background/document.ts";
export { ClassPF2e } from "./class/document.ts";

// Others
export { AbilityItemPF2e } from "./ability/document.ts";
export { CampaignFeaturePF2e } from "./campaign-feature/document.ts";
export { ConsumablePF2e } from "./consumable/document.ts";
export { DeityPF2e } from "./deity/document.ts";
export { FeatPF2e } from "./feat/document.ts";
export { HeritagePF2e } from "./heritage/document.ts";
export { KitPF2e } from "./kit/document.ts";
export { LorePF2e } from "./lore.ts";
export { MeleePF2e } from "./melee/document.ts";
export { ShieldPF2e } from "./shield/document.ts";
export { SpellPF2e } from "./spell/document.ts";
export { SpellcastingEntryPF2e } from "./spellcasting-entry/document.ts";

Expand Down
2 changes: 1 addition & 1 deletion src/module/item/physical/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ interface PhysicalSystemSource extends ItemSystemSource {
usage?: { value: string };
activations?: Record<string, ItemActivation>;
temporary?: boolean;
subitems?: PhysicalItemSource[];

/**
* Data for apex items: the attribute upgraded and, in case of multiple apex items, whether the upgrade has been
Expand Down Expand Up @@ -72,7 +73,6 @@ interface PhysicalSystemData extends Omit<PhysicalSystemSource, "description">,
bulk: BulkData;
material: ItemMaterialData;
traits: PhysicalItemTraits;
subitems?: PhysicalItemSource[];
temporary: boolean;
identification: IdentificationData;
usage: UsageDetails;
Expand Down
14 changes: 4 additions & 10 deletions src/module/item/physical/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -595,12 +595,9 @@ abstract class PhysicalItemPF2e<TParent extends ActorPF2e | null = ActorPF2e | n
): Promise<this | undefined> {
if (this.parentItem) {
const parentItem = this.parentItem;
const newSubitems =
"subitems" in parentItem._source.system
? parentItem._source.system.subitems.map((i) =>
i._id === this.id ? fu.mergeObject(i, data, { ...context, inplace: false }) : i,
)
: [];
const newSubitems = parentItem._source.system.subitems?.map((i) =>
i._id === this.id ? fu.mergeObject(i, data, { ...context, inplace: false }) : i,
);
const updated = await parentItem.update({ system: { subitems: newSubitems } }, context);
if (updated) {
this._onUpdate(data as DeepPartial<this["_source"]>, context, game.user.id);
Expand All @@ -616,10 +613,7 @@ abstract class PhysicalItemPF2e<TParent extends ActorPF2e | null = ActorPF2e | n
override async delete(context: DocumentModificationContext<TParent> = {}): Promise<this | undefined> {
if (this.parentItem) {
const parentItem = this.parentItem;
const newSubitems =
"subitems" in parentItem._source.system
? parentItem._source.system.subitems.filter((i) => i._id !== this.id)
: [];
const newSubitems = parentItem._source.system.subitems?.filter((i) => i._id !== this.id) ?? [];
const updated = await parentItem.update({ "system.subitems": newSubitems }, context);
if (updated) {
this._onDelete(context, game.user.id);
Expand Down
38 changes: 35 additions & 3 deletions src/module/item/physical/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { ActorProxyPF2e } from "@actor";
import type { ContainerPF2e } from "@item";
import type { ContainerPF2e, PhysicalItemPF2e } from "@item";
import { PhysicalItemSource } from "@item/base/data/index.ts";
import { ContainerBulkData } from "@item/container/data.ts";
import { REINFORCING_RUNE_LOC_PATHS } from "@item/shield/values.ts";
import { Rarity } from "@module/data.ts";
import { createHTMLElement, localizer } from "@util";
import * as R from "remeda";
import { Bulk, STACK_DEFINITIONS } from "./bulk.ts";
import { CoinsPF2e } from "./coins.ts";
import { BulkData } from "./data.ts";
import type { PhysicalItemPF2e } from "./document.ts";
import { getMaterialValuationData } from "./materials.ts";
import { RUNE_DATA, getRuneValuationData } from "./runes.ts";

Expand Down Expand Up @@ -216,5 +216,37 @@ function prepareBulkData(item: PhysicalItemPF2e): BulkData | ContainerBulkData {
: data;
}

/**
* Detach a subitem from another physical item, either creating it as a new, independent item or incrementing the
* quantity of aan existing stack.
*/
async function detachSubitem(item: PhysicalItemPF2e, subitem: PhysicalItemPF2e, skipConfirm: boolean): Promise<void> {
const localize = localizer("PF2E.Item.Physical.Attach.Detach");
const confirmed =
skipConfirm ||
(await Dialog.confirm({
title: localize("Label"),
content: createHTMLElement("p", { children: [localize("Prompt", { attachable: subitem.name })] }).outerHTML,
}));
if (confirmed) {
const deletePromise = subitem.delete();
const createPromise = (async (): Promise<unknown> => {
// Find a stack match, cloning the subitem as worn so the search won't fail due to it being equipped
const stack = item.actor?.inventory.findStackableItem(
subitem.clone({ "system.equipped.carryType": "worn" }),
);
return (
stack?.update({ "system.quantity": stack.quantity + 1 }) ??
Item.implementation.create(
fu.mergeObject(subitem.toObject(), { _id: null, "system.containerId": item.system.containerId }),
{ parent: item.actor },
)
);
})();

await Promise.all([deletePromise, createPromise]);
}
}

export { coinCompendiumIds } from "./coins.ts";
export { CoinsPF2e, computeLevelRarityPrice, generateItemName, handleHPChange, prepareBulkData };
export { CoinsPF2e, computeLevelRarityPrice, detachSubitem, generateItemName, handleHPChange, prepareBulkData };
3 changes: 2 additions & 1 deletion src/module/item/physical/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export { PhysicalItemPF2e } from "./document.ts";

export * from "./bulk.ts";
export * from "./data.ts";
export { PhysicalItemPF2e } from "./document.ts";
export * from "./helpers.ts";
export * from "./materials.ts";
export * from "./runes.ts";
Expand Down
6 changes: 3 additions & 3 deletions src/module/item/shield/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ class ShieldPF2e<TParent extends ActorPF2e | null = ActorPF2e | null> extends Ph
);
}

override acceptsSubitem(attachable: PhysicalItemPF2e): boolean {
override acceptsSubitem(candidate: PhysicalItemPF2e): boolean {
return (
candidate.isOfType("weapon") &&
candidate.system.traits.value.some((t) => t === "attached-to-shield") &&
!this.system.traits.integrated &&
attachable.isOfType("weapon") &&
attachable.system.traits.value.some((t) => t === "attached-to-shield") &&
!this.subitems.some((i) => i.isOfType("weapon"))
);
}
Expand Down
6 changes: 3 additions & 3 deletions src/module/item/treasure/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@ import { CarriedUsage } from "@item/physical/usage.ts";

type TreasureSource = BasePhysicalItemSource<"treasure", TreasureSystemSource>;

type TreasureSystemSource = Omit<PhysicalSystemSource, "usage"> & {
type TreasureSystemSource = Omit<PhysicalSystemSource, "subitems" | "usage"> & {
apex?: never;
/** Usage for treasure isn't stored. */
readonly usage?: never;
stackGroup: "coins" | "gems" | null;
subitems?: never;
};

interface TreasureSystemData extends Omit<PhysicalSystemData, "equipped"> {
interface TreasureSystemData extends Omit<PhysicalSystemData, "equipped" | "subitems"> {
equipped: TreasureEquippedData;
/** Treasure need only be on one's person. */
usage: CarriedUsage;

stackGroup: "coins" | "gems" | null;

apex?: never;
subitems?: never;
}

interface TreasureEquippedData extends EquippedData {
Expand Down
8 changes: 5 additions & 3 deletions src/module/item/weapon/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,14 @@ class WeaponPF2e<TParent extends ActorPF2e | null = ActorPF2e | null> extends Ph
return new Set(this.system.traits.otherTags);
}

override acceptsSubitem(attachable: PhysicalItemPF2e): boolean {
override acceptsSubitem(candidate: PhysicalItemPF2e): boolean {
return (
candidate !== this &&
candidate.isOfType("weapon") &&
candidate.system.traits.value.some((t) => t === "attached-to-crossbow-or-firearm") &&
["crossbow", "firearm"].includes(this.group ?? "") &&
!this.isAttachable &&
!this.system.traits.value.includes("combination") &&
attachable.isOfType("weapon") &&
attachable.system.traits.value.some((t) => t === "attached-to-crossbow-or-firearm") &&
!this.subitems.some((i) => i.isOfType("weapon"))
);
}
Expand Down
1 change: 1 addition & 0 deletions src/styles/tooltip/_carry-type-menu.scss
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
aside.locked-tooltip.pf2e.carry-type-menu {
white-space: nowrap;
width: 7rem;

ul {
display: flex;
Expand Down
7 changes: 4 additions & 3 deletions types/foundry/client/data/documents/item.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,13 @@ declare global {

interface Item<TParent extends Actor | null = Actor | null> extends ClientBaseItem<TParent> {
get uuid(): ItemUUID;

_sheet: ItemSheet<this, DocumentSheetOptions> | null;

get sheet(): ItemSheet<this, DocumentSheetOptions>;
}

namespace Item {
const implementation: typeof Item;
}

type EmbeddedItemUUID = `Actor.${string}.Item.${string}`;
type WorldItemUUID = WorldDocumentUUID<Item<null>>;
type CompendiumItemUUID = `Compendium.${string}.Item.${string}`;
Expand Down