Skip to content

Instantly share code, notes, and snippets.

@mtbarr
Last active March 6, 2021 00:35
Show Gist options
  • Save mtbarr/d914b7a9255245f88200cb6df71abc4d to your computer and use it in GitHub Desktop.
Save mtbarr/d914b7a9255245f88200cb6df71abc4d to your computer and use it in GitHub Desktop.
A delegation to work item descriptions (Lore) intelligently. It will generally be necessary to make defensive copies to make customizations.
package io.github.sasuked.gear.utils.description;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import org.bukkit.ChatColor;
import java.util.List;
import java.util.function.Function;
/**
*
* A delegation to work item descriptions (Lore) intelligently.
* It will generally be necessary to make defensive
* copies to make customizations.
*
* <pre>
* class DescriptionUseCase {
*
* private final Description defaultDescription = Description.of(
* "- User information - ",
* "",
* " Player Name: @playerName",
* " Player Level: @playerLevel",
* " Player Experience: @playerExp"
* );
*
* public Description renderDescription(Description description, Player viewer) {
* return description.clone()
* .replace("@playerName", viewer.getName())
* .replace("@playerLevel", viewer.getLevel())
* .replace("@playerExperience", viewer.getTotalExperience());
* }
* }
* </pre>
*
*/
public final class Description implements Cloneable {
private static final Function<String, String> COLOR_FUNCTION = string -> ChatColor.translateAlternateColorCodes('&', string);
private String[] content;
private Description(String... content) {
this.content = content;
}
public static Description of(String... value) {
return new Description(value);
}
public Description transform(Function<String, String> transformer) {
for (int i = 0; i < content.length; i++) {
content[i] = transformer.apply(content[i]);
}
return this;
}
public Description replace(String placeHolder, String value) {
return transform(line -> line.replace(placeHolder, value));
}
public Description replace(String placeHolder, Object value) {
return replace(placeHolder, String.valueOf(value));
}
public Description colorize() {
return transform(COLOR_FUNCTION);
}
public Description ident(int startSpaceLength, int endSpaceLength) {
String startSpace = startSpaceLength <= 0 ? "" : Strings.repeat(" ", startSpaceLength);
String endSpace = endSpaceLength <= 0 ? "" : Strings.repeat(" ", endSpaceLength);
return transform(line -> startSpace + line + endSpace);
}
@Override
protected Description clone() {
return new Description(content);
}
public List<String> getContentAsList() {
return ImmutableList.copyOf(content);
}
public String[] getContent() {
return content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment