Skip to content
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
8 changes: 4 additions & 4 deletions apps/maker-gjs/src/services/flags-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
type FlagKind,
type FlagUsage,
defaultFlagInitial,
findFlagUsage,
findFlagUsages,
newFlagId,
} from '@pixelrpg/engine'

Expand Down Expand Up @@ -33,9 +33,9 @@ export function newFlag(list: readonly FlagData[], name: string, kind: FlagKind

/** Where `flagId` is referenced, across the library and every loaded map. */
export function flagUsage(
data: Parameters<typeof findFlagUsage>[0],
maps: Parameters<typeof findFlagUsage>[1],
data: Parameters<typeof findFlagUsages>[0],
maps: Parameters<typeof findFlagUsages>[1],
flagId: string,
): FlagUsage[] {
return findFlagUsage(data, maps, flagId)
return findFlagUsages(data, maps).get(flagId) ?? []
}
25 changes: 25 additions & 0 deletions apps/maker-gjs/src/services/game-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type { HeroOption, StartMapOption } from '../widgets/game/game-dialogs.ts
import type { GameView, GameViewModel, LanguageRow } from '../widgets/game-view.ts'
import { listCharacterViewModels } from './cast-controller-view-model.ts'
import { buildGameCheckup } from './game-checkup.model.ts'
import { buildFlagRows } from './game-flags.model.ts'
import { buildGameRulesModel } from './game-rules-model.ts'
import { collectAtlasTeleports } from './project-loader.ts'
import type { ProjectStore } from './project-store.ts'
Expand Down Expand Up @@ -56,6 +57,10 @@ export interface CreditRemoveHost {
reportCreditRemoved(name: string, undo: () => void): void
/** "Test in": the language a test run speaks (`undefined` = the project default). */
setTestLocale(locale: string | undefined): void
/** A flag was removed: a toast whose Undo runs `undo`. */
reportFlagRemoved(name: string, undo: () => void): void
/** A flag was kept because `count` places still name it. */
reportFlagInUse(name: string, count: number): void
}

export class GameController {
Expand All @@ -77,6 +82,7 @@ export class GameController {
this.store.setLanguages(languages)
},
setTestLocale: (locale) => host.setTestLocale(locale),
removeFlag: (flagId) => this._removeFlag(flagId, host),
})
store.on('project-changed', (project) => {
if (!project) {
Expand Down Expand Up @@ -114,6 +120,24 @@ export class GameController {
store.on('credits-changed', () => {
if (this.store.project) this._rebuild()
})
// New, renamed or removed flags; map and library edits that change
// what uses them already re-render through their own events.
store.on('flags-changed', () => {
if (this.store.project) this._rebuild()
})
}

private _removeFlag(flagId: string, host: CreditRemoveHost): void {
const result = this.store.removeFlag(flagId)
if (result.removed) {
const previous = result.previous
host.reportFlagRemoved(previous.name, () => {
this.store.upsertFlag(previous)
})
} else if ('reason' in result && result.reason === 'in-use') {
const name = this.store.flags().find((f) => f.id === flagId)?.name ?? flagId
host.reportFlagInUse(name, result.usage.length)
}
}

/** Persist a single project-metadata field edit (no row re-render). */
Expand Down Expand Up @@ -197,6 +221,7 @@ export class GameController {
projectResource: resource,
credits: this.store.credits(),
languages: languageRows(data, maps),
flags: buildFlagRows({ project: data, maps, characterIds: characters.map((c) => c.id) }),
}
this.view.setData(model)
}
Expand Down
91 changes: 91 additions & 0 deletions apps/maker-gjs/src/services/game-flags.model.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { describe, expect, it } from '@gjsify/unit'
import type { GameProjectData, MapData } from '@pixelrpg/engine'

import { buildFlagRows } from './game-flags.model.ts'

const project = {
flags: [
{ id: 'key', name: 'Has key', kind: 'yes-no' },
{ id: 'idle', name: 'Idle', kind: 'yes-no' },
],
entityLibrary: [
{
id: 'door',
name: 'Door',
components: [
{
type: 'actions',
actions: [{ id: 'a', type: 'set-flag', flag: 'key', value: true }],
},
],
states: [{ id: 's', when: { flag: 'ghost' }, components: [] }],
},
{
id: 'hero',
name: 'Hero',
components: [],
states: [{ id: 's', when: { flag: 'key' }, components: [] }],
},
],
} as unknown as GameProjectData

const maps = [
{
id: 'm',
name: 'Forest',
objectPlacements: [
{
id: 'p1',
defId: 'door',
overrides: {
name: 'Front door',
components: [
{
type: 'actions',
actions: [{ id: 'b', type: 'set-flag', flag: 'key', value: true }],
},
],
},
},
],
},
] as unknown as MapData[]

export default async () => {
await describe('buildFlagRows', async () => {
await it('keeps named flags first and appends unnamed used ids', async () => {
const rows = buildFlagRows({ project, maps, characterIds: ['hero'] })
expect(rows.map((r) => r.id)).toStrictEqual(['key', 'idle', 'ghost'])
})

await it('leaves an unused flag with no usages', async () => {
const rows = buildFlagRows({ project, maps, characterIds: ['hero'] })
expect(rows[1].usages.length).toBe(0)
})

await it('names placements by override and links by kind', async () => {
const key = buildFlagRows({ project, maps, characterIds: ['hero'] })[0].usages
const placed = key.find((u) => u.access === 'write' && u.mapName === 'Forest')!
expect(placed.thingName).toBe('Front door')
expect(placed.link).toStrictEqual({
action: 'win.focus-placement',
target: ['m', 'p1'],
})
const lib = key.find((u) => u.thingName === 'Hero')!
expect(lib.access).toBe('read')
expect(lib.link).toStrictEqual({
action: 'win.open-character',
target: 'hero',
})
const obj = buildFlagRows({
project,
maps: [],
characterIds: ['hero'],
})[0].usages.find((u) => u.thingName === 'Door')!
expect(obj.link).toStrictEqual({
action: 'win.open-object',
target: 'door',
})
})
})
}
79 changes: 79 additions & 0 deletions apps/maker-gjs/src/services/game-flags.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { type FlagAccess, type FlagData, type FlagKind, type MapData, findFlagUsages } from '@pixelrpg/engine'
import type { GameProjectData } from '@pixelrpg/engine'

import type { CheckupLink } from './game-checkup.model.ts'

/**
* The Game page's Flags section as facts: one row per flag with every
* place that reads or writes it. String-free like `game-checkup.model.ts`;
* `widgets/game/flags-list.ts` owns the words.
*/

/** One place a flag is used, with where a tap goes. */
export interface FlagUsageRow {
/** Unique within its flag (a flag can be used twice by one thing). */
readonly key: string
readonly access: FlagAccess
/** The thing's name (a placement's own name wins over its definition's). */
readonly thingName: string
/** The map it stands on, or `null` for a library thing not placed here. */
readonly mapName: string | null
readonly link: CheckupLink | null
}

/** One flag and its usages. */
export interface FlagRow {
readonly id: string
readonly name: string
readonly kind: FlagKind
readonly usages: readonly FlagUsageRow[]
}

export interface FlagsModelInput {
readonly project: Pick<GameProjectData, 'entityLibrary' | 'flags'>
readonly maps: readonly MapData[]
/** Ids of library entries that are characters: their tap opens the Cast. */
readonly characterIds: readonly string[]
}

/** Every flag, named flags first by their order in the project; unnamed ids a project still uses follow. */
export function buildFlagRows(input: FlagsModelInput): FlagRow[] {
const { project, maps, characterIds } = input
const usages = findFlagUsages(project, maps)
const defs = new Map((project.entityLibrary ?? []).map((d) => [d.id, d]))
const mapById = new Map(maps.map((m) => [m.id, m]))
const characters = new Set(characterIds)

const rowFor = (flag: Pick<FlagData, 'id' | 'name' | 'kind'>): FlagRow => {
const list = usages.get(flag.id) ?? []
return {
id: flag.id,
name: flag.name,
kind: flag.kind,
usages: list.map((u, i) => {
const map = u.mapId ? mapById.get(u.mapId) : undefined
const placement = map?.objectPlacements?.find((p) => p.id === u.placementId)
const def = defs.get(u.entityId)
const thingName = placement?.overrides?.name?.trim() || def?.name || u.entityId
const link: CheckupLink | null =
u.mapId && u.placementId
? { action: 'win.focus-placement', target: [u.mapId, u.placementId] }
: defs.has(u.entityId)
? { action: characters.has(u.entityId) ? 'win.open-character' : 'win.open-object', target: u.entityId }
: null
return {
key: `${u.mapId ?? ''}/${u.placementId ?? u.entityId}/${u.stateIndex ?? ''}/${u.actionIndex ?? ''}/${u.access}/${i}`,
access: u.access,
thingName,
mapName: map ? map.name?.trim() || map.id : null,
link,
}
}),
}
}

const rows = (project.flags ?? []).map(rowFor)
const known = new Set(rows.map((r) => r.id))
for (const id of usages.keys()) if (!known.has(id)) rows.push(rowFor({ id, name: id, kind: 'yes-no' }))
return rows
}
2 changes: 1 addition & 1 deletion apps/maker-gjs/src/services/game-section.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* title card with "Play from the start", which is what most visits are
* for. Shared by `GameView` and the `win.game-section` action.
*/
export const GAME_SECTIONS = ['start', 'rules', 'languages', 'checkup', 'about'] as const
export const GAME_SECTIONS = ['start', 'rules', 'languages', 'flags', 'checkup', 'about'] as const

/** One of the Game page's sections. */
export type GameSection = (typeof GAME_SECTIONS)[number]
Expand Down
8 changes: 7 additions & 1 deletion apps/maker-gjs/src/services/project-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1270,7 +1270,13 @@ export default async () => {
store.setCollabSession(session)

const refused = store.removeFlag('has-key')
expect(refused).toStrictEqual({ removed: false, reason: 'in-use', usage: [{ where: 'entity', id: 'door' }] })
expect(refused.removed).toBe(false)
expect(refused.removed === false && refused.reason === 'in-use' ? refused.usage[0] : null).toMatchObject({
flagId: 'has-key',
access: 'write',
entityId: 'door',
mapId: null,
})
expect(data.flags).toHaveLength(1)
expect(session.sent).toHaveLength(0)

Expand Down
4 changes: 2 additions & 2 deletions apps/maker-gjs/src/services/project-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
FLAG_UPSERT_KIND,
type FlagData,
type FlagKind,
findFlagUsage,
findFlagUsages,
type CreditEntry,
effectiveComponentRegistry,
projectHasSimpleViewHiddenContent,
Expand Down Expand Up @@ -540,7 +540,7 @@ export class ProjectStore {
const data = this.data
const previous = data?.flags?.find((f) => f.id === flagId)
if (!data || !previous) return { removed: false, reason: 'unknown' }
const usage = findFlagUsage(data, this.mapDatas(), flagId)
const usage = findFlagUsages(data, this.mapDatas()).get(flagId) ?? []
if (usage.length > 0) return { removed: false, reason: 'in-use', usage }
applyFlagRemove(data, flagId)
this._persistProject()
Expand Down
2 changes: 2 additions & 0 deletions apps/maker-gjs/src/test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import serialQueueSuite from './services/serial-queue.spec.js'
import sceneNavigatorSuite from './services/scene-navigator.spec.js'
import engineStateSyncSuite from './services/engine-state-sync.spec.js'
import gameCheckupModelSuite from './services/game-checkup.model.spec.js'
import gameFlagsModelSuite from './services/game-flags.model.spec.js'
import gameRulesModelSuite from './services/game-rules-model.spec.js'
import gvariantSuite from './services/gvariant.spec.js'
import lanDiscoverySuite from './services/lan-discovery.spec.js'
Expand Down Expand Up @@ -118,6 +119,7 @@ run({
entityTemplatesSuite,
entityVisualsSuite,
gameCheckupModelSuite,
gameFlagsModelSuite,
gameRulesModelSuite,
gvariantSuite,
instanceIdSuite,
Expand Down
20 changes: 19 additions & 1 deletion apps/maker-gjs/src/widgets/application-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
SignalScope,
type Tile,
} from '@pixelrpg/gjs'
import { gettext as _ } from 'gettext'
import { gettext as _, ngettext } from 'gettext'
import { installWindowAccels, WINDOW_SHORTCUTS } from '../actions/accels.ts'
import { installBackActions } from '../actions/back-actions.ts'
import { installCastActions } from '../actions/cast-actions.ts'
Expand Down Expand Up @@ -1894,6 +1894,24 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe
this._showUndoToast(_('Removed “%s”').replace('%s', name), undo)
}

/** {@link CreditRemoveHost} — a flag was removed; Undo puts it back. */
reportFlagRemoved(name: string, undo: () => void): void {
this._showUndoToast(_('Removed flag “%s”').replace('%s', name), undo)
}

/** {@link CreditRemoveHost} — a used flag stays; the Flags list says where. */
reportFlagInUse(name: string, count: number): void {
this._showToast(
ngettext(
'“%s” is still used in %d place. See Game › Flags.',
'“%s” is still used in %d places. See Game › Flags.',
count,
)
.replace('%s', name)
.replace('%d', String(count)),
)
}

/** {@link AnimationClearHost} — a cell was emptied; Undo restores its pictures. */
reportAnimationCleared(animationId: string, undo: () => void): void {
this._showUndoToast(_('Cleared “%s”').replace('%s', animationId), undo)
Expand Down
Loading
Loading