repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
typekev/react-mk
|
src/constants.ts
|
import { Range } from './types';
export const defaultKeyPressDelay: Range = [100, 150];
export const defaultSentenceDelay: Range = [125.8, 219.4];
|
typekev/react-mk
|
tests/Cursor.test.tsx
|
<reponame>typekev/react-mk
import React from 'react';
import ReactDOM from 'react-dom';
import Cursor from '../src/Cursor';
describe('Cursor component', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Cursor />, div);
ReactDOM.unmountComponentAtNode(div);
});
it('renders with blink disabled without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Cursor blink={false} />, div);
ReactDOM.unmountComponentAtNode(div);
});
it('renders a child without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Cursor>Test</Cursor>, div);
ReactDOM.unmountComponentAtNode(div);
});
});
|
typekev/react-mk
|
src/useKeyboard.ts
|
import { useState, useRef, useEffect, Dispatch, SetStateAction } from 'react';
import { Action, Range } from './types';
import getTimers from './getTimers';
import getTimer from './getTimer';
import { defaultKeyPressDelay } from './constants';
const initialState: string[] = [];
export const backspace = (chars: string[], setChars: Dispatch<SetStateAction<string[]>>) =>
setChars(chars.length > 1 ? chars.slice(0, chars.length - 1) : initialState);
export const type = (
chars: string[],
nextChar: string,
setChars: Dispatch<SetStateAction<string[]>>,
) => setChars([...chars, nextChar]);
const useKeyboard = () => {
const [chars, setChars] = useState<string[]>(initialState);
const [remainingChars, setRemainingChars] = useState<string[]>(initialState);
const [resolver, setResolver] = useState<(() => void) | undefined>();
const [delayRange, setDelayRange] = useState(defaultKeyPressDelay);
const charsRef = useRef(chars);
charsRef.current = chars;
useEffect(() => {
/* istanbul ignore next */
if (remainingChars.length > initialState.length) {
const [nextChar, ...newRemainingChars] = remainingChars;
const doType = () => type(chars, nextChar, setChars);
const doSetRemainingChars = () => setRemainingChars(newRemainingChars);
getTimer(nextChar, delayRange).then(doType).then(doSetRemainingChars);
} else if (resolver) {
resolver();
setResolver(undefined);
setRemainingChars(initialState);
}
}, [remainingChars]);
const setText = (action: Action, keyPressDelayRange: Range) =>
new Promise<void>((resolve) => {
setResolver(() => resolve);
setDelayRange(keyPressDelayRange);
setChars(initialState);
/* istanbul ignore else */
if (typeof action === 'string' && action.length > 0) {
setRemainingChars(action.split(''));
} else {
resolve();
}
});
const clearText = (action: Action) =>
new Promise<Action>((resolve) =>
/* istanbul ignore next */
!chars.length
? resolve(action)
: getTimers(
charsRef.current,
() => {
/* istanbul ignore next */
backspace(charsRef.current, setChars);
/* istanbul ignore next */
return charsRef.current.length === 0 && resolve(action);
},
delayRange,
),
);
const text = chars.join('');
return { text, setText, clearText };
};
export default useKeyboard;
|
typekev/react-mk
|
tests/Keyboard.test.tsx
|
<reponame>typekev/react-mk
import React from 'react';
import { act } from 'react-dom/test-utils';
import Enzyme, { mount } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import Keyboard, { type as typeFunction } from '../src/Keyboard';
Enzyme.configure({ adapter: new Adapter() });
describe('Keyboard component', () => {
const setState = jest.fn<void, string[]>();
beforeEach(() => {
jest.spyOn<any, string>(React, 'useState').mockImplementation((init) => [init, setState]);
});
it('renders a child with the value Test', async () => {
let wrapper;
const text = 'Test';
await act(async () => {
wrapper = mount(<Keyboard>{text}</Keyboard>);
});
expect(wrapper.prop('children')).toBe(text);
wrapper.unmount();
});
it('renders a child with the value Test', async () => {
let wrapper;
const text = 'Test';
await act(async () => {
wrapper = mount(<Keyboard>{({ type }) => type(text)}</Keyboard>);
});
await act(async () => {
setTimeout(() => expect(wrapper.prop('children')).toBe(text), 2000);
});
wrapper.unmount();
});
it('renders a child with the value Test', async () => {
let wrapper;
const text = 'Test';
await act(async () => {
wrapper = mount(<Keyboard>{({ type }) => type(text, text, text)}</Keyboard>);
});
await act(async () => {
setTimeout(() => expect(setState).toHaveBeenCalledWith(text), 2000);
});
wrapper.unmount();
});
it('renders a an empty string', async () => {
let wrapper;
const setState = jest.fn<void, string[]>();
const text = '';
await act(async () => {
wrapper = mount(<Keyboard>{text}</Keyboard>);
});
await act(async () => {
setTimeout(() => expect(setState).toHaveBeenCalledWith(text), 2000);
});
wrapper.unmount();
});
it('returns an array of length 4', () => {
const text = 'Test';
expect(typeFunction(text, text, text, text).length).toBe(4);
});
});
|
typekev/react-mk
|
tests/getTimer.test.ts
|
import getTimer, { clearTimer, createTimer, getTimeout } from '../src/getTimer';
import { Range } from '../src/types'
describe('getTimer function', () => {
it('should not throw an error when passed a string', () => {
expect(() => getTimer('Test')).not.toThrow();
});
it('should return Test', () => {
const text = 'Test';
getTimer(text).then(action => expect(action).toBe(text));
});
it('should return Test', () => {
const text = 'Test';
expect(clearTimer({ action: text, timer: setTimeout(() => { }, 100) })).toBe(text);
});
it('should return a timer, a delay of 400', () => {
const text = 'Test';
const delayRange: Range = [100, 100];
const { timer, delay } = createTimer(text, delayRange)(() => Promise.resolve());
expect(typeof timer).toBe(typeof setTimeout(() => Promise.resolve(), delay));
expect(delay).toBe(delayRange[0] * text.length);
});
it('should return a timer', () => {
const text = 'Test';
const delay = 100;
const timer = getTimeout(() => { }, text, delay);
expect(typeof timer).toBe(typeof setTimeout(() => Promise.resolve(), delay));
});
});
|
typekev/react-mk
|
src/getDelay.ts
|
<reponame>typekev/react-mk
import { Action } from './types';
import getKeyPressDelay from './getKeyPressDelay';
import { defaultKeyPressDelay } from './constants';
/**
* Returns a delay in milliseconds based on a given `action` and `delayRange`
*
* @param action - The smallest possible output
* @param delayRange - The largest possible output
* @returns A millisecond delay
*/
const getDelay = (action: Action, delayRange = defaultKeyPressDelay) =>
typeof action === 'number' ? action : action.length * getKeyPressDelay(...delayRange);
export default getDelay;
|
typekev/react-mk
|
src/getKeyPressDelay.ts
|
<reponame>typekev/react-mk
/**
* Returns a number between `min` and `max`.
*
* @param min - The smallest possible output
* @param max - The largest possible output
* @returns A number in the range of `min` and `max`
*/
const getKeyPressDelay = (min: number, max: number) =>
Math.floor(Math.random() * (max - min) + min);
export default getKeyPressDelay;
|
typekev/react-mk
|
src/Cursor.tsx
|
<gh_stars>10-100
import React, { PropsWithChildren, DetailedHTMLProps } from 'react';
import { css, keyframes } from '@emotion/css';
const blinkAnimation = keyframes`
from {
opacity: 1;
}
50% {
opacity: 0;
}
to {
opacity: 1;
}
`;
interface Props extends DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>, HTMLSpanElement> {
blink?: boolean;
blinkAnimationDuration?: number;
}
export default function Cursor({
blink = true,
blinkAnimationDuration = 700,
children = '|',
...rest
}: PropsWithChildren<Props>) {
return (
<span
{...rest}
className={css`
width: 96px;
height: 96px;
border-radius: 50%;
animation: ${blinkAnimation} ${blinkAnimationDuration}ms ${blink ? 'infinite' : 0};
transform-origin: center bottom;
`}
>
{children}
</span>
);
}
|
typekev/react-mk
|
src/getTimers.ts
|
<gh_stars>10-100
import { Action, Range } from "./types";
import getTimer from './getTimer';
import getDelay from './getDelay';
export const getPreviousDelay = (delays: number[], index: number) => index && delays[index - 1];
export const accumulateDelays = (
accumulatedDelays: number[],
action: Action,
index: number,
delayRange?: Range,
) => [
...accumulatedDelays,
getDelay(action, delayRange) + getPreviousDelay(accumulatedDelays, index),
];
export const getDelays = (actions: Action[], delayRange?: Range) =>
actions.reduce<number[]>(
(accumulatedDelays, action, index) =>
accumulateDelays(accumulatedDelays, action, index, delayRange),
[],
);
export const startTimers = (actions: Action[], then: () => void) => (
delay: number,
index: number,
) => getTimer(actions[index], [delay, delay]).then(then);
const getTimers = (actions: Action[], then: () => void, delayRange?: Range) => {
const delays = getDelays(actions, delayRange);
delays.forEach(startTimers(actions, then));
};
export default getTimers;
|
typekev/react-mk
|
tests/useKeyboard.test.tsx
|
<filename>tests/useKeyboard.test.tsx
import React from 'react';
import { act } from 'react-dom/test-utils';
import Enzyme, { shallow } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { Action, Range } from '../src/types';
import useKeyboard, { backspace, type } from '../src/useKeyboard';
Enzyme.configure({ adapter: new Adapter() });
interface HookReturn {
text: string;
setText: (action: Action, keyPressDelayRange: Range) => Promise<unknown>;
clearText: (action: Action) => Promise<Action>;
}
const Div = (_params: { hook: HookReturn }) => <div />;
const HookWrapper = ({ hook }: { hook: () => HookReturn }) => (
<Div key="hookWrapper" hook={hook()} />
);
const getProps = (wrapper) => wrapper.findWhere((node) => node.key() === 'hookWrapper').props();
describe('useKeyboard hook', () => {
it('should return an empty string by default', () => {
const wrapper = shallow(<HookWrapper hook={useKeyboard} />);
const {
hook: { text },
} = getProps(wrapper);
expect(text).toBe('');
wrapper.unmount();
});
it('should set text to Test then clear it', async () => {
const wrapper = shallow(<HookWrapper hook={useKeyboard} />);
const textTest = 'Test';
const {
hook: { setText },
} = getProps(wrapper);
setText(textTest);
const {
hook: { text },
} = getProps(wrapper);
await act(async () => {
setTimeout(() => expect(text).toBe(textTest), 2000);
});
const {
hook: { clearText },
} = getProps(wrapper);
clearText();
await act(async () => {
const {
hook: { text: delayedText },
} = getProps(wrapper);
setTimeout(() => expect(delayedText).toBe(''), 2000);
});
wrapper.unmount();
});
it('returns undefined and does not throw when chars is greater than 1', () => {
const chars = ['a', 'b', 'c'];
expect(typeof backspace(chars, () => {})).toBe('undefined');
expect(() => backspace(chars, () => {})).not.toThrow();
});
it('returns undefined and does not throw when chars is empty', () => {
const chars = [];
expect(typeof backspace(chars, () => {})).toBe('undefined');
expect(() => backspace(chars, () => {})).not.toThrow();
});
it('returns undefined and does not throw', () => {
const chars = ['a', 'b', 'c'];
const char = 'd';
expect(typeof type(chars, char, () => {})).toBe('undefined');
expect(() => type(chars, char, () => {})).not.toThrow();
});
});
|
typekev/react-mk
|
tests/getKeyPressDelay.test.ts
|
<reponame>typekev/react-mk
import getKeyPressDelay from '../src/getKeyPressDelay';
describe('getKeyPressDelay function', () => {
it('should not throw', () => {
expect(() => getKeyPressDelay(100, 200)).not.toThrow();
});
});
|
typekev/react-mk
|
tests/getDelay.test.ts
|
import getDelay from '../src/getDelay';
describe('getDelay function', () => {
it('should not throw an error when passed a string', () => {
expect(() => getDelay('Test')).not.toThrow();
});
it('should equal 100', () => {
const delay = getDelay('A', [100, 100]);
expect(delay).toBe(100);
});
it('should equal 400', () => {
const delay = getDelay('Test', [100, 100]);
expect(delay).toBe(400);
});
it('should equal 1000', () => {
const delay = getDelay(1000);
expect(delay).toBe(1000);
});
});
|
typekev/react-mk
|
src/getTimer.ts
|
import { Action, Range } from "./types";
import getDelay from "./getDelay";
interface Props { action: Action, timer: NodeJS.Timeout }
export const clearTimer = ({ action, timer }: Props) => {
clearTimeout(timer);
return action;
};
export const getTimeout = (resolve: (params: Props) => void, action: Action, delay: number) => {
const timer: NodeJS.Timeout = setTimeout(
() => resolve({ action, timer }),
delay
);
return timer;
};
export const createTimer = (action: Action, delayRange?: Range) => (resolve: (params: Props) => void) => {
const delay = getDelay(action, delayRange);
const timer = getTimeout(resolve, action, delay);
return { timer, delay };
};
const getTimer = (action: Action, delayRange?: Range) =>
new Promise<Props>(createTimer(action, delayRange)).then(clearTimer);
export default getTimer;
|
nft-login/nft-marketplace
|
src/store.ts
|
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store, MutationTree } from 'vuex'
import { Blockchain } from './model/blockchain';
import { Web3Blockchain } from './controller/web3_blockchain';
export interface State {
account: string;
balance: number;
blockchain: Blockchain;
blockchainLoaded: boolean;
}
const mutations = <MutationTree<State>>{
setAccount(state, payload) {
state.account = payload;
},
setBalance(state, payload) {
state.balance = payload;
},
setBlockchainLoaded(state, payload) {
state.blockchainLoaded = payload;
state.blockchain = state.blockchain;
}
};
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
state: {
account: "",
balance: 0.0,
blockchain: new Web3Blockchain(),
blockchainLoaded: false
},
mutations: mutations
})
export function useStore() {
return baseUseStore(key)
}
|
nft-login/nft-marketplace
|
src/main.ts
|
<gh_stars>1-10
import { createApp } from 'vue';
import { createRouter, createWebHashHistory } from 'vue-router';
import App from './App.vue';
import Home from './pages/Home.vue';
import Marketplace from './pages/Marketplace.vue';
import MyTokens from './pages/MyTokens.vue';
import Mint from './pages/Mint.vue';
import About from './pages/About.vue';
import { store, key } from './store';
const routes = [
{
path: '/', component: Home
},
{
path: '/marketplace', component: Marketplace
},
{
path: '/mytokens', component: MyTokens
},
{
path: '/mint', component: Mint
},
{ path: '/about', component: About },
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
const app = createApp(App);
app.use(router);
app.use(store, key);
app.mount('#app');
|
nft-login/nft-marketplace
|
src/controller/web3_blockchain.ts
|
import { ethers } from "ethers";
import { ContractFactory } from 'ethers';
import { Blockchain } from "../model/blockchain";
import * as EarlyAccessGame from "../abis/EarlyAccessGame.json";
function getContract() {
const search = window.location.search;
const contract = new URLSearchParams(search).get("contract");
console.log("?contract=", contract);
return contract;
}
interface Provider {
request: Function;
eth: {
Contract: Function
}
on: Function
}
interface NetworkObjects {
[keys: string]: {
address: string;
}
}
export class Web3Blockchain implements Blockchain {
provider?: Provider;
contract?: any;
constructor() {
this.init();
}
init = async () => {
this.provider = window.ethereum;
const accounts = await window.ethereum?.request({ method: "eth_requestAccounts" });
if (this.provider) {
console.log("Ethereum successfully detected!");
} else {
console.error("Please install MetaMask!");
}
}
loadContract = async (contractAddress: string) => {
const accounts = await window.ethereum?.request({ method: "eth_requestAccounts" });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner()
this.contract = await new ethers.Contract(contractAddress, EarlyAccessGame.abi, signer)
};
chainId = async (): Promise<string> => {
return parseInt(await this.provider?.request({
method: "eth_chainId",
}), 16).toString();
};
contractAddress = async () => {
const networkId: string = await this.chainId();
let networks: NetworkObjects = EarlyAccessGame.networks as unknown as NetworkObjects;
const networkData: any = networks[networkId];
if (!networkData) {
return false;
}
const contractAddress = getContract() || networkData.address;
return contractAddress;
};
account = async () => {
const accounts = await this.provider?.request({ method: "eth_requestAccounts" });
return accounts[0];
}
balance = async () => {
const balance = await this.provider?.request({
method: "eth_getBalance",
params: [await this.account(), "latest"],
});
return ethers.utils.formatUnits(balance, "ether");
};
nftName = async () => {
return await this.contract?.name();
}
nftSymbol = async () => {
return await this.contract?.symbol();
};
balanceOf = async (account: string) => {
let totalTokensOwnedByAccount = await this.contract?.balanceOf(account);
return totalTokensOwnedByAccount.toNumber();
};
baseURI = async () => {
return await this.contract.baseURI();
};
tokenCount = async () => {
return (await this.contract.totalSupply()).toNumber();
};
getToken = async (index: number) => {
const contract = this.contract;
let price = await contract.priceOf(index);
price = ethers.utils.formatUnits(price, "ether");
const token = {
id: index,
uri: await contract.tokenURI(index),
price,
owner: await contract.ownerOf(index),
forSale: await contract.isForSale(index),
};
return token;
};
buyToken = async (tokenId: number, price: string): Promise<void> => {
return new Promise(async (resolve, reject) => {
this.contract.buy(tokenId, { from: await this.account(), value: ethers.utils.parseEther(price) }).then((tx: any) => {
tx.wait().then(resolve);
}).catch(reject);
});
};
toggleForSale = async (tokenId: number): Promise<void> => {
return new Promise(async (resolve, reject) => {
this.contract.toggleForSale(tokenId, { from: await this.account() }).then((tx: any) => {
tx.wait().then(resolve);
}).catch(reject);
});
};
changeTokenPrice = async (tokenId: number, price: string): Promise<void> => {
const newTokenPrice = ethers.utils.parseEther(price);
return new Promise(async (resolve, reject) => {
this.contract.setPrice(tokenId, newTokenPrice, { from: await this.account() }).then((tx: any) => {
tx.wait().then(resolve);
}).catch(reject);
});
};
deployNew = async (name: string, symbol: string, tokenURI: string, price: string): Promise<string> => {
return new Promise(async (resolve, reject) => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner()
const factory = new ContractFactory(EarlyAccessGame.abi, EarlyAccessGame.bytecode, signer);
console.log(this.contract);
let contract = await factory
.deploy(
name,
symbol,
tokenURI,
ethers.utils.parseEther(price)
);
await contract.deployed()
resolve(contract.address)
});
};
mint = async (tokenCount: number): Promise<void> => {
return new Promise(async (resolve, reject) => {
this.contract
.mintMultiple(await this.account(), tokenCount, { from: await this.account() }).then((tx: any) => {
tx.wait().then(resolve);
}).catch(reject);
});
};
}
|
nft-login/nft-marketplace
|
src/model/blockchain.ts
|
<reponame>nft-login/nft-marketplace<gh_stars>1-10
import { Token } from "./token";
export interface Blockchain {
init(): Promise<void>;
chainId(): Promise<string>;
contractAddress(): Promise<string>;
loadContract(contractAddress: string): Promise<void>;
account(): Promise<string>;
balance(): Promise<string>;
nftName(): Promise<string>;
nftSymbol(): Promise<string>;
balanceOf(account: string): Promise<number>;
baseURI(): Promise<string>;
tokenCount(): Promise<number>;
getToken(tokenId: number): Promise<Token>;
buyToken(tokenId: number, price: string): Promise<void>;
toggleForSale(tokenId: number): Promise<void>;
changeTokenPrice(tokenId: number, newPrice: string): Promise<void>;
deployNew(name: string, symbol: string, tokenURI: string, price: string): Promise<string>;
mint(tokenCount: number): Promise<void>;
}
|
lTyl/phaser-on-nodejs
|
lib/fakeXMLHttpRequest.d.ts
|
<gh_stars>0
/// <reference types="node" />
declare class FakeXMLHttpRequest {
url: string;
status: number;
response: any;
responseText: string;
open(_type: string, url: string): void;
send(): void;
onload(xhr: any, event: any): void;
onerror(err: NodeJS.ErrnoException | null): void;
onprogress(): void;
}
export default FakeXMLHttpRequest;
|
lTyl/phaser-on-nodejs
|
src/fakeXMLHttpRequest.ts
|
import path from 'path'
import fs from 'fs'
class FakeXMLHttpRequest {
public url: string
public status = 200
public response: any
public responseText: string
public open(_type: string, url: string) {
this.url = path.resolve(__dirname, url)
}
public send() {
// use base64 for images and utf8 for json files
const encoding = /\.json$/gm.test(this.url) ? 'utf8' : 'base64'
fs.readFile(this.url, { encoding }, (err, data) => {
if (err) throw err
this.response = data
this.responseText = data
const event = { target: { status: this.status } }
this.onload(this, event)
})
}
public onload(xhr: any, event: any) {}
public onerror(err: NodeJS.ErrnoException | null) {}
public onprogress() {}
}
export default FakeXMLHttpRequest
|
lTyl/phaser-on-nodejs
|
src/index.ts
|
<gh_stars>0
declare global {
namespace NodeJS {
interface Global {
document: any
window: any
Image: any
navigator: any
// XMLHttpRequest: any
HTMLCanvasElement: any
HTMLVideoElement: any
requestAnimationFrame: any
URL: any
phaserOnNodeFPS: number
}
}
}
import Canvas from 'canvas'
import jsdom from 'jsdom'
import FakeXMLHttpRequest from './fakeXMLHttpRequest'
const { JSDOM } = jsdom
const dom = new JSDOM(`<!DOCTYPE html><body></body>`)
const document = dom.window.document
const window = dom.window
window.focus = () => {}
global.document = document
global.window = window
global.Image = Canvas.Image
global.window.Element = undefined
global.navigator = { userAgent: 'node' }
// global.XMLHttpRequest = FakeXMLHttpRequest
global.HTMLCanvasElement = window.HTMLCanvasElement
global.HTMLVideoElement = window.HTMLVideoElement
global.URL = () => {}
global.URL.createObjectURL = (base64: any) => `data:image/png;base64,${base64}`
global.URL.revokeObjectURL = () => {}
// phaser on node variables
global.phaserOnNodeFPS = 15
const animationFrame = (cb: any) => {
if (typeof cb !== 'function') return 0 // this line saves a lot of cpu
window.setTimeout(() => cb(0), 1000 / global.phaserOnNodeFPS)
return 0
}
export { animationFrame }
window.requestAnimationFrame = cb => {
return animationFrame(cb)
}
const requestAnimationFrame = window.requestAnimationFrame
export { requestAnimationFrame }
|
lTyl/phaser-on-nodejs
|
lib/index.d.ts
|
<reponame>lTyl/phaser-on-nodejs
declare global {
namespace NodeJS {
interface Global {
document: any;
window: any;
Image: any;
navigator: any;
HTMLCanvasElement: any;
HTMLVideoElement: any;
requestAnimationFrame: any;
URL: any;
phaserOnNodeFPS: number;
}
}
}
declare const animationFrame: (cb: any) => number;
export { animationFrame };
declare const requestAnimationFrame: (callback: FrameRequestCallback) => number;
export { requestAnimationFrame };
|
xmlking/nodeui
|
src/index.ts
|
<reponame>xmlking/nodeui
export * from './gauge'
export * from './spinner'
export * from './progress'
export * from './sparkline'
export * from './line'
export * from './lineBuffer'
export * from './table'
export * from './banner'
|
xmlking/nodeui
|
src/table.ts
|
<reponame>xmlking/nodeui<filename>src/table.ts
import * as chalk from "chalk";
export class Table {
constructor(public tableContent = '') {
}
// Adds a new table row to the output
tr() {
return this;
};
// Adds a new table cell to the output
td(cellContent, cellWidth) {
return this;
}
// Draw this table to the screen
output() {
return this;
};
}
|
xmlking/nodeui
|
src/line.ts
|
import * as chalk from "chalk";
export class Line {
private lineContent = "";
constructor(public defaultBuffer?) {
}
// Put text in the line
text(text, styles?) {
if(styles) {
styles.forEach(function (element) {
text = element(text);
});
}
this.lineContent += text;
return this;
};
// Put padding in the line.
padding(width, styles?) {
let padding = Array(width + 1).join(" ");
if(styles) {
styles.forEach(function (element) {
padding = element(padding);
});
}
this.lineContent += padding;
return this;
};
// Put padding in the line.
column(text, columnWidth, textStyles?) {
let textWidth = chalk.stripColor(text).length;
if (textWidth > columnWidth) {
this.text(text.slice(0, columnWidth), textStyles);
}
else if (textWidth < columnWidth) {
this.text(text, textStyles);
this.padding(columnWidth - textWidth, []);
}
else {
this.text(text, textStyles);
}
return this;
}
// Fill the rest of the width of the line with space.
fill(styles?) {
let fillWidth = process.stdout.columns - chalk.stripColor(this.lineContent).length;
if (fillWidth > 0)
this.padding(fillWidth, styles);
return this;
}
// Store a line in a line buffer to be output later.
store(buffer?) {
if (typeof buffer == 'undefined') {
if (typeof this.defaultBuffer == 'undefined')
process.stderr.write('Attempt to store a line in a line buffer, without providing a line buffer to store that line in.');
else
this.defaultBuffer.addLine(this);
}
else {
buffer.addLine(this);
}
return this;
}
// Output a line directly to the screen.
output() {
process.stdout.write(this.lineContent + "\n");
return this;
}
// Return the contents
contents() {
return this.lineContent;
}
}
|
xmlking/nodeui
|
examples.ts
|
require('core-js/es7/symbol.js');
import * as chalk from 'chalk';
import * as os from 'os';
import {Banner, Gauge, Spinner, Sparkline, Progress, Line, LineBuffer} from './src/index'
require('draftlog').into(console);
export function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/********************/
const total = os.totalmem();
const free = os.freemem();
const used = total - free;
const human = Math.ceil(used / 1000000) + ' MB';
console.log('' + new Gauge(used, total, 20, total * 0.8, chalk.bold.grey(human)));
/********************/
const reqsPerSec = [10,12,3,7,12,9,23,10,9,19,16,18,12,12];
console.log(new Sparkline(reqsPerSec, 'reqs/sec').toString());
/********************/
const thisProgressBar = new Progress(20);
console.log(thisProgressBar.update(40, 100));
/********************/
const headers = new Line()
.padding(2)
.column('Column One', 20, [chalk.cyan])
.column('Column Two', 20, [chalk.cyan])
.column('Column Three', 20, [chalk.cyan])
.column('Column Four', 20, [chalk.cyan])
.fill()
.output();
const body = new Line()
.padding(2)
.column((Math.random()*100).toFixed(3), 20)
.column((Math.random()*100).toFixed(3), 20)
.column((Math.random()*100).toFixed(3), 20)
.column((Math.random()*100).toFixed(3), 20)
.fill()
.output();
/********************/
const outputBuffer = new LineBuffer({
x: 0,
y: 0,
width: 'console',
height: 'console'
});
const message = new Line(outputBuffer)
.column('Title Placehole', 20, [chalk.green])
.fill()
.store();
const blankLine = new Line(outputBuffer)
.fill()
.store();
const header = new Line(outputBuffer)
.column('Suscipit', 20, [chalk.cyan])
.column('Voluptatem', 20, [chalk.cyan])
.column('Nesciunt', 20, [chalk.cyan])
.column('Laudantium', 11, [chalk.cyan])
.fill()
.store();
let line;
for(let l = 0; l < 20; l++)
{
line = new Line(outputBuffer)
.column((Math.random()*100).toFixed(3), 20)
.column((Math.random()*100).toFixed(3), 20)
.column((Math.random()*100).toFixed(3), 20)
.column((Math.random()*100).toFixed(3), 11)
.fill()
.store();
}
outputBuffer.output();
/********************/
const banner = new Banner(' Node UI is Awesome! See what you can build with this module ');
/********************/
async function* getProgressSlowly() {
let progress = 0;
while (progress <= 100) {
await sleep(50);
progress += Math.round(Math.random() * 5);
if (progress >= 100) {
yield 100;
} else {
yield progress;
}
}
}
async function startDownload() {
// let progress = 0;
// let myProgress = new Progress();
// let myProgress = new Progress(50, chalk.green('Finished download!'), chalk.red('|'), '-');
let myProgress = new Progress(50, chalk.green('Finished download!'));
for await (let progress of getProgressSlowly()) {
myProgress.update(progress, 100)
}
}
(async () => {
console.log('Starting downloads...');
for (let i = 0; i < 10; i ++) {
startDownload()
// await sleep(100)
}
})();
/********************/
const countdown = new Spinner('Exiting in 10 seconds... ');
countdown.start(chalk.bgYellow.blue);
let number = 20;
setInterval(function () {
number--;
countdown.message = 'Exiting in ' + number + ' seconds... ';
if (number === 0) {
process.stdout.write('\n');
process.exit(0);
}
}, 1000);
/********************/
|
xmlking/nodeui
|
src/progress.ts
|
<gh_stars>1-10
import * as chalk from "chalk";
export class Progress {
private draft: any;
constructor(public width = 50, public suffix = '', private filled = chalk.blue('='), private empty = ' ') {
this.draft = console.draft();
}
update(currentValue, maxValue) {
let bar = Math.ceil(currentValue / maxValue * this.width);
if(bar > this.width) bar = this.width;
const display = chalk.dim('[') + this.filled.repeat(bar) + this.empty.repeat(this.width - bar) + chalk.dim('] ') + chalk.yellow(Math.ceil(currentValue / maxValue * 100) + '%');
if(bar < this.width) {
this.draft(display);
} else {
this.draft(display, this.suffix);
}
}
}
|
xmlking/nodeui
|
test.ts
|
<filename>test.ts<gh_stars>1-10
import { SpecReporter, DisplayProcessor } from "jasmine-spec-reporter";
import {Configuration} from "jasmine-spec-reporter/built/configuration";
const Jasmine = require("jasmine");
import SuiteInfo = jasmine.SuiteInfo;
class CustomProcessor extends DisplayProcessor {
public displayJasmineStarted(info: SuiteInfo, log: string): string {
return `TypeScript ${log}`;
}
}
const jrunner = new Jasmine();
jrunner.loadConfig({
spec_dir: 'src',
spec_files: [
"**/*.spec.ts"
],
"stopSpecOnExpectationFailure": false,
"random": false
});
jrunner.env.clearReporters();
jrunner.addReporter(new SpecReporter(<Configuration>{
customProcessors: [CustomProcessor],
spec: {
displayStacktrace: true
}
}));
jrunner.loadConfigFile();
jrunner.execute();
|
xmlking/nodeui
|
src/gauge.ts
|
import * as chalk from "chalk";
export class Gauge {
constructor(public value, public maxValue, public width, public dangerZone, public suffix) {
}
toString() {
if (this.maxValue === 0) {
return '[]';
}
else {
let barLength = Math.ceil(this.value / this.maxValue * this.width);
if (barLength > this.width)
barLength = this.width;
let barColor = chalk.green;
if (this.value > this.dangerZone)
barColor = chalk.red;
return `[${barColor('|'.repeat(barLength))}${'-'.repeat(this.width + 1 - barLength)}] ${this.suffix}`;
}
}
}
|
xmlking/nodeui
|
src/typings.d.ts
|
<filename>src/typings.d.ts
// https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/third-party-lib.md
// https://www.typescriptlang.org/docs/handbook/declaration-merging.html
// declare module 'typeless-package';
// declare var stringScriptGlobal: any;
// import { Observable } from "./observable";
// declare module "./observable" {
// interface Observable<T> {
// map<U>(f: (x: T) => U): Observable<U>;
// }
// }
// Observable.prototype.map = function (f) {
// // ... another exercise for the reader
// }
// declare global {
// interface Console {
// draft(...args: any[]): any;
// }
// }
interface Console {
draft(args?: any[]): any;
}
declare namespace NodeJS {
interface WritableStream {
columns?: number;
rows?: number;
}
}
|
xmlking/nodeui
|
src/spinner.spec.ts
|
<reponame>xmlking/nodeui
import * as chalk from 'chalk';
import {Spinner} from "./spinner";
export function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
describe('Spinner', () => {
let spinner: Spinner;
beforeEach(function(done) {
// require('yargs').argv.serve ? require('draftlog').into(console, true) : require('draftlog').into(console);
require('draftlog').into(console);
spyOn(console, 'log');
spinner = new Spinner('initial text');
done();
});
it('should have initial message', () => {
expect(spinner.message).toEqual('initial text');
});
it('should log 25 times', async (done) => {
spinner.start();
await sleep(800);
spinner.message = 'next message';
await sleep(800);
spinner.message = 'almost done...';
await sleep(800);
spinner.stop();
expect(console.log).toHaveBeenCalledTimes(25);
done()
});
});
|
xmlking/nodeui
|
src/spinner.ts
|
import {ChalkChain} from "chalk";
export class Spinner {
private draft: any;
private timer: any;
private frames: string[] = 'win32' == process.platform ? ['|', '/', '-', '\\'] : ['◜', '◠', '◝', '◞', '◡', '◟'];
constructor(public message: any) {
this.draft = console.draft();
}
start(color?: ChalkChain, interval = 100) {
let i = 0;
this.timer = setInterval(() => {
// Next frame
let frame = this.frames[i++ % this.frames.length];
if(color) {
this.draft(color(`${frame} ${this.message}`));
} else {
this.draft(frame, this.message);
}
}, interval);
}
stop() {
this.draft(); // remove draft line
clearInterval(this.timer);
}
}
|
xmlking/nodeui
|
src/lineBuffer.ts
|
<reponame>xmlking/nodeui
import * as chalk from "chalk";
export interface UserOptions {
x?: number
y?: number
width?: string | number
height?: string | number
scroll?: number
}
export class LineBuffer {
static defaultOptions: UserOptions = {
x: 0,
y: 0,
width: 'console',
height: 'console',
scroll: 0
};
lines = [];
constructor(public userOptions: UserOptions) {
Object.assign(this.userOptions, LineBuffer.defaultOptions);
}
get height(): number {
if (typeof this.userOptions.height === 'string')
return process.stdout.rows;
else
return this.userOptions.height;
}
get width(): number {
if (typeof this.userOptions.width === 'string')
return process.stdout.columns;
else
return this.userOptions.width;
}
addLine(lineObject) {
this.lines.push(lineObject);
return this;
}
fill(fillLine) {
const fillHeight = this.height - this.lines.length;
if (fillHeight > 0) {
for (let i = 0; i < fillHeight; i++) {
this.addLine(fillLine);
}
}
return this;
}
output() {
// First grab a subset of the lines depending on the scroll location and the height of the buffer.
let outputLines;
let sliceEnd;
let outputHeight = this.height;
if (this.userOptions.scroll > this.lines.length)
return;
if (this.lines.length - this.userOptions.scroll > outputHeight)
outputLines = this.lines.slice(this.userOptions.scroll, this.userOptions.scroll + outputHeight);
else
outputLines = this.lines.slice(this.userOptions.scroll);
// First move the cursor to the location where we want the buffer to draw.
let currentY = this.userOptions.y;
outputLines.forEach(function (line) {
// TODO
//process.stdout.write(clc.moveTo(this.userOptions.x, currentY));
line.output();
currentY++;
});
};
}
|
xmlking/nodeui
|
src/banner.ts
|
import * as chalk from "chalk";
import {ChalkChain} from "chalk";
export class Banner {
constructor(public text, color: ChalkChain = chalk.yellow) {
const words = text.split('');
console.log(chalk.dim('*'.repeat(words.length)));
const update = console.draft();
console.log(chalk.dim('*'.repeat(words.length)));
setInterval( () => {
words.push(words.shift());
update(color(words.join('')));
}, 100)
}
}
|
xmlking/nodeui
|
src/gauge.spec.ts
|
import * as chalk from 'chalk';
import {Gauge} from "./gauge";
describe('Gauge', () => {
let gauge: Gauge;
beforeEach(function(done) {
const total = 2000;
const free = 500;
const used = total - free;
const human = used + ' MB';
gauge = new Gauge(used, total, 20, total * 0.8, chalk.bold.grey(human));
done();
});
it('when value is less then dangerZone, it should be green', () => {
let expected = `[${chalk.green('|'.repeat(15))}${'-'.repeat(6)}] ${chalk.bold.grey('1500 MB')}`;
expect(gauge.toString()).toEqual(expected);
});
it('when value is more then dangerZone, it should be red', () => {
gauge.value = 1800;
let expected = `[${chalk.red('|'.repeat(18))}${'-'.repeat(3)}] ${chalk.bold.grey('1500 MB')}`;
expect(gauge.toString()).toEqual(expected);
});
});
|
xmlking/nodeui
|
src/sparkline.ts
|
import * as chalk from "chalk";
const sparklineSymbols = [
'\u2581',
'\u2582',
'\u2583',
'\u2584',
'\u2585',
'\u2586',
'\u2587',
'\u2588'
];
export class Sparkline {
constructor(public points, public suffix = '') {
}
toString() {
let max = Math.max.apply(Math, this.points);
let scaledSequence = this.points.map(function (thisPoint) {
if(max === 0)
return [0, 0];
else if(thisPoint === 0)
return [0, 0];
else
return [
Math.ceil(thisPoint / max * (sparklineSymbols.length-1)),
thisPoint
];
});
let sparklineGraph = '';
let alreadyDrawnMax = false;
scaledSequence.forEach(function (symbolNumber) {
if(symbolNumber[1] == max && !alreadyDrawnMax)
{
sparklineGraph += chalk.green(sparklineSymbols[symbolNumber[0]]);
alreadyDrawnMax = true;
}
else
sparklineGraph += sparklineSymbols[symbolNumber[0]];
});
return sparklineGraph + ' ' + chalk.black.bold(this.points[this.points.length-1] + this.suffix + ' (') + chalk.green(max + this.suffix) + chalk.black.bold(')');
}
}
|
RS022741/io-source
|
src/service/mock-service-proxy/MockServiceRequestValidator.ts
|
import { ServiceOperationTypeEnum, IMockServiceOperation } from './MockServiceOperations';
import { ServiceProxyError } from '../ServiceProxyError';
export class MockServiceRequestValidator {
private isOnline: boolean = false;
public validateRequest<TData, TReturn>(
operationType: ServiceOperationTypeEnum,
resourcePath: string,
matchingOperations: IMockServiceOperation<any, any>[]
) {
if (!this.isOnline) {
const error = 'Could not call service operation because there is no connectivity';
console.warn(error);
throw new ServiceProxyError(resourcePath, 400, error);
}
if (matchingOperations.length > 1) {
const error = `More than 1 ${operationType} service operation found for URL '${resourcePath}'`;
console.warn(error);
throw new ServiceProxyError(resourcePath, 400, error);
}
if (matchingOperations.length === 0) {
const error = `A ${operationType} service operation was not found for URL '${resourcePath}'!`;
console.warn(error);
throw new ServiceProxyError(resourcePath, 400, error);
}
}
public setConnectivityStatus(isOnline: boolean) {
this.isOnline = isOnline;
}
}
|
RS022741/io-source
|
src/serializers/Serializer.ts
|
<filename>src/serializers/Serializer.ts
export type Reviver = (key: string, value: any) => any;
export interface ISerializer {
parse<T>(json: string, reviver?: Reviver): T;
stringify<T>(object: T): string;
}
|
RS022741/io-source
|
src/key-value-storage/LocalForageProxy.ts
|
<gh_stars>1-10
import * as localForage from 'localforage';
import {IKeyValueStorageProxy} from './KeyValueStorageProxy';
import {ISerializer} from '../serializers/Serializer';
export class LocalForageProxy implements IKeyValueStorageProxy {
private localForageStore: LocalForage;
private serializer: ISerializer;
constructor(serializer: ISerializer) {
this.serializer = serializer;
this.localForageStore = localForage.createInstance({
driver: <any[]>[localForage.INDEXEDDB, localForage.WEBSQL, localForage.LOCALSTORAGE]
});
}
public getKeys(): Promise<string[]> {
return this.localForageStore.keys();
}
public getItem<T>(key: string) {
return this.localForageStore.getItem<T>(key)
.then((value: T) => {
if (this.serializer === JSON) {
return value;
} else {
if (value) {
return this.serializer.parse(<any>value) as T;
} else {
return undefined;
}
}
});
}
public setItem<T>(key: string, value: T) {
let processedValue: any = value;
if (this.serializer !== JSON) {
processedValue = this.serializer.stringify(value);
} else {
processedValue = value;
}
return this.localForageStore.setItem(key, processedValue);
}
public getString(key: string) {
return this.getItem<string>(key);
}
public setString(key: string, value: string) {
return this.setItem(key, value);
}
public removeItem(key: string) {
return this.localForageStore.removeItem(key)
.then(() => {
return Promise.resolve();
});
}
}
|
RS022741/io-source
|
src/service/mock-service-proxy/GlobalResponseHeaders.ts
|
import { IServiceResponse } from '../ServiceProxy';
export class GlobalResponseHeaders {
private globalResponseHeaders: {[name: string]: string | (() => string)} = {};
public addGlobalResponseHeader(name: string, value: (() => string) | string) {
this.globalResponseHeaders[name] = value;
}
public addGlobalResponseHeaders(response: IServiceResponse<any>) {
const processedGlobalResponseHeaders = Object.keys(this.globalResponseHeaders)
.reduce((previousHeaderName, currentHeaderName) => {
const value = this.globalResponseHeaders[currentHeaderName];
let processedValue: string;
if (typeof value === 'function') {
processedValue = value();
} else {
processedValue = value;
}
return {
...previousHeaderName,
[currentHeaderName]: processedValue
}
}, {});
response.headers = {
...processedGlobalResponseHeaders,
...response.headers
};
}
}
|
RS022741/io-source
|
src/index.ts
|
export {HttpServiceProxy} from './service/HttpServiceProxy';
export {IServiceProxy, IServiceResponse, IServiceResponseError} from './service/ServiceProxy';
export {IServiceResponseListener, ServiceProxyResponseEvent} from './service/ServiceProxyResponseEvent';
export { MockServiceProxy } from './service/MockServiceProxy';
export { ILoggedServiceCall } from './service/mock-service-proxy/MockServiceExecution';
export { IMockServiceOperation, ServiceOperationTypeEnum } from './service/mock-service-proxy/MockServiceOperations';
export {IKeyValueStorageProxy} from './key-value-storage/KeyValueStorageProxy';
export {LocalForageProxy} from './/key-value-storage/LocalForageProxy';
export {LocalStorageProxy} from './key-value-storage/LocalStorageProxy';
export {MockKeyValueStorageProxy} from './key-value-storage/MockKeyValueStorageProxy';
export {CircularSerializer} from './serializers/CircularSerializer';
export {ServiceProxyError} from './service/ServiceProxyError';
|
RS022741/io-source
|
src/service/ServiceProxy.ts
|
import {ServiceProxyResponseEvent} from './ServiceProxyResponseEvent';
export interface IHttpHeaders {
[headerName: string]: string;
}
export interface IServiceResponseError {
message: string;
}
export interface IServiceResponse<T> {
status: number;
responseBody: T | IServiceResponseError;
headers?: Headers;
}
export interface IServiceCallOptions {
headers?: IHttpHeaders;
deserializeResponse?: boolean;
serializeRequest?: boolean;
returnRawResponseBlob?: boolean;
}
export interface IServiceProxy {
createViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn>;
readViaService<T>(resourcePath: string, options?: IServiceCallOptions): Promise <T>;
patchViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise <TReturn>;
updateViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise <TReturn>;
deleteViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise <TReturn>;
responseEvent: ServiceProxyResponseEvent;
}
|
RS022741/io-source
|
src/serializers/CircularSerializer.ts
|
import {ISerializer, Reviver} from './Serializer';
export class CircularSerializer implements ISerializer {
public parse<T>(json: string, reviver?: Reviver): T {
const obj = JSON.parse(json, reviver);
return <T>JsonNetDecycle.retrocycle(obj);
}
public stringify<T>(object: T): string {
return JSON.stringify(JsonNetDecycle.decycle(object));
}
}
/* tslint:disable */
//https://bitbucket.org/smithkl42/jsonnetdecycle/src
//Douglass Crockford's circular JSON implemenation
//https://github.com/douglascrockford/JSON-js/blob/master/cycle.js
//We may need to go back to Crockford's solution if JSON.net changes its reference style to be in line with the IETF draft proposal
module JsonNetDecycle {
function findReferences(obj: any, catalog: any): void {
// The catalogObject function walks recursively through an object graph
// looking for $id properties. When it finds an object with that property, then
// it adds it to the catalog under that key.
var i: number;
if (obj && typeof obj === 'object') {
var id: string = obj.$id;
if (typeof id === 'string') {
catalog[id] = obj;
}
if (Object.prototype.toString.apply(obj) === '[object Array]') {
for (i = 0; i < obj.length; i += 1) {
findReferences(obj[i], catalog);
}
} else {
for (let name in obj) {
if (obj.hasOwnProperty(name)) {
if (typeof obj[name] === 'object') {
findReferences(obj[name], catalog);
}
}
}
}
}
}
function resolveReferences(obj: any, catalog: any): any {
var i: number, item: any, name: string, id: string;
if (obj && typeof obj === 'object') {
if (Object.prototype.toString.apply(obj) === '[object Array]') {
for (i = 0; i < obj.length; i += 1) {
item = obj[i];
if (item && typeof item === 'object') {
id = item.$ref;
if (typeof id === 'string') {
obj[i] = catalog[id];
} else {
obj[i] = resolveReferences(item, catalog);
}
}
}
} else if (obj.$values && Object.prototype.toString.apply(obj.$values) === '[object Array]') {
var arr = new Array();
for (i = 0; i < obj.$values.length; i += 1) {
item = obj.$values[i];
if (item && typeof item === 'object') {
id = item.$ref;
if (typeof id === 'string') {
arr[i] = catalog[id];
} else {
arr[i] = resolveReferences(item, catalog);
}
} else {
arr[i] = item;
}
}
obj = arr;
} else {
for (name in obj) {
if (obj.hasOwnProperty(name)) {
if (typeof obj[name] === 'object') {
item = obj[name];
if (item) {
id = item.$ref;
if (typeof id === 'string') {
obj[name] = catalog[id];
} else {
obj[name] = resolveReferences(item, catalog);
}
}
}
}
}
}
}
return obj;
}
function getDecycledCopy(obj: any, catalog: any): any {
// The createReferences function recurses through the object, producing the deep copy.
var i: number; // The loop counter
var name: string; // Property name
var nu: any; // The new object or array
switch (typeof obj) {
case 'object':
// typeof null === 'object', so get out if this value is not really an object.
// Also get out if it is a weird builtin object.
if (obj === null ||
obj instanceof Boolean ||
obj instanceof Date ||
obj instanceof Number ||
obj instanceof RegExp ||
obj instanceof String) {
return obj;
}
// If the value is an object or array, look to see if we have already
// encountered it. If so, return a {$id:id} object. This is a hard way, O(n)
// linear search that will get slower as the number of unique objects grows.
// JavaScript really should have a decent dictionary or map class.
for (i = 0; i < catalog.length; i += 1) {
if (catalog[i] === obj) {
return { $ref: i.toString() };
}
}
// Otherwise, accumulate the unique value and its id.
obj.$id = catalog.length.toString();
catalog.push(obj);
// If it is an array, replicate the array.
if (Object.prototype.toString.apply(obj) === '[object Array]') {
nu = [];
for (i = 0; i < obj.length; i += 1) {
nu[i] = getDecycledCopy(obj[i], catalog);
}
} else {
// If it is an object, replicate the object.
nu = {};
for (name in obj) {
if (Object.prototype.hasOwnProperty.call(obj, name)) {
nu[name] = getDecycledCopy(obj[name], catalog);
}
}
}
return nu;
case 'number':
case 'string':
case 'boolean':
default:
return obj;
}
}
export function decycle<T>(obj: T): T {
var catalog: any[] = []; // Keep a reference to each unique object or array
var newObj = getDecycledCopy(obj, catalog);
return newObj;
}
export function retrocycle(obj: any): any {
var catalog: any[] = [];
findReferences(obj, catalog);
return resolveReferences(obj, catalog);
}
}
|
RS022741/io-source
|
src/service/MockServiceProxy.ts
|
<reponame>RS022741/io-source
import { IServiceProxy, IServiceCallOptions, IHttpHeaders } from './ServiceProxy';
import { ServiceProxyResponseEvent } from './ServiceProxyResponseEvent';
import { MockServiceExecution } from './mock-service-proxy/MockServiceExecution';
import { MockServiceParameters } from './mock-service-proxy/MockServiceParameters';
import { GlobalResponseHeaders } from './mock-service-proxy/GlobalResponseHeaders';
import { IMockServiceProxyOptions } from './mock-service-proxy/MockServiceProxyOptions';
import { MockServiceOperations } from './mock-service-proxy/MockServiceOperations';
import { MockServiceDefinitions, IServiceResponseFunction } from './mock-service-proxy/MockServiceDefinitions';
export class MockServiceProxy implements IServiceProxy {
private options: IMockServiceProxyOptions;
private operations: MockServiceOperations;
private parameters: MockServiceParameters;
private serviceProxyResponseEvent: ServiceProxyResponseEvent;
private execution: MockServiceExecution;
private globalResponseHeaders: GlobalResponseHeaders;
private serviceDefinitions: MockServiceDefinitions;
private globalHeaders: IHttpHeaders;
constructor(options: IMockServiceProxyOptions) {
this.options = options;
this.operations = new MockServiceOperations();
this.serviceProxyResponseEvent = new ServiceProxyResponseEvent();
this.parameters = new MockServiceParameters();
this.globalResponseHeaders = new GlobalResponseHeaders();
this.globalHeaders = {};
this.execution = new MockServiceExecution(
this.options,
this.operations,
this.parameters,
this.globalResponseHeaders,
this.serviceProxyResponseEvent,
this.globalHeaders
);
this.serviceDefinitions = new MockServiceDefinitions(this.operations);
this.execution.setConnectivityStatus(true);
}
public setConnectivityStatus(isOnline: boolean) {
this.execution.setConnectivityStatus(isOnline);
}
public createViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.execution.fakeAjaxCall<TData, TReturn>('create', resourcePath, data, options);
}
public readViaService<T>(resourcePath: string, options?: IServiceCallOptions): Promise<T> {
return this.execution.fakeAjaxCall<void, T>('read', resourcePath, null, options);
}
public patchViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.execution.fakeAjaxCall<TData, TReturn>('patch', resourcePath, data, options);
}
public updateViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.execution.fakeAjaxCall<TData, TReturn>('update', resourcePath, data, options);
}
public deleteViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.execution.fakeAjaxCall<TData, TReturn>('delete', resourcePath, data, options);
}
public addCreateOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.serviceDefinitions.addCreateOperation(url, responseFunction);
}
public addReadOperation<TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.serviceDefinitions.addReadOperation(url, responseFunction);
}
public addPatchOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.serviceDefinitions.addUpdateOperation(url, responseFunction);
}
public addUpdateOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.serviceDefinitions.addUpdateOperation(url, responseFunction);
}
public addDeleteOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.serviceDefinitions.addDeleteOperation(url, responseFunction);
}
public addGlobalRequestHeader(headerName: string, headerValue: string) {
this.globalHeaders[headerName] = headerValue;
}
public addGlobalResponseHeader(name: string, value: (() => string) | string) {
this.globalResponseHeaders.addGlobalResponseHeader(name, value);
}
public addGlobalParameter(name: string, value: any) {
this.parameters.setParam(name, value);
}
public get responseEvent() {
return this.serviceProxyResponseEvent;
}
public get loggedCalls() {
return this.execution.loggedCalls;
}
}
|
RS022741/io-source
|
src/service/HttpServiceProxy.ts
|
<gh_stars>1-10
import 'whatwg-fetch';
import {ISerializer} from '../serializers/Serializer';
import {IServiceProxy, IServiceCallOptions} from './ServiceProxy';
import {ServiceProxyResponseEvent} from './ServiceProxyResponseEvent';
import {ServiceProxyError} from './ServiceProxyError';
export class HttpServiceProxy implements IServiceProxy {
private serializer: ISerializer;
private globalHeaders: { [headerName: string]: string};
private baseUrl: string | null;
private serviceProxyResponseEvent: ServiceProxyResponseEvent
constructor(baseUrl: string | null = null, serializer: ISerializer = JSON) {
this.serializer = serializer;
this.globalHeaders = {};
this.baseUrl = baseUrl;
this.serviceProxyResponseEvent = new ServiceProxyResponseEvent();
}
public get responseEvent() {
return this.serviceProxyResponseEvent;
}
public addGlobalRequestHeader(headerName: string, headerValue: string) {
this.globalHeaders[headerName] = headerValue;
}
public createViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.ajaxRequest<TData, TReturn>('POST', resourcePath, data, options);
}
public readViaService<T>(resourcePath: string, options?: IServiceCallOptions): Promise<T> {
return this.ajaxRequest<void, T>('GET', resourcePath, null, options);
}
public patchViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.ajaxRequest<TData, TReturn>('PATCH', resourcePath, data, options);
}
public updateViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.ajaxRequest<TData, TReturn>('PUT', resourcePath, data, options);
}
public deleteViaService<TData, TReturn>(resourcePath: string, data: TData, options?: IServiceCallOptions): Promise<TReturn> {
return this.ajaxRequest<TData, TReturn>('DELETE', resourcePath, data, options);
}
private ajaxRequest<TData, TReturn>(
verb: string,
resourcePath: string,
data?: TData,
options?: IServiceCallOptions
): Promise<TReturn> {
const url = this.baseUrl ? this.baseUrl + resourcePath : resourcePath;
const deserializeResponse = (options && options.deserializeResponse) !== undefined ? options.deserializeResponse : true;
const returnRawResponseBlob = (options && options.returnRawResponseBlob) !== undefined ? options.returnRawResponseBlob : false;
const serializeRequest = (options && options.serializeRequest) !== undefined ? options.serializeRequest : true;
const headersFromOptions = options && options.headers || {};
const defaultHeaders: { [header: string]: string } = {};
let acceptHeaderOverridden = false;
let contentTypeHeaderOverridden = false;
if (options && options.headers) {
Object.keys(options.headers).forEach((header) => {
const lowerCaseHeader = header.toLocaleLowerCase();
if (lowerCaseHeader === 'accept') {
acceptHeaderOverridden = true;
}
if (lowerCaseHeader === 'content-type') {
contentTypeHeaderOverridden = true;
}
});
}
if (!contentTypeHeaderOverridden) {
defaultHeaders['content-type'] = 'application/json';
}
if (!acceptHeaderOverridden) {
defaultHeaders['accept'] = 'application/json';
}
const config: any = {
method: verb,
credentials: 'include'
};
config.headers = { ...defaultHeaders, ...this.globalHeaders, ...headersFromOptions };
if (verb !== 'GET') {
if (serializeRequest) {
config.body = this.serializer.stringify(data);
} else {
config.body = data;
}
}
return fetch(url, config)
.then(response => {
return <Promise<TReturn>>this.handleResponse(
url,
response,
deserializeResponse,
returnRawResponseBlob
);
});
}
private async handleResponse<TReturn>(
url: string,
response: Response,
deserializeResponse: boolean,
returnRawResponseBlob: boolean
): Promise<TReturn> {
if (response.status >= 200 && response.status < 400) {
let responseBody: TReturn = null;
if (returnRawResponseBlob) {
responseBody = await response.blob() as any;
} else {
const responseJson = await response.text()
if (deserializeResponse && !!responseJson) {
responseBody = this.serializer.parse<TReturn>(responseJson);
} else {
responseBody = <TReturn>(<any>responseJson);
}
}
this.serviceProxyResponseEvent.fire({ status: response.status, responseBody, headers: response.headers }, url);
return responseBody;
} else {
return response.text()
.then(errorResponseText => {
const error = new ServiceProxyError(url, response.status, errorResponseText);
this.serviceProxyResponseEvent.fire({ status: response.status, responseBody: errorResponseText, headers: response.headers }, url);
return <Promise<TReturn>>Promise.reject(error);
});
}
}
}
|
RS022741/io-source
|
src/key-value-storage/KeyValueStorageProxy.ts
|
<gh_stars>1-10
import {ISerializer} from '../serializers/Serializer';
export interface IKeyValueStorageProxy {
getKeys(): Promise<string[]>;
getItem<T>(name: string): Promise<T>;
setItem<T>(name: string, data: T): Promise<void>;
getString(name: string): Promise<string>;
setString(name: string, value: string): Promise<void>;
removeItem(name: string): Promise<void>;
}
export abstract class KeyValueStorageProxy implements IKeyValueStorageProxy {
private serializer: ISerializer;
private dataMap: { [key: string]: any };
constructor(serializer: ISerializer, dataMap: {[key: string]: any}) {
this.serializer = serializer;
this.dataMap = dataMap;
}
public getItem<T>(name: string): Promise<T> {
return this
.getString(name)
.then(itemString => {
if (itemString) {
return this.serializer.parse<T>(itemString);
} else {
return undefined;
}
});
}
public getKeys() {
return Promise.resolve(Object.keys(this.dataMap));
}
public removeItem(name: string) {
delete this.dataMap[name];
return Promise.resolve();
}
public setItem<T>(name: string, data: T) {
let stringifiedData: string;
if (typeof data === 'string') {
stringifiedData = data;
} else {
stringifiedData = this.serializer.stringify<T>(data);
}
return this.setString(name, <string>stringifiedData);
}
public getString(name: string): Promise<string> {
return Promise.resolve(this.dataMap[name]);
}
public setString(name: string, data: string) {
this.dataMap[name] = data;
return Promise.resolve();
}
}
|
RS022741/io-source
|
src/key-value-storage/LocalStorageProxy.ts
|
<filename>src/key-value-storage/LocalStorageProxy.ts
import {ISerializer} from '../serializers/Serializer';
import {KeyValueStorageProxy, IKeyValueStorageProxy} from './KeyValueStorageProxy';
export class LocalStorageProxy extends KeyValueStorageProxy implements IKeyValueStorageProxy {
constructor(serializer: ISerializer) {
super(serializer, localStorage);
}
}
|
RS022741/io-source
|
src/service/mock-service-proxy/MockServiceOperations.ts
|
import { IServiceCallOptions, IServiceResponse } from '../ServiceProxy';
export interface IMockServiceOperationResponseFunction<TRequest, TResponse> {
(urlMatches?: string[], requestBody?: TRequest, options?: IServiceCallOptions, params?: any): IServiceResponse<TResponse>;
}
export interface IMockServiceOperation<TRequest, TResponse> {
operationType: ServiceOperationTypeEnum;
urlRegex: RegExp;
response: IMockServiceOperationResponseFunction<TRequest, TResponse>;
}
export type ServiceOperationTypeEnum =
'create'
| 'read'
| 'patch'
| 'update'
| 'delete';
export class MockServiceOperations {
private serviceOperations: IMockServiceOperation<any, any>[] = [];
public add<TRequest, TResponse>(operation: IMockServiceOperation<TRequest, TResponse>) {
this.serviceOperations.push(operation);
}
public getMatchingOperations<TData, TReturn>(
operationType: ServiceOperationTypeEnum,
resourcePath: string
) {
const operations = this.serviceOperations;
const matchingOperations: IMockServiceOperation<any, any>[] = [];
for (let i = 0; i < operations.length; i++) {
const operation = operations[i];
const urlMatches = resourcePath.match(operation.urlRegex);
if (urlMatches && operation.operationType === operationType) {
matchingOperations.push(operation);
}
}
return matchingOperations;
}
}
|
RS022741/io-source
|
src/service/ServiceProxyError.ts
|
export class ServiceProxyError extends Error {
public readonly httpStatus: number;
public readonly responseText: string
public readonly details: any;
constructor(url: string, httpStatus: number, responseBody: any) {
super(`Service call to ${url} resulted in an error with status code ${httpStatus}. See the details and responseText properties for more info.`);
Object.setPrototypeOf(this, ServiceProxyError.prototype);
this.httpStatus = httpStatus;
if (typeof responseBody === 'string') {
this.responseText = responseBody;
try {
const details = JSON.parse(responseBody);
if (typeof details === 'object') {
this.details = details;
}
} catch (e) {
//Eat it
}
} else if (typeof responseBody === 'object') {
this.responseText = JSON.stringify(responseBody);
this.details = responseBody;
}
}
}
|
RS022741/io-source
|
src/service/mock-service-proxy/MockServiceParameters.ts
|
export class MockServiceParameters {
public params: any = {};
public setParams(params: any) {
this.params = params;
}
public setParam(paramName: string, paramValue: any) {
this.params[paramName] = paramValue;
}
}
|
RS022741/io-source
|
src/service/ServiceProxyResponseEvent.ts
|
<filename>src/service/ServiceProxyResponseEvent.ts
import {IServiceResponse} from './ServiceProxy';
export interface IServiceResponseListener {
(response: IServiceResponse<any>, url?: string): void;
}
export class ServiceProxyResponseEvent {
private listeners: IServiceResponseListener[] = [];
public listen(callback: IServiceResponseListener) {
this.listeners.push(callback);
}
public fire(response: IServiceResponse<any>, url?: string) {
this.listeners.forEach(listener => {
listener(response, url);
});
}
}
|
RS022741/io-source
|
src/service/mock-service-proxy/MockServiceProxyOptions.ts
|
<reponame>RS022741/io-source<filename>src/service/mock-service-proxy/MockServiceProxyOptions.ts
export interface IMockServiceProxyOptions {
addRandomDelays?: boolean;
maxRandomDelayMilliseconds?: number;
}
|
RS022741/io-source
|
src/service/mock-service-proxy/MockServiceDefinitions.ts
|
<gh_stars>1-10
import { MockServiceOperations, IMockServiceOperationResponseFunction } from './MockServiceOperations';
import { IServiceResponse } from '../ServiceProxy';
export interface IServiceResponseFunctionBaseArgs {
urlParameters?: string;
requestBody?: any;
globalServiceParameters?: any;
}
export interface IServiceResponseFunctionUrlParameter {
[key: string]: string;
}
export interface IServiceResponseFunction<TResponse> {
(urlParameters?: any, requestBody?: any, globalServiceParameters?: any): TResponse | IServiceResponse<TResponse>
}
export class MockServiceDefinitions {
private mockServiceOperations: MockServiceOperations;
constructor(mockServiceOperations: MockServiceOperations) {
this.mockServiceOperations = mockServiceOperations;
}
public addCreateOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.mockServiceOperations.add({
operationType: 'create',
urlRegex: this.convertUrlToRegex(url),
response: this.getResponseFunction<TRequest, TResponse>(url, responseFunction)
});
}
public addReadOperation<TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.mockServiceOperations.add({
operationType: 'read',
urlRegex: this.convertUrlToRegex(url),
response: this.getResponseFunction<void, TResponse>(url, responseFunction)
});
}
public addPatchOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.mockServiceOperations.add({
operationType: 'patch',
urlRegex: this.convertUrlToRegex(url),
response: this.getResponseFunction<TRequest, TResponse>(url, responseFunction)
});
}
public addUpdateOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.mockServiceOperations.add({
operationType: 'update',
urlRegex: this.convertUrlToRegex(url),
response: this.getResponseFunction<TRequest, TResponse>(url, responseFunction)
});
}
public addDeleteOperation<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
) {
this.mockServiceOperations.add({
operationType: 'delete',
urlRegex: this.convertUrlToRegex(url),
response: this.getResponseFunction<TRequest, TResponse>(url, responseFunction)
});
}
private getResponseFunction<TRequest, TResponse>(
url: string | RegExp,
responseFunction?: IServiceResponseFunction<TResponse>
): IMockServiceOperationResponseFunction<TRequest, TResponse> {
return (urlMatches: RegExpMatchArray, requestBody: TRequest, globalServiceParameters: any): IServiceResponse<TResponse> => {
if (!responseFunction) {
return {
status: 204,
responseBody: null as TResponse
};
}
const response = responseFunction(
this.getUrlParams(url, urlMatches),
requestBody,
globalServiceParameters
);
if (!response) {
return {
status: 204,
responseBody: null
};
} else if (
(response as IServiceResponse<TResponse>).responseBody !== undefined
&& (response as IServiceResponse<TResponse>).status
) {
return {
status: (response as IServiceResponse<TResponse>).status,
responseBody: (response as IServiceResponse<TResponse>).responseBody
};
} else {
return {
status: 200,
responseBody: response as TResponse
};
}
};
}
private getUrlParams(url: string | RegExp, urlMatches: RegExpMatchArray): Object | RegExpMatchArray {
if (url instanceof RegExp) {
return urlMatches;
} else {
const matches = url.match(/\{([a-zA-Z0-9_-]+)\}/g);
const urlParams: any = {};
matches && matches.forEach((value, index) => {
urlParams[value.replace('{', '').replace('}', '')] = urlMatches[index + 1];
});
return urlParams;
}
}
private convertUrlToRegex(url: string | RegExp) {
if (url instanceof RegExp) {
return url;
} else {
return new RegExp(`^${url.replace(/\//g, '\/').replace(/\{.*\}/g, '([A-Za-z0-9-_]*)')}$`);
}
}
}
|
RS022741/io-source
|
src/key-value-storage/MockKeyValueStorageProxy.ts
|
import {IKeyValueStorageProxy} from './KeyValueStorageProxy';
export class MockKeyValueStorageProxy implements IKeyValueStorageProxy {
private data: {[key: string]: any} = {};
public getKeys(): Promise<string[]> {
return Promise.resolve(Object.keys(this.data));
}
public getItem<T>(name: string): Promise<T> {
return Promise.resolve<T>(this.data[name]);
}
public setItem<T>(name: string, data: T): Promise<void> {
this.data[name] = data;
return Promise.resolve();
}
public getString(name: string) {
return this.getItem<string>(name);
}
public setString(name: string, value: string) {
return this.setItem(name, value);
}
public removeItem(name: string): Promise<void> {
delete this.data[name];
return Promise.resolve();
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/app.module.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { APP_BASE_HREF } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { AppComponent } from './app.component';
import { SidebarModule } from './sidebar/sidebar.module';
import { FixedPluginModule } from './shared/fixedplugin/fixedplugin.module';
import { FooterModule } from './shared/footer/footer.module';
import { NavbarModule} from './shared/navbar/navbar.module';
import { AdminLayoutComponent } from './layouts/admin/admin-layout.component';
import { AuthLayoutComponent } from './layouts/auth/auth-layout.component';
import { AppRoutes } from './app.routing';
import { HttpClientModule } from '@angular/common/http';
import { AuthGuard } from './_guards/index';
import { ListVolunteersComponent } from './list-volunteers/list-volunteers.component';
import { NewVolunteerComponent } from './new-volunteer/new-volunteer.component';
import { ListFamilyComponent } from './list-family/list-family.component';
import { NewFamilyComponent } from './new-family/new-family.component';
import { NewBusinessComponent } from './new-business/new-business.component';
import { ListBusinessComponent } from './list-business/list-business.component';
import { ListServicesComponent } from './list-services/list-services.component';
import { YesNoPipe } from './yesno.pipe';
import { YesNoActivePipe } from './yesnoactive.pipe';
import { RequestServiceComponent } from './request-service/request-service.component';
import { EditServicesComponent } from './edit-services/edit-services.component';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { UserComponent } from './userpage/user.component';
import { ClipboardModule } from '@angular/cdk/clipboard';
import { ActiveServicesComponent } from './active-services/active-services.component';
import { FamilyApplicationComponent } from './family-application/family-application.component';
import { ActiveFamilyComponent } from './active-family/active-family.component';
import { RequestServiceLoginComponent } from './request-service-login/request-service-login.component';
import { BusinessCategoryComponent } from './business-category/business-category.component';
import { NewCategoryComponent } from './new-category/new-category.component';
import { BusinessSignupComponent } from './business-signup/business-signup.component';
import { YesNoApprovedPipe } from './yesnoapproved.pipe';
import { VpizzaHistoryComponent } from './vpizza-history/vpizza-history.component';
<<<<<<< Updated upstream
=======
import { ContactPipe } from './contact.pipe';
>>>>>>> Stashed changes
@NgModule({
imports: [
BrowserAnimationsModule,
FormsModule,
RouterModule.forRoot(AppRoutes,{
useHash: true
}),
NgbModule,
HttpModule,
SidebarModule,
NavbarModule,
FooterModule,
ClipboardModule,
FixedPluginModule,
HttpClientModule,
CommonModule
],
declarations: [
AppComponent,
AdminLayoutComponent,
AuthLayoutComponent,
ListVolunteersComponent,
NewVolunteerComponent,
ListFamilyComponent,
NewFamilyComponent,
NewBusinessComponent,
ListBusinessComponent,
ListServicesComponent,
YesNoPipe,
YesNoActivePipe,
RequestServiceComponent,
EditServicesComponent,
UserComponent,
ActiveServicesComponent,
FamilyApplicationComponent,
ActiveFamilyComponent,
RequestServiceLoginComponent,
BusinessCategoryComponent,
NewCategoryComponent,
BusinessSignupComponent,
YesNoApprovedPipe,
<<<<<<< Updated upstream
VpizzaHistoryComponent
=======
VpizzaHistoryComponent,
ContactPipe
>>>>>>> Stashed changes
],
providers: [AuthGuard],
bootstrap: [ AppComponent ]
})
export class AppModule { }
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/request-service/request-service.component.ts
|
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { NgForm } from '@angular/forms';
import { ServicesService } from '../services.service';
import { BusinessService } from '../business.service';
import { FamilyService } from '../family.service';
import { Router, ActivatedRoute } from '@angular/router';
import Swal from 'sweetalert2';
import { analyzeAndValidateNgModules } from '@angular/compiler';
import { ServiceModel } from 'app/service.model';
import { FamilyModel } from 'app/family.model';
declare interface DataTable {
headerRow: string[];
dataRows: string[];
}
declare var $: any;
@Component({
selector: 'app-request-service',
templateUrl: './request-service.component.html',
styleUrls: ['./request-service.component.css'],
providers: [DatePipe]
})
export class RequestServiceComponent implements OnInit {
public errorInForm: boolean;
public categoryList: [];
public serviceList: [];
public dataTable: DataTable;
public familyId;
public family: FamilyModel;
public requestedServices: any = [];
public requestList: any = [];
public note;
public currentDate = new Date();
public today;
public reqCount = 0;
public addDisable = false;
public pizzaDisable = false;
public submitDisable = true;
constructor(public serviceService: ServicesService, public businessService: BusinessService, public familyService: FamilyService, public router: Router, private datePipe: DatePipe, private activeRoute: ActivatedRoute) {
this.today = this.datePipe.transform(this.currentDate, 'yyyy-MM-dd');
}
ngOnInit(): void {
this.activeRoute.queryParams.subscribe(params => {
this.familyId = params['familyId'];
});
if (!this.familyId) {
this.router.navigate(['/request/login']);
}
else {
this.familyService.getFamilyById(this.familyId).subscribe((responseData) => {
if(responseData) {
this.family = responseData.results[0];
this.family.first_name = responseData.results[0]['first_name'] + ' ' + responseData.results[0]['last_name'];
this.family.last_name = responseData.results[0]['cancer_warrior_name'];
}
else {
this.router.navigate(['/request/login']);
}
})
}
this.serviceService.getAllCategories().subscribe((responseData) => {
if (responseData) {
this.categoryList = responseData.results;
}
});
this.businessService.getActiveBusinesses().subscribe((responseData) => {
if (responseData) {
this.serviceList = responseData.results;
}
});
this.dataTable = {
headerRow: [ 'Service', 'Notes', 'Delete?'],
dataRows: this.requestList
};
}
ngAfterViewInit(){
$('#datatable').DataTable({
searching: false,
paging: false,
info: false,
"language": {
"emptyTable": "No services requested."
},
bAutoWidth: false,
aoColumns : [
{ sWidth: '49%' },
{ sWidth: '49%' },
{ sWidth: '2%' },
],
});
var table = $('#datatable').DataTable();
}
onAdd(form: NgForm) {
if ( form.invalid ) { // Validating form has data
console.log('returned');
this.errorInForm = true;
return;
}
else {
let item;
item = {serviceId: form.value.req1.id, service: form.value.req1.name, notes: form.value.notes};
this.requestList.push(item);
this.note = null;
this.submitDisable = false;
this.reqCount++;
if(this.reqCount >= 8){
this.addDisable = true;
}
}
}
onDelete(serviceId) {
this.requestList.splice(serviceId - 1, 1);
this.reqCount--;
if(this.reqCount < 8) {
this.addDisable = false;
}
if(this.reqCount <= 0) {
this.submitDisable = true;
}
}
onSave(form: NgForm) {
if ( form.invalid ) { // Validating form has data
console.log('returned');
this.errorInForm = true;
return;
}
else {
Swal.fire({
title: "Submit request?",
text: "Please double-check your request before submitting.",
type: "info",
showCancelButton: true,
cancelButtonClass: "btn btn-info",
confirmButtonClass: "btn btn-success",
confirmButtonText: "Submit it!",
cancelButtonText: "Go back",
reverseButtons: true
})
.then((fulfill) => {
if(fulfill.value) {
for(let i = 0; i < this.requestList.length; i++){
if(this.requestList[i]['serviceId'] || this.requestList[i]['serviceId'] != "") {
const request: any = {
familyId: this.familyId,
businessId: this.requestList[i]['serviceId'],
notes: this.requestList[i]['notes']
};
this.serviceService.saveRequest(request).subscribe((reqResponseData) => {
if (reqResponseData.requestCreated) {
this.addDisable = true;
this.submitDisable = true;
Swal.fire({
title: "Request Submitted!",
text: "Your request for service was submitted successfully. Thank you! You may now close this form.",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "success"
})
}
});
}
}
}
});
}
}
requestRefill(form: NgForm) {
Swal.fire({
title: "Request a V Pizza card refill?",
text: "If you have recently used your V Pizza gift card and would like to request a refill, please click \"Yes\" below.",
imageUrl: "../assets/img/VP_logo.png",
imageWidth: 150,
imageHeight: 121,
showCancelButton: true,
cancelButtonClass: "btn btn-info",
confirmButtonClass: "btn btn-success",
confirmButtonText: "Yes, refill my card!",
cancelButtonText: "No thanks",
reverseButtons: true
})
.then((fulfill) => {
if(fulfill.value) {
const request: any = {
familyId: this.familyId,
businessId: -1
};
this.serviceService.saveRequest(request).subscribe((reqResponseData) => {
if (reqResponseData.requestCreated) {
this.pizzaDisable = true;
Swal.fire({
title: "Refill Request Submitted!",
text: "Your refill request was submitted successfully. You may now submit additional requests for service, or close this form.",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "success"
})
}
});
}
});
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/edit-services/edit-services.component.ts
|
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ServicesService } from '../services.service';
import { Router, ActivatedRoute } from '@angular/router';
import {Md5} from 'ts-md5/dist/md5';
import Swal from 'sweetalert2';
import { ServiceModel } from 'app/service.model';
declare var $: any;
@Component({
selector: 'app-edit-service',
templateUrl: './edit-services.component.html',
styleUrls: ['./edit-services.component.css']
})
export class EditServicesComponent implements OnInit {
private md5 = new Md5();
public serviceId: number;
public service: ServiceModel;
errorInForm: boolean;
passwordMatch: boolean;
constructor(public serviceService: ServicesService, public router: Router, private activeRoute: ActivatedRoute) {
this.activeRoute.queryParams.subscribe(params => {
this.serviceId = params['id'];
});
if (this.serviceId) {
this.serviceService.getRequestById(this.serviceId).subscribe((responseData) => {
if (responseData) {
this.service = responseData.results[0];
}
});
}
}
ngOnInit(): void {
}
onSave(form: NgForm) {
if ( form.invalid ) { // Validating form has data
console.log('returned');
this.errorInForm = true;
return;
}
else {
const request: any = {
familyName: form.value.familyName,
businessCategory: form.value.businessCategory,
notifiedBusiness: form.value.businessContacted,
notifiedFamily: form.value.familyContacted,
active: form.value.active
};
this.serviceService.saveRequest(request).subscribe((responseData) => {
if (responseData.requestCreated) {
Swal.fire({
title: "Request updated!",
text: "Your request for service was updated successfully. Thank you!",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "success"
})
}
});
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/contact.pipe.spec.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
import { ContactPipe } from './contact.pipe';
describe('ContactPipe', () => {
it('create an instance', () => {
const pipe = new ContactPipe();
expect(pipe).toBeTruthy();
});
});
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/list-volunteers/list-volunteers.component.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
import { Component, OnInit } from '@angular/core';
import { UsersService } from '../users.service';
import { UserModel } from '../user.model';
import { Router } from '@angular/router';
declare var $: any;
declare interface DataTable {
headerRow: string[];
footerRow: string[];
dataRows: UserModel[];
}
@Component({
selector: 'app-list-volunteers',
templateUrl: './list-volunteers.component.html',
styleUrls: ['./list-volunteers.component.css']
})
export class ListVolunteersComponent implements OnInit {
public usersList: UserModel[];
public dataTable: DataTable;
public userRole: number;
constructor(public userService: UsersService, public router: Router) {
this.userRole = JSON.parse(localStorage.getItem('currentUser')).role;
}
ngOnInit() {
this.userService.listUsers().subscribe((usersReturned) => {
if (usersReturned) {
this.usersList = usersReturned.results;
this.dataTable = {
headerRow: [ 'Id', 'Name', 'Email', 'Address', 'role', 'Status', 'Actions' ],
footerRow: [ 'Id', 'Name', 'Email', 'Address', 'role', 'Status', 'Actions'],
dataRows: this.usersList
};
}
});
}
ngAfterViewInit(){
$('#datatable').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
var table = $('#datatable').DataTable();
}
getRoleDescription(roleId: number) {
if (roleId === 1) {
return 'Administrator';
} else {
return 'Volunteer';
}
}
getStatusDescription(statusId: number) {
if (statusId == 1) {
return 'Active';
} else {
return 'Inactive';
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/new-category/new-category.component.ts
|
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { BusinessService } from 'app/business.service';
import Swal from 'sweetalert2';
import { Router, ActivatedRoute, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET } from '@angular/router';
@Component({
selector: 'app-new-category',
templateUrl: './new-category.component.html',
styleUrls: ['./new-category.component.css']
})
export class NewCategoryComponent implements OnInit {
public errorInForm: Boolean;
private loggedInUser: any;
public viewMode: boolean;
public editMode: boolean;
public creationMode: boolean;
private categoryId: number;
public category: any;
constructor(public businessService: BusinessService, public router: Router, private activeRoute: ActivatedRoute) {
const tree: UrlTree = router.parseUrl(this.router.url);
const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
const s: UrlSegment[] = g.segments;
console.log(s[2].path)
if (s[2].path === 'new') {
this.creationMode = true;
}
if (s[2].path === 'view') {
this.viewMode = true;
}
if (s[2].path === 'edit') {
this.editMode = true;
}
this.activeRoute.queryParams.subscribe(params => {
this.categoryId = params['categoryId'];
});
if (this.categoryId) {
this.businessService.getCategoryById(this.categoryId).subscribe((responseData) => {
if (responseData) {
this.category = responseData.results[0];
}
});
}
this.loggedInUser = JSON.parse(localStorage.getItem('currentUser')).email;
}
ngOnInit(): void {
}
onSave(form: NgForm) {
if ( form.invalid ) {
console.log('returned');
this.errorInForm = true;
return;
} else {
if(this.creationMode){
const category: any = {
categoryName: form.value.categoryName,
createdBy: this.loggedInUser,
};
this.businessService.createCategory(category).subscribe((responseData) => {
if (responseData.categoryCreated) {
Swal.fire({
title: 'Record Created Successfully!',
text: 'The category was created successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
this.router.navigate(['/business/category']);
}
});
}
if(this.editMode){
const category: any = {
id: this.categoryId,
categoryName: form.value.categoryName,
updatedBy: this.loggedInUser,
};
this.businessService.updateCategory(category).subscribe((responseData) => {
if (responseData.categoryUpdated) {
Swal.fire({
title: 'Record Updated Successfully!',
text: 'The category was updated successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
this.router.navigate(['/business/category']);
}
});
}
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/note.model.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject<filename>src/app/note.model.ts
export interface NoteModel {
id: number;
familyId: number;
createdBy: string;
createdDate: string;
contents: string;
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/yesnoapproved.pipe.spec.ts
|
import { YesNoApprovedPipe } from './yesnoapproved.pipe';
describe('YesNoApprovedPipe', () => {
it('create an instance', () => {
const pipe = new YesNoApprovedPipe();
expect(pipe).toBeTruthy();
});
});
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/auth.service.ts
|
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { HttpClient } from '../../node_modules/@angular/common/http';
import { Http, ResponseContentType } from '@angular/http';
import { map } from 'rxjs/operators';
import {environment} from '../environments/environment';
import { UserModel } from './user.model';
import { UserAPIResponse } from './response.model';
import {Md5} from 'ts-md5/dist/md5';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private usersList: any = [];
private response: UserAPIResponse;
private serverAddress = environment.backendURL;
// tslint:disable-next-line: deprecation
constructor(private httpClient: HttpClient, private router: Router, private http: Http) {}
getUser(username: string, password: string) {
const md5 = new Md5();
const hashedPasswrod = md5.appendStr(password).end();
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/' + username + '/password/' + hashedPasswrod);
}
getCurrentUser(username: string) {
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/current/' + username);
}
postLoginHistory(loginHistory) {
return this.httpClient.post<{sessionSaved: Boolean}>(this.serverAddress + 'api/volunteer/login/new/', loginHistory);
}
getIPAddress(){
return this.httpClient.get<{ipObject: string}>("http://api.ipify.org/?format=json");
}
getLoginHistory(userId: number) {
return this.httpClient.get<{loginHistory: any}>(this.serverAddress + 'api/volunteer/login/history/' + userId);
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/pages/lock/lock.component.ts
|
<filename>src/app/pages/lock/lock.component.ts
import { Component, OnInit, ElementRef } from '@angular/core';
import { Router, ActivatedRoute, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET } from '@angular/router';
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import {EmailService} from '../../email.service';
import {UsersService} from '../../users.service';
import { NgForm } from '@angular/forms';
import { UserModel } from 'app/user.model';
import {environment} from '../../../environments/environment';
import {Md5} from 'ts-md5/dist/md5';
declare var $:any;
@Component({
moduleId:module.id,
selector: 'lock-cmp',
templateUrl: './lock.component.html'
})
export class LockComponent implements OnInit{
test : Date = new Date();
public md5 = new Md5();
private toggleButton;
private sidebarVisible: boolean;
private nativeElement: Node;
public emailSent: boolean;
public emailNotFound: boolean;
private userModel: UserModel;
public errorInForm: boolean;
private passwordResetURL = environment.passwordResetURL;
private userEmail: string;
private userId: number;
public resetMode: boolean;
public recoverMode: boolean;
public passwordMismatch: boolean;
constructor(private element : ElementRef, public emailService: EmailService, public userService: UsersService, public router: Router, private activeRoute: ActivatedRoute) {
const tree: UrlTree = router.parseUrl(this.router.url);
const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
const s: UrlSegment[] = g.segments;
if (s[1].path === 'reset') {
this.resetMode = true;
this.activeRoute.queryParams.subscribe(params => {
this.userEmail = params['id'];
this.userService.getVolunteerByEmail(atob(this.userEmail)).subscribe((response) => {
if (response.status === 200) {
this.userId = response.body['results'][0].record_id;
}
});
});
} else {
this.recoverMode = true;
}
}
checkFullPageBackgroundImage(){
var $page = $('.full-page');
var image_src = $page.data('image');
if(image_src !== undefined){
var image_container = '<div class="full-page-background" style="background-image: url(' + image_src + ') "/>'
$page.append(image_container);
}
};
ngOnInit(){
this.checkFullPageBackgroundImage();
var body = document.getElementsByTagName('body')[0];
body.classList.add('lock-page');
var navbar : HTMLElement = this.element.nativeElement;
this.toggleButton = navbar.getElementsByClassName('navbar-toggle')[0];
setTimeout(function(){
// after 1000 ms we add the class animated to the login/register card
$('.card').removeClass('card-hidden');
}, 700)
}
ngOnDestroy(){
var body = document.getElementsByTagName('body')[0];
body.classList.remove('lock-page');
}
sidebarToggle(){
var toggleButton = this.toggleButton;
var body = document.getElementsByTagName('body')[0];
var sidebar = document.getElementsByClassName('navbar-collapse')[0];
if(this.sidebarVisible == false){
setTimeout(function(){
toggleButton.classList.add('toggled');
},500);
body.classList.add('nav-open');
this.sidebarVisible = true;
} else {
this.toggleButton.classList.remove('toggled');
this.sidebarVisible = false;
body.classList.remove('nav-open');
}
}
confirmPassword(password: string, confirmPassword: string) {
if (password === confirmPassword) {
return true;
} else {
return false;
}
}
forgotPassword(form: NgForm) {
if ( form.invalid ) {
this.errorInForm = true;
return;
} else {
this.errorInForm = false;
this.userService.getVolunteerByEmail(form.value.email).subscribe((response) => {
if (response.status === 200) {
this.emailNotFound = false;
const emailObject = {
mailTo: form.value.email,
subject: 'Password Reset',
messageBody: this.passwordResetURL + '?id=' + btoa(form.value.email)
}
this.emailService.sendEmail(emailObject).subscribe((mailResponse) => {
if (mailResponse) {
this.emailSent = true;
}
});
} else {
this.emailNotFound = true;
this.emailSent = false;
}
});
}
}
resetPassword(form: NgForm) {
if ( form.invalid ) {
this.errorInForm = true;
return;
} else {
if(this.confirmPassword(form.value.password, form.value.recoverPassword)){
const md5 = new Md5();
const passwordHash = md5.appendStr(form.value.password).end();
this.userService.changePassword(passwordHash, this.userId).subscribe((responseData) => {
if (responseData.userUpdated) {
this.router.navigate(['/pages/login'], { queryParams: { fromResetPassword: true } });
}
});
} else{
this.passwordMismatch = true;
}
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/active-services/active-services.component.ts
|
import { Component, OnInit } from '@angular/core';
import { ServicesService } from '../services.service';
import { ServiceModel } from '../service.model';
import { Router, ActivatedRoute } from '@angular/router';
import Swal from 'sweetalert2';
declare var $: any;
declare interface DataTable {
headerRow: string[];
footerRow: string[];
dataRows: ServiceModel[];
}
@Component({
selector: 'app-active-services',
templateUrl: './active-services.component.html',
styleUrls: ['./active-services.component.css']
})
export class ActiveServicesComponent implements OnInit {
public dataList;
public dataTable: DataTable;
constructor(public serviceService: ServicesService, public router: Router, private activeRoute: ActivatedRoute) {}
ngOnInit() {
this.serviceService.getAllServices().subscribe((returned) => {
if (returned) {
this.dataList = returned.results;
this.dataTable = {
headerRow: [ 'ID', 'Business Name', 'Category', 'Status'],
footerRow: [ 'ID', 'Business Name', 'Category', 'Status'],
dataRows: this.dataList
};
}
});
}
ngAfterViewInit(){
$('#table').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
}
markServiceActive(itemId) {
Swal.fire({
title: "MARK ACTIVE?",
text: "Would you like to mark this service as active? It will then become selectable by families.",
type: "warning",
showCancelButton: true,
cancelButtonClass: "btn btn-info",
confirmButtonClass: "btn btn-success",
confirmButtonText: "Yes, mark it!",
cancelButtonText: "No, leave it!",
reverseButtons: true
})
.then((mark) => {
if(mark.value) {
const request: any = {
id: itemId,
}
this.serviceService.markServiceActive(request).subscribe((responseData) => {
if (responseData.requestFulfilled) {
Swal.fire({
title: "Service changed!",
text: "The service has been made active.",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "success"
}).then((confirm) => {
if(confirm){
window.location.reload()
}
})
}
});
}
});
}
markServiceInactive(itemId) {
Swal.fire({
title: "MARK INACTIVE?",
text: "Would you like to mark this service as inactive? It will no longer be selectable by families.",
type: "warning",
showCancelButton: true,
cancelButtonClass: "btn btn-info",
confirmButtonClass: "btn btn-danger",
confirmButtonText: "Yes, mark it!",
cancelButtonText: "No, leave it!",
reverseButtons: true
})
.then((mark) => {
if(mark.value) {
const request: any = {
id: itemId,
}
this.serviceService.markServiceInactive(request).subscribe((responseData) => {
if (responseData.requestFulfilled) {
Swal.fire({
title: "Service changed!",
text: "The service has been made inactive.",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "success"
}).then((confirm) => {
if(confirm){
window.location.reload()
}
})
}
});
}
});
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/family.service.ts
|
<filename>src/app/family.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http, ResponseContentType } from '@angular/http';
import { map } from 'rxjs/operators';
import {environment} from '../environments/environment';
import { UserModel } from './user.model';
import { UserAPIResponse } from './response.model';
import { FamilyAPIResponse } from './family_response.model';
@Injectable({
providedIn: 'root'
})
export class FamilyService{
private servicesList: any = [];
private serverAddress = environment.backendURL;
constructor(private httpClient: HttpClient, private router: Router, private http: Http) { }
saveFamily(family: any) {
return this.httpClient.post<{familyCreated: boolean}>(this.serverAddress + 'api/family/new', family);
}
listFamily():any{
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/');
}
markFamilyActive(family: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/family/markActive', family);
}
markFamilyInactive(family: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/family/markInactive', family);
}
listActiveFamily(): any {
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/active');
}
listInactiveFamily(): any {
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/inactive');
}
familiesAddedThisMonth():any{
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/month');
}
familiesToApprove():any{
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/unapproved');
}
getFamilyByEmail(familyEmail: String) {
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/email/' + familyEmail);
}
getFamilyById(familyId: Number) {
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/id/' + familyId);
}
editFamily(family: any) {
return this.httpClient.post<{familyUpdated: boolean}>(this.serverAddress + 'api/family/edit', family);
}
approveFamily(familyId, approvedBy) {
return this.httpClient.post<{familyApproved: boolean}>(this.serverAddress + `api/family/${familyId}/approve/${approvedBy}`, null);
}
getApprovedFamily():any{
return this.httpClient.get<FamilyAPIResponse>(this.serverAddress + 'api/family/approved');
}
getServicesRendered(familyName): any {
return this.httpClient.get<any>(this.serverAddress + 'api/family/services/rendered/' + familyName);
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/business-signup/business-signup.component.ts
|
import { BusinessService } from '../business.service';
import { Router, ActivatedRoute, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET } from '@angular/router';
import Swal from 'sweetalert2';
import { BusinessModel } from '../business.model';
import { rejects } from 'assert';
import { environment } from 'environments/environment';
import { Component, OnInit, OnChanges, AfterViewInit, SimpleChanges } from '@angular/core';
import { FormControl, FormGroupDirective, NgForm, Validators, FormGroup } from '@angular/forms';
declare var swal:any;
declare var $:any;
@Component({
selector: 'app-business-signup',
templateUrl: './business-signup.component.html',
styleUrls: ['./business-signup.component.css']
})
export class BusinessSignupComponent implements OnInit {
public categoryList: [];
public errorInForm: boolean;
public fileToUpload: File = null;
public disableSubmit: boolean;
constructor(public businessService: BusinessService, public router: Router, private activeRoute: ActivatedRoute) {
this.disableSubmit = false;
this.businessService.getAllCategories().subscribe((responseData) => {
if (responseData) {
this.categoryList = responseData.results;
}
});
}
focus;
focus1;
focus2;
onFinishWizard(){
//here you can do something, sent the form to server via ajax and show a success message with swal
swal("Good job!", "Your business was saved successfully!", "success");
}
ngOnInit(){
setTimeout(function() {
$('.card.card-wizard').addClass('active');
}, 600);
if ($(".selectpicker").length != 0) {
$(".selectpicker").selectpicker({
iconBase: "nc-icon",
tickIcon: "nc-check-2"
});
}
// Code for the Validator
const $validator = $('.card-wizard form').validate({
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: {
required: true,
minlength: 3
},
email: {
required: true,
minlength: 3,
}
},
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-danger');
},
success: function(element) {
$(element).closest('.form-group').removeClass('has-danger').addClass('has-success');
},
errorPlacement : function(error, element) {
$(element).append(error);
}
});
// Wizard Initialization
$('.card-wizard').bootstrapWizard({
'tabClass': 'nav nav-pills',
'nextSelector': '.btn-next',
'previousSelector': '.btn-previous',
onNext: function(tab, navigation, index) {
var $valid = $('.card-wizard form').valid();
if(!$valid) {
$validator.focusInvalid();
return false;
}
},
onInit: function(tab: any, navigation: any, index: any){
// check number of tabs and fill the entire row
let $total = navigation.find('li').length;
let $wizard = navigation.closest('.card-wizard');
let $first_li = navigation.find('li:first-child a').html();
let $moving_div = $('<div class="moving-tab">' + $first_li + '</div>');
$('.card-wizard .wizard-navigation').append($moving_div);
$total = $wizard.find('.nav li').length;
let $li_width = 100/$total;
let total_steps = $wizard.find('.nav li').length;
let move_distance = $wizard.width() / total_steps;
let index_temp = index;
let vertical_level = 0;
let mobile_device = $(document).width() < 600 && $total > 3;
if(mobile_device){
move_distance = $wizard.width() / 2;
index_temp = index % 2;
$li_width = 50;
}
$wizard.find('.nav li').css('width',$li_width + '%');
let step_width = move_distance;
move_distance = move_distance * index_temp;
let $current = index + 1;
if($current == 1 || (mobile_device == true && (index % 2 == 0) )){
move_distance -= 8;
} else if($current == total_steps || (mobile_device == true && (index % 2 == 1))){
move_distance += 8;
}
if(mobile_device){
let x: any = index / 2;
vertical_level = parseInt(x);
vertical_level = vertical_level * 38;
}
$wizard.find('.moving-tab').css('width', step_width);
$('.moving-tab').css({
'transform':'translate3d(' + move_distance + 'px, ' + vertical_level + 'px, 0)',
'transition': 'all 0.5s cubic-bezier(0.29, 1.42, 0.79, 1)'
});
$('.moving-tab').css('transition','transform 0s');
},
onTabClick : function(tab: any, navigation: any, index: any){
const $valid = $('.card-wizard form').valid();
if (!$valid) {
return false;
} else {
return true;
}
},
onTabShow: function(tab: any, navigation: any, index: any) {
var $total = navigation.find('li').length;
var $current = index + 1;
var $wizard = navigation.closest('.card-wizard');
// If it's the last tab then hide the last button and show the finish instead
if ($current >= $total) {
$($wizard).find('.btn-next').hide();
$($wizard).find('.btn-finish').show();
} else {
$($wizard).find('.btn-next').show();
$($wizard).find('.btn-finish').hide();
}
let button_text = navigation.find('li:nth-child(' + $current + ') a').html();
setTimeout(function() {
$('.moving-tab').html(button_text);
}, 150);
var checkbox = $('.footer-checkbox');
if (index == 0) {
$(checkbox).css({
'opacity': '0',
'visibility': 'hidden',
'position': 'absolute'
});
} else {
$(checkbox).css({
'opacity': '1',
'visibility': 'visible'
});
}
$total = $wizard.find('.nav li').length;
let $li_width = 100 / $total;
let total_steps = $wizard.find('.nav li').length;
let move_distance = $wizard.width() / total_steps;
let index_temp = index;
let vertical_level = 0;
let mobile_device = $(document).width() < 600 && $total > 3;
if (mobile_device) {
move_distance = $wizard.width() / 2;
index_temp = index % 2;
$li_width = 50;
}
$wizard.find('.nav li').css('width', $li_width + '%');
let step_width = move_distance;
move_distance = move_distance * index_temp;
$current = index + 1;
// if($current == 1 || (mobile_device == true && (index % 2 == 0) )){
// move_distance -= 8;
// } else if($current == total_steps || (mobile_device == true && (index % 2 == 1))){
// move_distance += 8;
// }
if(mobile_device){
let x: any = index / 2;
vertical_level = parseInt(x);
vertical_level = vertical_level * 38;
}
$wizard.find('.moving-tab').css('width', step_width);
$('.moving-tab').css({
'transform': 'translate3d(' + move_distance + 'px, ' + vertical_level + 'px, 0)',
'transition': 'all 0.5s cubic-bezier(0.29, 1.42, 0.79, 1)'
});
}
});
$('[data-toggle="wizard-radio"]').click(function() {
let wizard = $(this).closest('.card-wizard');
wizard.find('[data-toggle="wizard-radio"]').removeClass('active');
$(this).addClass('active');
$(wizard).find('[type="radio"]').removeAttr('checked');
$(this).find('[type="radio"]').attr('checked', 'true');
});
$('[data-toggle="wizard-checkbox"]').click(function() {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).find('[type="checkbox"]').removeAttr('checked');
} else {
$(this).addClass('active');
$(this).find('[type="checkbox"]').attr('checked', 'true');
}
});
$('.set-full-height').css('height', 'auto');
}
ngAfterViewInit() {
$( window ).resize( () => { $('.card-wizard').each(function(){
const $wizard = $(this);
const index = $wizard.bootstrapWizard('currentIndex');
let $total = $wizard.find('.nav li').length;
let $li_width = 100/$total;
let total_steps = $wizard.find('.nav li').length;
let move_distance = $wizard.width() / total_steps;
let index_temp = index;
let vertical_level = 0;
let mobile_device = $(document).width() < 600 && $total > 3;
if(mobile_device){
move_distance = $wizard.width() / 2;
index_temp = index % 2;
$li_width = 50;
}
$wizard.find('.nav li').css('width',$li_width + '%');
let step_width = move_distance;
move_distance = move_distance * index_temp;
let $current = index + 1;
if($current == 1 || (mobile_device == true && (index % 2 == 0) )){
move_distance -= 8;
} else if($current == total_steps || (mobile_device == true && (index % 2 == 1))){
move_distance += 8;
}
if(mobile_device){
let x: any = index / 2;
vertical_level = parseInt(x);
vertical_level = vertical_level * 38;
}
$wizard.find('.moving-tab').css('width', step_width);
$('.moving-tab').css({
'transform':'translate3d(' + move_distance + 'px, ' + vertical_level + 'px, 0)',
'transition': 'all 0.5s cubic-bezier(0.29, 1.42, 0.79, 1)'
});
$('.moving-tab').css({
'transition': 'transform 0s'
});
});
});
}
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
//console.log(this.fileToUpload);
}
onSave(form: NgForm){
if ( form.invalid ) {
console.log('returned');
this.errorInForm = true;
return;
} else {
const business: any = {
businessName: form.value.businessName,
email: form.value.email,
pContactFName: form.value.pContactFName,
pContactLName: form.value.pContactLName,
pContactPNum: form.value.pContactPNum,
sContactFName: form.value.sContactFName,
sContactLname: form.value.sContactLname,
sContactPNum: form.value.sContactPNum,
address: form.value.address,
category: form.value.category,
serviceArea: form.value.serviceArea,
discountAmount: form.value.discountAmount,
preferredContact: form.value.preferredContact,
eoyReceipt: form.value.eoyReceipt,
notes: form.value.notes,
facebookUrl: form.value.facebook,
twitterUrl: form.value.twitter,
instagramUrl: form.value.instagram,
website: form.value.website,
createdBy: 'Business Sign Up Process'
};
this.businessService.createBusiness(business).subscribe((responseData) => {
if (responseData.businessCreated) {
if (this.fileToUpload!=null){
this.businessService.updateProfilePicture(this.fileToUpload, form.value.businessName).subscribe((responseData) => {
if (responseData.businessUpdated) {
console.log("Business updated");
}
});
}
this.disableSubmit = true;
Swal.fire({
title: 'Sign Up Completed Successfully!',
text: 'You can now close this page. Thanks for supporting V for Victory',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
});
}
});
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/yesno.pipe.spec.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject<filename>src/app/yesno.pipe.spec.ts
import { YesNoPipe } from './yesno.pipe';
describe('YesNoPipe', () => {
it('create an instance', () => {
const pipe = new YesNoPipe();
expect(pipe).toBeTruthy();
});
});
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/family.model.ts
|
export interface FamilyModel {
id: number;
first_name: string;
last_name: string;
email: string;
end_of_treatment_date: string;
street_address: string;
active: boolean;
welcomeLetter : boolean;
treamentLetter : boolean;
subscriberList : boolean;
facebookGroup : boolean;
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/request-service-login/request-service-login.component.ts
|
<filename>src/app/request-service-login/request-service-login.component.ts
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { NgForm } from '@angular/forms';
import { ServicesService } from '../services.service';
import { BusinessService } from '../business.service';
import { FamilyService } from '../family.service';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { analyzeAndValidateNgModules } from '@angular/compiler';
import { ServiceModel } from 'app/service.model';
declare var $: any;
@Component({
selector: 'app-request-service',
templateUrl: './request-service-login.component.html',
styleUrls: ['./request-service-login.component.css'],
providers: [DatePipe]
})
export class RequestServiceLoginComponent implements OnInit {
public errorInForm: boolean;
public categoryList: [];
public serviceList: [];
public family;
public requestedServices: any = [];
public requestList: any = [];
public submitted = false;
constructor(public familyService: FamilyService, public router: Router) {
}
ngOnInit(): void {
}
onSave(form: NgForm) {
if ( form.invalid ) { // Validating form has data
console.log('returned');
this.errorInForm = true;
return;
}
else {
this.familyService.getFamilyByEmail(form.value.email).subscribe((responseData) => {
if(!responseData) {
Swal.fire({
title: "Email not found!",
text: "This email address was not found in our system. Please double-check your entry, and if the problem persists, email us directly.",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "error"
})
}
else {
this.family = responseData.results[0]['id'],
this.router.navigate(['/request'], { queryParams: { familyId: this.family } });
}
})
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/business-category/business-category.component.ts
|
import { Component, OnInit } from '@angular/core';
import { BusinessService } from 'app/business.service';
declare var $: any;
declare interface DataTable {
headerRow: string[];
footerRow: string[];
dataRows: [];
}
@Component({
selector: 'app-business-category',
templateUrl: './business-category.component.html',
styleUrls: ['./business-category.component.css']
})
export class BusinessCategoryComponent implements OnInit {
public categoryList: [];
public dataTable: DataTable;
public userRole: number;
constructor(public businessService: BusinessService) {
this.userRole = JSON.parse(localStorage.getItem('currentUser')).role;
}
ngOnInit() {
this.businessService.getAllCategories().subscribe((responseData) => {
if (responseData) {
this.categoryList = responseData.results;
this.dataTable = {
headerRow: [ 'Id', 'Name', 'Created By', 'Options'],
footerRow: [ 'Id', 'Name', 'Created By', 'Options'],
dataRows: this.categoryList
};
}
});
}
ngAfterViewInit(){
$('#datatable').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
var table = $('#datatable').DataTable();
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/active-family/active-family.component.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
import { Component, OnInit } from '@angular/core';
import { FamilyService } from '../family.service';
import { FamilyModel } from '../family.model';
import { Router, ActivatedRoute } from '@angular/router';
import Swal from 'sweetalert2';
declare var $: any;
declare interface DataTable {
headerRow: string[];
footerRow: string[];
dataRows: FamilyModel[];
}
@Component({
selector: 'app-active-family',
templateUrl: './active-family.component.html',
styleUrls: ['./active-family.component.css']
})
export class ActiveFamilyComponent implements OnInit {
public dataList;
public dataTable: DataTable;
public inactiveFamily: FamilyModel[];
public inactiveFamilyTable: DataTable;
constructor(public familyService: FamilyService, public router: Router, private activeRoute: ActivatedRoute) {}
ngOnInit(){
this.familyService.listInactiveFamily().subscribe((returned) => {
if (returned) {
this.inactiveFamily = returned.results;
this.inactiveFamilyTable = {
headerRow: [ 'Id', 'First Name', 'Last Name', 'Email', 'Address', 'End Of Treatment Date' , 'Options'],
footerRow: [ 'Id', 'First Name', 'Last Name', 'Email', 'Address', 'End Of Treatment Date', 'Options'],
dataRows: this.inactiveFamily
};
}
});
}
ngAfterViewInit(){
$('#table').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
}
markFamilyActive(itemId) {
Swal.fire({
title: "MARK ACTIVE?",
text: "Would you like to make this family active? It will appear with on the Cancer Warrior's page.",
type: "warning",
showCancelButton: true,
cancelButtonClass: "btn btn-info",
confirmButtonClass: "btn btn-success",
confirmButtonText: "Yes, mark it!",
cancelButtonText: "No, leave it!",
reverseButtons: true
})
.then((mark) => {
if(mark.value) {
const request: any = {
id: itemId,
}
this.familyService.markFamilyActive(request).subscribe((responseData) => {
if (responseData.requestFulfilled) {
Swal.fire({
title: "Family has been made active.",
text: "The family is now active",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "success"
}).then((confirm) => {
if(confirm){
window.location.reload()
}
})
}
});
}
});
}
markFamilyInactive(itemId) {
Swal.fire({
title: "MARK INACTIVE?",
text: "Would you like to mark this service as inactive? It will no longer be selectable by families.",
type: "warning",
showCancelButton: true,
cancelButtonClass: "btn btn-info",
confirmButtonClass: "btn btn-danger",
confirmButtonText: "Yes, mark it!",
cancelButtonText: "No, leave it!",
reverseButtons: true
})
.then((mark) => {
if(mark.value) {
const request: any = {
id: itemId,
}
this.familyService.markFamilyInactive(request).subscribe((responseData) => {
if (responseData.requestFulfilled) {
Swal.fire({
title: "Service changed!",
text: "The service has been made inactive.",
buttonsStyling: false,
confirmButtonClass: "btn btn-success",
type: "success"
}).then((confirm) => {
if(confirm){
window.location.reload()
}
})
}
});
}
});
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/family_response.model.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
import { FamilyModel } from "./family.model";
export interface FamilyAPIResponse {
status: number;
results: FamilyModel[];
resultsLength: number;
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/business.service.ts
|
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http, ResponseContentType } from '@angular/http';
import { map } from 'rxjs/operators';
import {environment} from '../environments/environment';
import { UserModel } from './user.model';
import { UserAPIResponse } from './response.model';
import { BusinessAPIResponse } from './response.model';
@Injectable({
providedIn: 'root'
})
export class BusinessService{
private serverAddress = environment.backendURL;
constructor(private httpClient: HttpClient,private route: Router, private http: Http){}
listBusiness():any{
return this.httpClient.get<BusinessAPIResponse>(this.serverAddress + 'api/business/');
}
getBusinessById(businessId: Number) {
return this.httpClient.get<BusinessAPIResponse>(this.serverAddress + 'api/business/id/' + businessId);
}
getAllCategories(): any {
return this.httpClient.get<BusinessAPIResponse>(this.serverAddress + 'api/business/category/');
}
getActiveBusinesses(): any {
return this.httpClient.get<BusinessAPIResponse>(this.serverAddress + 'api/business/active/');
}
createBusiness(business: any) {
return this.httpClient.post<{businessCreated: boolean}>(this.serverAddress + 'api/business/new', business);
}
editBusiness(business: any) {
return this.httpClient.post<{businessUpdated: boolean}>(this.serverAddress + 'api/business/edit', business);
}
businessAddedThisMonth():any{
return this.httpClient.get<BusinessAPIResponse>(this.serverAddress + 'api/business/month');
}
businessToApprove():any{
return this.httpClient.get<BusinessAPIResponse>(this.serverAddress + 'api/business/unapproved');
}
createCategory(category: any) {
return this.httpClient.post<{categoryCreated: boolean}>(this.serverAddress + 'api/business/category/new', category);
}
getCategoryById(categoryId: number): any {
return this.httpClient.get<any>(this.serverAddress + 'api/business/category/' + categoryId);
}
updateCategory(category: any) {
return this.httpClient.post<{categoryUpdated: boolean}>(this.serverAddress + 'api/business/category/update', category);
}
updateProfilePicture(profilePicture: File, businessName) {
const formData: FormData = new FormData();
formData.append('fileKey', profilePicture, profilePicture.name);
return this.httpClient.post<{businessUpdated: boolean}>(this.serverAddress + 'api/business/picture/' + businessName, formData);
}
getServicesRendered(businessName): any {
return this.httpClient.get<any>(this.serverAddress + 'api/business/services/rendered/' + businessName);
}
approveBusiness(businessId, approvedBy) {
return this.httpClient.post<{businessApproved: boolean}>(this.serverAddress + `api/business/${businessId}/approve/${approvedBy}`, null);
}
disableBusiness(businessId, disabledBy) {
return this.httpClient.post<{businessDisabled: boolean}>(this.serverAddress + `api/business/${businessId}/disable/${disabledBy}`, null);
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/new-volunteer/new-volunteer.component.ts
|
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { UsersService } from '../users.service';
import { Router, ActivatedRoute, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET } from '@angular/router';
import {Md5} from 'ts-md5/dist/md5';
import Swal from 'sweetalert2';
import { UserModel } from '../user.model';
import { rejects } from 'assert';
import { environment } from 'environments/environment';
declare var $: any;
@Component({
selector: 'app-new-volunteer',
templateUrl: './new-volunteer.component.html',
styleUrls: ['./new-volunteer.component.css']
})
export class NewVolunteerComponent implements OnInit {
public md5 = new Md5();
public volunteerId: number;
private loggedInUser: any;
public user: UserModel;
errorInForm: boolean;
passwordMatch: boolean;
emailInUser: boolean;
usernameInUse: boolean;
public viewMode: boolean;
public editMode: boolean;
public creationMode: boolean;
public educationLevelList: [];
public roleList: [];
public fileToUpload: File = null;
public profileURL: string = null;
public userId: number;
public ownAccount = false;
constructor(public userService: UsersService, public router: Router, private activeRoute: ActivatedRoute) {
const tree: UrlTree = router.parseUrl(this.router.url);
const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
const s: UrlSegment[] = g.segments;
this.userId = JSON.parse(localStorage.getItem('currentUser')).record_id;
if (s[1].path === 'new') {
this.creationMode = true;
}
if (s[1].path === 'view') {
this.viewMode = true;
}
if (s[1].path === 'edit') {
this.editMode = true;
}
this.activeRoute.queryParams.subscribe(params => {
this.volunteerId = params['volunteerId'];
});
if (this.volunteerId) {
if(this.volunteerId == this.userId) {
this.ownAccount = true;
}
this.userService.getVolunteerById(this.volunteerId).subscribe((responseData) => {
if (responseData) {
this.user = responseData.results[0];
if (responseData.results[0]['profile_picture_url'] != null){
this.profileURL = environment.backendURL + `api/volunteer/username/${responseData.results[0]['username']}/profile/picture`
}
}
});
}
this.loggedInUser = JSON.parse(localStorage.getItem('currentUser')).email;
}
ngOnInit(): void {
this.userService.getAllEducations().subscribe((responseData) => {
if (responseData) {
this.educationLevelList = responseData.results;
}
});
this.userService.getAllRoles().subscribe((responseData) => {
if (responseData) {
this.roleList = responseData.results;
}
});
}
confirmPassword(password: string, confirmPassword: string) {
if (password === confirmPassword) {
return true;
} else {
return false;
}
}
validateEmail(email: string) {
let validEmail: boolean;
this.userService.getVolunteerByEmail(email).subscribe((response) => {
console.log(response);
if (response.status === 200) { // Email is in use
validEmail = false;
} else {
validEmail = true;
}
});
return validEmail;
}
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
//console.log(this.fileToUpload);
}
formatPhoneNumber(phoneNumber: String) {
if (!phoneNumber) { return ''; }
var value = phoneNumber.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9]/)) {
return phoneNumber;
}
var country, city, number;
switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;
case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;
case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;
default:
return phoneNumber;
}
if (country == 1) {
country = "";
}
number = number.slice(0, 3) + '-' + number.slice(3);
return (country + " (" + city + ") " + number).trim();
};
onSave(form: NgForm) {
if ( form.invalid ) {
console.log('returned');
this.errorInForm = true;
return;
} else {
if (this.creationMode) { // Creating New Record
if (this.confirmPassword(form.value.password, form.value.confirmPassword)) {
this.passwordMatch = true;
this.userService.getVolunteerByEmail(form.value.email).subscribe((response) => {
if (response.status === 200) { // Email is in use
this.emailInUser = true;
} else {
this.userService.getVolunteerByUsername(form.value.username).subscribe((responseUserName) => {
console.log(responseUserName);
if (responseUserName.status === 200) { // Username is in use
this.usernameInUse = true;
} else {
const user: any = {
firstName: form.value.firstName,
lastName: form.value.lastName,
username: form.value.username,
password: <PASSWORD>.md5.appendStr(form.value.password).end(),
email: form.value.email,
address: form.value.address,
homePhone: form.value.homePhone,
cellPhone: form.value.cellPhone,
workPhone: form.value.workPhone,
education: form.value.education,
licenses: form.value.licenses,
availability: form.value.availability,
role: form.value.role,
status: form.value.status,
driversLicense: form.value.driversLicense,
socialSecurity: form.value.socialSecurity,
emergencyFirstName: form.value.emergencyFirstName,
emergencyLastName: form.value.emergencyLastName,
emergencyEmail: form.value.emergencyEmail,
emergencyPhone: form.value.emergencyPhone,
emergencyAddress: form.value.emergencyAddress,
createdBy: this.loggedInUser
};
this.userService.saveUser(user).subscribe((responseData) => {
if (responseData.userCreated) {
if (this.fileToUpload!=null){
this.userService.updateProfilePicture(this.fileToUpload, form.value.username).subscribe((responseData) => {
if (responseData.userUpdated) {
console.log("User updated");
}
});
}
Swal.fire({
title: 'Record Saved Successfully!',
text: 'The volunteer was created successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
this.router.navigate(['/volunteers']);
}
});
}
})
}
});
} else {
this.passwordMatch = false;
}
}
if (this.editMode) { // Editing Existing Record
const user: any = {
id: this.volunteerId,
firstName: form.value.firstName,
lastName: form.value.lastName,
username: form.value.username,
email: form.value.email,
address: form.value.address,
homePhone: form.value.homePhone,
cellPhone: form.value.cellPhone,
workPhone: form.value.workPhone,
education: form.value.education,
licenses: form.value.licenses,
availability: form.value.availability,
role: form.value.role,
status: form.value.status,
driversLicense: form.value.driversLicense,
socialSecurity: form.value.socialSecurity,
emergencyFirstName: form.value.emergencyFirstName,
emergencyLastName: form.value.emergencyLastName,
emergencyEmail: form.value.emergencyEmail,
emergencyPhone: form.value.emergencyPhone,
emergencyAddress: form.value.emergencyAddress,
profilePicture: this.fileToUpload,
updatedBy: this.loggedInUser
};
this.userService.editUser(user).subscribe((responseData) => {
if (responseData.userUpdated) {
if (this.fileToUpload!=null){
this.userService.updateProfilePicture(this.fileToUpload, form.value.username).subscribe((responseData) => {
if (responseData.userUpdated) {
console.log("User updated: " + responseData.userUpdated);
}
});
}
Swal.fire({
title: 'Record Updated Successfully!',
text: 'The volunteer was updated successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
this.router.navigate(['/volunteers']);
}
});
}
}
}
changePassword() {
Swal.fire({
title: 'Password Change',
html: '<div class="form-group">' +
'<label for="password">New Password</label>' +
'<input id="password" type="password" class="form-control" />' +
'</div>' +
'<div class="form-group">' +
'<label for="confirmPassword">Confirm New Password</label>' +
'<input id="confirmPassword" type="password" class="form-control" />' +
'</div>',
showCancelButton: true,
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false,
allowOutsideClick: false,
allowEscapeKey : false,
preConfirm: function() {
return new Promise(function(resolve) {
if (!$('#password').val()) {
Swal.showValidationMessage('Enter a valid password.');
resolve();
} else {
if (!$('#confirmPassword').val()) {
Swal.showValidationMessage('Confirm password.');
resolve();
} else {
if ($('#confirmPassword').val() !== $('#password').val()) {
Swal.showValidationMessage('Passwords must match.');
resolve();
} else {resolve(); }
}
}
});
}
}).then((result) => {
if (result.value) { // OK button clicked
const md5 = new Md5();
const passwordHash = md5.appendStr($('#password').val()).end();
this.userService.changePassword(passwordHash, this.volunteerId).subscribe((responseData) => {
if (responseData.userUpdated) {
Swal.fire({
type: 'success',
text: 'Password changed successfully.',
confirmButtonClass: 'btn btn-info',
buttonsStyling: false
})
}
});
} else {
Swal.fire({
type: 'info',
text: 'Password change cancelled.',
confirmButtonClass: 'btn btn-info',
buttonsStyling: false
})
}
})
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/notes.service.ts
|
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http, ResponseContentType } from '@angular/http';
import {environment} from '../environments/environment';
import { NoteAPIResponse } from './response.model';
@Injectable({
providedIn: 'root'
})
export class NotesService{
private servicesList: any = [];
private serverAddress = environment.backendURL;
constructor(private httpClient: HttpClient, private router: Router, private http: Http) { }
getFamilyNotes(familyId: Number) {
return this.httpClient.get<NoteAPIResponse>(this.serverAddress + 'api/family/notes/id/' + familyId);
}
addNote(note: any) {
return this.httpClient.post<{noteAdded: boolean}>(this.serverAddress + 'api/family/notes/new', note);
}
editNote(note: any) {
return this.httpClient.post<{noteUpdated: boolean}>(this.serverAddress + 'api/family/notes/edit', note);
}
deleteNote(note: any) {
return this.httpClient.post<{noteDeleted: boolean}>(this.serverAddress + 'api/family/notes/delete', note);
}
getVPizzaTransactionHistory():any{
return this.httpClient.get<NoteAPIResponse>(this.serverAddress + 'api/VPizza/history');
}
markPizzaRefilled(pizza: any) {
return this.httpClient.post<{refilled: boolean}>(this.serverAddress + 'api/VPizza/refill', pizza);
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/pages/login/login.component.ts
|
import { Component, OnInit, ElementRef } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import { UserModel } from '../../user.model';
import { UserAPIResponse } from '../../response.model';
import {AuthService} from '../../auth.service';
import { NgForm } from '@angular/forms';
import {Buffer} from '../../../../node_modules/buffer'
import { DatePipe } from '@angular/common';
declare var $:any;
@Component({
moduleId:module.id,
selector: 'login-cmp',
templateUrl: './login.component.html',
providers: [DatePipe]
})
export class LoginComponent implements OnInit{
focus;
focus1;
focus2;
test : Date = new Date();
private toggleButton;
private sidebarVisible: boolean;
private nativeElement: Node;
private userModel: UserModel;
private apiResponse: UserAPIResponse;
private endSession: boolean;
noLoginValuesAlert: boolean;
incorrectUserAlert: boolean;
logoutAlert: boolean;
private fromPasswordReset: boolean;
public passwordResetAlert: boolean;
constructor(private element : ElementRef, public authService: AuthService,
private router: Router, private activeRoute: ActivatedRoute, private datePipe: DatePipe) {
this.nativeElement = element.nativeElement;
this.sidebarVisible = false;
this.activeRoute.queryParams.subscribe(params => {
this.endSession = params['endSession'];
this.fromPasswordReset = params['fromResetPassword'];
});
if (this.endSession) {
this.logoutAlert = true;
this.fromPasswordReset = false;
localStorage.removeItem('currentUser');
}
if (this.fromPasswordReset) {
this.passwordResetAlert = true;
}
}
checkFullPageBackgroundImage(){
var $page = $('.full-page');
var image_src = $page.data('image');
if(image_src !== undefined){
var image_container = '<div class="full-page-background" style="background-image: url(' + image_src + ') "/>'
$page.append(image_container);
}
};
ngOnInit(){
this.checkFullPageBackgroundImage();
var body = document.getElementsByTagName('body')[0];
body.classList.add('login-page');
var navbar : HTMLElement = this.element.nativeElement;
this.toggleButton = navbar.getElementsByClassName('navbar-toggle')[0];
setTimeout(function(){
// after 1000 ms we add the class animated to the login/register card
$('.card').removeClass('card-hidden');
}, 700)
}
ngOnDestroy(){
var body = document.getElementsByTagName('body')[0];
body.classList.remove('login-page');
}
sidebarToggle(){
var toggleButton = this.toggleButton;
var body = document.getElementsByTagName('body')[0];
var sidebar = document.getElementsByClassName('navbar-collapse')[0];
if(this.sidebarVisible == false){
setTimeout(function(){
toggleButton.classList.add('toggled');
},500);
body.classList.add('nav-open');
this.sidebarVisible = true;
} else {
this.toggleButton.classList.remove('toggled');
this.sidebarVisible = false;
body.classList.remove('nav-open');
}
}
onLogin(form: NgForm) {
if ( form.invalid ) { // Validating form has data
this.noLoginValuesAlert = true;
this.incorrectUserAlert = false;
this.logoutAlert = false;
return;
}
const user: any = {
userName: form.value.userName,
password: form.value.password
};
this.authService.getUser(user.userName, user.password).subscribe((userReturned) => {
if (userReturned) {
this.userModel = userReturned.results[0];
localStorage.setItem('currentUser', JSON.stringify(this.userModel));
//Saving Login History
var date = new Date();
var ipAddress = null;
this.authService.getIPAddress().subscribe((ipObject) => {
if (ipObject) {
ipAddress = ipObject['ip'];
const loginHistory = {
userId: this.userModel.record_id,
date: this.datePipe.transform(date, 'MM/dd/yyyy'),
time: this.datePipe.transform(date, 'HH:MM'),
clientIp: ipAddress
}
this.authService.postLoginHistory(loginHistory).subscribe((sessionSaved) => {
if (sessionSaved) {
console.log(sessionSaved);
}
});
}
});
this.router.navigate(['/dashboard']);
} else {
this.incorrectUserAlert = true;
this.logoutAlert = false;
this.noLoginValuesAlert = false;
}
});
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/new-business/new-business.component.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject<gh_stars>0
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { BusinessService } from '../business.service';
import { Router, ActivatedRoute, UrlTree, UrlSegmentGroup, UrlSegment, PRIMARY_OUTLET, NavigationEnd } from '@angular/router';
import Swal from 'sweetalert2';
import { BusinessModel } from '../business.model';
import { rejects } from 'assert';
import { environment } from 'environments/environment';
import { filter } from 'rxjs/operators';
declare const $: any;
declare interface DataTable {
headerRow: string[];
footerRow: string[];
dataRows: any[];
}
@Component({
selector: 'app-new-business',
templateUrl: './new-business.component.html',
styleUrls: ['./new-business.component.css']
})
export class NewBusinessComponent implements OnInit {
public businessId: number;
public business: BusinessModel;
errorInForm: boolean;
businessnameInUse: boolean;
public viewMode: boolean;
public editMode: boolean;
public creationMode: boolean;
public categoryList: [];
public fileToUpload: File = null;
public profileURL: string = null;
private loggedInUser: any;
public dataTable: DataTable;
public servicesRendered: Array<any>;
public businessApproved: boolean;
public previousUrl: string;
public userRole: number;
constructor(public businessService: BusinessService, public router: Router, private activeRoute: ActivatedRoute) {
}
ngOnInit() {
const tree: UrlTree = this.router.parseUrl(this.router.url);
const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
const s: UrlSegment[] = g.segments;
this.userRole = JSON.parse(localStorage.getItem('currentUser')).role;
if (s[1].path === 'new') {
this.creationMode = true;
}
if (s[1].path === 'view') {
this.viewMode = true;
}
if (s[1].path === 'edit') {
this.editMode = true;
}
this.activeRoute.queryParams.subscribe(params => {
this.businessId = params['businessId'];
this.previousUrl = params['from'];
if(!this.previousUrl) {
<<<<<<< Updated upstream
this.previousUrl = "/services/list";
=======
this.previousUrl = "/services/requests";
>>>>>>> Stashed changes
}
});
this.businessService.getAllCategories().subscribe((responseData) => {
if (responseData) {
this.categoryList = responseData.results;
}
});
if (this.businessId) {
this.businessService.getBusinessById(this.businessId).subscribe((responseData) => {
if (responseData) {
this.business = responseData.results[0];
console.log(this.business)
if (responseData.results[0]['profile_picture_url'] != null){
this.profileURL = environment.backendURL + `api/business/name/${responseData.results[0]['business_name']}/logo`
}
if (responseData.results[0]['approved_by'] != null){
this.businessApproved = true;
}
this.businessService.getServicesRendered(this.business['record_id']).subscribe((requests) => {
if (requests) {
this.servicesRendered = requests.results;
this.dataTable = {
headerRow: [ 'ID', 'Name', 'Date Requested', 'Date Fulfilled', 'Service Value', 'Service Cost', 'Pending'],
footerRow: [ 'ID', 'Name', 'Date Requested', 'Date Fulfilled', 'Service Value', 'Service Cost', 'Pending'],
dataRows: this.servicesRendered
};
} else{
this.dataTable = {
headerRow: [ 'ID', 'Name', 'Date Requested', 'Date Fulfilled', 'Pending'],
footerRow: [ 'ID', 'Name', 'Date Requested', 'Date Fulfilled', 'Pending'],
dataRows: []
};
}
});
}
});
}
this.loggedInUser = JSON.parse(localStorage.getItem('currentUser')).email;
}
ngAfterViewInit(){
$('#dataTable').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
var servicesRendered = $('#servicesRendered').DataTable();
}
formatPhoneNumber(phoneNumber: String) {
if (!phoneNumber) { return ''; }
var value = phoneNumber.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9]/)) {
return phoneNumber;
}
var country, city, number;
switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;
case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;
case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;
default:
return phoneNumber;
}
if (country == 1) {
country = "";
}
number = number.slice(0, 3) + '-' + number.slice(3);
return (country + " (" + city + ") " + number).trim();
};
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
//console.log(this.fileToUpload);
}
onSave(form: NgForm) {
if ( form.invalid ) {
console.log('returned');
this.errorInForm = true;
return;
} else {
if (this.creationMode) { // Creating New Record
const business: any = {
businessName: form.value.businessName,
email: form.value.email,
pContactFName: form.value.pContactFName,
pContactLName: form.value.pContactLName,
pContactPNum: form.value.pContactPNum,
sContactFName: form.value.sContactFName,
sContactLname: form.value.sContactLname,
sContactPNum: form.value.sContactPNum,
address: form.value.address,
category: form.value.category,
serviceArea: form.value.serviceArea,
discountAmount: form.value.discountAmount,
preferredContact: form.value.preferredContact,
eoyReceipt: form.value.eoyReceipt,
notes: form.value.notes,
facebookUrl: form.value.facebook,
twitterUrl: form.value.twitter,
instagramUrl: form.value.instagram,
website: form.value.website,
createdBy: this.loggedInUser
};
this.businessService.createBusiness(business).subscribe((responseData) => {
if (responseData.businessCreated) {
if (this.fileToUpload!=null){
this.businessService.updateProfilePicture(this.fileToUpload, form.value.businessName).subscribe((responseData) => {
if (responseData.businessUpdated) {
console.log("Business updated");
}
});
}
Swal.fire({
title: 'Record Saved Successfully!',
text: 'The business was created successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
this.router.navigate(['/business/list']);
}
});
}
if (this.editMode) { // Editing Existing Record
const business: any = {
id: this.businessId,
active: form.value.active,
businessName: form.value.businessName,
email: form.value.email,
pContactFName: form.value.pContactFName,
pContactLName: form.value.pContactLName,
pContactPNum: form.value.pContactPNum,
sContactFName: form.value.sContactFName,
sContactLname: form.value.sContactLname,
sContactPNum: form.value.sContactPNum,
address: form.value.address,
category: form.value.category,
serviceArea: form.value.serviceArea,
discountAmount: form.value.discountAmount,
preferredContact: form.value.preferredContact,
eoyReceipt: form.value.eoyReceipt,
notes: form.value.notes,
facebookUrl: form.value.facebook,
twitterUrl: form.value.twitter,
instagramUrl: form.value.instagram,
website: form.value.website,
updatedBy: this.loggedInUser
};
this.businessService.editBusiness(business).subscribe((responseData) => {
if (responseData.businessUpdated) {
if (this.fileToUpload!=null){
this.businessService.updateProfilePicture(this.fileToUpload, form.value.businessName).subscribe((responseData) => {
if (responseData.businessUpdated) {
console.log("Business updated");
}
});
}
Swal.fire({
title: 'Record Updated Successfully!',
text: 'The business was updated successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
this.router.navigate(['/business/list']);
}
});
}
}
}
approvedBusiness(businessId, businessName){
this.businessService.approveBusiness(businessId, this.loggedInUser).subscribe((responseData) => {
if (responseData.businessApproved) {
Swal.fire({
title: 'Business Approved Successfully!',
text: businessName + ' was approved successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
this.router.navigate(['/business/list']);
}
});
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/contact.pipe.ts
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'contact'
})
export class ContactPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
if(typeof value === 'undefined' || value === null) {
return "Not Stated";
}
else if(value == 'phone') {
return "Phone Call";
}
else if(value == 'email') {
return "Email";
}
else if(value == 'text') {
return "Text Message";
}
else if(value == 'voucher') {
return "Voucher/Gift Card";
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/business_response.model.ts
|
export interface BusinessAPIResponse {
status: number;
results: any[];
resultsLength: number;
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/yesnoactive.pipe.spec.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
import { YesNoActivePipe } from './yesno.pipe';
describe('YesNoActivePipe', () => {
it('create an instance', () => {
const pipe = new YesNoActivePipe();
expect(pipe).toBeTruthy();
});
});
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/users.service.ts
|
<filename>src/app/users.service.ts<gh_stars>0
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { HttpClient } from '../../node_modules/@angular/common/http';
import { Http, ResponseContentType } from '@angular/http';
import { map } from 'rxjs/operators';
import {environment} from '../environments/environment';
import { UserModel } from './user.model';
import { UserAPIResponse } from './response.model';
import { FamilyAPIResponse } from './family_response.model';
@Injectable({
providedIn: 'root'
})
export class UsersService {
private usersList: any = [];
private serverAddress = environment.backendURL;
constructor(private httpClient: HttpClient, private router: Router, private http: Http) { }
saveUser(user: any) {
return this.httpClient.post<{userCreated: boolean}>(this.serverAddress + 'api/volunteer/new', user);
}
listUsers(): any {
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/');
}
listVolunteerByStatus(status: string) {
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/status/' + status);
}
getAllVolunteersBySearchValue(searchValue: string) {
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/search/' + searchValue);
}
getVolunteerById(volunteerId: Number) {
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/id/' + volunteerId);
}
editUser(user: any) {
return this.httpClient.post<{userUpdated: boolean}>(this.serverAddress + 'api/volunteer/edit', user);
}
changePassword(passwordHash, volunteerId) {
return this.httpClient.post<{userUpdated: boolean}>(this.serverAddress + 'api/volunteer/change_password/'
+ passwordHash + '/' + volunteerId, null);
}
updateProfilePicture(profilePicture: File, username) {
const formData: FormData = new FormData();
formData.append('fileKey', profilePicture, profilePicture.name);
return this.httpClient.post<{userUpdated: boolean}>(this.serverAddress + 'api/volunteer/picture/' + username, formData);
}
getVolunteerByEmail(volunteerEmail: String) {
return this.httpClient.get(this.serverAddress + 'api/volunteer/email/' + volunteerEmail, {observe: 'response'});
}
getVolunteerByUsername(username: String) {
return this.httpClient.get(this.serverAddress + 'api/volunteer/username/' + username, {observe: 'response'});
}
getAllEducations(): any {
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/education/');
}
getAllRoles(): any {
return this.httpClient.get<UserAPIResponse>(this.serverAddress + 'api/volunteer/role/');
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/business.model.ts
|
export interface BusinessModel {
id: number;
businessName: string;
email: string;
pContactFName: string;
pContactLName: string;
pContactPNum: string;
sContactFName: string;
sContactLname: string;
sContactPNum: string;
address: string;
category: string;
serviceArea: string;
discountAmount: string;
preferredContact: string;
eoyReceipt: string;
notes: string;
active: boolean;
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/active-services/active-services.component.spec.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject<filename>src/app/active-services/active-services.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ActiveServicesComponent } from './active-services.component';
describe('ActiveServicesComponent', () => {
let component: ActiveServicesComponent;
let fixture: ComponentFixture<ActiveServicesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ActiveServicesComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ActiveServicesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/userpage/user.component.ts
|
import { environment } from 'environments/environment';
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { UserModel } from 'app/user.model';
import { UsersService } from 'app/users.service';
import { ActivatedRoute, Router } from '@angular/router';
import {Md5} from 'ts-md5/dist/md5';
import Swal from 'sweetalert2';
import { NgForm } from '@angular/forms';
import {AuthService} from '../auth.service';
declare var $: any;
declare interface DataTable {
headerRow: string[];
footerRow: string[];
dataRows: UserModel[];
}
@Component({
moduleId: module.id,
selector: 'user-cmp',
templateUrl: 'user.component.html'
})
export class UserComponent{
public fullName: string;
public username: string = null;
public userId: number;
public profilePictureURL: string = null;
public user: UserModel;
public educationLevelList: [];
public roleList: [];
private md5 = new Md5();
public errorInForm: boolean;
public fileToUpload: File = null;
public loginHistory: [];
public dataTable: DataTable;
constructor(public userService: UsersService, public router: Router, private activeRoute: ActivatedRoute, public authService: AuthService) {
this.activeRoute.queryParams.subscribe(params => {
this.userId = params['id'];
});
if (this.userId) {
this.userService.getVolunteerById(this.userId).subscribe((responseData) => {
if (responseData) {
this.user = responseData.results[0];
}
});
}
this.fullName = JSON.parse(localStorage.getItem('currentUser')).first_name + ' ' +
JSON.parse(localStorage.getItem('currentUser')).last_name;
if (JSON.parse(localStorage.getItem('currentUser')).profile_picture_url){
this.username = JSON.parse(localStorage.getItem('currentUser')).username;
this.profilePictureURL = environment.backendURL + `api/volunteer/username/${this.username}/profile/picture`;
}
}
ngOnInit() {
this.userService.getAllEducations().subscribe((responseData) => {
if (responseData) {
this.educationLevelList = responseData.results;
}
});
this.userService.getAllRoles().subscribe((responseData) => {
if (responseData) {
this.roleList = responseData.results;
}
});
this.authService.getLoginHistory(this.userId).subscribe((loginHistory) => {
if (loginHistory) {
this.loginHistory = loginHistory['results'];
this.dataTable = {
headerRow: [ 'Date', 'Time', 'Client IP'],
footerRow: [ 'Date', 'Time', 'Client IP'],
dataRows: loginHistory['results']
};
}
});
}
ngAfterViewInit(){
$('#datatable').DataTable({
"pagingType": "simple",
"lengthMenu": [
[5, 10, -1],
[5, 10, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
}
});
var table = $('#datatable').DataTable();
}
formatPhoneNumber(phoneNumber: String) {
if (!phoneNumber) { return ''; }
var value = phoneNumber.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9]/)) {
return phoneNumber;
}
var country, city, number;
switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;
case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;
case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;
default:
return phoneNumber;
}
if (country == 1) {
country = "";
}
number = number.slice(0, 3) + '-' + number.slice(3);
return (country + " (" + city + ") " + number).trim();
};
changePassword() {
Swal.fire({
title: 'Password Change',
html: '<div class="form-group">' +
'<label for="password">New Password</label>' +
'<input id="password" type="password" class="form-control" />' +
'</div>' +
'<div class="form-group">' +
'<label for="confirmPassword">Confirm New Password</label>' +
'<input id="confirmPassword" type="password" class="form-control" />' +
'</div>',
showCancelButton: true,
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false,
allowOutsideClick: false,
allowEscapeKey : false,
preConfirm: function() {
return new Promise<void>(function(resolve) {
if (!$('#password').val()) {
Swal.showValidationMessage('Enter a valid password.');
resolve();
} else {
if (!$('#confirmPassword').val()) {
Swal.showValidationMessage('Confirm password.');
resolve();
} else {
if ($('#confirmPassword').val() !== $('#password').val()) {
Swal.showValidationMessage('Passwords must match.');
resolve();
} else {resolve(); }
}
}
});
}
}).then((result) => {
if (result.value) { // OK button clicked
const md5 = new Md5();
const passwordHash = md5.appendStr($('#password').val()).end();
this.userService.changePassword(passwordHash, this.userId).subscribe((responseData) => {
if (responseData.userUpdated) {
Swal.fire({
type: 'success',
text: 'Password changed successfully.',
confirmButtonClass: 'btn btn-info',
buttonsStyling: false
})
}
});
} else {
Swal.fire({
type: 'info',
text: 'Password change cancelled.',
confirmButtonClass: 'btn btn-info',
buttonsStyling: false
})
}
})
}
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
//console.log(this.fileToUpload);
}
onSave(form: NgForm) {
if ( form.invalid ) {
console.log('returned');
this.errorInForm = true;
return;
} else {
const user: any = {
id: this.userId,
firstName: form.value.firstName,
lastName: form.value.lastName,
username: form.value.username,
email: form.value.email,
address: form.value.address,
homePhone: form.value.homePhone,
cellPhone: form.value.cellPhone,
workPhone: form.value.workPhone,
education: this.user['educational_background'], // This way the value is set in the DB without reading the field in the from
licenses: form.value.licenses,
availability: form.value.availability,
role: this.user['role'],
status: this.user['status'],
driversLicense: form.value.driversLicense,
socialSecurity: form.value.socialSecurity,
emergencyFirstName: form.value.emergencyFirstName,
emergencyLastName: form.value.emergencyLastName,
emergencyEmail: form.value.emergencyEmail,
emergencyPhone: form.value.emergencyPhone,
emergencyAddress: form.value.emergencyAddress,
profilePicture: this.fileToUpload
};
this.userService.editUser(user).subscribe((responseData) => {
if (responseData.userUpdated) {
if (this.fileToUpload!=null){
this.userService.updateProfilePicture(this.fileToUpload, form.value.username).subscribe((responseData) => {
if (responseData.userUpdated) {
console.log("User updated: " + responseData.userUpdated);
// TODO: When the user does not have profile picture and a picture is added, the picture does not load.
// This is because the app is using the currentUser object from the localstorage and it has null on the profile url
// set this value to the new uploaded picture url so it works as it should.
// otherwise the user will have to log out and log back in for the picture to laod since when logging in we get the picture url back.
// The same happens for any of the other values that are taken form the currentUser object, like name, last name, etc
}
});
}
Swal.fire({
title: 'Record Updated Successfully!',
text: 'The volunteer was updated successfully.',
buttonsStyling: false,
confirmButtonClass: 'btn btn-success',
type: 'success'
})
}
});
}
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/list-family/list-family.component.spec.ts
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ListFamilyComponent } from './list-family.component';
describe('ListFamilyComponent', () => {
let component: ListFamilyComponent;
let fixture: ComponentFixture<ListFamilyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ListFamilyComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ListFamilyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/email.service.ts
|
<reponame>ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { HttpClient } from '../../node_modules/@angular/common/http';
import { Http, ResponseContentType } from '@angular/http';
import { map } from 'rxjs/operators';
import {environment} from '../environments/environment';
import { UserModel } from './user.model';
import { UserAPIResponse } from './response.model';
@Injectable({
providedIn: 'root'
})
export class EmailService {
private serverAddress = environment.backendURL;
constructor(private httpClient: HttpClient, private router: Router, private http: Http) { }
sendEmail(emailObject: any) {
return this.httpClient.post<{mailResponse: boolean}>(this.serverAddress + 'api/email/send', emailObject);
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/services.service.ts
|
<gh_stars>0
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http, ResponseContentType } from '@angular/http';
import { map } from 'rxjs/operators';
import {environment} from '../environments/environment';
import { ServiceModel } from './service.model';
import { ServiceAPIResponse } from './response.model';
@Injectable({
providedIn: 'root'
})
export class ServicesService {
private servicesList: any = [];
private serverAddress = environment.backendURL;
constructor(private httpClient: HttpClient, private router: Router, private http: Http) { }
getAllServices(): any {
return this.httpClient.get<ServiceAPIResponse>(this.serverAddress + 'api/service');
}
getAllCategories(): any {
return this.httpClient.get<ServiceAPIResponse>(this.serverAddress + 'api/service/category');
}
getActiveServices(): any {
return this.httpClient.get<ServiceAPIResponse>(this.serverAddress + 'api/service/list');
}
saveRequest(request: any) {
return this.httpClient.post<{requestCreated: boolean}>(this.serverAddress + 'api/service/new', request);
}
fulfillRequest(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/fulfill', request);
}
markBusinessNotified(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/notifyBusiness', request);
}
markFamilyNotified(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/notifyFamily', request);
}
markBusinessFollowedUp(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/followupBusiness', request);
}
markFamilyFollowedUp(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/followupFamily', request);
}
markServiceActive(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/markActive', request);
}
markServiceInactive(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/markInactive', request);
}
listActiveRequests(): any {
return this.httpClient.get<ServiceAPIResponse>(this.serverAddress + 'api/service/active');
}
listRenderedServices(): any {
return this.httpClient.get<ServiceAPIResponse>(this.serverAddress + 'api/service/rendered');
}
getServiceById(serviceId: Number) {
return this.httpClient.get<ServiceAPIResponse>(this.serverAddress + 'api/service/get/id/' + serviceId);
}
getRequestById(serviceId: Number) {
return this.httpClient.get<ServiceAPIResponse>(this.serverAddress + 'api/service/id/' + serviceId);
}
deleteRequest(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/delete', request);
}
servicesRequestedThisMonth():any{
return this.httpClient.get<any>(this.serverAddress + 'api/service/requested/month');
}
setValueCost(request: any) {
return this.httpClient.post<{requestFulfilled: boolean}>(this.serverAddress + 'api/service/valuecost', request);
}
}
|
ASRangel2012/VforVictory_Angular_Frontend_SeniorDesignProject
|
src/app/response.model.ts
|
import { UserModel } from "./user.model";
import { ServiceModel } from "./service.model";
import { BusinessModel } from "./business.model";
import { FamilyModel } from "./family.model";
import { NoteModel } from "./note.model"
export interface FamilyAPIResponse {
status: number;
results: FamilyModel[];
resultsLength: number;
}
export interface UserAPIResponse {
status: number;
results: UserModel[];
resultsLength: number;
}
export interface ServiceAPIResponse {
status: number;
results: ServiceModel[];
resultsLength: number;
}
export interface BusinessAPIResponse {
status: number;
results: BusinessModel[];
resultsLength: number;
}
export interface NoteAPIResponse {
status: number;
results: NoteModel[];
resultsLength: number;
}
|
angelxehg/angelxehg.github.io
|
src/meta/data/platforms.ts
|
<reponame>angelxehg/angelxehg.github.io<filename>src/meta/data/platforms.ts
import { LinkMeta } from "../types"
const platforms: LinkMeta[] = [
{
name: "Android",
icon: {
style: { color: "#3DD985" },
svgPath: "fontawesome/android-brands.svg",
},
href: "https://www.android.com/intl/es_es/",
},
{
name: "AWS",
icon: {
style: {
color: "#F79400",
backgroundColor: "#222e3d",
borderRadius: "50%",
padding: "0.1rem",
},
svgPath: "fontawesome/aws-brands.svg",
},
href: "https://aws.amazon.com/es/",
},
{
name: "Capacitor",
icon: {
svgPath: "iconify/capacitorjs.svg",
},
href: "https://capacitorjs.com/",
},
{
name: "DigitalOcean",
icon: {
style: { color: "#007CF7" },
svgPath: "fontawesome/digital-ocean-brands.svg",
},
href: "https://www.digitalocean.com/",
},
{
name: "Firebase",
icon: {
svgPath: "seek-logo/firebase.svg",
},
href: "https://firebase.google.com/",
},
{
name: "GitHub",
icon: {
svgPath: "bootstrap-icons/github.svg",
},
href: "https://github.com/",
},
{
name: "GitHub Pages",
icon: {
svgPath: "bootstrap-icons/github.svg",
},
href: "https://pages.github.com/",
},
{
name: "GitLab",
icon: {
style: { color: "#F46A25" },
svgPath: "seek-logo/gitlab.svg",
},
href: "https://gitlab.com/",
},
{
name: "Heroku",
icon: {
svgPath: "iconify/heroku.svg",
style: {
backgroundColor: "white",
borderRadius: "15%",
},
},
href: "https://dashboard.heroku.com/",
},
{
name: "Netlify",
icon: {
style: {
backgroundColor: "#0e1e25",
borderRadius: "50%",
padding: "0.1rem",
},
svgPath: "seek-logo/netlify.svg",
},
href: "https://www.netlify.com/",
},
]
export default platforms
|
angelxehg/angelxehg.github.io
|
src/components/SEO.tsx
|
<reponame>angelxehg/angelxehg.github.io
import React from "react"
import PropTypes from "prop-types"
import { Helmet } from "react-helmet"
import { useSiteMetadata } from "../hooks/use-site-metadata"
import { useTheme } from "./Theme"
interface SEOProps {
description: any
lang: any
meta: any
title: any
image: any
}
const SEO = (props: SEOProps) => {
const { theme } = useTheme()
const { description, lang, meta, title, image } = props
const site = useSiteMetadata()
const metaDescription = description || site.description
const defaultTitle = site.title
const seoImage = `${site.siteUrl}/${
image !== "" ? image.slice(1) : "images/OpenGraph.Opt.png"
}`
const seoTitle = `${title} | ${defaultTitle}`
return (
<Helmet
htmlAttributes={{
lang,
}}
title={title}
titleTemplate={defaultTitle ? `%s | <NAME>` : ""}
meta={[
{
name: `description`,
content: metaDescription,
},
{
property: `og:title`,
content: seoTitle,
},
{
property: `og:site_name`,
content: defaultTitle,
},
{
property: `og:description`,
content: metaDescription,
},
{
property: `og:type`,
content: `website`,
},
{
property: `og:image`,
content: seoImage,
},
{
name: `twitter:card`,
content: `summary_large_image`,
},
{
name: `twitter:creator`,
content: site.author || ``,
},
{
name: `twitter:title`,
content: seoTitle,
},
{
name: `twitter:image`,
content: seoImage,
},
{
name: `twitter:description`,
content: metaDescription,
},
{
name: `google-site-verification`,
content: '0hO20fg4BEvRMjuTmUHifKltClQKkc4KKlwGD9tg6-M',
},
].concat(meta)}
>
<body className={`${theme}`}></body>
</Helmet>
)
}
SEO.defaultProps = {
lang: `en`,
meta: [],
description: ``,
image: "",
}
SEO.propTypes = {
description: PropTypes.string,
lang: PropTypes.string,
meta: PropTypes.arrayOf(PropTypes.object),
title: PropTypes.string.isRequired,
image: PropTypes.string,
}
export default SEO
|
angelxehg/angelxehg.github.io
|
src/pages/posts.tsx
|
import React, { useEffect, useState } from "react"
import { Link } from "gatsby"
import Layout from "../layouts/Layout"
import DefaultFooter from "../components/Footer"
import SEO from "../components/SEO"
import { CreateBadge, CreateLink } from "../components/Link"
import DefaultNavbar from "../components/Navbar"
interface DevToPost {
id: number
title: string
description: string
readable_publish_date: string
canonical_url: string
social_image: string
tags: string
}
const fetchDevToPosts = async () => {
const response = await fetch("https://dev.to/api/articles?username=angelxehg")
if (response.status !== 200) {
throw new Error("Couldn't fetch from dev.to")
}
const items: DevToPost[] = await response.json()
return items
}
interface PostCardProps {
item: DevToPost
}
const PostCard = (
props: PostCardProps & { titleAs: "h2" | "h3" }
): JSX.Element => {
const {
title,
description,
canonical_url: href,
social_image,
tags,
} = props.item
return (
<article className="card" style={{ height: "100%" }}>
<img src={social_image} alt={description} className="card-img-top" />
<div className="card-body">
{props.titleAs === "h2" && (
<h2 className="card-title h5">
<CreateLink from="Dev.to" extend={{ title, href }} noIcon />
</h2>
)}
{props.titleAs === "h3" && (
<h3 className="card-title h5">
<CreateLink from="Dev.to" extend={{ title, href }} noIcon />
</h3>
)}
<p className="card-text m-0">{description}</p>
<p className="card-text m-0">
{tags.split(", ").map(tagName => (
<CreateBadge
key={tagName}
from={tagName}
extend={{
title: tagName.charAt(0).toUpperCase() + tagName.slice(1),
href: `https://dev.to/t/${tagName}`,
}}
/>
))}
</p>
</div>
</article>
)
}
export const PostsSection = () => {
const [posts, setPosts] = useState<DevToPost[]>([])
useEffect(() => {
fetchDevToPosts().then(posts => setPosts(posts.slice(0, 4)))
}, [])
return (
<section id="posts">
<h2>
Últimas{" "}
<CreateLink
from="Dev.to"
iconProps={{ size: "1.325rem" }}
extend={{ title: "entradas", href: "/posts" }}
/>
:
</h2>
<div className="row">
{posts.map(item => (
<div key={item.id} className="col-lg-6 p-sm-1 pb-3">
<PostCard item={item} titleAs="h3" />
</div>
))}
</div>
<CreateLink
from="Dev.to"
extend={{ title: "Ver todas las entradas >", href: "/posts" }}
/>
</section>
)
}
const PostsPage = (): JSX.Element => {
const [posts, setPosts] = useState<DevToPost[]>([])
useEffect(() => {
fetchDevToPosts().then(posts => setPosts(posts.slice(0, 4)))
}, [])
return (
<Layout>
<SEO title="Entradas" lang="es" />
<DefaultNavbar />
<div className="hero">
<div className="container-lg ps-sm-4 pe-sm-4 pt-3 pb-3">
<Link to="/">{"< "}Volver a Portafolio</Link>
<header className="mt-1">
<h1>Todas mis entradas</h1>
<p className="m-0">
Estas son las entradas que he publicado en{" "}
<CreateLink from="Dev.to" />
</p>
</header>
</div>
</div>
<main className="container-lg ps-sm-4 pe-sm-4 pt-3 pb-3">
<div className="row">
{posts.map(item => (
<div key={item.id} className="col-lg-6 p-sm-1 pb-3">
<PostCard titleAs="h2" item={item} />
</div>
))}
</div>
</main>
<DefaultFooter />
</Layout>
)
}
export default PostsPage
|
angelxehg/angelxehg.github.io
|
src/layouts/Center.tsx
|
<reponame>angelxehg/angelxehg.github.io
import React from "react"
import { ThemeContextProvider } from "../components/Theme"
import "./Center.scss"
interface CenterLayoutProps {
children: React.ReactNode | React.ReactNode[]
}
const CenterLayout = (props: CenterLayoutProps): JSX.Element => (
<ThemeContextProvider>
<div className="center-layout p-1">
<main className="center-layout-content">{props.children}</main>
</div>
</ThemeContextProvider>
)
export default CenterLayout
|
angelxehg/angelxehg.github.io
|
src/components/Navbar.tsx
|
import React, { useState } from "react"
import { Link } from "gatsby"
import { useTheme } from "./Theme"
const SunSVG = require("../assets/bootstrap-icons/sun.svg")
const MoonSVG = require("../assets/bootstrap-icons/moon.svg")
const ListSVG = require("../assets/bootstrap-icons/list.svg")
const DefaultNavbar = (): JSX.Element => {
const { theme, toggle } = useTheme()
const [collapsed, setCollapsed] = useState(true)
return (
<nav className={`navbar sticky-top navbar-expand-md`}>
<div className="container-lg ps-sm-4 pe-sm-4">
<Link to="/" className="navbar-brand">
<NAME>
</Link>
<button
aria-label="Toggle Theme"
onClick={toggle}
style={{ border: "none", background: "none" }}
>
{theme === "dark" && <MoonSVG className="btn-indigo" />}
{theme === "light" && <SunSVG className="btn-orange" />}
</button>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#defaultNavbar"
aria-controls="defaultNavbar"
aria-expanded="false"
aria-label="Toggle navigation"
onClick={() => setCollapsed(!collapsed)}
>
<ListSVG
style={{
height: "1.8rem",
width: "1.8rem",
}}
/>
</button>
<div
className={collapsed ? "collapse navbar-collapse" : "navbar-collapse"}
id="defaultNavbar"
>
<ul className="navbar-nav me-auto"></ul>
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/#about" className="nav-link text-reset">
Acerca de
</Link>
</li>
<li className="nav-item">
<Link to="/#skills" className="nav-link text-reset">
Habilidades
</Link>
</li>
<li className="nav-item">
<Link to="/projects" className="nav-link text-reset">
Proyectos
</Link>
</li>
<li className="nav-item">
<Link to="/posts" className="nav-link text-reset">
Blog
</Link>
</li>
</ul>
</div>
</div>
</nav>
)
}
export default DefaultNavbar
|
angelxehg/angelxehg.github.io
|
src/components/Link.tsx
|
<reponame>angelxehg/angelxehg.github.io<filename>src/components/Link.tsx<gh_stars>0
import React from "react"
import { Link as GatsbyLink } from "gatsby"
import Icon, { IconProps } from "./Icon"
import { getLinkMeta } from "../meta/links"
import { LinkMeta } from "../meta/types"
const ClickableIcon = (props: { meta: LinkMeta; iconProps: IconProps }) => {
const { href, name, displayName, icon } = props.meta
return (
<a
href={href}
title={displayName || name}
className="me-2"
rel="external"
style={{ textDecoration: "none" }}
>
<Icon meta={icon} {...props.iconProps} />
</a>
)
}
interface LinkProps {
noTitle?: boolean
noIcon?: boolean
noUnderline?: boolean
iconProps?: IconProps
}
const Link = (props: LinkProps & { meta: LinkMeta }) => {
const { href, name, displayName, icon } = props.meta
const { noTitle, noIcon, noUnderline, iconProps } = props
const styles = noUnderline ? { textDecoration: "none" } : undefined
const isLocal = href[0] === "/"
return (
<>
{isLocal ? (
<GatsbyLink to={href} title={displayName || name} style={styles}>
{(!noTitle && displayName) || name}
</GatsbyLink>
) : (
<a
href={href}
title={displayName || name}
rel="external"
style={styles}
>
{(!noTitle && displayName) || name}
</a>
)}
{!noIcon && (
<span className="ms-1">
<Icon meta={icon} {...iconProps} />
</span>
)}
</>
)
}
const extendMeta = (
base: LinkMeta,
extend?: { title: string; href: string }
): LinkMeta => {
if (extend) {
const { title, href } = extend
return { ...base, displayName: title, href }
}
return base
}
export const CreateIcon = (props: {
className?: string
iconProps: IconProps
from: string
extend?: { title: string; href: string }
}) => {
const { from, extend } = props
const baseMeta = getLinkMeta(from)
const newMeta = extendMeta(baseMeta, extend)
return <ClickableIcon {...props} meta={newMeta} />
}
export const CreateLink = (
props: LinkProps & { from: string; extend?: { title: string; href: string } }
) => {
const { from, extend } = props
const baseMeta = getLinkMeta(from)
const newMeta = extendMeta(baseMeta, extend)
return <Link {...props} meta={newMeta} />
}
export const CreateBadge = (
props: LinkProps & { from: string; extend?: { title: string; href: string } }
) => {
return (
<span className="badge rounded-pill mt-1 me-1">
<CreateLink noUnderline {...props} />
</span>
)
}
|
angelxehg/angelxehg.github.io
|
src/components/Footer.tsx
|
<reponame>angelxehg/angelxehg.github.io
import React from "react"
import { CreateLink } from "./Link"
const repoVer = {
title: "v2.0.3",
href: "https://github.com/angelxehg/angelxehg.github.io/tree/v2.0.3",
}
const issueLink = {
title: "Issues",
href: "https://github.com/angelxehg/angelxehg.github.io/issues",
}
const DefaultFooter = (): JSX.Element => (
<footer className="navbar">
<div className="container-lg ps-sm-4 pe-sm-4" style={{ display: "block" }}>
<p className="navbar-text m-0">
© {new Date().getFullYear()}, <NAME> @{" "}
<CreateLink from="GitHub" extend={repoVer} />. Portafolio profesional
creado con <CreateLink from="GatsbyJS" /> y{" "}
<CreateLink from="Bootstrap" />. Reporta problemas o envía tus
sugerencias a la página <CreateLink from="GitHub" extend={issueLink} />
</p>
<p className="navbar-text m-0">
Las marcas y logotipos presentados en este sitio web pertenecen a sus
respectivos dueños. Iconos de <CreateLink from="FontAwesome" />
</p>
</div>
</footer>
)
export default DefaultFooter
|
angelxehg/angelxehg.github.io
|
src/hooks/use-pages.tsx
|
<filename>src/hooks/use-pages.tsx
import { graphql, useStaticQuery } from "gatsby"
import { IGatsbyImageData } from "gatsby-plugin-image"
export interface RAWPage {
id: string
slug: string
excerpt: string
frontmatter: {
title: string
date: string
image: { childImageSharp: { gatsbyImageData: IGatsbyImageData } }
caption: string
stack: string[]
published: boolean
}
}
export interface Page {
id: string
slug: string
date: string
title: string
excerpt: string
image: IGatsbyImageData
caption: string
stack: string[]
published: boolean
}
export const toPage = (item: RAWPage): Page => {
const { id, slug, excerpt } = item
const { date, title, caption, stack, published } = item.frontmatter
return {
id,
slug,
date,
title,
excerpt,
caption,
stack,
published,
image: item.frontmatter.image.childImageSharp.gatsbyImageData,
}
}
export const sortByDate = (a: Page, b: Page) => {
if (a.date < b.date) {
return 1
}
if (a.date > b.date) {
return -1
}
return 0
}
export const usePages = (): Page[] => {
const { allMdx } = useStaticQuery(graphql`
query AllProjects {
allMdx {
nodes {
id
slug
excerpt(pruneLength: 35)
frontmatter {
title
date(formatString: "YYYY-MM-DD")
image {
childImageSharp {
gatsbyImageData(layout: FULL_WIDTH)
}
}
caption
stack
published
}
}
}
}
`)
const nodes: RAWPage[] = allMdx.nodes
return nodes
.map(toPage)
.sort(sortByDate)
.filter(i => i.published === true)
}
|
angelxehg/angelxehg.github.io
|
src/meta/stacks.ts
|
interface Stack {
title: string
tools: string[]
}
const stacks: Stack[] = [
{
title: "Mis herramientas favoritas:",
tools: [
"React",
"Firebase",
"GatsbyJS",
"Ubuntu",
"VSCode",
"Netlify",
"GitHub",
],
},
{
title: "Estoy aprendiendo:",
tools: ["Dart", "Flutter", "GraphQL", "Angular", "Ionic", "Capacitor"],
},
{
title: "También trabajo con:",
tools: [
"HTML5",
"JavaScript",
"TypeScript",
"Python",
"Django",
"Markdown",
"NPM",
"Git",
],
},
{
title: "Otras herramientas:",
tools: [
"Cordova",
"Heroku",
"Bootstrap",
"GitLab",
"DigitalOcean",
"NodeJS",
"AWS",
],
},
]
export default stacks
|
angelxehg/angelxehg.github.io
|
src/pages/404.tsx
|
<gh_stars>0
import React from "react"
import { Link } from "gatsby"
import CenterLayout from "../layouts/Center"
import SEO from "../components/SEO"
const ConcernedSVG = require("../assets/concerned.svg")
const NotFoundPage = (): JSX.Element => (
<CenterLayout>
<SEO title="404: Not found" lang="es" />
<main className="card">
<ConcernedSVG
style={{ width: "5rem", height: "5rem" }}
className="align-self-center mt-2"
/>
<div className="card-body">
<h1 className="card-title h5">404 Not Found</h1>
<p className="card-text m-0">
La página que buscas no existe.{" "}
<Link to="/">Ir a página principal</Link>
</p>
</div>
</main>
</CenterLayout>
)
export default NotFoundPage
|
angelxehg/angelxehg.github.io
|
src/templates/page.tsx
|
<gh_stars>0
import React from "react"
import { graphql, Link } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import { GatsbyImage, IGatsbyImageData } from "gatsby-plugin-image"
import Footer from "../components/Footer"
import SEO from "../components/SEO"
import Layout from "../layouts/Layout"
import DefaultNavbar from "../components/Navbar"
import { CreateBadge } from "../components/Link"
export const query = graphql`
query PostsByID($id: String!) {
mdx(id: { eq: $id }) {
body
frontmatter {
title
date(formatString: "YYYY-MM-DD")
image {
childImageSharp {
gatsbyImageData(layout: FULL_WIDTH)
}
}
stack
caption
}
}
}
`
interface PageTemplateProps {
data: {
mdx: {
body: string
frontmatter: {
title: string
date: string
image: {
childImageSharp: {
gatsbyImageData: IGatsbyImageData
}
}
stack: string[]
caption: string
}
}
}
}
const PageTemplate = (props: PageTemplateProps): JSX.Element => {
const { frontmatter, body } = props.data.mdx
const { title, image, caption, stack } = frontmatter
return (
<Layout>
<SEO
title={title}
lang="es"
image={image.childImageSharp.gatsbyImageData.images.fallback?.src || ""}
/>
<DefaultNavbar />
<div className="hero">
<div className="container-lg ps-sm-4 pe-sm-4 pt-3 pb-3">
<div className="row">
<div className="col-lg-8 col-md-6">
<Link to="/projects">{"< "}Volver a Proyectos</Link>
<header className="mt-1">
<h1>{title}</h1>
<p className="m-0">{caption}</p>
</header>
<p>
{stack.map(toolName => (
<CreateBadge key={toolName} from={toolName} />
))}
</p>
</div>
<div className="col-lg-4 col-md-6">
<GatsbyImage
image={image.childImageSharp.gatsbyImageData}
className="rounded"
alt={caption}
/>
</div>
</div>
</div>
</div>
<main className="container-lg ps-sm-4 pe-sm-4 pt-3">
<MDXRenderer>{body}</MDXRenderer>
</main>
<Footer />
</Layout>
)
}
export default PageTemplate
|
angelxehg/angelxehg.github.io
|
src/meta/data/websites.ts
|
import { LinkMeta } from "../types"
const websites: LinkMeta[] = [
{
name: "Instagram",
icon: {
svgPath: "bootstrap-icons/instagram.svg",
},
href: "https://instagram.com/",
},
{
name: "LinkedIn",
icon: {
svgPath: "bootstrap-icons/linkedin.svg",
},
href: "https://www.linkedin.com/",
},
{
name: "PayPal",
icon: {
svgPath: "seek-logo/paypal.svg",
},
href: "https://paypal.com/",
},
{
name: "Twitter",
icon: {
svgPath: "bootstrap-icons/twitter.svg",
},
href: "https://www.twitter.com/",
},
{
name: "Dev.to",
icon: {
fill: true,
svgPath: "iconify/devto.svg",
},
href: "https://dev.to/",
},
{
name: "Diplomas",
icon: {
fill: true,
svgPath: "fontawesome/certificate-solid.svg",
},
href: "https://platzi.com/",
},
]
export default websites
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.