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
20 changes: 20 additions & 0 deletions packages/gjs/src/widgets/editor/condition-model.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
removeLeaf,
replaceLeaf,
usesItems,
whenSentence,
} from './condition-model.ts'

const FLAGS: ConditionFlag[] = [
Expand Down Expand Up @@ -109,6 +110,25 @@ export default async () => {
expect(conditionSummary({ type: 'has-item', itemId: 'sword' }, FLAGS)).toBe('Has item sword')
})

await it('says a state card\'s condition as one whole "When" sentence', async () => {
expect(whenSentence({ type: 'counter', flag: 'coins', op: '≥', value: 3 }, FLAGS)).toBe('When Coins ≥ 3')
expect(whenSentence({ flag: 'key' }, FLAGS)).toBe('When Has Key is Yes')
expect(whenSentence({ flag: 'key', equals: false }, FLAGS)).toBe('When Has Key is No')
expect(whenSentence({ flag: 'mood', equals: 'happy' }, FLAGS)).toBe('When Mood is “happy”')
expect(
whenSentence(
{ type: 'all', of: [{ flag: 'key' }, { type: 'counter', flag: 'coins', op: '≠', value: 0 }] },
FLAGS,
),
).toBe('When all of: Has Key is Yes; Coins ≠ 0')
expect(whenSentence({ type: 'any', of: [{ flag: 'key' }, { flag: 'mood', equals: 'a' }] }, FLAGS)).toBe(
'When any of: Has Key is Yes; Mood is “a”',
)
expect(whenSentence({ type: 'not', of: { flag: 'key' } }, FLAGS)).toBe('When not: Has Key is Yes')
expect(whenSentence({ type: 'has-item', itemId: 'sword' }, FLAGS)).toBe('When the player has item sword')
expect(whenSentence(undefined, FLAGS)).toBe('Only when switched on by an action')
})

await it('flags items so the editor can warn', async () => {
expect(usesItems({ type: 'has-item', itemId: 'a' })).toBe(true)
expect(usesItems({ type: 'any', of: [{ flag: 'key' }, { type: 'has-item', itemId: 'a' }] })).toBe(true)
Expand Down
58 changes: 58 additions & 0 deletions packages/gjs/src/widgets/editor/condition-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,26 @@ export interface ConditionText {
not(part: string): string
/** What stands in for a flag or item nobody picked yet. */
noFlag: string
/**
* The same leaves as one WHOLE "When …" sentence each, for a state card:
* a translation reorders the words, so none of these is built by
* gluing {@link ConditionText.flagIsYesNo} and friends to a "When".
*/
when: WhenText
}

/** The "When …" sentences of a state card. */
export interface WhenText {
flagIsYesNo(flag: string, on: boolean): string
flagIsText(flag: string, value: string): string
counter(flag: string, op: CounterOperator, value: number): string
hasItem(item: string): string
/** `parts` are the leaf sentences without a leading "When", joined by the caller. */
all(parts: string): string
any(parts: string): string
not(part: string): string
/** A state without a condition: switched on by hand only. */
manual: string
}

export const ENGLISH_CONDITION_TEXT: ConditionText = {
Expand All @@ -52,6 +72,16 @@ export const ENGLISH_CONDITION_TEXT: ConditionText = {
any: (parts) => parts.join(' or '),
not: (part) => `Not: ${part}`,
noFlag: '…',
when: {
flagIsYesNo: (flag, on) => `When ${flag} is ${on ? 'Yes' : 'No'}`,
flagIsText: (flag, value) => `When ${flag} is “${value}”`,
counter: (flag, op, value) => `When ${flag} ${op} ${value}`,
hasItem: (item) => `When the player has item ${item}`,
all: (parts) => `When all of: ${parts}`,
any: (parts) => `When any of: ${parts}`,
not: (part) => `When not: ${part}`,
manual: 'Only when switched on by an action',
},
}

/** A flag as the picker knows it. */
Expand Down Expand Up @@ -217,3 +247,31 @@ export function conditionSummary(
const parts = condition.of.map((l) => leafSummary(l, flags, text))
return condition.type === 'all' ? text.all(parts) : text.any(parts)
}

/**
* The condition as a card's "When …" sentence. A single leaf reads as one
* whole sentence; a group lists its leaves (each as its plain summary,
* `; ` apart) inside one whole group sentence. Built from the same leaf
* summary as {@link conditionSummary}, so the two never disagree.
*/
export function whenSentence(
condition: Condition | undefined,
flags: readonly ConditionFlag[],
text: ConditionText = ENGLISH_CONDITION_TEXT,
): string {
if (!condition) return text.when.manual
const name = (id: string) => (id ? (flags.find((f) => f.value === id)?.label ?? text.noFlag) : text.noFlag)
if (!isGroup(condition)) {
if ('type' in condition && condition.type === 'has-item') return text.when.hasItem(condition.itemId || text.noFlag)
if ('type' in condition && condition.type === 'counter')
return text.when.counter(name(condition.flag), condition.op, condition.value)
const leaf = condition as { flag: string; equals?: FlagValue }
const equals = leaf.equals ?? true
return typeof equals === 'string'
? text.when.flagIsText(name(leaf.flag), equals)
: text.when.flagIsYesNo(name(leaf.flag), equals !== false)
}
if (condition.type === 'not') return text.when.not(leafSummary(condition.of, flags, text))
const parts = condition.of.map((l) => leafSummary(l, flags, text)).join('; ')
return condition.type === 'all' ? text.when.all(parts) : text.when.any(parts)
}
17 changes: 17 additions & 0 deletions packages/gjs/src/widgets/editor/condition-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ export function conditionText(): ConditionText {
any: (parts) => parts.join(_(' or ')),
not: (part) => fill(_('Not: %1$s'), part),
noFlag: _('…'),
when: {
// Translators: a state card's condition. %1$s is a flag name; "Yes" is the flag being switched on.
flagIsYesNo: (flag, on) => fill(on ? _('When %1$s is Yes') : _('When %1$s is No'), flag),
// Translators: a state card's condition. %1$s is a flag name, %2$s the word it must hold.
flagIsText: (flag, value) => fill(_('When %1$s is “%2$s”'), flag, value),
// Translators: a state card's condition. %1$s is a number flag, %2$s a comparison sign (≥, ≤, =, …), %3$s a number.
counter: (flag, op, value) => fill(_('When %1$s %2$s %3$s'), flag, op, value),
// Translators: a state card's condition. %1$s is the name of an item.
hasItem: (item) => fill(_('When the player has item %1$s'), item),
// Translators: a state card's condition. %1$s is a list of short conditions separated by semicolons; all must hold.
all: (parts) => fill(_('When all of: %1$s'), parts),
// Translators: a state card's condition. %1$s is a list of short conditions separated by semicolons; one must hold.
any: (parts) => fill(_('When any of: %1$s'), parts),
// Translators: a state card's condition. %1$s is a short condition that must NOT hold.
not: (part) => fill(_('When not: %1$s'), part),
manual: _('Only when switched on by an action'),
},
}
}

Expand Down
37 changes: 24 additions & 13 deletions packages/gjs/src/widgets/editor/entity-components-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
type DormantComponentFacts,
dormantComponentFacts,
} from './entity-components-editor.model.ts'
import { ConditionEditor } from './condition-editor.ts'
import { StateCard } from './state-card.ts'
import { EventActionListEditor } from './event-action-list-editor.ts'

/** A per-component editor widget in the stack — the generic inspector or a bespoke one. */
Expand Down Expand Up @@ -91,6 +91,7 @@ export class EntityComponentsEditor extends Adw.Bin {
private _name = ''
private _editorData: EntityDefinition['editorData']
private _states: EntityDefinition['states']
private _stateCards = new Map<string, StateCard>()
private _components: ComponentData[] = []
private _refOptions: ComponentRefOptions = {}
private _fullView = true
Expand Down Expand Up @@ -210,7 +211,7 @@ export class EntityComponentsEditor extends Adw.Bin {
setRefOptions(options: ComponentRefOptions): void {
this._refOptions = options
for (const editor of this._componentEditors()) editor.setRefOptions(options)
for (const child of this._rendered) if (child instanceof ConditionEditor) child.setRefOptions(options)
for (const child of this._rendered) if (child instanceof StateCard) child.setRefOptions(options)
}

/** Populate from an entity definition (no `entity-changed` echo). */
Expand Down Expand Up @@ -240,6 +241,7 @@ export class EntityComponentsEditor extends Adw.Bin {
this._silent = true
for (const child of this._rendered) this._box.remove(child)
this._rendered = []
this._stateCards.clear()
for (let i = 0; i < this._components.length; i++) {
const child = this._buildRow(this._components[i], i)
if (!child) continue
Expand Down Expand Up @@ -341,17 +343,26 @@ export class EntityComponentsEditor extends Adw.Bin {
}

/**
* One "When" editor per state: the condition that switches the state on.
* Absent `when` (a manually switched state) has no row — nothing to edit.
* One card per state, in the order the engine checks them: the first
* state whose condition holds wins. A state without a condition is
* shown too (as "switched on by an action") so the order is complete.
*/
private _renderStateConditions(): void {
;(this._states ?? []).forEach((state, index) => {
if (state.when === undefined) return
const editor = new ConditionEditor()
editor.set_title(_('When “%s”').replace('%s', state.id))
editor.setRefOptions(this._refOptions)
editor.setCondition(state.when)
editor.connect('condition-changed', (_w: ConditionEditor, json: string) => {
const states = this._states ?? []
if (states.length === 0) return
const hint = new Gtk.Label({
// Translators: shown above the list of a thing's states.
label: _('States are checked from top to bottom. The first one whose condition holds is used.'),
wrap: true,
xalign: 0,
cssClasses: ['dim-label', 'caption'],
})
this._box.insert_child_after(hint, this._lastRenderedOrNull())
this._rendered.push(hint)
states.forEach((state, index) => {
const card = new StateCard(state.id, state.when, this._refOptions)
this._stateCards.set(state.id, card)
card.connect('condition-changed', (_w: StateCard, json: string) => {
if (!this._states) return
try {
this._states = this._states.map((st, i) => (i === index ? { ...st, when: JSON.parse(json) } : st))
Expand All @@ -360,8 +371,8 @@ export class EntityComponentsEditor extends Adw.Bin {
}
this._emitChange()
})
this._box.insert_child_after(editor, this._lastRenderedOrNull())
this._rendered.push(editor)
this._box.insert_child_after(card, this._lastRenderedOrNull())
this._rendered.push(card)
})
}

Expand Down
1 change: 1 addition & 0 deletions packages/gjs/src/widgets/editor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export * from './sheet-alpha'
export * from './sheet-detent-controller'
export * from './sheet-detents'
export * from './starter-pack-shelf'
export * from './state-card'
export * from './teleport-overlay.geometry'
export * from './teleport-overlay'
export * from './terrain-label'
Expand Down
5 changes: 5 additions & 0 deletions packages/gjs/src/widgets/editor/phone-chrome.probe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ export default async () => {
expect(cond.sheetMinPx).toBeLessThanOrEqual(cond.floorPx)
expect(cond.sheetAllocPx).toBe(cond.floorPx)
expect(cond.offenders.length).toBe(0)
console.log(
`[phone-chrome] state cards ${cond.stateCards} widest min ${cond.stateCardMinPx} (floor ${cond.floorPx})`,
)
expect(cond.stateCards).toBe(2)
expect(cond.stateCardMinPx).toBeLessThanOrEqual(cond.floorPx)
})

await it('keeps the Game memory page, every row kind and the experts group, within the floor', async () => {
Expand Down
15 changes: 15 additions & 0 deletions packages/gjs/src/widgets/editor/phone-chrome.probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { pumpUntil, solidPaintable, solidPaintableRect } from './pixel-probe.ts'
import { RecentTiles } from './recent-tiles.ts'
import { RECENT_TILES_MAX } from './recent-tiles.geometry.ts'
import { SceneEditor } from './scene-editor.ts'
import { StateCard } from './state-card.ts'
import type { TileDescriptor } from './tile-palette.ts'
import { sheetGridOf } from './tile-sheet.geometry.ts'

Expand Down Expand Up @@ -271,6 +272,14 @@ export interface ConditionWidthReport {
sheetAllocPx: number
/** Every descendant whose own minimum exceeds `floorPx`, outermost first. */
offenders: WidthReport[]
/** How many state cards the selected gate showed, and the widest minimum among them. */
stateCards: number
stateCardMinPx: number
}

function collectStateCards(widget: Gtk.Widget, out: StateCard[]): void {
if (widget instanceof StateCard) out.push(widget)
for (let c = widget.get_first_child(); c; c = c.get_next_sibling()) collectStateCards(c, out)
}

function scan(widget: Gtk.Widget, floorPx: number, depth: number, out: WidthReport[]): void {
Expand Down Expand Up @@ -332,8 +341,12 @@ export function probeConditionEditor(): ConditionWidthReport {
pumpUntil(() => editor.get_mapped() && editor._phone_bar.get_width() > 0, 'condition sheet window')
const offenders: WidthReport[] = []
scan(editor._bottom_sheet, floorPx, 0, offenders)
const cards: StateCard[] = []
collectStateCards(editor._bottom_sheet, cards)
const result = {
floorPx,
stateCards: cards.length,
stateCardMinPx: Math.max(0, ...cards.map((c) => c.measure(Gtk.Orientation.HORIZONTAL, -1)[0])),
sheetMinPx: editor._bottom_sheet.measure(Gtk.Orientation.HORIZONTAL, -1)[0],
sheetAllocPx: editor._bottom_sheet.get_width(),
offenders,
Expand Down Expand Up @@ -400,6 +413,8 @@ export function probeGameMemory(): ConditionWidthReport {
sheetMinPx: editor._bottom_sheet.measure(Gtk.Orientation.HORIZONTAL, -1)[0],
sheetAllocPx: editor._bottom_sheet.get_width(),
offenders,
stateCards: 0,
stateCardMinPx: 0,
}
window.destroy()
return result
Expand Down
111 changes: 111 additions & 0 deletions packages/gjs/src/widgets/editor/state-card.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import Adw from '@girs/adw-1'
import GObject from '@girs/gobject-2.0'
import Gtk from '@girs/gtk-4.0'
import type { Condition } from '@pixelrpg/engine'
import { gettext as _ } from 'gettext'
import type { ComponentRefOptions } from './component-inspector.ts'
import { ConditionEditor } from './condition-editor.ts'
import { type ConditionFlag, whenSentence } from './condition-model.ts'
import { conditionText } from './condition-summary.ts'

const DIALOG_WIDTH = 420
const DIALOG_HEIGHT = 520

/** Typed view of the signals {@link StateCard} registers. */
export interface StateCardSignals extends Adw.PreferencesGroup.SignalSignatures {
'condition-changed': (conditionJson: string) => void
}

/**
* One state of a thing as a card: the state's name, a "When …" sentence
* that reads its condition back (the same summary source as the condition
* editor), and — during a test run only — an "Active now" badge on the
* state the engine resolved. Tapping the sentence opens the
* {@link ConditionEditor} in a dialog; a state without a condition has
* only the sentence "switched on by an action" and nothing to edit.
*/
export class StateCard extends Adw.PreferencesGroup {
private _condition: Condition | undefined
private _refOptions: ComponentRefOptions = {}
private _row = new Adw.ActionRow({ titleLines: 0 })
private _badge = new Gtk.Label({
label: _('Active now'),
visible: false,
valign: Gtk.Align.CENTER,
ellipsize: 3,
cssClasses: ['state-active-badge'],
})

static {
GObject.registerClass(
{
GTypeName: 'PixelRpgStateCard',
Signals: { 'condition-changed': { param_types: [GObject.TYPE_STRING] } },
},
StateCard,
)
}

declare connect: GObject.SignalMethods<this, StateCardSignals>['connect']
declare connect_after: GObject.SignalMethods<this, StateCardSignals>['connect_after']
declare emit: GObject.SignalMethods<this, StateCardSignals>['emit']

constructor(stateId: string, condition: Condition | undefined, refOptions: ComponentRefOptions) {
super({ title: stateId })
this._condition = condition
this._refOptions = refOptions
this.set_header_suffix(this._badge)
this._row.add_css_class('state-card-row')
if (condition !== undefined) {
this._row.set_activatable(true)
this._row.add_suffix(new Gtk.Image({ iconName: 'go-next-symbolic', valign: Gtk.Align.CENTER }))
this._row.connect('activated', () => this._presentEditor())
}
this.add(this._row)
this._refreshSentence()
}

setRefOptions(options: ComponentRefOptions): void {
this._refOptions = options
this._refreshSentence()
}

/** Show or hide the "Active now" badge; the host calls this only during a run. */
setActive(active: boolean): void {
this._badge.set_visible(active)
}

private get _flags(): ConditionFlag[] {
return (this._refOptions.flags ?? []).map((f) => ({ value: f.value, label: f.label, kind: f.kind }))
}

private _refreshSentence(): void {
this._row.set_title(whenSentence(this._condition, this._flags, conditionText()))
}

private _presentEditor(): void {
const editor = new ConditionEditor()
editor.setRefOptions(this._refOptions)
editor.setCondition(this._condition)
editor.connect('condition-changed', (_w: ConditionEditor, json: string) => {
try {
this._condition = JSON.parse(json) as Condition
} catch {
return
}
this._refreshSentence()
this.emit('condition-changed', json)
})
const page = new Adw.PreferencesPage()
page.add(editor)
const view = new Adw.ToolbarView({ content: page })
view.add_top_bar(new Adw.HeaderBar())
const dialog = new Adw.Dialog({
title: this.get_title(),
contentWidth: DIALOG_WIDTH,
contentHeight: DIALOG_HEIGHT,
})
dialog.set_child(view)
dialog.present(this)
}
}
Loading
Loading