Skip to content

Commit

Permalink
Latest sync including AsyncNodePlugin (#263)
Browse files Browse the repository at this point in the history
* everything minus language, internal plugins, async

* this works

* lint

* update yarn version according to readme

* revert yarn version

* remove resolutions

* fix flow test

* fix android test

* temporarily disable applitools

* try again after updating api key

* not use latest version of bundler because it requires newer ruby version

* update iOS tests to transition inside afterTransition (#268)

update tests to transition inside afterTransition

Co-authored-by: zwu01 <nancy_wu1@intuit.com>

* remove comment block

* lint

* modify long text test

* lint

---------

Co-authored-by: brocollie08 <sentony03@gmail.com>
Co-authored-by: nancywu1 <66387473+nancywu1@users.noreply.github.com>
Co-authored-by: zwu01 <nancy_wu1@intuit.com>
  • Loading branch information
4 people authored Jan 25, 2024
1 parent 1500ba3 commit 7c26e7b
Show file tree
Hide file tree
Showing 26 changed files with 777 additions and 123 deletions.
2 changes: 1 addition & 1 deletion android/demo/scripts/androidtest.sh
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ adb shell settings put global animator_duration_scale 0
# see https://code.google.com/p/android/issues/detail?id=3254

adb logcat -c &&
python - <<END
python2 - <<END
import os
import re
import subprocess as sp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@ import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.intuit.player.android.reference.demo.test.base.AssetUITest
import com.intuit.player.android.reference.demo.test.base.waitForViewInRoot
import org.junit.Test

class PlayerFragmentScrollingTest : AssetUITest("misc") {

@Test
fun shouldScrollToTopOnTransition() {
launchMock("long-multi-view")
waitForViewInRoot(withText("It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way—in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.\n\nThere were a king with a large jaw and a queen with a plain face, on the throne of England; there were a king with a large jaw and a queen with a fair face, on the throne of France. In both countries it was clearer than crystal to the lords of the State preserves of loaves and fishes, that things in general were settled for ever.\n\nIt was the year of Our Lord one thousand seven hundred and seventy-five. Spiritual revelations were conceded to England at that favoured period, as at this. Mrs. Southcott had recently attained her five-and-twentieth blessed birthday, of whom a prophetic private in the Life Guards had heralded the sublime appearance by announcing that arrangements were made for the swallowing up of London and Westminster. Even the Cock-lane ghost had been laid only a round dozen of years, after rapping out its messages, as the spirits of this very year last past (supernaturally deficient in originality) rapped out theirs. Mere messages in the earthly order of events had lately come to the English Crown and People, from a congress of British subjects in America: which, strange to relate, have proved more important to the human race than any communications yet received through any of the chickens of the Cock-lane brood.\n\nFrance, less favoured on the whole as to matters spiritual than her sister of the shield and trident, rolled with exceeding smoothness down hill, making paper money and spending it. Under the guidance of her Christian pastors, she entertained herself, besides, with such humane achievements as sentencing a youth to have his hands cut off, his tongue torn out with pincers, and his body burned alive, because he had not kneeled down in the rain to do honour to a dirty procession of monks which passed within his view, at a distance of some fifty or sixty yards. It is likely enough that, rooted in the woods of France and Norway, there were growing trees, when that sufferer was put to death, already marked by the Woodman, Fate, to come down and be sawn into boards, to make a certain movable framework with a sack and a knife in it, terrible in history. It is likely enough that in the rough outhouses of some tillers of the heavy lands adjacent to Paris, there were sheltered from the weather that very day, rude carts, bespattered with rustic mire, snuffed about by pigs, and roosted in by poultry, which the Farmer, Death, had already set apart to be his tumbrils of the Revolution. But that Woodman and that Farmer, though they work unceasingly, work silently, and no one heard them as they went about with muffled tread: the rather, forasmuch as to entertain any suspicion that they were awake, was to be atheistical and traitorous.\n\nIn England, there was scarcely an amount of order and protection to justify much national boasting. Daring burglaries by armed men, and highway robberies, took place in the capital itself every night; families were publicly cautioned not to go out of town without removing their furniture to upholsterers’ warehouses for security; the highwayman in the dark was a City tradesman in the light, and, being recognised and challenged by his fellow-tradesman whom he stopped in his character of “the Captain,” gallantly shot him through the head and rode away; the mail was waylaid by seven robbers, and the guard shot three dead, and then got shot dead himself by the other four, “in consequence of the failure of his ammunition:” after which the mail was robbed in peace; that magnificent potentate, the Lord Mayor of London, was made to stand and deliver on Turnham Green, by one highwayman, who despoiled the illustrious creature in sight of all his retinue; prisoners in London gaols fought battles with their turnkeys, and the majesty of the law fired blunderbusses in among them, loaded with rounds of shot and ball; thieves snipped off diamond crosses from the necks of noble lords at Court drawing-rooms; musketeers went into St. Giles’s, to search for contraband goods, and the mob fired on the musketeers, and the musketeers fired on the mob, and nobody thought any of these occurrences much out of the common way. In the midst of them, the hangman, ever busy and ever worse than useless, was in constant requisition; now, stringing up long rows of miscellaneous criminals; now, hanging a housebreaker on Saturday who had been taken on Tuesday; now, burning people in the hand at Newgate by the dozen, and now burning pamphlets at the door of Westminster Hall; to-day, taking the life of an atrocious murderer, and to-morrow of a wretched pilferer who had robbed a farmer’s boy of sixpence.\n\nAll these things, and a thousand like them, came to pass in and close upon the dear old year one thousand seven hundred and seventy-five. Environed by them, while the Woodman and the Farmer worked unheeded, those two of the large jaws, and those other two of the plain and the fair faces, trod with stir enough, and carried their divine rights with a high hand. Thus did the year one thousand seven hundred and seventy-five conduct their Greatnesses, and myriads of small creatures—the creatures of this chronicle among the rest—along the roads that lay before them."))
.check(matches(isDisplayed()))
onView(withText("Go to view 2")).perform(scrollTo(), click())
onView(withText("Can you see me?")).check(matches(isDisplayed()))
waitForViewInRoot(withText("Can you see me?"))
.check(matches(isDisplayed()))
}
}
49 changes: 49 additions & 0 deletions core/player/src/controllers/flow/__tests__/flow.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { waitFor } from '@testing-library/react';
import { FlowInstance } from '..';

test('starts the right state', () => {
Expand Down Expand Up @@ -146,6 +147,54 @@ test('Fails to transition when not started', () => {
expect(() => flow.transition('foo')).toThrowError();
});

test('Fails to transition during another transition', async () => {
const flow = new FlowInstance('flow', {
startState: 'View1',
View1: {
state_type: 'VIEW',
onStart: 'foo bar',
ref: 'foo',
transitions: {
Next: 'View2',
},
},
View2: {
state_type: 'VIEW',
ref: 'bar',
transitions: {
Next: 'View3',
},
},
});

let deferredVar: string;

const transition = () => {
try {
flow.transition('Next');
return 'foo';
} catch (error: unknown) {
return 'bar';
}
};

flow.hooks.resolveTransitionNode.intercept({
call: (nextState) => {
if (nextState?.onStart) {
deferredVar = transition();
}
},
});

flow.start();

await waitFor(() => {
expect(deferredVar).toBeDefined();
});

expect(deferredVar!).toBe('bar');
});

describe('promise api', () => {
it('resolves when were done', async () => {
const flow = new FlowInstance('flow', {
Expand Down
10 changes: 10 additions & 0 deletions core/player/src/controllers/flow/flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export class FlowInstance {
private flow: NavigationFlow;
private log?: Logger;
private history: string[];
private isTransitioning = false;
private flowPromise?: DeferredPromise<NavigationFlowEndState>;
public readonly id: string;
public currentState?: NamedState;
Expand Down Expand Up @@ -115,6 +116,12 @@ export class FlowInstance {
}

public transition(transitionValue: string, options?: TransitionOptions) {
if (this.isTransitioning) {
throw new Error(
`Transitioning while ongoing transition from ${this.currentState?.name} is in progress is not supported`
);
}

if (this.currentState?.value.state_type === 'END') {
this.log?.warn(
`Skipping transition using ${transitionValue}. Already at and END state`
Expand Down Expand Up @@ -186,6 +193,7 @@ export class FlowInstance {

const prevState = this.currentState;

this.isTransitioning = true;
nextState = this.hooks.resolveTransitionNode.call(nextState);

const newCurrentState = {
Expand All @@ -205,6 +213,8 @@ export class FlowInstance {
...newCurrentState,
});

this.isTransitioning = false;

this.hooks.afterTransition.call(this);
}
}
40 changes: 37 additions & 3 deletions core/player/src/view/parser/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { setIn } from 'timm';
import { omit, setIn } from 'timm';
import { SyncBailHook, SyncWaterfallHook } from 'tapable-ts';
import type { Template } from '@player-ui/types';
import type { Node, AnyAssetType } from './types';
import type { AnyAssetType, Node } from './types';
import { NodeType } from './types';
import { getNodeID, hasAsync } from './utils';

export * from './types';
export * from './utils';

export const EMPTY_NODE: Node.Empty = {
type: NodeType.Empty,
Expand Down Expand Up @@ -73,6 +75,27 @@ export class Parser {
return viewNode as Node.View;
}

private parseAsync(
obj: object,
type: Node.ChildrenTypes,
options: ParseObjectOptions
): Node.Node | null {
const parsedAsync = this.parseObject(omit(obj, 'async'), type, options);
const parsedNodeId = getNodeID(parsedAsync);
if (parsedAsync !== null && parsedNodeId) {
return this.createASTNode(
{
id: parsedNodeId,
type: NodeType.Async,
value: parsedAsync,
},
obj
);
}

return null;
}

public createASTNode(node: Node.Node | null, value: any): Node.Node | null {
const tapped = this.hooks.onCreateASTNode.call(node, value);

Expand Down Expand Up @@ -123,7 +146,6 @@ export class Parser {
path: string[] = []
): NestedObj => {
if (typeof objToParse !== 'object' || objToParse === null) {
// value = objToParse;
return { value: objToParse, children: [] };
}

Expand Down Expand Up @@ -253,6 +275,18 @@ export class Parser {
],
};
}
} else if (localValue && hasAsync(localValue)) {
const localAsync = this.parseAsync(
localValue,
NodeType.Value,
options
);
if (localAsync) {
children.push({
path: [...path, localKey],
value: localAsync,
});
}
} else if (localValue && Array.isArray(localValue)) {
const childValues = localValue
.map((childVal) =>
Expand Down
9 changes: 9 additions & 0 deletions core/player/src/view/parser/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export enum NodeType {
Value = 'value',
MultiNode = 'multi-node',
Switch = 'switch',
Async = 'async',
Unknown = 'unknown',
Empty = 'empty',
}
Expand Down Expand Up @@ -110,6 +111,13 @@ export declare namespace Node {
value: Value;
}

export interface Async extends Base<NodeType.Async> {
/** The unique id of the node */
id: string;
/** The value representing the node */
value: Node;
}

export interface PluginOptions {
/** A list of plugins */
plugins?: {
Expand All @@ -136,6 +144,7 @@ export declare namespace Node {
| View
| MultiNode
| Switch
| Async
| Unknown
| Empty;
}
21 changes: 21 additions & 0 deletions core/player/src/view/parser/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { Node } from './types';

/** Check to see if the object contains async */
export function hasAsync(obj: object): boolean {
return Object.prototype.hasOwnProperty.call(obj, 'async');
}

/** Get the ID of the Node if there is one */
export function getNodeID(node?: Node.Node | null): string | undefined {
if (!node) {
return;
}

if (
'value' in node &&
typeof node.value === 'object' &&
typeof node.value?.id === 'string'
) {
return node.value.id;
}
}
8 changes: 7 additions & 1 deletion core/player/src/view/plugins/switch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,13 @@ export default class SwitchPlugin implements ViewPlugin {
const cases: Node.SwitchCase[] = [];

switchContent.forEach(
(switchCase: { [x: string]: any; case: any }) => {
(switchCase: {
[x: string]: any;
/**
*
*/
case: any;
}) => {
const { case: switchCaseExpr, ...switchBody } = switchCase;
const value = parser.parseObject(
switchBody,
Expand Down
Loading

0 comments on commit 7c26e7b

Please sign in to comment.