Skip to content
Open
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
338 changes: 313 additions & 25 deletions package-lock.json

Large diffs are not rendered by default.

61 changes: 46 additions & 15 deletions src/engine/grid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,11 @@ export enum GridLayers {

export type Tile = {
id: string;
TileComponent: React.ComponentType;
TileComponent: React.ComponentType<any>;
layer: GridLayers;
position: Vector;
entity?: EntityContext;
};

type TileHandle = {
tile: Tile;
position: Vector;
state?: any;
};

export type Cell = {
Expand Down Expand Up @@ -67,13 +63,15 @@ export type GridState = {
};

export type GridActions = {
addTile: (
addTile: <T extends {}, S>(
position: Vector,
TileComponent: React.ComponentType,
TileComponent: React.ComponentType<T>,
layer?: GridLayers,
entity?: EntityContext
) => TileHandle;
removeTile: (handle: TileHandle) => void;
entity?: EntityContext,
state?: S
) => Tile;
updateTileState: (handle: Tile, state: any) => Tile;
removeTile: (handle: Tile) => void;
findTiles: (predicate: TileFilterPredicate) => Tile[];
getCell: (at: Vector) => Cell;
updateSeen: (seen: SeenGrid) => void;
Expand All @@ -85,13 +83,21 @@ export const [useGrid, GridProvider] = createContext<GridActions>();
export const [useGridState, GridStateProvider] = createContext<GridState>();

export const gridMutations = {
addTile: (
addTile: <T, S>(
position: Vector,
TileComponent: React.ComponentType,
TileComponent: React.ComponentType<T>,
layer: GridLayers = GridLayers.Floor,
entity?: EntityContext
entity?: EntityContext,
state?: S
) => (grid: GridState): [GridState, Tile] => {
const tile: Tile = { TileComponent, id: v4(), layer, position, entity };
const tile: Tile = {
TileComponent,
id: v4(),
layer,
position,
entity,
state
};
// TODO: Following grid expansion code didn't work (because of immer proxy)
// can be reinstated now but need to handle seen grid too
// if (!original.map[position.y]) {
Expand All @@ -113,6 +119,31 @@ export const gridMutations = {
tile
];
},
updateTileState: (handle: Tile, state: any) => (
grid: GridState
): [GridState, Tile] => {
const tiles = grid.map[handle.position.y]?.[handle.position.x]?.tiles;
if (!tiles) {
return [grid, handle];
}
// Slightly contorted map so we can retrieve the newly generated item to return as handle
let newHandle: Tile | undefined;
const newTiles = tiles.map(tile => {
// TODO: Can't remember why refs didn't work and id was needed...
if (tile.id === handle.id) {
newHandle = { ...tile, state };
return newHandle;
}
return tile;
});
if (newHandle) {
const newGrid = produce(grid, grid => {
grid.map[handle.position.y][handle.position.x].tiles = newTiles;
});
return [newGrid, newHandle! || handle];
}
return [grid, handle];
},
removeTile: (handle: Tile) => (grid: GridState): [GridState, undefined] => {
const tiles = grid.map[handle.position.y]?.[handle.position.x]?.tiles;
const index = tiles?.findIndex(tile => tile.id === handle.id);
Expand Down
27 changes: 19 additions & 8 deletions src/engine/hasTile.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
import React, { useEffect } from "react";
import React, { useEffect, useRef } from "react";
import { hasPosition } from "./hasPosition";
import { useGrid, GridLayers } from "./grid";
import { useGrid, GridLayers, TileHandle, Tile } from "./grid";
import { useEntity } from "./useEntitiesState";
import { Emoji } from "../ui/Typography";

export type TileProps = {
TileComponent?: React.ComponentType;
};

export const hasTile = (
TileComponent: React.ComponentType,
layer?: GridLayers
export const hasTile = <T extends {}, S>(
TileComponent: React.ComponentType<T>,
layer?: GridLayers,
state?: S
) => {
const entity = useEntity();
const { addTile, removeTile } = useGrid();
const { addTile, removeTile, updateTileState } = useGrid();

const [position] = hasPosition(null);

const tileRef = useRef<Tile>();

useEffect(() => {
if (position) {
const tileHandle = addTile(position, TileComponent, layer, entity);
return () => removeTile(tileHandle);
tileRef.current = addTile(position, TileComponent, layer, entity, state);
// TODO: If only position changed, move the tile instead of replace
return () => removeTile(tileRef.current!);
}
}, [position, TileComponent, addTile, removeTile]);

useEffect(() => {
// TODO: Hmm ... could go on main effect
if (tileRef.current && tileRef.current.state !== state) {
updateTileState(tileRef.current, state);
}
}, [state]);
};

export const tile = (glyph: string) => () => <Emoji>{glyph}</Emoji>;
25 changes: 25 additions & 0 deletions src/engine/text/commonFunctions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { text } from './parse';

const vowels = [
"a","e","i","o","u"
]

// TODO: some dictionary of "an" h-words like hour?
const usesAnForm = (word:string) => vowels.includes(word[0])

type AProps = {
word:string
}

const titleCase = (word:string) => word[0].toLocaleUpperCase() + word.slice(1)s

export const commonFunctions = text`
a($word):
${({word}: AProps)=> usesAnForm(word) ? "an" : "a"} $word

title:
${titleCase}

null:
!
`
168 changes: 109 additions & 59 deletions src/engine/text/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ type MainAST = ContentChoiceAST & {

type ImportLabels = Record<string, string | ChoiceAST[]>;

export type ParsedText = (
rng: RNG,
variables?: Record<string, string>,
importLabels?: ImportLabels
) => string;
const ERROR_MAIN : MainAST = {
type:"main",
choices: []
labels: []
}

const createLabelsFromObject = (labels: ImportLabels) =>
Object.entries(labels).map<LabelAST>(([key, value]) => ({
Expand All @@ -63,13 +63,13 @@ const createLabelsFromObject = (labels: ImportLabels) =>
{
type: "choice",
content: { type: "text", text: value } as ContentTextAST,
weight: 10
} as ChoiceAST
weight: 10,
} as ChoiceAST,
]
: ((Array.isArray(value) ? value : [value]) as ChoiceAST[])
: ((Array.isArray(value) ? value : [value]) as ChoiceAST[]),
}));

export const parse = (input: string): ParsedText => {
export const parse = (input: string): MainAST => {
const parser = new nearley.Parser(
nearley.Grammar.fromCompiled(grammar as nearley.CompiledRules)
);
Expand All @@ -80,68 +80,118 @@ export const parse = (input: string): ParsedText => {
console.error("Unparseable text:");
console.error(input);
console.error(error);
return () => "<Error: Unparseable text>";
throw new Error("Unparseable text");
}
const main = (parsed.results[0] as unknown) as MainAST;
if (main === undefined) {
console.error("Undefined main:");
console.error(input);
console.error(parsed);
return () => "<Error: Undefined main>";
throw new Error("Undefined main");
}
const execute = (
return main;
};

export const executeText = (
main: MainAST,
rng: RNG,
variables: Record<string, string> = {},
externals: any[] = [],
importLabels?: ImportLabels
) => {
let mergedLabels = importLabels
? [...main.labels, ...createLabelsFromObject(importLabels)]
: main.labels;
const processContent = (content: ContentAST): string => {
if (Array.isArray(content)) {
return content.map((choice) => processContent(choice)).join("");
}
switch (content.type) {
case "text":
return (content as ContentTextAST).text;
case "choices":
case "main":
case "label":
const choices = (content as ContentChoiceAST).choices;
const chosen = rng.pick(choices);
return processContent(chosen.content);
case "substitution":
case "assignment":
const label = content as ContentSubstitutionAST;
let found;
if (Object.prototype.hasOwnProperty.call(variables, label.label)) {
found = variables[label.label];
} else {
found = mergedLabels.find((l) => l.name === label.label);
}
if (found === undefined) {
return `<Error: Label ${label.label}not found>`;
}
const result =
typeof found === "string" ? found : processContent(found);
if (content.type === "assignment") {
variables[(content as ContentAssignmentAST).variable] = result;
}
return result;
case "function":
const functionNode = content as FunctionAST;
switch (functionNode.name) {
case "OUT":
break;
}
default:
throw new Error("Unknown content type: " + content.type);
}
};
return processContent(main);
};

export type ParsedTextTemplate = {
main: MainAST;
externals: any[];
render: (
rng: RNG,
variables: Record<string, string> = {},
variables?: Record<string, string>,
importLabels?: ImportLabels
) => {
let mergedLabels = importLabels
? [...main.labels, ...createLabelsFromObject(importLabels)]
: main.labels;
const processContent = (content: ContentAST): string => {
if (Array.isArray(content)) {
return content.map(choice => processContent(choice)).join("");
}
switch (content.type) {
case "text":
return (content as ContentTextAST).text;
case "choices":
case "main":
case "label":
const choices = (content as ContentChoiceAST).choices;
const chosen = rng.pick(choices);
return processContent(chosen.content);
case "substitution":
case "assignment":
const label = content as ContentSubstitutionAST;
let found;
if (Object.prototype.hasOwnProperty.call(variables, label.label)) {
found = variables[label.label];
} else {
found = mergedLabels.find(l => l.name === label.label);
}
if (found === undefined) {
return `<Error: Label ${label.label}not found>`;
}
const result =
typeof found === "string" ? found : processContent(found);
if (content.type === "assignment") {
variables[(content as ContentAssignmentAST).variable] = result;
}
return result;
default:
throw new Error("Unknown content type: " + content.type);
}
};
return processContent(main);
};
return execute;
) => string;
};

export const text = (input: TemplateStringsArray, ...interpolations: any[]) => {
export const text = (
input: TemplateStringsArray,
...interpolations: any[]
): ParsedTextTemplate => {
const flattened = input
.map(value => {
return value;
.map((fragment, i) => {
if (interpolations[i]) {
return `${fragment}<OUT(${i})>`;
}
return fragment;
})
.join("");
return parse(flattened);
try {
const main = parse(flattened);
const externals = interpolations.slice();

return {
main,
externals,
render: (
rng: RNG,
variables?: Record<string, string>,
importLabels?: ImportLabels,
) => executeText(main, rng, variables, externals, importLabels),
stream: <S extends {}>(
rng: RNG,
currentState: S,
variables?: Record<string, string>,
importLabels?: ImportLabels,
) => executeText(main, rng, currentState, externals, importLabels)
};
} catch (e) {
return {
main: ERROR_MAIN,
externals: [],
render: () => `<Error: ${e.message}>`
}
}
};
17 changes: 17 additions & 0 deletions src/engine/useStory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useState, useRef } from "react";
import { parse } from "./text/parse";

export const useStory = <S extends {}>(initializer, defaultState = {}) => {
// TODO: implement persistedState already
const [state, setState] = useState<S>(null!);
// Quite a cheap hack. Maybe need to use useEffect, but it's nice if the story
// runs straight away so state that gets set can be used immediately.
// If state changes do we re-run initializer? Need a system to record rng decisions?
const firstRef = useRef(false);
const mainRef = useRef<MainAST>();
if (!mainRef.current) {
firstRef.current = true;
mainRef.current = initializer();
}
const main = mainRef.current;
};
Loading