react-intl#IntlProvider TypeScript Examples

The following examples show how to use react-intl#IntlProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: component.test.tsx    From synapse-extension with MIT License 6 votes vote down vote up
describe('token list', () => {
  const history = useHistory();
  beforeEach(() => {
    render(
      <IntlProvider locale="en" messages={en}>
        <Router>
          <Component udtsCapacity={udtsCapacity} udtsMeta={udtsMeta} explorerUrl={explorerUrl} />
        </Router>
      </IntlProvider>,
    );
  });
  it('should have correct amount of Love Lina Token', () => {
    const elems = screen.getAllByLabelText('Token List');
    expect(elems).toHaveLength(5);
  });

  it('should able to go to send tx page', () => {
    const sendBtns = screen.getAllByText('Send');
    expect(sendBtns).toHaveLength(4);
    userEvent.click(sendBtns[0]);
    expect(history.push).toBeCalled();
  });
});
Example #2
Source File: index.test.tsx    From pipeline-editor with Apache License 2.0 6 votes vote down vote up
it("calls onChange when a field changes", async () => {
  const handleChange = jest.fn();
  render(
    <IntlProvider locale="en">
      <NodeProperties
        nodes={[nodes]}
        selectedNodes={[selectedNode]}
        onChange={handleChange}
      />
    </IntlProvider>
  );
  // UPDATE_PROPERTY is triggered on mount sometimes?
  const initialCalls = handleChange.mock.calls.length;
  userEvent.click(screen.getByRole("checkbox"));
  expect(handleChange).toHaveBeenCalledTimes(initialCalls + 1);
});
Example #3
Source File: index.tsx    From yana with MIT License 6 votes vote down vote up
// TODO closing a open tab removes its file contents, because the editor isnt mounted anymore and the content getter returns {}, which overwrites the previous content
ReactDOM.render(
  <IntlProvider locale="en">
    <AppDataProvider>
      <TelemetryProvider>
        <AppNotifications />
        <ThemeProvider>
          <DevToolsContextProvider>
            <DataInterfaceProvider>
              <MainContentContextProvider>
                <SpotlightContainer>
                  <OverlaySearchProvider>
                    <LayoutContainer />
                    <Alerter.Instance.Container />
                    <DropZoneContainer />
                  </OverlaySearchProvider>
                </SpotlightContainer>
              </MainContentContextProvider>
            </DataInterfaceProvider>
          </DevToolsContextProvider>
        </ThemeProvider>
      </TelemetryProvider>
    </AppDataProvider>
  </IntlProvider>,
  document.getElementById('root')
);
Example #4
Source File: IntlProviderWrapper.tsx    From mo360-ftk with MIT License 6 votes vote down vote up
public render() {
    const I18nProvider = withInject(injectIntl(Provider));
    return (
      <IntlProvider locale={this.state.defaultLocale} defaultLocale={this.state.defaultLocale}>
        <I18nProvider setLang={this.setLang} lang={this.state.defaultLocale}>
          {this.props.children}
        </I18nProvider>
      </IntlProvider>
    );
  }
Example #5
Source File: testUtils.tsx    From antibody-web with MIT License 6 votes vote down vote up
renderWithStubAppContext = (component, api = {}): [RenderResult, AppContextType] => {
  const testApi = {
    generateTest: jest.fn((): any => ({ testRecord: { timerStartedAt: 10 } })),
    uploadImage: jest.fn((): any => { }),
    interpretResult: jest.fn((): any => Promise.resolve()),
    updateTest: jest.fn(),
    ...api
  };



  const appContext: AppContextType = {
    state: { locale: "en-gb" },
    setLocale: () => { },
    setAppError: () => { },
    dispatch: () => { },
    container: {
      getLogin: () => (): any => { },
      getTestApi: jest.fn(() => testApi)
    }
  };

  return [render(
    <AppContext.Provider value={appContext} >
      <IntlProvider
        locale="en-gb"
        messages={flatten(messages["en-gb"])}>
        {component}
      </IntlProvider>
    </AppContext.Provider >
  ), appContext];
}
Example #6
Source File: index.test.tsx    From synapse-extension with MIT License 6 votes vote down vote up
describe('address list component', () => {
  beforeEach(async () => {
    const onSelectAddress = jest.fn();
    await act(async () => {
      await browser.storage.local.set({
        currentNetwork: fixtures.currentNetwork,
      });
      render(
        <IntlProvider locale="en" messages={en}>
          <Router>
            <App onSelectAddress={onSelectAddress} AddressListItem={AddressListItem} />
          </Router>
        </IntlProvider>,
      );
    });
  });

  it('should render address list', async () => {
    await waitFor(() => {
      browser.runtime.sendMessage({
        type: MESSAGE_TYPE.ADDRESS_LIST,
        data: fixtures.addressesList,
      });
    });
    const items = screen.getAllByRole('navigation', { name: 'Address List' });
    expect(items).toHaveLength(4);
  });
});
Example #7
Source File: App.tsx    From covid_dashboard with MIT License 6 votes vote down vote up
public render() {
    const {env} = this.state;
    return (
      <IntlProvider locale={env.lang} messages={this.getMessage()}>
        <Router>
          <div className="App">
            <Route exact path='/' >{this.drawMain()}</Route>
            <Route exact path='/public' >{this.drawMain()}</Route>
            <Route exact path='/contributors' ><Contributors lang={env.lang} onSwitchLang={this.handleSwitchLocale} /></Route>
            <Route exact path='/algorithm' ><AlgorithmPage lang={env.lang} onSwitchLang={this.handleSwitchLocale} /></Route>
          </div>
        </Router>
      </IntlProvider>
    );
  }
Example #8
Source File: index.test.tsx    From synapse-extension with MIT License 6 votes vote down vote up
describe('AppBar component', () => {
  let tree;
  let container;
  let getByTestId;

  beforeEach(() => {
    tree = render(
      <IntlProvider locale="en" messages={en}>
        <App handleNetworkChange={null} />
      </IntlProvider>,
    );
    container = tree.container;
    getByTestId = tree.getByTestId;
  });

  it('should render logo', () => {
    const elem = container.querySelector('img');
    expect(container).toContainElement(elem);
  });

  it('should render setting icon on left side', () => {
    const elem = getByTestId('setting-icon');
    expect(elem).not.toBeNull();
  });
});
Example #9
Source File: _app.tsx    From typescript-fun with MIT License 6 votes vote down vote up
render() {
    const { Component, pageProps } = this.props;
    return (
      <ThemeProvider>
        <IntlProvider locale={'en'}>
          <CSSReset />
          <Component {...pageProps} />
        </IntlProvider>
      </ThemeProvider>
    );
  }
Example #10
Source File: index.test.tsx    From pipeline-editor with Apache License 2.0 6 votes vote down vote up
it("calls onFileRequested when a browse button is pressed", async () => {
  const handleFileRequested = jest.fn().mockResolvedValue([]);
  render(
    <IntlProvider locale="en">
      <NodeProperties
        nodes={[nodes]}
        selectedNodes={[selectedNode]}
        onFileRequested={handleFileRequested}
      />
    </IntlProvider>
  );
  userEvent.click(screen.getByText(/browse/i));
  expect(handleFileRequested).toHaveBeenCalledTimes(1);
  expect(handleFileRequested).toHaveBeenCalledWith({
    canSelectMany: false,
    defaultUri: "example.ipynb",
    filters: { File: undefined },
    filename: "example.ipynb",
    propertyID: "elyra_filename",
  });
});
Example #11
Source File: index.tsx    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <QueryClientProvider client={queryClient}>
        <IntlProvider locale={navigator.language}>
          <HelmetProvider>
            <SnackbarProvider maxSnack={3} dense hideIconVariant>
              <MediaQueryProvider>
                <Router>
                  <ScrollToTop />
                  <App />
                </Router>
              </MediaQueryProvider>
            </SnackbarProvider>
          </HelmetProvider>
        </IntlProvider>
      </QueryClientProvider>
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root")
);
Example #12
Source File: App.test.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
it("renders without crashing", () => {
  const div = document.createElement("div");
  ReactDOM.render(
    <JmixAppProvider
      jmixREST={jmixREST}
      apolloClient={apolloClient}
      metadata={metadata}
      Modals={Modals}
    >
      <IntlProvider locale="en">
        <App />
      </IntlProvider>
    </JmixAppProvider>,
    div
  );
  ReactDOM.unmountComponentAtNode(div);
});
Example #13
Source File: LocaleContextController.tsx    From react-starter-boilerplate with MIT License 6 votes vote down vote up
LocaleContextController = ({ children }: LocaleContextControllerProps) => {
  const [locale, setLocale] = useState<AppLocale>(defaultLocale);

  return (
    <IntlProvider defaultLocale={defaultLocale} locale={locale} messages={translations[locale]}>
      <LocaleContext.Provider value={{ defaultLocale, locale, setLocale }}>{children}</LocaleContext.Provider>
    </IntlProvider>
  );
}
Example #14
Source File: I18nProvider.tsx    From amazon-chime-live-events with Apache License 2.0 6 votes vote down vote up
export default function I18nProvider(props: Props) {
  const { children } = props;
  return (
    <IntlProvider
      locale={
        (navigator.languages && navigator.languages[0]) || navigator.language
      }
      defaultLocale={DEFAULT_LOCALE}
      messages={messages[DEFAULT_LOCALE]}
    >
      {children}
    </IntlProvider>
  );
}
Example #15
Source File: I18nProvider.tsx    From amazon-chime-sdk-classroom-demo with Apache License 2.0 6 votes vote down vote up
export default function I18nProvider(props: Props) {
  const { children } = props;
  return (
    <IntlProvider
      locale={
        (navigator.languages && navigator.languages[0]) || navigator.language
      }
      defaultLocale={DEFAULT_LOCALE}
      messages={messages[DEFAULT_LOCALE]}
    >
      {children}
    </IntlProvider>
  );
}
Example #16
Source File: locale-context.tsx    From malagu with MIT License 6 votes vote down vote up
export function LocaleContext({ children }: React.PropsWithChildren<any>) {
    const localeManager = ContainerUtil.get<LocaleManager>(LocaleManager);
    const [locale, setLocale] = React.useState(localeManager.currentSubject.value);
    React.useEffect(() => {
        const subscription = localeManager.currentSubject.subscribe(l => setLocale(l));
        return () => subscription.unsubscribe();
    }, []);

    return (
        <IntlProvider locale={locale?.lang || navigator.language} messages={locale?.messages} onError={err => {
            const logger = ContainerUtil.get<Logger>(Logger);
            if (err.code !== 'MISSING_TRANSLATION') {
                logger.warn(err);
            }
        }}>
            {children}
        </IntlProvider>);
}
Example #17
Source File: LocalizationProvider.tsx    From ever-wallet-browser-extension with GNU General Public License v3.0 6 votes vote down vote up
export function LocalizationProvider({ children }: Props): JSX.Element {
    const rpcState = useRpcState()

    const locale = rpcState.state.selectedLocale || rpcState.state.defaultLocale

    const messages = React.useMemo(
        () => (({ en, ko } as { [key: string]: LocalizationKeys })[locale]),
        [locale]
    )

    return (
        <IntlProvider
            key="intl"
            locale={locale}
            defaultLocale={rpcState.state.defaultLocale}
            messages={messages}
            onError={noop}
        >
            {children}
        </IntlProvider>
    )
}
Example #18
Source File: index.test.tsx    From pipeline-editor with Apache License 2.0 6 votes vote down vote up
it("renders common properties with one node selected", () => {
  render(
    <IntlProvider locale="en">
      <NodeProperties nodes={[nodes]} selectedNodes={[selectedNode]} />
    </IntlProvider>
  );
  expect(screen.getByText(/notebook label/i)).toBeInTheDocument();
  expect(screen.getByLabelText(/properties/i)).toBeInTheDocument();
});
Example #19
Source File: index.test.tsx    From synapse-extension with MIT License 5 votes vote down vote up
describe('sign/auth page', () => {
  const RawTxDetail = () => <div>RawTxDetail</div>;
  const message = {
    type: MESSAGE_TYPE.EXTERNAL_SIGN,
    data: { tx: { version: '0x0' } },
  };
  beforeEach(() => {
    render(
      <IntlProvider locale="en" messages={en}>
        <Router>
          <App RawTxDetail={RawTxDetail} message={message} />
        </Router>
      </IntlProvider>,
    );
  });

  it('should render form fields: submitbutton', async () => {
    const submitButton = screen.getByRole('button', { name: /confirm/i });
    expect(submitButton).toBeInTheDocument();
  });

  it('should change form fields: password', async () => {
    const password = screen.getByLabelText('Password');

    expect(password).toBeInTheDocument();
    expect(password).toBeEmpty();

    await userEvent.type(password, 'test password');

    expect(screen.getByRole('form')).toHaveFormValues({
      password: 'test password',
    });
  });

  it('should submit', async () => {
    const password = screen.getByLabelText('Password');
    await userEvent.type(password, 'password_1');
    expect(screen.getByRole('form')).toHaveFormValues({
      password: 'password_1',
    });
    const confirmBtn = screen.getByText('Confirm');
    expect(confirmBtn).toBeInTheDocument();
    userEvent.click(confirmBtn);
    await waitFor(() => {
      expect(browser.runtime.sendMessage).toBeCalled();
    });
  });
});
Example #20
Source File: App.tsx    From antibody-web with MIT License 5 votes vote down vote up
App = () => {
  const [appState, dispatch] = useReducer(
    appReducer,
    initialState
  );

  const setAppError = useCallback((error: AppError | null) => {
    dispatch({
      type: "SET_ERROR",
      error
    });
  }, [dispatch]);

  const setLocale = useCallback((locale: string) => {
    dispatch({
      type: "SET_LOCALE",
      locale,
    });
  }, []);

  const container = new AppContainer();

  return (
    <AppContext.Provider
      value={{ state: appState, setLocale, setAppError, dispatch, container }}
    >
      <IntlProvider
        locale={appState.locale}
        messages={flatten(messages[appState.locale])}
      >
        <HelmetProvider>
          <ErrorBoundary>
            <Router>
              <Layout error={appState.error}>
                <Switch>
                  <Route
                    path="/"
                    exact
                    component={Home} />
                  <LoginProvider>
                    <TestRoutes />
                  </LoginProvider>
                </Switch>
              </Layout>
            </Router>
          </ErrorBoundary>
        </HelmetProvider>
      </IntlProvider>
    </AppContext.Provider>
  );
}
Example #21
Source File: HorizontalMenu.test.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
describe('HorizontalMenu', () => {
  const horizontalMenuJsx: JSX.Element = (
    <IntlProvider locale="en">
      <HorizontalMenu>
        <MenuItem
          caption={"item title"}
        >
          <span> first item title</span>
          <span> first item content</span>
        </MenuItem>
        <MenuItem
          screenId={"secondScreen"}
          caption={"item title"}
        >
          <span> Second item title</span>
          <span> Second item content</span>
        </MenuItem>
        <SubMenuItem
          caption={"test"}
        >
          <MenuItem
            caption={"item title"}
            screenId={"thirdScreen"}
          >
            <span> Third item title</span>
            <span> Third item content</span>
          </MenuItem>
          <MenuItem
            screenId={"fourthScreen"}
            caption={"item title"}
          >
            <span> Fourth item title</span>
            <span> Fourth item content</span>
          </MenuItem>
        </SubMenuItem>
      </HorizontalMenu>
    </IntlProvider>
  )

  let horizontalMenuTestRenderer: ReactTestRenderer;

  describe('HorizontalMenu renders without crashing', () => {
    it('HorizontalMenu render and mount', () => {
      TestRenderer.act(() => {
        horizontalMenuTestRenderer = TestRenderer.create(horizontalMenuJsx)
      })
    })

    it('HorizontalMenu unmount', () => {
      TestRenderer.act(() => {
        horizontalMenuTestRenderer.unmount();
      })
    })
  })
})
Example #22
Source File: edit.test.tsx    From synapse-extension with MIT License 5 votes vote down vote up
describe('Edit UDT', () => {
  const match = {
    params: {
      typeHash: '0x123',
    },
  };
  beforeEach(async () => {
    await browser.storage.local.set({
      udts: [
        {
          decimal: '8',
          name: 'simpleUDT',
          typeHash: '0x123',
          symbol: 'UDT',
        },
      ],
    });
    await act(async () => {
      render(
        <IntlProvider locale="en" messages={en}>
          <Router>
            <App match={match} />
          </Router>
        </IntlProvider>,
      );
    });
  });

  it('should render form fields: submitbutton', async () => {
    const submitButton = screen.getByRole('button', { name: /Confirm/i });
    expect(submitButton).toBeInTheDocument();
  });

  it('should create new udt', async () => {
    expect(screen.getByRole('form')).toHaveFormValues({
      decimal: '8',
      name: 'simpleUDT',
      typeHash: '0x123',
      symbol: 'UDT',
    });

    const name = screen.getByLabelText('UDT Name');
    await userEvent.type(name, '123');

    const typeHash = screen.getByLabelText('UDT Hash');
    await userEvent.type(typeHash, '123');

    const symbol = screen.getByLabelText('Symbol');
    await userEvent.type(symbol, '123');

    const decimal = screen.getByLabelText('Decimal');
    await userEvent.type(decimal, '123');

    expect(screen.getByRole('form')).toHaveFormValues({
      decimal: '8123',
      name: 'simpleUDT123',
      typeHash: '0x123123',
      symbol: 'UDT123',
    });

    const submitBtn = screen.getByRole('button', { name: /Confirm/i });
    userEvent.click(submitBtn);
    await waitFor(() => {
      expect(browser.storage.local.set).toBeCalled();
    });
  });
});
Example #23
Source File: intl.tsx    From project-loved-web with MIT License 5 votes vote down vote up
export function IntlProviderWrapper({ children }: PropsWithChildren<{}>) {
  const [locale, setLocale] = useState(() => {
    const storageLocale = localStorage.getItem('locale');

    if (storageLocale) {
      return storageLocale;
    }

    const navigatorLanguages = navigator.languages ?? [navigator.language || 'en'];

    for (let navigatorLanguage of navigatorLanguages) {
      navigatorLanguage = navigatorLanguage.toLowerCase();

      // Not technically correct but should be fine for the few locales targeted here.
      // <https://datatracker.ietf.org/doc/html/rfc5646#section-2.1>
      const [language, region] = navigatorLanguage.split('-');
      const languageAndRegion = region ? `${language}-${region}` : language;

      if (locales.some((locale) => locale.code === languageAndRegion)) {
        return languageAndRegion;
      }

      if (locales.some((locale) => locale.code === language)) {
        return language;
      }
    }

    return 'en';
  });
  const contextValue: IntlContextValue = useMemo(
    () => [
      locale,
      (newLocale) => {
        localStorage.setItem('locale', newLocale);
        setLocale(newLocale);
      },
    ],
    [locale],
  );
  const messages = useMemo(() => loadMessages(locale), [locale]);

  return (
    <intlContext.Provider value={contextValue}>
      <IntlProvider defaultLocale='en' locale={locale} messages={messages}>
        {children}
      </IntlProvider>
    </intlContext.Provider>
  );
}
Example #24
Source File: testUtils.tsx    From antibody-web with MIT License 5 votes vote down vote up
renderWithReactIntl = component => {
  return render(<IntlProvider
    locale="en-gb"
    messages={flatten(messages["en-gb"])}>
    {component}
  </IntlProvider>);
}
Example #25
Source File: LocalesStore.test.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
I18nParamsComponent: React.FC<I18nParamsComponentProps> = ({ locale, messages, id, values }) => {
  return (
    <IntlProvider locale={locale} messages={messages}>
      <I18nParamsChildComponent id={id} values={values}/>
    </IntlProvider>
  )
}
Example #26
Source File: index.test.tsx    From synapse-extension with MIT License 4 votes vote down vote up
describe('import privateKey page', () => {
  beforeEach(() => {
    render(
      <IntlProvider locale="en" messages={en}>
        <Router>
          <App />
        </Router>
      </IntlProvider>,
    );
  });

  it('send message err', async () => {
    await waitFor(() => {
      browser.runtime.sendMessage({
        message: 'Private Key',
        type: MESSAGE_TYPE.IMPORT_KEYSTORE_ERR,
      });
      expect(browser.runtime.sendMessage).toBeCalled();
    });
  });

  it('send message ok', async () => {
    browser.runtime.sendMessage({
      message: 'Private Key',
      type: MESSAGE_TYPE.IMPORT_PRIVATE_KEY_OK,
    });
    await waitFor(() => {
      expect(browser.runtime.sendMessage).toBeCalled();
    });
  });

  it('should change radio form fields: private key', async () => {
    const radio = screen.getByRole('radio', { name: 'Private Key' });
    expect(radio).toBeInTheDocument();

    fireEvent.change(radio, { target: { value: '1', checked: true } });
    expect(radio).toBeChecked();
  });

  it('should change radio form fields: keystore', async () => {
    const radio = screen.getByRole('radio', { name: 'Keystore' });
    expect(radio).toBeInTheDocument();

    fireEvent.change(radio, { target: { value: '1', checked: true } });
    expect(radio).toBeChecked();
  });

  it('should change radio form fields: private key', async () => {
    const radio = screen.getByRole('radio', { name: 'Private Key' });
    expect(radio).toBeInTheDocument();

    fireEvent.change(radio, { target: { value: '1', checked: true } });
    expect(radio).toBeChecked();

    const radioKeystore = screen.getByRole('radio', { name: 'Keystore' });
    expect(radioKeystore).toBeInTheDocument();

    fireEvent.change(radioKeystore, { target: { value: '1', checked: true } });
    expect(radioKeystore).toBeChecked();
  });

  it('should be able to submit', async () => {
    const privateKey = screen.getByPlaceholderText('Private Key');
    const password = screen.getByLabelText('Password');
    //   const privateKey = container.querySelector('[name="privateKey"]');
    //   const password = container.querySelector('[name="password"]');

    await userEvent.type(privateKey, 'aaa');
    await userEvent.type(password, 'password_1');
    expect(screen.getByRole('form')).toHaveFormValues({
      privateKey: 'aaa',
      password: 'password_1',
    });

    const submitButton = screen.getByRole('button', { name: 'Import' });
    expect(submitButton).toBeInTheDocument();

    userEvent.click(submitButton);
    await waitFor(() => {
      expect(browser.runtime.sendMessage).toBeCalled();
    });
  });

  it('submit import private key', async () => {
    const submitBtns = screen.getAllByText('Import');
    expect(submitBtns).toHaveLength(2);
  });
});
Example #27
Source File: SubMenuItem.test.tsx    From jmix-frontend with Apache License 2.0 4 votes vote down vote up
describe('MenuItem', () => {

  const subMenuItemJsx: JSX.Element = (
    <SubMenuItem
      caption={"test"}
    >
      <span> item title</span>
      <span> item content</span>
    </SubMenuItem>
  )

  const subMenuItemWithEmptyChildrenJsx: JSX.Element = (
    <SubMenuItem
      caption={"test"}
    >
    </SubMenuItem>
  )

  const subMenuItemWithMenuItemsJsx: JSX.Element = (
    <SubMenuItem
      caption={"test"}
    >
      <MenuItem
        caption={"item title"}
      >
        first tested menu item
        </MenuItem>
      <MenuItem
        caption={"item title"}
      >
        second tested menu item
        </MenuItem>
    </SubMenuItem>
  )

  const subMenuItemWithSubMenuItemsJsx: JSX.Element = (
    <SubMenuItem
      caption={"test1"}
    >
      <SubMenuItem
        caption={"test2"}
      >
        <SubMenuItem
          caption={"test3"}
        >
          <MenuItem
            caption={"item title"}
          >
            first tested menu item
          </MenuItem>
          <MenuItem
            caption={"item title"}
          >
            second tested menu item
          </MenuItem>
        </SubMenuItem>
      </SubMenuItem>
    </SubMenuItem>
  )

  let menuItemTestRenderer: ReactTestRenderer;
  describe("SubMenuItem wrapped into VerticalMenu", () => {
    describe('SubMenuItem with empty children renders without crashing', () => {
      it('SubMenuItem with empty children render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <VerticalMenu>
                {subMenuItemWithEmptyChildrenJsx}
              </VerticalMenu>
            </IntlProvider>
          )
        })
      })

      it('SubMenuItem with empty children unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })

    describe('SubMenuItem with content renders without crashing', () => {
      it('SubMenuItem with content render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <VerticalMenu>
                {subMenuItemJsx}
              </VerticalMenu>
            </IntlProvider>
          )
        })
      })

      it('SubMenuItem with content unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })

    describe('SubMenuItem with MenuItem renders without crashing', () => {
      it('SubMenuItem with MenuItem render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <VerticalMenu>
                {subMenuItemWithMenuItemsJsx}
              </VerticalMenu>
            </IntlProvider>
          )
        })
      })
      it('SubMenuItem with MenuItem props unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })

    describe('SubMenuItem with SubMenuItem renders without crashing', () => {
      it('SubMenuItem with SubMenuItem render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <VerticalMenu>
                {subMenuItemWithSubMenuItemsJsx}
              </VerticalMenu>
            </IntlProvider>
          )
        })
      })
      it('SubMenuItem with MenuItem  props unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })
  })

  describe("SubMenuItem wrapped into HorizontalMenu", () => {
    describe('SubMenuItem with empty children renders without crashing', () => {
      it('SubMenuItem with empty children render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <HorizontalMenu>
                {subMenuItemWithEmptyChildrenJsx}
              </HorizontalMenu>
            </IntlProvider>
          )
        })
      })

      it('SubMenuItem with empty children unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })

    describe('SubMenuItem with content renders without crashing', () => {
      it('SubMenuItem with content render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <HorizontalMenu>
                {subMenuItemJsx}
              </HorizontalMenu>
            </IntlProvider>
          )
        })
      })

      it('SubMenuItem with content unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })

    describe('SubMenuItem with MenuItem renders without crashing', () => {
      it('SubMenuItem with MenuItem render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <HorizontalMenu>
                {subMenuItemWithMenuItemsJsx}
              </HorizontalMenu>
            </IntlProvider>
          )
        })
      })
      it('SubMenuItem with MenuItem props unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })

    describe('SubMenuItem with SubMenuItem renders without crashing', () => {
      it('SubMenuItem with SubMenuItem render and mount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer = TestRenderer.create(
            <IntlProvider locale="en">
              <HorizontalMenu>
                {subMenuItemWithSubMenuItemsJsx}
              </HorizontalMenu>
            </IntlProvider>
          )
        })
      })
      it('SubMenuItem with MenuItem  props unmount', () => {
        TestRenderer.act(() => {
          menuItemTestRenderer.unmount();
        })
      })
    })
  })
})
Example #28
Source File: index.test.tsx    From synapse-extension with MIT License 4 votes vote down vote up
describe('setting page', () => {
  const history = useHistory();

  beforeEach(async () => {
    localStorage.setItem('IS_LOGIN', 'YES');
    await act(async () => {
      render(
        <IntlProvider locale="en" messages={en}>
          <Router>
            <App />
          </Router>
        </IntlProvider>,
      );
    });
  });

  it('should render item: Export Mnemonic', async () => {
    const element = screen.getByText('Export Mnemonic');

    expect(element).toBeInTheDocument();
  });

  it('should render item: Export Private Key', async () => {
    const element = screen.getByText('Export Private Key / Keystore');

    expect(element).toBeInTheDocument();
  });

  it('should render item: Import Private Key', async () => {
    const element = screen.getByText('Import Private Key / Keystore');

    expect(element).toBeInTheDocument();
  });

  it('should render item: Manage Contacts', async () => {
    const element = screen.getByText('Manage Contacts');

    expect(element).toBeInTheDocument();
  });

  it('should render item: Manage UDTs', async () => {
    const element = screen.getByText('Manage UDTs');

    expect(element).toBeInTheDocument();
  });

  it('should render item: Manage Networks', async () => {
    const element = screen.getByText('Manage Networks');

    expect(element).toBeInTheDocument();
  });

  it('should render item: English', async () => {
    const element = screen.getByText('English');

    expect(element).toBeInTheDocument();
  });

  it('should render delete wallet form and submit', async () => {
    const deletBtn = screen.getByText(/delete wallet/i);
    expect(deletBtn).toBeInTheDocument();
    userEvent.click(deletBtn);

    const password = await screen.findByLabelText('Password');
    await userEvent.type(password, 'password_1');
    expect(screen.getByRole('form')).toHaveFormValues({
      password: 'password_1',
    });

    const confirmBtn = screen.getByText('Confirm');
    expect(confirmBtn).toBeInTheDocument();
    userEvent.click(confirmBtn);

    await waitFor(() => {
      expect(browser.runtime.sendMessage).toBeCalled();
    });

    // browser.runtime.sendMessage({
    //   type: MESSAGE_TYPE.DELETE_WALLET_ERR,
    // });
    // const incorrectPwd = await screen.findByText('Incorrect Password');
    // expect(incorrectPwd).toBeInTheDocument();
    // await waitFor(() => {
    //   const incorrectPwd = screen.getByText('Incorrect Password');
    //   expect(incorrectPwd).toBeInTheDocument();
    // });

    // browser.runtime.sendMessage({
    //   type: MESSAGE_TYPE.DELETE_WALLET_OK,
    // });
    // expect(browser.runtime.sendMessage).toBeCalled();
    // await waitFor(() => {
    // expect(history.push).toBeCalled();
    // expect(history.push).toBeCalledWith('./mnemonic-setting');
    // });
  });
});
Example #29
Source File: index.tsx    From pipeline-editor with Apache License 2.0 4 votes vote down vote up
PipelineEditor = forwardRef(
  (
    {
      pipeline,
      palette,
      pipelineProperties,
      toolbar,
      onAction,
      onChange,
      onDoubleClickNode,
      onError,
      onFileRequested,
      onPropertiesUpdateRequested,
      readOnly,
      children,
      nativeKeyboardActions,
      leftPalette,
    }: Props,
    ref
  ) => {
    const theme = useTheme();
    const controller = useRef(new PipelineController());

    const [supernodeOpen, setSupernodeOpen] = useState(false);

    useEffect(() => {
      const store = controller.current.objectModel.store.store;

      let currentlyOpen: boolean;
      function handleChange() {
        let previouslyOpen = currentlyOpen;
        currentlyOpen = store.getState().breadcrumbs.length > 1;

        if (previouslyOpen !== currentlyOpen) {
          setSupernodeOpen(currentlyOpen);
        }
      }

      const unsubscribe = store.subscribe(handleChange);
      return () => {
        unsubscribe();
      };
    }, []);

    const [currentTab, setCurrentTab] = useState<string | undefined>();
    const [panelOpen, setPanelOpen] = useState(false);

    useCloseContextMenu(controller);

    const blockingRef = useBlockEvents({
      wheel: true,
      contextmenu: readOnly,
    });

    useEffect(() => {
      try {
        controller.current.open(pipeline);
        if (!readOnly) {
          controller.current.setPalette(palette);
          controller.current.validate({ redColor: theme.palette.error.main });
        } else {
          controller.current.resetStyles();
        }
        // don't call to persist change because it will cause an infinate loop
      } catch (e) {
        onError?.(e);
      }
    }, [palette, onError, pipeline, readOnly, theme.palette.error.main]);

    useImperativeHandle(
      ref,
      () => ({
        addFile: async (payload: any) => {
          controller.current.editActionHandler({
            editType: "createNode",
            ...payload,
          });
        },
      }),
      []
    );

    const handleContextMenu = useCallback(
      (e: ContextMenuEvent, defaultMenu: ContextMenu): ContextMenu => {
        const canPaste = isMenuItemEnabled(defaultMenu, "paste");

        const canDisconnect = isMenuItemEnabled(defaultMenu, "disconnectNode");

        const canExpand = isMenuItemEnabled(
          defaultMenu,
          "expandSuperNodeInPlace"
        );

        if (e.selectedObjectIds.length > 1) {
          return [
            {
              action: "createSuperNode",
              label: "Create Supernode",
              // NOTE: There is a bug if you try to create a supernode with only
              // a comment selected. This will disable creating supernodes when
              // the comment is right clicked on even if other nodes are
              // selected, which is allowed. Just too lazy to loop through all
              // selected items to determine if non comments are also selected.
              enable: e.type !== "comment",
            },
            {
              divider: true,
            },
            {
              action: "cut",
              label: "Cut",
            },
            {
              action: "copy",
              label: "Copy",
            },
            {
              divider: true,
            },
            {
              action: "disconnectNode",
              label: "Disconnect",
              enable: canDisconnect,
            },
            {
              action: "deleteSelectedObjects",
              label: "Delete",
            },
          ];
        }

        switch (e.type) {
          case "canvas":
            return [
              {
                action: "newFileNode",
                label: "New Node from File",
              },
              {
                action: "createComment",
                label: "New Comment",
              },
              {
                divider: true,
              },
              {
                action: "paste",
                label: "Paste",
                enable: canPaste,
              },
            ];
          case "node":
            if (e.targetObject.type === "execution_node") {
              const filenameRef = controller.current.resolveParameterRef(
                e.targetObject.op,
                "filehandler"
              );
              const parameters = e.targetObject.app_data?.component_parameters;

              return [
                {
                  action: "openFile",
                  label: filenameRef
                    ? "Open File"
                    : "Open Component Definition",
                  // NOTE: This only checks if the string is empty, but we
                  // should verify the file exists.
                  enable:
                    filenameRef === undefined ||
                    (parameters?.[filenameRef] !== undefined &&
                      parameters?.[filenameRef].trim() !== ""),
                },
                {
                  action: "properties",
                  label: "Open Properties",
                },
                {
                  divider: true,
                },
                {
                  action: "createSuperNode",
                  label: "Create Supernode",
                },
                {
                  divider: true,
                },
                {
                  action: "cut",
                  label: "Cut",
                },
                {
                  action: "copy",
                  label: "Copy",
                },
                {
                  divider: true,
                },
                {
                  action: "disconnectNode",
                  label: "Disconnect",
                  enable: canDisconnect,
                },
                {
                  action: "deleteSelectedObjects",
                  label: "Delete",
                },
              ];
            }
            if (e.targetObject.type === "super_node") {
              return [
                {
                  action: canExpand
                    ? "expandSuperNodeInPlace"
                    : "collapseSuperNodeInPlace",
                  label: canExpand ? "Expand Supernode" : "Collapse Supernode",
                },
                {
                  divider: true,
                },
                {
                  action: "createSuperNode",
                  label: "Create Supernode",
                },
                {
                  divider: true,
                },
                {
                  action: "cut",
                  label: "Cut",
                },
                {
                  action: "copy",
                  label: "Copy",
                },
                {
                  divider: true,
                },
                {
                  action: "disconnectNode",
                  label: "Disconnect",
                  enable: canDisconnect,
                },
                {
                  action: "deleteSelectedObjects",
                  label: "Delete",
                },
              ];
            }
            break;
          case "link":
            return [
              {
                action: "deleteLink",
                label: "Delete",
              },
            ];
          case "comment":
            return [
              {
                action: "createSuperNode",
                label: "Create Supernode",
                // NOTE: There is a bug if you try to create a supernode with only
                // a comment selected.
                enable: false,
              },
              {
                divider: true,
              },
              {
                action: "cut",
                label: "Cut",
              },
              {
                action: "copy",
                label: "Copy",
              },
              {
                divider: true,
              },
              {
                action: "disconnectNode",
                label: "Disconnect",
                enable: canDisconnect,
              },
              {
                action: "deleteSelectedObjects",
                label: "Delete",
              },
            ];
        }

        // anything else
        return defaultMenu;
      },
      []
    );

    const handleClickAction = useCallback(
      (e: CanvasClickEvent) => {
        if (e.clickType === "DOUBLE_CLICK" && e.objectType === "node") {
          if (onDoubleClickNode !== undefined) {
            return onDoubleClickNode(e);
          }
          controller.current.editActionHandler({ editType: "properties" });
        }
      },
      [onDoubleClickNode]
    );

    const [selectedNodeIDs, setSelectedNodeIDs] = useState<string[]>();
    const handleSelectionChange = useCallback(
      (e: CanvasSelectionEvent) => {
        setSelectedNodeIDs(e.selectedNodes.map((n: NodeTypeDef) => n.id));
        if (e.selectedNodes.length > 0) {
          setCurrentTab("properties");
        } else if (controller.current.getNodes().length > 0 || leftPalette) {
          setCurrentTab("pipeline-properties");
        } else {
          setCurrentTab("palette");
        }
      },
      [leftPalette]
    );

    const handleBeforeEditAction = useCallback(
      (e: CanvasEditEvent) => {
        if (isCreateNodeEvent(e) && e.finalized === true) {
          delete e.finalized;
          return e;
        }

        if (isCreateNodeEvent(e)) {
          // the edit was created by canvas, reconstruct and pass to addNode
          controller.current.addNode({
            ...e,
            onPropertiesUpdateRequested,
          });

          // cancel the edit until we finalize properties.
          return null;
        }

        return e;
      },
      [onPropertiesUpdateRequested]
    );

    const handleEditAction = useCallback(
      async (e: CanvasEditEvent) => {
        let payload;
        let type = e.editType;
        if (e.editType === "openFile") {
          const filenameRef = controller.current.resolveParameterRef(
            e.targetObject.op,
            "filehandler"
          );
          if (filenameRef) {
            payload =
              e.targetObject?.app_data?.component_parameters?.[filenameRef];
          } else {
            type = "openComponentDef";
            payload = {
              componentId: controller.current
                .getAllPaletteNodes()
                .find((n) => n.op === e.targetObject.op)?.id,
              componentSource: e.targetObject.app_data.component_source,
            };
          }
        }
        onAction?.({ type: type, payload });

        if (e.editType === "newFileNode") {
          const nodes = controller.current.getAllPaletteNodes();
          const extensions = nodes.map((n) => n.app_data.extensions).flat();

          const [file] = await onFileRequested?.({
            canSelectMany: false,
            filters: { File: extensions },
          });

          const node = nodes.find((n) =>
            n.app_data.extensions?.includes(path.extname(file))
          );

          if (node !== undefined) {
            controller.current.editActionHandler({
              editType: "createNode",
              nodeTemplate: {
                op: node.op,
              },
              pipelineId: e.pipelineId,
              offsetX: e.mousePos.x,
              offsetY: e.mousePos.y,
              path: file,
            });
          }
        }

        if (e.editType === "properties") {
          setCurrentTab("properties");
          setPanelOpen(true);
        }

        if (e.editType === "toggleOpenPanel") {
          setPanelOpen((prev) => !prev);
        }

        if (e.editType === "createExternalNode") {
          controller.current.editActionHandler({
            editType: "createNode",
            nodeTemplate: e.nodeTemplate,
            offsetX: e.offsetX,
            offsetY: e.offsetY,
            pipelineId: e.pipelineId,
          });
        }

        // Catch any events where a save isn't necessary.
        switch (e.editType) {
          case "properties":
          case "openFile":
          case "toggleOpenPanel":
          case "copy": // NOTE: "cut" deletes an item so needs a save.
          case "displaySubPipeline":
          case "displayPreviousPipeline":
            return;
        }

        onChange?.(controller.current.getPipelineFlow());
      },
      [onAction, onChange, onFileRequested]
    );

    const handlePropertiesChange = useCallback(
      (nodeID, data) => {
        controller.current.updateProperties(nodeID, data);
        onChange?.(controller.current.getPipelineFlow());
      },
      [onChange]
    );

    const handlePipelinePropertiesChange = useCallback(
      (data) => {
        const pipeline = controller.current.getPipelineFlow();
        if (pipeline?.pipelines?.[0]?.app_data) {
          pipeline.pipelines[0].app_data.properties = prefixedToNested(
            data,
            true
          );
          controller.current.setPipelineFlow(pipeline);
          onChange?.(controller.current.getPipelineFlow());
        }
      },
      [onChange]
    );

    const handleTooltip = (tipType: string, e: TipEvent) => {
      function isNodeTipEvent(type: string, _e: TipEvent): _e is TipNode {
        return type === "tipTypeNode";
      }
      if (isNodeTipEvent(tipType, e) && e.node.type === "execution_node") {
        const error = controller.current.errors(e.node.id);
        const properties = controller.current.properties(e.node.id);
        const node = controller.current
          .getAllPaletteNodes()
          .find((n) => n.op === e.node.op);
        return (
          <NodeTooltip
            error={error}
            properties={properties}
            nodeLabel={node?.label}
          />
        );
      }
      if (isNodeTipEvent(tipType, e) && e.node.type === "super_node") {
        // TODO: Can we can sub node errors propagated up?
        return "Supernode";
      }
      return null;
    };

    if (readOnly) {
      return (
        <Container className="pipeline-read-only" ref={blockingRef}>
          <IntlProvider locale="en">
            <CommonCanvas
              canvasController={controller.current}
              contextMenuHandler={() => {}}
              editActionHandler={() => {
                controller.current.setPipelineFlow(pipeline);
                controller.current.resetStyles();
              }}
              toolbarConfig={[]}
              config={{
                enableInternalObjectModel: false,
                emptyCanvasContent: children,
                enablePaletteLayout: "None",
                enableNodeFormatType: "Horizontal",
                enableToolbarLayout: "None",
                enableNodeLayout: {
                  bodyPath: READ_ONLY_NODE_SVG_PATH,
                  selectionPath: READ_ONLY_NODE_SVG_PATH,
                  dropShadow: false,
                },
              }}
            />
          </IntlProvider>
        </Container>
      );
    }

    const selectedNodes = controller.current.idsToNodes(selectedNodeIDs ?? []);
    const upstreamNodes = selectedNodeIDs?.[0]
      ? controller.current.getUpstreamNodes(selectedNodeIDs[0])
      : [];

    const panelTabs = [
      {
        id: "pipeline-properties",
        label: "Pipeline Properties",
        title: "Edit pipeline properties",
        icon: theme.overrides?.pipelineIcon,
        content: (
          <PipelineProperties
            pipelineFlow={pipeline}
            propertiesSchema={pipelineProperties}
            onFileRequested={onFileRequested}
            onPropertiesUpdateRequested={onPropertiesUpdateRequested}
            onChange={handlePipelinePropertiesChange}
          />
        ),
      },
      {
        id: "properties",
        label: "Node Properties",
        title: "Edit node properties",
        icon: theme.overrides?.propertiesIcon,
        content: (
          <NodeProperties
            selectedNodes={selectedNodes}
            nodes={controller.current.getAllPaletteNodes()}
            upstreamNodes={upstreamNodes}
            onFileRequested={onFileRequested}
            onPropertiesUpdateRequested={onPropertiesUpdateRequested}
            onChange={handlePropertiesChange}
          />
        ),
      },
    ];

    if (!leftPalette) {
      panelTabs.push({
        id: "palette",
        label: "Palette",
        title: "Add nodes to pipeline",
        icon: theme.overrides?.paletteIcon,
        content: (
          <PalettePanel nodes={controller.current.getAllPaletteNodes()} />
        ),
      });
    }

    return (
      <Container ref={blockingRef}>
        <IntlProvider locale="en">
          {supernodeOpen === true && (
            <Button
              hasToolbar={toolbar !== undefined}
              onClick={() => {
                controller.current.editActionHandler({
                  editType: "displayPreviousPipeline",
                });
              }}
            >
              Return to previous flow
            </Button>
          )}
          <SplitPanelLayout
            left={
              <CommonCanvas
                canvasController={controller.current}
                contextMenuHandler={handleContextMenu}
                clickActionHandler={handleClickAction}
                beforeEditActionHandler={handleBeforeEditAction}
                editActionHandler={handleEditAction}
                selectionChangeHandler={handleSelectionChange}
                tipHandler={handleTooltip}
                toolbarConfig={toolbar ?? []}
                config={{
                  enableInternalObjectModel: true,
                  emptyCanvasContent: children,
                  enablePaletteLayout: leftPalette ? "Flyout" : "None", // 'Flyout', 'None', 'Modal'
                  enableNodeFormatType: "Horizontal",
                  enableToolbarLayout: toolbar === undefined ? "None" : "Top",
                  enableNodeLayout: {
                    imagePosX: 10 + 2.5,
                    imagePosY: 0,
                    imageWidth: 16,
                    imageHeight: 35,
                    labelPosX: 32 + 2.5,
                    labelMaxWidth: 118 - 5,
                    defaultNodeHeight: 35,
                    inputPortLeftPosY: 17.5,
                    outputPortRightPosY: 17.5,
                    dropShadow: false,
                    labelPosY: 12 - 3,
                  },
                }}
                notificationConfig={{ enable: false }}
                contextMenuConfig={{
                  enableCreateSupernodeNonContiguous: true,
                  defaultMenuEntries: {
                    saveToPalette: false,
                    createSupernode: true,
                  },
                }}
                keyboardConfig={
                  nativeKeyboardActions
                    ? {
                        actions: {
                          undo: false,
                          redo: false,
                          cutToClipboard: false,
                          copyToClipboard: false,
                          pasteFromClipboard: false,
                        },
                      }
                    : undefined
                }
              />
            }
            right={
              <TabbedPanelLayout
                currentTab={currentTab}
                onTabClick={(id) => {
                  setCurrentTab(id);
                  onAction?.({ type: "openPanel" });
                  setPanelOpen(true);
                }}
                tabs={panelTabs}
                collapsed={panelOpen === false}
                showCloseButton={toolbar === undefined}
                onClose={() => {
                  onAction?.({ type: "closePanel" });
                  setPanelOpen(false);
                }}
              />
            }
            mode={
              panelOpen
                ? "open"
                : toolbar === undefined
                ? "collapsed"
                : "closed"
            }
          />
        </IntlProvider>
      </Container>
    );
  }
)