repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
hieutran3010/EnglishOnline
|
src/app/components/collection/List/List.tsx
|
<filename>src/app/components/collection/List/List.tsx
import React, { useState, useEffect, useCallback } from 'react';
import isEmpty from 'lodash/fp/isEmpty';
import getOr from 'lodash/fp/getOr';
import map from 'lodash/fp/map';
import { List, Input, Pagination, Space, Select, Tooltip, Button } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { ListProps } from 'antd/lib/list';
import { IDataSource, QueryCriteria, QueryOperator } from '../types';
import { Container } from './styles/StyledIndex';
const { Option } = Select;
const getItemValue = (item, field) => {
if (typeof item === 'string') {
return item;
}
if (isEmpty(field)) {
return item.toString();
}
return getOr('', field)(item);
};
interface Props {
graphQLDataSource: IDataSource;
pageSize?: number;
displayPath?: string;
onSelectionChanged?: (item: any) => void;
searchPlaceholder?: string;
searchHint?: string;
searchFields?: string[];
}
export default function DefaultList({
graphQLDataSource,
pageSize,
displayPath,
onSelectionChanged,
searchPlaceholder,
searchHint,
searchFields,
...restProps
}: Props & ListProps<any>) {
const [items, setItems] = useState<any[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [currentPageSize, setCurrentPageSize] = useState(pageSize || 10);
const [currentPage, setCurrentPage] = useState(1);
const [filters, setFilters] = useState<QueryCriteria[]>([]);
const fetchTotal = useCallback(async (currentFilters?: QueryCriteria[]) => {
const totalItem = await graphQLDataSource.countAsync(
currentFilters ?? filters,
);
setTotal(totalItem);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const fetchData = useCallback(
async (
pageSize?: number,
page?: number,
currentFilters?: QueryCriteria[],
) => {
setLoading(true);
const data = await graphQLDataSource.queryManyAsync(
{
pageSize: pageSize ?? currentPageSize,
page: page ?? currentPage,
criteria: currentFilters ?? filters,
},
true,
);
setItems(data);
setLoading(false);
},
[currentPage, currentPageSize, filters, graphQLDataSource],
);
useEffect(() => {
let reloadedSubscription;
if (graphQLDataSource) {
reloadedSubscription = graphQLDataSource.onReloaded.subscribe(() => {
fetchTotal();
fetchData();
});
}
return function cleanUp() {
if (reloadedSubscription) {
reloadedSubscription.unsubscribe();
}
};
}, [fetchData, fetchTotal, graphQLDataSource]);
useEffect(() => {
fetchTotal();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onItemClicked = useCallback(
item => () => {
if (onSelectionChanged) {
onSelectionChanged(item);
}
},
[onSelectionChanged],
);
const onPageChanged = useCallback(
(page: number, pageSize?: number | undefined) => {
setCurrentPage(page);
fetchData(pageSize, page);
},
[fetchData],
);
const onPageSizeChanged = useCallback(
(size: number) => {
setCurrentPageSize(size);
fetchData(size, currentPage);
},
[currentPage, fetchData],
);
const onSearchChanged = useCallback(
(searchKey: string) => {
if (isEmpty(searchKey)) {
setFilters([]);
fetchTotal([]);
fetchData(pageSize, currentPage, []);
return;
}
const criteria = map(
(searchField: string): QueryCriteria => {
return {
field: searchField,
operator: QueryOperator.C,
value: searchKey,
};
},
)(searchFields);
setFilters(criteria);
setCurrentPage(1);
fetchTotal(criteria);
fetchData(pageSize, 1, criteria);
},
[currentPage, fetchData, fetchTotal, pageSize, searchFields],
);
const onReloadData = useCallback(() => {
fetchTotal();
fetchData();
}, [fetchData, fetchTotal]);
const defaultItemRender = item => (
<List.Item onClick={onItemClicked(item)}>
{getItemValue(item, displayPath)}
</List.Item>
);
const { renderItem } = restProps;
return (
<Container>
<Space>
{!isEmpty(searchFields) && (
<Tooltip title={searchHint}>
<Input.Search
enterButton
disabled={loading}
size="small"
placeholder={searchPlaceholder}
onSearch={onSearchChanged}
allowClear
/>
</Tooltip>
)}
<Tooltip title="Tải lại dữ liệu">
<Button
type="primary"
shape="circle"
icon={<ReloadOutlined />}
size="small"
onClick={onReloadData}
/>
</Tooltip>
</Space>
<List
style={{
flex: '1 1 auto',
overflow: 'auto',
height: 0,
marginTop: 5,
marginBottom: 5,
}}
size="small"
dataSource={items}
renderItem={renderItem || defaultItemRender}
loading={loading}
{...restProps}
/>
<Space align="center">
<Pagination
size="small"
total={total}
simple
disabled={loading}
pageSize={currentPageSize}
current={currentPage}
onChange={onPageChanged}
/>
<Select
size="small"
onChange={onPageSizeChanged}
value={currentPageSize}
>
<Option value={10}>10/trang</Option>
<Option value={20}>20/trang</Option>
<Option value={30}>30/trang</Option>
<Option value={40}>40/trang</Option>
<Option value={50}>50/trang</Option>
</Select>
</Space>
</Container>
);
}
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/SearchControls/styles/StyledIndex.ts
|
<reponame>hieutran3010/EnglishOnline
import styled from 'styled-components/macro';
export const TextSearchContainer = styled.div`
padding: 8px;
.ant-input-group {
display: flex !important;
}
`;
|
hieutran3010/EnglishOnline
|
src/app/services/firebase/index.ts
|
import * as firebase from 'firebase/app';
const initializeFirebase = () => {
const config = require('./config.json');
// Initialize Firebase
firebase.initializeApp(config);
};
export { initializeFirebase };
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/Login/types.ts
|
<gh_stars>0
/* --- STATE --- */
export interface LoginState {
error: string;
isBeingLogin: boolean;
isRecovering: boolean;
recoveryError: string;
}
export interface LoginAction {
email: string;
password: string;
}
export type ContainerState = LoginState;
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/UserProfile/index.tsx
|
<filename>src/app/containers/Auth/UserProfile/index.tsx
/**
*
* UserProfile
*
*/
import React, { memo, useMemo, useCallback, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useInjectReducer, useInjectSaga } from 'utils/redux-injectors';
import { reducer, sliceKey, actions } from './slice';
import { selectIsChangingPass, selectPassChangingError } from './selectors';
import { userProfileSaga } from './saga';
import { RootContainer, ContentContainer } from 'app/components/Layout';
import { Form, Button, Alert } from 'antd';
import { PasswordInput } from 'app/components/Input';
import isEmpty from 'lodash/fp/isEmpty';
interface Props {}
export const UserProfile = memo((props: Props) => {
useInjectReducer({ key: sliceKey, reducer: reducer });
useInjectSaga({ key: sliceKey, saga: userProfileSaga });
const dispatch = useDispatch();
const [passChangingForm] = Form.useForm();
const isChangingPass = useSelector(selectIsChangingPass);
const passChangingError = useSelector(selectPassChangingError);
useEffect(() => {
return function cleanUp() {
dispatch(actions.reset());
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const validator = useMemo(
() => ({
oldPass: [{ required: true, message: 'Chưa nhập mật khẩu hiện tại' }],
newPass: [
{ required: true, message: 'Chưa nhập mật khẩu mới' },
({ getFieldValue }) => ({
validator(_rule, value) {
if (!value || getFieldValue('oldPass') === value) {
return Promise.reject(
'Mật khẩu mới phải khác mật khẩu hiện tại!',
);
}
return Promise.resolve();
},
}),
],
confirmNewPass: [
{ required: true, message: 'Chưa nhập xác nhận mật khẩu mới' },
({ getFieldValue }) => ({
validator(_rule, value) {
if (!value || getFieldValue('newPass') === value) {
return Promise.resolve();
}
return Promise.reject('Xác nhận mật khẩu mới không đúng!');
},
}),
],
}),
[],
);
const onChangePass = useCallback(
form => {
const { newPass } = form;
dispatch(
actions.changePass({
newPass,
onSuccess: () => {
passChangingForm.resetFields();
},
}),
);
},
[dispatch, passChangingForm],
);
return (
<RootContainer title="Đổi mật khẩu">
<ContentContainer>
<Form
labelCol={{ span: 4 }}
wrapperCol={{ span: 10 }}
onFinish={onChangePass}
form={passChangingForm}
>
<Form.Item
label="Mật khẩu hiện tại"
name="oldPass"
rules={validator.oldPass}
>
<PasswordInput
disabled={isChangingPass}
ref={(ref: any) => ref?.select()}
/>
</Form.Item>
<Form.Item
label="Mật khẩu mới"
name="newPass"
rules={validator.newPass}
>
<PasswordInput disabled={isChangingPass} />
</Form.Item>
<Form.Item
label="Xác nhận mật khẩu mới"
name="confirmNewPass"
rules={validator.confirmNewPass}
>
<PasswordInput disabled={isChangingPass} />
</Form.Item>
{!isEmpty(passChangingError) && (
<Form.Item label=" " colon={false}>
<Alert type="error" message={passChangingError} showIcon />
</Form.Item>
)}
<Form.Item label=" " colon={false}>
<Button type="primary" htmlType="submit" loading={isChangingPass}>
LƯU
</Button>
</Form.Item>
</Form>
</ContentContainer>
</RootContainer>
);
});
|
hieutran3010/EnglishOnline
|
src/app/components/Input/index.ts
|
<reponame>hieutran3010/EnglishOnline
import CurrencyInput from './CurrencyInput';
import PasswordInput from './PasswordInput';
export { CurrencyInput, PasswordInput };
|
hieutran3010/EnglishOnline
|
src/app/containers/Post/slice.ts
|
import { PayloadAction } from '@reduxjs/toolkit';
import Post from 'app/models/post';
import { createSlice } from 'utils/@reduxjs/toolkit';
import { ContainerState } from './types';
import { v4 as uuidv4 } from 'uuid';
// The initial state of the Post container
export const initialState: ContainerState = {
posts: [],
isFetchingPosts: false,
};
const postSlice = createSlice({
name: 'post',
initialState,
reducers: {
fetchPosts(state) {
state.isFetchingPosts = true;
},
fetchPostsCompleted(state, action: PayloadAction<Post[]>) {
state.isFetchingPosts = false;
state.posts = action.payload;
},
submitPost(state, action: PayloadAction<Post>) {
state.posts.splice(0, 0, {
id: uuidv4(),
owner: '<NAME>',
ownerAvatar:
'https://scontent.fvca1-2.fna.fbcdn.net/v/t1.0-9/120123166_10158465360393956_8815174325295557887_n.jpg?_nc_cat=100&ccb=2&_nc_sid=09cbfe&_nc_ohc=1zpC98ZIgGIAX_Dj9Mt&_nc_ht=scontent.fvca1-2.fna&oh=8361b5528fa55e30439223d27fa7d998&oe=5FDBF5E4',
content: action.payload.content,
});
},
},
});
export const { actions, reducer, name: sliceKey } = postSlice;
|
hieutran3010/EnglishOnline
|
src/app/fetchers/base/index.ts
|
import GraphQLFetcherBase from './GraphQLFetcherBase';
import RestfulFetcherBase from './RestfulFetcherBase';
export { GraphQLFetcherBase, RestfulFetcherBase };
|
hieutran3010/EnglishOnline
|
src/app/components/collection/List/index.ts
|
import List from './List';
import InfiniteLoadingList from './InfiniteLoadingList';
import DatasourceInfiniteLoadingList from './DatasourceInfiniteLoadingList';
export { List, InfiniteLoadingList, DatasourceInfiniteLoadingList };
|
hieutran3010/EnglishOnline
|
src/app/services/auth/authStorage.ts
|
<gh_stars>0
import User from 'app/models/user';
import { isEmpty } from 'lodash';
const CACHE_KEY = {
USER: 'USER',
};
class AuthStorage {
storeUser = (user: User) => {
localStorage.setItem(CACHE_KEY.USER, JSON.stringify(user));
};
getUser = (): User => {
const userStr = localStorage.getItem(CACHE_KEY.USER);
if (userStr && !isEmpty(userStr)) {
return JSON.parse(userStr) as User;
}
return new User();
};
clear = () => {
localStorage.removeItem(CACHE_KEY.USER);
};
}
const authStorage = new AuthStorage();
export default authStorage;
|
hieutran3010/EnglishOnline
|
src/app/components/Select/CountrySelect.tsx
|
<filename>src/app/components/Select/CountrySelect.tsx
import React, { useMemo, memo } from 'react';
import { Select } from 'antd';
import map from 'lodash/fp/map';
import find from 'lodash/fp/find';
import isEmpty from 'lodash/fp/isEmpty';
import isNil from 'lodash/fp/isNil';
import isUndefined from 'lodash/fp/isUndefined';
import { SelectProps } from 'antd/lib/select';
const countryData = require('./country.json');
const { Option } = Select;
interface ExcludedCountry {
country?: string;
reason?: string;
}
interface Props {
excludeCountries?: ExcludedCountry[];
}
const CountrySelect = React.forwardRef(
({ excludeCountries, ...restProps }: Props & SelectProps<any>, ref: any) => {
const { value } = restProps;
const options = useMemo(() => {
return map((country: any) => {
const { code, name } = country;
const c = `${name} - ${code}`;
let excludedCountry: ExcludedCountry = {};
if (!isEmpty(excludeCountries)) {
excludedCountry = find((item: ExcludedCountry) => c === item.country)(
excludeCountries,
) as ExcludedCountry;
}
const isDisabled =
!isEmpty(excludedCountry) &&
!isNil(excludedCountry) &&
!isUndefined(excludedCountry);
const isSelectedCountry = value && !isEmpty(value) && value.includes(c);
return (
<Option
key={code}
value={c}
disabled={isDisabled === true && !isSelectedCountry}
>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span>{c}</span>
<span>{isDisabled === true ? excludedCountry.reason : ''}</span>
</div>
</Option>
);
})(countryData);
}, [excludeCountries, value]);
return (
<Select
ref={ref}
mode="multiple"
style={{ width: '100%' }}
optionLabelProp="label"
allowClear
{...restProps}
>
{options}
</Select>
);
},
);
export default memo(CountrySelect);
export type { ExcludedCountry };
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/Login/Loadable.tsx
|
/**
*
* Asynchronously loads the component for Login
*
*/
import { lazyLoad } from 'utils/loadable';
import { LazyLoadingSkeleton } from 'app/components/Skeleton';
import React from 'react';
export const Login = lazyLoad(
() => import('./index'),
module => module.Login,
{ fallback: <LazyLoadingSkeleton /> },
);
|
hieutran3010/EnglishOnline
|
src/types/RootState.ts
|
import { LoginState } from 'app/containers/Auth/Login/types';
import { UserProfileState } from 'app/containers/Auth/UserProfile/types';
import { HomepageState } from 'app/containers/HomePage/types';
import { PostState } from 'app/containers/Post/types';
import { CoursesState } from 'app/containers/Courses/types';
// [IMPORT NEW CONTAINERSTATE ABOVE] < Needed for generating containers seamlessly
/*
Because the redux-injectors injects your reducers asynchronously somewhere in your code
You have to declare them here manually
*/
export interface RootState {
homepage?: HomepageState;
login?: LoginState;
userProfile?: UserProfileState;
post?: PostState;
courses?: CoursesState;
// [INSERT NEW REDUCER KEY ABOVE] < Needed for generating containers seamlessly
}
|
hieutran3010/EnglishOnline
|
src/app/components/Logo/index.tsx
|
<gh_stars>0
import React, { memo } from 'react';
interface Props {
isSmall?: boolean;
logoSmallSrc?: string | any;
logoSrc?: string | any;
height?: number;
}
const Logo = ({ isSmall, logoSmallSrc, logoSrc, height }: Props) => {
return (
<img
src={isSmall ? logoSmallSrc : logoSrc}
height={`${height ?? 40}px`}
width="auto"
alt=""
/>
);
};
export default memo(Logo);
|
hieutran3010/EnglishOnline
|
src/app/components/Skeleton/LazyLoadingSkeleton.tsx
|
<filename>src/app/components/Skeleton/LazyLoadingSkeleton.tsx
import React, { memo } from 'react';
import { Space, Spin, Typography } from 'antd';
const { Text } = Typography;
const LazyLoadingSkeleton = props => {
if (props.error) {
window.location.reload(true);
return <></>;
}
return (
<Space>
<Spin />
<Text>Đang tải...</Text>
</Space>
);
};
export default memo(LazyLoadingSkeleton);
|
hieutran3010/EnglishOnline
|
src/app/components/AppNavigation/styles/StyledTopNavigation.ts
|
import styled from 'styled-components/macro';
export const StyledLogoWrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
height: 60px;
padding-left: 20px;
`;
|
hieutran3010/EnglishOnline
|
src/app/containers/HomePage/UserNavigation.tsx
|
import React, { memo, useMemo, useCallback } from 'react';
import { Avatar, Dropdown, Menu, Divider, Space } from 'antd';
import { UserOutlined, LogoutOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import toString from 'lodash/fp/toString';
import { authService, authStorage } from 'app/services/auth';
import { showConfirm } from 'app/components/Modal/utils';
const UserNavigation = () => {
const user = authStorage.getUser();
const onSignOut = useCallback(() => {
showConfirm(
'Bạn có chắc đã lưu hết dữ liệu và muốn thoát khỏi hệ thống?',
() => authService.logout(),
);
}, []);
const menu = useMemo(() => {
return (
<Menu>
<Menu.Item key={1}>
<Link to="/userProfile"><NAME> Tài Khoản</Link>
</Menu.Item>
<Menu.Item key={2}>
<Divider style={{ margin: 0 }} />
</Menu.Item>
<Menu.Item key={3} danger onClick={onSignOut}>
<Space>
<LogoutOutlined style={{ marginBottom: 6 }} />
<span>Đăng Xuất</span>
</Space>
</Menu.Item>
</Menu>
);
}, [onSignOut]);
return (
<div>
<Dropdown overlay={menu}>
<Space>
<div style={{ display: 'flex' }}>
<span> - </span>
<span>{user.displayName}</span>
</div>
<Avatar icon={<UserOutlined />} />
</Space>
</Dropdown>
</div>
);
};
export default memo(UserNavigation);
|
hieutran3010/EnglishOnline
|
src/app/containers/Post/saga.ts
|
import { take, call, put, select, takeLatest } from 'redux-saga/effects';
import PostFetcher from 'app/fetchers/postFetcher';
import { actions } from './slice';
import Post from 'app/models/post';
const postFetcher = new PostFetcher();
export function* fetchPostsTask() {
let posts: Post[] = [
{
id: 'p1',
owner: '<NAME>',
ownerAvatar:
'https://lh3.googleusercontent.com/TtzZw1i1p988V8hIA-PMwjFBA3Q27XYZXxDdKr808DCehRZTwXvMpbCUEEGs9wcyDVPKeGxezs-fzQswVCEa3-P6r3kWI7z4IoHZnLE5At6fyBIKSVPmYOxBAyNxhmbtZqyiFmyyTa8Y28ZXnj6dQ10RZ-VuGSb8CLv_uS-hARBfYgxyaxPp-FaU3e4aRtg5wXb58ZLX2abgWmMkL5QDk-HmSyzmXCXheCe_PVZECgi-fEFemt9LayXj3ByGmxHtz7yZaVIfWqSioU-kUI1VeSQBvwoMq2N-L_fk4tkoBUzvxC9MHHRZHDlZfu93zgRHTEXSwgqAQ3IpKBJre2JQ_Ex6GHNm7glE9F2g1Z485IGP_0Rx-FJU0J01E6clsHPD_KXXNH8OhGiriFSOLGqKPA9NkouWMHtTzxOaXkCYejv309mAO2tmm4oXjEvWLgV64hZQAZ7GiMpKXFetmnH-bhaawJ2hVpzx-MyijWax8aj_Fvfv0CE7DHaNDHF-QFJmBNt0vK_a-ILaggufvKZwpw3TPMLejUYyDC8ewD1gKbCBlWkDBYifNRGIxDcxV32hIbDfCU-aJqBgOiDFcqnygwwtAn_KWs1gdMazQPb-SuTGMZ_hqIw0sx_1X8Tr-GEAMhY2oDF4rSQV2ghjSD2s7740XXsINgQ0fdK_A5WFctQwCybDp40UVbigqbejOw=w729-h972-no?authuser=0',
content: 'Có ai có khóa học tiếng anh nào hay không?',
postComments: [
{
id: 'comment1',
owner: '<NAME>',
content: 'Chị có nè, inbox chị đi nhé',
postId: 'p1',
},
],
},
{
id: 'p2',
owner: '<NAME>',
ownerAvatar:
'https://scontent.fvca1-2.fna.fbcdn.net/v/t1.0-9/120123166_10158465360393956_8815174325295557887_n.jpg?_nc_cat=100&ccb=2&_nc_sid=09cbfe&_nc_ohc=1zpC98ZIgGIAX_Dj9Mt&_nc_ht=scontent.fvca1-2.fna&oh=8361b5528fa55e30439223d27fa7d998&oe=5FDBF5E4',
content:
'Các bạn có muốn tham gia vào group tiếng anh giao tiếp cơ bản ko?',
},
{
id: 'p3',
owner: '<NAME>',
ownerAvatar:
'https://lh3.googleusercontent.com/TtzZw1i1p988V8hIA-PMwjFBA3Q27XYZXxDdKr808DCehRZTwXvMpbCUEEGs9wcyDVPKeGxezs-fzQswVCEa3-P6r3kWI7z4IoHZnLE5At6fyBIKSVPmYOxBAyNxhmbtZqyiFmyyTa8Y28ZXnj6dQ10RZ-VuGSb8CLv_uS-hARBfYgxyaxPp-FaU3e4aRtg5wXb58ZLX2abgWmMkL5QDk-HmSyzmXCXheCe_PVZECgi-fEFemt9LayXj3ByGmxHtz7yZaVIfWqSioU-kUI1VeSQBvwoMq2N-L_fk4tkoBUzvxC9MHHRZHDlZfu93zgRHTEXSwgqAQ3IpKBJre2JQ_Ex6GHNm7glE9F2g1Z485IGP_0Rx-FJU0J01E6clsHPD_KXXNH8OhGiriFSOLGqKPA9NkouWMHtTzxOaXkCYejv309mAO2tmm4oXjEvWLgV64hZQAZ7GiMpKXFetmnH-bhaawJ2hVpzx-MyijWax8aj_Fvfv0CE7DHaNDHF-QFJmBNt0vK_a-ILaggufvKZwpw3TPMLejUYyDC8ewD1gKbCBlWkDBYifNRGIxDcxV32hIbDfCU-aJqBgOiDFcqnygwwtAn_KWs1gdMazQPb-SuTGMZ_hqIw0sx_1X8Tr-GEAMhY2oDF4rSQV2ghjSD2s7740XXsINgQ0fdK_A5WFctQwCybDp40UVbigqbejOw=w729-h972-no?authuser=0',
content:
'Có bạn nào biết các thì hay dùng trong giao tiếp hàng ngày không?',
},
{
id: 'p4',
owner: '<NAME>',
ownerAvatar:
'https://scontent.fvca1-2.fna.fbcdn.net/v/t1.0-9/120123166_10158465360393956_8815174325295557887_n.jpg?_nc_cat=100&ccb=2&_nc_sid=09cbfe&_nc_ohc=1zpC98ZIgGIAX_Dj9Mt&_nc_ht=scontent.fvca1-2.fna&oh=8361b5528fa55e30439223d27fa7d998&oe=5FDBF5E4',
content:
'Cùng thảo luận các từ vựng trong ngành công nghệ thông tin nhé?',
},
{
id: 'p5',
owner: '<NAME>',
ownerAvatar:
'https://lh3.googleusercontent.com/TtzZw1i1p988V8hIA-PMwjFBA3Q27XYZXxDdKr808DCehRZTwXvMpbCUEEGs9wcyDVPKeGxezs-fzQswVCEa3-P6r3kWI7z4IoHZnLE5At6fyBIKSVPmYOxBAyNxhmbtZqyiFmyyTa8Y28ZXnj6dQ10RZ-VuGSb8CLv_uS-hARBfYgxyaxPp-FaU3e4aRtg5wXb58ZLX2abgWmMkL5QDk-HmSyzmXCXheCe_PVZECgi-fEFemt9LayXj3ByGmxHtz7yZaVIfWqSioU-kUI1VeSQBvwoMq2N-L_fk4tkoBUzvxC9MHHRZHDlZfu93zgRHTEXSwgqAQ3IpKBJre2JQ_Ex6GHNm7glE9F2g1Z485IGP_0Rx-FJU0J01E6clsHPD_KXXNH8OhGiriFSOLGqKPA9NkouWMHtTzxOaXkCYejv309mAO2tmm4oXjEvWLgV64hZQAZ7GiMpKXFetmnH-bhaawJ2hVpzx-MyijWax8aj_Fvfv0CE7DHaNDHF-QFJmBNt0vK_a-ILaggufvKZwpw3TPMLejUYyDC8ewD1gKbCBlWkDBYifNRGIxDcxV32hIbDfCU-aJqBgOiDFcqnygwwtAn_KWs1gdMazQPb-SuTGMZ_hqIw0sx_1X8Tr-GEAMhY2oDF4rSQV2ghjSD2s7740XXsINgQ0fdK_A5WFctQwCybDp40UVbigqbejOw=w729-h972-no?authuser=0',
content:
'Các bạn nghĩ sao về tầm quan trọng tiếng anh trong cuộc sống hiện nay?',
},
{
id: 'p11',
owner: '<NAME>',
ownerAvatar:
'https://lh3.googleusercontent.com/TtzZw1i1p988V8hIA-PMwjFBA3Q27XYZXxDdKr808DCehRZTwXvMpbCUEEGs9wcyDVPKeGxezs-fzQswVCEa3-P6r3kWI7z4IoHZnLE5At6fyBIKSVPmYOxBAyNxhmbtZqyiFmyyTa8Y28ZXnj6dQ10RZ-VuGSb8CLv_uS-hARBfYgxyaxPp-FaU3e4aRtg5wXb58ZLX2abgWmMkL5QDk-HmSyzmXCXheCe_PVZECgi-fEFemt9LayXj3ByGmxHtz7yZaVIfWqSioU-kUI1VeSQBvwoMq2N-L_fk4tkoBUzvxC9MHHRZHDlZfu93zgRHTEXSwgqAQ3IpKBJre2JQ_Ex6GHNm7glE9F2g1Z485IGP_0Rx-FJU0J01E6clsHPD_KXXNH8OhGiriFSOLGqKPA9NkouWMHtTzxOaXkCYejv309mAO2tmm4oXjEvWLgV64hZQAZ7GiMpKXFetmnH-bhaawJ2hVpzx-MyijWax8aj_Fvfv0CE7DHaNDHF-QFJmBNt0vK_a-ILaggufvKZwpw3TPMLejUYyDC8ewD1gKbCBlWkDBYifNRGIxDcxV32hIbDfCU-aJqBgOiDFcqnygwwtAn_KWs1gdMazQPb-SuTGMZ_hqIw0sx_1X8Tr-GEAMhY2oDF4rSQV2ghjSD2s7740XXsINgQ0fdK_A5WFctQwCybDp40UVbigqbejOw=w729-h972-no?authuser=0',
content: 'Mình đang cần bộ đề ôn thi TOIEC, có bạn nào có không?',
},
{
id: 'p12',
owner: '<NAME>',
ownerAvatar:
'https://lh3.googleusercontent.<KEY>0',
content: 'Cuối tuần này ai muốn tham giao English Coffee ko?',
},
{
id: 'p13',
owner: '<NAME>',
ownerAvatar:
'https://scontent.fvca1-2.fna.fbcdn.net/v/t1.0-9/120123166_10158465360393956_8815174325295557887_n.jpg?_nc_cat=100&ccb=2&_nc_sid=09cbfe&_nc_ohc=1zpC98ZIgGIAX_Dj9Mt&_nc_ht=scontent.fvca1-2.fna&oh=8361b5528fa55e30439223d27fa7d998&oe=5FDBF5E4',
content: 'Các bạn có phân biệt được các loại certificate của TOIEC ko?',
},
{
id: 'p14',
owner: '<NAME>',
ownerAvatar:
'https://scontent.fvca1-2.fna.fbcdn.net/v/t1.0-9/120123166_10158465360393956_8815174325295557887_n.jpg?_nc_cat=100&ccb=2&_nc_sid=09cbfe&_nc_ohc=1zpC98ZIgGIAX_Dj9Mt&_nc_ht=scontent.fvca1-2.fna&oh=8361b5528fa55e30439223d27fa7d998&oe=5FDBF5E4',
content: 'IELTS mới đổi cấu trúc đề thi, có ai biết về việc này không?',
},
];
try {
// posts = yield postFetcher.queryManyAsync({});
} catch (error) {
console.log(error);
}
yield put(actions.fetchPostsCompleted(posts));
}
export function* postSaga() {
yield takeLatest(actions.fetchPosts.type, fetchPostsTask);
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/Login/slice.ts
|
import { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from 'utils/@reduxjs/toolkit';
import { ContainerState, LoginAction } from './types';
// The initial state of the Login container
export const initialState: ContainerState = {
error: '',
isBeingLogin: false,
isRecovering: false,
recoveryError: '',
};
const loginSlice = createSlice({
name: 'login',
initialState,
reducers: {
setError(state, action: PayloadAction<string>) {
state.error = action.payload;
},
setIsBeingLogin(state, action: PayloadAction<boolean>) {
state.isBeingLogin = action.payload;
},
login(state, action: PayloadAction<LoginAction>) {},
recoveryPassword(
state,
action: PayloadAction<{ email: string; onSent: () => void }>,
) {
state.isRecovering = true;
},
recoveryPasswordCompleted(state, action: PayloadAction<string>) {
const error = action.payload;
state.isRecovering = false;
state.recoveryError = error;
},
},
});
export const { actions, reducer, name: sliceKey } = loginSlice;
|
hieutran3010/EnglishOnline
|
src/app/containers/HomePage/slice.ts
|
import { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from 'utils/@reduxjs/toolkit';
import { getScreenMode, ScreenMode } from 'app/components/AppNavigation';
import { ContainerState } from './types';
const initScreenMode = getScreenMode();
// The initial state of the CustomerCreateOrUpdatePage container
export const initialState: ContainerState = {
screenMode: initScreenMode,
collapsedMenu: initScreenMode !== ScreenMode.FULL,
};
const homepageSlice = createSlice({
name: 'homepage',
initialState,
reducers: {
setScreenMode(state, action: PayloadAction<ScreenMode>) {
state.screenMode = action.payload;
},
toggleCollapsedMenu(state) {
state.collapsedMenu = !state.collapsedMenu;
},
},
});
export const { actions, reducer, name: sliceKey } = homepageSlice;
|
hieutran3010/EnglishOnline
|
src/app/components/AppNavigation/types.ts
|
import { ReactElement } from 'react';
export enum ScreenMode {
FULL = 'FULL',
TABLET = 'TABLET',
MOBILE = 'MOBILE',
}
export interface IMenuItem {
key: string;
order?: number;
icon: ReactElement;
path?: string;
displayName: string;
activePaths?: string[];
childMenu?: IMenuItem[];
canShow?: () => boolean;
}
export interface IMenu {
items: IMenuItem[];
onSelectedMenuChanged?: (key: string) => void;
selectedMenuKeys?: string[];
}
export interface IDrawerMenu extends IMenu {
visible?: boolean;
onClose?: () => void;
header?: React.ReactNode;
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/components/UserAvatar.tsx
|
<filename>src/app/containers/Auth/components/UserAvatar.tsx
import React, { memo, useState, useEffect } from 'react';
import { Popover, Avatar, Spin, Typography, Descriptions } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import isEmpty from 'lodash/fp/isEmpty';
import { PopoverProps } from 'antd/lib/popover';
import { AvatarProps } from 'antd/lib/avatar';
import User from 'app/models/user';
import { authService } from 'app/services/auth';
const { Text } = Typography;
interface Props {
title?: string;
userId?: string;
type?: 'avatar' | 'displayName' | 'displayNameWithLabel';
}
const UserAvatar = ({
title,
userId,
type,
...restProps
}: Props & PopoverProps & AvatarProps) => {
const { placement } = restProps;
const [user, setUser] = useState<User>();
const [loading, setLoading] = useState<boolean>(false);
useEffect(() => {
let didCancel = false;
async function getUserAsync() {
if (isEmpty(userId)) {
return;
}
setLoading(true);
const c = await authService.getUserById(userId);
if (!didCancel) {
setUser(c);
setLoading(false);
}
}
getUserAsync();
return function cleanUp() {
didCancel = true;
};
}, [userId]);
if (type === 'displayNameWithLabel') {
return (
<Descriptions column={1} size="small">
<Descriptions.Item label={title}>
{loading ? (
<Spin size="small" />
) : (
<Text>{user?.displayName ?? '<Chưa có>'}</Text>
)}
</Descriptions.Item>
</Descriptions>
);
}
return (
<Popover
title={title}
placement={placement || 'left'}
content={<span>{user?.displayName}</span>}
>
{loading ? (
<Spin size="small" />
) : type === 'avatar' ? (
<Avatar
icon={<UserOutlined />}
size="small"
src={user?.avatarUrl}
{...restProps}
/>
) : (
<Text>{user?.displayName}</Text>
)}
</Popover>
);
};
UserAvatar.defaultProps = {
type: 'avatar',
};
export default memo(UserAvatar);
|
hieutran3010/EnglishOnline
|
src/app/components/Layout/AppLayout.tsx
|
<reponame>hieutran3010/EnglishOnline<filename>src/app/components/Layout/AppLayout.tsx
import React, { memo, useCallback, useMemo, useState } from 'react';
import { Layout } from 'antd';
import {
LeftNavigation,
TopNavigation,
ScreenMode,
} from 'app/components/AppNavigation';
import { IMenuItem } from 'app/components/AppNavigation/types';
import DrawerMenu from '../AppNavigation/DrawerMenu';
import Logo from '../Logo';
const { Content } = Layout;
export const getMarginLeft = (screenMode: ScreenMode, collapsed: boolean) => {
if (screenMode === ScreenMode.MOBILE) {
return 20;
}
if (screenMode === ScreenMode.FULL) {
return collapsed ? 100 : 211;
}
return 100;
};
interface AppLayout {
menus: IMenuItem[];
logo: any;
logoSmall: any;
screenMode: ScreenMode;
isCollapsed: boolean;
onCollapsed: () => void;
renderTopRightComponent?: () => React.Component;
onSelectedMenuChanged?: (key: string) => void;
selectedMenuKeys?: string[];
}
const AppLayout = ({
menus,
logo,
logoSmall,
screenMode,
isCollapsed,
renderTopRightComponent,
onCollapsed,
onSelectedMenuChanged,
selectedMenuKeys,
...restProps
}: AppLayout | any) => {
const _isCollapsed = useMemo(() => {
if (screenMode !== ScreenMode.FULL) {
return true;
}
return isCollapsed;
}, [isCollapsed, screenMode]);
const [visibleDrawer, setVisibleDrawer] = useState(false);
const _onDrawerSelectedMenuChanged = useCallback(
(key: string) => {
setVisibleDrawer(false);
onSelectedMenuChanged(key);
},
[onSelectedMenuChanged],
);
const onShowDrawer = useCallback(() => {
setVisibleDrawer(true);
}, []);
const onCloseDrawer = useCallback(() => {
setVisibleDrawer(false);
}, []);
const { children } = restProps;
return (
<Layout style={{ height: '100%' }}>
<TopNavigation
isCollapsed={_isCollapsed}
onCollapse={onCollapsed}
menus={menus}
logo={logo}
logoSmall={logoSmall}
renderRightComponent={renderTopRightComponent}
screenMode={screenMode}
onShowDrawer={onShowDrawer}
/>
<Layout>
{screenMode !== ScreenMode.MOBILE ? (
<LeftNavigation
isCollapsed={_isCollapsed}
menus={menus}
onSelectedMenuChanged={onSelectedMenuChanged}
selectedMenuKeys={selectedMenuKeys}
/>
) : (
<DrawerMenu
items={menus}
onSelectedMenuChanged={_onDrawerSelectedMenuChanged}
selectedMenuKeys={selectedMenuKeys}
visible={visibleDrawer}
onClose={onCloseDrawer}
header={<Logo logoSrc={logo} height={35} />}
/>
)}
<Content
style={{
marginRight: 20,
marginTop: 20,
marginBottom: 20,
marginLeft: getMarginLeft(screenMode, _isCollapsed),
display: 'flex',
}}
>
<div style={{ flex: 'auto', width: '100%' }}>{children}</div>
</Content>
</Layout>
</Layout>
);
};
export default memo(AppLayout);
|
hieutran3010/EnglishOnline
|
src/app/components/AppNavigation/Menu.tsx
|
import React, { memo, useCallback } from 'react';
import { Link } from 'react-router-dom';
import map from 'lodash/fp/map';
import { Menu as AntMenu } from 'antd';
import { IMenu, IMenuItem } from './types';
import isEmpty from 'lodash/fp/isEmpty';
const { SubMenu } = AntMenu;
const Menu = ({ items, onSelectedMenuChanged, selectedMenuKeys }: IMenu) => {
const onSelect = useCallback(
({ key }) => {
onSelectedMenuChanged && onSelectedMenuChanged(key);
},
[onSelectedMenuChanged],
);
return (
<AntMenu
theme="light"
mode="inline"
onSelect={onSelect}
selectedKeys={selectedMenuKeys}
>
{map((menu: IMenuItem) => {
if (isEmpty(menu.childMenu)) {
return (
<AntMenu.Item key={menu.key} icon={menu.icon}>
<Link to={menu.path || ''}>{menu.displayName}</Link>
</AntMenu.Item>
);
}
return (
<SubMenu key={menu.key} icon={menu.icon} title={menu.displayName}>
{map((child: IMenuItem) => {
return (
<AntMenu.Item key={child.key} icon={child.icon}>
<Link to={child.path || ''}>{child.displayName}</Link>
</AntMenu.Item>
);
})(menu.childMenu)}
</SubMenu>
);
})(items)}
</AntMenu>
);
};
export default memo(Menu);
|
hieutran3010/EnglishOnline
|
src/app/collection-datasource/graphql/utils.ts
|
import isEmpty from 'lodash/fp/isEmpty';
import toLower from 'lodash/fp/toLower';
import { GRAPHQL_QUERY_OPERATOR } from './constants';
import { QueryCriteria } from '../types';
const formatCriteriaValue = (criteria: QueryCriteria) => {
const { value, isExplicitFilter } = criteria;
if (isExplicitFilter && typeof value !== 'string') {
return value;
}
if (typeof value === 'string') {
return `"${isExplicitFilter ? value : toLower(value)}"`;
}
return value;
};
export const parseQueryCriteriaToGraphQLDoorQuery = (
queryCriteria: QueryCriteria[],
isSearchOr?: boolean,
) => {
const getQueryString = (criteria: QueryCriteria) => {
const { field, operator, value } = criteria;
switch (operator) {
case GRAPHQL_QUERY_OPERATOR.CONTAINS:
return `${field}.ToLower().Contains(${formatCriteriaValue(criteria)})`;
case GRAPHQL_QUERY_OPERATOR.EQUALS:
case GRAPHQL_QUERY_OPERATOR.NOT_EQUAL:
case GRAPHQL_QUERY_OPERATOR.GT:
case GRAPHQL_QUERY_OPERATOR.GTE:
case GRAPHQL_QUERY_OPERATOR.LT:
case GRAPHQL_QUERY_OPERATOR.LTE:
return `${field} ${operator} ${formatCriteriaValue(criteria)}`;
case GRAPHQL_QUERY_OPERATOR.ANY_FALSE:
return `!${field}.Any(s => s.${value})`;
case GRAPHQL_QUERY_OPERATOR.ANY_TRUE:
return `${field}.Any(s => s.${value})`;
default:
return '';
}
};
if (!isEmpty(queryCriteria)) {
const parsedFilters = queryCriteria.map((criteria: QueryCriteria) => {
const { field, operator, value } = criteria;
if (field.includes('@')) {
const fieldOrs = field.split('@');
const orQueries: string[] = [];
fieldOrs.forEach((orField: string) => {
const query = getQueryString({ field: orField, operator, value });
orQueries.push(query);
});
return `(${orQueries.join(' || ')})`;
}
return getQueryString(criteria);
});
return parsedFilters.join(isSearchOr ? ' || ' : ' && ');
}
return '';
};
|
hieutran3010/EnglishOnline
|
src/app/collection-datasource/index.ts
|
<gh_stars>0
import GraphQLDataSource from './graphql';
import PostFetcher from 'app/fetchers/postFetcher';
import PostCommentFetcher from 'app/fetchers/postCommentFetcher';
export enum FETCHER_KEY {
POST,
POST_COMMENT,
}
const getDataSource = (fetcherKey: FETCHER_KEY, extendFields?: string[]) => {
switch (fetcherKey) {
case FETCHER_KEY.POST: {
return new GraphQLDataSource(new PostFetcher());
}
case FETCHER_KEY.POST_COMMENT: {
return new GraphQLDataSource(new PostCommentFetcher());
}
}
};
export default getDataSource;
|
hieutran3010/EnglishOnline
|
src/utils/colorUtils.ts
|
<filename>src/utils/colorUtils.ts
const getContrast = (hexColor?: string) => {
if (!hexColor) {
return 'black';
}
// If a leading # is provided, remove it
if (hexColor.slice(0, 1) === '#') {
hexColor = hexColor.slice(1);
}
// Convert to RGB value
var r = parseInt(hexColor.substr(0, 2), 16);
var g = parseInt(hexColor.substr(2, 2), 16);
var b = parseInt(hexColor.substr(4, 2), 16);
// Get YIQ ratio
var yiq = (r * 299 + g * 587 + b * 114) / 1000;
// Check contrast
return yiq >= 128 ? 'black' : 'white';
};
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
export { getContrast, getRandomColor };
|
hieutran3010/EnglishOnline
|
src/app/services/auth/AuthService.ts
|
<reponame>hieutran3010/EnglishOnline<filename>src/app/services/auth/AuthService.ts<gh_stars>0
import { Subject } from 'rxjs';
import isEmpty from 'lodash/fp/isEmpty';
import toString from 'lodash/fp/toString';
import firebase from 'firebase/app';
import 'firebase/auth';
import User from 'app/models/user';
import { authStorage } from '.';
import UserFetcher from 'app/fetchers/userFetcher';
export const IS_AUTHENTICATED = 'IS_AUTHENTICATED';
export class AuthService {
onLoginSuccess = new Subject();
onLogoutSuccess = new Subject();
constructor() {
firebase.auth().onAuthStateChanged(this.onLoginChanged);
}
onLoginChanged = user => {
if (user) {
if (user.emailVerified === true) {
localStorage.removeItem(IS_AUTHENTICATED);
localStorage.setItem(IS_AUTHENTICATED, 'perfect');
}
this._getCurrentUser().then((user: User) => {
authStorage.storeUser(user);
this.onLoginSuccess.next(user);
});
} else {
localStorage.removeItem(IS_AUTHENTICATED);
authStorage.clear();
this.onLogoutSuccess.next();
}
};
isAuthenticated = (): boolean => {
return !isEmpty(localStorage.getItem(IS_AUTHENTICATED));
};
private _getCurrentUser = async (): Promise<User> => {
const firebaseUser = firebase.auth().currentUser;
const user = new User();
if (firebaseUser) {
user.id = firebaseUser.uid;
user.email = toString(firebaseUser.email);
user.emailVerified = firebaseUser.emailVerified;
user.displayName = toString(firebaseUser.displayName);
user.avatarUrl = toString(firebaseUser.photoURL);
user.phoneNumber = toString(firebaseUser.phoneNumber);
const tokenResult = await firebaseUser.getIdTokenResult();
user.role = tokenResult.claims['roles'];
}
return user;
};
// TODO: should log event for exception here
login = (email: string, password: string) => {
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch(error => {
const { code } = error;
switch (code) {
case 'auth/invalid-email': {
throw new Error('Email không đúng');
}
case 'auth/user-disabled': {
throw new Error('Tài khoản của bạn hiện đang bị khoá');
}
case 'auth/user-not-found': {
throw new Error('Tài khoản này không tồn tại');
}
case 'auth/wrong-password': {
throw new Error('Sai mật khẩu hoặc email');
}
default: {
throw new Error('Đăng nhập không thành công, vui lòng thử lại!');
}
}
});
};
logout = () => {
return firebase
.auth()
.signOut()
.catch(() => {
this.onLogoutSuccess.next();
});
};
getIdTokenAsync = async () => {
const currentUser = firebase.auth().currentUser;
if (currentUser) {
const tokenResult = await currentUser.getIdTokenResult();
return tokenResult.token;
}
return '';
};
sendEmailVerification = () => {
return firebase.auth().currentUser?.sendEmailVerification();
};
getUserById = (uid?: string): Promise<User> | undefined => {
if (!uid) {
return undefined;
}
const userFetcher = new UserFetcher();
return userFetcher.get(uid);
};
recovery(email) {
const actionCodeSettings = {
url: process.env.REACT_APP_PUBLIC_URL || '',
};
return firebase
.auth()
.sendPasswordResetEmail(email, actionCodeSettings)
.catch(error => {
const { code } = error;
switch (code) {
case 'auth/invalid-email': {
throw new Error('Email không đúng');
}
case 'auth/user-not-found': {
throw new Error('Không có tài khoản nào đã đăng ký với email này');
}
default:
throw new Error('Chưa gởi được email, vui lòng thử lại!');
}
});
}
changePass = (newPass: string) => {
return firebase
.auth()
.currentUser?.updatePassword(newPass)
.catch(error => {
const { code } = error;
switch (code) {
case 'auth/weak-password': {
throw new Error('Mật khẩu không đủ mạnh');
}
case 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN': {
throw new Error(
'Đăng xuất và đăng nhập lại vào phần mềm để thử lại!',
);
}
default: {
throw new Error('Chưa đổi được mật khẩu, vui lòng thử lại!');
}
}
});
};
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/Login/styles/StyledIndex.ts
|
<gh_stars>0
import styled from 'styled-components/macro';
export const StyledLogInContainer = styled.div`
display: flex;
height: 100vh;
background-color: rgb(217, 217, 217, 0.3);
justify-content: center;
align-items: center;
img {
margin-bottom: 24px;
margin-left: auto;
margin-right: auto;
}
`;
export const StyledLoginFormContainer = styled.div`
display: flex;
flex-direction: column;
background-color: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -1px rgba(0, 0, 0, 0.06);
width: 400px;
.ant-form-item .ant-btn {
width: 100%;
}
`;
|
hieutran3010/EnglishOnline
|
src/app/components/AppNavigation/DrawerMenu.tsx
|
import { Drawer } from 'antd';
import React, { memo } from 'react';
import Menu from './Menu';
import { IDrawerMenu } from './types';
const DrawerMenu = ({
visible,
header,
onClose,
...restProps
}: IDrawerMenu) => {
return (
<Drawer
placement="left"
visible={visible}
closable={false}
onClose={onClose}
title={header}
bodyStyle={{ padding: 0 }}
headerStyle={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Menu {...restProps} />
</Drawer>
);
};
export default memo(DrawerMenu);
|
hieutran3010/EnglishOnline
|
src/app/components/collection/List/InfiniteLoadingList.tsx
|
<reponame>hieutran3010/EnglishOnline
import React, { memo, ReactElement, useCallback } from 'react';
import { List, Spin } from 'antd';
import InfiniteScroll from 'react-infinite-scroller';
import size from 'lodash/fp/size';
export interface IInfiniteLoadingListProps {
onRenderItem: (item: any) => ReactElement;
loading?: boolean;
totalItems?: number;
data?: any[];
onLoadData?: () => void;
initialLoad?: boolean;
}
const InfiniteLoadingList = ({
onRenderItem,
loading,
data,
totalItems,
onLoadData,
initialLoad,
}: IInfiniteLoadingListProps) => {
const hasMore = size(data) < (totalItems || 0);
const handleInfiniteOnLoad = useCallback(() => {
onLoadData && onLoadData();
}, [onLoadData]);
return (
<InfiniteScroll
initialLoad={initialLoad}
pageStart={0}
loadMore={handleInfiniteOnLoad}
hasMore={hasMore && !loading}
useWindow={false}
>
<List dataSource={data} renderItem={onRenderItem} />
{loading && (
<div
style={{
display: 'flex',
width: '100%',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Spin />
</div>
)}
</InfiniteScroll>
);
};
export default memo(InfiniteLoadingList);
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/SimpleDataGrid.tsx
|
<reponame>hieutran3010/EnglishOnline
/* eslint-disable indent */
import React, { useState, useCallback, useMemo } from 'react';
import { Table } from 'antd';
import { Key, TablePaginationConfig } from 'antd/lib/table/interface';
import keys from 'lodash/fp/keys';
import find from 'lodash/fp/find';
import get from 'lodash/fp/get';
import isEmpty from 'lodash/fp/isEmpty';
import isArray from 'lodash/fp/isArray';
import head from 'lodash/fp/head';
import { ColumnDefinition, TableChangedEventArgs } from './types';
import { OrderOption, QueryCriteria, QueryOperator } from '../types';
import { formatColumns } from './utils';
import { TableProps } from 'antd/lib/table';
interface ISimpleDataGrid {
columns: ColumnDefinition[];
pageSizeOptions: Array<string>;
pageSize: number;
maxHeight?: number;
width?: number | string;
heightOffset?: number;
totalCount?: number;
onTableChanged?: (e: TableChangedEventArgs) => void;
}
export default function SimpleDataGrid({
columns,
pageSizeOptions,
pageSize,
maxHeight,
width,
heightOffset,
totalCount,
onTableChanged,
...restProps
}: ISimpleDataGrid & TableProps<any>) {
const [pagination, setPagination] = useState<TablePaginationConfig>({
pageSize,
current: 1,
});
/**
* From the filter model of Ant Table, let's create the criteria that are able to query via IDataSource
*/
const getQueryCriteria = useCallback(
(antTableFilters: Record<string, Key[] | null>): QueryCriteria[] => {
const result: QueryCriteria[] = [];
const filterKeys = keys(antTableFilters);
if (!isEmpty(filterKeys)) {
filterKeys.forEach((filterKey: string) => {
let filterValue = get(filterKey)(antTableFilters);
if (isArray(filterValue) && !isEmpty(filterValue)) {
filterValue = head(filterValue);
}
if (!isEmpty(filterValue)) {
const colConfig = find(
(col: ColumnDefinition) => col.key === filterKey,
)(columns);
if (colConfig) {
result.push({
field: colConfig.dataIndex || colConfig.filterField || '',
value: filterValue,
operator: colConfig.searchOperator || QueryOperator.C,
});
}
}
});
}
return result;
},
[columns],
);
const onTableChange = useCallback(
(
currentPagination: TablePaginationConfig,
filters: Record<string, Key[] | null>,
sorter: any,
) => {
setPagination({
current: currentPagination.current,
pageSize: currentPagination.pageSize,
});
let currentOrder: OrderOption | undefined = undefined;
if (sorter) {
const { field, order } = sorter;
currentOrder = {
orderByField: field,
isDescending: order === 'descend',
};
}
if (onTableChanged) {
const queryCriteria = getQueryCriteria(filters);
onTableChanged({
queryCriteria,
order: currentOrder,
pageSize: currentPagination.pageSize,
page: currentPagination.current,
});
}
},
[getQueryCriteria, onTableChanged],
);
const formattedColumns = useMemo(() => formatColumns(columns), [columns]);
const _maxHeight = useMemo(() => {
if (maxHeight) {
return maxHeight;
}
if (heightOffset) {
const offset = window.innerHeight * heightOffset;
return window.innerHeight - offset;
}
return 400;
}, [heightOffset, maxHeight]);
return (
<Table
scroll={{ x: width ?? 'max-content', y: _maxHeight }}
columns={formattedColumns}
rowKey={(record: any) => record.id}
onChange={onTableChange}
pagination={{
pageSizeOptions,
showSizeChanger: true,
defaultPageSize: 20,
pageSize: pagination.pageSize,
current: pagination.current,
total: totalCount,
}}
{...restProps}
/>
);
}
SimpleDataGrid.defaultProps = {
pageSizeOptions: ['10', '20', '30', '40', '50', '80', '100'],
pageSize: 20,
size: 'small',
};
|
hieutran3010/EnglishOnline
|
src/app/components/Layout/index.ts
|
import AppLayout from './AppLayout';
import RootContainer from './RootContainer';
import ContentContainer from './ContentContainer';
export { AppLayout, RootContainer, ContentContainer };
|
hieutran3010/EnglishOnline
|
src/app/components/AppNavigation/index.ts
|
import LeftNavigation from './LeftNavigation';
import TopNavigation from './TopNavigation';
import { ScreenMode } from './types';
const getScreenMode = (): ScreenMode => {
if (window.innerWidth <= 760) {
return ScreenMode.MOBILE;
}
if (window.innerWidth <= 1440) {
return ScreenMode.TABLET;
}
return ScreenMode.FULL;
};
export { LeftNavigation, TopNavigation, ScreenMode, getScreenMode };
|
hieutran3010/EnglishOnline
|
src/app/fetchers/userFetcher.ts
|
import User from 'app/models/user';
import { RestfulFetcherBase } from './base';
export default class UserFetcher extends RestfulFetcherBase<User> {
constructor() {
super('account');
}
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/UserProfile/slice.ts
|
<reponame>hieutran3010/EnglishOnline
import { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from 'utils/@reduxjs/toolkit';
import { ContainerState } from './types';
// The initial state of the UserProfile container
export const initialState: ContainerState = {
isChangingPass: false,
passChangingError: '',
};
const userProfileSlice = createSlice({
name: 'userProfile',
initialState,
reducers: {
changePass(
state,
action: PayloadAction<{ newPass: string; onSuccess: () => void }>,
) {
state.isChangingPass = true;
},
changePassCompleted(state, action: PayloadAction<string>) {
state.isChangingPass = false;
const errorMsg = action.payload;
state.passChangingError = errorMsg;
},
reset(state) {
state.isChangingPass = false;
state.passChangingError = '';
},
},
});
export const { actions, reducer, name: sliceKey } = userProfileSlice;
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/Login/saga.ts
|
import { call, put, takeLatest } from 'redux-saga/effects';
import { actions } from './slice';
import { PayloadAction } from '@reduxjs/toolkit';
import { LoginAction } from './types';
import { authService } from 'app/services/auth';
export function* loginTask(action: PayloadAction<LoginAction>) {
yield put(actions.setIsBeingLogin(true));
try {
const { email, password } = action.payload;
yield call(authService.login, email, password);
yield put(actions.setError(''));
} catch (error) {
const { message } = error;
yield put(actions.setError(message));
}
yield put(actions.setIsBeingLogin(false));
}
export function* recoveryPasswordTask(
action: PayloadAction<{ email: string; onSent: () => void }>,
) {
let errorMsg: string = '';
try {
yield call(authService.recovery, action.payload.email);
action.payload.onSent();
} catch (error) {
const { message } = error;
errorMsg = message;
}
yield put(actions.recoveryPasswordCompleted(errorMsg));
}
export function* loginSaga() {
yield takeLatest(actions.login.type, loginTask);
yield takeLatest(actions.recoveryPassword.type, recoveryPasswordTask);
}
|
hieutran3010/EnglishOnline
|
src/app/components/AppNavigation/TopNavigation.tsx
|
<reponame>hieutran3010/EnglishOnline<filename>src/app/components/AppNavigation/TopNavigation.tsx
import React, { memo } from 'react';
import { Button, Layout } from 'antd';
import {
MenuUnfoldOutlined,
MenuFoldOutlined,
MenuOutlined,
} from '@ant-design/icons';
import { StyledLogoWrapper } from './styles/StyledTopNavigation';
import { ScreenMode, IMenuItem } from './types';
import Logo from '../Logo';
const { Header } = Layout;
interface TopNavigation {
isCollapsed: boolean;
onCollapse: () => void;
menus: IMenuItem[];
logo: any;
logoSmall: any;
screenMode: ScreenMode;
renderRightComponent?: () => React.Component;
onShowDrawer?: () => void;
}
const TopNavigation = ({
isCollapsed,
onCollapse,
logoSmall,
logo,
renderRightComponent,
screenMode,
onShowDrawer,
}: TopNavigation) => {
return (
<Header
className="site-layout-background"
style={{
padding: 0,
boxShadow:
'0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
zIndex: 1,
width: '100%',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
position: 'sticky',
top: 0,
}}
>
<StyledLogoWrapper className="logo">
{screenMode === ScreenMode.MOBILE ? (
<Button
type="primary"
ghost
icon={<MenuOutlined />}
style={{ marginRight: 10 }}
onClick={onShowDrawer}
/>
) : (
<Logo isSmall={isCollapsed} logoSrc={logo} logoSmallSrc={logoSmall} />
)}
</StyledLogoWrapper>
{screenMode === ScreenMode.FULL ??
React.createElement(
isCollapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
{
className: 'trigger',
onClick: onCollapse,
style: {
fontSize: 18,
marginLeft: isCollapsed ? 24 : 80,
color: '#00a651',
},
},
)}
<div
style={{
flex: 1,
display: 'flex',
justifyContent: 'flex-end',
paddingRight: 20,
}}
>
{renderRightComponent && renderRightComponent()}
</div>
</Header>
);
};
export default memo(TopNavigation);
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/index.ts
|
import DataGrid from './DataGrid';
import SimpleDataGrid from './SimpleDataGrid';
import { COLUMN_TYPES } from './constants';
import { ColumnDefinition } from './types';
export { DataGrid, SimpleDataGrid, COLUMN_TYPES };
export type { ColumnDefinition };
|
hieutran3010/EnglishOnline
|
src/app/models/postComment.ts
|
import ModelBase from './modelBase';
export default class PostComment extends ModelBase {
owner!: string;
content!: string;
postId!: string;
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/UserProfile/types.ts
|
<reponame>hieutran3010/EnglishOnline
/* --- STATE --- */
export interface UserProfileState {
isChangingPass: boolean;
passChangingError: string;
}
export type ContainerState = UserProfileState;
|
hieutran3010/EnglishOnline
|
src/index.tsx
|
<reponame>hieutran3010/EnglishOnline
/**
* index.tsx
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ToastContainer } from 'react-toastify';
import * as serviceWorker from 'serviceWorker';
import * as Sentry from '@sentry/react';
import 'sanitize.css/sanitize.css';
// Import root app
import { App } from 'app';
import { HelmetProvider } from 'react-helmet-async';
import 'moment/locale/vi';
import locale from 'antd/es/locale/vi_VN';
import { configureAppStore } from 'store/configureStore';
// Initialize languages
import './locales/i18n';
import './styles/App.less';
import 'react-toastify/dist/ReactToastify.css';
import 'react-datasheet/lib/react-datasheet.css';
import { ConfigProvider } from 'antd';
Sentry.init({
dsn: process.env.REACT_APP_SENTRY_DSN,
ignoreErrors: [
'ResizeObserver loop limit exceeded',
'Non-Error promise rejection captured with keys: errorFields, outOfDate, values',
],
maxValueLength: 10000,
});
const store = configureAppStore();
const MOUNT_NODE = document.getElementById('root') as HTMLElement;
interface Props {
Component: typeof App;
}
const ConnectedApp = ({ Component }: Props) => (
<Provider store={store}>
<HelmetProvider>
{/* <React.StrictMode> */}
<ConfigProvider locale={locale}>
<Component />
</ConfigProvider>
<ToastContainer
position="top-center"
autoClose={5000}
hideProgressBar={false}
newestOnTop
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
/>
{/* </React.StrictMode> */}
</HelmetProvider>
</Provider>
);
const render = (Component: typeof App) => {
ReactDOM.render(<ConnectedApp Component={Component} />, MOUNT_NODE);
};
if (module.hot) {
// Hot reloadable translation json files and app
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept(['./app', './locales/i18n'], () => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
const App = require('./app').App;
render(App);
});
}
render(App);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
hieutran3010/EnglishOnline
|
src/app/services/auth/index.ts
|
<filename>src/app/services/auth/index.ts
import { AuthService } from './AuthService';
import authStorage from './authStorage';
const authService = new AuthService();
export { authService, authStorage };
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/UserProfile/saga.ts
|
import { call, put, takeLatest } from 'redux-saga/effects';
import { actions } from './slice';
import { PayloadAction } from '@reduxjs/toolkit';
import { authService } from 'app/services/auth';
import { toast } from 'react-toastify';
export function* changePassTask(
action: PayloadAction<{ newPass: string; onSuccess: () => void }>,
) {
let errorMsg: string = '';
try {
yield call(authService.changePass, action.payload.newPass);
action.payload.onSuccess();
} catch (error) {
const { message } = error;
errorMsg = message;
}
yield put(actions.changePassCompleted(errorMsg));
yield call(toast.success, 'Đã đổi mật khẩu!');
}
export function* userProfileSaga() {
yield takeLatest(actions.changePass.type, changePassTask);
}
|
hieutran3010/EnglishOnline
|
src/app/containers/Auth/Login/selectors.ts
|
<filename>src/app/containers/Auth/Login/selectors.ts
import { createSelector } from '@reduxjs/toolkit';
import { RootState } from 'types';
import { initialState } from './slice';
const selectDomain = (state: RootState) => state.login || initialState;
export const selectIsBeingLogin = createSelector(
[selectDomain],
loginState => loginState.isBeingLogin,
);
export const selectError = createSelector(
[selectDomain],
loginState => loginState.error,
);
export const selectRecoveryError = createSelector(
[selectDomain],
loginState => loginState.recoveryError,
);
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/constants.ts
|
export const COLUMN_TYPES = {
STRING: 'string',
DATE: 'date',
DATE_TIME: 'dateTime',
DATE_WITHOUT_YEAR: 'dateWithoutYear',
NUMBER: 'number',
CURRENCY: 'currency',
BOOLEAN: 'boolean',
PERCENT: 'percent',
};
|
hieutran3010/EnglishOnline
|
src/app/collection-datasource/types.ts
|
<reponame>hieutran3010/EnglishOnline
export interface QueryCriteria {
field: string;
value: any;
isExplicitFilter?: boolean;
operator: string;
}
|
hieutran3010/EnglishOnline
|
src/app/models/validators/userValidator.ts
|
<reponame>hieutran3010/EnglishOnline<filename>src/app/models/validators/userValidator.ts
import { Rule } from 'antd/lib/form';
import { REGEX_PATTERN } from 'utils/numberFormat';
type UserValidator = {
email: Rule[];
password: Rule[];
name: Rule[];
phoneNumber: Rule[];
role: Rule[];
};
const getUserValidator = (): UserValidator => ({
email: [
{ required: true, message: 'Chưa nhập Email' },
{ type: 'email', message: 'Email không đúng' },
],
password: [{ required: true, message: '<PASSWORD>' }],
name: [{ required: true, message: 'Chưa nhập Tên người dùng' }],
phoneNumber: [
{
pattern: new RegExp(REGEX_PATTERN.PHONE),
message: 'Số điện thoại chỉ cho phép các ký số từ 1 tới 9',
},
],
role: [{ required: true, message: 'Chưa chọn quyền' }],
});
interface LoginValidator {
email: Rule[];
password: Rule[];
}
export const getLoginValidator = (): LoginValidator => ({
email: [
{ required: true, message: 'Chưa nhập Email' },
{ type: 'email', message: 'Email không đúng' },
],
password: [{ required: true, message: '<PASSWORD>' }],
});
export default getUserValidator;
|
hieutran3010/EnglishOnline
|
src/app/containers/Post/index.tsx
|
/**
*
* Post
*
*/
import React, { memo, useCallback, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
Avatar,
Button,
Card,
Col,
List,
Row,
Skeleton,
Typography,
Form,
Input,
Space,
Comment,
} from 'antd';
import { LikeOutlined, CommentOutlined } from '@ant-design/icons';
import { useInjectReducer, useInjectSaga } from 'utils/redux-injectors';
import { reducer, sliceKey, actions } from './slice';
import { selectPosts, selectIsFetchingPosts } from './selectors';
import { postSaga } from './saga';
import PostModel from 'app/models/post';
import size from 'lodash/fp/size';
import PostComment from 'app/models/postComment';
const { Meta } = Card;
const { Text } = Typography;
export const Post = memo(() => {
useInjectReducer({ key: sliceKey, reducer: reducer });
useInjectSaga({ key: sliceKey, saga: postSaga });
const posts = useSelector(selectPosts);
const isFetchingPosts = useSelector(selectIsFetchingPosts);
const dispatch = useDispatch();
const [postForm] = Form.useForm();
const [commentForm] = Form.useForm();
useEffect(() => {
dispatch(actions.fetchPosts());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onRenderComment = useCallback((postComment: PostComment) => {
return (
<Comment
author={<a>{postComment.owner}</a>}
avatar={
<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
}
content={<p>{postComment.content}</p>}
/>
);
}, []);
const onSubmitComment = useCallback(form => {
console.log(form);
}, []);
const onRenderPost = useCallback(
(postModel: PostModel) => {
return (
<Card style={{ marginBottom: 15 }}>
<Skeleton loading={isFetchingPosts} avatar active>
<Meta
avatar={<Avatar src={postModel.ownerAvatar} />}
title={<Text strong>{postModel.owner}</Text>}
description={<Text>{postModel.content}</Text>}
/>
<Space
style={{
width: '100%',
borderTop: '1px solid #CCCCCC',
borderBottom: '1px solid #CCCCCC',
justifyContent: 'space-around',
marginTop: 20,
}}
>
<Button
icon={<LikeOutlined />}
key="like"
type="ghost"
style={{ border: 0, boxShadow: 'none' }}
>
Like
</Button>
<Button
icon={<CommentOutlined />}
key="comment"
type="ghost"
style={{ border: 0, boxShadow: 'none' }}
>
Comment
</Button>
</Space>
{postModel.postComments && size(postModel.postComments) > 0 && (
<>
<List
dataSource={postModel.postComments}
renderItem={onRenderComment}
rowKey={comment => comment.id}
/>
<Form
layout="inline"
form={commentForm}
onFinish={onSubmitComment}
>
<Form.Item>
<Avatar src="https://scontent.fvca1-2.fna.fbcdn.net/v/t1.0-9/120123166_10158465360393956_8815174325295557887_n.jpg?_nc_cat=100&ccb=2&_nc_sid=09cbfe&_nc_ohc=1zpC98ZIgGIAX_Dj9Mt&_nc_ht=scontent.fvca1-2.fna&oh=8361b5528fa55e30439223d27fa7d998&oe=5FDBF5E4" />
</Form.Item>
<Form.Item
name="content"
style={{ flex: 1 }}
rules={[
{ required: true, message: 'Please write something!' },
]}
>
<Input
style={{ width: '100%' }}
placeholder="Write a comment..."
/>
</Form.Item>
</Form>
</>
)}
</Skeleton>
</Card>
);
},
[commentForm, isFetchingPosts, onRenderComment, onSubmitComment],
);
const onSubmitPost = useCallback(
form => {
dispatch(actions.submitPost(form));
postForm.resetFields();
},
[dispatch, postForm],
);
return (
<>
<Row style={{ width: '100%' }} justify="center">
<Col xs={24} sm={24} md={24} lg={12} xl={12} xxl={12}>
<Card style={{ marginBottom: 15 }}>
<Form layout="inline" form={postForm} onFinish={onSubmitPost}>
<Form.Item>
<Avatar src="https://scontent.fvca1-2.fna.fbcdn.net/v/t1.0-9/120123166_10158465360393956_8815174325295557887_n.jpg?_nc_cat=100&ccb=2&_nc_sid=09cbfe&_nc_ohc=1zpC98ZIgGIAX_Dj9Mt&_nc_ht=scontent.fvca1-2.fna&oh=8361b5528fa55e30439223d27fa7d998&oe=5FDBF5E4" />
</Form.Item>
<Form.Item
name="content"
style={{ flex: 1 }}
rules={[{ required: true, message: 'Please input something!' }]}
>
<Input
style={{ width: '100%' }}
placeholder="What's on your mind?"
/>
</Form.Item>
<Form.Item>
<Button htmlType="submit" type="primary" shape="round">
POST
</Button>
</Form.Item>
</Form>
</Card>
</Col>
</Row>
<Row style={{ width: '100%', height: '100%' }} justify="center">
<Col xs={24} sm={24} md={24} lg={12} xl={12} xxl={12}>
<List
dataSource={posts}
renderItem={onRenderPost}
rowKey={post => post.id}
/>
</Col>
</Row>
</>
);
});
|
hieutran3010/EnglishOnline
|
src/app/components/Modal/utils.tsx
|
<gh_stars>0
import React from 'react';
import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
export const showConfirm = (message: string, onOk?, onCancel?) => {
Modal.confirm({
title: 'Xác Nhận',
icon: <ExclamationCircleOutlined />,
content: message,
okText: 'OK',
cancelText: 'Đóng',
onOk,
onCancel,
});
};
|
hieutran3010/EnglishOnline
|
src/app/components/Skeleton/index.ts
|
import LazyLoadingSkeleton from './LazyLoadingSkeleton';
export { LazyLoadingSkeleton };
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/DataGrid.tsx
|
<filename>src/app/components/collection/DataGrid/DataGrid.tsx
/* eslint-disable indent */
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table } from 'antd';
import {
Key,
TablePaginationConfig,
TableLocale,
} from 'antd/lib/table/interface';
import keys from 'lodash/fp/keys';
import find from 'lodash/fp/find';
import get from 'lodash/fp/get';
import isEmpty from 'lodash/fp/isEmpty';
import isArray from 'lodash/fp/isArray';
import head from 'lodash/fp/head';
import isEqual from 'lodash/fp/isEqual';
import all from 'lodash/fp/all';
import values from 'lodash/fp/values';
import { ColumnDefinition } from './types';
import {
IDataSource,
OrderOption,
QueryCriteria,
QueryOperator,
QueryParams,
} from '../types';
import { formatColumns } from './utils';
interface DataGrid {
dataSource: IDataSource;
columns: ColumnDefinition[];
pageSizeOptions: Array<string>;
pageSize: number;
maxHeight?: number;
width?: number | boolean | string | 'max-content';
heightOffset?: number;
locale?: TableLocale;
dontLoadInitialData?: boolean;
onTotalCountChanged?: (count: number) => void;
onLoadingTotalCount?: (isLoading: boolean) => void;
onLoading?: (isLoading: boolean) => void;
}
export default function DataGrid({
dataSource,
columns,
pageSizeOptions,
pageSize,
maxHeight,
width,
heightOffset,
locale,
dontLoadInitialData,
onTotalCountChanged,
onLoadingTotalCount,
onLoading,
...restProps
}: DataGrid & any) {
const [items, setItems] = useState<any[]>([]);
const [pagination, setPagination] = useState<TablePaginationConfig>({
pageSize,
current: 1,
});
const [total, setTotal] = useState<number>(0);
const [loading, setLoading] = useState<boolean>(false);
const [antTableFilter, setAntTableFilter] = useState<
Record<string, Key[] | null>
>({});
const [order, setOrder] = useState<OrderOption>({});
/**
* From the filter model of Ant Table, let's create the criteria that are able to query via IDataSource
*/
const getQueryCriteria = useCallback(
(antTableFilters: Record<string, Key[] | null>): QueryCriteria[] => {
const result: QueryCriteria[] = [];
const filterKeys = keys(antTableFilters);
if (!isEmpty(filterKeys)) {
filterKeys.forEach((filterKey: string) => {
let filterValue = get(filterKey)(antTableFilters);
if (isArray(filterValue) && !isEmpty(filterValue)) {
filterValue = head(filterValue);
}
if (!isEmpty(filterValue)) {
const colConfig = find(
(col: ColumnDefinition) => col.key === filterKey,
)(columns);
if (colConfig) {
result.push({
field: colConfig.dataIndex || colConfig.filterField || '',
value: filterValue,
operator: colConfig.searchOperator || QueryOperator.C,
});
}
}
});
}
return result;
},
[columns],
);
/**
* Fetch total count by QueryCriteria
*/
const fetchTotalCount = useCallback(
async (tableFilter?: Record<string, React.Key[] | null>) => {
onLoadingTotalCount && onLoadingTotalCount(true);
const _filter = tableFilter || antTableFilter;
// if (isEmpty(_filter) || all(v => isNil(v))(values(_filter))) {
// if (dontLoadInitialData === true) {
// setItems([]);
// return;
// }
// }
const queryCriteria = getQueryCriteria(_filter);
const totalItem = await dataSource.countAsync(queryCriteria);
setTotal(totalItem);
onTotalCountChanged && onTotalCountChanged(totalItem);
onLoadingTotalCount && onLoadingTotalCount(false);
},
[
antTableFilter,
dataSource,
getQueryCriteria,
onTotalCountChanged,
onLoadingTotalCount,
],
);
/**
* Fetch data by query criteria
*/
const fetchData = useCallback(
async (
tableFilter?: Record<string, React.Key[] | null>,
inputOrder?: OrderOption,
inputPagination?: TablePaginationConfig,
) => {
const _filter = tableFilter || antTableFilter;
// if (isEmpty(_filter) || all(v => isNil(v))(values(_filter))) {
// if (dontLoadInitialData === true) {
// setItems([]);
// return;
// }
// }
setLoading(true);
const paging = inputPagination || pagination;
const queryParams: QueryParams = {
pageSize: paging.pageSize,
page: paging.current,
criteria: getQueryCriteria(_filter),
order: inputOrder || order,
};
const data = await dataSource.queryManyAsync(queryParams);
setLoading(false);
setItems(data);
},
[antTableFilter, pagination, getQueryCriteria, order, dataSource],
);
/**
* Auto register reloading data when placeholder requesting and dispose it when component is unmounted
*/
useEffect(() => {
let reloadedSubscription;
if (dataSource) {
reloadedSubscription = dataSource.onReloaded.subscribe(() => {
// setAntTableFilter({});
// setOrder({});
// const pager = { ...pagination };
// pager.current = 1;
// setPagination(pager);
// fetchTotalCount({});
// fetchData({}, {}, pager);
fetchTotalCount();
fetchData();
});
}
return function cleanUp() {
if (reloadedSubscription) {
reloadedSubscription.unsubscribe();
}
};
}, [dataSource, fetchData, fetchTotalCount, pagination]);
/**
* Fetching total count at initializing
*/
useEffect(() => {
if (!dontLoadInitialData) {
fetchTotalCount();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dontLoadInitialData]);
/**
* Fetching data at initializing
*/
useEffect(() => {
if (!dontLoadInitialData) {
fetchData();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dontLoadInitialData]);
const onTableChange = useCallback(
(
currentPagination: TablePaginationConfig,
filters: Record<string, Key[] | null>,
sorter: any,
) => {
setPagination({
current: currentPagination.current,
pageSize: currentPagination.pageSize,
});
setAntTableFilter(filters);
let currentOrder: OrderOption | undefined = undefined;
if (sorter) {
const { field, order } = sorter;
currentOrder = {
orderByField: field,
isDescending: order === 'descend',
};
setOrder(currentOrder);
}
if (
!isEqual(filters, antTableFilter) &&
!(isEmpty(antTableFilter) && all(v => v === null)(values(filters)))
) {
fetchTotalCount(filters);
}
fetchData(filters, currentOrder, currentPagination);
},
[antTableFilter, fetchData, fetchTotalCount],
);
const formattedColumns = useMemo(() => formatColumns(columns), [columns]);
const _maxHeight = useMemo(() => {
if (maxHeight) {
return maxHeight;
}
if (heightOffset) {
const offset = window.innerHeight * heightOffset;
return window.innerHeight - offset;
}
return 400;
}, [heightOffset, maxHeight]);
return (
<Table
scroll={{ x: width ?? 'max-content', y: _maxHeight }}
columns={formattedColumns}
dataSource={items}
rowKey={(record: any) => record.id}
loading={loading}
onChange={onTableChange}
pagination={{
pageSizeOptions,
showSizeChanger: true,
defaultPageSize: 20,
pageSize: pagination.pageSize,
current: pagination.current,
total,
}}
locale={locale}
{...restProps}
/>
);
}
DataGrid.defaultProps = {
pageSizeOptions: ['10', '20', '30', '40', '50', '80', '100'],
pageSize: 20,
size: 'small',
};
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/types.ts
|
<reponame>hieutran3010/EnglishOnline
import { ReactElement } from 'react';
import { OrderOption, QueryCriteria } from '../types';
export interface ColumnDefinition {
title: string;
type?: string;
dataIndex?: string;
canFilter?: boolean;
filterField?: string;
searchOperator?: string;
key: string;
width?: number;
render?: (data?: any) => ReactElement;
sorter?: any;
fixed?: 'left' | 'right' | true;
editable?: boolean;
}
export interface TableChangedEventArgs {
queryCriteria?: QueryCriteria[];
order?: OrderOption;
pageSize?: number;
page?: number;
}
|
hieutran3010/EnglishOnline
|
src/app/components/collection/types.ts
|
import { Subject } from 'rxjs';
export interface IDataSource {
queryManyAsync: (params: QueryParams, isSearchOr?: boolean) => Promise<any[]>;
countAsync: (queryCriteria: QueryCriteria[]) => Promise<number>;
onReloaded: Subject<any>;
addAsync: (model: any) => Promise<any>;
onReloadData: () => void;
}
export interface QueryParams {
pageSize?: number;
page?: number;
order?: OrderOption;
criteria?: QueryCriteria[];
}
export interface QueryCriteria {
field: string;
value: any;
operator: string;
}
export const QueryOperator = {
E: '=',
NE: '!=',
GT: '>',
GTE: '>=',
LT: '<',
LTE: '<=',
C: 'contains',
ANY_TRUE: 'any',
ANY_FALSE: '!any',
};
export interface OrderOption {
orderByField?: string;
isDescending?: boolean;
}
|
hieutran3010/EnglishOnline
|
src/app/containers/HomePage/selectors.ts
|
import { createSelector } from '@reduxjs/toolkit';
import { RootState } from 'types';
import { initialState } from './slice';
const selectDomain = (state: RootState) => state.homepage || initialState;
export const selectScreenMode = createSelector(
[selectDomain],
homepageState => homepageState.screenMode,
);
export const selectCollapsedMenu = createSelector(
[selectDomain],
homepageState => homepageState.collapsedMenu,
);
|
hieutran3010/EnglishOnline
|
src/utils/numberFormat.ts
|
import { padStart, trimStart, replace, trim, toString } from 'lodash';
const toCurrency = (value: number, isUsd: boolean = false) => {
const formatted = toString(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
if (isUsd === true) {
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 4,
});
return formatter.format(value);
}
return `${formatted}đ`;
};
const toFullString = (value: number) => {
const str = toString(value);
if (str.length === 1) {
return padStart(str, 2, '0');
}
return str;
};
const formatPhoneNumber = (phoneNumber: string): string => {
const formatted = trimStart(
replace(trim(phoneNumber), new RegExp(/\D+/g), ''),
'0',
);
return formatted;
};
const REGEX_PATTERN = {
PHONE: '^[0-9]*$',
};
export { toCurrency, toFullString, REGEX_PATTERN, formatPhoneNumber };
|
hieutran3010/EnglishOnline
|
src/app/models/modelBase.ts
|
<reponame>hieutran3010/EnglishOnline
export default class ModelBase {
id: string;
constructor(entity: any = undefined) {
if (entity) {
this.id = entity.id;
} else {
this.id = '';
}
}
}
|
hieutran3010/EnglishOnline
|
src/app/components/Input/PasswordInput.tsx
|
import React, { memo } from 'react';
import Input, { InputProps } from 'antd/lib/input';
import { EyeTwoTone, EyeInvisibleOutlined } from '@ant-design/icons';
const PasswordInput = React.forwardRef((props: InputProps, ref: any) => {
return (
<Input.Password
ref={ref}
iconRender={visible =>
visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
}
{...props}
/>
);
});
export default memo(PasswordInput);
|
hieutran3010/EnglishOnline
|
src/app/containers/HomePage/types.ts
|
<reponame>hieutran3010/EnglishOnline
import { ScreenMode } from 'app/components/AppNavigation';
/* --- STATE --- */
export interface HomepageState {
screenMode: ScreenMode;
collapsedMenu: boolean;
}
export type ContainerState = HomepageState;
|
hieutran3010/EnglishOnline
|
src/app/collection-datasource/graphql/index.ts
|
<filename>src/app/collection-datasource/graphql/index.ts<gh_stars>0
import isEmpty from 'lodash/fp/isEmpty';
import isNil from 'lodash/fp/isNil';
import map from 'lodash/fp/map';
import { GraphQLEntityFetcher } from 'graphql-door-client';
import { Subject } from 'rxjs';
import {
IDataSource,
QueryParams,
QueryCriteria as CollectionControlQueryCriteria,
QueryOperator,
OrderOption,
} from 'app/components/collection/types';
import { GRAPHQL_QUERY_OPERATOR } from './constants';
import { parseQueryCriteriaToGraphQLDoorQuery } from './utils';
import { QueryCriteria } from '../types';
export default class GraphQLDataSource<TModel> implements IDataSource {
onReloaded = new Subject();
includeField?: string;
orderByFields?: string;
query?: string;
fetcher: GraphQLEntityFetcher<TModel>;
constructor(fetcher: GraphQLEntityFetcher<TModel>) {
this.fetcher = fetcher;
}
queryManyAsync = (
queryParams: QueryParams,
isSearchOr?: boolean,
): Promise<any[]> => {
const { order, pageSize, page, criteria } = queryParams;
const query = this.getGraphQLQuery(criteria || [], isSearchOr);
return this.fetcher.queryManyAsync({
query,
include: this.includeField,
orderBy: this.getOrderConfig(order || {}) || this.orderByFields,
pageSize,
page,
});
};
countAsync = (
queryCriteria: CollectionControlQueryCriteria[],
): Promise<number> => {
const query = this.getGraphQLQuery(queryCriteria);
return this.fetcher.countAsync(query);
};
addAsync = (model: any): Promise<any> => this.fetcher.addAsync(model);
onReloadData = () => {
this.onReloaded.next();
};
/**
* Convert the query criteria from collection-control to query that is able to work with GraphQL
* @param queryCriteria The query criteria that is received from collection control
*/
private convertToGraphQLQueryCriteria = (
queryCriteria: CollectionControlQueryCriteria[],
): QueryCriteria[] => {
let result: QueryCriteria[] = [];
if (queryCriteria && !isEmpty(queryCriteria)) {
result = map(
(criteria: CollectionControlQueryCriteria): QueryCriteria => {
return {
field: criteria.field,
value: criteria.value,
operator: this.convertToGraphQLOperator(criteria.operator),
};
},
)(queryCriteria);
}
return result;
};
/**
* Convert the query criteria from collection-control to query that is able to work with GraphQL, then merge with static query
* @param queryCriteria The query criteria that is received from collection control
*/
private getGraphQLQuery = (
queryCriteria: CollectionControlQueryCriteria[],
isSearchOr?: boolean,
): string => {
let graphQLQueryCriteria = this.convertToGraphQLQueryCriteria(
queryCriteria,
);
let graphqlQueries: string[] = [];
const graphqlQueryItem = parseQueryCriteriaToGraphQLDoorQuery(
graphQLQueryCriteria,
isSearchOr,
);
if (!isEmpty(graphqlQueryItem)) {
graphqlQueries.push(`${graphqlQueryItem}`);
}
if (this.query && !isEmpty(this.query) && !isNil(this.query)) {
graphqlQueries.push(this.query);
}
if (graphqlQueries.length > 1) {
graphqlQueries = map(query => `(${query})`)(graphqlQueries);
}
return graphqlQueries.join(' && ');
};
/**
* Convert the collection control operator to graphql operator
* @param controlOperator The collection control operator
*/
private convertToGraphQLOperator = (controlOperator: string): string => {
switch (controlOperator) {
case QueryOperator.C: {
return GRAPHQL_QUERY_OPERATOR.CONTAINS;
}
case QueryOperator.E: {
return GRAPHQL_QUERY_OPERATOR.EQUALS;
}
case QueryOperator.NE:
case QueryOperator.GT:
case QueryOperator.GTE:
case QueryOperator.LT:
case QueryOperator.LTE: {
return controlOperator;
}
case QueryOperator.ANY_TRUE: {
return GRAPHQL_QUERY_OPERATOR.ANY_TRUE;
}
case QueryOperator.ANY_FALSE: {
return GRAPHQL_QUERY_OPERATOR.ANY_FALSE;
}
default: {
return GRAPHQL_QUERY_OPERATOR.CONTAINS;
}
}
};
private getOrderConfig = (controlOrder: OrderOption): string => {
const { orderByField, isDescending } = controlOrder;
if (!orderByField || isEmpty(orderByField)) {
return '';
}
let result = orderByField;
if (isDescending === true) {
result = `${result} descending`;
}
return result;
};
}
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/SearchControls/index.tsx
|
/* eslint-disable no-param-reassign */
/* eslint-disable react/prop-types */
import React from 'react';
import { Input, Space, Button } from 'antd';
import { SearchOutlined, ClearOutlined } from '@ant-design/icons';
const getColumnSearchProps = (dataIndex: string, searchInput?: any) => ({
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}) => (
<Space style={{ margin: 10 }}>
<Input
ref={node => {
searchInput = node;
}}
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => confirm()}
allowClear
style={{ width: 188 }}
/>
<Button onClick={() => clearFilters()}>
<ClearOutlined />
</Button>
</Space>
),
filterIcon: filtered => (
<SearchOutlined style={{ color: filtered ? '#00a651' : undefined }} />
),
onFilterDropdownVisibleChange: visible => {
if (visible) {
setTimeout(() => searchInput?.select());
}
},
});
const getLocalColumnSearchProps = (dataIndex: string, searchInput?: any) => ({
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}) => (
<Space style={{ margin: 10 }}>
<Input
ref={node => {
searchInput = node;
}}
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => confirm()}
allowClear
style={{ width: 188 }}
/>
<Button onClick={() => clearFilters()}>
<ClearOutlined />
</Button>
</Space>
),
filterIcon: filtered => (
<SearchOutlined style={{ color: filtered ? '#00a651' : undefined }} />
),
onFilter: (value, record) =>
record[dataIndex] &&
record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
onFilterDropdownVisibleChange: visible => {
if (visible) {
setTimeout(() => searchInput?.select());
}
},
});
export { getColumnSearchProps, getLocalColumnSearchProps };
|
hieutran3010/EnglishOnline
|
src/styles/global-styles.ts
|
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
html,
body {
height: 100%;
width: 100%;
}
.ant-btn .anticon svg {
margin-bottom: 6px
}
.ant-btn-link .anticon svg {
margin-bottom: 3px!important;
}
.ant-avatar .anticon svg {
margin-bottom: 6px
}
.ant-picker-input svg {
margin-bottom: 5px;
}
.data-grid-container .data-grid .cell {
vertical-align: middle;
padding: 0px 5px;
}
.data-grid-container table {
width: 100%
}
.data-grid-container .data-grid .cell > input {
height: 20px;
}
.ant-select-selection-item-remove svg {
margin-bottom: 5px;
}
.ant-select-item-option-state svg {
margin-bottom: 5px;
}
.ant-menu-item svg {
margin-bottom: 7px;
}
.ant-select-auto-complete svg {
margin-bottom: 7px;
}
.ant-picker-suffix svg {
margin-bottom: 5px;
}
.ant-picker-separator svg {
margin-bottom: 5px;
}
.ant-radio-button-wrapper svg {
margin-bottom: 5px;
}
.ant-menu-submenu svg {
margin-bottom: 7px;
}
.ant-statistic-content-prefix svg {
margin-bottom: 6px;
}
.ant-pagination-item-link svg {
margin-bottom: 5px;
}
.ant-table-tbody > tr .ant-table-wrapper:only-child .ant-table td {
background-color: white;
}
.content-container {
.ant-card-actions {
position: sticky;
position: -webkit-sticky;
bottom: 0;
}
.ant-card-head {
position: sticky;
top: 0;
background-color: white;
z-index: 1;
}
}
`;
|
hieutran3010/EnglishOnline
|
src/app/components/collection/DataGrid/utils.tsx
|
<filename>src/app/components/collection/DataGrid/utils.tsx<gh_stars>0
import React from 'react';
import assign from 'lodash/fp/assign';
import map from 'lodash/fp/map';
import moment from 'moment';
import { ColumnDefinition } from './types';
import { COLUMN_TYPES } from './constants';
import { getColumnSearchProps } from './SearchControls';
/**
* Rely on Ant Table Column, add some custom field
*/
const formatColumns = (columns: ColumnDefinition[]) => {
return map((column: ColumnDefinition) => {
if (!column.type) {
return column;
}
let formattedColumn = column;
if (column.type === COLUMN_TYPES.DATE) {
formattedColumn = assign({
render: (text: Date) => (
<span>{text ? moment(text).format('DD-MM-YYYY') : ''}</span>
),
})(formattedColumn);
}
if (column.type === COLUMN_TYPES.DATE_TIME) {
formattedColumn = assign({
render: (text: Date) => (
<span>{text ? moment(text).format('DD-MM-YYYY HH:mm') : ''}</span>
),
})(formattedColumn);
}
if (column.type === COLUMN_TYPES.DATE_WITHOUT_YEAR) {
formattedColumn = assign({
render: (text: Date) => (
<span>{text ? moment(text).format('DD-MM') : ''}</span>
),
})(formattedColumn);
}
if (column.type === COLUMN_TYPES.CURRENCY) {
formattedColumn = assign({
render: (text: number) => (
<span>
{text ? `$ ${text}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '$ 0'}
</span>
),
})(formattedColumn);
}
if (column.type === COLUMN_TYPES.PERCENT) {
formattedColumn = assign({
render: (text: number) => <span>{text ? `${text}%` : ''}</span>,
})(formattedColumn);
}
const searchableColumnTypes = [COLUMN_TYPES.STRING, COLUMN_TYPES.NUMBER];
if (
column.canFilter === true &&
searchableColumnTypes.includes(column.type) &&
(column.dataIndex || column.filterField)
) {
formattedColumn = assign(
getColumnSearchProps(column.dataIndex || column.filterField || ''),
)(formattedColumn);
}
return formattedColumn;
})(columns);
};
export { formatColumns };
|
hieutran3010/EnglishOnline
|
src/app/components/Input/CurrencyInput.tsx
|
<filename>src/app/components/Input/CurrencyInput.tsx
import React, { memo } from 'react';
import { InputNumber } from 'antd';
import { InputNumberProps } from 'antd/lib/input-number';
const CurrencyInput = React.forwardRef((props: InputNumberProps, ref: any) => {
return (
<InputNumber
ref={ref}
formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
parser={(value: any) => value.replace(/\$\s?|(,*)/g, '')}
style={{ width: '100%' }}
{...props}
/>
);
});
export default memo(CurrencyInput);
|
sadnessOjisan/shop.ojisan.io
|
src/components/tags.tsx
|
<reponame>sadnessOjisan/shop.ojisan.io<filename>src/components/tags.tsx
import Link from "next/link";
import { VFC } from "react";
import { tagsStyle } from "../style/tags.css";
type Props = { tags: { id: string; name: string }[]; className?: string };
export const Tags: VFC<Props> = (props) => {
return (
<span className={`${props.className} ${tagsStyle.tips}`}>
{props.tags.map((c) => (
<Link key={c.id} href={`/tags/${c.id}`}>
<a className={tagsStyle.link}>
<div className={tagsStyle.category}>{c.name}</div>
</a>
</Link>
))}
</span>
);
};
|
sadnessOjisan/shop.ojisan.io
|
src/pages/tags/[tid].tsx
|
<filename>src/pages/tags/[tid].tsx
import { GetStaticPaths, GetStaticProps } from "next";
import Head from "next/head";
import Link from "next/link";
import { VFC } from "react";
import { ItemListItem } from "../../components/item-list-item";
import { Layout } from "../../components/layout";
import { META_TAG_CONTENT } from "../../const";
import { repository } from "../../repository";
import { itemDetailPageStyle } from "../../style/item-detail-page.css";
import { tagDetailPageStyle } from "../../style/tag-detail-page.css";
import { ShopItems, Tag } from "../../validator";
type Props = {
data: ShopItems;
tag: Tag;
};
const TagDetail: VFC<Props> = (props) => {
return (
<Layout>
<Head>
<title>{`${props.tag.name} | ${META_TAG_CONTENT.siteTitle}`}</title>
<meta
property="og:url"
content={`${META_TAG_CONTENT.origin}/tags/${props.tag.id}`}
/>
<meta property="og:type" content="website" />
<meta
property="og:title"
content={`${props.tag.name} | ${META_TAG_CONTENT.siteTitle}`}
/>
<meta
property="og:description"
content={`${props.tag.name} を買うなら ${META_TAG_CONTENT.siteTitle}!!sadnessOjisan の不用品を購入できるサイトです。`}
/>
<meta property="og:site_name" content={META_TAG_CONTENT.siteTitle} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content={META_TAG_CONTENT.twitterName} />
<meta name="twitter:creator" content={META_TAG_CONTENT.twitterName} />
</Head>
<div className={itemDetailPageStyle.wrapper}>
<h2 className={tagDetailPageStyle.title}>{props.tag.name}</h2>
<div className={tagDetailPageStyle.items}>
{props.data.contents.map((d) => (
<Link href={`/items/${d.id}`} key={d.id}>
<a className={tagDetailPageStyle.itemLink}>
<ItemListItem
className={tagDetailPageStyle.itemListWrapper}
data={{
id: d.id,
name: d.name,
price: d.price,
categories: d.categories,
images: d.images,
status: d.status,
}}
/>
</a>
</Link>
))}
</div>
</div>
</Layout>
);
};
export const getStaticPaths: GetStaticPaths = async () => {
const data = await repository.getAllTags();
const ids = data.contents.map((d) => d.id);
// Get the paths we want to pre-render based on posts
const paths = ids.map((id) => ({
params: { tid: id },
}));
return { paths, fallback: false };
};
export const getStaticProps: GetStaticProps<Props> = async (context) => {
const tagId = context.params ? context.params["tid"] : undefined;
if (typeof tagId !== "string") throw new Error("invalid path");
const data = await repository.getItemsByTagId(tagId);
const tag = await repository.getTagById(tagId);
return {
props: {
data,
tag,
},
};
};
export default TagDetail;
|
sadnessOjisan/shop.ojisan.io
|
src/style/tags.css.ts
|
<gh_stars>1-10
import { style } from "@vanilla-extract/css";
export const tagsStyle = {
tips: style({ display: "flex" }),
category: style({
background: "lightgray",
padding: "2px 8px",
marginLeft: "4px",
borderRadius: "4px",
fontSize: 12,
":first-child": {
marginLeft: 0,
},
}),
link: style({
color: "black",
textDecoration: "none",
":visited": {
color: "black",
},
}),
};
|
sadnessOjisan/shop.ojisan.io
|
src/pages/about.tsx
|
<reponame>sadnessOjisan/shop.ojisan.io<filename>src/pages/about.tsx<gh_stars>1-10
import Head from "next/head";
import { VFC } from "react";
import { Layout } from "../components/layout";
import { META_TAG_CONTENT } from "../const";
import { aboutPageStyles } from "../style/about-page.css";
const TermPage: VFC = () => (
<div>
<Head>
<title>{`About | ${META_TAG_CONTENT.siteTitle}`}</title>
<meta property="og:url" content={`${META_TAG_CONTENT.origin}/about`} />
<meta property="og:type" content="website" />
<meta
property="og:title"
content={`about | ${META_TAG_CONTENT.siteTitle}`}
/>
<meta property="og:site_name" content={META_TAG_CONTENT.siteTitle} />
</Head>
<Layout>
<div className={aboutPageStyles.wrapper}>
<h2 className={aboutPageStyles.midashi}>このサイトについて</h2>
<p className={aboutPageStyles.text}>
<a
href="https://twitter.com/sadnessOjisan"
className={aboutPageStyles.link}
>
sadnessOjisan
</a>
はそろそろ引っ越したいです。荷物を減らしたいです。なので僕の荷物の不用品情報サイトを作りました。通信販売サイトではありません。
</p>
<p className={aboutPageStyles.text}>
<a href="https://microcms.io/" className={aboutPageStyles.link}>
CMS
</a>
に在庫を補充・更新したらHPが更新されるJAMStackサイトです。決済手段は実装していないため、TwitterDMなどでのやりとりにて決済・配送をします。
</p>
<h2 className={aboutPageStyles.midashi}>ルール</h2>
<p className={aboutPageStyles.text}>
欲しい商品がある場合、販売者の何らかの連絡方法(Twitter, Discord,
Facebook Messenger
など)に連絡をください。「商談中」ステータスとして扱います。
</p>
<p className={aboutPageStyles.text}>
「商談中」ステータスでは、受け渡し方法・価格・配送方法・返品についての相談・確認を行います。この段階でキャンセルは可能です。もし双方ともに商談内容に納得できたら、商談を確定させ、「配送中」ステータスに移行します。なお配送中ステータスになると、原則としてキャンセルはできません。
</p>
<p className={aboutPageStyles.text}>
リアルタイムでCMSを更新しない・されない都合上、同時に申し込みが複数件入る可能性がありますが、その際に誰を優先するかは販売者側で決めます。
</p>
<p className={aboutPageStyles.text}>
基本的に配送は、
<a
href="https://www.kuronekoyamato.co.jp/ytc/customer/send/sp/"
className={aboutPageStyles.link}
>
匿名配送(LINEを利用)
</a>
にてお願いします。ただし、販売者とプライベートで会ったことがある方は手渡しや他の配送方法でも可能であり、販売者としても助かります。
</p>
<p className={aboutPageStyles.text}>
申込者からの連絡に応じて価格や配送時期を決める都合上、特定商取引法に基づく表記に関する事項は、その連絡の際に問い合わせていただけると遅延なく提示いたします。
</p>
<p className={aboutPageStyles.text}>
堅苦しいやりとりはしたくないので、知り合いを優先して取引します。
</p>
<p className={aboutPageStyles.text}>
このルールは予告なく変更する可能性があります。
</p>
<h2 className={aboutPageStyles.midashi}>特定商取引法に基づく表記</h2>
<p className={aboutPageStyles.text}>
そもそも通信販売サイトではありませんが、通信販売サイトであると仮定すると以下の通りとなります。
</p>
<p className={aboutPageStyles.text}>URL: https://shop.ojisan.io</p>
<p className={aboutPageStyles.text}>EMail: <EMAIL></p>
<p className={aboutPageStyles.text}>
販売価格: 各商品ページの参考価格に基づき、協議のもと決定する
</p>
<p className={aboutPageStyles.text}>
支払い方法: PayPay / LinePay / 銀行振り込み による先払い
</p>
<p className={aboutPageStyles.text}>
商品代金以外の必要経費: 振込手数料、決済手数料などの支払い手数料
</p>
<p className={aboutPageStyles.text}>
商品引き渡し時期: 販売者・購入者の協議のもと決定する
</p>
<p className={aboutPageStyles.text}>
商品の引き渡し方法: 郵送・もしくは手渡し
</p>
<p className={aboutPageStyles.text}>
不良品について: 1週間以内であれば返品可能
</p>
<p className={aboutPageStyles.text}>
返品について: 不良品の場合を除いて不可
</p>
<p className={aboutPageStyles.text}>
※上記以外の事項に関しましては、お取引の際に請求があれば遅延なく提示いたします。
</p>
<h2 className={aboutPageStyles.midashi}>プライバシーポリシー</h2>
<p className={aboutPageStyles.text}>
商談のため購入希望者の氏名・メールアドレス・LINE
IDを収集します。この収集した情報は、 shop.ojisan.io
における購入手続きの遂行以外に利用はいたしません。
</p>
</div>
</Layout>
</div>
);
export default TermPage;
|
LazyDuke/ts-promise
|
src/typescript/index.ts
|
<reponame>LazyDuke/ts-promise
import isArrayLikeObject from 'lodash.isarraylikeobject'
class TsPromise {
static PENDING = 'PENDING'
static FULFILLED = 'FULFILLED'
static REJECTED = 'REJECTED'
static resolvePromise: ResolvePromise = (
anotherPromise,
x,
resolve,
reject
) => {
// 如果 onFulfilled 或者 onRejected 返回一个值 x ,则运行下面的 Promise 解决过程:[[Resolve]](promise2, x)
// 运行 [[Resolve]](promise, x) 需遵循以下步骤:
// 如果 promise 和 x 指向同一对象,以 TypeError 为拒因拒绝执行 promise 以防止循环引用
if (anotherPromise === x) {
return reject(new TypeError('Chaining cycle detected for promise'))
}
// 如果 x 为 Promise ,则使 promise 接受 x 的状态
if (x instanceof TsPromise || x instanceof Promise) {
return x.then(
(
// 如果 x 处于执行态,用相同的值执行 promise
value: any
) => {
return TsPromise.resolvePromise(
anotherPromise,
value,
resolve,
reject
)
},
(
// 如果 x 处于拒绝态,用相同的拒因拒绝 promise
reason: any
) => {
return reject(reason)
}
)
// 如果 x 为对象或者函数
} else if (
x !== null &&
(typeof x === 'object' || typeof x === 'function')
) {
let called = false
try {
// 把 x.then 赋值给 then(这步我们先是存储了一个指向 x.then 的引用,然后测试并调用该引用,以避免多次访问 x.then 属性。这种预防措施确保了该属性的一致性,因为其值可能在检索调用时被改变。)
const then = x.then
// 如果 then 是函数,将 x 作为函数的作用域 this 调用之。传递两个回调函数作为参数,
if (typeof then === 'function') {
return then.call(
x,
(
// 第一个参数叫做 resolvePromise ,
value: any
) => {
// 如果 resolvePromise 和 rejectPromise 均被调用,或者被同一参数调用了多次,则优先采用首次调用并忽略剩下的调用
if (called) {
return
}
called = true
// 如果 resolvePromise 以值 y 为参数被调用,则运行 [[Resolve]](promise, y)
return TsPromise.resolvePromise(
anotherPromise,
value,
resolve,
reject
)
},
(
// 第二个参数叫做 rejectPromise
reason: any
) => {
// 如果 resolvePromise 和 rejectPromise 均被调用,或者被同一参数调用了多次,则优先采用首次调用并忽略剩下的调用
if (called) {
return
}
called = true
// 如果 rejectPromise 以拒因 r 为参数被调用,则以拒因 r 拒绝 promise
return reject(reason)
}
)
} else {
//如果 then 不是函数,以 x 为参数执行 promise
return resolve(x)
}
} catch (error) {
// 如果调用 then 方法抛出了异常 e, 如果 resolvePromise 或 rejectPromise 已经被调用,则忽略之
if (called) {
return
}
called = true
// 如果取 x.then 的值时抛出错误 e ,则以 e 为拒因拒绝 promise
return reject(error)
}
} else {
// 如果 x 不为对象或者函数,以 x 为参数执行 promise
return resolve(x)
}
}
static resolve: TsPromiseResolve = value =>
new TsPromise((resolve, reject) => {
return resolve(value)
})
static reject: TsPromiseReject = reason =>
new TsPromise((resolve, reject) => {
return reject(reason)
})
static all: All = promises => {
if (!isArrayLikeObject(promises)) {
throw new TypeError(
`${
typeof promises === 'undefined' ? '' : typeof promises
} ${promises} is not iterable (cannot read property Symbol(Symbol.iterator))`
)
}
// 实现的 promise 基于 macroTask 的 setTimeout 实现,需要 async/await 调节执行顺序
// 原生的 promise 基于 microTask 实现,执行顺序是正确的,不需要 async/await
return new TsPromise(async (resolve, reject) => {
const result = []
for (const promise of promises) {
await TsPromise.resolve(promise).then(resolvePromise, rejectPromise)
}
return resolve(result)
function resolvePromise(value: any) {
if (value instanceof TsPromise || value instanceof Promise) {
value.then(resolvePromise, rejectPromise)
} else {
result.push(value)
}
}
function rejectPromise(reason: any) {
return reject(reason)
}
})
}
static race: Race = promises => {
if (!isArrayLikeObject(promises)) {
throw new TypeError(
`${
typeof promises === 'undefined' ? '' : typeof promises
} ${promises} is not iterable (cannot read property Symbol(Symbol.iterator))`
)
}
return new TsPromise((resolve, reject) => {
for (const promise of promises) {
TsPromise.resolve(promise).then(
value => {
return resolve(value)
},
reason => {
return reject(reason)
}
)
}
})
}
static defer = () => {
let dfd: any = {}
dfd.promise = new TsPromise((resolve, reject) => {
dfd.resolve = resolve
dfd.reject = reject
})
return dfd
}
static deferred = TsPromise.defer
value: any
reason: any
status = TsPromise.PENDING
onFulfilledCallbacks: onFulfilledCallback[] = []
onRejectedCallbacks: onRejectedCallback[] = []
constructor(executor: Executor) {
// 参数校验
if (typeof executor !== 'function') {
throw new TypeError(`Promise resolver ${executor} is not a function`)
}
// 失败后的一系列操作(状态的改变,失败回调的执行)
const reject: Reject = reason => {
// 只有处于 pending 状态的 promise 能调用 resolve
if (this.status === TsPromise.PENDING) {
// reject 调用后,status 转为 rejected
this.status = TsPromise.REJECTED
// 储存 rejected 的拒因
this.reason = reason
// 一旦 reject 执行,调用储存在失败回调数组里的回调
this.onRejectedCallbacks.forEach(onRejected => onRejected())
}
}
// 成功后的一系列操作(状态的改变,成功回调的执行)
const resolve: Resolve = x => {
const __resolve = (value: any) => {
// 只有处于 pending 状态的 promise 能调用 resolve
if (this.status === TsPromise.PENDING) {
// resolve 调用后,status 转为 fulfilled
this.status = TsPromise.FULFILLED
// 储存 fulfilled 的终值
this.value = value
// 一旦 resolve 执行,调用储存在成功回调数组里的回调
this.onFulfilledCallbacks.forEach(onFulfilled => onFulfilled())
}
}
return TsPromise.resolvePromise.call(this, this, x, __resolve, reject)
}
try {
executor(resolve, reject)
} catch (error) {
// 如果 executor 执行报错,则直接执行 reject
reject(error)
}
}
/**
* 一个 promise 必须提供一个 then 方法以访问其当前值、终值和拒因
*/
then: Then = (onFulfilled, onRejected) => {
// 如果 onFulfilled 不是函数,其必须被“忽略”
onFulfilled =
typeof onFulfilled === 'function' ? onFulfilled : value => value
// 如果 onFulfilled 不是函数,其必须被“忽略”
onRejected =
typeof onRejected === 'function'
? onRejected
: error => {
throw error
}
// then 方法必须返回一个 promise 对象
const anotherPromise = new TsPromise((resolve, reject) => {
// 封装处理链式调用的方法
const handle: Handle = (fn, argv) => {
// 确保 onFulfilled 和 onRejected 方法异步执行
setTimeout(() => {
try {
const x = fn(argv)
return TsPromise.resolvePromise(anotherPromise, x, resolve, reject)
} catch (error) {
return reject(error)
}
})
}
// 当 status 为执行态(Fulfilled)时
if (this.status === TsPromise.FULFILLED) {
// 则执行 onFulfilled,value 作为第一个参数
handle(onFulfilled, this.value)
}
// 当 status 为拒绝态(Rejected)时
if (this.status === TsPromise.REJECTED) {
// 则执行 onRejected,reason 作为第一个参数
handle(onRejected, this.reason)
}
// 当 status 为 Pending 时
if (this.status === TsPromise.PENDING) {
// 将 onFulfilled 存入成功回调数组
this.onFulfilledCallbacks.push(() => {
handle(onFulfilled, this.value)
})
// 将 onRejected 存入失败回调数组
this.onRejectedCallbacks.push(() => {
handle(onRejected, this.reason)
})
}
})
return anotherPromise
}
catch: Catch = onRejected => {
return this.then(null, onRejected)
}
finally: Finally = fn => {
return this.then(
(value: any) => {
setTimeout(fn)
return value
},
(reason: any) => {
setTimeout(fn)
throw reason
}
)
}
}
export default TsPromise
interface Executor {
(resolve: Resolve, reject?: Reject): void
}
interface Resolve {
(value?: any | PromiseLike<any>): void
}
interface Reject {
(reason?: any): void
}
interface Then {
(onFulfilled: OnFulfilled, onRejected: OnRejected): TsPromise
}
interface Catch {
(onRejected: OnRejected): TsPromise
}
interface Finally {
(fn: Function): TsPromise
}
interface Handle {
(fn: OnFulfilled | OnRejected, argv: any): void
}
interface OnFulfilled {
(value?: any): any
}
interface onFulfilledCallback {
(): void
}
interface OnRejected {
(error: Error): void
}
interface onRejectedCallback {
(): void
}
interface ResolvePromise {
(anotherPromise: TsPromise, x: any, resolve: Resolve, reject: Reject): void
}
interface TsPromiseResolve {
(value?: any | PromiseLike<any>): TsPromise
}
interface TsPromiseReject {
(reason?: any): TsPromise
}
interface All {
(promises: TsPromise[]): TsPromise
}
interface Race {
(promises: TsPromise[]): TsPromise
}
|
seriouslag/vue-tagsinput
|
src/index.ts
|
<reponame>seriouslag/vue-tagsinput
/**
* This file is the main import for the built library
*/
import { VueConstructor } from 'vue';
import TagsInput from './TagsInput.vue';
export * from './Tag';
export { TagsInput };
export function install (Vue: VueConstructor) {
Vue.component('TagsInput', TagsInput);
}
export default install;
|
seriouslag/vue-tagsinput
|
src/shims-vue.d.ts
|
/* Shim file to help typescript understand vue files */
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/news/news.component.ts
|
import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core';
import { NewsConfig } from '../news.interface';
import { NgElement, NgElementStrategy } from '@angular/elements';
import { Subscription } from 'rxjs';
@Component({
// selector: 'team-news',
template: `
<div class="card card-plain card-blog">
<div class="card-body">
<h6 class="category text-info">NEWS WIDGET FROM TEAMS</h6>
<h4 class="card-title">
<a href="javascript:void(0)">
{{ title }}
</a>
</h4>
<p class="card-description">
{{ content }}
</p>
<div class="author">
<span> {{ author }} </span>
</div>
</div>
</div>
`,
styles: [
`
.card-blog{
border-bottom:1px solid rgba(255, 255, 255, 0.6);
border-radius:0px;
}
`
],
encapsulation: ViewEncapsulation.Emulated
})
export class NewsComponent implements OnInit {
/* ngElementStrategy: NgElementStrategy;
protected ngElementEventsSubscription: Subscription | null;
newsMessage: string; */
newsMessage: string;
@Input() title: string;
@Input() content: string;
@Input() author: string;
@Input()
set message(message: string) {
this.newsMessage = message;
this.hurray(message);
}
get message(): string {
return this.newsMessage;
}
ngOnInit() {}
/* constructor() {
// super();
} */
hurray(message) {
console.log(`I got a MSG ${message}`);
}
/* connectedCallback(){
console.log(`news connectedCallback`);
}
disconnectedCallback(){
console.log(`news disconnectedCallback`);
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(
`Custom News element attributes changed. ${name} / ${oldValue} / ${newValue} `
);
} */
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
src/app/models/players.interface.ts
|
export interface PlayersRoot {
error: string;
total: string;
data: PlayersInfo[];
}
export interface PlayersInfo {
id: string;
firstname: string;
lastname: string;
shirtnumber: string;
position: string;
quote: string;
statusSent?: boolean;
skills: PlayerStats[];
stats: PlayerStats[];
}
export interface PlayerStats {
key: string;
value: string;
icon?: string;
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/team.service.ts
|
<gh_stars>1-10
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TeamService {
private state$ = new Subject<any>();
constructor() {}
public getState(): Observable<any> {
return this.state$.asObservable();
}
public setState(state: string) {
this.state$.next(state);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
src/app/navbar/navbar.component.ts
|
<filename>src/app/navbar/navbar.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StateService } from '../state.service';
import { Subscription } from 'rxjs';
import { AcknowledgementStatus } from '../models/acknowledgement.interface';
import { PlayersInfo } from '../models/players.interface';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit, OnDestroy {
private sidebarVisible = false;
public showStatus: boolean;
playerSubscription: Subscription;
playersInfo: PlayersInfo[];
subscription: Subscription;
// public selectionInfos: AcknowledgementStatus[];
public selectionInfos: any[];
constructor(private stateService: StateService) {}
ngOnInit(): void {
this.initNav();
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
this.playerSubscription.unsubscribe();
}
public initNav() {
this.showStatus = false;
this.getPlayers();
this.subscription = this.stateService.getMessage().subscribe(data => {
if (typeof data !== 'string') {
this.changeStatus(data);
}
});
}
private changeStatus(data: AcknowledgementStatus) {
this.selectionInfos.find(
selectionInfos => selectionInfos.id === data.id
).status = data.status;
this.selectionInfos.find(
selectionInfos => selectionInfos.id === data.id
).received = true;
this.showStatus = true;
/* for (const i in this.selectionInfos) {
if (this.selectionInfos[i].id === data.id) {
this.selectionInfos[i].status = data.status;
this.selectionInfos[i].received = true;
this.showStatus = true;
break; // Stop this loop, we found it!
}
} */
}
sidebarToggle() {
const body = document.getElementsByTagName('body')[0];
if (this.sidebarVisible === false) {
body.classList.add('nav-open');
this.sidebarVisible = true;
} else {
this.sidebarVisible = false;
body.classList.remove('nav-open');
}
}
sendState(msg) {
this.stateService.setState(msg);
}
getPlayers() {
this.playerSubscription = this.stateService
.getPlayers()
.subscribe(players => {
this.selectionInfos = players.data;
console.log(this.selectionInfos);
});
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/news/src/app/app.module.ts
|
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA, Injector } from '@angular/core';
import { RouterModule } from '@angular/router';
import { createCustomElement } from '@angular/elements';
import { NewsPageComponent } from './news-page/news-page.component';
import { CoreComponent } from './core/core.component';
import { AppComponent } from './app.component';
import { NewsComponent } from './news/news.component';
import { EmptyComponent } from './empty/empty.component';
@NgModule({
declarations: [AppComponent, NewsComponent, EmptyComponent, NewsPageComponent, CoreComponent],
imports: [
BrowserModule,
RouterModule.forRoot(
[
{
path: 'news',
component: CoreComponent,
children: [
{ path: 'newsPage', component: NewsPageComponent }
]
},
{ path: '**', component: EmptyComponent }
],
{ useHash: true }
)
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [],
bootstrap: [],
entryComponents: [AppComponent, NewsComponent]
})
export class AppModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const newsAppElement = createCustomElement(AppComponent, {
injector: this.injector
});
customElements.define('news-root', newsAppElement);
const newsElement = createCustomElement(NewsComponent, {
injector: this.injector
});
customElements.define('news-widget', newsElement);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/core/core.component.ts
|
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
@Component({
// selector: 'team-core',
template: `
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<div class="framework">
<img alt="..." src="assets/img/angular.png" class="avatar"/>
</div>
<h5 class="card-category">Team Micro App</h5>
<h3 class="card-title">Team</h3>
</div>
<div class="card-body">
<ul class="nav nav-pills">
<li class="nav-item">
<a routerLink="fixture" routerLinkActive="active-route" class="nav-link">Fixture</a>
</li>
<li class="nav-item">
<a routerLink="standings" routerLinkActive="active-route" class="nav-link">Standings</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<router-outlet></router-outlet>
</div>
<div class="col-md-4">
<div class="frameworkJS">
<img alt="..." src="assets/img/javascript.png" />
</div>
<h4 class="text-info">Team Overall Performance</h4>
<skill-progress label="Wins" progress="50"></skill-progress>
<skill-progress label="Passing" progress="90"></skill-progress>
<skill-progress label="Shooting" progress="70"></skill-progress>
<skill-progress label="dribbling" progress="60"></skill-progress>
<skill-progress label="tackling" progress="40"></skill-progress>
<news-widget title="Maecenas congue, ante quis dignissim imperdiet" content=" Proin maximus sapien eu interdum pharetra. In sit amet urna vitae orci luctus porttitor vitae lacinia ligula. Suspendisse molestie justo a ante iaculis, a dignissim lectus pulvinar. Integer fermentum urna at odio commodo, non vehicula lacus mattis. Pellentesque congue neque ac justo ultricies fermentum." author="<NAME>"></news-widget>
</div>
</div>
`,
styles: [`
.framework{
float:left;
width:30px;
height:30px;
position: relative;
left: -10px;
}
.frameworkJS {
float: left;
width: 30px;
height: 30px;
position: absolute;
left: 15px;
top: 0px;
}
.text-info{
margin-left:40px;
}
.frameworkJS img {
border-radius: 0px;
}
.navPills {
border-bottom: 4px solid #c70101;
}
.active-route {
color: #ffffff;
background-color: transparent;
border-bottom: 4px solid #e14eca;
}
`]
})
export class CoreComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/fixtures/fixtures.component.ts
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'team-fixtures',
templateUrl: './fixtures.component.html',
styleUrls: ['./fixtures.component.scss']
})
export class FixturesComponent implements OnInit {
fixtures: any[];
constructor() {}
ngOnInit(): void {
this.fixtures = [{
date: 'Sat 20 Jun',
home: 'EDGE FC',
away: 'DEV FC',
time: '20:00'
}, {
date: 'Sun 21 Jun',
home: 'Build FC',
away: 'EDGE FC',
time: '20:00'
}, {
date: 'Sat 27 Jun',
home: 'EDGE FC',
away: 'Test FC',
time: '20:00'
}, {
date: 'Sun 28 Jun',
home: 'Build FC',
away: 'EDGE FC',
time: '20:00'
}];
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/news/src/app/news/news.component.ts
|
import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core';
@Component({
// selector: 'team-news',
template: `
<div class="card card-plain card-blog">
<div class="card-body">
<div class="framework"><img alt="..." src="assets/img/angular.png" class="avatar"
/></div> <h6 class="category text-info">NEWS Web Component from project: news</h6>
<h4 class="card-title">
<a href="javascript:void(0)">
{{ title }}
</a>
</h4>
<p class="card-description">
{{ content }}
</p>
<div class="author">
<span> {{ author }} </span>
</div>
</div>
</div>
`,
styles: [
`
.card-blog{
border-bottom:1px solid rgba(255, 255, 255, 0.3);
border-radius:0px;
}
.framework{
float:left;
width:30px;
height:30px;
position: relative;
left: -10px;
}
`
],
encapsulation: ViewEncapsulation.Emulated
})
export class NewsComponent implements OnInit {
newsMessage: string;
@Input() title: string;
@Input() content: string;
@Input() author: string;
@Input()
set message(message: string) {
this.newsMessage = message;
this.hurray(message);
}
get message(): string {
return this.newsMessage;
}
ngOnInit() {}
/* constructor() {
// super();
} */
hurray(message) {
console.log(`I got a MSG ${message}`);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/app.module.ts
|
<reponame>sathyaleo08/MicroFrotEndWithWebComponent-code
import { TeamService } from './team.service';
import { FixturesComponent } from './fixtures/fixtures.component';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { NewsComponent } from './news/news.component';
import { CoreComponent } from './core/core.component';
import { createCustomElement } from '@angular/elements';
import { EmptyComponent } from './empty/empty.component';
import { StandingsComponent } from './standings/standings.component';
import { LineUpComponent } from './line-up/line-up.component';
@NgModule({
declarations: [
AppComponent,
FixturesComponent,
NewsComponent,
CoreComponent,
EmptyComponent,
StandingsComponent,
LineUpComponent
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(
[
{
path: 'team',
component: CoreComponent,
children: [
{ path: 'fixture', component: FixturesComponent },
{ path: 'standings', component: StandingsComponent },
{ path: 'lineUp', component: LineUpComponent }
]
},
{ path: '**', component: EmptyComponent }
],
{ useHash: true }
)
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [TeamService],
entryComponents: [AppComponent]
})
export class AppModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const teamAppElement = createCustomElement(AppComponent, {
injector: this.injector
});
customElements.define('team-root', teamAppElement);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/news/src/app/core/core.component.ts
|
<filename>projects/news/src/app/core/core.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
// selector: 'news-core',
template: `
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header">
<div class="framework"><img alt="..." src="assets/img/angular.png" class="avatar"
/></div> <h5 class="card-category">NEWS Micro App</h5>
<h3 class="card-title">NEWS</h3>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<router-outlet></router-outlet>
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-6">
<div class="framework-JS"><img alt="..." src="assets/img/javascript.png" class="avatar"
/></div>
<card-stats label="ranking" value="8" icon="fa-trophy"></card-stats>
</div>
<div class="col-md-6">
<div class="framework-JS"><img alt="..." src="assets/img/javascript.png" class="avatar"
/></div>
<card-stats label="standing" value="3" icon="fa-futbol"></card-stats>
</div>
</div>
<news-widget title="Maecenas congue, ante quis dignissim imperdiet" content=" Proin maximus sapien eu interdum pharetra. In sit amet urna vitae orci luctus porttitor vitae lacinia ligula. Suspendisse molestie justo a ante iaculis, a dignissim lectus pulvinar. Integer fermentum urna at odio commodo, non vehicula lacus mattis. Pellentesque congue neque ac justo ultricies fermentum." author="<NAME>"></news-widget>
</div>
</div>
`,
styles: [`
.framework-JS{
position: absolute;
z-index: 2;
}
.framework-JS .avatar{
width: 25px;
height: 25px;
overflow: hidden;
border-radius: 0px;
margin-bottom: 15px;
}
.framework{
float:left;
width:30px;
height:60px;
position: relative;
left: -10px;
}
.navPills {
border-bottom: 4px solid #c70101;
}
.active-route {
color: #ffffff;
background-color: transparent;
border-bottom: 4px solid #e14eca;
}
`]
})
export class CoreComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/news/src/app/app.component.ts
|
<reponame>sathyaleo08/MicroFrotEndWithWebComponent-code
import {
Component,
OnInit,
Input,
Output,
EventEmitter,
ViewEncapsulation
} from '@angular/core';
import { Router } from '@angular/router';
@Component({
// selector: 'news-root',
template: `
<div>
<router-outlet></router-outlet>
</div>
`,
encapsulation: ViewEncapsulation.Emulated
})
export class AppComponent implements OnInit {
title: any;
@Input('state')
set state(state: any) {
// this.title = state;
console.log(`News received new state: ${state}`);
console.log(state);
this.title = state;
}
@Output() messageToClub = new EventEmitter<any>();
constructor(
private router: Router
) {}
ngOnInit() {
this.router.initialNavigation(); // Manually triggering initial navigation for @angular/elements ?
this.router.navigate(['/news/newsPage']);
// just for demonstration!
setTimeout(() => {
console.log(
`NEWS sending signal after 2000ms! ${this.title} -----------------------------------`
);
this.messageToClub.next(`NEWS initialized!`);
}, 2000);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/news/src/app/news-page/news-page.component.ts
|
import { Component, OnInit } from '@angular/core';
@Component({
// tslint:disable-next-line: component-selector
selector: 'news-page',
template: `
<div class="row">
<div class="col-sm-12">
<div class="card card-blog card-plain blog-horizontal">
<div class="row">
<div class="col-lg-4">
<div class="card-image">
<a href="javascript:void(0)"
><img class="img rounded" src="assets/img/news2.jpg"
/></a>
</div>
</div>
<div class="col-lg-8">
<div class="card-body">
<h3 class="card-title">
<a href="javascript:void(0)">
Donec maximus sapien eget libero fringilla
</a>
</h3>
<p class="card-description">
Etiam iaculis dapibus malesuada. Suspendisse rhoncus mi quis arcu
aliquet, eget tincidunt dui hendrerit. Proin molestie enim urna, a
venenatis risus porttitor vitae. Sed ac sollicitudin neque. Proin
scelerisque ornare convallis. Nulla facilisi. Pellentesque
ultricies rhoncus sollicitudin. Nunc id iaculis ligula, sed
aliquam risus. Etiam nec dui eros....
<a href="javascript:void(0)"> Read More </a>
</p>
<div class="author">
<img
alt="..."
class="avatar img-raised"
src="assets/img/james.jpg"
/>
<div class="text">
<span class="name"><NAME></span>
<div class="meta">2h</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card card-blog card-plain blog-horizontal">
<div class="row">
<div class="col-lg-4">
<div class="card-image">
<a href="javascript:void(0)"
><img class="img rounded" src="assets/img/news3.jpg"
/></a>
</div>
</div>
<div class="col-lg-8">
<div class="card-body">
<h3 class="card-title">
<a href="javascript:void(0)">
Aliquam orci nec, cursus leo
</a>
</h3>
<p class="card-description">
Nunc non gravida quam. Phasellus commodo elit a erat consectetur
ullamcorper. Ut porta congue risus, vel egestas arcu dignissim
non. Donec aliquam nunc non lacus suscipit blandit. Morbi vel
lacus lobortis, imperdiet felis sed, rutrum diam. Curabitur
pulvinar lorem sit amet sem fringilla, sit amet pulvinar quam
sagittis. Sed sagittis ipsum at iaculis viverra....
<a href="javascript:void(0)"> Read More </a>
</p>
<div class="author">
<img
alt="..."
class="avatar img-raised"
src="assets/img/mike.jpg"
/>
<div class="text">
<span class="name"><NAME> </span>
<div class="meta">3 day ago</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
`,
styles: [
`
.card-blog.blog-horizontal .author .avatar {
width: 40px;
height: 40px;
position: absolute;
}
.card-blog.blog-horizontal .author {
position: relative;
display: inline-block;
text-align: left;
margin: 20px auto 0;
}
.card-blog.blog-horizontal .author .text {
position: relative;
left: 55px;
top: 1px;
}
`
],
})
export class NewsPageComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
src/app/app.component.ts
|
import { AcknowledgementStatus } from './models/acknowledgement.interface';
import { Component, OnInit } from '@angular/core';
import { element } from 'protractor';
import { Subject } from 'rxjs';
import { StateService } from './state.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'football-club';
config = {
team: {
loaded: false,
path: 'team/main.js',
element: 'team-root'
},
players: {
loaded: false,
path: 'players/main.js',
element: 'players-root'
},
news: {
loaded: false,
path: 'news/main.js',
element: 'news-root'
}
};
constructor(private stateService: StateService) {}
ngOnInit() {
this.load('news');
this.load('team');
this.load('players');
this.loadWebComponentLibrary();
}
loadWebComponentLibrary() {
const content = document.getElementById('content');
const skillsProgressScript = document.createElement('script');
skillsProgressScript.src =
'assets/webComponentLibraries/skills-progress.js';
content.appendChild(skillsProgressScript);
const cardStatsScript = document.createElement('script');
cardStatsScript.src = 'assets/webComponentLibraries/card-stats.js';
content.appendChild(cardStatsScript);
}
load(name: string): void {
console.log('Load ', name);
const configItem = this.config[name];
if (configItem.loaded) {
return;
}
const content = document.getElementById('content');
const script = document.createElement('script');
script.src = configItem.path;
content.appendChild(script);
const microAppElement: HTMLElement = document.createElement(
configItem.element
);
content.appendChild(microAppElement);
microAppElement.addEventListener('messageToClub', msg =>
this.handleMessage(msg)
);
microAppElement.setAttribute('state', 'init');
script.onerror = () => console.error(`error loading ${configItem.path}`);
this.stateService.registerClient(microAppElement);
}
handleMessage(msg): void {
console.log('Club received message: ', msg.detail);
this.stateService.setMessage(msg.detail);
}
sendState(msg) {
this.stateService.setState(msg);
}
simulateMsg(flag: boolean) {
const msgToSimulate: AcknowledgementStatus = {
id: 'EDGE_02',
name: '<NAME>',
status: flag
};
this.stateService.setMessage(msgToSimulate);
}
simulateString() {
this.stateService.setMessage('init');
}
simulateAMsg(flag: boolean) {
const msgAToSimulate: AcknowledgementStatus = {
id: 'EDGE_11',
name: '<NAME>',
status: flag
};
this.stateService.setMessage(msgAToSimulate);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/news.interface.ts
|
export interface NewsConfig{
title: string;
content: string;
author: string;
channel: string;
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/standings/standings.component.ts
|
import { Component, OnInit, OnDestroy } from '@angular/core';
import { TeamService } from '../team.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'team-standings',
templateUrl: './standings.component.html',
styleUrls: ['./standings.component.scss']
})
export class StandingsComponent implements OnInit, OnDestroy {
subscription: Subscription;
constructor(private teamService: TeamService) {
}
ngOnInit(): void {
this.subscription = this.teamService.getState().subscribe(data => {
console.log('Init ' + data);
});
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/players/src/app/detail/detail.component.ts
|
<filename>projects/players/src/app/detail/detail.component.ts<gh_stars>1-10
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { PlayersService } from '../players.service';
import { PlayersInfo } from '../models/players.interface';
@Component({
selector: 'players-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnInit, OnDestroy {
webComponentLoaded: boolean;
playerSubscription: Subscription;
playersInfo: PlayersInfo[];
constructor(private playerService: PlayersService) {}
ngOnInit(): void {
this.webComponentLoaded = false;
// this.loadWebComponentLibrary();
this.getPlayers();
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.playerSubscription.unsubscribe();
}
getPlayers() {
this.playerSubscription = this.playerService
.getPlayers()
.subscribe(players => {
this.playersInfo = players.data;
console.log(this.playersInfo);
});
}
loadWebComponentLibrary() {
if (this.webComponentLoaded) {
return;
}
const content = document.getElementById('cardLoader');
const cardStatsScript = document.createElement('script');
cardStatsScript.src = 'assets/webComponentLibraries/card-stats.js';
content.appendChild(cardStatsScript);
this.webComponentLoaded = true;
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/app.component.ts
|
import { TeamService } from './team.service';
import {
Component,
OnInit,
Input,
Output,
EventEmitter,
ViewEncapsulation
} from '@angular/core';
import { Router } from '@angular/router';
@Component({
// selector: 'team-root',
template: `
<div>
<router-outlet></router-outlet>
</div>
`,
encapsulation: ViewEncapsulation.Emulated
})
export class AppComponent implements OnInit {
@Input('state')
set state(state: any) {
console.log(`Team received new state: ${state}`);
console.log(state);
this.teamService.setState(state);
}
@Output() messageToClub = new EventEmitter<any>();
constructor(
private router: Router,
private teamService: TeamService
) {}
ngOnInit() {
this.router.initialNavigation(); // Manually triggering initial navigation for @angular/elements ?
// this.router.navigate(['/team/fixture']);
// just for demonstration!
setTimeout(() => {
console.log(
`Team sending signal after 2000ms! ${this.state} -----------------------------------`
);
this.messageToClub.next(`Team initialized!`);
}, 2000);
}
/* sendMessageToClub(msg) {
this.teamService.setState(msg);
console.log(
`Team sending through click! state: ${msg} -----------------------------------`
);
this.messageToClub.next(msg);
} */
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/players/src/app/cards/cards.component.ts
|
import { PlayersService } from './../players.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { AcknowledgementStatus } from 'src/app/models/acknowledgement.interface';
import { PlayersInfo } from '../models/players.interface';
@Component({
selector: 'players-cards',
templateUrl: './cards.component.html',
styleUrls: ['./cards.component.scss']
})
export class CardsComponent implements OnInit, OnDestroy {
showButtons: boolean;
webComponentLoaded: boolean;
playersInfo: PlayersInfo[];
subscription: Subscription;
playerSubscription: Subscription;
constructor(private playerService: PlayersService) {}
ngOnInit(): void {
this.initCards();
// this.loadWebComponentLibrary();
this.getPlayers();
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
this.playerSubscription.unsubscribe();
}
initCards() {
this.webComponentLoaded = true;
this.showButtons = false;
this.subscription = this.playerService.getState().subscribe(data => {
if (data === 'sendInvite') {
this.showButtons = true;
}
});
}
getPlayers() {
this.playerSubscription = this.playerService
.getPlayers()
.subscribe(players => {
this.playersInfo = players.data;
console.log(this.playersInfo);
});
}
loadWebComponentLibrary() {
if (this.webComponentLoaded) {
return;
}
const content = document.getElementById('webComponentLoader');
const skillsProgressScript = document.createElement('script');
skillsProgressScript.src =
'assets/webComponentLibraries/skills-progress.js';
content.appendChild(skillsProgressScript);
this.webComponentLoaded = true;
}
sendInvite(playerId: string, acknowledgement: boolean) {
const playerInfoObj: PlayersInfo = this.playersInfo.find(
player => player.id === playerId
);
this.playersInfo.find(player => player.id === playerId).statusSent = true;
const ackObj: AcknowledgementStatus = {
id: playerInfoObj.id,
name: playerInfoObj.firstname + playerInfoObj.lastname,
status: acknowledgement
};
console.log(ackObj);
console.log(this.playersInfo);
// this.playerService.acknowledgeInvite(ackObj);
this.playerService.setInvite(ackObj);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
src/app/state.service.ts
|
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class StateService {
constructor(private http: HttpClient) {}
private state$ = new Subject();
private message$ = new Subject<any>();
private clients: HTMLElement[] = [];
public registerClient(client: HTMLElement) {
this.clients.push(client);
}
public setState(state: any) {
switch (state) {
case 'init':
for (const client of this.clients) {
client.setAttribute('state', state);
}
break;
case 'requestLineUp':
this.clients
.filter(elm => elm.nodeName === 'TEAM-ROOT')[0]
.setAttribute('state', state);
break;
case 'sendInvite':
this.clients
.filter(elm => elm.nodeName === 'PLAYERS-ROOT')[0]
.setAttribute('state', state);
break;
default:
break;
}
}
public getMessage(): Observable<any> {
return this.message$.asObservable();
}
public setMessage(state: any) {
this.message$.next(state);
}
public getPlayers(): Observable<any> {
return this.http.get('assets/data/players.status.json');
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/team/src/app/line-up/line-up.component.ts
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'team-line-up',
templateUrl: './line-up.component.html',
styleUrls: ['./line-up.component.scss']
})
export class LineUpComponent implements OnInit {
constructor() { }
ngOnInit(): void {
this.loadWebComponentLibrary();
}
loadWebComponentLibrary() {
const content = document.getElementById('playerLoader');
const cardStatsScript = document.createElement('script');
cardStatsScript.src = 'assets/webComponentLibraries/soccer-player.js';
content.appendChild(cardStatsScript);
}
}
|
sathyaleo08/MicroFrotEndWithWebComponent-code
|
projects/players/src/app/players.service.ts
|
<filename>projects/players/src/app/players.service.ts
import { Injectable, EventEmitter } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PlayersService {
private state$ = new Subject<any>();
private acknowledgeInvite$ = new Subject<any>();
data = new EventEmitter();
constructor(private http: HttpClient) {}
public getState(): Observable<any> {
return this.state$.asObservable();
}
public setState(state: string) {
this.state$.next(state);
}
public acknowledgeInvite(acknowledgement: any) {
this.data.emit(acknowledgement);
}
public getInvite(): Observable<any> {
return this.acknowledgeInvite$.asObservable();
}
public setInvite(state: any) {
this.acknowledgeInvite$.next(state);
}
public getPlayers(): Observable<any> {
return this.http.get('assets/data/players.data.json');
}
}
|
PopeFelix/assemblyscript-json
|
assembly/__tests__/string_escape.spec.ts
|
import { JSON } from '../JSON'
describe('Escaped characters', () => {
it('Does not escape characters unneccessarily', () => {
const strings = [
'sphinx of black quartz, judge my vow',
'{}',
'[]',
'/',
'|',
'/|||/|||[{]}<>,.',
'ஂ ஃ அ ஆ இ ஈ உ ஊ எ ஏ ஐ ஒ ஓ ஔ க ங ச ஜ ஞ ட ண த ந ன ப ம ய ர ற ல ள',
'ᄀ ᄁ ᄂ ᄃ ᄄ ᄅ ᄆ ᄇ ᄈ ᄉ ᄊ ᄋ ᄌ ᄍ ᄎ ᄏ ᄐ ᄑ ᄒ ᄓ ᄔ ᄕ ᄖ ᄗ ᄘ ᄙ ᄚ ᄛ ',
'℀ ℁ ℂ ℃ ℄ ℅ ℆ ℇ ℈ ℉ ℊ ℋ ℌ ℍ ℎ ℏ ℐ ℑ ℒ ℓ ℔ ℕ № ℗ ℘ ℙ ℚ ℛ ℜ ℝ ℞ ℟ ℠ ℡ ™ ℣ ℤ ℥ Ω ℧ ℨ ℩ K Å ℬ ℭ ℮ ℯ ℰ ℱ Ⅎ ℳ ℴ ℵ ℶ ℷ ℸ ',
'☀ ☁ ☂ ☃ ☄ ★ ☆ ☇ ☈ ☉ ☊ ☋ ☌ ☍ ☎ ☏ ☐ ☑ ☒ ☓ ☚ ☛ ☜ ☝ ☞ ☟ ☠ ☡ ☢ ☣ ☤ ☥ ☦ ☧ ☨ ☩ ☪ ☫ ☬ ☭ ☮ ☯ ☰ ☱ ☲ ☳ ☴ ☵ ☶ ☷ ☸ ☹ ☺ ☻ ☼ ☽ ☾ ☿ ♀ ♁ ♂ ♃ ♄ ♅ ♆ ♇ ♈ ♉ ♊ ♋ ♌ ♍ ♎ ♏ ♐ ♑ ♒ ♓',
]
strings.forEach((str) => {
const jsonStr = new JSON.Str(str)
expect(jsonStr.toString()).toBe('"' + str + '"')
})
})
it('Escapes quotes and backslashes', () => {
const strings = ['"', '\\', '"\\"', '\\"\\"']
strings.forEach((str) => {
const jsonStr = new JSON.Str(str)
expect(jsonStr.toString()).toBe('"' + escaped(str) + '"')
})
})
it('Escapes control characters', () => {
const strings = ['\n', '\r', '\r\n', '\b', '\f', '\t', '\v', '\b\f\t\v\r']
strings.forEach((str) => {
const jsonStr = new JSON.Str(str)
expect(jsonStr.toString()).toBe('"' + escaped(str) + '"')
})
})
})
function escaped(str: string): string {
const escapedChars: i32[] = []
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i)
if (
charCode < 0x20 || // control characters
charCode == 0x22 || // double quote (")
charCode == 0x5c
) {
// backslash / reverse solidus (\)
escapedChars.push(0x5c)
}
escapedChars.push(charCode)
}
return String.fromCharCodes(escapedChars)
}
|
culmat/bal-ui-library
|
src/components/bal-accordion/bal-accordion.tsx
|
<reponame>culmat/bal-ui-library
import {Component, Host, h, Prop, State, Watch, Method} from "@stencil/core";
@Component({
tag: "bal-accordion",
shadow: true,
})
export class BalAccordion {
@State() isCollapsed: boolean = true;
/**
* Type defines the theme of the accordion toggle
*/
@Prop() type:
| "is-primary"
| "is-info" = "is-primary";
/**
* Controls if the accordion is collapsed or not
*/
@Prop() collapsed: boolean = true;
@Watch("collapsed")
validateCollapsed(newValue: boolean) {
this.isCollapsed = newValue;
}
/**
* Open the accordion
*/
@Method()
async open() {
this.isCollapsed = false;
}
/**
* Close the accordion
*/
@Method()
async close() {
this.isCollapsed = true;
}
/**
* Triggers the accordion
*/
@Method()
async toggle() {
this.isCollapsed = !this.isCollapsed;
}
componentWillLoad() {
this.isCollapsed = this.collapsed;
}
render() {
return (
<Host class="accordion">
<bal-button expanded={true}
light={true}
inverted={true}
type={this.type}
onClick={() => this.toggle()}>
<span style={!this.isCollapsed && {display: "none"}}>
<slot name="trigger-open">Open me!</slot>
</span>
<span style={this.isCollapsed && {display: "none"}}>
<slot name="trigger-close">Close me!</slot>
</span>
</bal-button>
<div style={this.isCollapsed && {display: "none"}}>
<slot></slot>
</div>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/autocomplete-item/autocomplete-item.tsx
|
import {Component, Element, Event, EventEmitter, h, Host, Method, Prop, State, Watch} from "@stencil/core";
import {Components} from "../../components";
@Component({
tag: "bal-autocomplete-item",
styleUrl: "autocomplete-item.scss",
shadow: true,
})
export class AutocompleteItem {
@Element() element!: HTMLElement;
labelElement!: HTMLSpanElement;
displayed = false;
@State() hidden = true;
/**
* Value of this item, which is also use as a label
*/
@Prop() value = "";
/**
* Highlights the given text in the value.
*/
@Prop() activated = false;
/**
* Highlights the given text in the value.
*/
@Prop() highlightedValue = "";
@Watch("highlightedValue")
searchValueChanged(newHighlightedValue: string) {
const index = this.value.toLowerCase().indexOf(newHighlightedValue.toLowerCase());
this.hidden = index < 0;
if (index >= 0) {
this.labelElement.innerHTML = this.value.substring(0, index)
+ "<span class='highlight'>"
+ this.value.substring(index, index + newHighlightedValue.length)
+ "</span>"
+ this.value.substring(index + newHighlightedValue.length, this.value.length);
this.displayed = true;
} else {
this.displayed = false;
}
}
/**
* Click event of the dropdown item.
*/
@Event() balClick: EventEmitter;
/**
* Tell's if the item is highlighted by the search term.
*/
@Method()
async isDisplayed(): Promise<boolean> {
return this.displayed;
}
/**
* Tell's if the item is activated by selection.
*/
@Method()
async isActive(): Promise<boolean> {
return this.activated;
}
/**
* Tell's if the item is activated by selection.
*/
@Method()
async isHidden(): Promise<boolean> {
return this.hidden;
}
get parent(): Components.BalAutocomplete {
return this.element.parentNode as any;
}
async selectItem() {
await this.parent.selectItem(this.value);
this.balClick.emit(this.value);
}
render() {
return (
<Host>
<button class={[
"dropdown-item",
this.hidden ? "is-hidden" : "",
this.activated ? "is-active" : "",
].join(" ")}
onClick={() => this.selectItem()}>
<span ref={el => this.labelElement = el as HTMLSpanElement}>
{this.value}
</span>
</button>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/tab-item/tab-item.tsx
|
import {Component, Host, h, Prop, Method, State, Watch} from "@stencil/core";
export interface TabItemOptions {
value: string;
label: string;
active: boolean;
}
@Component({
tag: "bal-tab-item",
styleUrl: "tab-item.scss",
shadow: true,
})
export class TabItem {
@State() isContentHidden = true;
/**
* This is the key of the tab.
*/
@Prop() value: string = "";
/**
* Label for the tab.
*/
@Prop() label: string = "";
/**
* Tell's if the tab is active and the content is visible.
*/
@Prop() active: boolean = false;
@Watch("active")
activatedHandler(newActive: boolean) {
this.isContentHidden = !newActive;
}
/**
* Options of the tab like label, value etc.
*/
@Method()
async getOptions(): Promise<TabItemOptions> {
return {
value: this.value,
label: this.label,
active: this.active,
};
}
/**
* Sets the tab active.
*/
@Method()
async setActive(active: boolean): Promise<void> {
this.active = active;
}
componentWillLoad() {
this.isContentHidden = !this.active;
}
render() {
return (
<Host>
<div style={this.isContentHidden && {display: "none"}}>
<slot/>
</div>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/bal-dropdown/bal-dropdown.tsx
|
import {Component, Host, h, State, Method, Prop, EventEmitter, Event, Listen, Element, Watch} from "@stencil/core";
export interface DropDownOption {
label: string;
value: any;
}
@Component({
tag: "bal-dropdown",
styleUrl: "bal-dropdown.scss",
shadow: true,
})
export class BalDropdown {
@Element() element!: HTMLElement;
@State() dropdownIsActive = false;
@State() selected: DropDownOption = null;
/**
* If `true` the field gets a line below.
*/
@Prop() showBottomLine = true;
/**
* If `true` the field expands over the whole width.
*/
@Prop() expanded = false;
/**
* The value of the selected dropdown item.
*/
@Prop({mutable: true, reflect: true}) value: any = null;
@Watch("value")
valueWatcher(newValue: any) {
this.selectDropdownItem.emit(newValue);
}
@Event() dropdownSelected: EventEmitter;
@Event() selectDropdownItem: EventEmitter;
componentDidLoad() {
if (this.value) {
this.selectDropdownItem.emit(this.value);
}
}
@Listen("click", {target: "document"})
clickOnOutside(event: UIEvent) {
if (!this.element.contains((event.target as any)) && this.dropdownIsActive) {
this.toggle();
}
}
/**
* Open & closes the dropdown
*/
@Method()
async toggle() {
this.dropdownIsActive = !this.dropdownIsActive;
}
/**
* Open the dropdown menu
*/
@Method()
async open() {
this.dropdownIsActive = true;
}
/**
* Closes the dropdown menu
*/
@Method()
async close() {
this.dropdownIsActive = false;
}
/**
* Selects a dropdown item and changes the value.
*/
@Method()
async selectItem(option: DropDownOption) {
this.value = option.value;
this.selected = option;
this.dropdownSelected.emit(this.value);
if (this.dropdownIsActive) {
this.toggle();
}
}
/**
* Returns the value of the dropdown.
*/
@Method()
async getSelectedValue() {
return this.value;
}
get dropDownTitle() {
return this.selected && this.selected.label || "-";
}
render() {
return (
<Host>
<div class={[
"dropdown",
this.expanded ? "is-fullwidth" : "",
this.dropdownIsActive ? "is-active" : "",
].join(" ")}>
<div class="dropdown-trigger" onClick={() => this.toggle()}>
<slot name="trigger">
<button class={this.showBottomLine ? "button showBottomLine" : "button"}
aria-haspopup="true"
aria-controls="dropdown-menu">
<span innerHTML={this.dropDownTitle}></span>
<span class="icon is-small">
<i class="bal-icon-caret-down" aria-hidden="true"></i>
</span>
</button>
</slot>
</div>
<div class="dropdown-menu" role="menu">
<div class="dropdown-content">
<slot/>
</div>
</div>
</div>
</Host>
);
}
}
|
culmat/bal-ui-library
|
src/components/bal-button/bal-button.e2e.ts
|
<reponame>culmat/bal-ui-library
import {newE2EPage} from "@stencil/core/testing";
describe("bal-button", () => {
it("renders", async () => {
const page = await newE2EPage();
await page.setContent(
`<bal-button type="is-primary">Press me</bal-button>`,
);
const buttonElement = await page.find("bal-button >>> button");
expect(buttonElement).toHaveClass("button");
expect(buttonElement).toHaveClass("is-primary");
});
});
|
culmat/bal-ui-library
|
src/components.d.ts
|
<reponame>culmat/bal-ui-library
/* eslint-disable */
/* tslint:disable */
/**
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from '@stencil/core/internal';
import {
DateCallback,
} from './components/bal-datepicker/bal-datepicker';
import {
DropDownOption,
} from './components/bal-dropdown/bal-dropdown';
import {
TabItemOptions,
} from './components/tab-item/tab-item';
import {
TabItemOptions as TabItemOptions1,
} from './components/tab-item/tab-item';
export namespace Components {
interface BalAccordion {
/**
* Close the accordion
*/
'close': () => Promise<void>;
/**
* Controls if the accordion is collapsed or not
*/
'collapsed': boolean;
/**
* Open the accordion
*/
'open': () => Promise<void>;
/**
* Triggers the accordion
*/
'toggle': () => Promise<void>;
/**
* Type defines the theme of the accordion toggle
*/
'type': | "is-primary"
| "is-info";
}
interface BalAutocomplete {
/**
* If `true` the field is disabled
*/
'disabled': boolean;
/**
* If `true` the field expands over the whole width.
*/
'expanded': boolean;
/**
* Sets the given value to the input, closes the dropdown and triggers a change event.
*/
'selectItem': (newValue: string) => Promise<void>;
/**
* The value of the autocomplete.
*/
'value': string;
}
interface BalAutocompleteItem {
/**
* Highlights the given text in the value.
*/
'activated': boolean;
/**
* Highlights the given text in the value.
*/
'highlightedValue': string;
/**
* Tell's if the item is activated by selection.
*/
'isActive': () => Promise<boolean>;
/**
* Tell's if the item is highlighted by the search term.
*/
'isDisplayed': () => Promise<boolean>;
/**
* Tell's if the item is activated by selection.
*/
'isHidden': () => Promise<boolean>;
/**
* Value of this item, which is also use as a label
*/
'value': string;
}
interface BalButton {
/**
* If `true` the button is disabled
*/
'disabled': boolean;
/**
* If `true` the button has a full width
*/
'expanded': boolean;
/**
* If `true` the button is inverted
*/
'inverted': boolean;
/**
* If `true` the button has a light color
*/
'light': boolean;
/**
* If `true` the label is hidden and a loading spinner is shown instead.
*/
'loading': boolean;
/**
* If `true` the button is outlined
*/
'outlined': boolean;
/**
* The theme type of the button. Given by bulma our css framework.
*/
'type': | "is-primary"
| "is-info"
| "is-success"
| "is-warning"
| "is-danger"
| "is-link";
}
interface BalDatepicker {
/**
* Close the datepicker dropdown
*/
'close': () => Promise<void>;
/**
* Disable the input
*/
'disabled': boolean;
/**
* Callback to determine which date in the datepicker should be selectable.
*/
'filter': DateCallback;
/**
* Language of the datepicker. Possible values are `de`, `fr`,`it` or `en`.
*/
'language': string;
/**
* Latest date available for selection
*/
'maxDate': string;
/**
* Latest year available for selection
*/
'maxYear': string;
/**
* Earliest date available for selection
*/
'minDate': string;
/**
* Earliest year available for selection
*/
'minYear': string;
/**
* Open the datepicker dropdown
*/
'open': () => Promise<void>;
/**
* Placeholder text to render if no date has been selected.
*/
'placeholder': string;
/**
* The value of the datepicker with the format `dd.MM.yyyy`.
*/
'value': string;
}
interface BalDropdown {
/**
* Closes the dropdown menu
*/
'close': () => Promise<void>;
/**
* If `true` the field expands over the whole width.
*/
'expanded': boolean;
/**
* Returns the value of the dropdown.
*/
'getSelectedValue': () => Promise<any>;
/**
* Open the dropdown menu
*/
'open': () => Promise<void>;
/**
* Selects a dropdown item and changes the value.
*/
'selectItem': (option: DropDownOption) => Promise<void>;
/**
* If `true` the field gets a line below.
*/
'showBottomLine': boolean;
/**
* Open & closes the dropdown
*/
'toggle': () => Promise<void>;
/**
* The value of the selected dropdown item.
*/
'value': any;
}
interface BalDropdownItem {
/**
* The value of the dropdown item. This value will be returned by the parent <bal-dropdown> element.
*/
'value': string | boolean | number | object;
}
interface BalField {
/**
* Baloise icon for the left side of the input
*/
'iconLeft': string;
/**
* Baloise icon for the right side of the input
*/
'iconRight': string;
/**
* Label text
*/
'label': string;
/**
* If `true` a asterix (*) is added to the label text
*/
'required': boolean;
/**
* Validation message text
*/
'validationMessage': string;
}
interface BalSpinner {}
interface BalTabItem {
/**
* Tell's if the tab is active and the content is visible.
*/
'active': boolean;
/**
* Options of the tab like label, value etc.
*/
'getOptions': () => Promise<TabItemOptions>;
/**
* Label for the tab.
*/
'label': string;
/**
* Sets the tab active.
*/
'setActive': (active: boolean) => Promise<void>;
/**
* This is the key of the tab.
*/
'value': string;
}
interface BalTabs {
/**
* If `true` the field expands over the whole width.
*/
'expanded': boolean;
/**
* Select a tab by the value of the tab item.
*/
'select': (value: string) => Promise<void>;
}
interface BalTag {
/**
* The theme type of the tag. Given by bulma our css framework.
*/
'type': | "is-primary"
| "is-info"
| "is-success"
| "is-warning"
| "is-danger"
| "is-light";
}
interface BalToast {
/**
* Closes this toast
*/
'close': () => Promise<void>;
/**
* Closes the toast after the given duration in ms
*/
'closeIn': (duration: number) => Promise<void>;
/**
* Message text
*/
'message': string;
/**
* The theme type of the toast. Given by bulma our css framework.
*/
'type': | "is-primary"
| "is-info"
| "is-success"
| "is-warning"
| "is-danger";
}
}
declare global {
interface HTMLBalAccordionElement extends Components.BalAccordion, HTMLStencilElement {}
var HTMLBalAccordionElement: {
prototype: HTMLBalAccordionElement;
new (): HTMLBalAccordionElement;
};
interface HTMLBalAutocompleteElement extends Components.BalAutocomplete, HTMLStencilElement {}
var HTMLBalAutocompleteElement: {
prototype: HTMLBalAutocompleteElement;
new (): HTMLBalAutocompleteElement;
};
interface HTMLBalAutocompleteItemElement extends Components.BalAutocompleteItem, HTMLStencilElement {}
var HTMLBalAutocompleteItemElement: {
prototype: HTMLBalAutocompleteItemElement;
new (): HTMLBalAutocompleteItemElement;
};
interface HTMLBalButtonElement extends Components.BalButton, HTMLStencilElement {}
var HTMLBalButtonElement: {
prototype: HTMLBalButtonElement;
new (): HTMLBalButtonElement;
};
interface HTMLBalDatepickerElement extends Components.BalDatepicker, HTMLStencilElement {}
var HTMLBalDatepickerElement: {
prototype: HTMLBalDatepickerElement;
new (): HTMLBalDatepickerElement;
};
interface HTMLBalDropdownElement extends Components.BalDropdown, HTMLStencilElement {}
var HTMLBalDropdownElement: {
prototype: HTMLBalDropdownElement;
new (): HTMLBalDropdownElement;
};
interface HTMLBalDropdownItemElement extends Components.BalDropdownItem, HTMLStencilElement {}
var HTMLBalDropdownItemElement: {
prototype: HTMLBalDropdownItemElement;
new (): HTMLBalDropdownItemElement;
};
interface HTMLBalFieldElement extends Components.BalField, HTMLStencilElement {}
var HTMLBalFieldElement: {
prototype: HTMLBalFieldElement;
new (): HTMLBalFieldElement;
};
interface HTMLBalSpinnerElement extends Components.BalSpinner, HTMLStencilElement {}
var HTMLBalSpinnerElement: {
prototype: HTMLBalSpinnerElement;
new (): HTMLBalSpinnerElement;
};
interface HTMLBalTabItemElement extends Components.BalTabItem, HTMLStencilElement {}
var HTMLBalTabItemElement: {
prototype: HTMLBalTabItemElement;
new (): HTMLBalTabItemElement;
};
interface HTMLBalTabsElement extends Components.BalTabs, HTMLStencilElement {}
var HTMLBalTabsElement: {
prototype: HTMLBalTabsElement;
new (): HTMLBalTabsElement;
};
interface HTMLBalTagElement extends Components.BalTag, HTMLStencilElement {}
var HTMLBalTagElement: {
prototype: HTMLBalTagElement;
new (): HTMLBalTagElement;
};
interface HTMLBalToastElement extends Components.BalToast, HTMLStencilElement {}
var HTMLBalToastElement: {
prototype: HTMLBalToastElement;
new (): HTMLBalToastElement;
};
interface HTMLElementTagNameMap {
'bal-accordion': HTMLBalAccordionElement;
'bal-autocomplete': HTMLBalAutocompleteElement;
'bal-autocomplete-item': HTMLBalAutocompleteItemElement;
'bal-button': HTMLBalButtonElement;
'bal-datepicker': HTMLBalDatepickerElement;
'bal-dropdown': HTMLBalDropdownElement;
'bal-dropdown-item': HTMLBalDropdownItemElement;
'bal-field': HTMLBalFieldElement;
'bal-spinner': HTMLBalSpinnerElement;
'bal-tab-item': HTMLBalTabItemElement;
'bal-tabs': HTMLBalTabsElement;
'bal-tag': HTMLBalTagElement;
'bal-toast': HTMLBalToastElement;
}
}
declare namespace LocalJSX {
interface BalAccordion {
/**
* Controls if the accordion is collapsed or not
*/
'collapsed'?: boolean;
/**
* Type defines the theme of the accordion toggle
*/
'type'?: | "is-primary"
| "is-info";
}
interface BalAutocomplete {
/**
* If `true` the field is disabled
*/
'disabled'?: boolean;
/**
* If `true` the field expands over the whole width.
*/
'expanded'?: boolean;
/**
* Emitted when the toggle loses focus.
*/
'onBalBlur'?: (event: CustomEvent<void>) => void;
/**
* Emitted when the checked property has changed.
*/
'onBalChange'?: (event: CustomEvent<string>) => void;
/**
* Emitted when the toggle has focus..
*/
'onBalFocus'?: (event: CustomEvent<void>) => void;
/**
* The value of the autocomplete.
*/
'value'?: string;
}
interface BalAutocompleteItem {
/**
* Highlights the given text in the value.
*/
'activated'?: boolean;
/**
* Highlights the given text in the value.
*/
'highlightedValue'?: string;
/**
* Click event of the dropdown item.
*/
'onBalClick'?: (event: CustomEvent<any>) => void;
/**
* Value of this item, which is also use as a label
*/
'value'?: string;
}
interface BalButton {
/**
* If `true` the button is disabled
*/
'disabled'?: boolean;
/**
* If `true` the button has a full width
*/
'expanded'?: boolean;
/**
* If `true` the button is inverted
*/
'inverted'?: boolean;
/**
* If `true` the button has a light color
*/
'light'?: boolean;
/**
* If `true` the label is hidden and a loading spinner is shown instead.
*/
'loading'?: boolean;
/**
* If `true` the button is outlined
*/
'outlined'?: boolean;
/**
* The theme type of the button. Given by bulma our css framework.
*/
'type'?: | "is-primary"
| "is-info"
| "is-success"
| "is-warning"
| "is-danger"
| "is-link";
}
interface BalDatepicker {
/**
* Disable the input
*/
'disabled'?: boolean;
/**
* Callback to determine which date in the datepicker should be selectable.
*/
'filter'?: DateCallback;
/**
* Language of the datepicker. Possible values are `de`, `fr`,`it` or `en`.
*/
'language'?: string;
/**
* Latest date available for selection
*/
'maxDate'?: string;
/**
* Latest year available for selection
*/
'maxYear'?: string;
/**
* Earliest date available for selection
*/
'minDate'?: string;
/**
* Earliest year available for selection
*/
'minYear'?: string;
/**
* Triggers when the value of the datepicker is changed
*/
'onInput'?: (event: CustomEvent<string>) => void;
/**
* Placeholder text to render if no date has been selected.
*/
'placeholder'?: string;
/**
* The value of the datepicker with the format `dd.MM.yyyy`.
*/
'value'?: string;
}
interface BalDropdown {
/**
* If `true` the field expands over the whole width.
*/
'expanded'?: boolean;
'onDropdownSelected'?: (event: CustomEvent<any>) => void;
'onSelectDropdownItem'?: (event: CustomEvent<any>) => void;
/**
* If `true` the field gets a line below.
*/
'showBottomLine'?: boolean;
/**
* The value of the selected dropdown item.
*/
'value'?: any;
}
interface BalDropdownItem {
/**
* Click event of the dropdown item.
*/
'onClickEvent'?: (event: CustomEvent<any>) => void;
/**
* The value of the dropdown item. This value will be returned by the parent <bal-dropdown> element.
*/
'value'?: string | boolean | number | object;
}
interface BalField {
/**
* Baloise icon for the left side of the input
*/
'iconLeft'?: string;
/**
* Baloise icon for the right side of the input
*/
'iconRight'?: string;
/**
* Label text
*/
'label'?: string;
/**
* If `true` a asterix (*) is added to the label text
*/
'required'?: boolean;
/**
* Validation message text
*/
'validationMessage'?: string;
}
interface BalSpinner {}
interface BalTabItem {
/**
* Tell's if the tab is active and the content is visible.
*/
'active'?: boolean;
/**
* Label for the tab.
*/
'label'?: string;
/**
* This is the key of the tab.
*/
'value'?: string;
}
interface BalTabs {
/**
* If `true` the field expands over the whole width.
*/
'expanded'?: boolean;
/**
* Emitted when the changes has finished.
*/
'onBalTabsDidChange'?: (event: CustomEvent<TabItemOptions>) => void;
}
interface BalTag {
/**
* The theme type of the tag. Given by bulma our css framework.
*/
'type'?: | "is-primary"
| "is-info"
| "is-success"
| "is-warning"
| "is-danger"
| "is-light";
}
interface BalToast {
/**
* Message text
*/
'message'?: string;
/**
* The theme type of the toast. Given by bulma our css framework.
*/
'type'?: | "is-primary"
| "is-info"
| "is-success"
| "is-warning"
| "is-danger";
}
interface IntrinsicElements {
'bal-accordion': BalAccordion;
'bal-autocomplete': BalAutocomplete;
'bal-autocomplete-item': BalAutocompleteItem;
'bal-button': BalButton;
'bal-datepicker': BalDatepicker;
'bal-dropdown': BalDropdown;
'bal-dropdown-item': BalDropdownItem;
'bal-field': BalField;
'bal-spinner': BalSpinner;
'bal-tab-item': BalTabItem;
'bal-tabs': BalTabs;
'bal-tag': BalTag;
'bal-toast': BalToast;
}
}
export { LocalJSX as JSX };
declare module "@stencil/core" {
export namespace JSX {
interface IntrinsicElements {
'bal-accordion': LocalJSX.BalAccordion & JSXBase.HTMLAttributes<HTMLBalAccordionElement>;
'bal-autocomplete': LocalJSX.BalAutocomplete & JSXBase.HTMLAttributes<HTMLBalAutocompleteElement>;
'bal-autocomplete-item': LocalJSX.BalAutocompleteItem & JSXBase.HTMLAttributes<HTMLBalAutocompleteItemElement>;
'bal-button': LocalJSX.BalButton & JSXBase.HTMLAttributes<HTMLBalButtonElement>;
'bal-datepicker': LocalJSX.BalDatepicker & JSXBase.HTMLAttributes<HTMLBalDatepickerElement>;
'bal-dropdown': LocalJSX.BalDropdown & JSXBase.HTMLAttributes<HTMLBalDropdownElement>;
'bal-dropdown-item': LocalJSX.BalDropdownItem & JSXBase.HTMLAttributes<HTMLBalDropdownItemElement>;
'bal-field': LocalJSX.BalField & JSXBase.HTMLAttributes<HTMLBalFieldElement>;
'bal-spinner': LocalJSX.BalSpinner & JSXBase.HTMLAttributes<HTMLBalSpinnerElement>;
'bal-tab-item': LocalJSX.BalTabItem & JSXBase.HTMLAttributes<HTMLBalTabItemElement>;
'bal-tabs': LocalJSX.BalTabs & JSXBase.HTMLAttributes<HTMLBalTabsElement>;
'bal-tag': LocalJSX.BalTag & JSXBase.HTMLAttributes<HTMLBalTagElement>;
'bal-toast': LocalJSX.BalToast & JSXBase.HTMLAttributes<HTMLBalToastElement>;
}
}
}
|
culmat/bal-ui-library
|
stencil.config.ts
|
import {Config} from "@stencil/core";
import {sass} from "@stencil/sass";
import {postcss} from "@stencil/postcss";
import autoprefixer from "autoprefixer";
export const config: Config = {
devServer: {
reloadStrategy: "pageReload",
},
namespace: "bal-ui-library",
globalStyle: "src/scss/bal-ui-library.scss",
copy: [
{
src: "**/*.md",
},
{
src: "docs/**/*.css",
},
{
src: "docs/**/*.js",
},
{
src: "components.d.ts",
},
],
plugins: [
sass(),
postcss({
plugins: [autoprefixer()],
}),
],
outputTargets: [
{
type: "dist",
esmLoaderPath: "../loader",
},
{
type: "docs-readme",
},
{
type: "www",
dir: "www",
serviceWorker: null, // disable service workers
},
],
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.