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

New method for customizing the oracle tree #696

Merged
merged 12 commits into from
Mar 27, 2023
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- Fixed bug with Starforged asset decoration; it should now switch with the game theme as intended ([#700](https://github.com/ben/foundry-ironsworn/pull/700))
- Drop the custom font ([#702](https://github.com/ben/foundry-ironsworn/pull/702))
- Fix a tooltip bug on the edit-sector button
- Added a new method of customizing oracles, which should work better for larger projects like Ironsmith ([#686](https://github.com/ben/foundry-ironsworn/pull/696))

## 1.20.30

Expand Down
15 changes: 13 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ import { FirstStartDialog } from './module/applications/firstStartDialog'
import { SFSettingTruthsDialogVue } from './module/applications/vueSfSettingTruthsDialog'
import { WorldTruthsDialog } from './module/applications/worldTruthsDialog'
import { OracleWindow } from './module/applications/oracle-window'
import {
getOracleTree,
registerOracleTree
} from './module/features/customoracles'

export interface EmitterEvents extends Record<EventType, unknown> {
highlightMove: string // Foundry UUID
Expand All @@ -27,7 +31,6 @@ export type IronswornEmitter = Emitter<EmitterEvents>

export interface IronswornConfig {
actorClass: typeof IronswornActor
importFromDatasworn: typeof importFromDatasworn

applications: {
// Dialogs
Expand All @@ -44,10 +47,15 @@ export interface IronswornConfig {
OracleRollMessage: typeof OracleRollMessage
}

importFromDatasworn: typeof importFromDatasworn

Dataforged: typeof starforged
dataforgedHelpers: typeof dataforgedHelpers

emitter: IronswornEmitter

registerOracleTree: typeof registerOracleTree
getOracleTree: typeof getOracleTree
}

export const IRONSWORN: IronswornConfig = {
Expand All @@ -71,5 +79,8 @@ export const IRONSWORN: IronswornConfig = {
Dataforged: starforged,
dataforgedHelpers,

emitter: Mitt<EmitterEvents>()
emitter: Mitt<EmitterEvents>(),

registerOracleTree,
getOracleTree
}
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { registerTours } from './module/features/tours'
import { CompactPCSheet } from './module/actor/sheets/compact-pc-sheet'

import 'virtual:svg-icons-register'
import { registerDefaultOracleTrees } from './module/features/customoracles'

declare global {
interface LenientGlobalVariableTypes {
Expand Down Expand Up @@ -228,11 +229,11 @@ Hooks.once('ready', async () => {

registerDragAndDropHooks()
registerChatAlertHooks()
runStartupMacro()

await registerDefaultOracleTrees()

await FirstStartDialog.maybeShow()
await registerTours()

// Pre-load all the oracles
await primeCommonPackCaches()
runStartupMacro()
})
102 changes: 78 additions & 24 deletions src/module/features/customoracles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import type {
Ironsworn
} from 'dataforged'
import { starforged, ironsworn } from 'dataforged'
import { compact } from 'lodash-es'
import { cloneDeep, compact } from 'lodash-es'
import { getFoundryTableByDfId } from '../dataforged'
import { cachedDocumentsForPack } from './pack-cache'

export interface IOracleTreeNode {
dataforgedNode?: IOracle | IOracleCategory
tables: Array<() => RollTable>
tables: string[] // UUIDs
displayName: string
children: IOracleTreeNode[]
forceExpanded?: boolean
Expand All @@ -26,12 +26,11 @@ const ISOracleCategories = ((ironsworn as any).default as Ironsworn)[
'Oracle Categories'
]

const emptyNode = () =>
({
displayName: '',
tables: [],
children: []
} as IOracleTreeNode)
const emptyNode: () => IOracleTreeNode = () => ({
displayName: '',
tables: [],
children: []
})

async function createOracleTree(
compendium: string,
Expand All @@ -47,23 +46,17 @@ async function createOracleTree(
rootNode.children.push(await walkOracleCategory(category))
}

// Add in custom oracles from a well-known directory
await augmentWithFolderContents(rootNode)

// Fire the hook and allow extensions to modify the tree
await Hooks.call('ironswornOracles', rootNode)

return rootNode
}

export async function createIronswornOracleTree(): Promise<IOracleTreeNode> {
async function createIronswornOracleTree(): Promise<IOracleTreeNode> {
return await createOracleTree(
'foundry-ironsworn.ironswornoracles',
ISOracleCategories
)
}

export async function createStarforgedOracleTree(): Promise<IOracleTreeNode> {
async function createStarforgedOracleTree(): Promise<IOracleTreeNode> {
return await createOracleTree(
'foundry-ironsworn.starforgedoracles',
SFOracleCategories
Expand Down Expand Up @@ -107,9 +100,9 @@ export async function walkOracle(
const node: IOracleTreeNode = {
...emptyNode(),
dataforgedNode: oracle,
tables: compact([table != null ? () => table : undefined]),
tables: compact([table?.uuid]),
displayName:
table?.name ||
table?.name ??
game.i18n.localize(`IRONSWORN.OracleCategories.${oracle.Name}`)
}

Expand All @@ -127,7 +120,7 @@ export async function walkOracle(
node.children.push({
...emptyNode(),
displayName: name,
tables: [() => subtable]
tables: [subtable.uuid]
})
}
}
Expand Down Expand Up @@ -155,7 +148,7 @@ async function augmentWithFolderContents(node: IOracleTreeNode) {
// Add this folder
const newNode: IOracleTreeNode = {
...emptyNode(),
displayName: folder.name || '(folder)'
displayName: folder.name ?? '(folder)'
}
parent.children.push(newNode)

Expand All @@ -168,7 +161,7 @@ async function augmentWithFolderContents(node: IOracleTreeNode) {
for (const table of folder.contents) {
newNode.children.push({
...emptyNode(),
tables: [() => table as RollTable],
tables: [table.uuid],
displayName: table.name ?? '(table)'
})
}
Expand All @@ -177,14 +170,14 @@ async function augmentWithFolderContents(node: IOracleTreeNode) {
walkFolder(node, rootFolder)
}

export function findPathToNodeByTableId(
export function findPathToNodeByTableUuid(
rootNode: IOracleTreeNode,
tableId: string
tableUuid: string
): IOracleTreeNode[] {
const ret: IOracleTreeNode[] = []
function walk(node: IOracleTreeNode) {
ret.push(node)
const foundTable = node.tables.find((x) => x().id === tableId)
const foundTable = node.tables.find((x) => x === tableUuid)
if (foundTable != null) return true
for (const child of node.children) {
if (walk(child)) return true
Expand Down Expand Up @@ -212,3 +205,64 @@ export function findPathToNodeByDfId(rootNode: IOracleTreeNode, dfId: string) {
walk(rootNode)
return ret
}

type OracleCategory = 'ironsworn' | 'starforged'

const ORACLES: Record<OracleCategory, IOracleTreeNode> = {
ironsworn: emptyNode(),
starforged: emptyNode()
}

export function registerOracleTreeInternal(
category: OracleCategory,
rootNode: IOracleTreeNode
) {
ORACLES[category] = rootNode
}

let defaultTreesInitialized = false

export async function registerDefaultOracleTrees() {
const ironswornOracles = await createIronswornOracleTree()
registerOracleTreeInternal('ironsworn', ironswornOracles)

const starforgedOracles = await createStarforgedOracleTree()
registerOracleTreeInternal('starforged', starforgedOracles)

defaultTreesInitialized = true
}

// Available in browser
export function registerOracleTree(
category: OracleCategory,
rootNode: IOracleTreeNode
) {
// Check if internal registrations have been done
// If not, do nothing and send a warning to the UI
if (!defaultTreesInitialized) {
const message =
'Not ready yet. Call registerOracleTree from a "ready" hook please.'
ui.notifications?.warn(message)
throw new Error(message)
}

registerOracleTreeInternal(category, rootNode)
}

export function getOracleTree(category: OracleCategory): IOracleTreeNode {
return cloneDeep(ORACLES[category])
}

export async function getOracleTreeWithCustomOracles(
category: OracleCategory
): Promise<IOracleTreeNode> {
const rootNode = getOracleTree(category)

// Add in custom oracles from a well-known directory
await augmentWithFolderContents(rootNode)

// Fire the hook and allow extensions to modify the tree
Hooks.call('ironswornOracles', rootNode)

return rootNode
}
26 changes: 12 additions & 14 deletions src/module/rolls/oracle-roll-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import { compact, pick, sortBy } from 'lodash-es'
import { marked } from 'marked'
import { getFoundryTableByDfId } from '../dataforged'
import {
createIronswornOracleTree,
createStarforgedOracleTree,
findPathToNodeByDfId,
findPathToNodeByTableId
findPathToNodeByTableUuid,
getOracleTreeWithCustomOracles
} from '../features/customoracles'

export interface TableRow {
Expand Down Expand Up @@ -68,9 +67,9 @@ export class OracleRollMessage {

static async fromDfOracleId(dfOracleId: string): Promise<OracleRollMessage> {
// Subtitle can be inferred from the structure of the DF ID
const oracleTreeRoot = await (dfOracleId.startsWith('Ironsworn/')
? createIronswornOracleTree
: createStarforgedOracleTree)()
const oracleTreeRoot = await getOracleTreeWithCustomOracles(
dfOracleId.startsWith('Ironsworn/') ? 'ironsworn' : 'starforged'
)
const pathElements = findPathToNodeByDfId(oracleTreeRoot, dfOracleId)
const pathNames = pathElements.map((x) => x.displayName)
pathNames.shift() // root node has no display name
Expand Down Expand Up @@ -172,18 +171,17 @@ export class OracleRollMessage {
}

private async oraclePath(): Promise<string | undefined> {
if (!this.tableUuid) return undefined
const uuid = _parseUuid(this.tableUuid)
if (this.tableUuid == null) return undefined

const starforgedRoot = await getOracleTreeWithCustomOracles('starforged')
const ironswornRoot = await getOracleTreeWithCustomOracles('ironsworn')

const [starforgedRoot, ironswornRooot] = await Promise.all([
createStarforgedOracleTree(),
createIronswornOracleTree()
])
const pathElements =
findPathToNodeByTableId(starforgedRoot, uuid.documentId!) ??
findPathToNodeByTableId(ironswornRooot, uuid.documentId!)
findPathToNodeByTableUuid(starforgedRoot, this.tableUuid) ??
findPathToNodeByTableUuid(ironswornRoot, this.tableUuid)
pathElements.shift() // no display name for root node
pathElements.pop() // last node is the table we rolled

return pathElements.map((x) => x.displayName).join(' / ')
}

Expand Down
2 changes: 1 addition & 1 deletion src/module/vue/components/buttons/btn-oracle.vue
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async function rollOracle() {
if (props.overrideClick && props.onClick) return $emit('click')

const randomTable = sample(props.node.tables)
const orm = await OracleRollMessage.fromTableUuid(randomTable?.()?.uuid ?? '')
const orm = await OracleRollMessage.fromTableUuid(randomTable ?? '')
orm.createOrUpdate()
}
</script>
28 changes: 25 additions & 3 deletions src/module/vue/components/oracle-tree-node.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
<RulesTextOracle
v-if="state.descriptionExpanded"
:class="$style.content"
:oracle-table="node.tables[0]"
:table-rows="state.tableRows"
:table-description="state.tableDescription"
:source="node.dataforgedNode?.Source"
@moveclick="moveclick"
@oracleclick="oracleclick" />
Expand Down Expand Up @@ -65,7 +66,7 @@
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { computed, nextTick, reactive, ref } from 'vue'
import type { IOracleTreeNode } from '../../features/customoracles'
import { FontAwesome } from './icon/icon-common'
import BtnOracle from './buttons/btn-oracle.vue'
Expand All @@ -78,9 +79,19 @@ import IronIcon from './icon/iron-icon.vue'

const props = defineProps<{ node: IOracleTreeNode }>()

// FIXME: use v10 types when available, or hack some together for tables
type TableRowData = {
low: number
high: number
text: string
selected: boolean
}

const state = reactive({
manuallyExpanded: props.node.forceExpanded ?? false,
descriptionExpanded: false,
tableRows: [] as Array<TableRowData>,
tableDescription: '',
highlighted: false
})

Expand All @@ -90,7 +101,18 @@ const isLeaf = computed(() => {
return props.node.tables.length > 0
})

function toggleDescription() {
async function toggleDescription() {
if (!state.tableDescription) {
const table = (await fromUuid(props.node.tables[0])) as RollTable
state.tableRows = table.results.map((row: any) => ({
low: row.range[0],
high: row.range[1],
text: row.text,
selected: false
}))
state.tableDescription = (table as any).description ?? ''
await nextTick()
}
state.descriptionExpanded = !state.descriptionExpanded
}
function toggleManually() {
Expand Down
Loading