# Global Constants, classes and functions # Components, KubeJS and you! In 1.18.2 and beyond KubeJS uses Components in a lot of places. It returns them for entity names, item names and accepts them for everything from tooltips to sending messages to players.

All examples use `event.player.tell` from the `player.chat` event to output their example, but they will with anywhere that accepts a Component!

Making your own Components starts from the ComponentWrapper class, invokable with just `Component` or `Text` from anywhere. The examples all use `Component` but `Text` works just the same. #### ComponentWrapper methods:
Name Return TypeInfo
of(Object o)MutableComponentReturns a component based on what was input. Accepts strings, primitives like numbers, snbt/nbt format of Components and a couple others.
clickEventOf(Object o)ClickEventReturns a ClickEvent based on what was input. See examples below
prettyPrintNbt(Tag tag)ComponentReturns a component with a prettified version of the input NBT.
join(MutableComponent seperator, Iterable<? extends Component> texts)MutableComponentReturns the result of looping through `texts` and joining them, separating each one with `seperator`.
string(String text)MutableComponentReturns a basic unformatted TextComponent with just the input text
translate(String key)MutableComponentReturns a basic unformatted TranslatableComponent with the input key.
translate(String key, Object... objects)MutableComponentReturns an unformatted TranslatableComponent with `objects` as the replacements for %s in the translation output.
keybind(String keybind)MutableComponentReturns a basic unformatted KeybindComponent with the specified keybind.
<color>(Object text)MutableComponentReturns a basic Component with the specified color for text coloring. Valid colors are in the list below. Do not include the <> brackets.
A list of colors accepted in various places: - black - darkBlue - darkGreen - darkAqua - darkRed - darkPurple - gold - gray - darkGray - blue - green - aqua - red - lightPurple - yellow - white Basic examples: ```JavaScript onEvent('player.chat', event => { // Tell the player a normal message event.player.tell(Component.string('Hello world')) // Now in black event.player.tell(Component.black('Welcome to the dark side, we have cookies!')) // Tell them the diamond item, in whatever language they have set event.player.tell(Component.translate('item.minecraft.diamond')) // Now tell them whatever key they have crouching set to event.player.tell(Component.keybind('key.sneak')) // And finally show them the nbt data of the item they are holding event.player.tell(Component.prettyPrintNbt(event.player.mainHandItem.nbt)) }) ``` ### MutableComponent These are methods you can call on any MutableComponent. This includes ComponentKJS, which is a KubeJS extension for vanilla's components and is injected into vanillas code on runtime. All methods from ComponentKJS are included, but only relevant ones from vanilla are included.
Name Return TypeInfo
iterator()Iterator<Component>Returns an Iterator for the components contained in this component, useful for when multiple have been joined or appended. From ComponentKJS.
self()MutableComponentReturns the component you ran it on. From ComponentKJS.
toJson()JsonElementReturns the Json representation of this Component. From ComponentKJS.
<color>()MutableComponentModifies the Component with the specified color applied as formatting, and returns itself. Do not include the <> brackets. From ComponentKJS.
color(Color c)MutableComponentModifies the Component to have the input Color, and returns itself. (Color is a Rhino color). From ComponentKJS.
noColor()MutableComponentModifies the Component to have no color, and returns itself. From ComponentKJS.
bold() italic() underlined() strikethrough() obfuscated() MutableComponentModifies the Component to have said formatting and returns itself. From ComponentKJS.
bold(@Nullable Boolean value) italic(@Nullable Boolean value) underlined(@Nullable Boolean value) strikethrough(@Nullable Boolean value) obfuscated(@Nullable Boolean value) MutableComponentModifies the Component to have said formatting and returns itself. From ComponentKJS.
insertion(@Nullable String s)MutableComponentMakes the Component insert the specified string into the players chat box when shift clicked (does not send it) and returns itself. From ComponentKJS.
font(@Nullable ResourceLocation s)MutableComponentChanges the Components font to the specified font and returns itself. For more information on adding fonts see the [Minecraft Wiki's Resource packs page.](https://minecraft.fandom.com/wiki/Resource_Pack#Fonts) From ComponentKJS.
click(@Nullable ClickEvent s)MutableComponentSets this components ClickEvent to the specified ClickEvent. From ComponentKJS.
hover(@Nullable Component s)MutableComponentSets the hover tooltip for this Component to the input Component. From ComponentKJS.
setStyle(Style style)MutableComponentSets the style to the input Style (net.minecraft.network.chat.Style) and returns itself. Not recommended for use, use the specific methods added by CompontentKJS instead.
append(String string)MutableComponentAppends the input string as a basic TextComponent to this Component then returns itself.
append(Component component)MutableComponentAppends the input Component to this Component then returns itself.
withStyle(Style style)MutableComponentMerges the input style with the current style, preffering properties from the new style if a conflict exists.
getStyle()StyleReturns this Components current Style.
getContents()MutableComponentReturns this Components contents. Will return the text for TextComponents, the pattern for SelectorComponents and an empty string for all other Components.
getSiblings()List<Component> Returns a list of all Components which have been append()ed to this Component
plainCopy()BaseComponentReturns a basic copy of this, preserving only the contents and not the style or siblings.
copy()MutableComponentReturns a full copy of this Component, preserving style and siblings
getString()StringReturns this components text as a String. Will return a blank string for any non-text component
More complex examples: ```JavaScript // First a prefix, like a rank. This won't be changing so we can just declare it up here. const prefix = Component.darkRed('[Admin]').underlined() onEvent('player.chat', event => { // First cancel the event because we are going to be sending the message ourselves event.cancel() // The main Component we will be adding stuff to. It is just a copy of the prefix component for now let component = prefix.copy() // If we didn't copy it all the modifications we made to it would be applied to the original as well! // Make a component of the players name and then surround with < > and make it white again. Then append it our main copmponent. // A component will inherit any styiling it doesnt have from whatever it has been .append()ed to, so you need to apply formatting rather liberally some times! let playerName = Component.string(event.getUsername()) // Doing it this way means we only have to apply the white formatting and no underline once to the name let nameComponent = Component.white(' <').underlined(false).append(playerName).append('> ') component.append(nameComponent) // Finnally add the message (obfuscated, of course) and send it! // We make sure to set its color and underline though, otherwise it will end up inheriting the red and underline from the prefix! component.append(Component.string(event.message).obfuscated().white().underlined(false)) event.server.tell(component) }) ``` # Item and Ingredient When making recipes you can specify items in many ways, the most common is just to use `'namspace:id'`, like `'minecraft:diamond'`, however you can also use `Item#of` and `Ingredient#of` for advanced additions, such as NBT or count. Note that Item and Ingredient are **not** the same! They may work similarly but there are differences. Item can only ever represent a single item type whereas Ingredient can represent multiple item types (and multiple instances of the same item type with different properties such as NBT data). For most cases Ingredient should be preferred over Item. #### Item/ItemWrapper Its Java class name is ItemWrapper but it is bound to Item in JS.
Name Return TypeInfo
of(ItemStackJS in)ItemStackJSReturns an ItemStackJS based on what was input. Note that this relies mostly on Rhinos type wrapping to function, see [paragraph below](https://mods.latvian.dev/books/kubejs-legacy/page/item-and-ingredient#:~:text=Item%23of%20relies%20on%20Rhinos%20type%20wrapping%20to%20function%2C%20which%20calls%20ItemStackJS%23of.%20This%20tries%20its%20best%20to%20turn%20the%20input%20into%20an%20ItemStackJS.%20If%20no%20match%20is%20found%20ItemStackJS.EMPTY%20is%20returned.) about ItemStackJS#of for more info
of(ItemStackJS in, int count)ItemStackJSSee above. count will override any other count set from the first parameter.
of(ItemStackJS in, CompoundTag tag)ItemStackJSSee above. NBT is merged, with the input NBT taking priority over existing NBT.
of(ItemStackJS in, int count, CompoundTag nbt)ItemStackJSCombines the functionality of the above two.
withNBT(ItemStackJS in, CompoundTag nbt)ItemStackJSSame as the corresponding #of.
withChance(ItemStackJS in, double chance)ItemStackJSSame as #of, chance will override currently set chance.
getList()ListJSReturns a list of ItemStackJS, one per registered item.
getTypeList()ListJSReturns a list of String, one per registered item.
getEmpty()ItemStackJSReturns ItemSTackJS.EMPTY
clearListCache()voidClears the caches used for #getList and #getTypeList
fireworks(Map<String, Object> properties)FireworkJSReturns a FireworkJS based on the input map of propeties. See FireworkJS#of on the FireworkJS page for more information <TODO: Make and link FireworkJS page>
getItem(ResourceLocation id)ItemReturns the instance of the Item class associated with the item id passed in.
@Nullable findGroup(String id)CreativeModTabReturns the Creative tab associated with the id passed in, returns null if none found.
exists(ResourceLocation id)booleanReturns if the item id passed in exists or not.
isItem(@Nullable Object o)booleanJust does an instanceof ItemStackJS check on the object passed in.
Item#of relies on Rhinos type wrapping to function, which calls ItemStackJS#of. This tries its best to turn the input into an ItemStackJS. If no match is found ItemStackJS.EMPTY is returned. Valid inputs: - null/ItemStack.EMPTY/Items.EMPTY/ItemStackJS.EMPTY - will return ItemStackJS.EMPTY - ItemStackJS - will return the same object passed in. - FluidStackJS - will return a new DummyFluidItemStackJS - IngredientJS - will return the first item in the Ingredient - ItemStack - will return a new ItemStackJS wrapping the ItemStack passed in - ResourceLocation - will lookup this ResourceLocation in the item registry and return it if found. If not found will return ItemStackJS.EMPTY, and throw an error if RecipeJS.itemErrors is true - ItemLike - will return a new ItemStackJS of the input - JsonObject - will return an item based on properties in the Json. `item` will be used as the item id, or `tag` if item does not exist. `count`, `chance` and `nbt` all set their respective properties - RegEx - will return a new ItemStackJS of the first item id that matches this regex. - String (CharSequence) - will parse it and return a new ItemStackJS based on the input item id. Prefix with `nx ` to change the count (where n is any number between 1 and 64). Put `#` before the item id to parse it as a tag instead. Put `@` before the item id to parse it as a modid instead. Prefix with `%` to parse it as a creative menu tab group. Surround in `/` to parse as a RegEx. NOTE: will only be the first item in any of the groups mentioned above! - Map/JS Object - uses the same rules as a JsonObject. #### Ingredient/IngredientWrapper Its Java class name is IngredientWrapper but it is bound to Ingredient in JS. All static methods.
Name Return TypeInfo
getNone()IngredientJSReturns ItemStack.EMPTY
getAll()IngredientJSReturns an IngredientJS of every single item in game. All of them.
of(Object object)IngredientJSWorks exactly the same as Item#of except it recognises Ingredient and forge json ingredient syntax.
of(Object object, int count)IngredientJSSame as above. The count passed in will override any from the first parameter.
custom(Predicate<ItemStackJS> predicate)IngredientJSTakes the arrow function or anonymous function passed in and makes an IngredientJS with that as IngredientJS#test. Return true from the function if the ItemStackJS passed should match as an ingredient.
custom(IngredientJS in, Predicate<ItemStackJS> predicate)IngredientJSSame as above except it must match the IngredientJS passed in as the first parameter before the custom function is called.
customNBT(IngredientJS in, Predicate<CompoundTag> predicate)IngredientJSSame as above except the Predicate is passed the items NBT instead of the full ItemStackJS. Useful for advanced NBT matching.
matchAny(Object objects)IngredientJSAdds the passed in object to an ingredient. If it is a list then it adds all items in the list. All objects are passed through #of before adding.
registerCustomIngredientAction(String id, CustomIngredientActionCallback callback)voidRegisters a custom ingredient action. See the [recipe page](https://mods.latvian.dev/books/kubejs-legacy/page/recipeeventjs#bkmrk-poorly-documented-th) for more information.
isIngredient(@Nullable Object o)booleanJust does an instanceof IngredientJS check on the object passed in.

Remember that Item and Ingredient are not equivalent!

Examples ``` ``` #### ItemStackJS A wrapper class for vanilla's ItemStack. All methods listed here are instance methods, all useful static methods are wrapped in ItemWrapper. Implements IngredientJS and overrides most of its default methods.
Name Return TypeInfo
getItem()ItemReturns the instance of the Item class associated with this ItemStackJS.
getItemStack()ItemStackReturns the vanilla ItemStack that this wraps.
getId()StringReturns the item id associated with this ItemStackJS in the form mod\_name:item\_name
getTags()Colletion<ResourceLocation>Returns all item tags the item has. (NOT NBT tags).
hasTag(ResourceLocation tag)booleanReturns if the item has the input tag or not.
copy()ItemStackJSReturns a copy of this ItemStackJS.
setCount(int count)voidSets the count on this ItemStackJS.
getCount()intGets the count.
withCount()ItemStackJSReturns a copy of this ItemStackJS with a different count.
isEmpty()booleanReturns if this is an empty item or not.
isInvalidRecipeIngredient()booleanReturns if this is a valid recipe ingredient.
isBlock()booleanReturns if this item is a BlockItem, that is it can be placed and form a block.
@Nullable getNbt()CompoundTagGets this items NBT data.
setNbt(@Nullable CompoundTag tag)voidSets this items NBT data
hasNBT() booleanReturns if this item has NBT data.
getNbtString()StringReturns this items NBT data as a string. If you want to display it to the player see [Text#prettyPrintNbt](https://mods.latvian.dev/books/kubejs-legacy/page/components-kubejs-and-you#:~:text=prettyPrintNbt(Tag%20tag)).
removeNBT()ItemStackJSReturns a copy with no NBT data.
withNBT(CompoundTag nbt)ItemStackJSReturns a copy with the specified NBT data. Any tags from the original NBT are kept if not overwritten by the NBT passed in.
hasChance()booleanReturns if the ItemStackJS has a chance.
removeChance()voidRemoves the chance from this ItemStackJS.
setChance(double c)voidSets the chance for this ItemStackJS.
getChance()doubleReturns the chance.
withChance(double c)ItemStackJSReturns a copy with the chance passed in, unless the chance passed in is the same as the current chance, in which case it returns this.
getName()ComponentsReturns this items name. Probably a Translateable Component unless its been overridden by something else (ie method below).
withName(@Nullable Component displayName)ItemStackJSReturns a copy with a different display name set.
toString()StringReturns a string representing this ItemStackJS. The same method used for the `/kubejs hand` command.
test(ItemStackJS other)booleanReturns if this ItemStackJS equals another one. Tests for item type and NBT data.
testVanilla(ItemStack other)booleanReturns if this ItemStackJS equals the passed in ItemStack. Tests for item type and NBT data.
testVanillaItem(Item item) booleanReturns if the Item passed in is the same as this ItemStackJS's Item. Basically checks they are the same item type.
getStacks()Set<ItemStackJS>Returns this ItemStackJS as the only entry in a Set.
getVanillaItems()Set<Item>Returns this ItemStackJS associated Item as the only entry in a Set.
getFirst()ItemStackJSRetuns a copy of this ItemStackJS
hashCode()intReturns a hash code of the Item and NBT data.
equals(Object o)booleanReturns if this is equal to the input object.
strongEquals(Object o)booleanReturns if this is equal to the input object. Checks count as well.
getEnchantments()MapJSReturns a MapJS of this itemStackJS enchament id's to their level.
hasEnchantment(Enchantment enchantment, int level)booleanReturns if this ItemStackJS is enchanted with a minimum of the passed in enchantment level.
enchant(MapJS enchantments)ItemStackJSEnchants a copy of this ItemStackJS with the MapJS passed in (it should be a map of enchantment ids to levels), then returns the copy.
enchant(Enchantment enchantment, int level)ItemStackJSEnchants a copy of this item with the passed in Enchantment at the specified level, then returns the copy.
getMod()StringReturns the mod id of the mod this item is from.
ignoreNBT()IngredientJSReturns a new IgnoreNBTIngredientJS of this item.
weakNBT()IngredientJSReturns a new WeakNBTIngredientJS of this item.
areItemsEqual(ItemStackJS other)booleanReturns if this item type is equal to the item type of the passed in ItemStackJS
areItemsEqual(ItemStack other)booleanReturns if this item type is equal to the item type of the passed in ItemStack
isNBTEqual(ItemStackJS other)booleanReturns if the NBT of this ItemStackJS is equal to the NBT of the ItemStackJS passed in.
isNBTEqual(ItemStack other)booleanReturns if the NBT of this ItemStackJS is equal to the NBT of the ItemStack passed in.
getHarvestSpeed(@Nullable BlockContainerJS block)floatReturns the mining speed of this ItemStackJS if used to mine the passed in BlockContainerJS
getHarvestSpeed()floatReturns this items default mining speed
toJson() toResultJson() toRawResultJson() JsonElementReturns a Json representation of this ItemStackJS. They all appear to work almost identically.
toNBT()CompoundTagReturns an NBT representation of this ItemStackJS, the same sort that vanilla uses to store items in blocks.
onChanged(@Nullable Tag o)voidSets the items NBT data to the tag passed in, only if it is a CompoundTag or null.
getItemGroup()StringReturns the name of the creative tab this item belongs in. An empty string if it does not exist in the creative tabs (like a jigsaw block).
getItemIds()Set<String>Returns a set with this items id as the only entry.
getFluidStack()FluidStackJSReturns null, by default. Overriden by some superclasses to return the FluidStackJS that this item represents.
getTypeData()CompoundTagUnknown purpose.
``` ```