repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
YaroShkvorets/ant-design-vue
|
components/vc-table/Footer/Cell.tsx
|
import { defineComponent } from 'vue';
import Cell from '../Cell';
import { useInjectSummary } from '../context/SummaryContext';
import { useInjectTable } from '../context/TableContext';
import type { AlignType } from '../interface';
import { getCellFixedInfo } from '../utils/fixUtil';
export interface SummaryCellProps {
index: number;
colSpan?: number;
rowSpan?: number;
align?: AlignType;
}
export default defineComponent<SummaryCellProps>({
name: 'SummaryCell',
inheritAttrs: false,
props: ['index', 'colSpan', 'rowSpan', 'align'] as any,
setup(props, { attrs, slots }) {
const tableContext = useInjectTable();
const summaryContext = useInjectSummary();
return () => {
const { index, colSpan = 1, rowSpan, align } = props;
const { prefixCls, direction } = tableContext;
const { scrollColumnIndex, stickyOffsets, flattenColumns } = summaryContext;
const lastIndex = index + colSpan - 1;
const mergedColSpan = lastIndex + 1 === scrollColumnIndex ? colSpan + 1 : colSpan;
const fixedInfo = getCellFixedInfo(
index,
index + mergedColSpan - 1,
flattenColumns,
stickyOffsets,
direction,
);
return (
<Cell
class={attrs.class as string}
index={index}
component="td"
prefixCls={prefixCls}
record={null}
dataIndex={null}
align={align}
customRender={() => ({
children: slots.default?.(),
props: {
colSpan: mergedColSpan,
rowSpan,
},
})}
{...fixedInfo}
/>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/locale/de_DE.tsx
|
<filename>components/locale/de_DE.tsx<gh_stars>1000+
/* eslint-disable no-template-curly-in-string */
import Pagination from '../vc-pagination/locale/de_DE';
import DatePicker from '../date-picker/locale/de_DE';
import TimePicker from '../time-picker/locale/de_DE';
import Calendar from '../calendar/locale/de_DE';
import type { Locale } from '../locale-provider';
const typeTemplate = '${label} ist nicht gültig. ${type} erwartet';
const localeValues: Locale = {
locale: 'de',
Pagination,
DatePicker,
TimePicker,
Calendar,
global: {
placeholder: 'Bitte auswählen',
},
Table: {
filterTitle: 'Filter-Menü',
filterConfirm: 'OK',
filterReset: 'Zurücksetzen',
selectAll: 'Selektiere Alle',
selectInvert: 'Selektion Invertieren',
selectionAll: 'Wählen Sie alle Daten aus',
sortTitle: 'Sortieren',
expand: 'Zeile erweitern',
collapse: 'Zeile reduzieren',
triggerDesc: 'Klicken zur absteigenden Sortierung',
triggerAsc: 'Klicken zur aufsteigenden Sortierung',
cancelSort: 'Klicken zum Abbrechen der Sortierung',
},
Modal: {
okText: 'OK',
cancelText: 'Abbrechen',
justOkText: 'OK',
},
Popconfirm: {
okText: 'OK',
cancelText: 'Abbrechen',
},
Transfer: {
titles: ['', ''],
searchPlaceholder: 'Suchen',
itemUnit: 'Eintrag',
itemsUnit: 'Einträge',
remove: 'Entfernen',
selectCurrent: 'Alle auf aktueller Seite auswählen',
removeCurrent: 'Auswahl auf aktueller Seite aufheben',
selectAll: 'Alle auswählen',
removeAll: 'Auswahl aufheben',
selectInvert: 'Auswahl umkehren',
},
Upload: {
uploading: 'Hochladen...',
removeFile: 'Datei entfernen',
uploadError: 'Fehler beim Hochladen',
previewFile: 'Dateivorschau',
downloadFile: 'Download-Datei',
},
Empty: {
description: 'Keine Daten',
},
Text: {
edit: 'Bearbeiten',
copy: 'Kopieren',
copied: 'Kopiert',
expand: 'Erweitern',
},
PageHeader: {
back: 'Zurück',
},
Form: {
defaultValidateMessages: {
default: 'Feld-Validierungsfehler: ${label}',
required: 'Bitte geben Sie ${label} an',
enum: '${label} muss eines der folgenden sein [${enum}]',
whitespace: '${label} darf kein Leerzeichen sein',
date: {
format: '${label} ist ein ungültiges Datumsformat',
parse: '${label} kann nicht in ein Datum umgewandelt werden',
invalid: '${label} ist ein ungültiges Datum',
},
types: {
string: typeTemplate,
method: typeTemplate,
array: typeTemplate,
object: typeTemplate,
number: typeTemplate,
date: typeTemplate,
boolean: typeTemplate,
integer: typeTemplate,
float: typeTemplate,
regexp: typeTemplate,
email: typeTemplate,
url: typeTemplate,
hex: typeTemplate,
},
string: {
len: '${label} muss genau ${len} Zeichen lang sein',
min: '${label} muss mindestens ${min} Zeichen lang sein',
max: '${label} darf höchstens ${max} Zeichen lang sein',
range: '${label} muss zwischen ${min} und ${max} Zeichen lang sein',
},
number: {
len: '${label} muss gleich ${len} sein',
min: '${label} muss mindestens ${min} sein',
max: '${label} darf maximal ${max} sein',
range: '${label} muss zwischen ${min} und ${max} liegen',
},
array: {
len: 'Es müssen ${len} ${label} sein',
min: 'Es müssen mindestens ${min} ${label} sein',
max: 'Es dürfen maximal ${max} ${label} sein',
range: 'Die Anzahl an ${label} muss zwischen ${min} und ${max} liegen',
},
pattern: {
mismatch: '${label} enspricht nicht dem ${pattern} Muster',
},
},
},
};
export default localeValues;
|
YaroShkvorets/ant-design-vue
|
components/table/hooks/usePagination.ts
|
<filename>components/table/hooks/usePagination.ts
import useState from '../../_util/hooks/useState';
import type { Ref } from 'vue';
import { computed } from 'vue';
import type { PaginationProps } from '../../pagination';
import type { TablePaginationConfig } from '../interface';
export const DEFAULT_PAGE_SIZE = 10;
export function getPaginationParam(
pagination: TablePaginationConfig | boolean | undefined,
mergedPagination: TablePaginationConfig,
) {
const param: any = {
current: mergedPagination.current,
pageSize: mergedPagination.pageSize,
};
const paginationObj = pagination && typeof pagination === 'object' ? pagination : {};
Object.keys(paginationObj).forEach(pageProp => {
const value = (mergedPagination as any)[pageProp];
if (typeof value !== 'function') {
param[pageProp] = value;
}
});
return param;
}
function extendsObject<T extends Object>(...list: T[]) {
const result: T = {} as T;
list.forEach(obj => {
if (obj) {
Object.keys(obj).forEach(key => {
const val = (obj as any)[key];
if (val !== undefined) {
(result as any)[key] = val;
}
});
}
});
return result;
}
export default function usePagination(
totalRef: Ref<number>,
paginationRef: Ref<TablePaginationConfig | false | undefined>,
onChange: (current: number, pageSize: number) => void,
): [Ref<TablePaginationConfig>, () => void] {
const pagination = computed(() =>
paginationRef.value && typeof paginationRef.value === 'object' ? paginationRef.value : {},
);
const paginationTotal = computed(() => pagination.value.total || 0);
const [innerPagination, setInnerPagination] = useState<{
current?: number;
pageSize?: number;
}>(() => ({
current: 'defaultCurrent' in pagination.value ? pagination.value.defaultCurrent : 1,
pageSize:
'defaultPageSize' in pagination.value ? pagination.value.defaultPageSize : DEFAULT_PAGE_SIZE,
}));
// ============ Basic Pagination Config ============
const mergedPagination = computed(() => {
const mP = extendsObject<Partial<TablePaginationConfig>>(
innerPagination.value,
pagination.value,
{
total: paginationTotal.value > 0 ? paginationTotal.value : totalRef.value,
},
);
// Reset `current` if data length or pageSize changed
const maxPage = Math.ceil((paginationTotal.value || totalRef.value) / mP.pageSize!);
if (mP.current! > maxPage) {
// Prevent a maximum page count of 0
mP.current = maxPage || 1;
}
return mP;
});
const refreshPagination = (current = 1, pageSize?: number) => {
if (pagination.value === false) return;
setInnerPagination({
current,
pageSize: pageSize || mergedPagination.value.pageSize,
});
};
const onInternalChange: PaginationProps['onChange'] = (current, pageSize) => {
if (pagination.value) {
pagination.value.onChange?.(current, pageSize);
}
refreshPagination(current, pageSize);
onChange(current, pageSize || mergedPagination.value.pageSize);
};
return [
computed(() => {
return pagination.value === false
? {}
: { ...mergedPagination.value, onChange: onInternalChange };
}),
refreshPagination,
];
}
|
YaroShkvorets/ant-design-vue
|
components/vc-pagination/Options.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import PropTypes from '../_util/vue-types';
import KEYCODE from './KeyCode';
import { computed, defineComponent, ref, withDirectives } from 'vue';
import antInput from '../_util/antInputDirective';
import type { EventHandler } from '../_util/EventInterface';
export default defineComponent({
props: {
disabled: PropTypes.looseBool,
changeSize: PropTypes.func,
quickGo: PropTypes.func,
selectComponentClass: PropTypes.any,
current: PropTypes.number,
pageSizeOptions: PropTypes.array.def(['10', '20', '50', '100']),
pageSize: PropTypes.number,
buildOptionText: PropTypes.func,
locale: PropTypes.object,
rootPrefixCls: PropTypes.string,
selectPrefixCls: PropTypes.string,
goButton: PropTypes.any,
},
setup(props) {
const goInputText = ref('');
const validValue = computed(() => {
return !goInputText.value || isNaN(goInputText.value as any)
? undefined
: Number(goInputText.value);
});
const defaultBuildOptionText = opt => {
return `${opt.value} ${props.locale.items_per_page}`;
};
const handleChange: EventHandler = e => {
const { value, composing } = e.target;
if (e.isComposing || composing || goInputText.value === value) return;
goInputText.value = value;
};
const handleBlur: EventHandler = e => {
const { goButton, quickGo, rootPrefixCls } = props;
if (goButton || goInputText.value === '') {
return;
}
if (
e.relatedTarget &&
(e.relatedTarget.className.indexOf(`${rootPrefixCls}-item-link`) >= 0 ||
e.relatedTarget.className.indexOf(`${rootPrefixCls}-item`) >= 0)
) {
goInputText.value = '';
return;
} else {
quickGo(validValue.value);
goInputText.value = '';
}
};
const go: EventHandler = e => {
if (goInputText.value === '') {
return;
}
if (e.keyCode === KEYCODE.ENTER || e.type === 'click') {
// https://github.com/vueComponent/ant-design-vue/issues/1316
props.quickGo(validValue.value);
goInputText.value = '';
}
};
const pageSizeOptions = computed(() => {
const { pageSize, pageSizeOptions } = props;
if (pageSizeOptions.some(option => option.toString() === pageSize.toString())) {
return pageSizeOptions;
}
return pageSizeOptions.concat([pageSize.toString()]).sort((a, b) => {
// eslint-disable-next-line no-restricted-globals
const numberA = isNaN(Number(a)) ? 0 : Number(a);
// eslint-disable-next-line no-restricted-globals
const numberB = isNaN(Number(b)) ? 0 : Number(b);
return numberA - numberB;
});
});
return () => {
const {
rootPrefixCls,
locale,
changeSize,
quickGo,
goButton,
selectComponentClass: Select,
selectPrefixCls,
pageSize,
disabled,
} = props;
const prefixCls = `${rootPrefixCls}-options`;
let changeSelect = null;
let goInput = null;
let gotoButton = null;
if (!changeSize && !quickGo) {
return null;
}
if (changeSize && Select) {
const buildOptionText = props.buildOptionText || defaultBuildOptionText;
const options = pageSizeOptions.value.map((opt, i) => (
<Select.Option key={i} value={opt}>
{buildOptionText({ value: opt })}
</Select.Option>
));
changeSelect = (
<Select
disabled={disabled}
prefixCls={selectPrefixCls}
showSearch={false}
class={`${prefixCls}-size-changer`}
optionLabelProp="children"
value={(pageSize || pageSizeOptions.value[0]).toString()}
onChange={value => changeSize(Number(value))}
getPopupContainer={triggerNode => triggerNode.parentNode}
>
{options}
</Select>
);
}
if (quickGo) {
if (goButton) {
gotoButton =
typeof goButton === 'boolean' ? (
<button
type="button"
onClick={go}
onKeyup={go}
disabled={disabled}
class={`${prefixCls}-quick-jumper-button`}
>
{locale.jump_to_confirm}
</button>
) : (
<span onClick={go} onKeyup={go}>
{goButton}
</span>
);
}
goInput = (
<div class={`${prefixCls}-quick-jumper`}>
{locale.jump_to}
{withDirectives(
<input
disabled={disabled}
type="text"
value={goInputText.value}
onInput={handleChange}
onChange={handleChange}
onKeyup={go}
onBlur={handleBlur}
/>,
[[antInput]],
)}
{locale.page}
{gotoButton}
</div>
);
}
return (
<li class={`${prefixCls}`}>
{changeSelect}
{goInput}
</li>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/upload/UploadList.tsx
|
<reponame>YaroShkvorets/ant-design-vue<gh_stars>1000+
import type { CSSProperties } from 'vue';
import { defineComponent, inject, nextTick } from 'vue';
import BaseMixin from '../_util/BaseMixin';
import { getOptionProps, initDefaultProps } from '../_util/props-util';
import {
getTransitionProps,
Transition,
getTransitionGroupProps,
TransitionGroup,
} from '../_util/transition';
import { defaultConfigProvider } from '../config-provider';
import { previewImage, isImageUrl } from './utils';
import LoadingOutlined from '@ant-design/icons-vue/LoadingOutlined';
import PaperClipOutlined from '@ant-design/icons-vue/PaperClipOutlined';
import PictureTwoTone from '@ant-design/icons-vue/PictureTwoTone';
import FileTwoTone from '@ant-design/icons-vue/FileOutlined';
import DeleteOutlined from '@ant-design/icons-vue/DeleteOutlined';
import DownloadOutlined from '@ant-design/icons-vue/DownloadOutlined';
import EyeOutlined from '@ant-design/icons-vue/EyeOutlined';
import Tooltip from '../tooltip';
import Progress from '../progress';
import classNames from '../_util/classNames';
import { UploadListProps } from './interface';
export default defineComponent({
name: 'AUploadList',
mixins: [BaseMixin],
props: initDefaultProps(UploadListProps, {
listType: 'text', // or picture
progressAttr: {
strokeWidth: 2,
showInfo: false,
},
showRemoveIcon: true,
showDownloadIcon: false,
showPreviewIcon: true,
previewFile: previewImage,
}),
setup() {
return {
configProvider: inject('configProvider', defaultConfigProvider),
};
},
updated() {
nextTick(() => {
const { listType, items, previewFile } = this.$props;
if (listType !== 'picture' && listType !== 'picture-card') {
return;
}
(items || []).forEach(file => {
if (
typeof document === 'undefined' ||
typeof window === 'undefined' ||
!window.FileReader ||
!window.File ||
!(file.originFileObj instanceof File || file.originFileObj instanceof Blob) ||
file.thumbUrl !== undefined
) {
return;
}
/*eslint-disable */
file.thumbUrl = '';
if (previewFile) {
previewFile(file.originFileObj).then(previewDataUrl => {
// Need append '' to avoid dead loop
file.thumbUrl = previewDataUrl || '';
(this as any).$forceUpdate();
});
}
});
});
},
methods: {
handlePreview(file, e) {
const { onPreview } = this.$props;
if (!onPreview) {
return;
}
e.preventDefault();
return this.$emit('preview', file);
},
handleDownload(file) {
const { onDownload } = this.$props;
if (typeof onDownload === 'function') {
this.$emit('download', file);
} else if (file.url) {
window.open(file.url);
}
},
handleClose(file) {
this.$emit('remove', file);
},
},
render() {
const {
prefixCls: customizePrefixCls,
items = [],
listType,
showPreviewIcon,
showRemoveIcon,
showDownloadIcon,
locale,
progressAttr,
} = getOptionProps(this);
const getPrefixCls = this.configProvider.getPrefixCls;
const prefixCls = getPrefixCls('upload', customizePrefixCls);
const list = items.map(file => {
let progress;
let icon = file.status === 'uploading' ? <LoadingOutlined /> : <PaperClipOutlined />;
if (listType === 'picture' || listType === 'picture-card') {
if (listType === 'picture-card' && file.status === 'uploading') {
icon = <div class={`${prefixCls}-list-item-uploading-text`}>{locale.uploading}</div>;
} else if (!file.thumbUrl && !file.url) {
icon = <PictureTwoTone class={`${prefixCls}-list-item-thumbnail`} />;
} else {
const thumbnail = isImageUrl(file) ? (
<img
src={file.thumbUrl || file.url}
alt={file.name}
class={`${prefixCls}-list-item-image`}
/>
) : (
<FileTwoTone class={`${prefixCls}-list-item-icon`} />
);
icon = (
<a
class={`${prefixCls}-list-item-thumbnail`}
onClick={e => this.handlePreview(file, e)}
href={file.url || file.thumbUrl}
target="_blank"
rel="noopener noreferrer"
>
{thumbnail}
</a>
);
}
}
if (file.status === 'uploading') {
const progressProps = {
...progressAttr,
type: 'line',
percent: file.percent,
};
// show loading icon if upload progress listener is disabled
const loadingProgress = 'percent' in file ? <Progress {...progressProps} /> : null;
progress = (
<div class={`${prefixCls}-list-item-progress`} key="progress">
{loadingProgress}
</div>
);
}
const infoUploadingClass = classNames({
[`${prefixCls}-list-item`]: true,
[`${prefixCls}-list-item-${file.status}`]: true,
[`${prefixCls}-list-item-list-type-${listType}`]: true,
});
const linkProps =
typeof file.linkProps === 'string' ? JSON.parse(file.linkProps) : file.linkProps;
const removeIcon = showRemoveIcon ? (
<DeleteOutlined title={locale.removeFile} onClick={() => this.handleClose(file)} />
) : null;
const downloadIcon =
showDownloadIcon && file.status === 'done' ? (
<DownloadOutlined title={locale.downloadFile} onClick={() => this.handleDownload(file)} />
) : null;
const downloadOrDelete = listType !== 'picture-card' && (
<span
key="download-delete"
class={`${prefixCls}-list-item-card-actions ${listType === 'picture' ? 'picture' : ''}`}
>
{downloadIcon && <a title={locale.downloadFile}>{downloadIcon}</a>}
{removeIcon && <a title={locale.removeFile}>{removeIcon}</a>}
</span>
);
const listItemNameClass = classNames({
[`${prefixCls}-list-item-name`]: true,
[`${prefixCls}-list-item-name-icon-count-${
[downloadIcon, removeIcon].filter(x => x).length
}`]: true,
});
const preview = file.url
? [
<a
target="_blank"
rel="noopener noreferrer"
class={listItemNameClass}
title={file.name}
{...linkProps}
href={file.url}
onClick={e => this.handlePreview(file, e)}
>
{file.name}
</a>,
downloadOrDelete,
]
: [
<span
key="view"
class={`${prefixCls}-list-item-name`}
onClick={e => this.handlePreview(file, e)}
title={file.name}
>
{file.name}
</span>,
downloadOrDelete,
];
const style: CSSProperties | undefined =
file.url || file.thumbUrl
? undefined
: {
pointerEvents: 'none',
opacity: 0.5,
};
const previewIcon = showPreviewIcon ? (
<a
href={file.url || file.thumbUrl}
target="_blank"
rel="noopener noreferrer"
style={style}
onClick={e => this.handlePreview(file, e)}
title={locale.previewFile}
>
<EyeOutlined />
</a>
) : null;
const actions = listType === 'picture-card' && file.status !== 'uploading' && (
<span class={`${prefixCls}-list-item-actions`}>
{previewIcon}
{file.status === 'done' && downloadIcon}
{removeIcon}
</span>
);
let message;
if (file.response && typeof file.response === 'string') {
message = file.response;
} else {
message = (file.error && file.error.statusText) || locale.uploadError;
}
const iconAndPreview = (
<span>
{icon}
{preview}
</span>
);
const transitionProps = getTransitionProps('fade');
const dom = (
<div class={infoUploadingClass} key={file.uid}>
<div class={`${prefixCls}-list-item-info`}>{iconAndPreview}</div>
{actions}
<Transition {...transitionProps}>{progress}</Transition>
</div>
);
const listContainerNameClass = classNames({
[`${prefixCls}-list-picture-card-container`]: listType === 'picture-card',
});
return (
<div key={file.uid} class={listContainerNameClass}>
{file.status === 'error' ? <Tooltip title={message}>{dom}</Tooltip> : <span>{dom}</span>}
</div>
);
});
const listClassNames = classNames({
[`${prefixCls}-list`]: true,
[`${prefixCls}-list-${listType}`]: true,
});
const animationDirection = listType === 'picture-card' ? 'animate-inline' : 'animate';
const transitionGroupProps = {
...getTransitionGroupProps(`${prefixCls}-${animationDirection}`),
class: listClassNames,
};
return (
<TransitionGroup {...transitionGroupProps} tag="div">
{list}
</TransitionGroup>
);
},
});
|
YaroShkvorets/ant-design-vue
|
components/_util/component-classes.ts
|
/**
* source by `component-classes`
* https://github.com/component/classes.git
*/
import indexOf from 'lodash-es/indexOf';
/**
* Whitespace regexp.
*/
const re = /\s+/;
export class ClassList {
el: Element;
list: DOMTokenList;
constructor(el: Element) {
if (!el || !el.nodeType) {
throw new Error('A DOM element reference is required');
}
this.el = el;
this.list = el.classList;
}
array() {
const className = this.el.getAttribute('class') || '';
const str = className.replace(/^\s+|\s+$/g, '');
const arr = str.split(re);
if ('' === arr[0]) arr.shift();
return arr;
}
/**
* Add class `name` if not already present.
*
* @param {String} name
* @return {ClassList}
* @api public
*/
add(name: string): ClassList {
// classList
if (this.list) {
this.list.add(name);
return this;
}
// fallback
const arr = this.array();
const i = indexOf(arr, name);
if (!~i) arr.push(name);
this.el.className = arr.join(' ');
return this;
}
/**
* Remove class `name` when present, or
* pass a regular expression to remove
* any which match.
*
* @param {String|RegExp} name
* @return {ClassList}
* @api public
*/
remove(name: string | RegExp): ClassList {
if ('[object RegExp]' === toString.call(name)) {
return this._removeMatching(name as RegExp);
}
// classList
if (this.list) {
this.list.remove(name as string);
return this;
}
// fallback
const arr = this.array();
const i = indexOf(arr, name);
if (~i) arr.splice(i, 1);
this.el.className = arr.join(' ');
return this;
}
/**
* Remove all classes matching `re`.
*
* @param {RegExp} re
* @return {ClassList}
* @api private
*/
_removeMatching(re: RegExp): ClassList {
const arr = this.array();
for (let i = 0; i < arr.length; i++) {
if (re.test(arr[i])) {
this.remove(arr[i]);
}
}
return this;
}
/**
* Toggle class `name`, can force state via `force`.
*
* For browsers that support classList, but do not support `force` yet,
* the mistake will be detected and corrected.
*
* @param {String} name
* @param {Boolean} force
* @return {ClassList}
* @api public
*/
toggle(name: string, force: boolean): ClassList {
// classList
if (this.list) {
if ('undefined' !== typeof force) {
if (force !== this.list.toggle(name, force)) {
this.list.toggle(name); // toggle again to correct
}
} else {
this.list.toggle(name);
}
return this;
}
// fallback
if ('undefined' !== typeof force) {
if (!force) {
this.remove(name);
} else {
this.add(name);
}
} else {
if (this.has(name)) {
this.remove(name);
} else {
this.add(name);
}
}
return this;
}
/**
* Check if class `name` is present.
*
* @param {String} name
* @api public
*/
has(name: string) {
return this.list ? this.list.contains(name) : !!~indexOf(this.array(), name);
}
/**
* Check if class `name` is present.
*
* @param {String} name
* @api public
*/
contains(name: string) {
return this.has(name);
}
}
/**
* Wrap `el` in a `ClassList`.
*
* @param {Element} el
* @return {ClassList}
* @api public
*/
export default function (el: Element): ClassList {
return new ClassList(el);
}
|
YaroShkvorets/ant-design-vue
|
components/locale/az_AZ.tsx
|
<gh_stars>1000+
import Pagination from '../vc-pagination/locale/az_AZ';
import DatePicker from '../date-picker/locale/az_AZ';
import TimePicker from '../time-picker/locale/az_AZ';
import Calendar from '../calendar/locale/az_AZ';
import type { Locale } from '../locale-provider';
const localeValues: Locale = {
locale: 'az',
Pagination,
DatePicker,
TimePicker,
Calendar,
Table: {
filterTitle: 'Filter menyu',
filterConfirm: 'Axtar',
filterReset: 'Sıfırla',
emptyText: 'Məlumat yoxdur',
selectAll: 'Cari səhifəni seç',
selectInvert: 'Invert current page',
},
Modal: {
okText: 'Bəli',
cancelText: 'Ləğv et',
justOkText: 'Bəli',
},
Popconfirm: {
okText: 'Bəli',
cancelText: 'Ləğv et',
},
Transfer: {
titles: ['', ''],
notFoundContent: 'Tapılmadı',
searchPlaceholder: '<NAME>',
itemUnit: 'item',
itemsUnit: 'items',
},
Select: {
notFoundContent: 'Tapılmadı',
},
Upload: {
uploading: 'Yüklənir...',
removeFile: 'Faylı sil',
uploadError: 'Yükləmə xətası',
previewFile: 'Fayla önbaxış',
},
};
export default localeValues;
|
YaroShkvorets/ant-design-vue
|
components/vc-virtual-list/Item.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import type { FunctionalComponent, PropType } from 'vue';
import { cloneVNode } from 'vue';
export interface ItemProps {
setRef: (element: HTMLElement) => void;
}
const Item: FunctionalComponent<ItemProps> = ({ setRef }, { slots }) => {
const children = slots.default?.();
return children && children.length
? cloneVNode(children[0], {
ref: setRef as any,
})
: children;
};
Item.props = {
setRef: {
type: Function as PropType<(element: HTMLElement) => void>,
default: () => {},
},
};
export default Item;
|
YaroShkvorets/ant-design-vue
|
components/_util/pickAttrs.ts
|
<filename>components/_util/pickAttrs.ts
const attributes = `accept acceptcharset accesskey action allowfullscreen allowtransparency
alt async autocomplete autofocus autoplay capture cellpadding cellspacing challenge
charset checked classid classname colspan cols content contenteditable contextmenu
controls coords crossorigin data datetime default defer dir disabled download draggable
enctype form formaction formenctype formmethod formnovalidate formtarget frameborder
headers height hidden high href hreflang htmlfor httpequiv icon id inputmode integrity
is keyparams keytype kind label lang list loop low manifest marginheight marginwidth max maxlength media
mediagroup method min minlength multiple muted name novalidate nonce open
optimum pattern placeholder poster preload radiogroup readonly rel required
reversed role rowspan rows sandbox scope scoped scrolling seamless selected
shape size sizes span spellcheck src srcdoc srclang srcset start step style
summary tabindex target title type usemap value width wmode wrap`;
const eventsName = `onCopy onCut onPaste onCompositionend onCompositionstart onCompositionupdate onKeydown
onKeypress onKeyup onFocus onBlur onChange onInput onSubmit onClick onContextmenu onDoubleclick onDblclick
onDrag onDragend onDragenter onDragexit onDragleave onDragover onDragstart onDrop onMousedown
onMouseenter onMouseleave onMousemove onMouseout onMouseover onMouseup onSelect onTouchcancel
onTouchend onTouchmove onTouchstart onTouchstartPassive onTouchmovePassive onScroll onWheel onAbort onCanplay onCanplaythrough
onDurationchange onEmptied onEncrypted onEnded onError onLoadeddata onLoadedmetadata
onLoadstart onPause onPlay onPlaying onProgress onRatechange onSeeked onSeeking onStalled onSuspend onTimeupdate onVolumechange onWaiting onLoad onError`;
const propList = `${attributes} ${eventsName}`.split(/[\s\n]+/);
/* eslint-enable max-len */
const ariaPrefix = 'aria-';
const dataPrefix = 'data-';
function match(key: string, prefix: string) {
return key.indexOf(prefix) === 0;
}
export interface PickConfig {
aria?: boolean;
data?: boolean;
attr?: boolean;
}
/**
* Picker props from exist props with filter
* @param props Passed props
* @param ariaOnly boolean | { aria?: boolean; data?: boolean; attr?: boolean; } filter config
*/
export default function pickAttrs(props: object, ariaOnly: boolean | PickConfig = false) {
let mergedConfig;
if (ariaOnly === false) {
mergedConfig = {
aria: true,
data: true,
attr: true,
};
} else if (ariaOnly === true) {
mergedConfig = {
aria: true,
};
} else {
mergedConfig = {
...ariaOnly,
};
}
const attrs = {};
Object.keys(props).forEach(key => {
if (
// Aria
(mergedConfig.aria && (key === 'role' || match(key, ariaPrefix))) ||
// Data
(mergedConfig.data && match(key, dataPrefix)) ||
// Attr
(mergedConfig.attr && (propList.includes(key) || propList.includes(key.toLowerCase())))
) {
attrs[key] = props[key];
}
});
return attrs;
}
|
YaroShkvorets/ant-design-vue
|
components/date-picker/PickerButton.tsx
|
<gh_stars>1000+
import type { FunctionalComponent } from 'vue';
import type { ButtonProps } from '../button';
import Button from '../button';
const PickerButton: FunctionalComponent<ButtonProps> = (props: ButtonProps, { attrs, slots }) => {
return <Button size="small" type="primary" {...props} {...attrs} v-slots={slots}></Button>;
};
export default PickerButton;
|
YaroShkvorets/ant-design-vue
|
components/table/hooks/useFilter/FilterWrapper.tsx
|
<reponame>YaroShkvorets/ant-design-vue
const FilterDropdownMenuWrapper = (_props, { slots }) => (
<div onClick={e => e.stopPropagation()}>{slots.default?.()}</div>
);
export default FilterDropdownMenuWrapper;
|
YaroShkvorets/ant-design-vue
|
components/_util/hooks/useRefs.ts
|
import type { Ref, ComponentPublicInstance } from 'vue';
import { onBeforeUpdate, ref } from 'vue';
import type { Key } from '../type';
type RefType = HTMLElement | ComponentPublicInstance;
export type RefsValue = Map<Key, RefType>;
type UseRef = [(key: Key) => (el: RefType) => void, Ref<RefsValue>];
const useRefs = (): UseRef => {
const refs = ref<RefsValue>(new Map());
const setRef = (key: Key) => (el: RefType) => {
refs.value.set(key, el);
};
onBeforeUpdate(() => {
refs.value = new Map();
});
return [setRef, refs];
};
export default useRefs;
|
YaroShkvorets/ant-design-vue
|
components/tabs/src/interface.ts
|
import type { Key, VueNode } from '../../_util/type';
import type { TabPaneProps } from './TabPanelList/TabPane';
export type TabSizeMap = Map<Key, { width: number; height: number; left: number; top: number }>;
export interface TabOffset {
width: number;
height: number;
left: number;
right: number;
top: number;
}
export type TabOffsetMap = Map<Key, TabOffset>;
export type TabPosition = 'left' | 'right' | 'top' | 'bottom';
export interface Tab extends TabPaneProps {
key: Key;
node: VueNode;
}
export type RenderTabBar = (props: { DefaultTabBar: any; [key: string]: any }) => VueNode;
export interface TabsLocale {
dropdownAriaLabel?: string;
removeAriaLabel?: string;
addAriaLabel?: string;
}
export interface EditableConfig {
onEdit: (type: 'add' | 'remove', info: { key?: Key; event: MouseEvent | KeyboardEvent }) => void;
showAdd?: boolean;
removeIcon?: () => VueNode;
addIcon?: () => VueNode;
}
export interface AnimatedConfig {
inkBar?: boolean;
tabPane?: boolean;
}
export type OnTabScroll = (info: { direction: 'left' | 'right' | 'top' | 'bottom' }) => void;
export type TabBarExtraPosition = 'left' | 'right';
export type TabBarExtraMap = Partial<Record<TabBarExtraPosition, any>>;
export type TabBarExtraContent = VueNode;
|
YaroShkvorets/ant-design-vue
|
components/transfer/ListItem.tsx
|
<filename>components/transfer/ListItem.tsx
import PropTypes from '../_util/vue-types';
import classNames from '../_util/classNames';
import type { TransferLocale } from '.';
import DeleteOutlined from '@ant-design/icons-vue/DeleteOutlined';
import defaultLocale from '../locale/default';
import Checkbox from '../checkbox';
import TransButton from '../_util/transButton';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import type { ExtractPropTypes } from 'vue';
import { defineComponent } from 'vue';
function noop() {}
export const transferListItemProps = {
renderedText: PropTypes.any,
renderedEl: PropTypes.any,
item: PropTypes.any,
checked: PropTypes.looseBool,
prefixCls: PropTypes.string,
disabled: PropTypes.looseBool,
showRemove: PropTypes.looseBool,
onClick: PropTypes.func,
onRemove: PropTypes.func,
};
export type TransferListItemProps = Partial<ExtractPropTypes<typeof transferListItemProps>>;
export default defineComponent({
name: 'ListItem',
inheritAttrs: false,
props: transferListItemProps,
emits: ['click', 'remove'],
setup(props, { emit }) {
return () => {
const { renderedText, renderedEl, item, checked, disabled, prefixCls, showRemove } = props;
const className = classNames({
[`${prefixCls}-content-item`]: true,
[`${prefixCls}-content-item-disabled`]: disabled || item.disabled,
});
let title: string;
if (typeof renderedText === 'string' || typeof renderedText === 'number') {
title = String(renderedText);
}
return (
<LocaleReceiver componentName="Transfer" defaultLocale={defaultLocale.Transfer}>
{(transferLocale: TransferLocale) => {
const labelNode = <span class={`${prefixCls}-content-item-text`}>{renderedEl}</span>;
if (showRemove) {
return (
<li class={className} title={title}>
{labelNode}
<TransButton
disabled={disabled || item.disabled}
class={`${prefixCls}-content-item-remove`}
aria-label={transferLocale.remove}
onClick={() => {
emit('remove', item);
}}
>
<DeleteOutlined />
</TransButton>
</li>
);
}
return (
<li
class={className}
title={title}
onClick={
disabled || item.disabled
? noop
: () => {
emit('click', item);
}
}
>
<Checkbox
class={`${prefixCls}-checkbox`}
checked={checked}
disabled={disabled || item.disabled}
/>
{labelNode}
</li>
);
}}
</LocaleReceiver>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/hooks/useRangeDisabled.ts
|
import type { RangeValue, PickerMode, Locale } from '../interface';
import { getValue } from '../utils/miscUtil';
import type { GenerateConfig } from '../generate';
import { isSameDate, getQuarter } from '../utils/dateUtil';
import type { ComputedRef, Ref } from 'vue';
import { computed } from 'vue';
export default function useRangeDisabled<DateType>(
{
picker,
locale,
selectedValue,
disabledDate,
disabled,
generateConfig,
}: {
picker: Ref<PickerMode>;
selectedValue: Ref<RangeValue<DateType>>;
disabledDate?: Ref<(date: DateType) => boolean>;
disabled: ComputedRef<[boolean, boolean]>;
locale: Ref<Locale>;
generateConfig: Ref<GenerateConfig<DateType>>;
},
openRecordsRef: Ref<{
[x: number]: boolean;
}>,
) {
const startDate = computed(() => getValue(selectedValue.value, 0));
const endDate = computed(() => getValue(selectedValue.value, 1));
function weekFirstDate(date: DateType) {
return generateConfig.value.locale.getWeekFirstDate(locale.value.locale, date);
}
function monthNumber(date: DateType) {
const year = generateConfig.value.getYear(date);
const month = generateConfig.value.getMonth(date);
return year * 100 + month;
}
function quarterNumber(date: DateType) {
const year = generateConfig.value.getYear(date);
const quarter = getQuarter(generateConfig.value, date);
return year * 10 + quarter;
}
const disabledStartDate = (date: DateType) => {
if (disabledDate && disabledDate?.value?.(date)) {
return true;
}
// Disabled range
if (disabled[1] && endDate) {
return (
!isSameDate(generateConfig.value, date, endDate.value) &&
generateConfig.value.isAfter(date, endDate.value)
);
}
// Disabled part
if (openRecordsRef.value[1] && endDate.value) {
switch (picker.value) {
case 'quarter':
return quarterNumber(date) > quarterNumber(endDate.value);
case 'month':
return monthNumber(date) > monthNumber(endDate.value);
case 'week':
return weekFirstDate(date) > weekFirstDate(endDate.value);
default:
return (
!isSameDate(generateConfig.value, date, endDate.value) &&
generateConfig.value.isAfter(date, endDate.value)
);
}
}
return false;
};
const disabledEndDate = (date: DateType) => {
if (disabledDate.value?.(date)) {
return true;
}
// Disabled range
if (disabled[0] && startDate) {
return (
!isSameDate(generateConfig.value, date, endDate.value) &&
generateConfig.value.isAfter(startDate.value, date)
);
}
// Disabled part
if (openRecordsRef.value[0] && startDate.value) {
switch (picker.value) {
case 'quarter':
return quarterNumber(date) < quarterNumber(startDate.value);
case 'month':
return monthNumber(date) < monthNumber(startDate.value);
case 'week':
return weekFirstDate(date) < weekFirstDate(startDate.value);
default:
return (
!isSameDate(generateConfig.value, date, startDate.value) &&
generateConfig.value.isAfter(startDate.value, date)
);
}
}
return false;
};
return [disabledStartDate, disabledEndDate];
}
|
YaroShkvorets/ant-design-vue
|
components/badge/index.ts
|
import type { App, Plugin } from 'vue';
import Badge from './Badge';
import Ribbon from './Ribbon';
export type { BadgeProps } from './Badge';
Badge.install = function (app: App) {
app.component(Badge.name, Badge);
app.component(Ribbon.name, Ribbon);
return app;
};
export { Ribbon as BadgeRibbon };
export default Badge as typeof Badge &
Plugin & {
readonly Ribbon: typeof Ribbon;
};
|
YaroShkvorets/ant-design-vue
|
components/locale/da_DK.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import Pagination from '../vc-pagination/locale/da_DK';
import DatePicker from '../date-picker/locale/da_DK';
import TimePicker from '../time-picker/locale/da_DK';
import Calendar from '../calendar/locale/da_DK';
import type { Locale } from '../locale-provider';
const localeValues: Locale = {
locale: 'da',
DatePicker,
TimePicker,
Calendar,
Pagination,
Table: {
filterTitle: 'Filtermenu',
filterConfirm: 'OK',
filterReset: 'Nulstil',
selectAll: 'Vælg alle',
selectInvert: 'Inverter valg',
},
Modal: {
okText: 'OK',
cancelText: 'Afbryd',
justOkText: 'OK',
},
Popconfirm: {
okText: 'OK',
cancelText: 'Afbryd',
},
Transfer: {
searchPlaceholder: 'Søg her',
itemUnit: 'element',
itemsUnit: 'elementer',
},
Upload: {
uploading: 'Uploader...',
removeFile: 'Fjern fil',
uploadError: 'Fejl ved upload',
previewFile: 'Forhåndsvisning',
downloadFile: 'Download fil',
},
Empty: {
description: 'Ingen data',
},
};
export default localeValues;
|
YaroShkvorets/ant-design-vue
|
components/vc-tooltip/index.ts
|
<filename>components/vc-tooltip/index.ts
// base rc-tooltip 5.1.1
import Tooltip from './src/Tooltip';
export default Tooltip;
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/RangePicker.tsx
|
import type { DisabledTimes, PanelMode, PickerMode, RangeValue, EventValue } from './interface';
import type { PickerBaseProps, PickerDateProps, PickerTimeProps } from './Picker';
import type { SharedTimeProps } from './panels/TimePanel';
import PickerTrigger from './PickerTrigger';
import PickerPanel from './PickerPanel';
import usePickerInput from './hooks/usePickerInput';
import getDataOrAriaProps, { toArray, getValue, updateValues } from './utils/miscUtil';
import { getDefaultFormat, getInputSize, elementsContains } from './utils/uiUtil';
import type { ContextOperationRefProps } from './PanelContext';
import { useProvidePanel } from './PanelContext';
import {
isEqual,
getClosingViewDate,
isSameDate,
isSameWeek,
isSameQuarter,
formatValue,
parseValue,
} from './utils/dateUtil';
import useValueTexts from './hooks/useValueTexts';
import useTextValueMapping from './hooks/useTextValueMapping';
import type { GenerateConfig } from './generate';
import type { PickerPanelProps } from '.';
import { RangeContextProvider } from './RangeContext';
import useRangeDisabled from './hooks/useRangeDisabled';
import getExtraFooter from './utils/getExtraFooter';
import getRanges from './utils/getRanges';
import useRangeViewDates from './hooks/useRangeViewDates';
import type { DateRender } from './panels/DatePanel/DateBody';
import useHoverValue from './hooks/useHoverValue';
import type { VueNode } from '../_util/type';
import type { ChangeEvent, FocusEventHandler, MouseEventHandler } from '../_util/EventInterface';
import { computed, defineComponent, ref, toRef, watch, watchEffect } from 'vue';
import useMergedState from '../_util/hooks/useMergedState';
import { warning } from '../vc-util/warning';
import useState from '../_util/hooks/useState';
import classNames from '../_util/classNames';
function reorderValues<DateType>(
values: RangeValue<DateType>,
generateConfig: GenerateConfig<DateType>,
): RangeValue<DateType> {
if (values && values[0] && values[1] && generateConfig.isAfter(values[0], values[1])) {
return [values[1], values[0]];
}
return values;
}
function canValueTrigger<DateType>(
value: EventValue<DateType>,
index: number,
disabled: [boolean, boolean],
allowEmpty?: [boolean, boolean] | null,
): boolean {
if (value) {
return true;
}
if (allowEmpty && allowEmpty[index]) {
return true;
}
if (disabled[(index + 1) % 2]) {
return true;
}
return false;
}
export type RangeType = 'start' | 'end';
export type RangeInfo = {
range: RangeType;
};
export type RangeDateRender<DateType> = (props: {
current: DateType;
today: DateType;
info: RangeInfo;
}) => VueNode;
export type RangePickerSharedProps<DateType> = {
id?: string;
value?: RangeValue<DateType>;
defaultValue?: RangeValue<DateType>;
defaultPickerValue?: [DateType, DateType];
placeholder?: [string, string];
disabled?: boolean | [boolean, boolean];
disabledTime?: (date: EventValue<DateType>, type: RangeType) => DisabledTimes;
ranges?: Record<
string,
Exclude<RangeValue<DateType>, null> | (() => Exclude<RangeValue<DateType>, null>)
>;
separator?: VueNode;
allowEmpty?: [boolean, boolean];
mode?: [PanelMode, PanelMode];
onChange?: (values: RangeValue<DateType>, formatString: [string, string]) => void;
onCalendarChange?: (
values: RangeValue<DateType>,
formatString: [string, string],
info: RangeInfo,
) => void;
onPanelChange?: (values: RangeValue<DateType>, modes: [PanelMode, PanelMode]) => void;
onFocus?: FocusEventHandler;
onBlur?: FocusEventHandler;
onMouseenter?: MouseEventHandler;
onMouseleave?: MouseEventHandler;
onOk?: (dates: RangeValue<DateType>) => void;
direction?: 'ltr' | 'rtl';
autocomplete?: string;
/** @private Internal control of active picker. Do not use since it's private usage */
activePickerIndex?: 0 | 1;
dateRender?: RangeDateRender<DateType>;
panelRender?: (originPanel: VueNode) => VueNode;
};
type OmitPickerProps<Props> = Omit<
Props,
| 'value'
| 'defaultValue'
| 'defaultPickerValue'
| 'placeholder'
| 'disabled'
| 'disabledTime'
| 'showToday'
| 'showTime'
| 'mode'
| 'onChange'
| 'onSelect'
| 'onPanelChange'
| 'pickerValue'
| 'onPickerValueChange'
| 'onOk'
| 'dateRender'
>;
type RangeShowTimeObject<DateType> = Omit<SharedTimeProps<DateType>, 'defaultValue'> & {
defaultValue?: DateType[];
};
export type RangePickerBaseProps<DateType> = {} & RangePickerSharedProps<DateType> &
OmitPickerProps<PickerBaseProps<DateType>>;
export type RangePickerDateProps<DateType> = {
showTime?: boolean | RangeShowTimeObject<DateType>;
} & RangePickerSharedProps<DateType> &
OmitPickerProps<PickerDateProps<DateType>>;
export type RangePickerTimeProps<DateType> = {
order?: boolean;
} & RangePickerSharedProps<DateType> &
OmitPickerProps<PickerTimeProps<DateType>>;
export type RangePickerProps<DateType> =
| RangePickerBaseProps<DateType>
| RangePickerDateProps<DateType>
| RangePickerTimeProps<DateType>;
// TMP type to fit for ts 3.9.2
type OmitType<DateType> = Omit<RangePickerBaseProps<DateType>, 'picker'> &
Omit<RangePickerDateProps<DateType>, 'picker'> &
Omit<RangePickerTimeProps<DateType>, 'picker'>;
type MergedRangePickerProps<DateType> = {
picker?: PickerMode;
} & OmitType<DateType>;
function RangerPicker<DateType>() {
return defineComponent<MergedRangePickerProps<DateType>>({
name: 'RangerPicker',
inheritAttrs: false,
props: [
'prefixCls',
'id',
'popupStyle',
'dropdownClassName',
'transitionName',
'dropdownAlign',
'getPopupContainer',
'generateConfig',
'locale',
'placeholder',
'autofocus',
'disabled',
'format',
'picker',
'showTime',
'use12Hours',
'separator',
'value',
'defaultValue',
'defaultPickerValue',
'open',
'defaultOpen',
'disabledDate',
'disabledTime',
'dateRender',
'panelRender',
'ranges',
'allowEmpty',
'allowClear',
'suffixIcon',
'clearIcon',
'pickerRef',
'inputReadOnly',
'mode',
'renderExtraFooter',
'onChange',
'onOpenChange',
'onPanelChange',
'onCalendarChange',
'onFocus',
'onBlur',
'onMouseenter',
'onMouseleave',
'onOk',
'onKeydown',
'components',
'order',
'direction',
'activePickerIndex',
'autocomplete',
] as any,
setup(props, { attrs, expose }) {
const needConfirmButton = computed(
() => (props.picker === 'date' && !!props.showTime) || props.picker === 'time',
);
// We record opened status here in case repeat open with picker
const openRecordsRef = ref<Record<number, boolean>>({});
const containerRef = ref<HTMLDivElement>(null);
const panelDivRef = ref<HTMLDivElement>(null);
const startInputDivRef = ref<HTMLDivElement>(null);
const endInputDivRef = ref<HTMLDivElement>(null);
const separatorRef = ref<HTMLDivElement>(null);
const startInputRef = ref<HTMLInputElement>(null);
const endInputRef = ref<HTMLInputElement>(null);
// ============================= Misc ==============================
const formatList = computed(() =>
toArray(
getDefaultFormat<DateType>(props.format, props.picker, props.showTime, props.use12Hours),
),
);
// Active picker
const [mergedActivePickerIndex, setMergedActivePickerIndex] = useMergedState<0 | 1>(0, {
value: toRef(props, 'activePickerIndex'),
});
// Operation ref
const operationRef = ref<ContextOperationRefProps>(null);
const mergedDisabled = computed<[boolean, boolean]>(() => {
const { disabled } = props;
if (Array.isArray(disabled)) {
return disabled;
}
return [disabled || false, disabled || false];
});
// ============================= Value =============================
const [mergedValue, setInnerValue] = useMergedState<RangeValue<DateType>>(null, {
value: toRef(props, 'value'),
defaultValue: props.defaultValue,
postState: values =>
props.picker === 'time' && !props.order
? values
: reorderValues(values, props.generateConfig),
});
// =========================== View Date ===========================
// Config view panel
const [startViewDate, endViewDate, setViewDate] = useRangeViewDates({
values: mergedValue,
picker: toRef(props, 'picker'),
defaultDates: props.defaultPickerValue,
generateConfig: toRef(props, 'generateConfig'),
});
// ========================= Select Values =========================
const [selectedValue, setSelectedValue] = useMergedState(mergedValue.value, {
postState: values => {
let postValues = values;
if (mergedDisabled.value[0] && mergedDisabled.value[1]) {
return postValues;
}
// Fill disabled unit
for (let i = 0; i < 2; i += 1) {
if (mergedDisabled[i] && !getValue(postValues, i) && !getValue(props.allowEmpty, i)) {
postValues = updateValues(postValues, props.generateConfig.getNow(), i);
}
}
return postValues;
},
});
// ============================= Modes =============================
const [mergedModes, setInnerModes] = useMergedState<[PanelMode, PanelMode]>(
[props.picker, props.picker],
{
value: toRef(props, 'mode'),
},
);
watch(
() => props.picker,
() => {
setInnerModes([props.picker, props.picker]);
},
);
const triggerModesChange = (modes: [PanelMode, PanelMode], values: RangeValue<DateType>) => {
setInnerModes(modes);
props.onPanelChange?.(values, modes);
};
// ========================= Disable Date ==========================
const [disabledStartDate, disabledEndDate] = useRangeDisabled(
{
picker: toRef(props, 'picker'),
selectedValue,
locale: toRef(props, 'locale'),
disabled: mergedDisabled,
disabledDate: toRef(props, 'disabledDate'),
generateConfig: toRef(props, 'generateConfig'),
},
openRecordsRef,
);
// ============================= Open ==============================
const [mergedOpen, triggerInnerOpen] = useMergedState(false, {
value: toRef(props, 'open'),
defaultValue: props.defaultOpen,
postState: postOpen =>
mergedDisabled.value[mergedActivePickerIndex.value] ? false : postOpen,
onChange: newOpen => {
props.onOpenChange?.(newOpen);
if (!newOpen && operationRef.value && operationRef.value.onClose) {
operationRef.value.onClose();
}
},
});
const startOpen = computed(() => mergedOpen.value && mergedActivePickerIndex.value === 0);
const endOpen = computed(() => mergedOpen.value && mergedActivePickerIndex.value === 1);
// ============================= Popup =============================
// Popup min width
const popupMinWidth = ref(0);
watch(mergedOpen, () => {
if (!mergedOpen.value && containerRef.value) {
popupMinWidth.value = containerRef.value.offsetWidth;
}
});
// ============================ Trigger ============================
const triggerRef = ref<any>();
function triggerOpen(newOpen: boolean, index: 0 | 1) {
if (newOpen) {
clearTimeout(triggerRef.value);
openRecordsRef.value[index] = true;
setMergedActivePickerIndex(index);
triggerInnerOpen(newOpen);
// Open to reset view date
if (!mergedOpen.value) {
setViewDate(null, index);
}
} else if (mergedActivePickerIndex.value === index) {
triggerInnerOpen(newOpen);
// Clean up async
// This makes ref not quick refresh in case user open another input with blur trigger
const openRecords = openRecordsRef.value;
triggerRef.value = setTimeout(() => {
if (openRecords === openRecordsRef.value) {
openRecordsRef.value = {};
}
});
}
}
function triggerOpenAndFocus(index: 0 | 1) {
triggerOpen(true, index);
// Use setTimeout to make sure panel DOM exists
window.setTimeout(() => {
const inputRef = [startInputRef, endInputRef][index];
if (inputRef.value) {
inputRef.value.focus();
}
}, 0);
}
function triggerChange(newValue: RangeValue<DateType>, sourceIndex: 0 | 1) {
let values = newValue;
let startValue = getValue(values, 0);
let endValue = getValue(values, 1);
const { generateConfig, locale, picker, order, onCalendarChange, allowEmpty, onChange } =
props;
// >>>>> Format start & end values
if (startValue && endValue && generateConfig.isAfter(startValue, endValue)) {
if (
// WeekPicker only compare week
(picker === 'week' &&
!isSameWeek(generateConfig, locale.locale, startValue, endValue)) ||
// QuotaPicker only compare week
(picker === 'quarter' && !isSameQuarter(generateConfig, startValue, endValue)) ||
// Other non-TimePicker compare date
(picker !== 'week' &&
picker !== 'quarter' &&
picker !== 'time' &&
!isSameDate(generateConfig, startValue, endValue))
) {
// Clean up end date when start date is after end date
if (sourceIndex === 0) {
values = [startValue, null];
endValue = null;
} else {
startValue = null;
values = [null, endValue];
}
// Clean up cache since invalidate
openRecordsRef.value = {
[sourceIndex]: true,
};
} else if (picker !== 'time' || order !== false) {
// Reorder when in same date
values = reorderValues(values, generateConfig);
}
}
setSelectedValue(values);
const startStr =
values && values[0]
? formatValue(values[0], { generateConfig, locale, format: formatList.value[0] })
: '';
const endStr =
values && values[1]
? formatValue(values[1], { generateConfig, locale, format: formatList.value[0] })
: '';
if (onCalendarChange) {
const info: RangeInfo = { range: sourceIndex === 0 ? 'start' : 'end' };
onCalendarChange(values, [startStr, endStr], info);
}
// >>>>> Trigger `onChange` event
const canStartValueTrigger = canValueTrigger(
startValue,
0,
mergedDisabled.value,
allowEmpty,
);
const canEndValueTrigger = canValueTrigger(endValue, 1, mergedDisabled.value, allowEmpty);
const canTrigger = values === null || (canStartValueTrigger && canEndValueTrigger);
if (canTrigger) {
// Trigger onChange only when value is validate
setInnerValue(values);
if (
onChange &&
(!isEqual(generateConfig, getValue(mergedValue.value, 0), startValue) ||
!isEqual(generateConfig, getValue(mergedValue.value, 1), endValue))
) {
onChange(values, [startStr, endStr]);
}
}
// >>>>> Open picker when
// Always open another picker if possible
let nextOpenIndex: 0 | 1 = null;
if (sourceIndex === 0 && !mergedDisabled.value[1]) {
nextOpenIndex = 1;
} else if (sourceIndex === 1 && !mergedDisabled.value[0]) {
nextOpenIndex = 0;
}
if (
nextOpenIndex !== null &&
nextOpenIndex !== mergedActivePickerIndex.value &&
(!openRecordsRef.value[nextOpenIndex] || !getValue(values, nextOpenIndex)) &&
getValue(values, sourceIndex)
) {
// Delay to focus to avoid input blur trigger expired selectedValues
triggerOpenAndFocus(nextOpenIndex);
} else {
triggerOpen(false, sourceIndex);
}
}
const forwardKeydown = (e: KeyboardEvent) => {
if (mergedOpen && operationRef.value && operationRef.value.onKeydown) {
// Let popup panel handle keyboard
return operationRef.value.onKeydown(e);
}
/* istanbul ignore next */
/* eslint-disable no-lone-blocks */
{
warning(
false,
'Picker not correct forward Keydown operation. Please help to fire issue about this.',
);
return false;
}
};
// ============================= Text ==============================
const sharedTextHooksProps = {
formatList,
generateConfig: toRef(props, 'generateConfig'),
locale: toRef(props, 'locale'),
};
const [startValueTexts, firstStartValueText] = useValueTexts<DateType>(
computed(() => getValue(selectedValue.value, 0)),
sharedTextHooksProps,
);
const [endValueTexts, firstEndValueText] = useValueTexts<DateType>(
computed(() => getValue(selectedValue.value, 1)),
sharedTextHooksProps,
);
const onTextChange = (newText: string, index: 0 | 1) => {
const inputDate = parseValue(newText, {
locale: props.locale,
formatList: formatList.value,
generateConfig: props.generateConfig,
});
const disabledFunc = index === 0 ? disabledStartDate : disabledEndDate;
if (inputDate && !disabledFunc(inputDate)) {
setSelectedValue(updateValues(selectedValue.value, inputDate, index));
setViewDate(inputDate, index);
}
};
const [startText, triggerStartTextChange, resetStartText] = useTextValueMapping({
valueTexts: startValueTexts,
onTextChange: newText => onTextChange(newText, 0),
});
const [endText, triggerEndTextChange, resetEndText] = useTextValueMapping({
valueTexts: endValueTexts,
onTextChange: newText => onTextChange(newText, 1),
});
const [rangeHoverValue, setRangeHoverValue] = useState<RangeValue<DateType>>(null);
// ========================== Hover Range ==========================
const [hoverRangedValue, setHoverRangedValue] = useState<RangeValue<DateType>>(null);
const [startHoverValue, onStartEnter, onStartLeave] = useHoverValue(
startText,
sharedTextHooksProps,
);
const [endHoverValue, onEndEnter, onEndLeave] = useHoverValue(endText, sharedTextHooksProps);
const onDateMouseenter = (date: DateType) => {
setHoverRangedValue(updateValues(selectedValue.value, date, mergedActivePickerIndex.value));
if (mergedActivePickerIndex.value === 0) {
onStartEnter(date);
} else {
onEndEnter(date);
}
};
const onDateMouseleave = () => {
setHoverRangedValue(updateValues(selectedValue.value, null, mergedActivePickerIndex.value));
if (mergedActivePickerIndex.value === 0) {
onStartLeave();
} else {
onEndLeave();
}
};
// ============================= Input =============================
const getSharedInputHookProps = (index: 0 | 1, resetText: () => void) => ({
forwardKeydown,
onBlur: (e: FocusEvent) => {
props.onBlur?.(e);
},
isClickOutside: (target: EventTarget | null) =>
!elementsContains(
[panelDivRef.value, startInputDivRef.value, endInputDivRef.value],
target as HTMLElement,
),
onFocus: (e: FocusEvent) => {
setMergedActivePickerIndex(index);
props.onFocus?.(e);
},
triggerOpen: (newOpen: boolean) => {
triggerOpen(newOpen, index);
},
onSubmit: () => {
triggerChange(selectedValue.value, index);
resetText();
},
onCancel: () => {
triggerOpen(false, index);
setSelectedValue(mergedValue.value);
resetText();
},
});
const [startInputProps, { focused: startFocused, typing: startTyping }] = usePickerInput({
...getSharedInputHookProps(0, resetStartText),
blurToCancel: needConfirmButton,
open: startOpen,
value: startText,
onKeydown: (e, preventDefault) => {
props.onKeydown?.(e, preventDefault);
},
});
const [endInputProps, { focused: endFocused, typing: endTyping }] = usePickerInput({
...getSharedInputHookProps(1, resetEndText),
blurToCancel: needConfirmButton,
open: endOpen,
value: endText,
onKeydown: (e, preventDefault) => {
props.onKeydown?.(e, preventDefault);
},
});
// ========================== Click Picker ==========================
const onPickerClick = (e: MouseEvent) => {
// When click inside the picker & outside the picker's input elements
// the panel should still be opened
if (
!mergedOpen.value &&
!startInputRef.value.contains(e.target as Node) &&
!endInputRef.value.contains(e.target as Node)
) {
if (!mergedDisabled.value[0]) {
triggerOpenAndFocus(0);
} else if (!mergedDisabled.value[1]) {
triggerOpenAndFocus(1);
}
}
};
const onPickerMousedown = (e: MouseEvent) => {
// shouldn't affect input elements if picker is active
if (
mergedOpen.value &&
(startFocused.value || endFocused.value) &&
!startInputRef.value.contains(e.target as Node) &&
!endInputRef.value.contains(e.target as Node)
) {
e.preventDefault();
}
};
// ============================= Sync ==============================
// Close should sync back with text value
const startStr = computed(() =>
mergedValue.value?.[0]
? formatValue(mergedValue.value[0], {
locale: props.locale,
format: 'YYYYMMDDHHmmss',
generateConfig: props.generateConfig,
})
: '',
);
const endStr = computed(() =>
mergedValue.value?.[1]
? formatValue(mergedValue.value[1], {
locale: props.locale,
format: 'YYYYMMDDHHmmss',
generateConfig: props.generateConfig,
})
: '',
);
watch([mergedOpen, startValueTexts, endValueTexts], () => {
if (!mergedOpen.value) {
setSelectedValue(mergedValue.value);
if (!startValueTexts.value.length || startValueTexts.value[0] === '') {
triggerStartTextChange('');
} else if (firstStartValueText.value !== startText.value) {
resetStartText();
}
if (!endValueTexts.value.length || endValueTexts.value[0] === '') {
triggerEndTextChange('');
} else if (firstEndValueText.value !== endText.value) {
resetEndText();
}
}
});
// Sync innerValue with control mode
watch([startStr, endStr], () => {
setSelectedValue(mergedValue.value);
});
// ============================ Warning ============================
if (process.env.NODE_ENV !== 'production') {
watchEffect(() => {
const { value, disabled } = props;
if (
value &&
Array.isArray(disabled) &&
((getValue(disabled, 0) && !getValue(value, 0)) ||
(getValue(disabled, 1) && !getValue(value, 1)))
) {
warning(
false,
'`disabled` should not set with empty `value`. You should set `allowEmpty` or `value` instead.',
);
}
});
}
expose({
focus: () => {
if (startInputRef.value) {
startInputRef.value.focus();
}
},
blur: () => {
if (startInputRef.value) {
startInputRef.value.blur();
}
if (endInputRef.value) {
endInputRef.value.blur();
}
},
});
// ============================ Ranges =============================
const rangeList = computed(() =>
Object.keys(props.ranges || {}).map(label => {
const range = props.ranges![label];
const newValues = typeof range === 'function' ? range() : range;
return {
label,
onClick: () => {
triggerChange(newValues, null);
triggerOpen(false, mergedActivePickerIndex.value);
},
onMouseenter: () => {
setRangeHoverValue(newValues);
},
onMouseleave: () => {
setRangeHoverValue(null);
},
};
}),
);
// ============================= Panel =============================
const panelHoverRangedValue = computed(() => {
if (
mergedOpen.value &&
hoverRangedValue.value &&
hoverRangedValue.value[0] &&
hoverRangedValue.value[1] &&
props.generateConfig.isAfter(hoverRangedValue.value[1], hoverRangedValue.value[0])
) {
return hoverRangedValue.value;
} else {
return null;
}
});
function renderPanel(
panelPosition: 'left' | 'right' | false = false,
panelProps: Partial<PickerPanelProps<DateType>> = {},
) {
const { generateConfig, showTime, dateRender, direction, disabledTime, prefixCls, locale } =
props;
let panelShowTime: boolean | SharedTimeProps<DateType> | undefined =
showTime as SharedTimeProps<DateType>;
if (showTime && typeof showTime === 'object' && showTime.defaultValue) {
const timeDefaultValues: DateType[] = showTime.defaultValue!;
panelShowTime = {
...showTime,
defaultValue: getValue(timeDefaultValues, mergedActivePickerIndex.value) || undefined,
};
}
let panelDateRender: DateRender<DateType> | null = null;
if (dateRender) {
panelDateRender = ({ current: date, today }) =>
dateRender({
current: date,
today,
info: {
range: mergedActivePickerIndex.value ? 'end' : 'start',
},
});
}
return (
<RangeContextProvider
value={{
inRange: true,
panelPosition,
rangedValue: rangeHoverValue.value || selectedValue.value,
hoverRangedValue: panelHoverRangedValue.value,
}}
>
<PickerPanel<DateType>
{...(props as any)}
{...panelProps}
dateRender={panelDateRender}
showTime={panelShowTime}
mode={mergedModes.value[mergedActivePickerIndex.value]}
generateConfig={generateConfig}
style={undefined}
direction={direction}
disabledDate={
mergedActivePickerIndex.value === 0 ? disabledStartDate : disabledEndDate
}
disabledTime={date => {
if (disabledTime) {
return disabledTime(date, mergedActivePickerIndex.value === 0 ? 'start' : 'end');
}
return false;
}}
class={classNames({
[`${prefixCls}-panel-focused`]:
mergedActivePickerIndex.value === 0 ? !startTyping.value : !endTyping.value,
})}
value={getValue(selectedValue.value, mergedActivePickerIndex.value)}
locale={locale}
tabIndex={-1}
onPanelChange={(date, newMode) => {
// clear hover value when panel change
if (mergedActivePickerIndex.value === 0) {
onStartLeave(true);
}
if (mergedActivePickerIndex.value === 1) {
onEndLeave(true);
}
triggerModesChange(
updateValues(mergedModes.value, newMode, mergedActivePickerIndex.value),
updateValues(selectedValue.value, date, mergedActivePickerIndex.value),
);
let viewDate = date;
if (
panelPosition === 'right' &&
mergedModes.value[mergedActivePickerIndex.value] === newMode
) {
viewDate = getClosingViewDate(viewDate, newMode as any, generateConfig, -1);
}
setViewDate(viewDate, mergedActivePickerIndex.value);
}}
onOk={null}
onSelect={undefined}
onChange={undefined}
defaultValue={
mergedActivePickerIndex.value === 0
? getValue(selectedValue.value, 1)
: getValue(selectedValue.value, 0)
}
defaultPickerValue={undefined}
/>
</RangeContextProvider>
);
}
const onContextSelect = (date: DateType, type: 'key' | 'mouse' | 'submit') => {
const values = updateValues(selectedValue.value, date, mergedActivePickerIndex.value);
if (type === 'submit' || (type !== 'key' && !needConfirmButton.value)) {
// triggerChange will also update selected values
triggerChange(values, mergedActivePickerIndex.value);
// clear hover value style
if (mergedActivePickerIndex.value === 0) {
onStartLeave();
} else {
onEndLeave();
}
} else {
setSelectedValue(values);
}
};
useProvidePanel({
operationRef,
hideHeader: computed(() => props.picker === 'time'),
onDateMouseenter,
onDateMouseleave,
hideRanges: computed(() => true),
onSelect: onContextSelect,
open: mergedOpen,
});
return () => {
const {
prefixCls = 'rc-picker',
id,
popupStyle,
dropdownClassName,
transitionName,
dropdownAlign,
getPopupContainer,
generateConfig,
locale,
placeholder,
autofocus,
picker = 'date',
showTime,
separator = '~',
disabledDate,
panelRender,
allowClear,
suffixIcon,
clearIcon,
inputReadOnly,
renderExtraFooter,
onMouseenter,
onMouseleave,
onOk,
components,
direction,
autocomplete = 'off',
} = props;
let arrowLeft = 0;
let panelLeft = 0;
if (
mergedActivePickerIndex.value &&
startInputDivRef.value &&
separatorRef.value &&
panelDivRef.value
) {
// Arrow offset
arrowLeft = startInputDivRef.value.offsetWidth + separatorRef.value.offsetWidth;
if (panelDivRef.value.offsetWidth && arrowLeft > panelDivRef.value.offsetWidth) {
panelLeft = arrowLeft;
}
}
const arrowPositionStyle = direction === 'rtl' ? { right: arrowLeft } : { left: arrowLeft };
function renderPanels() {
let panels: VueNode;
const extraNode = getExtraFooter(
prefixCls,
mergedModes.value[mergedActivePickerIndex.value],
renderExtraFooter,
);
const rangesNode = getRanges({
prefixCls,
components,
needConfirmButton: needConfirmButton.value,
okDisabled:
!getValue(selectedValue.value, mergedActivePickerIndex.value) ||
(disabledDate && disabledDate(selectedValue.value[mergedActivePickerIndex.value])),
locale,
rangeList: rangeList.value,
onOk: () => {
if (getValue(selectedValue.value, mergedActivePickerIndex.value)) {
// triggerChangeOld(selectedValue.value);
triggerChange(selectedValue.value, mergedActivePickerIndex.value);
if (onOk) {
onOk(selectedValue.value);
}
}
},
});
if (picker !== 'time' && !showTime) {
const viewDate =
mergedActivePickerIndex.value === 0 ? startViewDate.value : endViewDate.value;
const nextViewDate = getClosingViewDate(viewDate, picker, generateConfig);
const currentMode = mergedModes.value[mergedActivePickerIndex.value];
const showDoublePanel = currentMode === picker;
const leftPanel = renderPanel(showDoublePanel ? 'left' : false, {
pickerValue: viewDate,
onPickerValueChange: newViewDate => {
setViewDate(newViewDate, mergedActivePickerIndex.value);
},
});
const rightPanel = renderPanel('right', {
pickerValue: nextViewDate,
onPickerValueChange: newViewDate => {
setViewDate(
getClosingViewDate(newViewDate, picker, generateConfig, -1),
mergedActivePickerIndex.value,
);
},
});
if (direction === 'rtl') {
panels = (
<>
{rightPanel}
{showDoublePanel && leftPanel}
</>
);
} else {
panels = (
<>
{leftPanel}
{showDoublePanel && rightPanel}
</>
);
}
} else {
panels = renderPanel();
}
let mergedNodes: VueNode = (
<>
<div class={`${prefixCls}-panels`}>{panels}</div>
{(extraNode || rangesNode) && (
<div class={`${prefixCls}-footer`}>
{extraNode}
{rangesNode}
</div>
)}
</>
);
if (panelRender) {
mergedNodes = panelRender(mergedNodes);
}
return (
<div
class={`${prefixCls}-panel-container`}
style={{ marginLeft: panelLeft }}
ref={panelDivRef}
onMousedown={e => {
e.preventDefault();
}}
>
{mergedNodes}
</div>
);
}
const rangePanel = (
<div
class={classNames(`${prefixCls}-range-wrapper`, `${prefixCls}-${picker}-range-wrapper`)}
style={{ minWidth: `${popupMinWidth.value}px` }}
>
<div class={`${prefixCls}-range-arrow`} style={arrowPositionStyle} />
{renderPanels()}
</div>
);
// ============================= Icons =============================
let suffixNode: VueNode;
if (suffixIcon) {
suffixNode = <span class={`${prefixCls}-suffix`}>{suffixIcon}</span>;
}
let clearNode: VueNode;
if (
allowClear &&
((getValue(mergedValue.value, 0) && !mergedDisabled.value[0]) ||
(getValue(mergedValue.value, 1) && !mergedDisabled.value[1]))
) {
clearNode = (
<span
onMousedown={e => {
e.preventDefault();
e.stopPropagation();
}}
onMouseup={e => {
e.preventDefault();
e.stopPropagation();
let values = mergedValue.value;
if (!mergedDisabled.value[0]) {
values = updateValues(values, null, 0);
}
if (!mergedDisabled.value[1]) {
values = updateValues(values, null, 1);
}
triggerChange(values, null);
triggerOpen(false, mergedActivePickerIndex.value);
}}
class={`${prefixCls}-clear`}
>
{clearIcon || <span class={`${prefixCls}-clear-btn`} />}
</span>
);
}
const inputSharedProps = {
size: getInputSize(picker, formatList.value[0], generateConfig),
};
let activeBarLeft = 0;
let activeBarWidth = 0;
if (startInputDivRef.value && endInputDivRef.value && separatorRef.value) {
if (mergedActivePickerIndex.value === 0) {
activeBarWidth = startInputDivRef.value.offsetWidth;
} else {
activeBarLeft = arrowLeft;
activeBarWidth = endInputDivRef.value.offsetWidth;
}
}
const activeBarPositionStyle =
direction === 'rtl' ? { right: `${activeBarLeft}px` } : { left: `${activeBarLeft}px` };
// ============================ Return =============================
return (
<PickerTrigger
visible={mergedOpen.value}
popupStyle={popupStyle}
prefixCls={prefixCls}
dropdownClassName={dropdownClassName}
dropdownAlign={dropdownAlign}
getPopupContainer={getPopupContainer}
transitionName={transitionName}
range
direction={direction}
v-slots={{
popupElement: () => rangePanel,
}}
>
<div
ref={containerRef}
class={classNames(prefixCls, `${prefixCls}-range`, attrs.class, {
[`${prefixCls}-disabled`]: mergedDisabled.value[0] && mergedDisabled.value[1],
[`${prefixCls}-focused`]:
mergedActivePickerIndex.value === 0 ? startFocused.value : endFocused.value,
[`${prefixCls}-rtl`]: direction === 'rtl',
})}
style={attrs.style}
onClick={onPickerClick}
onMouseenter={onMouseenter}
onMouseleave={onMouseleave}
onMousedown={onPickerMousedown}
{...getDataOrAriaProps(props)}
>
<div
class={classNames(`${prefixCls}-input`, {
[`${prefixCls}-input-active`]: mergedActivePickerIndex.value === 0,
[`${prefixCls}-input-placeholder`]: !!startHoverValue.value,
})}
ref={startInputDivRef}
>
<input
id={id}
disabled={mergedDisabled.value[0]}
readonly={
inputReadOnly || typeof formatList.value[0] === 'function' || !startTyping.value
}
value={startHoverValue.value || startText.value}
onInput={(e: ChangeEvent) => {
triggerStartTextChange(e.target.value);
}}
autofocus={autofocus}
placeholder={getValue(placeholder, 0) || ''}
ref={startInputRef}
{...startInputProps.value}
{...inputSharedProps}
autocomplete={autocomplete}
/>
</div>
<div class={`${prefixCls}-range-separator`} ref={separatorRef}>
{separator}
</div>
<div
class={classNames(`${prefixCls}-input`, {
[`${prefixCls}-input-active`]: mergedActivePickerIndex.value === 1,
[`${prefixCls}-input-placeholder`]: !!endHoverValue.value,
})}
ref={endInputDivRef}
>
<input
disabled={mergedDisabled.value[1]}
readonly={
inputReadOnly || typeof formatList.value[0] === 'function' || !endTyping.value
}
value={endHoverValue.value || endText.value}
onInput={(e: ChangeEvent) => {
triggerEndTextChange(e.target.value);
}}
placeholder={getValue(placeholder, 1) || ''}
ref={endInputRef}
{...endInputProps.value}
{...inputSharedProps}
autocomplete={autocomplete}
/>
</div>
<div
class={`${prefixCls}-active-bar`}
style={{
...activeBarPositionStyle,
width: `${activeBarWidth}px`,
position: 'absolute',
}}
/>
{suffixNode}
{clearNode}
</div>
</PickerTrigger>
);
};
},
});
}
const InterRangerPicker = RangerPicker<any>();
export default InterRangerPicker;
|
YaroShkvorets/ant-design-vue
|
components/tabs/src/TabPanelList/index.tsx
|
import { useInjectTabs } from '../TabContext';
import type { TabPosition, AnimatedConfig } from '../interface';
import type { Key } from '../../../_util/type';
import type { PropType } from 'vue';
import { defineComponent } from 'vue';
import { cloneElement } from '../../../_util/vnode';
export interface TabPanelListProps {
activeKey: Key;
id: string;
rtl: boolean;
animated?: AnimatedConfig;
tabPosition?: TabPosition;
destroyInactiveTabPane?: boolean;
}
export default defineComponent({
name: 'TabPanelList',
inheritAttrs: false,
props: {
activeKey: { type: [String, Number] as PropType<Key> },
id: { type: String },
rtl: { type: Boolean },
animated: { type: Object as PropType<AnimatedConfig>, default: undefined as AnimatedConfig },
tabPosition: { type: String as PropType<TabPosition> },
destroyInactiveTabPane: { type: Boolean },
},
setup(props) {
const { tabs, prefixCls } = useInjectTabs();
return () => {
const { id, activeKey, animated, tabPosition, rtl, destroyInactiveTabPane } = props;
const tabPaneAnimated = animated.tabPane;
const pre = prefixCls.value;
const activeIndex = tabs.value.findIndex(tab => tab.key === activeKey);
return (
<div class={`${pre}-content-holder`}>
<div
class={[
`${pre}-content`,
`${pre}-content-${tabPosition}`,
{
[`${pre}-content-animated`]: tabPaneAnimated,
},
]}
style={
activeIndex && tabPaneAnimated
? { [rtl ? 'marginRight' : 'marginLeft']: `-${activeIndex}00%` }
: null
}
>
{tabs.value.map(tab => {
return cloneElement(tab.node, {
key: tab.key,
prefixCls: pre,
tabKey: tab.key,
id,
animated: tabPaneAnimated,
active: tab.key === activeKey,
destroyInactiveTabPane,
});
})}
</div>
</div>
);
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/tabs/src/hooks/useTouchMove.ts
|
<gh_stars>1000+
import type { Ref } from 'vue';
import { ref, onBeforeUnmount, onMounted } from 'vue';
import useState from '../../../_util/hooks/useState';
type TouchEventHandler = (e: TouchEvent) => void;
type WheelEventHandler = (e: WheelEvent) => void;
const MIN_SWIPE_DISTANCE = 0.1;
const STOP_SWIPE_DISTANCE = 0.01;
const REFRESH_INTERVAL = 20;
const SPEED_OFF_MULTIPLE = 0.995 ** REFRESH_INTERVAL;
// ================================= Hook =================================
export default function useTouchMove(
domRef: Ref<HTMLDivElement>,
onOffset: (offsetX: number, offsetY: number) => boolean,
) {
const [touchPosition, setTouchPosition] = useState<{ x: number; y: number }>();
const [lastTimestamp, setLastTimestamp] = useState<number>(0);
const [lastTimeDiff, setLastTimeDiff] = useState<number>(0);
const [lastOffset, setLastOffset] = useState<{ x: number; y: number }>();
const motionRef = ref<number>();
// ========================= Events =========================
// >>> Touch events
function onTouchStart(e: TouchEvent) {
const { screenX, screenY } = e.touches[0];
setTouchPosition({ x: screenX, y: screenY });
window.clearInterval(motionRef.value);
}
function onTouchMove(e: TouchEvent) {
if (!touchPosition.value) return;
e.preventDefault();
const { screenX, screenY } = e.touches[0];
setTouchPosition({ x: screenX, y: screenY });
const offsetX = screenX - touchPosition.value.x;
const offsetY = screenY - touchPosition.value.y;
onOffset(offsetX, offsetY);
const now = Date.now();
setLastTimestamp(now);
setLastTimeDiff(now - lastTimestamp.value);
setLastOffset({ x: offsetX, y: offsetY });
}
function onTouchEnd() {
if (!touchPosition.value) return;
setTouchPosition(null);
setLastOffset(null);
// Swipe if needed
if (lastOffset.value) {
const distanceX = lastOffset.value.x / lastTimeDiff.value;
const distanceY = lastOffset.value.y / lastTimeDiff.value;
const absX = Math.abs(distanceX);
const absY = Math.abs(distanceY);
// Skip swipe if low distance
if (Math.max(absX, absY) < MIN_SWIPE_DISTANCE) return;
let currentX = distanceX;
let currentY = distanceY;
motionRef.value = window.setInterval(() => {
if (Math.abs(currentX) < STOP_SWIPE_DISTANCE && Math.abs(currentY) < STOP_SWIPE_DISTANCE) {
window.clearInterval(motionRef.value);
return;
}
currentX *= SPEED_OFF_MULTIPLE;
currentY *= SPEED_OFF_MULTIPLE;
onOffset(currentX * REFRESH_INTERVAL, currentY * REFRESH_INTERVAL);
}, REFRESH_INTERVAL);
}
}
// >>> Wheel event
const lastWheelDirectionRef = ref<'x' | 'y'>();
function onWheel(e: WheelEvent) {
const { deltaX, deltaY } = e;
// Convert both to x & y since wheel only happened on PC
let mixed = 0;
const absX = Math.abs(deltaX);
const absY = Math.abs(deltaY);
if (absX === absY) {
mixed = lastWheelDirectionRef.value === 'x' ? deltaX : deltaY;
} else if (absX > absY) {
mixed = deltaX;
lastWheelDirectionRef.value = 'x';
} else {
mixed = deltaY;
lastWheelDirectionRef.value = 'y';
}
if (onOffset(-mixed, -mixed)) {
e.preventDefault();
}
}
// ========================= Effect =========================
const touchEventsRef = ref<{
onTouchStart: TouchEventHandler;
onTouchMove: TouchEventHandler;
onTouchEnd: TouchEventHandler;
onWheel: WheelEventHandler;
}>({
onTouchStart,
onTouchMove,
onTouchEnd,
onWheel,
});
function onProxyTouchStart(e: TouchEvent) {
touchEventsRef.value.onTouchStart(e);
}
function onProxyTouchMove(e: TouchEvent) {
touchEventsRef.value.onTouchMove(e);
}
function onProxyTouchEnd(e: TouchEvent) {
touchEventsRef.value.onTouchEnd(e);
}
function onProxyWheel(e: WheelEvent) {
touchEventsRef.value.onWheel(e);
}
onMounted(() => {
document.addEventListener('touchmove', onProxyTouchMove, { passive: false });
document.addEventListener('touchend', onProxyTouchEnd, { passive: false });
// No need to clean up since element removed
domRef.value?.addEventListener('touchstart', onProxyTouchStart, { passive: false });
domRef.value?.addEventListener('wheel', onProxyWheel, { passive: false });
});
onBeforeUnmount(() => {
document.removeEventListener('touchmove', onProxyTouchMove);
document.removeEventListener('touchend', onProxyTouchEnd);
});
}
|
YaroShkvorets/ant-design-vue
|
components/vc-tree-select/TreeSelect.tsx
|
<filename>components/vc-tree-select/TreeSelect.tsx
import generate from './generate';
import OptionList from './OptionList';
const TreeSelect = generate({ prefixCls: 'vc-tree-select', optionList: OptionList as any });
export default TreeSelect;
|
YaroShkvorets/ant-design-vue
|
antd-tools/generator-types/src/index.ts
|
import glob from 'fast-glob';
import { join, dirname } from 'path';
import { mdParser } from './parser';
import { formatter } from './formatter';
import { genWebTypes } from './web-types';
import { readFileSync, outputFileSync } from 'fs-extra';
import type { Options, VueTag } from './type';
import { normalizePath, getComponentName } from './utils';
import { genVeturTags, genVeturAttributes } from './vetur';
async function readMarkdown(options: Options) {
// const mds = await glob(normalizePath(`${options.path}/**/*.md`))
const mds = await glob(normalizePath(`${options.path}/**/*.md`));
return mds
.filter(md => options.test.test(md))
.map(path => {
const docPath = dirname(path);
const componentName = docPath.substring(docPath.lastIndexOf('/') + 1);
return {
componentName: getComponentName(componentName || ''),
md: readFileSync(path, 'utf-8'),
};
});
}
export async function parseAndWrite(options: Options) {
if (!options.outputDir) {
throw new Error('outputDir can not be empty.');
}
const docs = await readMarkdown(options);
const datas = docs
.map(doc => formatter(mdParser(doc.md), doc.componentName, options.tagPrefix))
.filter(item => item) as VueTag[][];
const tags: VueTag[] = [];
datas.forEach(arr => {
tags.push(...arr);
});
const webTypes = genWebTypes(tags, options);
const veturTags = genVeturTags(tags);
const veturAttributes = genVeturAttributes(tags);
outputFileSync(join(options.outputDir, 'tags.json'), JSON.stringify(veturTags, null, 2));
outputFileSync(
join(options.outputDir, 'attributes.json'),
JSON.stringify(veturAttributes, null, 2),
);
outputFileSync(join(options.outputDir, 'web-types.json'), JSON.stringify(webTypes, null, 2));
}
export default { parseAndWrite };
|
YaroShkvorets/ant-design-vue
|
components/form/FormItemContext.ts
|
import type { ComputedRef, InjectionKey, ConcreteComponent } from 'vue';
import {
watch,
computed,
inject,
provide,
ref,
onBeforeUnmount,
getCurrentInstance,
defineComponent,
} from 'vue';
import devWarning from '../vc-util/devWarning';
export type FormItemContext = {
id: ComputedRef<string>;
onFieldBlur: () => void;
onFieldChange: () => void;
clearValidate: () => void;
};
type InternalFormItemContext = {
addFormItemField: (key: Symbol, type: ConcreteComponent) => void;
removeFormItemField: (key: Symbol) => void;
};
const ContextKey: InjectionKey<FormItemContext> = Symbol('ContextProps');
const InternalContextKey: InjectionKey<InternalFormItemContext> = Symbol('InternalContextProps');
export const useProvideFormItemContext = (
props: FormItemContext,
useValidation: ComputedRef<boolean> = computed(() => true),
) => {
const formItemFields = ref(new Map<Symbol, ConcreteComponent>());
const addFormItemField = (key: Symbol, type: ConcreteComponent) => {
formItemFields.value.set(key, type);
formItemFields.value = new Map(formItemFields.value);
};
const removeFormItemField = (key: Symbol) => {
formItemFields.value.delete(key);
formItemFields.value = new Map(formItemFields.value);
};
const instance = getCurrentInstance();
watch([useValidation, formItemFields], () => {
if (process.env.NODE_ENV !== 'production') {
if (useValidation.value && formItemFields.value.size > 1) {
devWarning(
false,
'Form.Item',
`FormItem can only collect one field item, you haved set ${[
...formItemFields.value.values(),
]
.map(v => `\`${v.name}\``)
.join(', ')} ${formItemFields.value.size} field items.
You can set not need to be collected fields into \`a-form-item-rest\``,
);
let cur = instance;
while (cur.parent) {
console.warn('at', cur.type);
cur = cur.parent;
}
}
}
});
provide(ContextKey, props);
provide(InternalContextKey, {
addFormItemField,
removeFormItemField,
});
};
const defaultContext: FormItemContext = {
id: computed(() => undefined),
onFieldBlur: () => {},
onFieldChange: () => {},
clearValidate: () => {},
};
const defaultInternalContext: InternalFormItemContext = {
addFormItemField: () => {},
removeFormItemField: () => {},
};
export const useInjectFormItemContext = () => {
const internalContext = inject(InternalContextKey, defaultInternalContext);
const formItemFieldKey = Symbol('FormItemFieldKey');
const instance = getCurrentInstance();
internalContext.addFormItemField(formItemFieldKey, instance.type);
onBeforeUnmount(() => {
internalContext.removeFormItemField(formItemFieldKey);
});
// We should prevent the passing of context for children
provide(InternalContextKey, defaultInternalContext);
provide(ContextKey, defaultContext);
return inject(ContextKey, defaultContext);
};
export default defineComponent({
name: 'AFormItemRest',
setup(_, { slots }) {
provide(InternalContextKey, defaultInternalContext);
provide(ContextKey, defaultContext);
return () => {
return slots.default?.();
};
},
});
|
YaroShkvorets/ant-design-vue
|
components/vc-picker/panels/Header.tsx
|
import type { CSSProperties } from 'vue';
import type { VueNode } from '../../_util/type';
import useMergeProps from '../hooks/useMergeProps';
import { useInjectPanel } from '../PanelContext';
const HIDDEN_STYLE: CSSProperties = {
visibility: 'hidden',
};
export type HeaderProps = {
prefixCls: string;
// Icons
prevIcon?: VueNode;
nextIcon?: VueNode;
superPrevIcon?: VueNode;
superNextIcon?: VueNode;
/** Last one step */
onPrev?: () => void;
/** Next one step */
onNext?: () => void;
/** Last multiple steps */
onSuperPrev?: () => void;
/** Next multiple steps */
onSuperNext?: () => void;
children?: VueNode;
};
function Header(_props: HeaderProps, { slots }) {
const props = useMergeProps(_props);
const {
prefixCls,
prevIcon = '\u2039',
nextIcon = '\u203A',
superPrevIcon = '\u00AB',
superNextIcon = '\u00BB',
onSuperPrev,
onSuperNext,
onPrev,
onNext,
} = props;
const { hideNextBtn, hidePrevBtn } = useInjectPanel();
return (
<div class={prefixCls}>
{onSuperPrev && (
<button
type="button"
onClick={onSuperPrev}
tabindex={-1}
class={`${prefixCls}-super-prev-btn`}
style={hidePrevBtn.value ? HIDDEN_STYLE : {}}
>
{superPrevIcon}
</button>
)}
{onPrev && (
<button
type="button"
onClick={onPrev}
tabindex={-1}
class={`${prefixCls}-prev-btn`}
style={hidePrevBtn.value ? HIDDEN_STYLE : {}}
>
{prevIcon}
</button>
)}
<div class={`${prefixCls}-view`}>{slots.default?.()}</div>
{onNext && (
<button
type="button"
onClick={onNext}
tabindex={-1}
class={`${prefixCls}-next-btn`}
style={hideNextBtn.value ? HIDDEN_STYLE : {}}
>
{nextIcon}
</button>
)}
{onSuperNext && (
<button
type="button"
onClick={onSuperNext}
tabindex={-1}
class={`${prefixCls}-super-next-btn`}
style={hideNextBtn.value ? HIDDEN_STYLE : {}}
>
{superNextIcon}
</button>
)}
</div>
);
}
Header.displayName = 'Header';
Header.inheritAttrs = false;
export default Header;
|
YaroShkvorets/ant-design-vue
|
components/vc-util/Dom/contains.ts
|
<filename>components/vc-util/Dom/contains.ts
export default function contains(root: HTMLElement | null | undefined, n?: HTMLElement) {
if (!root) {
return false;
}
return root.contains(n);
}
|
YaroShkvorets/ant-design-vue
|
components/vc-tree-select/Context.tsx
|
<reponame>YaroShkvorets/ant-design-vue
import type {
FlattenDataNode,
InternalDataEntity,
Key,
LegacyDataNode,
RawValueType,
} from './interface';
import type { SkipType } from './hooks/useKeyValueMapping';
import type { ComputedRef, InjectionKey, PropType } from 'vue';
import { computed, defineComponent, inject, provide } from 'vue';
interface ContextProps {
checkable: boolean;
customCheckable: () => any;
checkedKeys: Key[];
halfCheckedKeys: Key[];
treeExpandedKeys: Key[];
treeDefaultExpandedKeys: Key[];
onTreeExpand: (keys: Key[]) => void;
treeDefaultExpandAll: boolean;
treeIcon: any;
showTreeIcon: boolean;
switcherIcon: any;
treeLine: boolean;
treeNodeFilterProp: string;
treeLoadedKeys: Key[];
treeMotion: any;
loadData: (treeNode: LegacyDataNode) => Promise<unknown>;
onTreeLoad: (loadedKeys: Key[]) => void;
// Cache help content. These can be generated by parent component.
// Let's reuse this.
getEntityByKey: (key: Key, skipType?: SkipType, ignoreDisabledCheck?: boolean) => FlattenDataNode;
getEntityByValue: (
value: RawValueType,
skipType?: SkipType,
ignoreDisabledCheck?: boolean,
) => FlattenDataNode;
slots: {
title?: (data: InternalDataEntity) => any;
titleRender?: (data: InternalDataEntity) => any;
[key: string]: (d: any) => any | undefined;
};
}
const SelectContextKey: InjectionKey<ComputedRef<ContextProps>> = Symbol('SelectContextKey');
export const SelectContext = defineComponent({
name: 'SelectContext',
props: {
value: { type: Object as PropType<ContextProps> },
},
setup(props, { slots }) {
provide(
SelectContextKey,
computed(() => props.value),
);
return () => slots.default?.();
},
});
export const useInjectTreeSelectContext = () => {
return inject(
SelectContextKey,
computed(() => ({} as ContextProps)),
);
};
|
YaroShkvorets/ant-design-vue
|
components/locale/nl_NL.tsx
|
<filename>components/locale/nl_NL.tsx
/* eslint-disable no-template-curly-in-string */
import Pagination from '../vc-pagination/locale/nl_NL';
import DatePicker from '../date-picker/locale/nl_NL';
import TimePicker from '../time-picker/locale/nl_NL';
import Calendar from '../calendar/locale/nl_NL';
import type { Locale } from '../locale-provider';
const typeTemplate = '${label} is geen geldige ${type}';
const localeValues: Locale = {
locale: 'nl',
Pagination,
DatePicker,
TimePicker,
Calendar,
global: {
placeholder: 'Maak een selectie',
},
Table: {
cancelSort: 'Klik om sortering te annuleren',
collapse: 'Rij inklappen',
emptyText: 'Geen data',
expand: 'Rij uitklappen',
filterConfirm: 'OK',
filterEmptyText: 'Geen filters',
filterReset: 'Reset',
filterTitle: 'Filteren',
selectAll: 'Selecteer huidige pagina',
selectInvert: 'Keer volgorde om',
selectNone: 'Maak selectie leeg',
selectionAll: 'Selecteer alle data',
sortTitle: 'Sorteren',
triggerAsc: 'Klik om oplopend te sorteren',
triggerDesc: 'Klik om aflopend te sorteren',
},
Modal: {
okText: 'OK',
cancelText: 'Annuleer',
justOkText: 'OK',
},
Popconfirm: {
okText: 'OK',
cancelText: 'Annuleer',
},
Transfer: {
itemUnit: 'item',
itemsUnit: 'items',
remove: 'Verwijder',
removeAll: 'Verwijder alles',
removeCurrent: 'Verwijder huidige pagina',
searchPlaceholder: 'Zoek hier',
selectAll: 'Selecteer alles',
selectCurrent: 'Selecteer huidige pagina',
selectInvert: 'Huidige pagina omkeren',
titles: ['', ''],
},
Upload: {
downloadFile: 'Bestand downloaden',
previewFile: 'Preview file',
removeFile: 'Verwijder bestand',
uploadError: 'Fout tijdens uploaden',
uploading: 'Uploaden...',
},
Empty: {
description: 'Geen gegevens',
},
Icon: {
icon: 'icoon',
},
Text: {
edit: 'Bewerken',
copy: 'kopiëren',
copied: 'Gekopieerd',
expand: 'Uitklappen',
},
PageHeader: {
back: 'Terug',
},
Form: {
optional: '(optioneel)',
defaultValidateMessages: {
default: 'Validatiefout voor ${label}',
required: 'Gelieve ${label} in te vullen',
enum: '${label} moet één van [${enum}] zijn',
whitespace: '${label} mag geen blanco teken zijn',
date: {
format: '${label} heeft een ongeldig formaat',
parse: '${label} kan niet naar een datum omgezet worden',
invalid: '${label} is een ongeldige datum',
},
types: {
string: typeTemplate,
method: typeTemplate,
array: typeTemplate,
object: typeTemplate,
number: typeTemplate,
date: typeTemplate,
boolean: typeTemplate,
integer: typeTemplate,
float: typeTemplate,
regexp: typeTemplate,
email: typeTemplate,
url: typeTemplate,
hex: typeTemplate,
},
string: {
len: '${label} moet ${len} karakters lang zijn',
min: '${label} moet minimaal ${min} karakters lang zijn',
max: '${label} mag maximaal ${max} karakters lang zijn',
range: '${label} moet tussen ${min}-${max} karakters lang zijn',
},
number: {
len: '${label} moet gelijk zijn aan ${len}',
min: '${label} moet minimaal ${min} zijn',
max: '${label} mag maximaal ${max} zijn',
range: '${label} moet tussen ${min}-${max} liggen',
},
array: {
len: 'Moeten ${len} ${label} zijn',
min: 'Minimaal ${min} ${label}',
max: 'maximaal ${max} ${label}',
range: 'Het aantal ${label} moet tussen ${min}-${max} liggen',
},
pattern: {
mismatch: '${label} komt niet overeen met het patroon ${pattern}',
},
},
},
Image: {
preview: 'Voorbeeld',
},
};
export default localeValues;
|
YaroShkvorets/ant-design-vue
|
components/date-picker/generatePicker/interface.ts
|
<gh_stars>1000+
import type {
PickerBaseProps as RCPickerBaseProps,
PickerDateProps as RCPickerDateProps,
PickerTimeProps as RCPickerTimeProps,
} from '../../vc-picker/Picker';
import type {
RangePickerBaseProps as RCRangePickerBaseProps,
RangePickerDateProps as RCRangePickerDateProps,
RangePickerTimeProps as RCRangePickerTimeProps,
} from '../../vc-picker/RangePicker';
import type { Locale as RcPickerLocale } from '../../vc-picker/interface';
import type { TimePickerLocale } from '../../time-picker';
import type { SizeType } from '../../config-provider';
type InjectDefaultProps<Props> = Omit<
Props,
| 'locale'
| 'generateConfig'
| 'prevIcon'
| 'nextIcon'
| 'superPrevIcon'
| 'superNextIcon'
| 'hideHeader'
| 'components'
> & {
locale?: PickerLocale;
size?: SizeType;
bordered?: boolean;
};
export type PickerLocale = {
lang: RcPickerLocale & AdditionalPickerLocaleLangProps;
timePickerLocale: TimePickerLocale;
} & AdditionalPickerLocaleProps;
export type AdditionalPickerLocaleProps = {
dateFormat?: string;
dateTimeFormat?: string;
weekFormat?: string;
monthFormat?: string;
};
export type AdditionalPickerLocaleLangProps = {
placeholder: string;
yearPlaceholder?: string;
quarterPlaceholder?: string;
monthPlaceholder?: string;
weekPlaceholder?: string;
rangeYearPlaceholder?: [string, string];
rangeMonthPlaceholder?: [string, string];
rangeWeekPlaceholder?: [string, string];
rangePlaceholder?: [string, string];
};
// Picker Props
export type PickerBaseProps<DateType> = InjectDefaultProps<RCPickerBaseProps<DateType>>;
export type PickerDateProps<DateType> = InjectDefaultProps<RCPickerDateProps<DateType>>;
export type PickerTimeProps<DateType> = InjectDefaultProps<RCPickerTimeProps<DateType>>;
export type PickerProps<DateType> =
| PickerBaseProps<DateType>
| PickerDateProps<DateType>
| PickerTimeProps<DateType>;
// Range Picker Props
export type RangePickerBaseProps<DateType> = InjectDefaultProps<RCRangePickerBaseProps<DateType>>;
export type RangePickerDateProps<DateType> = InjectDefaultProps<RCRangePickerDateProps<DateType>>;
export type RangePickerTimeProps<DateType> = InjectDefaultProps<RCRangePickerTimeProps<DateType>>;
export type RangePickerProps<DateType> =
| RangePickerBaseProps<DateType>
| RangePickerDateProps<DateType>
| RangePickerTimeProps<DateType>;
|
pdmyrs/webpack-starter-project
|
src/main/webpack/site/ts/app.ts
|
<reponame>pdmyrs/webpack-starter-project
console.log('Hiya');
const cards1 = document.querySelectorAll('.card.v1');
cards1.forEach(function(card) {
const button = card.querySelector('.button');
button.addEventListener('click', () => {
card.querySelector<HTMLElement>('.added-to-cart').style.display = 'block';
console.log(card.children);
});
});
const cards2 = document.querySelectorAll('.card.v2');
cards2.forEach(function(card) {
const button = card.querySelector('.button');
button.addEventListener('click', () => {
card.querySelector<HTMLElement>('.added-to-cart').style.display = 'block';
card.querySelector<HTMLElement>('.extra').style.display = 'block';
console.log(card.children);
});
});
|
MLH-Fellowship/fellow-dashboard
|
frontend/pages/links.tsx
|
<reponame>MLH-Fellowship/fellow-dashboard
import ExternalLink from "../components/externallink";
import Sidebar from "../components/sidebar";
import Head from "next/head";
export default function Links() {
return (
<>
<Head>
<title>Important Links</title>
</Head>
<Sidebar pageTitle="Important Links">
<ExternalLink
linkUrl="https://mlh-fellowship.gitbook.io/fellow-handbook/"
linkName="Fellow Handbook"
/>
<ExternalLink
linkUrl="https://mlh-fellowship.trainualapp.com/"
linkName="Trainual"
/>
<ExternalLink
linkUrl="https://mlh-fellowship.topicbox.com/"
linkName="Topicbox"
/>
</Sidebar>
</>
);
}
|
MLH-Fellowship/fellow-dashboard
|
frontend/components/issuecard.tsx
|
<reponame>MLH-Fellowship/fellow-dashboard
import {
Box,
Flex,
Heading,
Text,
Link,
Avatar,
Icon,
Tag,
} from "@chakra-ui/react";
import { GoMilestone } from "react-icons/go";
function extractRepoName(issueUrl: string) {
var url = new URL(issueUrl);
var pathArray = url.pathname.split("/");
return pathArray[2] + "/" + pathArray[3];
}
export default function IssueCard({
issueName,
issueBody,
issueLabels,
issueNumber,
issueRepo,
issueAvatar,
issueUser,
}: {
issueName: string;
issueBody: string;
issueLabels: any;
issueNumber: number;
issueRepo: string;
issueAvatar: string;
issueUser: string;
}) {
return (
<Flex
w="xs"
flexDirection="column"
borderRadius="lg"
backgroundColor="gray.800"
m="5"
>
<Box mt={5} ml={5} mr={5}>
<Text fontSize="xs">{extractRepoName(issueRepo)}</Text>
</Box>
<Flex ml={5} mr={5} justifyContent="space-between">
<Link href={issueRepo} target="_blank">
<Heading size="lg">{`#${issueNumber} ${issueName}`}</Heading>
</Link>
<Avatar src={issueAvatar} size="sm" />
</Flex>
<Flex ml={5} mr={5} mt={2}>
<Flex>
{issueLabels ? (
issueLabels.map((label: any) => (
<Tag
key={label.id}
size="sm"
mr={2}
backgroundColor={`#${label.color}`}
color="black"
>
{label.name}
</Tag>
))
) : (
<></>
)}
</Flex>
</Flex>
<Flex ml={5} mr={5} mb={5} mt={2}>
<Text>{issueBody.substr(0, 80)}...</Text>
</Flex>
</Flex>
);
}
|
MLH-Fellowship/fellow-dashboard
|
frontend/components/issues.tsx
|
import { useState, useEffect } from "react";
import { VStack, Heading, Spinner } from "@chakra-ui/react";
import { getSession } from "next-auth/client";
import { Get } from "../utils/network";
import IssueCard from "./issuecard";
export default function Issues() {
const [issueData, setIssueData] = useState([]);
useEffect(() => {
async function getIssues() {
const session = await getSession();
const response = await Get(
`/github/issues/assigned/${session.accessToken}`
);
setIssueData(response.data);
}
getIssues();
});
return (
<VStack>
<Heading>Issues</Heading>
{issueData ? (
issueData
.slice(0, 3)
.map((issue: any) => (
<IssueCard
issueName={issue.title}
issueBody={issue.body}
issueLabels={issue.labels}
issueRepo={issue.html_url}
issueNumber={issue.number}
issueAvatar={issue.avatar_url}
issueUser={issue.login}
key={issue.id}
/>
))
) : (
<Spinner size="xl" />
)}
</VStack>
);
}
|
MLH-Fellowship/fellow-dashboard
|
frontend/components/externallink.tsx
|
<filename>frontend/components/externallink.tsx<gh_stars>1-10
import { Link } from "@chakra-ui/react";
import { ExternalLinkIcon } from "@chakra-ui/icons";
export default function ExternalLink({ linkName, linkUrl }) {
return (
<>
<Link href={linkUrl} isExternal>
{linkName} <ExternalLinkIcon mx={2} />
</Link>
<br />
</>
);
}
|
MLH-Fellowship/fellow-dashboard
|
frontend/utils/network.ts
|
<gh_stars>1-10
import axios from "axios";
const API_URL = "http://localhost:3001";
const Post = async (data, url) => {
const response = await axios.put(`${API_URL}${url}`, data);
return response;
};
const Get = async (url) => {
const response = await axios.get(`${API_URL}${url}`);
return response;
};
export { Post, Get };
|
MLH-Fellowship/fellow-dashboard
|
frontend/pages/dashboard.tsx
|
import Head from "next/head";
import { useSession } from "next-auth/client";
import { Stack, Container, Heading, Center, Text } from "@chakra-ui/react";
import Sidebar from "../components/sidebar";
import Scratchpad from "../components/scratchpad";
import Issues from "../components/issues";
export default function Dashboard() {
const [session, loading] = useSession();
if (session) {
return (
<>
<Head>
<title>Dashboard</title>
</Head>
<Sidebar pageTitle="Dashboard">
<Stack spacing={2} direction={["column", "row"]}>
<Container>
<Center>
<Heading>Standup Notes</Heading>
</Center>
<Center>
<Text fontSize="xs">(psst you can edit this)</Text>
</Center>
<Container
padding={5}
borderRadius="lg"
backgroundColor="gray.700"
mt={2}
>
<Scratchpad />
</Container>
</Container>
<Container>
<Issues />
</Container>
</Stack>
</Sidebar>
</>
);
}
return (
<Sidebar pageTitle="Dashboard">
<h1>Not Signed In</h1>
</Sidebar>
);
}
|
Alpvax/vue-ds
|
src/game/utils/CompletionBar.ts
|
interface BarParams {
percentage: number,
totalLength: number,
char: string,
finalChar?: string,
endChars?: string[]
}
const toBar = ({percentage, totalLength, char, finalChar = "", endChars = ["[", "]"]}: BarParams) => {
let barLength = Math.round(percentage * totalLength);
let emptyLength = totalLength - barLength;
let bar = endChars[0]
for (let i = 0; i < barLength; i++) {
bar += char;
}
bar += finalChar;
for (let i = 0; i < emptyLength; i++) {
bar += " ";
}
bar += endChars[1];
return bar;
}
export default toBar;
|
mnemonia/recycle
|
src/app/model/Subscription.ts
|
<reponame>mnemonia/recycle
export enum MaterialId {
ALU = 2,
METALL = 3,
GLAS = 5,
GLAS_BOTTLE = 6,
PET = 8,
BATTERY = 9,
CARDBOARD = 13,
ELECTRIC_HOUSEHOLD = 28,
PE_DAIRY_PRODUCE_BOTTLES = 30, // PE Dairy Produce Bottles
PE_KUNSTSTOFF_FLASCHEN = 37, // Plastic bottles
SAMMELSACK_CH = 100,
MIGROS_GENERATION_M = 101
}
export class Material {
id: number;
}
export class SammelstelleMunicipality {
name: string;
material_regional: string;
remote_id: number;
}
export class SammelstelleCity {
id: number;
zip: string;
name: string;
file: string;
outdated: string;
municipality: SammelstelleMunicipality;
}
export class Sammelstelle {
city: SammelstelleCity;
id: number;
full_name: string;
lat: number;
lng: number;
materials: Material[];
active: number;
exactness: number;
inaccurate: boolean;
}
export class LocationAttrs {
detail: string;// "glarus nord gl"
featureId: string;// "1630"
geom_quadindex: string;//"030"
geom_st_box2d: string;// "BOX(2714690.326 1211186.713,2733163.974 1225966.591)"
label: string;// "<b>Glarus Nord (GL)</b>"
lat: number;// 47.10641860961914
lon: number;// 9.079218864440918
num: number;// 1
origin: string;// "gg25"
rank: number;// 2
x: number;// 1218570.375
y: number;// 2724521
zoomlevel: number;
}
export class Location {
is_search_history: boolean;
result: string;
attrs: LocationAttrs;
address_canonical: string;
}
export class Price {
value: number;
value_per_kg: number;
}
export class JobStatus {
state: number;
}
export class Interval {
repeat_weekday_number: number; // 0 monday, 1 thuesday, .., 6 sunday
repeat_dayhour_number: number; // 0 00:00, 12 12:00, 18 18:00
repeat_weeks: number; // 1 = every week
is_active: boolean;
}
export class Job {
type: string;
description: string;
status: JobStatus;
first_start_date: string;
last_done_date: string;
image_name: string;
price: Price;
material_id: MaterialId;
is_selected: boolean;
sammelstellen: Sammelstelle[];
}
export class Subscription {
surname: string;
lastname: string;
street: string;
number: string;
plz4: string;
plzname: string;
is_address_identified: boolean;
jobs: Job[];
interval: Interval;
timestamp: string;
price_per_month: Price;
gdekt: string;
gdname: string;
gdid: number;
total_saved_km_per_year: number;
total_saved_co2_per_year: number;
total_saved_fuel_per_year_in_liter: number;
total_saved_fuel_per_year_in_fr: number;
estimated_weight_in_kg: number;
address_canonical: string;
}
|
mnemonia/recycle
|
src/app/services/geo/geo.service.ts
|
<reponame>mnemonia/recycle
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {Location} from '../../model/Subscription';
@Injectable({
providedIn: 'root'
})
export class GeoService {
constructor(private httpClient: HttpClient) { }
public findLocation(query: string): Observable<any> {
const url = '//api3.geo.admin.ch/rest/services/api/SearchServer?lang=de&searchText=' + query + '%20GL&origins=address&type=locations&limit=5&sr=2056';
return this.httpClient.get(url).pipe(
//tap(res => console.log(res)),
map((res: any) => res.results),
map((res: any) => {
const objs = [];
res.forEach(r => {
const o = new Location();
o.attrs = r.attrs;
o.address_canonical = r.attrs.label.replace('<b>', '')
.replace('</b>','')
.replace('<i>Lokalname swisstopo</i>','')
.replace('<i>','')
.replace('</i>','');
o.is_search_history = false;
o.result = query;
objs.push(o);
});
return objs;
})
);
}
public identify(location: Location): Observable<any> {
const url = 'https://api3.geo.admin.ch/rest/services/all/MapServer/identify?geometry=' + location.attrs.y + ',' + location.attrs.x + '&geometryFormat=geojson&geometryType=esriGeometryPoint&lang=de&layers=all:ch.swisstopo.swissboundaries3d-gemeinde-flaeche.fill,ch.swisstopo-vd.ortschaftenverzeichnis_plz&limit=10&returnGeometry=false&sr=2056&tolerance=0';
console.warn('url', url);
return this.httpClient.get(url).pipe(map( (res: any) => res.results));
}
}
|
mnemonia/recycle
|
src/app/services/job/jobs.service.ts
|
import { Injectable } from '@angular/core';
import {Interval, Job, JobStatus, Price, MaterialId} from '../../model/Subscription';
@Injectable({
providedIn: 'root'
})
export class JobsService {
constructor() { }
public find(): Job[] {
const jobs = [];
let job = new Job();
job.type = 'sammelsack-ch-recycling';
job.description = 'Sammelsack';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 2;
job.price.value = 0;
job.material_id = MaterialId.SAMMELSACK_CH;
job.image_name = '' + job.material_id.valueOf() + '.svg';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
job = new Job();
job.type = 'plastic-recycling';
job.description = 'Kunststoff';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 2;
job.price.value = 0;
job.material_id = MaterialId.PE_KUNSTSTOFF_FLASCHEN;
job.image_name = '' + job.material_id.valueOf() + '.svg';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
job = new Job();
job.type = 'pet-recycling';
job.description = 'PET';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 2;
job.price.value = 0;
job.material_id = MaterialId.PET;
job.image_name = '' + job.material_id.valueOf() + '.svg';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
job = new Job();
job.type = 'glassbottle-recycling';
job.description = 'Glasflaschen';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 1;
job.price.value = 0;
job.material_id = MaterialId.GLAS_BOTTLE;
job.image_name = '' + job.material_id.valueOf() + '.svg';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
job = new Job();
job.type = 'generationm-recycling';
job.description = 'Kunststoffe';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 3;
job.price.value = 0;
job.material_id = MaterialId.MIGROS_GENERATION_M;
job.image_name = '' + job.material_id.valueOf() + '.png';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
job = new Job();
job.type = 'carton-recycling';
job.description = 'Karton';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 1.5;
job.price.value = 0;
job.material_id = MaterialId.CARDBOARD;
job.image_name = '' + job.material_id.valueOf() + '.svg';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
job = new Job();
job.type = 'battery-recycling';
job.description = 'Batterien';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 2.5;
job.price.value = 0;
job.material_id = MaterialId.BATTERY;
job.image_name = '' + job.material_id.valueOf() + '.svg';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
job = new Job();
job.type = 'electro-recycling';
job.description = 'Elektro';
job.first_start_date = new Date().toISOString();
job.last_done_date = new Date().toISOString();
job.status = new JobStatus();
job.status.state = 0;
job.price = new Price();
job.price.value_per_kg = 2.5;
job.price.value = 0;
job.material_id = MaterialId.ELECTRIC_HOUSEHOLD;
job.image_name = '' + job.material_id.valueOf() + '.svg';
job.is_selected = false;
job.sammelstellen = [];
jobs.push(job);
return jobs;
}
}
|
mnemonia/recycle
|
src/app/app.module.ts
|
<reponame>mnemonia/recycle<gh_stars>0
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {SubscriptionService} from './services/subscribe/subscription.service';
import {JobsService} from './services/job/jobs.service';
import {PaymentService} from './services/payment/payment.service';
import {HashLocationStrategy, LocationStrategy} from '@angular/common';
import {GeoService} from './services/geo/geo.service';
import {HttpClient, HttpClientModule} from '@angular/common/http';
import {RecyclingMapService} from './services/recycling-map/recycling-map.service';
import {MathService} from './services/math/math.service';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
HttpClientModule,
IonicModule.forRoot(),
AppRoutingModule
],
providers: [
StatusBar,
SplashScreen,
HttpClient,
JobsService,
SubscriptionService,
PaymentService,
RecyclingMapService,
GeoService,
MathService,
{provide: RouteReuseStrategy, useClass: IonicRouteStrategy},
{provide: LocationStrategy, useClass: HashLocationStrategy}
],
bootstrap: [AppComponent]
})
export class AppModule {}
|
mnemonia/recycle
|
src/app/subscribe/subscribe.page.ts
|
import {Component, OnInit} from '@angular/core';
import {SubscriptionService} from '../services/subscribe/subscription.service';
import {Location, MaterialId, Price, Subscription} from '../model/Subscription';
import {PaymentService} from '../services/payment/payment.service';
import {GeoService} from '../services/geo/geo.service';
import {RecyclingMapService} from '../services/recycling-map/recycling-map.service';
import {MathService} from '../services/math/math.service';
@Component({
selector: 'app-subscribe',
templateUrl: './subscribe.page.html',
styleUrls: ['./subscribe.page.scss'],
})
export class SubscribePage implements OnInit {
subscription: Subscription;
price: Price;
locations: Location[] = [];
places: any[];
places_temp: any[];
is_in_search_edit_mode = false;
constructor(private subscriptionService: SubscriptionService,
private paymentService: PaymentService,
private geoApi: GeoService,
private recyclingMapService: RecyclingMapService,
private mathService: MathService) {
}
ngOnInit() {
this.places = [];
this.places_temp = [];
this.subscription = this.subscriptionService.create();
this.recalc();
}
public recalc() {
this.findSammelstellen();
this.paymentService.calculatePrice(this.subscription);
}
public findLocation($event) {
if (!this.is_in_search_edit_mode) {
return;
}
this.locations = [];
if ($event.detail.value.trim() === '') {
return;
}
this.geoApi.findLocation($event.detail.value.trim()).subscribe(
(res) => {
this.locations = res;
},
(err) => {
console.error(err);
}
);
}
public removeLocations($event) {
this.locations = [];
this.places = [];
this.subscription.is_address_identified = false;
this.setIs_in_search_edit_mode(true);
}
public setIs_in_search_edit_mode(value: boolean) {
this.is_in_search_edit_mode = value;
}
public jumpToLocation(location: Location) {
// console.log('location', location);
this.setIs_in_search_edit_mode(false);
this.locations = [];
this.subscription.address_canonical = location.address_canonical;
//console.log('this.subscription.address_canonical', this.subscription.address_canonical);
this.geoApi.identify(location).subscribe((res) => {
res.filter(r => r.layerBodId === 'ch.swisstopo.swissboundaries3d-gemeinde-flaeche.fill')
.forEach(r => {
this.subscription.gdekt = r.properties.kanton;
this.subscription.gdname = r.properties.gemname;
this.subscription.gdid = r.id;
});
res.filter(r => r.layerBodId === 'ch.swisstopo-vd.ortschaftenverzeichnis_plz')
.forEach(r => {
this.subscription.plz4 = '' + r.properties.plz;
this.subscription.plzname = r.properties.langtext;
//console.log('plzname', this.subscription.plzname);
this.subscription.is_address_identified = true;
});
},
(err) => {
this.subscription.is_address_identified = false;
},
() => {
this.findSammelstellen();
}
);
}
private findSammelstellen() {
const selectedJobs = this.subscription.jobs.filter(j => j.is_selected);
let sammelstellenStats = [];
this.places = [];
this.places_temp = [];
this.subscription.total_saved_km_per_year = 0;
this.subscription.total_saved_co2_per_year = 0;
this.subscription.total_saved_fuel_per_year_in_liter = 0;
this.subscription.total_saved_fuel_per_year_in_fr = 0;
this.recyclingMapService.findSammelstellen(this.subscription.plz4).subscribe(
(sammelstellen) => {
selectedJobs.forEach(j => {
let sammelstelleWithMaterialMatch = [];
if (j.material_id === MaterialId.MIGROS_GENERATION_M) {
sammelstelleWithMaterialMatch =
sammelstellen.filter(s => s.full_name.indexOf('Migros') >= 0);
if (sammelstelleWithMaterialMatch.length === 0) {
sammelstelleWithMaterialMatch.push(this.recyclingMapService.getMigrosGlarus());
}
} else if (j.material_id === MaterialId.SAMMELSACK_CH) {
sammelstelleWithMaterialMatch =
sammelstellen.filter(s => s.full_name.indexOf('Bowald') >= 0);
if (sammelstelleWithMaterialMatch.length === 0) {
sammelstelleWithMaterialMatch.push(this.recyclingMapService.getSammelsackGlarus());
}
} else {
sammelstelleWithMaterialMatch =
sammelstellen.filter(s => s.materials.filter(m => m.id === j.material_id.valueOf()).length > 0);
}
j.sammelstellen = sammelstelleWithMaterialMatch;
j.sammelstellen.forEach(s => {
const stats = sammelstellenStats.filter(sm => sm.id === s.id);
if (stats.length === 0) {
const sts = {
id: s.id,
sammelstelle: s,
total_count: 1,
material: {},
materials: []};
sts.material[j.material_id] = 1;
sts.materials.push(j.material_id);
sammelstellenStats.push(sts);
} else {
stats.forEach(sts => {
sts.total_count += 1;
if (!(j.material_id in sts.material)) {
sts.material[j.material_id] = 1;
sts.materials.push(j.material_id);
} else {
sts.material[j.material_id] += 1;
}
});
}
});
});
},
(err) => console.error(err),
() => {
// case one is found for all materials:
const size = selectedJobs.length;
let allMatchingSammelstellen = sammelstellenStats.filter(s => s.total_count === size);
if (allMatchingSammelstellen.length > 0) {
const sts = allMatchingSammelstellen[0];
this.places.push(sts);
const to_address = sts.sammelstelle.full_name + ', '
+ sts.sammelstelle.city.zip + ' ' + sts.sammelstelle.city.name;
this.recyclingMapService.calculateRoutes(to_address,
this.subscription.address_canonical).subscribe(
(route: any) => {
sts.sammelstelle.distance_in_km = route.route.rawdistance / 1000;
sts.sammelstelle.co2_exhaust_in_kg = sts.sammelstelle.distance_in_km * 0.185;
sts.sammelstelle.match_count = 0;
},
(err) => {},
() => {
this.places = this.places.sort((a, b) => {
if (a.sammelstelle.distance_in_km > b.sammelstelle.distance_in_km) {
return 1;
}
if (a.sammelstelle.distance_in_km < b.sammelstelle.distance_in_km) {
return -1;
}
return 0;
});
if (this.places.length > 0) {
this.subscription.total_saved_km_per_year = (52 / this.subscription.interval.repeat_weeks) * 2 * sts.sammelstelle.distance_in_km;
this.subscription.total_saved_co2_per_year = (52 / this.subscription.interval.repeat_weeks) * 2 * sts.sammelstelle.co2_exhaust_in_kg;
this.subscription.total_saved_fuel_per_year_in_liter = this.subscription.total_saved_km_per_year * (8 / 100);
this.subscription.total_saved_fuel_per_year_in_fr = this.subscription.total_saved_fuel_per_year_in_liter * 1.38;
}
});
} else {
sammelstellenStats.forEach(sts => {
this.places_temp.push(sts);
const to_address = sts.sammelstelle.full_name + ', '
+ sts.sammelstelle.city.zip + ' ' + sts.sammelstelle.city.name;
this.recyclingMapService.calculateRoutes(to_address,
this.subscription.address_canonical).subscribe(
(route: any) => {
sts.sammelstelle.distance_in_km = route.route.rawdistance / 1000;
sts.sammelstelle.co2_exhaust_in_kg = sts.sammelstelle.distance_in_km * 0.185;
sts.sammelstelle.match_count = 0;
},
(err) => {},
() => {
console.log('sammelstellenStats unsorted', sammelstellenStats);
this.places_temp = sammelstellenStats.sort((a, b) => {
if (a.total_count < b.total_count) {
return 1;
}
if (a.total_count > b.total_count) {
return -1;
}
if (a.sammelstelle.distance_in_km > b.sammelstelle.distance_in_km) {
return 1;
}
if (a.sammelstelle.distance_in_km < b.sammelstelle.distance_in_km) {
return -1;
}
return 0;
});
const ms = [];
const plx = [];
for (let sts of this.places_temp) {
let hasAdded = false;
sts.materials.forEach(m => {
console.warn(ms.filter(mz => mz === m).length);
console.warn(ms);
if (ms.length === 0 || ms.filter(mz => mz === m).length === 0) {
ms.push(m);
hasAdded = true;
}
});
if (hasAdded) {
plx.push(sts);
}
if (ms.length >= selectedJobs.length) {
console.log(ms.length, selectedJobs.length);
break;
}
}
this.places_temp = plx;
console.log('sammelstellenStats sorted', this.places_temp);
this.subscription.total_saved_km_per_year = 0;
this.subscription.total_saved_co2_per_year = 0;
this.places_temp.forEach(sts2 => {
console.log('sammelstelle '+sts2.sammelstelle.full_name+' distance_in_km', sts2.sammelstelle.distance_in_km);
if (!isNaN(sts2.sammelstelle.distance_in_km)) {
console.log('this.subscription.total_saved_km_per_year', this.subscription.total_saved_km_per_year);
this.subscription.total_saved_km_per_year += (52 / this.subscription.interval.repeat_weeks) * 2 * sts2.sammelstelle.distance_in_km;
this.subscription.total_saved_co2_per_year += (52 / this.subscription.interval.repeat_weeks) * 2 * sts2.sammelstelle.co2_exhaust_in_kg;
this.subscription.total_saved_fuel_per_year_in_liter = this.subscription.total_saved_km_per_year * (8 / 100);
this.subscription.total_saved_fuel_per_year_in_fr = this.subscription.total_saved_fuel_per_year_in_liter * 1.38;
}
});
this.places = this.places_temp;
}
);
});
}
}
);
}
setWeight(weight) {
setTimeout(() => {
this.subscription.estimated_weight_in_kg = weight;
this.recalc();
}, 450);
}
setWeekday(weekday) {
setTimeout(() => {
this.subscription.interval.repeat_weekday_number = weekday;
//this.recalc();
}, 450);
}
setDayHour(hr) {
setTimeout(() => {
this.subscription.interval.repeat_dayhour_number = hr;
// this.recalc();
}, 450);
}
setRepeatWeeks(w) {
setTimeout(() => {
this.subscription.interval.repeat_weeks = w;
this.recalc();
}, 450);
}
}
|
mnemonia/recycle
|
src/app/services/payment/payment.service.ts
|
<filename>src/app/services/payment/payment.service.ts
import { Injectable } from '@angular/core';
import {Price, Subscription} from '../../model/Subscription';
@Injectable({
providedIn: 'root'
})
export class PaymentService {
constructor() { }
public calculatePrice(subscription: Subscription): Price {
const price = new Price();
price.value = 25;
price.value_per_kg = 0;
subscription.jobs.forEach(job => {
price.value += job.price.value;
});
return price;
}
}
|
mnemonia/recycle
|
src/app/my-jobs/my-jobs.page.ts
|
<reponame>mnemonia/recycle
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my-jobs',
templateUrl: './my-jobs.page.html',
styleUrls: ['./my-jobs.page.scss'],
})
export class MyJobsPage implements OnInit {
constructor() { }
ngOnInit() {
}
}
|
mnemonia/recycle
|
src/app/app-routing.module.ts
|
<gh_stars>0
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: '',
redirectTo: 'subscribe',
pathMatch: 'full'
},
{
path: 'subscribe',
loadChildren: () => import('./subscribe/subscribe.module').then( m => m.SubscribePageModule)
},
{
path: 'jobs',
loadChildren: () => import('./jobs/jobs.module').then( m => m.JobsPageModule)
},
{
path: 'job-details',
loadChildren: () => import('./job-details/job-details.module').then( m => m.JobDetailsPageModule)
},
{
path: 'my-jobs',
loadChildren: () => import('./my-jobs/my-jobs.module').then( m => m.MyJobsPageModule)
},
{
path: 'job-select',
loadChildren: () => import('./job-select/job-select.module').then( m => m.JobSelectPageModule)
},
{
path: 'settings',
loadChildren: () => import('./settings/settings.module').then( m => m.SettingsPageModule)
},
{
path: 'information',
loadChildren: () => import('./information/information.module').then( m => m.InformationPageModule)
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule {}
|
mnemonia/recycle
|
src/app/services/job/my-jobs.service.spec.ts
|
import { TestBed } from '@angular/core/testing';
import { MyJobsService } from './my-jobs.service';
describe('MyJobsService', () => {
let service: MyJobsService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MyJobsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
|
mnemonia/recycle
|
src/app/services/recycling-map/recycling-map.service.ts
|
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {from, Observable, of} from 'rxjs';
import {Sammelstelle} from '../../model/Subscription';
import {map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class RecyclingMapService {
constructor(private httpClient: HttpClient) { }
public findSammelstellen(plz4): Observable<Sammelstelle[]> {
if (plz4.trim() === '') {
return of([]);
}
const url = 'https://recycling-map.ch/inc/functions.php?execute=collecting_points';
const data = new FormData();
data.append('with_municipality', '1');
data.append('q', plz4)
data.append('max_city_radius', '1');
data.append('with_nearest','3');
data.append('municipality', '');
data.append('distance', 'false');
return this.httpClient.post(url, data).pipe(
map((res: Sammelstelle[]) => res)
);
}
public findSammelsackPlaces(plz4, gbdkt): Observable<Sammelstelle[]> {
if (gbdkt === 'GL') {
//return of([{"city":{"id":3534,"zip":"8750","name":"Glarus","file":"https:\/\/www.glarus.ch\/onlineschalter.html\/2872","outdated":"","municipality":{"name":"Glarus","material_regional":"","remote_id":1632}},"id":603011,"full_name":"<NAME> (Muldenservice) Landstrasse 59","lat":47.0471,"lng":9.06075,"materials":[{"id":23},{"id":9},{"id":10},{"id":28},{"id":13},{"id":16},{"id":4},{"id":19},{"id":41},{"id":25},{"id":21}],"active":1,"exactness":"-1","inaccurate":false}]);
}
return of([]);
}
public calculateRoutes(to_address, from_address) {
if (to_address.trim() === '' || from_address.trim() === '') {
return of({route:{}});
}
from_address = encodeURI(from_address);
to_address = encodeURI(to_address);
const url = 'https://map.search.ch/api/getcenter.json?from=' + from_address + '&to=' + to_address + '&mode=car&charset=UTF-8&api=1&api_id=0&lang=de';
return this.httpClient.get(url);
}
public getMigrosGlarus() {
return {
"city": {
"id": 3534,
"zip": "8750",
"name": "Glarus",
"file": "https://www.glarus.ch/onlineschalter.html/2872",
"outdated": "",
"municipality": {
"name": "Glarus",
"material_regional": "",
"remote_id": 1632
}
},
"id": 626801,
"full_name": "<NAME> (<NAME>) Schweizerhofstrasse 6",
"lat": 47.0407,
"lng": 9.07089,
"materials": [
{
"id": 9
},
{
"id": 35
},
{
"id": 28
},
{
"id": 1
},
{
"id": 37
},
{
"id": 16
},
{
"id": 30
},
{
"id": 8
},
{
"id": 29
}
],
"active": 1,
"exactness": "-1",
"inaccurate": false
};
}
public getSammelsackGlarus() {
return {
"city": {
"id": 3534,
"zip": "8750",
"name": "Glarus",
"file": "https://www.glarus.ch/onlineschalter.html/2872",
"outdated": "",
"municipality": {
"name": "Glarus",
"material_regional": "",
"remote_id": 1632
}
},
"id": 603011,
"full_name": "<NAME> (Muldenservice) Landstrasse 59",
"lat": 47.0471,
"lng": 9.06075,
"materials": [
{
"id": 23
},
{
"id": 9
},
{
"id": 10
},
{
"id": 28
},
{
"id": 13
},
{
"id": 16
},
{
"id": 4
},
{
"id": 19
},
{
"id": 41
},
{
"id": 25
},
{
"id": 21
}
],
"active": 1,
"exactness": "1",
"inaccurate": false
};
}
}
|
mnemonia/recycle
|
src/app/services/subscribe/subscription.service.ts
|
<filename>src/app/services/subscribe/subscription.service.ts
import { Injectable } from '@angular/core';
import {Interval, Subscription} from '../../model/Subscription';
import {JobsService} from '../job/jobs.service';
import {PaymentService} from '../payment/payment.service';
@Injectable({
providedIn: 'root'
})
export class SubscriptionService {
constructor(private jobService: JobsService, private paymentService: PaymentService) { }
public create() {
const c = new Subscription();
c.surname = 'Maxi';
c.lastname = 'Mustermann';
c.street = '';
c.number = '';
c.is_address_identified = false;
c.plz4 = '';
c.plzname = '';
c.gdekt = '';
c.gdname = '';
c.interval = new Interval();
c.interval.repeat_weekday_number = 0;
c.interval.repeat_dayhour_number = 18;
c.estimated_weight_in_kg = 3;
c.interval.repeat_weeks = 2;
c.interval.is_active = false;
c.jobs = this.jobService.find() ;
c.price_per_month = this.paymentService.calculatePrice(c);
c.total_saved_co2_per_year = 0;
c.total_saved_km_per_year = 0;
c.total_saved_fuel_per_year_in_liter = 0;
c.total_saved_fuel_per_year_in_fr = 0;
c.address_canonical = c.street + ' ' + c.number + ' ' + c.plz4 + ' ' + c.plzname;
return c;
}
}
|
mnemonia/recycle
|
src/app/subscribe/subscribe.page.spec.ts
|
<reponame>mnemonia/recycle
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { SubscribePage } from './subscribe.page';
describe('SubscribePage', () => {
let component: SubscribePage;
let fixture: ComponentFixture<SubscribePage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SubscribePage ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(SubscribePage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
mnemonia/recycle
|
src/app/job-details/job-details-routing.module.ts
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { JobDetailsPage } from './job-details.page';
const routes: Routes = [
{
path: '',
component: JobDetailsPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class JobDetailsPageRoutingModule {}
|
mnemonia/recycle
|
src/app/my-jobs/my-jobs.module.ts
|
<gh_stars>0
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MyJobsPageRoutingModule } from './my-jobs-routing.module';
import { MyJobsPage } from './my-jobs.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
MyJobsPageRoutingModule
],
declarations: [MyJobsPage]
})
export class MyJobsPageModule {}
|
mnemonia/recycle
|
src/app/services/recycling-map/recycling-map.service.spec.ts
|
<reponame>mnemonia/recycle
import { TestBed } from '@angular/core/testing';
import { RecyclingMapService } from './recycling-map.service';
describe('RecyclingMapService', () => {
let service: RecyclingMapService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(RecyclingMapService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
|
cody-robertson/plaid-express-ts
|
src/plaid/token/plaid-token.service.ts
|
<filename>src/plaid/token/plaid-token.service.ts<gh_stars>0
import { PlaidClient } from '../plaid-client'
import { LinkTokenContainer } from "./link-token.interface";
import Debug from "debug";
import { AccessTokenContainer} from "./access-token.interface";
const debug = Debug('plaid:token-service')
export const getLinkToken = async (user_uuid: string) : Promise<LinkTokenContainer> => {
const response = await PlaidClient.createLinkToken({
user: {
client_user_id: user_uuid
},
client_name: 'Plaid Test App',
products: ['auth', 'transactions'],
country_codes: ['US'],
language: 'en'
});
debug(`Received link_token for user ${user_uuid} via request id ${response.request_id}`)
return {
link_token: response.link_token,
user_uuid: user_uuid
};
}
export const exchangePublicToken = async (public_token: string) : Promise<AccessTokenContainer> => {
const response = await PlaidClient.exchangePublicToken(public_token);
debug(`Received access_token for item id ${response.item_id} via request id ${response.request_id}`)
return {
public_token: response.access_token,
item_id: response.item_id
}
}
|
cody-robertson/plaid-express-ts
|
src/plaid/plaid-client.ts
|
import Plaid from "plaid";
export const PlaidClient = new Plaid.Client({
clientID: process.env.PLAID_CLIENT_ID || "",
secret: process.env.PLAID_SECRET || "",
env: Plaid.environments[process.env.PLAID_ENVIRONMENT || 'sandbox'],
options: {}
});
|
cody-robertson/plaid-express-ts
|
src/index.ts
|
<filename>src/index.ts
import express from 'express';
import helmet from "helmet";
import dotenv from 'dotenv';
import Debug from 'debug';
import {plaidRouter} from "./plaid/plaid.router";
dotenv.config();
const debug = Debug('index');
if (!process.env.PORT) {
process.exit(1);
}
const PORT: number = parseInt(process.env.PORT as string, 10);
const app = express();
app.use(helmet());
app.use(express.json());
app.use('api/plaid', plaidRouter);
app.listen(PORT, () => {
debug(`Listening on port ${PORT}`);
});
|
cody-robertson/plaid-express-ts
|
src/plaid/plaid.router.ts
|
import express from "express";
import {plaidTokenRouter} from "./token/plaid-token.router";
export const plaidRouter = express.Router();
plaidRouter.use('/token', plaidTokenRouter);
|
cody-robertson/plaid-express-ts
|
src/plaid/token/access-token.interface.ts
|
export interface AccessTokenContainer {
public_token: string,
item_id: string
}
|
cody-robertson/plaid-express-ts
|
src/plaid/token/plaid-token.router.ts
|
<reponame>cody-robertson/plaid-express-ts
import express, { Request, Response } from "express";
import { getLinkToken, exchangePublicToken } from "./plaid-token.service";
export const plaidTokenRouter = express.Router();
plaidTokenRouter.get('/link_token', async (req: Request, res: Response) => {
try {
const tokenResponse = await getLinkToken('REPLACEMEWITHUSERUUID');
res.status(200).send(tokenResponse);
}
catch (e) {
res.status(500).send(e.message);
}
});
plaidTokenRouter.post('/exchange', async (req: Request, res: Response) => {
if (!req.body?.public_token) {
res.status(400).send('Missing body parameter "public_token"')
}
else {
try {
const tokenResponse = await exchangePublicToken(req.body.public_token);
res.status(201).send(tokenResponse);
}
catch (e) {
res.status(500).send(e.message);
}
}
});
|
cody-robertson/plaid-express-ts
|
src/plaid/token/link-token.interface.ts
|
<filename>src/plaid/token/link-token.interface.ts
export interface LinkTokenContainer {
link_token: string;
user_uuid: string;
}
|
EdgarPezoa/React-query_tsx_tailwindcss
|
src/Pages/Games/GameEdit/index.tsx
|
import React, { FunctionComponent } from "react";
type GameEditProps = {};
const GameEdit: FunctionComponent<GameEditProps> = (props) => {
return (
<div>
<h1>GameEdit screen</h1>
</div>
);
};
export default GameEdit;
|
EdgarPezoa/React-query_tsx_tailwindcss
|
src/Pages/Games/GameCreate/index.tsx
|
import React, { FunctionComponent } from 'react'
type GameCreateProps = {}
const GameCreate: FunctionComponent<GameCreateProps> = props => {
return (
<div>
<h1>GameCreate screen</h1>
</div>
)
}
export default GameCreate
|
EdgarPezoa/React-query_tsx_tailwindcss
|
src/App.tsx
|
import React, { FunctionComponent } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import GameList from "./Pages/Games/GameList";
import GameCreate from "./Pages/Games/GameCreate";
import GameEdit from "./Pages/Games/GameEdit";
import Game from "./Pages/Games/Game";
type AppProps = {};
const App: FunctionComponent<AppProps> = (props) => {
return (
<Router>
<Switch>
<Route path="/create">
<GameCreate />
</Route>
<Route path="/edit/:id">
<GameEdit />
</Route>
<Route path="/:id">
<Game />
</Route>
<Route path="/">
<GameList />
</Route>
</Switch>
</Router>
);
};
export default App;
|
EdgarPezoa/React-query_tsx_tailwindcss
|
src/Components/GameCard.tsx
|
<filename>src/Components/GameCard.tsx
import React, { FunctionComponent } from "react";
import PropTypes from "prop-types";
type GameCardProps = {
title: string;
image: string;
company: string;
platforms: string[];
};
const GameCard: FunctionComponent<GameCardProps> = (props) => {
const { title, image, company, platforms } = props;
const renderPlatforms = () => {
return (
<ul className="flex space-x-2 items-center pt-3">
<li>Platforms:</li>
{platforms.map((platformNew, index) => {
return <li className="border rounded-full px-2 py-1 text-center border-purple-400 hover:border-purple-600 hover:ring-2" key={index}>{platformNew}</li>;
})}
</ul>
);
};
return (
<div className="w-full h-full border-2 border-gray-200 rounded-lg border-opacity-75 shadow-md">
<div className="">
<h1 className="text-center p-3 text-lg font-semibold">
{title}
</h1>
</div>
<div className="">
<img className="min-w-full h-auto" src={image} alt={title} />
</div>
<div className="m-4">
<p>Company: <span className="italic text-lg ml-1">{company}</span></p>
{renderPlatforms()}
</div>
</div>
);
};
GameCard.propTypes = {
title: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
company: PropTypes.string.isRequired,
platforms: PropTypes.array.isRequired,
};
export default GameCard;
|
EdgarPezoa/React-query_tsx_tailwindcss
|
src/Pages/Games/GameList/index.tsx
|
<reponame>EdgarPezoa/React-query_tsx_tailwindcss
import React, { FunctionComponent, useState } from "react";
import GameCard from "../../../Components/GameCard";
import { useQuery } from "react-query";
import { gameList } from "../../../api";
type GameListProps = {};
const GameList: FunctionComponent<GameListProps> = (props) => {
const { isLoading, isError, error, isIdle, data } = useQuery(
"gameList",
gameList
);
const [search, setSearch] = useState("");
const renderGameCards = () => {
return data.data.map((game) => {
if (
search === "" ||
game.title.toLocaleLowerCase().startsWith(search)
) {
return (
<div
className="flex justify-center bg-gray-100 m-4"
key={game.id}
>
<GameCard
title={game.title}
image={game.image}
company={game.company}
platforms={game.platforms}
/>
</div>
);
} else {
return null;
}
});
};
if (isLoading) {
return <p>Is loading...</p>;
}
if (isError) {
return <p>Is {error}, reload</p>;
}
if (isIdle) {
return <p>Is loading...</p>;
}
return (
<div className="m-4">
<h1 className="text-6xl text-center py-3">Game List~</h1>
{/* Search bar */}
<div className="flex justify-center items-center bg-gray-100 m-4 space-x-8 p-4">
<label className="text-lg italic font-bold" htmlFor="gameTitle">
Search for a game
</label>
<input
value={search}
className="w-1/4 rounded-md focus:outline-none focus:ring-2 focus:border-blue-300 text-sm text-black placeholder-gray-500 border border-gray-200 py-2 pl-3"
placeholder="Game's Title"
type="text"
name="gameTitle"
id="gameTitle"
onChange={(event) =>
setSearch(event.target.value.toLowerCase())
}
/>
</div>
{/* Games Cards */}
<div className="grid lg:grid-cols-3 sm:grid-cols-2 md:grid-cols-2">{renderGameCards()}</div>
</div>
);
};
export default GameList;
|
EdgarPezoa/React-query_tsx_tailwindcss
|
src/Pages/Games/Game/index.tsx
|
import React, { FunctionComponent } from 'react'
type GameProps = {}
const Game:FunctionComponent<GameProps> = props => {
return (
<div>
<h1>Game screen</h1>
</div>
)
}
export default Game
|
rbalet/ngx-mat-intl-tel-input
|
projects/ngx-mat-intl-tel-input/src/public-api.ts
|
/*
* Public API Surface of ngx-mat-intl-tel-input
*/
export * from "./lib/ngx-mat-intl-tel-input.component";
export * from "./lib/ngx-mat-intl-tel-input.module";
|
willem-vanheemstrasystems/angular2-bem-headstart
|
ANG2_BEM_002/src/app/app.component.ts
|
<reponame>willem-vanheemstrasystems/angular2-bem-headstart
/* Based on https://www.bennadel.com/blog/3204-solved-css-specificity-and-shadow-dom-overrides-in-angular-2-4-1.htm */
import { Component } from '@angular/core';
/*
* In this particular exploration, we're going to be overriding the host element's "margin" property.
* Notice that margin is defined on both ":host" and on ":host(.mini)".
* We're going to be overriding both of those use-cases from our root component.
* And, since we're moving our global stylesheet into the shadow DOM of the root component,
* the root component is the only other piece of code that we need to look at
*/
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
}
|
willem-vanheemstrasystems/angular2-bem-headstart
|
ANG2_BEM_002/src/app/card-deck/card-deck.component.ts
|
import { Component, OnInit, ChangeDetectionStrategy } from "@angular/core";
@Component({
selector: 'app-card-deck',
inputs: [ "avatarUrl", "name", "title" ],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './card-deck.component.html',
styleUrls: ['./card-deck.component.css']
})
export class CardDeckComponent implements OnInit {
public avatarUrl: string;
public name: string;
public title: string;
constructor() {
this.avatarUrl = "";
this.name = "";
this.title = "";
}
ngOnInit() {
}
}
|
FloChehab/airflow
|
airflow/ui/src/api/index.ts
|
<gh_stars>1-10
/* eslint-disable no-console */
/*!
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import axios, { AxiosResponse } from 'axios';
import {
useMutation, useQuery, useQueryClient, setLogger,
} from 'react-query';
import humps from 'humps';
import { useToast } from '@chakra-ui/react';
import type { Dag, DagRun, Version } from 'interfaces';
import type {
DagsResponse,
DagRunsResponse,
TaskInstancesResponse,
TriggerRunRequest,
} from 'interfaces/api';
axios.defaults.baseURL = `${process.env.WEBSERVER_URL}/api/v1`;
axios.interceptors.response.use(
(res) => (res.data ? humps.camelizeKeys(res.data) as unknown as AxiosResponse : res),
);
// turn off logging, retry and refetch on tests
const isTest = process.env.NODE_ENV === 'test';
setLogger({
log: isTest ? () => {} : console.log,
warn: isTest ? () => {} : console.warn,
error: isTest ? () => {} : console.warn,
});
const toastDuration = 3000;
const refetchInterval = isTest ? false : 1000;
export function useDags() {
return useQuery<DagsResponse, Error>(
'dags',
(): Promise<DagsResponse> => axios.get('/dags'),
{
refetchInterval,
retry: !isTest,
},
);
}
export function useDagRuns(dagId: Dag['dagId'], dateMin?: string) {
return useQuery<DagRunsResponse, Error>(
['dagRun', dagId],
(): Promise<DagRunsResponse> => axios.get(`dags/${dagId}/dagRuns${dateMin ? `?start_date_gte=${dateMin}` : ''}`),
{ refetchInterval },
);
}
export function useTaskInstances(dagId: Dag['dagId'], dagRunId: DagRun['dagRunId'], dateMin?: string) {
return useQuery<TaskInstancesResponse, Error>(
['taskInstance', dagRunId],
(): Promise<TaskInstancesResponse> => (
axios.get(`dags/${dagId}/dagRuns/${dagRunId}/taskInstances${dateMin ? `?start_date_gte=${dateMin}` : ''}`)
),
);
}
export function useVersion() {
return useQuery<Version, Error>(
'version',
(): Promise<Version> => axios.get('/version'),
);
}
export function useTriggerRun(dagId: Dag['dagId']) {
const queryClient = useQueryClient();
const toast = useToast();
return useMutation(
(trigger: TriggerRunRequest) => axios.post(`dags/${dagId}/dagRuns`, humps.decamelizeKeys(trigger)),
{
onSettled: (res, error) => {
if (error) {
toast({
title: 'Error triggering DAG',
description: (error as Error).message,
status: 'error',
duration: toastDuration,
isClosable: true,
});
} else {
toast({
title: 'DAG Triggered',
status: 'success',
duration: toastDuration,
isClosable: true,
});
const dagRunData = queryClient.getQueryData(['dagRun', dagId]) as unknown as DagRunsResponse;
if (dagRunData) {
queryClient.setQueryData(['dagRun', dagId], {
dagRuns: [...dagRunData.dagRuns, res],
totalEntries: dagRunData.totalEntries += 1,
});
} else {
queryClient.setQueryData(['dagRun', dagId], {
dagRuns: [res],
totalEntries: 1,
});
}
}
queryClient.invalidateQueries(['dagRun', dagId]);
},
},
);
}
export function useSaveDag(dagId: Dag['dagId']) {
const queryClient = useQueryClient();
const toast = useToast();
return useMutation(
(updatedValues: Record<string, any>) => axios.patch(`dags/${dagId}`, humps.decamelizeKeys(updatedValues)),
{
onMutate: async (updatedValues: Record<string, any>) => {
await queryClient.cancelQueries(['dag', dagId]);
const previousDag = queryClient.getQueryData(['dag', dagId]) as Dag;
const previousDags = queryClient.getQueryData('dags') as DagsResponse;
const newDags = previousDags.dags.map((dag) => (
dag.dagId === dagId ? { ...dag, ...updatedValues } : dag
));
const newDag = {
...previousDag,
...updatedValues,
};
// optimistically set the dag before the async request
queryClient.setQueryData(['dag', dagId], () => newDag);
queryClient.setQueryData('dags', (old) => ({
...(old as Dag[]),
...{
dags: newDags,
totalEntries: previousDags.totalEntries,
},
}));
return { [dagId]: previousDag, dags: previousDags };
},
onSettled: (res, error, variables, context) => {
const previousDag = (context as any)[dagId] as Dag;
const previousDags = (context as any).dags as DagsResponse;
// rollback to previous cache on error
if (error) {
queryClient.setQueryData(['dag', dagId], previousDag);
queryClient.setQueryData('dags', previousDags);
toast({
title: 'Error updating pipeline',
description: (error as Error).message,
status: 'error',
duration: toastDuration,
isClosable: true,
});
} else {
// check if server response is different from our optimistic update
if (JSON.stringify(res) !== JSON.stringify(previousDag)) {
queryClient.setQueryData(['dag', dagId], res);
queryClient.setQueryData('dags', {
dags: previousDags.dags.map((dag) => (
dag.dagId === dagId ? res : dag
)),
totalEntries: previousDags.totalEntries,
});
}
toast({
title: 'Pipeline Updated',
status: 'success',
duration: toastDuration,
isClosable: true,
});
}
queryClient.invalidateQueries(['dag', dagId]);
},
},
);
}
|
cha3ban/nextjs-monorepo-example
|
apps/web-app/src/backend/config/container.config.ts
|
export { prismaClient } from '../../../../../packages/db-main-prisma';
|
madvincy/ng2-amrs
|
src/app/clinic-dashboard/hiv/hiv-program.module.ts
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatProgressSpinnerModule, MatProgressBarModule, MatTabsModule,
MatSlideToggleModule, MatDatepickerModule, MatNativeDateModule, MatDatepickerToggle
} from '@angular/material';
import {
TabViewModule, FieldsetModule, ButtonModule, GrowlModule,
AccordionModule
} from 'primeng/primeng';
import { AgGridModule } from 'ag-grid-angular/main';
import {
DateTimePickerModule
} from 'ngx-openmrs-formentry/';
import { CalendarModule } from 'angular-calendar';
import { ChartModule } from 'angular2-highcharts';
import { Moh731ReportComponent } from './moh-731/moh-731-report.component';
import { clinicDashboardHivRouting } from './hiv-program.routes';
import { HivCareLibModule } from '../../hiv-care-lib/hiv-care-lib.module';
import { EtlApi } from '../../etl-api/etl-api.module';
import { HivModuleComponent } from './hiv-program.component';
import { DepartmentProgramFilterModule
} from './../../department-program-filter/department-program-filter.module';
import {
PatientStatusChangeVisualizationContainerComponent
} from './patient-status-change-visualization/patient-status-change-visualization.container.component';
import {
PatientStatusChangeVisualizationComponent
} from './patient-status-change-visualization/patient-status-change-visualization.component';
import {
PatientStatusDatalistCellComponent
} from './patient-status-change-visualization/patient-status-data-list-cell.component';
import { PatientStatusChangeListComponent
} from './patient-status-change-visualization/patient-status-change-list.component';
import {
HivSummaryIndicatorComponent
} from './hiv-summary-indicators/hiv-summary-indicator.component';
import { DataListsModule } from '../../shared/data-lists/data-lists.module';
import { ClinicScheduleLibModule } from '../../clinic-schedule-lib/clinic-schedule-lib.module';
import {
PatientsRequiringVLComponent
} from './patients-requiring-vl/patients-requiring-vl.component';
import { DailyScheduleClinicFlowComponent
} from './clinic-flow/daily-schedule-clinic-flow.component';
import { HivCareComparativeComponent
} from './hiv-visualization/hiv-care-overview.component';
import {
HivDailyScheduleComponent
} from './daily-schedule/daily-schedule.component';
import {
HivMonthlyScheduleComponent
} from './monthly-schedule/monthly-schedule.component';
import {
PatientStatusIndicatorDefComponent
} from './clinical-summary-visualization/patient-status-overview/indicator-definition.component';
import {
ArtOverviewComponent
} from './clinical-summary-visualization/art-overview/art-overview.component';
import {
PatientStatusOverviewComponent
} from './clinical-summary-visualization/patient-status-overview/patient-status-overview.component';
import {
VisualizationPatientListComponent
} from './clinical-summary-visualization/visualization-patient-list/visualization.patient-list.component';
import { DashboardFiltersComponent } from '../dashboard-filters/dashboard-filters.component';
import { DateRangeComponent } from '../dashboard-filters/date-range/date-range.component';
import { RangeSliderComponent } from '../dashboard-filters/range-slider/range-slider.component';
import {
IndicatorSelectComponent
} from '../dashboard-filters/indicator-selector/indicator-selector.component';
import {
GenderSelectComponent
} from '../dashboard-filters/gender-selector/gender-selector.component';
import {
ArtOverviewIndicatorDefComponent
} from './clinical-summary-visualization/art-overview/indicator-definitions.component';
import {
ClinicalSummaryVisualizationService
} from '../../hiv-care-lib/services/clinical-summary-visualization.service';
import {
ProgramVisitEncounterSearchModule
} from '../../program-visit-encounter-search/program-visit-encounter-search.module';
import { RouterModule } from '@angular/router';
import {
Moh731MonthlyVizComponent
} from './moh731-monthly-viz/moh731-monthly-viz.component';
import { ClinicKibanaVizComponent } from '../../clinic-dashboard/clinic-kibana-viz/clinic-kibana-viz.component';
import { KibanaLibModule } from '../../kibana-lib';
import { HivEnhancedComponent } from './hiv-enhanced-program/hiv-enhanced-program.component';
import {
HivEnhancedFiltersComponent
} from './hiv-enhanced-program/hiv-enhanced-program-filters/hiv-enhanced-program-filters.component';
import {
HivEnhancedPatientListComponent
} from './hiv-enhanced-program/hiv-enhanced-patient-list/hiv-enhanced-patient-list.component';
import { DefaulterListComponent } from '../general/defaulter-list/defaulter-list.component';
import { GeneralModule } from '../general/general.module';
import { ChangeDepartmentModule } from '../change-department/change-department.module';
import { HivDifferentiatedCareComponent } from './hiv-differentiated-care-program/hiv-differentiated-care-program.component';
import {
HivDifferentiatedCarePatientListComponent
} from './hiv-differentiated-care-program/hiv-differentiated-care-program-patient-list/hiv-differentiated-care-patient-list.component';
import { SurgeReportComponent } from './surge-report/surge-report.component';
import { ReportingUtilitiesModule } from 'src/app/reporting-utilities/reporting-utilities.module';
import { BsDatepickerModule } from 'ngx-bootstrap';
import { ClinicDashboardRetentionReportComponent } from './retention-report/clinic-dashboard-retention-report.component';
@NgModule({
imports: [
clinicDashboardHivRouting,
HivCareLibModule,
DateTimePickerModule,
AgGridModule,
EtlApi,
DataListsModule,
CommonModule,
FormsModule,
MatTabsModule,
MatProgressSpinnerModule,
MatProgressBarModule,
MatDatepickerModule,
MatNativeDateModule,
MatSlideToggleModule,
CalendarModule,
TabViewModule,
FieldsetModule,
ButtonModule,
GrowlModule,
AccordionModule,
ChartModule,
ProgramVisitEncounterSearchModule,
ClinicScheduleLibModule,
DepartmentProgramFilterModule,
ChangeDepartmentModule,
GeneralModule,
KibanaLibModule,
ReportingUtilitiesModule,
BsDatepickerModule.forRoot()
],
exports: [
HivSummaryIndicatorComponent,
DailyScheduleClinicFlowComponent,
PatientsRequiringVLComponent,
PatientStatusChangeListComponent,
PatientStatusDatalistCellComponent,
PatientStatusChangeVisualizationComponent,
PatientStatusChangeVisualizationContainerComponent,
DashboardFiltersComponent,
GenderSelectComponent,
IndicatorSelectComponent,
DateRangeComponent,
RangeSliderComponent,
RouterModule
],
declarations: [
Moh731ReportComponent,
HivSummaryIndicatorComponent,
DailyScheduleClinicFlowComponent,
PatientsRequiringVLComponent,
PatientStatusIndicatorDefComponent,
VisualizationPatientListComponent,
ArtOverviewComponent,
PatientStatusOverviewComponent,
ArtOverviewIndicatorDefComponent,
// HivSummaryIndicatorsPatientListComponent,
HivCareComparativeComponent,
HivDailyScheduleComponent,
HivMonthlyScheduleComponent,
PatientStatusChangeListComponent,
PatientStatusDatalistCellComponent,
PatientStatusChangeVisualizationComponent,
PatientStatusChangeVisualizationContainerComponent,
DashboardFiltersComponent,
GenderSelectComponent,
IndicatorSelectComponent,
DateRangeComponent,
RangeSliderComponent,
HivEnhancedComponent,
HivEnhancedFiltersComponent,
HivEnhancedPatientListComponent,
DefaulterListComponent,
Moh731MonthlyVizComponent,
ClinicKibanaVizComponent,
HivDifferentiatedCareComponent,
HivDifferentiatedCarePatientListComponent,
SurgeReportComponent,
ClinicDashboardRetentionReportComponent
],
providers: [
ClinicalSummaryVisualizationService
],
entryComponents: [PatientStatusDatalistCellComponent]
})
export class HivProgramModule { }
|
madvincy/ng2-amrs
|
src/app/patient-dashboard/oncology/program-snapshot/oncology-program-snapshot.component.ts
|
import { Component, OnDestroy, OnInit, Input } from '@angular/core';
import { Subscription } from 'rxjs';
import * as _ from 'lodash';
import { Patient } from '../../../models/patient.model';
import { OncologySummaryResourceService
} from '../../../etl-api/oncology-summary-resource.service';
@Component({
selector: 'oncology-snapshot',
styleUrls: ['./oncology-program-snapshot.component.css'],
templateUrl: './oncology-program-snapshot.component.html'
})
export class OncologyProgramSnapshotComponent implements OnInit, OnDestroy {
@Input() public patient: Patient;
@Input() public programUuid;
public loadingSummary = false;
public hasData = false;
public isIntegratedProgram = false;
public hasError = false;
public subscription: Subscription;
public patientUuid: any;
public errors: any = [];
public summaryData: any;
constructor(
private oncolologySummary: OncologySummaryResourceService,
private integratedProgramSnapshot: OncologySummaryResourceService) {
}
public ngOnInit() {
_.delay((patientUuid) => {
if (_.isNil(this.patient)) {
this.hasError = true;
} else {
this.hasData = false;
if (this.programUuid === '37ff4124-91fd-49e6-8261-057ccfb4fcd0') {
this.loadScreeningAndDiagnosisData(patientUuid);
} else {
this.loadOncologyDataSummary(patientUuid);
}
}
}, 0, this.patient.uuid);
}
public ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
public loadOncologyDataSummary(patientUuid) {
if (this.programUuid && patientUuid) {
this.oncolologySummary.getOncologySummary('summary', patientUuid, this.programUuid).subscribe((summary) => {
this.summaryData = summary[0];
this.hasData = true;
this.hasError = false;
this.loadingSummary = false;
}, (error) => {
this.loadingSummary = false;
this.hasData = false;
this.hasError = true;
console.log(error);
this.errors.push({
id: 'summary',
message: 'Error Fetching Summary'
});
});
}
}
private loadScreeningAndDiagnosisData(patientUuid: any) {
this.hasData = true;
this.hasError = false;
this.integratedProgramSnapshot.getIntegratedProgramSnapshot(patientUuid)
.subscribe((screeningSummary) => {
this.isIntegratedProgram = true;
this.summaryData = screeningSummary;
this.hasData = true;
this.hasError = false;
this.loadingSummary = false;
}, (error => {
this.loadingSummary = false;
this.hasData = false;
this.hasError = true;
console.log(error);
this.errors.push({
id: 'summary',
message: 'Error Fetching Summary'
});
}));
}
}
|
madvincy/ng2-amrs
|
src/app/program-visit-encounter-search/program-visit-encounter-search.component.spec.ts
|
/* tslint:disable:no-unused-variable */
import { FormsModule } from '@angular/forms';
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { of } from 'rxjs';
import { ProgramVisitEncounterSearchComponent } from './program-visit-encounter-search.component';
import { AppSettingsService } from './../app-settings/app-settings.service';
import { LocalStorageService } from './../utils/local-storage.service';
import { AppFeatureAnalytics } from './../shared/app-analytics/app-feature-analytics.service';
import { FakeAppFeatureAnalytics } from './../shared/app-analytics/app-feature-analytcis.mock';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { PatientProgramResourceService } from './../etl-api/patient-program-resource.service';
import { AngularMultiSelectModule } from 'angular2-multiselect-dropdown/angular2-multiselect-dropdown';
import { DepartmentProgramsConfigService } from './../etl-api/department-programs-config.service';
import { IonicStorageModule } from '@ionic/storage';
import { SelectDepartmentService } from './../shared/services/select-department.service';
import { DateTimePickerModule } from 'ngx-openmrs-formentry/';
import { PatientService } from '../patient-dashboard/services/patient.service';
import { delay } from 'rxjs/operators';
class MockRouter {
public navigate = jasmine.createSpy('navigate');
}
class MockActivatedRoute {
public params = of([{ 'id': 1 }]);
public snapshot = {
queryParams: { date: '' }
};
}
const testParams = {
'encounterType': ['f5381269-c889-4c5a-b384-d017441eedae'],
'endDate': '2018-12-18',
'programType': ['b731ba72-cf99-4176-9fcd-37cd186400c7'],
'resetFilter': 'false',
'startDate': '2018-12-18',
'visitType': ['5033fbfc-ddc9-4f7f-853d-379659e48bdd']
};
const mockEmittedParams = {
'programType': ['b731ba72-cf99-4176-9fcd-37cd186400c7'],
'visitType': ['5033fbfc-ddc9-4f7f-853d-379659e48bdd'],
'encounterType': ['f5381269-c889-4c5a-b384-d017441eedae'],
'startDate': '2018-12-18',
'endDate': '',
'resetFilter': 'false'
};
const departmentConfig = {
'uud1': {
'name': 'CDM',
'programs': [
{
'uuid': 'fc15ac01-5381-4854-bf5e-917c907aa77f',
'name': 'CDM PROGRAM'
}
]
},
'uud2': {
'name': 'OVC',
'programs': [
{
'uuid': '781d8768-1359-11df-a1f1-0026b9348838',
'name': 'OVC PROGRAM'
}
]
},
'uud3': {
'name': 'BSG',
'programs': [
{
'uuid': '781d8a88-1359-11df-a1f1-0026b9348838',
'name': 'BSG PROGRAM'
}
]
}
};
const mockDepartmentPrograms = [
{
'uuid': 'b731ba72-cf99-4176-9fcd-37cd186400c7',
'name': 'HTN AND DM CARE AT THE SECONDARY CARE LEVEL'
},
{
'uuid': 'bd9a8b06-73c7-44a8-928c-5e72247f4c1d',
'name': 'HTN AND DM CARE AT THE TERTIARY CARE LEVEL PROGRAM'
}
];
const mockPrograms = [
{
'id': 'b731ba72-cf99-4176-9fcd-37cd186400c7',
'itemName': 'HTN AND DM CARE AT THE SECONDARY CARE LEVEL'
},
{
'id': 'bd9a8b06-73c7-44a8-928c-5e72247f4c1d',
'itemName': 'HTN AND DM CARE AT THE TERTIARY CARE LEVEL PROGRAM'
}
];
const mockProgramVisitsConfig = {
'b731ba72-cf99-4176-9fcd-37cd186400c7': {
'name': 'HTN-DM SECONDARY CARE',
'visitTypes': [
{
'uuid': '5033fbfc-ddc9-4f7f-853d-379659e48bdd',
'name': 'DM-HTN Secondary Visit',
'encounterTypes': [
{
'uuid': 'f5381269-c889-4c5a-b384-d017441eedae',
'display': 'CDMTRIAGE'
},
{
'uuid': '9af62145-1114-4711-a2b4-1c23ae69eb46',
'display': 'HTNDMINITIAL'
}
]
}
]
},
'bd9a8b06-73c7-44a8-928c-5e72247f4c1d': {
'name': 'HTN-DM TERTIARY CARE',
'visitTypes': [
{
'uuid': '67da2bee-70de-451c-8002-75429c71c46c',
'name': 'DM-HTN Tertiary visit',
'encounterTypes': [
{
'uuid': 'f5381269-c889-4c5a-b384-d017441eedae',
'display': 'CDMTRIAGE'
},
{
'uuid': '14c3b999-2d5c-4c2e-b173-5212b9170652',
'display': 'COEDMINITIAL'
}
]
}
]
}
};
const visitTypes = [
{
'id': '1',
'itemName': 'visitType1'
},
{
'id': '2',
'itemName': 'visitType2'
}
];
const departmentProgramSpyService = jasmine.createSpyObj('DepartmentProgramsConfigService', ['getDartmentProgramsConfig']);
const patientProgramSpyService = jasmine.createSpyObj('PatientProgramResourceService', ['getAllProgramVisitConfigs',
'getPatientProgramVisitConfigs', 'getPatientProgramVisitTypes']);
const departmentProgramServiceSpy = departmentProgramSpyService.getDartmentProgramsConfig
.and.returnValue(of(departmentConfig));
describe('Component: ProgramVisitEncounterSearch', () => {
let fixture: ComponentFixture<ProgramVisitEncounterSearchComponent>;
let comp: ProgramVisitEncounterSearchComponent;
let localStorageService: LocalStorageService;
let route: ActivatedRoute;
let router: Router;
let patientProgramService: PatientProgramResourceService;
let departmentProgramService: DepartmentProgramsConfigService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports:
[
AngularMultiSelectModule,
FormsModule,
DateTimePickerModule,
IonicStorageModule.forRoot()
],
declarations: [
ProgramVisitEncounterSearchComponent
],
providers: [
PatientProgramResourceService,
AppSettingsService,
LocalStorageService,
DepartmentProgramsConfigService,
SelectDepartmentService,
PatientService,
Storage,
{ provide: Router, useClass: MockRouter },
{
provide: ActivatedRoute,
useClass: MockActivatedRoute
},
{
provide: AppFeatureAnalytics,
useClass: FakeAppFeatureAnalytics
},
{
provide: PatientProgramResourceService,
useValue: departmentProgramSpyService
},
{
provide: DepartmentProgramsConfigService,
useValue: departmentProgramServiceSpy
}
]
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(ProgramVisitEncounterSearchComponent);
comp = fixture.componentInstance;
patientProgramService = fixture.debugElement.injector.get<PatientProgramResourceService>(PatientProgramResourceService);
localStorageService = fixture.debugElement.injector.get<LocalStorageService>(LocalStorageService);
departmentProgramService = fixture.debugElement.injector.get<DepartmentProgramsConfigService>(DepartmentProgramsConfigService);
router = fixture.debugElement.injector.get(Router);
route = fixture.debugElement.injector.get(ActivatedRoute);
});
}));
afterEach(() => {
TestBed.resetTestingModule();
});
it('should create an instance', () => {
expect(comp).toBeDefined();
});
it('should set the correct programs filter based on department selected', async () => {
comp.programVisitsConfig = mockProgramVisitsConfig;
comp.loadProgramFilter(mockDepartmentPrograms);
expect(JSON.stringify(comp.programs)).toBe(JSON.stringify(mockPrograms));
});
it('should get correct options from options map', async () => {
const mockValues = ['142939b0-28a9-4649-baf9-a9d012bf3b3d'];
const mockMap = new Map();
mockMap.set('142939b0-28a9-4649-baf9-a9d012bf3b3d', {
'id': '142939b0-28a9-4649-baf9-a9d012bf3b3d',
'itemName': 'BREAST CANCER SCREENING PROGRAM'
});
const mockProgramArray = [{
'id': '142939b0-28a9-4649-baf9-a9d012bf3b3d',
'itemName': 'BREAST CANCER SCREENING PROGRAM'
}];
const filterArray = comp.loadFilterFromMap(mockValues, mockMap);
expect(JSON.stringify(filterArray)).toBe(JSON.stringify(mockProgramArray));
});
it('should correctly identify params string value', async () => {
const testString = 'uuid';
const testArray = ['uuid'];
const isString1 = comp.isString(testString);
const isString2 = comp.isString(testArray);
expect(isString1).toBe(true);
expect(isString2).toBe(false);
});
it('should generate correct filter items from params object', () => {
comp.visitMaps.set('5033fbfc-ddc9-4f7f-853d-379659e48bdd', {
'id': '5033fbfc-ddc9-4f7f-853d-379659e48bdd',
'itemName': 'DM-HTN Secondary Visit'
});
comp.programVisitMap.set('b731ba72-cf99-4176-9fcd-37cd186400c7', [
{
'uuid': '5033fbfc-ddc9-4f7f-853d-379659e48bdd',
'name': 'DM-HTN Secondary Visit',
}]);
comp.visitTypeEncounterTypeMap.set('5033fbfc-ddc9-4f7f-853d-379659e48bdd', [
{
'uuid': 'f5381269-c889-4c5a-b384-d017441eedae',
'display': 'CDMTRIAGE'
},
{
'uuid': '9af62145-1114-4711-a2b4-1c23ae69eb46',
'display': 'HTNDMINITIAL'
}
]);
comp.programMaps.set('b731ba72-cf99-4176-9fcd-37cd186400c7', {
'id': 'b731ba72-cf99-4176-9fcd-37cd186400c7',
'itemName': 'HTN AND DM CARE AT THE SECONDARY CARE LEVEL'
});
comp.encounterMaps.set('f5381269-c889-4c5a-b384-d017441eedae', {
'uuid': 'f5381269-c889-4c5a-b384-d017441eedae',
'display': 'CDMTRIAGE'
});
const programSelected = [{
'id': 'b731ba72-cf99-4176-9fcd-37cd186400c7',
'itemName': 'HTN AND DM CARE AT THE SECONDARY CARE LEVEL'
}];
const visitTypeSelected = [{
'id': '5033fbfc-ddc9-4f7f-853d-379659e48bdd',
'itemName': 'DM-HTN Secondary Visit'
}];
const encounterSelected = [{
'uuid': 'f5381269-c889-4c5a-b384-d017441eedae',
'display': 'CDMTRIAGE'
}];
spyOn(comp, 'emitParams');
comp.getParamsFromUrl(testParams);
expect(JSON.stringify(comp.program)).toBe(JSON.stringify(programSelected));
expect(JSON.stringify(comp.visitType)).toBe(JSON.stringify(visitTypeSelected));
expect(JSON.stringify(comp.encounterType)).toBe(JSON.stringify(encounterSelected));
expect(comp.emitParams).toHaveBeenCalled();
expect(comp.emitParams).toHaveBeenCalledWith(mockEmittedParams);
});
});
|
crislerwin/azeria-front
|
src/themes/light.ts
|
<reponame>crislerwin/azeria-front<filename>src/themes/light.ts<gh_stars>0
import { DefaultTheme } from 'styled-components';
export const light: DefaultTheme = {
title: `light`,
colors: {
primary: `#fff`,
secondary: `#fff`,
background: `#f7f7f8`,
title: `#212024`,
},
};
|
crislerwin/azeria-front
|
src/services/api.ts
|
<reponame>crislerwin/azeria-front<gh_stars>0
import axios from 'axios';
const api = axios.create({
baseURL: `https://randomuser.me/api/`,
headers: {
'Content-Type': `application/json`,
},
params: {
results: 1000,
nat: `us`,
},
});
export default api;
|
crislerwin/azeria-front
|
src/pages/index.tsx
|
import api from '@/services/api';
import { useEffect, useState } from 'react';
import { SimpleTable, IUser } from '@/components/SimpleTable';
export default function Home() {
const [users, setUsers] = useState<IUser[]>([]);
useEffect(() => {
async function fetchData() {
await api.get(`/`).then((response) => {
setUsers(response.data.results);
});
}
fetchData();
}, []);
return (
<>
<SimpleTable users={users} />
</>
);
}
|
crislerwin/azeria-front
|
src/components/SimpleTable/styles.ts
|
<reponame>crislerwin/azeria-front<filename>src/components/SimpleTable/styles.ts
import styled from 'styled-components';
const Container = styled.div`
display: flex;
flex-direction: column;
`;
const Table = styled.table`
border-collapse: collapse;
width: 40rem;
text-align: center;
`;
const TableBody = styled.tbody`
display: block;
height: 400px;
overflow-y: scroll;
`;
const TableRow = styled.tr`
display: table-row;
vertical-align: inherit;
border-color: inherit;
`;
const TableData = styled.td`
padding: 6px;
border: 1px solid #ddd;
`;
const Header = styled.div`
display: flex;
flex-direction: row;
width: 40rem;
padding: 10px;
border: 1px solid #ddd;
`;
const Name = styled.div`
margin-left: 1rem;
`;
const LastName = styled.div`
margin-left: 2rem;
`;
const Email = styled.div`
margin-left: 8rem;
`;
const Phone = styled.div`
margin-left: 8rem;
`;
const Title = styled.h1`
font-size: 18px;
color: #333;
margin: 0;
`;
export {
Container,
Table,
TableBody,
TableRow,
TableData,
Header,
Name,
LastName,
Email,
Phone,
Title,
};
|
crislerwin/azeria-front
|
src/components/SimpleTable/index.tsx
|
<reponame>crislerwin/azeria-front<filename>src/components/SimpleTable/index.tsx
import {
Container,
Table,
TableBody,
TableRow,
TableData,
Header,
Name,
LastName,
Title,
Phone,
Email,
} from './styles';
export type IUser = {
gender: string;
name: {
title: string;
first: string;
last: string;
};
location: {
street: {
number: number;
name: string;
};
city: string;
state: string;
country: string;
postcode: number;
coordinates: {
latitude: string;
longitude: string;
};
timezone: {
offset: string;
description: string;
};
};
email: string;
login: {
uuid: string;
username: string;
password: <PASSWORD>;
salt: string;
md5: string;
sha1: string;
sha256: string;
};
dob: {
date: string;
age: number;
};
registered: {
date: string;
age: number;
};
phone: string;
cell: string;
id: {
name: string;
value: string;
};
picture: {
large: string;
medium: string;
thumbnail: string;
};
};
type IProps = {
users: IUser[];
};
export const SimpleTable: React.FC<IProps> = ({ users }) => {
return (
<Container>
<Header>
<Name>
<Title>Name</Title>
</Name>
<LastName>
<Title>LastName</Title>
</LastName>
<Email>
<Title>Email</Title>
</Email>
<Phone>
<Title>Phone</Title>
</Phone>
</Header>
<Table>
<TableBody>
{users.map((user) => (
<TableRow key={user.login.uuid}>
<TableData>{user.name.first}</TableData>
<TableData>{user.name.last}</TableData>
<TableData>{user.email}</TableData>
<TableData>{user.phone}</TableData>
</TableRow>
))}
</TableBody>
</Table>
</Container>
);
};
|
crislerwin/azeria-front
|
src/pages/_app.tsx
|
<reponame>crislerwin/azeria-front
import { AppProps } from 'next/app';
import { ThemeProvider } from 'styled-components';
import { light } from '../themes/light';
import GlobalStyles from '@/styles/globalStyles';
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<ThemeProvider theme={light}>
<Component {...pageProps} />
<GlobalStyles />
</ThemeProvider>
);
}
|
szgaljic/react-login
|
src/components/home-page/HomePage.tsx
|
<reponame>szgaljic/react-login
import * as React from 'react';
class HomePage extends React.Component {
constructor(props: any) {
super(props);
this.state= {
user: {}
};
}
render() {
// const { user } = this.state;
return (
<div className="col-md-6 col-md-offset-3">
<p>You're logged in with React & Basic HTTP Authentication!!</p>
</div>
);
}
}
export { HomePage };
|
szgaljic/react-login
|
src/components/navbar/Navbar.tsx
|
<gh_stars>0
import * as React from 'react';
import {Link} from 'react-router-dom';
import {AuthenticationService} from '../../services/AuthenticationService';
export class Navbar extends React.Component {
constructor(props: any) {
super(props);
this.state = {
user: AuthenticationService.getUser()
}
}
render() {
return (
<nav className="navbar navbar-expand-lg navbar-warning bg-warning">
<ul className="navbar-nav mr-auto float-right">
<li className="nav-item">
<Link to="/login" className="nav-link">Login</Link>
</li>
<li className="nav-item">
<Link to="/register" className="nav-link">Register</Link>
</li>
</ul>
</nav>
);
}
}
|
szgaljic/react-login
|
src/components/login-page/LoginPage.tsx
|
import * as React from 'react';
import {Redirect} from 'react-router';
import {Credentials} from '../../models/classes/Credentials';
import {AuthenticationService} from '../../services/AuthenticationService';
class LoginPage extends React.Component<{}, {
username: string,
password: string,
submitted: boolean,
loading: boolean,
error: string,
success: boolean}> {
constructor(props: any) {
super(props);
this.state = {
username: '',
password: '',
submitted: false,
loading: false,
error: '',
success: false,
};
}
handleSubmit = (e: any) => {
e.preventDefault();
this.setState({submitted: true});
const { username, password } = this.state;
if (!(username && password)) {
return;
}
return AuthenticationService.login(new Credentials(username, password)).then(_ => {
this.setState({success: true})
});
};
handleChange = (e: any) => {
const { name, value } = e.target as {name: 'username' | 'password', value: string};
// @ts-ignore
this.setState({ [name]: value });
};
render() {
const { username, password, submitted, loading, error, success } = this.state;
if (success) {
return <Redirect to='/home'/>
}
return (
<div className="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" onSubmit={this.handleSubmit}>
<div className={'form-group' + (submitted && !username ? ' has-error' : '')}>
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name="username" value={username} onChange={this.handleChange} />
{submitted && !username &&
<div className="help-block">Username is required</div>
}
</div>
<div className={'form-group' + (submitted && !password ? ' has-error' : '')}>
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name="password" value={password} onChange={this.handleChange} />
{submitted && !password &&
<div className="help-block">Password is required</div>
}
</div>
<div className="form-group">
<button className="btn btn-primary" disabled={loading}>Submit</button>
</div>
</form>
</div>
);
}
}
export {LoginPage}
|
szgaljic/react-login
|
src/services/AuthenticationService.tsx
|
<filename>src/services/AuthenticationService.tsx
import {Credentials} from '../models/classes/Credentials';
import {RegisterDetails} from '../models/classes/RegisterDetails';
import {TokenDetails} from '../models/interfaces/TokenDetails';
import {UserDetails} from '../models/interfaces/UserDetails';
export const AuthenticationService = {
registerUser,
login,
getUser,
};
const SUCESSFUL_STATUSES = [201, 200];
const LOCAL_STORAGE_TOKEN_KEY = 'accessToken';
const ROOT_URL = 'http://localhost:5000/api/';
function saveToken(accessToken: string) {
localStorage.setItem(LOCAL_STORAGE_TOKEN_KEY, accessToken)
}
function getToken(): string | null {
return localStorage.getItem(LOCAL_STORAGE_TOKEN_KEY);
}
function login(credentials: Credentials) {
const requestOptions = {
method: 'GET',
headers: {Authorization: credentials.basicAuth},
};
return fetch(ROOT_URL + 'auth/token', requestOptions).then(res => {
if (SUCESSFUL_STATUSES.includes(res.status)) {
res.json().then((tokenDetails: TokenDetails) => {
saveToken(tokenDetails.token)
});
}
});
}
function registerUser(registrationDetails: RegisterDetails) {
const requestOptions = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(registrationDetails)
};
return fetch(ROOT_URL + 'registerUser', requestOptions).then(res => {});
}
function loggedInUser(token: string): Promise<UserDetails | null> {
const requestOptions = {
method: 'GET',
headers: {Authorization: 'Basic ' + btoa(token + ':')}
};
return fetch(ROOT_URL + 'users/me', requestOptions).then(res => {
if (SUCESSFUL_STATUSES.includes(res.status)) {
return res.json().then((userDetails: UserDetails) => userDetails)
}
return Promise.resolve(null)
});
}
function getUser(): Promise<UserDetails | null> | null {
const token = getToken();
if (token) {
return loggedInUser(token);
}
return null;
}
|
szgaljic/react-login
|
src/models/classes/Credentials.tsx
|
export class Credentials {
constructor(public username: string, private password: string) {}
get basicAuth(): string {
return 'Basic ' + btoa(this.username + ':' + this.password);
}
}
|
szgaljic/react-login
|
src/components/private-route/PrivateRoute.tsx
|
<gh_stars>0
import * as React from 'react';
import {Route, Redirect} from 'react-router-dom'
// @ts-ignore
export const PrivateRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={props => (
localStorage.getItem('accessToken') ? <Component {...props} /> :
<Redirect to={{ pathname: '/dashboard', state: {from: props.location} }}/>
)} />
);
|
szgaljic/react-login
|
src/models/interfaces/TokenDetails.tsx
|
<filename>src/models/interfaces/TokenDetails.tsx
export interface TokenDetails {
duration: number;
token: string;
}
|
szgaljic/react-login
|
src/models/classes/RegisterDetails.tsx
|
import {UserDetails} from '../interfaces/UserDetails';
export class RegisterDetails implements UserDetails {
constructor(public email: string, public username: string, private password: string, public type: string = 'user') {}
}
|
szgaljic/react-login
|
src/app/App.tsx
|
<filename>src/app/App.tsx
import * as React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import {Navbar} from '../components/navbar/Navbar';
import {PrivateRoute} from '../components/private-route/PrivateRoute';
import {HomePage} from '../components/home-page/HomePage';
import {LoginPage} from '../components/login-page/LoginPage';
import {RegistrationPage} from '../components/registration-page/RegistrationPage';
class App extends React.Component {
render(): React.ReactNode {
return (
<Router>
<div>
<Route path="/" component={Navbar}/>
<PrivateRoute exact path="/home" component={HomePage}/>
<Route exact path="/register" component={RegistrationPage} />
<Route exact path="/login" component={LoginPage} />
</div>
</Router>
);
}
}
export default App;
|
gastonrd7/influencers-models
|
src/index.ts
|
<gh_stars>0
enum DomainsEnum {
ADME_CORE = "ADME_CORE",
ADME_MONEY = "ADME_MONEY"
}
enum Model {
company = "company",
campaign = "campaign",
advertisement = "advertisement",
post = "post",
postExternal = "postExternal",
insight = "insight",
person = "person",
historic = "historic",
region = "region",
sex = "sex",
age = "age",
category = "category",
star = "star",
sponsorshipEffectiveness = "sponsorshipEffectiveness",
spotEffectiveness = "spotEffectiveness",
advertisingEffectiveness = "advertisingEffectiveness",
insightTypePrice = "insightTypePrice",
nationality = "nationality",
religion = "religion",
all = "*",
allModelAndAllField = ">",
permission_role = "permission_role",
permission = "permission",
person_company = "person_company",
role = "role",
person_credential = "person_credential",
people_relationship = "people_relationship",
referral = "referral",
trace = "trace",
webSession = "webSession",
socialMediaImplementation = "socialMediaImplementation",
fullStackWorkFlowState = "fullStackWorkFlowState",
termsAndConditions = "termsAndConditions",
payment = "payment",
transactionItem = "transactionItem",
transactionItemTransaction = "transactionItemTransaction",
transaction = "transaction"
}
enum transactionItemFields {
_id = "_id",
createdAt = "createdAt"
}
enum transactionItemTransactionFields {
_id = "_id",
createdAt = "createdAt"
}
enum transactionFields {
_id = "_id",
createdAt = "createdAt"
}
enum transactionItemTransaction {
_id = "_id",
}
enum paymentFields {
_id = "_id",
createdAt = "createdAt"
}
enum syncTradeTypeEnum {
PaymentToInfluencer = "PaymentToInfluencer",
PaymentToAdme = "PaymentToAdme",
PaymentToReferent = "PaymentToReferent",
PaymentFromReferred = "PaymentFromReferred",
DistributeToReferents = "DistributeToReferents",
CampaignPayed = "CampaignPayed",
TaxCollected = "TaxCollected",
TaxPayment = "TaxPayment",
WithdrawByShopping = "WithdrawByShopping"
}
enum syncFields {
syncDirection = "syncDirection",
syncFowardStatus = "syncFowardStatus",
syncForwardStatusDt = "syncForwardStatusDt",
syncParentDomain = "syncParentDomain",
syncParentModel = "syncParentModel",
syncParentEntityId = "syncParentEntityId",
originCampaignId = "originCampaignId",
originAdvertisementId = "originAdvertisementId",
originPostId = "originPostId",
originInsightId = "originInsightId",
tradeType = "tradeType",
amount = "amount"
}
enum syncFowardStatusEnum {
Pending = "Pending",
InProgress = "InProgress",
Failed = "Failed",
Done = "Done",
NotNeeded = "NotNeeded"
}
enum moneyDistributionStatusEnum {
WaitingForApproval = "WaitingForApproval",
Approved = "Approved",
Done = "Done",
Failed = "Failed"
}
enum syncDirectionEnum {
Up = "Up",
Injection = "Injection",
Ejection = "Ejection"
}
enum cronJobs {
SocialMedia_ReadInsights = "SocialMedia_ReadInsights",
SocialMedia_ReadRelationships = "SocialMedia_ReadRelationships",
Money_Ejection_From_Core_Advertisement_DistributeMoney = "Money_Ejection_From_Core_Advertisement_DistributeMoney",
Money_Ejection_From_Core_Insight_DistributeMoney = "Money_Ejection_From_Core_Insight_DistributeMoney",
Money_Ejection_From_Core_Payment_PayToInfluencer = "Money_Ejection_From_Core_Payment_PayToInfluencer",
Money_Ejection_From_Core_Payment_PayToAdme = "Money_Ejection_From_Core_Payment_PayToAdme",
Money_Ejection_From_Core_Payment_PayToReferent = "Money_Ejection_From_Core_Payment_PayToReferent",
Money_Ejection_From_Money_TransactionItem_PayTaxes = "Money_Ejection_From_Money_TransactionItem_PayTaxes",
Money_Injection_From_Core_Payment_CampaignPayed = "Money_Injection_From_Core_Payment_CampaignPayed",
Money_Injection_From_Money_TransactionItem_CampaignPayed = "Money_Injection_From_Money_TransactionItem_CampaignPayed",
Money_Injection_From_Money_TransactionItemTransaction_CampaignPayed = "Money_Injection_From_Money_TransactionItemTransaction_CampaignPayed",
Money_Injection_From_Money_TransactionItemTransaction_PayTaxes = "Money_Injection_From_Money_TransactionItemTransaction_PayTaxes",
Money_Injection_From_Money_TransactionItemTransaction_WithdrawByShopping = "Money_Injection_From_Money_TransactionItemTransaction_WithdrawByShopping",
Money_Up_From_Core_Payment_DistributeToReferents = "Money_Up_From_Core_Payment_DistributeToReferents"
}
enum messagingPayloadBaseFields {
_id = "_id",
eventUuid = 'eventUuid'
}
enum appTypes {
Web = "Web",
Mobile = "Mobile",
Feed = "Feed",
Others ="Others"
}
enum permission_roleFields {
_id = "_id",
roleId = "roleId",
permissionId = "permissionId",
creationDt = "creationDt"
}
enum permissionFields {
_id = "_id",
app = "app",
permission = "permission",
description = "description",
enabled = "enabled",
creationDt = "creationDt"
}
enum person_companyFields {
_id = "_id",
personId = "personId",
companyId = "companyId",
roleId = "roleId",
creationDt = "creationDt",
}
enum roleFields {
_id = "_id",
role = "role",
app = "app",
description = "description",
creationDt = "creationDt",
}
enum insightTypePriceFields {
_id = "_id",
name = "name",
thumbnail = "thumbnail",
price = "price"
}
enum regionFields {
_id = "_id",
country = "country",
state = "state",
city = "city",
iso2 = "iso2",
iso3 = "iso3",
personIds = "personIds",
thumbnail = "thumbnail",
geoPoint = "geoPoint"
}
enum nationalityFields {
_id = "_id",
name = "name",
personIds = "personIds",
geoPoint = "geoPoint"
}
enum religionFields {
_id = "_id",
name = "name",
personIds = "personIds"
}
enum sexFields {
_id = "_id",
name = "name",
personIds = "personIds"
}
enum ageFields {
_id = "_id",
age = "age",
personIds = "personIds"
}
enum categoryFields {
_id = "_id",
name = "name",
personIds = "personIds",
updatedDt = "updatedDt"
}
enum starFields {
_id = "_id",
stars = "stars",
customerPersonIds = "customerPersonIds",
platformPersonIds = "platformPersonIds"
}
enum insightTypeFields {
_id = "_id",
name = "name",
thumbnail = "thumbnail",
price = "price"
}
enum sponsorshipEffectivenessFields {
_id = "_id",
from = "from",
to = "to",
AdPrice = "AdPrice",
framePrice = "framePrice",
hashtagPrice = "hashtagPrice",
webSitePrice = "webSitePrice",
tagMentionMePrice = "tagMentionMePrice",
sealPrice = "sealPrice",
tagMentionPeoplePrice = "tagMentionPeoplePrice",
productUsagePrice = "productUsagePrice",
insightAveragePrice = "insightAveragePrice",
freezedBudget = "freezedBudget",
insightPriceFactor = "insightPriceFactor",
totalPrice = "totalPrice",
personIds = "personIds"
}
enum spotEffectivenessFields {
_id = "_id",
from = "from",
to = "to",
AdPrice = "AdPrice",
insightAveragePrice = "insightAveragePrice",
freezedBudget = "freezedBudget",
insightPriceFactor = "insightPriceFactor",
totalPrice = "totalPrice",
personIds = "personIds"
}
enum advertisingEffectivenessFields {
_id = "_id",
from = "from",
to = "to",
AdPrice = "AdPrice",
framePrice = "framePrice",
hashtagPrice = "hashtagPrice",
webSitePrice = "webSitePrice",
tagMentionMePrice = "tagMentionMePrice",
sealPrice = "sealPrice",
tagMentionPeoplePrice = "tagMentionPeoplePrice",
productUsagePrice = "productUsagePrice",
insightAveragePrice = "insightAveragePrice",
freezedBudget = "freezedBudget",
insightPriceFactor = "insightPriceFactor",
totalPrice = "totalPrice",
personIds = "personIds"
}
enum advertisementFields {
_id = "_id",
campaignId = "campaignId",
campaignName = "campaignName",
campaignType = "campaignType",
companyId = "companyId",
companyName = "companyName",
companyLogo = "companyLogo",
personId = "personId",
address_geoPoint = "address_geoPoint",
personGenre = "personGenre",
active = "active",
multimediaUri = "multimediaUri",
sponsored = "sponsored",
caption = "caption",
taggedPeople = "taggedPeople",
status = "status",
rejectionReason = "rejectionReason",
platformScore = "platformScore",
custumerScore = "custumerScore",
creationDt = "creationDt",
bannerIncluded = "bannerIncluded",
watermarkIncluded = "watermarkIncluded",
linkIncluded = "linkIncluded",
mentionToCompanyIncluded = "mentionIncluded",
hashtagIncluded = "hashtagIncluded",
mentionToOtherIncluded = "mentionToOtherIncluded",
productUsageIncluded = "productUsageIncluded",
productUsageOficialIncluded = "productUsageOficialIncluded",
engagementVelocityExpected = "engagementVelocityExpected",
engagementVelocityReal = "engagementVelocityReal",
budgetFreezed = "budgetFreezed",
moneyAvailable = "moneyAvailable",
moneyEarned = "moneyEarned",
zeroBudgetDt = "zeroBudgetDt",
advertisementPrice = "advertisementPrice",
resourceFramePrice = "resourceFramePrice",
resourceHashtagPrice = "resourceHashtagPrice",
resourceWebSitePrice = "resourceWebSitePrice",
resourceTagMentionMePrice = "resourceTagMentionMePrice",
resourceSealPrice = "resourceSealPrice",
resourceTagMentionPeoplePrice = "resourceTagMentionPeoplePrice",
resourceUsagePrice = "resourceProductUsagePrice",
resourceUsageOfficialPrice = "resourceUsageOfficialPrice",
socialMediaTarget = "socialMediaTarget",
facebookStatus = "facebookStatus",
facebookStatusDt = "facebookStatusDt",
instagramStatus = "instagramStatus",
instagramStatusDt = "instagramStatusDt",
twitterStatus = "twitterStatus",
twitterStatusDt = "twitterStatusDt",
tagPrice = "tagPrice",
tagCount = "tagCount",
likePrice = "likePrice",
likeCount = "likeCount",
sharedPrice = "sharedPrice",
sharedCount = "sharedCount",
linkPrice = "linkPrice",
linkCount = "linkCount",
printPrice = "printPrice",
printCount = "printCount",
mentionPrice = "mentionPrice",
mentionCount = "mentionCount",
hashtagPrice = "hashtagPrice",
hashtagCount = "hashtagCount",
commentPrice = "commentPrice",
commentCount = "commentCount",
notSponsoredTagCount = "notSponsoredTagCount",
notSponsoredLikeCount = "notSponsoredLikeCount",
notSponsoredSharedCount = "notSponsoredSharedCount",
notSponsoredLinkCount = "notSponsoredLinkCount",
notSponsoredPrintCount = "notSponsoredPrintCount",
notSponsoredMentionCount = "notSponsoredMentionCount",
notSponsoredHashtagCount = "notSponsoredHashtagCount",
notSponsoredCommentCount = "notSponsoredCommentCount",
facebookLikeCount = "facebookLikeCount",
facebookLinkCount = "facebookLinkCount",
facebookTagCount = "facebookTagCount",
facebookSharedCount = "facebookSharedCount",
facebookMentionCount = "facebookMentionCount",
facebookHashtagCount = "facebookHashtagCount",
facebookPrintCount = "facebookPrintCount",
facebookCommentCount = "facebookCommentCount",
twitterLikeCount = "twitterLikeCount",
twitterLinkCount = "twitterLinkCount",
twitterTagCount = "twitterTagCount",
twitterSharedCount = "twitterSharedCount",
twitterMentionCount = "twitterMentionCount",
twitterHashtagCount = "twitterHashtagCount",
twitterPrintCount = "twitterPrintCount",
twitterCommentCount = "twitterCommentCount",
instagramLikeCount = "instagramLikeCount",
instagramLinkCount = "instagramLinkCount",
instagramTagCount = "instagramTagCount",
instagramSharedCount = "instagramSharedCount",
instagramMentionCount = "instagramMentionCount",
instagramHashtagCount = "instagramHashtagCount",
instagramPrintCount = "instagramPrintCount",
instagramCommentCount = "instagramCommentCount",
resources = "resources",
moneyDistributionStatus = "moneyDistributionStatus"
}
enum advertisementStatusEnum {
NotSponsored = "NotSponsored",
WaitingForPlatformAudit = "WaitingForPlatformAudit",
WaitingForCustomerAudit = "WaitingForCustomerAudit",
RejectedByPlatform = "RejectedByPlatform",
RejectedByCustomer = "RejectedByCustomer",
Approved = "Approved"
}
enum postExternalFields {
advertisementId = "advertisementId",
platform = "platform",
platformObjectIdentity = "platformObjectIdentity"
}
enum postFields {
_id = "_id",
advertisementId = "advertisementId",
personId = "personId",
campaignId = "campaignId",
companyId = "companyId",
platform = "platform",
postPlatformId = "postPlatformId",
creationDt = "creationDt",
feedDt = "feedDt",
feedStatus = "feedStatus",
status = "status",
advertisementBudgetFreezed = "advertisementBudgetFreezed",
engagementVelocity = "engagementVelocity",
tagCount = "tagCount",
likeCount = "likeCount",
sharedCount = "sharedCount",
linkCount = "linkCount",
printCount = "printCount",
mentionCount = "mentionCount",
hashtagCount = "hashtagCount",
commentCount = "commentCount",
notSponsoredTagCount = "notSponsoredTagCount",
notSponsoredLikeCount = "notSponsoredLikeCount",
notSponsoredSharedCount = "notSponsoredSharedCount",
notSponsoredLinkCount = "notSponsoredLinkCount",
notSponsoredPrintCount = "notSponsoredPrintCount",
notSponsoredMentionCount = "notSponsoredMentionCount",
notSponsoredHashtagCount = "notSponsoredHashtagCount",
notSponsoredCommentCount = "notSponsoredCommentCount",
facebookLikeCount = "facebookLikeCount",
facebookLinkCount = "facebookLinkCount",
facebookTagCount = "facebookTagCount",
facebookSharedCount = "facebookSharedCount",
facebookMentionCount = "facebookMentionCount",
facebookHashtagCount = "facebookHashtagCount",
facebookPrintCount = "facebookPrintCount",
facebookCommentCount = "facebookCommentCount",
twitterLikeCount = "twitterLikeCount",
twitterLinkCount = "twitterLinkCount",
twitterTagCount = "twitterTagCount",
twitterSharedCount = "twitterSharedCount",
twitterMentionCount = "twitterMentionCount",
twitterHashtagCount = "twitterHashtagCount",
twitterPrintCount = "twitterPrintCount",
twitterCommentCount = "twitterCommentCount",
instagramLikeCount = "instagramLikeCount",
instagramLinkCount = "instagramLinkCount",
instagramTagCount = "instagramTagCount",
instagramSharedCount = "instagramSharedCount",
instagramMentionCount = "instagramMentionCount",
instagramHashtagCount = "instagramHashtagCount",
instagramPrintCount = "instagramPrintCount",
instagramCommentCount = "instagramCommentCount",
}
enum socialMediaStatusEnum {
None = "None",
PostRequired = "PostRequired",
Posting = "Posting",
Posted = "Posted",
Failed = "Failed",
Removed = "Removed",
}
enum feedStatusEnum {
Idle = "Idle",
Fetching = "Fetching",
Failed = "Failed"
}
enum historicFields {
_id = "_id",
model = "model",
field = "field",
entityId = "entityId",
value = "value",
creationDt = "creationDt"
}
enum insightFields {
_id = "_id",
postId = "postId",
platform = "platform",
advertisementId = "advertisementId",
campaignId = "campaignId",
platformObjectIdentity = "platformObjectIdentity",
companyId = "companyId",
address_geoPoint = "address_geoPoint",
genre = "genre",
genderId = "genderId",
birthDateYear = "birthDateYear",
birthDateMonth = "birthDateMonth",
birthDateDay = "birthDateDay",
type = "type",
moneyDistributionStatus = "moneyDistributionStatus",
creationDt = "creationDt",
}
enum insightGenreEnum {
Male = "Male",
Female = "Female",
Unknown = "Unknown"
}
enum insightTypeEnum {
Like = "Like",
Link = "Link",
Tag = "Tag",
Mention = "Mention",
Hashtag = "Hashtag",
Print = "Print",
Shared = "Shared",
Comment = "Comment",
Amazesme = 'Amazesme',
Iloveit = 'Iloveit',
Ienjoy = 'Ienjoy',
Angersme = 'Angersme',
Icare = 'Icare',
Saddensme = 'Saddensme'
}
enum resourceTypeEnum {
frame = "frame",
hashtag = "hashtag",
webSite = "webSite",
tagMentionMe = "tagMentionMe",
seal = "seal",
tagMentionPeople = "tagMentionPeople",
productUsage = "productUsage",
spot = "spot"
}
enum person_credentialFields {
_id = "_id",
personId = "personId",
platform = "platform",
friendsFeedDt = "friendsFeedDt",
friendsFeedStatus = "friendsFeedStatus",
platformObjectIdentity = "platformObjectIdentity",
status = "status",
displayName = "displayName",
access_token = "access_token",
expires = "expires",
userName = "userName",
password = "password",
picture = "picture",
birthday = "birthday",
firstName = "firstName",
lastName = "lastName",
email = "email",
verTermsAndConditions = "verTermsAndConditions",
creationDt = "creationDt",
enabled = "enabled"
}
enum person_credential_statusEnum {
NOT_LINKED = "NOT_LINKED",
LINKING = "LINKING",
LINKED = "LINKED",
FAILED = "FAILED",
EXPIRED = "EXPIRED",
MANUAL_ACTION_REQUIRED = "MANUAL_ACTION_REQUIRED",
TERMS_SIGNATURE_REQUIRED = "TERMS_SIGNATURE_REQUIRED"
}
enum person_credential_statusEnumDescription {
NOT_LINKED = "Not linked yet!",
LINKING = "Linking...",
LINKED = "Linked",
FAILED = "Process has failed",
EXPIRED = "Expired",
MANUAL_ACTION_REQUIRED = "Manual action is required",
TERMS_SIGNATURE_REQUIRED = "Terms signature is required"
};
enum platformEnum {
Facebook = "Facebook",
Twitter = "Twitter",
Instagram = "Instagram"
}
enum companyFields {
_id = "_id",
name = "name",
logo = "logo",
active = "active",
campaignsOnGoingCount = "campaignsOnGoingCount",
campaignsWaitingForApprovalCount = "campaignsWaitingForApprovalCount",
campaignsPendingForApprovalCount = "campaignsPendingForApprovalCount",
campaignsFinishedCount = "campaignsFinishedCount",
campaignsWaitingForPaymentCount = "campaignsWaitingForPaymentCount",
campaignsStoppedCount = "campaignsStoppedCount",
campaignsDraftCount = "campaignsDraftCount",
moneyPerEngagementExpected = "moneyPerEngagementExpected",
moneyPerEngagementReal = "moneyPerEngagementReal",
investment = "investment",
budgetAvailable = "budgetAvailable",
budgetFreezed = "budgetFreezed",
budgetSpent = "budgetSpent",
platformStars = "platformStars",
customerStars = "customerStars"
}
enum people_relationshipFields {
_id = "_id",
personId = "personId",
platformObjectIdentity = "platformObjectIdentity",
platform = "platform",
relationship = "relationship",
invitationStatus = "invitationStatus",
creationDt = "creationDt"
}
enum people_relationshipEnum {
FRIEND_OF = "FRIEND_OF",
FOLLOWS_TO = "FOLLOWS_TO",
FOLLOWED_BY = "FOLLOWED_BY"
}
enum campaignInfluencePeopleAsEnum {
IR = "IR",
ID = "ID"
}
enum personAvailableCampaignFields {
_id = "_id",
companyId = "companyId",
companyName = "companyName",
companyLogo = "companyLogo",
companyPlatformStars = "companyPlatformStars",
companyCustomerStars = "companyCustomerStars",
name = "name",
type = "type",
slogan = "slogan",
brief = "brief",
resources = "resources",
paymentType = "paymentType",
specificTarget = "specificTarget",
categoryCriterias = "categoryCriterias"
}
enum campaignFields {
_id = "_id",
companyId = "companyId",
companyName = "companyName",
companyLogo = "companyLogo",
companyPlatformStars = "companyPlatformStars",
companyCustomerStars = "companyCustomerStars",
name = "name",
slogan = "slogan",
brief = "brief",
specificTarget = "specificTarget",
influencePeopleAs = "influencePeopleAs",
influencerPerEachOfThem = "influencerPerEachOfThem",
followers = "followers",
type = "type",
paymentType = "paymentType",
paymentStatus = "paymentStatus",
productPaymentDescription = "productPaymentDescription",
paymentPerEach = "paymentPerEach",
regionCriterias = "regionCriterias",
regionScope = "regionScope",
nationalityCriterias = "nationalityCriterias",
nationalityScope = "nationalityScope",
religionCriterias = "religionCriterias",
religionScope = "religionScope",
sexCriterias = "sexCriterias",
sexScope = "sexScope",
adsPerIR = "adsPerIR",
resources = "resources",
nextStatuses = "nextStatuses",
customerStarCriterias = "customerStarCriterias",
platformStarCriterias = "platformStarCriterias",
customerStarScope = "customerStarScope",
platformStarScope = "platformStarScope",
sponsorshipEffectivenessCriterias = "sponsorshipEffectivenessCriterias",
sponsorshipEffectivenessScope = "sponsorshipEffectivenessScope",
sponsorshipEffectivenessScopeAll = "sponsorshipEffectivenessScopeAll",
spotEffectivenessCriterias = "spotEffectivenessCriterias",
spotEffectivenessScope = "spotEffectivenessScope",
spotEffectivenessScopeAll = "spotEffectivenessScopeAll",
advertisingEffectivenessCriterias = "advertisingEffectivenessCriterias",
advertisingEffectivenessScope = "advertisingEffectivenessScope",
advertisingEffectivenessScopeAll = "advertisingEffectivenessScopeAll",
categoryCriterias = "categoryCriterias",
categoryScope = "categoryScope",
ageCriterias = "ageCriterias",
ageScope = "ageScope",
specificTargetScope = "specificTargetScope",
regionCriteriaUpdatedDt = "regionCriteriaUpdatedDt",
nationalityCriteriaUpdatedDt = "nationalityCriteriaUpdatedDt",
religionCriteriaUpdatedDt = "religionCriteriaUpdatedDt",
ageCriteriaUpdatedDt = "ageCriteriaUpdatedDt",
sexCriteriaUpdatedDt = "sexCriteriaUpdatedDt",
customerStarCriteriaUpdatedDt = "customerStarCriteriaUpdatedDt",
platformStarCriteriaUpdatedDt = "platformStarCriteriaUpdatedDt",
sponsorshipEffectivenessCriteriaUpdatedDt = "sponsorshipEffectivenessCriteriaUpdatedDt",
spotEffectivenessCriteriaUpdatedDt = "spotEffectivenessCriteriaUpdatedDt",
advertisingEffectivenessCriteriaUpdatedDt = "advertisingEffectivenessCriteriaUpdatedDt",
categoryCriteriaUpdatedDt = "categoryCriteriaUpdatedDt",
endDt = "endDt",
startDt = "startDt",
active = "active",
status = "status",
investment = "investment",
budgetAvailable = "budgetAvailable",
budgetFreezed = "budgetFreezed",
budgetSpent = "budgetSpent",
moneyPerEngagementExpected = "moneyPerEngagementExpected",
moneyPerEngagementReal = "moneyPerEngagementReal",
engagementReal = "engagementReal",
engagementExpected = "engagementExpected",
influencersExpected = "influencersExpected",
engagementVelocityReal = "engagementVelocityReal",
engagementVelocityExpected = "engagementVelocityExpected",
forecastDays = "forecastDays",
influencersScope = "influencersScope",
influencedScopeCount = "influencedScopeCount",
influencedExtraScopeCount = "influencedExtraScopeCount",
influencersScopeCount = "influencersScopeCount",
engagementScopeCount = "engagementScopeCount",
influencersScopeAll = "influencersScopeAll",
peopleCollectionUpdateDt = "peopleCollectionUpdateDt",
creationDt = "creationDt",
engagementFacebook = "engagementFacebook",
engagementInstagram = "engagementInstagram",
engagementTwitter = "engagementTwitter",
tagCount = "tagCount",
likeCount = "likeCount",
sharedCount = "sharedCount",
linkCount = "linkCount",
printCount = "printCount",
mentionCount = "mentionCount",
hashtagCount = "hashtagCount",
commentCount = "commentCount",
engagementNotSponsored = "engagementNotSponsored",
engagementMaleInfluencer = "engagementMaleInfluencer",
engagementFemaleInfluencer = "engagementFemaleInfluencer",
engagementMaleInfluenced = "engagementMaleInfluenced",
engagementFemaleInfluenced = "engagementFemaleInfluenced",
engagementAnonymousInfluenced = "engagementAnonymousInfluenced",
investmentRequired = "investmentRequired",
influencersTotal = "influencersTotal",
influencersTotalHistoric = "influencersTotalHistoric",
engagementRealHistoric = "engagementRealHistoric",
engagementNotSponsoredTotalHistory = "engagementNotSponsoredTotalHistory",
facebookLikeCount = "facebookLikeCount",
facebookLinkCount = "facebookLinkCount",
facebookTagCount = "facebookTagCount",
facebookSharedCount = "facebookSharedCount",
facebookMentionCount = "facebookMentionCount",
facebookHashtagCount = "facebookHashtagCount",
facebookPrintCount = "facebookPrintCount",
facebookCommentCount = "facebookCommentCount",
twitterLikeCount = "twitterLikeCount",
twitterLinkCount = "twitterLinkCount",
twitterTagCount = "twitterTagCount",
twitterSharedCount = "twitterSharedCount",
twitterMentionCount = "twitterMentionCount",
twitterHashtagCount = "twitterHashtagCount",
twitterPrintCount = "twitterPrintCount",
twitterCommentCount = "twitterCommentCount",
instagramLikeCount = "instagramLikeCount",
instagramLinkCount = "instagramLinkCount",
instagramTagCount = "instagramTagCount",
instagramSharedCount = "instagramSharedCount",
instagramMentionCount = "instagramMentionCount",
instagramHashtagCount = "instagramHashtagCount",
instagramPrintCount = "instagramPrintCount",
instagramCommentCount = "instagramCommentCount",
facebookMaleInfluencerCount = "facebookMaleInfluencerCount",
facebookFemaleInfluencerCount = "facebookFemaleInfluencerCount",
facebookMaleInfluencedCount = "facebookMaleInfluencedCount",
facebookAnonymousInfluencedCount = "facebookAnonymousInfluencedCount",
facebookFemaleInfluencedCount = "facebookFemaleInfluencedCount",
twitterMaleInfluencerCount = "twitterMaleInfluencerCount",
twitterFemaleInfluencerCount = "twitterFemaleInfluencerCount",
twitterMaleInfluencedCount = "twitterMaleInfluencedCount",
twitterAnonymousInfluencedCount = "twitterAnonymousInfluencedCount",
twitterFemaleInfluencedCount = "twitterFemaleInfluencedCount",
instagramMaleInfluencerCount = "instagramMaleInfluencerCount",
instagramFemaleInfluencerCount = "instagramFemaleInfluencerCount",
instagramMaleInfluencedCount = "instagramMaleInfluencedCount",
instagramAnonymousInfluencedCount = "instagramAnonymousInfluencedCount",
instagramFemaleInfluencedCount = "instagramFemaleInfluencedCount",
facebookMaleInfluencerCardinal = "facebookMaleInfluencerCardinal",
facebookFemaleInfluencerCardinal = "facebookFemaleInfluencerCardinal",
twitterMaleInfluencerCardinal = "twitterMaleInfluencerCardinal",
twitterFemaleInfluencerCardinal = "twitterFemaleInfluencerCardinal",
instagramMaleInfluencerCardinal = "instagramMaleInfluencerCardinal",
instagramFemaleInfluencerCardinal = "instagramFemaleInfluencerCardinal",
facebookMaleInfluencedCardinal = "facebookMaleInfluencedCardinal",
facebookFemaleInfluencedCardinal = "facebookFemaleInfluencedCardinal",
twitterMaleInfluencedCardinal = "twitterMaleInfluencedCardinal",
twitterFemaleInfluencedCardinal = "twitterFemaleInfluencedCardinal",
instagramMaleInfluencedCardinal = "instagramMaleInfluencedCardinal",
instagramFemaleInfluencedCardinal = "instagramFemaleInfluencedCardinal",
facebookInfluencedsCardinal = "facebookInfluencedsCardinal",
facebookInfluencersCardinal = "facebookInfluencersCardinal",
instagramInfluencedsCardinal = "instagramInfluencedsCardinal",
instagramInfluencersCardinal = "instagramInfluencersCardinal",
twitterInfluencedsCardinal = "twitterInfluencedsCardinal",
twitterInfluencersCardinal = "twitterInfluencersCardinal"
}
enum campaignPaymentStatusEnum {
Done = "Done",
Pending = "Pending",
Failed = "Failed"
}
enum campaignSpecificTargetScopeFields {
personId = "personId",
firstName = "firstName",
lastName = "lastName",
key = "key",
sponsorshipEffectiveness = "sponsorshipEffectiveness",
spotEffectiveness = "spotEffectiveness",
advertisingEffectiveness = "advertisingEffectiveness"
}
enum itemMoment {
timespan = "timespan",
value = "value"
}
enum genreType {
Male = "Male",
Female = "Female"
}
enum coordinate {
value = "value"
}
enum campaignStatusEnum {
PreDraft = "PreDraft",
Draft = "Draft",
OnGoing = "OnGoing",
WaitingForPayment = "WaitingForPayment",
WaitingForApproval = "WaitingForApproval",
Stopped = "Stopped",
Finished = "Finished"
}
enum campaignTypeEnum {
Spot = "Spot",
Sponsorship = "Sponsorship",
Advertising = "Advertising"
}
enum campaignPaymentTypeEnum {
Money = "Money",
Product = "Product"
}
enum personFields {
_id = "_id",
username = "username",
password = "password",
referentCode = "referentCode",
signUpReferentPersonId = "signUpReferentPersonId",
roleIds = "roleIds",
firstName = "firstName",
lastName = "lastName",
email = "email",
nationality = "nationality",
religion = "religion",
thumbnail = "thumbnail",
genre = "genre",
genderId = "genderId",
birthDateYear = "birthDateYear",
birthDateMonth = "birthDateMonth",
birthDateDay = "birthDateDay",
age = "age",
facebookId = "facebookId",
instagramId = "instagramId",
twitterId = "twitterId",
key = "key",
categories = "categories",
customerStars = "customerStars",
platformStars = "platformStars",
sponsorshipEffectiveness = "sponsorshipEffectiveness",
sponsorshipFreezedBudgetReference = "sponsorshipFreezedBudgetReference",
sponsorshipEffectivenessReference = "sponsorshipEffectivenessReference",
spotEffectiveness = "spotEffectiveness",
spotFreezedBudgetReference = "spotFreezedBudgetReference",
spotEffectivenessReference = "spotEffectivenessReference",
advertisingEffectiveness = "advertisingEffectiveness",
advertisingFreezedBudgetReference = "advertisingFreezedBudgetReference",
advertisingEffectivenessReference = "advertisingEffectivenessReference",
countryId = "countryId",
stateId = "stateId",
address_regionId = "address_regionId",
address_street = "address_street",
address_postalCode = "address_postalCode",
address_geoPoint = "address_geoPoint",
sponsorshipCampaignsUpdatedDt = "sponsorshipCampaignsUpdatedDt",
advertisingCampaignsUpdatedDt = "advertisingCampaignsUpdatedDt",
spotCampaignsUpdatedDt = "spotCampaignsUpdatedDt",
sponsorshipCampaigns = "sponsorshipCampaigns",
spotCampaigns = "spotCampaigns",
advertisingCampaigns = "advertisingCampaigns",
sponsorshipCampaignsCount = "sponsorshipCampaignsCount",
advertisingCampaignsCount = "advertisingCampaignsCount",
spotCampaignsCount = "spotCampaignsCount",
referralsUpdateDt = "referralsUpdateDt",
referralsCount = "referralsCount",
referralClanCount = "referralClanCount",
referralTitheTotal = "referralTitheTotal",
nonSponsoredAdsCount = "nonSponsoredAdsCount",
sponsorshipAdsCount = "sponsorshipAdsCount",
sponsorshipEarnedMoneyTotal = "sponsorshipEarnedMoneyTotal",
spotAdsCount = "spotAdsCount",
spotEarnedMoneyTotal = "spotEarnedMoneyTotal",
advertisingAdsCount = "advertisingAdsCount",
advertisingEarnedMoneyTotal = "advertisingEarnedMoneyTotal",
influencerCategory = "influencerCategory",
sponsorshipCampaignCategories = "sponsorshipCampaignCategories",
spotCampaignCategories = "spotCampaignCategories",
advertisingCampaignCategories = "advertisingCampaignCategories",
potentialReferralsUpdatedDt = "potentialReferralsUpdatedDt",
potentialReferrals = "potentialReferrals",
socialMediaAccountsReadyToUse = "socialMediaAccountsReadyToUse"
}
enum personPotentialReferralsFields {
status = "status",
potentialReferral = "potentialReferral"
}
enum People_relationshipInvitationStatusEnum {
DIDNOTSEND = "DIDNOTSEND",
SENT = "SENT",
ACCEPTED = "ACCEPTED",
REJECTED = "REJECTED"
}
enum influencerCategoryEnum {
KING = "KING",
QUEEN = "QUEEN",
PRINCE = "PRINCE",
PRINCESS = "PRINCESS",
DUKE = "DUKE",
DUCHESS = "DUCHESS",
PEASANT = "PEASANT"
}
enum nationalityEnum {
Argentina = "Argentina",
EstadosUnidos = "EstadosUnidos",
Venezuela = "Venezuela",
Colombia = "Colombia"
}
enum religionEnum {
Cristiana = "Cristiana",
Judia = "Judia",
Indu = "Indu",
Protestante = "Protestante"
}
enum referralFields {
_id = "_id",
referentPersonId = "referentPersonId",
referralPersonId = "referralPersonId",
titheTotal = "titheTotal",
creationDt = "creationDt",
referralFirstName = "referralFirstName",
referralLastName = "referralLastName",
referralThumbnail = "referralThumbnail",
referralCustomerStars = "referralCustomerStars",
referralPlatformStars = "referralPlatformStars",
referralReferralsCount = "referralReferralsCount",
referralReferralClanCount = "referralReferralClanCount",
referralInfluencerCategory = "referralInfluencerCategory",
referralNonSponsoredAdsCount = "referralNonSponsoredAdsCount",
referralSponsorshipAdsCount = "referralSponsorshipAdsCount",
referralAdvertisingAdsCount = "referralAdvertisingAdsCount",
referralSpotAdsCount = "referralSpotAdsCount"
}
enum appTypeEnum {
Web = "Web",
Mobile = "Mobile",
Feed = "Feed",
Others = "Others"
}
enum traceFields {
_id = "_id",
traceId = "traceId",
traceUseCase = "traceUseCase",
traceCauseOnOrigin = "traceCauseOnOrigin",
traceOriginModel = "traceOriginModel",
traceOriginModelId = "traceOriginModelId",
traceOriginModelField = "traceOriginModelField",
traceConsecuenceOnDestination = "traceConsecuenceOnDestination",
traceHandler = "traceHandler",
traceHandlerExecutionId = "traceHandlerExecutionId",
traceDestinationModel = "traceDestinationModel",
traceDestinationModelId = "traceDestinationModelId",
traceDestinationModelField = "traceDestinationModelField",
traceCreatedAt = "traceCreatedAt",
}
enum webSessionFields {
_id = "_id",
browser = "browser",
domain = "domain",
personId = "personId",
cookies = "cookies",
createdAt = "createdAt"
}
enum webSessionDomainEnum {
Chrome = "Chrome",
Firefox = "Firefox",
Edge = "Edge",
Safari = "Safari"
}
enum languagesEnum {
English = "English",
Spanish = "Spanish"
}
enum socialMediaImplementationFields {
_id = "_id",
platform = "platform",
method = "method",
failuresCount = "failuresCount",
methodVersion = "methodVersion",
createdAt = "createdAt"
}
enum fullStackWorkFlowStateFields{
_id = "_id",
personUserName = "personUserName",
key = "key",
state = "state",
payload = "payload",
lastUpdateDt = "lastUpdateDt"
}
enum socialMediaAuthenticationValuesWorkFlowStateEnum{
STARTED = "STARTED",
CANCELED = "CANCELED",
NONE = "NONE",
EMAIL_SAME_CODE_NEEDED = "EMAIL_SAME_CODE_NEEDED",
EMAIL_SAME_CODE_NEEDED_PROVIDED = "EMAIL_SAME_CODE_NEEDED_PROVIDED",
EMAIL_NEW_CODE_NEEDED = "EMAIL_NEW_CODE_NEEDED",
EMAIL_NEW_CODE_NEEDED_PROVIDED = "EMAIL_NEW_CODE_NEEDED_PROVIDED",
SMS_NEW_CODE_NEEDED = "SMS_NEW_CODE_NEEDED",
SMS_NEW_CODE_NEEDED_PROVIDED = "SMS_NEW_CODE_NEEDED_PROVIDED",
SMS_SAME_CODE_NEEDED = "SMS_SAME_CODE_NEEDED",
SMS_SAME_CODE_NEEDED_PROVIDED = "SMS_SAME_CODE_NEEDED_PROVIDED",
INVALID_CREDENTIALS = "INVALID_CREDENTIALS",
INVALID_CREDENTIALS_PROVIDED = "INVALID_CREDENTIALS_PROVIDED",
SUCCESS = "SUCCESS",
FAIL = "FAIL"
}
enum socialMediaAuthenticationKeysWorkFlowStateEnum{
LINK_STATE = "LINK_STATE"
}
enum termsAndConditionsFields{
_id = "_id",
platform = "platform",
version = "version",
status = "status",
lastUpdateDt = "lastUpdateDt"
}
enum termsAndConditionsStatusEnum{
DEVELOPING = "DEVELOPING",
INREVIEW = "INREVIEW",
PENDINGAPPROVAL = "PENDINGAPPROVAL",
APPROVED = "APPROVED",
DISMISSED = "DISMISSED",
EXPIRED = "EXPIRED",
NONE = "NONE"
}
export {
DomainsEnum,
Model,
appTypes,
permission_roleFields,
permissionFields,
person_companyFields,
roleFields,
insightTypePriceFields,
regionFields,
nationalityFields,
religionFields,
sexFields,
ageFields,
categoryFields,
starFields,
insightTypeFields,
sponsorshipEffectivenessFields,
spotEffectivenessFields,
advertisingEffectivenessFields,
advertisementFields,
postExternalFields,
postFields,
feedStatusEnum,
historicFields,
insightFields,
insightTypeEnum,
resourceTypeEnum,
companyFields,
campaignFields,
campaignSpecificTargetScopeFields,
itemMoment,
genreType,
coordinate,
campaignStatusEnum,
campaignTypeEnum,
campaignPaymentTypeEnum,
personFields,
appTypeEnum,
person_credentialFields,
people_relationshipFields,
campaignInfluencePeopleAsEnum,
socialMediaStatusEnum,
person_credential_statusEnum,
person_credential_statusEnumDescription,
platformEnum,
people_relationshipEnum,
influencerCategoryEnum,
referralFields,
nationalityEnum,
religionEnum,
advertisementStatusEnum,
personAvailableCampaignFields,
insightGenreEnum,
personPotentialReferralsFields,
People_relationshipInvitationStatusEnum,
traceFields,
webSessionFields,
webSessionDomainEnum,
languagesEnum,
socialMediaImplementationFields,
socialMediaAuthenticationValuesWorkFlowStateEnum,
socialMediaAuthenticationKeysWorkFlowStateEnum,
fullStackWorkFlowStateFields,
termsAndConditionsFields,
termsAndConditionsStatusEnum,
messagingPayloadBaseFields,
syncFields,
syncFowardStatusEnum,
syncDirectionEnum,
cronJobs,
paymentFields,
syncTradeTypeEnum,
transactionItemFields,
transactionItemTransaction,
moneyDistributionStatusEnum,
campaignPaymentStatusEnum,
transactionItemTransactionFields,
transactionFields
};
|
healer1064/Gimbal
|
packages/gimbal-core/src/components/Table/index.ts
|
<reponame>healer1064/Gimbal
import { TableInstanceOptions } from 'cli-table3';
import { Column, Config, Data, Finder, Renders } from '@/typings/components/Table';
import cliRenderer from './renderer/cli';
import htmlRenderer from './renderer/html';
import markdownRenderer from './renderer/markdown';
class Table {
private columns: Column[] = [];
private data: Data[] = [];
private options?: TableInstanceOptions;
public constructor(config?: Config) {
if (config) {
if (config.columns) {
this.columns = config.columns;
}
if (config.data) {
this.data = config.data;
}
if (config.options) {
this.options = config.options;
}
}
}
public addColumn(column: Column, index?: number): void {
const { columns } = this;
if (index == null) {
columns.push(column);
} else {
columns.splice(index, 0, column);
}
}
public getColumn(index: number): Column | void {
return this.columns[index];
}
public findColumn(callback: Finder, getIndex = false): Column | number | void {
if (getIndex) {
return this.columns.findIndex(callback);
}
return this.columns.find(callback);
}
public removeColumn(column: Column): void {
const { columns } = this;
const index = columns.indexOf(column);
if (index !== -1) {
columns.splice(index, 1);
}
}
public add(item: Data, index?: number): void {
const { data } = this;
if (index == null) {
data.push(item);
} else {
data.splice(index, 0, item);
}
}
public find(callback: Finder, getIndex = false): Data | number | void {
if (getIndex) {
return this.data.findIndex(callback);
}
return this.data.find(callback);
}
public get(index: number): Data | void {
return this.data[index];
}
public remove(item: Data): void {
const { data } = this;
const index = data.indexOf(item);
if (index !== -1) {
data.splice(index, 1);
}
}
public set(data: Data[]): void {
this.data = data;
}
public render(type: Renders): Promise<string> {
const { columns, data, options } = this;
switch (type) {
case 'cli':
return cliRenderer({ columns, data, options });
case 'markdown':
return markdownRenderer({ columns, data, options });
case 'html':
return htmlRenderer({ columns, data, options });
default:
return Promise.resolve('');
}
}
}
export default Table;
|
healer1064/Gimbal
|
packages/gimbal-core/src/logger/cli.ts
|
// @ts-ignore
import Spinnies from 'spinnies';
import { SpinniesConfig, SpinniesFinish, SpinniesOptions } from '@/typings/logger';
export const createSpinner = (options?: SpinniesConfig): Spinnies => new Spinnies(options);
export const spinnies = createSpinner();
const parseSpinnerOptions = (options: string | SpinniesOptions | SpinniesFinish): SpinniesOptions | SpinniesFinish =>
typeof options === 'string' ? { text: options } : options;
export const addSpinner = (name: string, options: string | SpinniesOptions): void => {
const spinnerOptions: SpinniesOptions = parseSpinnerOptions(options);
if (spinnerOptions.status === 'stopped') {
spinnerOptions.text = ` ${spinnerOptions.text}`;
}
spinnies.add(name, spinnerOptions);
};
export const getSpinner = (name: string): SpinniesOptions => spinnies.pick(name);
export const updateSpinner = (name: string, options: string | SpinniesOptions): void => {
const oldOptions: SpinniesOptions = getSpinner(name);
const spinnerOptions: SpinniesOptions = parseSpinnerOptions(options);
if (oldOptions && oldOptions.status === 'stopped' && spinnerOptions.status !== 'stopped') {
spinnerOptions.text = spinnerOptions.text.replace(/^\s+/, '');
}
spinnies.update(name, spinnerOptions);
};
export const startSpinner = (name: string): void => {
const spinnerOptions: SpinniesOptions = {
...getSpinner(name),
status: 'spinning',
};
updateSpinner(name, spinnerOptions);
};
export const finishSpinner = (name: string, success: boolean, output: string, text = ''): void => {
const oldOptions: SpinniesOptions = getSpinner(name);
const newText = oldOptions.text.replace(/^\s+/, '');
const spinnerOptions: SpinniesFinish = {
...parseSpinnerOptions(text),
text: `${newText} - ${success ? 'Success!' : 'Failed!'} - ${output}`,
};
if (success) {
spinnies.succeed(name, spinnerOptions);
} else {
spinnies.fail(name, spinnerOptions);
}
};
|
healer1064/Gimbal
|
packages/gimbal/src/ci/index.ts
|
<gh_stars>100-1000
import Config from '@/config';
import { Cls } from '@/typings/ci';
import CircleCICls from './CircleCI';
import GitHubActionsCls from './GitHubActions';
import TravisCICls from './TravisCI';
export const CircleCI = 'CircleCI';
export const GitHubActions = 'GitHubActions';
export const TravisCI = 'TravisCI';
export type CIs = CircleCICls | GitHubActionsCls | TravisCICls;
let ci: CIs | void;
interface Tests {
[label: string]: Cls;
}
interface CIConfig {
provider: string;
}
const tests: Tests = {
[CircleCI]: CircleCICls,
[GitHubActions]: GitHubActionsCls,
[TravisCI]: TravisCICls,
};
const normalizeConfiguredCI = (configuredCI?: string | CIConfig): CIConfig | void => {
if (configuredCI) {
return typeof configuredCI === 'string' ? { provider: configuredCI } : configuredCI;
}
return undefined;
};
const whichCI = (): CIs | void => {
if (ci) {
return ci;
}
const configuredCI = normalizeConfiguredCI(Config.get('configs.ci'));
const CI = configuredCI ? configuredCI.provider : Object.keys(tests).find((key: string): boolean => tests[key].is());
switch (CI) {
case CircleCI:
ci = new CircleCICls();
return ci;
case GitHubActions:
ci = new GitHubActionsCls();
return ci;
case TravisCI:
ci = new TravisCICls();
return ci;
default:
return undefined;
}
};
export default whichCI;
|
healer1064/Gimbal
|
packages/gimbal-core/src/utils/Queue.spec.ts
|
import Queue from './Queue';
describe('@modus/gimbal-core/utils/Queue', (): void => {
describe('add', (): void => {
it('should add to the queue', async (): Promise<void> => {
const instance = new Queue();
const spy = jest.fn();
instance.add(spy);
await instance.run();
expect(spy).toHaveBeenCalled();
});
it('should add multiple to the queue', async (): Promise<void> => {
const instance = new Queue();
const spy1 = jest.fn();
const spy2 = jest.fn();
instance.add(spy1, spy2);
await instance.run();
expect(spy1).toHaveBeenCalled();
expect(spy2).toHaveBeenCalled();
});
});
describe('run', (): void => {
describe('sequential', (): void => {
it('should run in sequence', async (): Promise<void> => {
const instance = new Queue();
const spy1 = jest.fn().mockResolvedValue('first');
const spy2 = jest.fn().mockResolvedValue('second');
instance.add(spy1, spy2);
const ret = await instance.run('data');
expect(ret).toEqual(['first', 'second']);
expect(spy1).toHaveBeenCalledWith('data');
expect(spy2).toHaveBeenCalledWith('data');
});
});
describe('parallel', (): void => {
it('should run in parallel', async (): Promise<void> => {
const instance = new Queue({
mode: 'parallel',
});
const spy1 = jest.fn().mockResolvedValue('first');
const spy2 = jest.fn().mockResolvedValue('second');
instance.add(spy1, spy2);
const ret = await instance.run('data');
expect(ret).toEqual(['first', 'second']);
expect(spy1).toHaveBeenCalledWith('data');
expect(spy2).toHaveBeenCalledWith('data');
});
});
});
});
|
healer1064/Gimbal
|
packages/gimbal/src/command/index.ts
|
<filename>packages/gimbal/src/command/index.ts
import program, { Command as CommandType } from 'commander';
import Config from '@/config';
import EventEmitter from '@/event';
import Logger from '@/logger';
import output from '@/output';
import { StartEvent, EndEvent, ActionStartEvent, ActionEndEvent, Report } from '@/typings/command';
import { CommandOptions } from '@/typings/utils/command';
import { getOptionsFromCommand } from '@/utils/command';
import comment from '@/vcs/comment';
import reconcileReports from './reconcile';
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
type Action = (commandOptions: CommandOptions, args?: string[]) => Promise<any>;
type DefaultValueFn = (options: CommandOptions) => CommandOptions;
interface Option {
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
defaultValue?: any | DefaultValueFn;
description?: string;
flag: string;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
process?: ((arg1: any, arg2: any) => void) | RegExp;
}
interface Config {
action: Action;
command: string;
}
class Command {
private action: Action;
private command: string;
public constructor(config: Config) {
this.action = config.action;
this.command = config.command;
}
public async run(args: string[] = []): Promise<void> {
try {
const commandOptions = getOptionsFromCommand(program, undefined, Config);
const startEvent: StartEvent = {
args,
commandOptions,
command: this,
};
await EventEmitter.fire(`command/${this.command}/start`, startEvent);
if (!Config.isLoaded) {
await Config.load(commandOptions.cwd, commandOptions);
}
const actionStartEvent: ActionStartEvent = {
args,
commandOptions,
command: this,
};
await EventEmitter.fire(`command/${this.command}/action/start`, actionStartEvent);
const reports: Report | Report[] = await this.action(commandOptions, args);
const report: Report = reconcileReports(reports);
const actionEndEvent: ActionEndEvent = {
args,
commandOptions,
command: this,
report,
};
await EventEmitter.fire(`command/${this.command}/action/end`, actionEndEvent);
await output(report, commandOptions);
await comment(report, commandOptions);
const endEvent: EndEvent = {
args,
commandOptions,
command: this,
report,
};
await EventEmitter.fire(`command/${this.command}/end`, endEvent);
if (!report.success) {
process.exit(1);
}
} catch (error) {
Logger.log(error);
process.exit(1);
}
}
}
export const preparseOptions = (): CommandOptions => {
const parsed = program.parseOptions(program.normalize(process.argv.slice(2)));
const match =
parsed.args[0] && program.commands.find((command: CommandType): boolean => command.name() === parsed.args[0]);
const cmd = match || program;
if (!match && parsed.args[0]) {
Logger.log(`The "${parsed.args[0]}" command was not found`);
}
cmd.parseOptions(parsed.args); // this applies option values onto the command/program
return getOptionsFromCommand(cmd, undefined, Config);
};
export default Command;
|
healer1064/Gimbal
|
packages/gimbal-core/src/logger/index.ts
|
import isCI from 'is-ci';
import { finishSpinner as finishSpinnerCI, startSpinner as startSpinnerCI } from './ci';
import { addSpinner as addSpinnerCLI, finishSpinner as finishSpinnerCLI, startSpinner as startSpinnerCLI } from './cli';
import { SpinniesOptions } from '@/typings/logger';
interface SpinnerTimes {
[name: string]: [number, number];
}
const spinnerTimes: SpinnerTimes = {};
export const addSpinner = (name: string, options: string | SpinniesOptions): void =>
isCI ? undefined : addSpinnerCLI(name, options);
export const startSpinner = (name: string): void => {
spinnerTimes[name] = process.hrtime();
if (isCI) {
startSpinnerCI(name);
} else {
startSpinnerCLI(name);
}
};
export const finishSpinner = (name: string, success: boolean, text = ''): void => {
const end = process.hrtime(spinnerTimes[name]);
const nanoseconds = end[0] * 1e9 + end[1];
const milliseconds = nanoseconds / 1e6;
const output = `${milliseconds.toLocaleString()} ms`;
delete spinnerTimes[name];
if (isCI) {
finishSpinnerCI(name, success, output);
} else if (success) {
finishSpinnerCLI(name, success, output, text);
}
};
|
healer1064/Gimbal
|
packages/gimbal/src/command/audit/index.ts
|
import { addSpinner, finishSpinner, startSpinner } from '@modus/gimbal-core/lib/logger';
import { resolvePath } from '@modus/gimbal-core/lib/utils/fs';
import findPort from '@modus/gimbal-core/lib/utils/port';
import Queue from '@modus/gimbal-core/lib/utils/Queue';
import Config from '@/config';
import Chrome from '@/module/chrome';
import { get, getMeta } from '@/module/registry';
import Serve from '@/module/serve';
import { Report, ReportItem } from '@/typings/command';
import { Modules } from '@/typings/module';
import { CommandOptions } from '@/typings/utils/command';
// register built-in modules
import '@/module/heap-snapshot/register';
import '@/module/lighthouse/register';
import '@/module/size/register';
import '@/module/unused-source/register';
interface AuditOptions {
chrome: Chrome;
url: string;
}
const didAuditPass = (report?: Report): boolean => !report || report.success;
const doAudit = async (options: AuditOptions, audits: Modules[], commandOptions: CommandOptions): Promise<Report> => {
const rets: ReportItem[] = [];
let success = true;
await Promise.all(
audits.map(
async (audit: string): Promise<void> => {
const mod = get(audit);
if (!mod) {
finishSpinner(audit, false, `"${mod}" was not found in the module registry`);
throw new Error(`"${mod}" was not found in the module registry`);
}
startSpinner(audit);
const report = await mod({
commandOptions,
...options,
});
if (report) {
if (!report.success) {
success = false;
}
if (report.data) {
rets.push(...report.data);
}
}
const succeed = didAuditPass(report);
finishSpinner(audit, succeed);
},
),
);
return {
data: rets,
success,
};
};
const audit = async (options: CommandOptions): Promise<Report | Report[]> => {
let audits: Modules[] = Config.get('audits');
if (!audits || !audits.length) {
/**
* This block is more for backwards compatibility. If the `gimbal audit`
* command was executed and there isn't the `audits` config, we can fall
* back on the old way using the cli options that opts out.
*/
audits = audits ? [...audits] : [];
if (options.calculateUnusedSource) {
audits.push('unused-source');
}
if (options.heapSnapshot) {
audits.push('heap-snapshot');
}
if (options.lighthouse) {
audits.push('lighthouse');
}
if (options.size) {
audits.push('size');
}
}
const servePort = await findPort();
const buildDir = resolvePath(options.cwd, options.buildDir as string);
const serve = new Serve({ port: servePort, public: buildDir });
const chrome = new Chrome();
let report: Report | Report[];
if (serve) {
await serve.start();
}
if (chrome) {
await chrome.launch();
}
if (Array.isArray(options.route)) {
const queue = new Queue();
options.route.forEach((route: string, index: number): void => {
const filteredAudits = audits.filter((name: string): boolean => {
const meta = getMeta(name);
if (meta && meta.maxNumRoutes && index >= meta.maxNumRoutes) {
return false;
}
return true;
});
if (filteredAudits.length) {
filteredAudits.forEach((name: string): void =>
addSpinner(name, { status: 'stopped', text: `[ ${name} ] - ${route}` }),
);
queue.add(
(): Promise<Report> =>
doAudit(
{
chrome,
url: `http://localhost:${servePort}${route}`,
},
filteredAudits,
{
...options,
route,
},
),
);
}
});
report = (await queue.run()) as Report[];
} else {
audits.forEach((name: string): void => addSpinner(name, `[ ${name} ]`));
report = await doAudit(
{
chrome,
url: `http://localhost:${servePort}${options.route}`,
},
audits,
options,
);
}
if (chrome) {
await chrome.kill();
}
if (serve) {
await serve.stop();
}
return report;
};
export default audit;
|
healer1064/Gimbal
|
packages/gimbal/src/index.ts
|
<reponame>healer1064/Gimbal
import fs from 'fs';
import path from 'path';
import program from 'commander';
import readPkg from 'read-pkg';
import updateNotifier from 'update-notifier';
import { preparseOptions } from '@/command';
import audit from '@/command/audit/program';
import Config from '@/config';
import processAudits from '@/config/audits';
import processJobs from '@/config/jobs';
import Logger, { setFromConfigs } from '@/logger';
import { CHILD_GIMBAL_PROCESS } from '@/utils/constants';
(async (): Promise<void> => {
const isBuilt = path.extname(__filename) === '.js';
if (!process.env[CHILD_GIMBAL_PROCESS]) {
const gimbal = fs.readFileSync(path.join(__dirname, 'ascii_art/gimbal.txt'), 'utf8');
/* eslint-disable-next-line no-console */
console.log(gimbal);
}
const packageJson = await readPkg({
cwd: isBuilt ? path.join(__dirname, '../../..') : path.join(__dirname, '..'),
});
program
.version(packageJson.version)
.description('A CLI tool for monitoring web performance in modern web projects')
// global options all command will receive
.option('--cwd [dir]', 'The directory to work in. Defaults to where the command was executed from.', process.cwd())
.option('--config [file]', 'The file to load as the configuration file.')
.option('--no-comment', 'Set to disable commenting results on the VCS')
.option('--no-check-thresholds', 'Set to disable checking thresholds.')
.option('--output-html [file]', 'The path to write the results as HTML to.')
.option('--output-json [file]', 'The path to write the results as JSON to.')
.option('--output-markdown [file]', 'The path to write the results as Markdown to.')
.option('--verbose', 'Turn on extra logging during command executions.')
// audit options
.option(
'--build-dir <dir>',
'Directory storing the build artifacts relative to the --cwd (defaults to "build")',
'build',
)
.option('--no-size', 'Disable checking resource sizes')
.option('--no-calculate-unused-source', 'Disable calculating unused CSS and JavaScript')
.option('--no-heap-snapshot', 'Disable getting a heap snapshot')
.option('--no-lighthouse', 'Disable the lighthouse auditing')
.option('--lighthouse-output-html <file>', 'Location to output the lighthouse HTML report to.')
.option(
'--route <route>',
'Route to run tests on.',
(value: string, previous: string | string[]): string[] => {
// means previous is just the defaultValue
if (!Array.isArray(previous)) {
return [value];
}
previous.push(value);
return previous;
},
'/',
);
// backwards compat so `gimbal audit` doesn't fail, we handle it below
program.command('audit');
// need to parse the options before commander kicks off so the config file
// is loaded. This way things like plugins will be ready
const options = preparseOptions();
try {
const config = await Config.load(options.cwd, options);
setFromConfigs();
// Notify of new package
updateNotifier({ pkg: packageJson }).notify();
// kick off commander
program.parse(process.argv);
if (config) {
const { audits, jobs } = config;
if (jobs && jobs.length) {
await processJobs(jobs, options);
} else if (audits && audits.length) {
await processAudits();
} else {
// no jobs so there is nothing to execute
// so let's show the help screen
program.help();
}
} else {
await audit.run();
}
Logger.log('Finished successfully');
process.exit(0);
} catch (e) {
Logger.log(e);
Logger.log('Finished with failure');
process.exit(1);
}
})();
|
healer1064/Gimbal
|
packages/typings/vcs/comment/index.d.ts
|
<reponame>healer1064/Gimbal
import { CIs } from '@/ci';
import GitHub from '@/vcs/GitHub';
import { Report, ReportItem } from '@/typings/command';
import { CommandOptions } from '@/typings/utils/command';
export interface CommentBuildStartEvent {
ci: CIs;
report: Report;
vcs: GitHub;
}
export interface CommentBuildEndEvent extends CommentBuildStartEvent {
markdown: string;
}
export interface CommentRenderTableStartEvent {
commandOptions: CommandOptions;
reportItem: ReportItem;
}
export interface CommentRenderTableEndEvent extends CommentRenderTableStartEvent {
renderedTable: string;
}
export interface CommentStartEvent {
ci: CIs;
comment: string;
report: Report;
vcs: GitHub;
}
export interface CommentEndEvent extends CommentStartEvent {
comment: string;
}
export interface CommentObject {
onlyFailures?: boolean;
}
export type Comment = boolean | CommentObject;
|
healer1064/Gimbal
|
packages/gimbal/src/module/unused-source/output.ts
|
import { Report, ReportItem } from '@/typings/command';
import { Entry } from '@/typings/module/unused-source';
import { CommandOptions } from '@/typings/utils/command';
const type = 'unused-source';
const parseReport = (raw: Entry[], options: CommandOptions): Report => {
const { checkThresholds } = options;
const success: boolean = !checkThresholds || raw.every((entry: Entry): boolean => entry.success);
const data: ReportItem[] = raw.map(
(entry: Entry): ReportItem => ({
label: entry.url,
// raw: entry,
rawLabel: entry.url,
rawThreshold: entry.threshold,
rawValue: entry.unusedPercentage,
success: entry.success,
threshold: entry.threshold,
thresholdLimit: 'lower',
value: entry.unusedPercentage,
type,
}),
);
return {
data: [
{
data,
label: 'Unused Source Checks',
rawLabel: 'Unused Source Checks',
success,
type,
},
],
// raw,
success,
};
};
export default parseReport;
|
healer1064/Gimbal
|
packages/typings/module/size/index.d.ts
|
<filename>packages/typings/module/size/index.d.ts
import { Report } from '@/typings/command';
import { CommandOptions } from '@/typings/utils/command';
export interface SizeConfigs {
maxSize: string;
path: string;
type?: string;
}
export interface SizeConfig {
compression?: 'brotli' | 'gzip';
threshold: SizeConfigs[];
}
export interface FileResult {
filePath: string;
isDirectory: boolean;
maxSizeBytes: number;
maxSize: string;
sizeBytes: number;
size: string;
thresholdPath: string;
}
export interface AuditStartEvent {
config: SizeConfig;
options: CommandOptions;
}
export interface AuditEndEvent {
audit: FileResult[];
config: SizeConfig;
options: CommandOptions;
}
export interface ReportStartEvent {
audit: FileResult[];
config: SizeConfig;
options: CommandOptions;
}
export interface ReportEndEvent {
audit: FileResult[];
config: SizeConfig;
options: CommandOptions;
report: Report;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.