repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
super-effective/colorutil
|
src/tests/rgbToCmyk.test.ts
|
import rgbToCmyk from '../rgbToCmyk';
import {
CMYK_BLACK,
CMYK_BLUE,
CMYK_GREEN,
CMYK_RED,
CMYK_TEAL,
RGB_BLACK,
RGB_BLUE,
RGB_GREEN,
RGB_RED,
RGB_TEAL,
} from './data/colors';
/**
* RGB to CMYK
*/
describe('rgbToCmyk', () => {
test('rgbToCmyk - multi value', () => {
const teal = rgbToCmyk(RGB_TEAL.red, RGB_TEAL.green, RGB_TEAL.blue);
expect(teal).toStrictEqual(CMYK_TEAL);
});
test('rgbToCmyk - red', () => {
const red = rgbToCmyk(RGB_RED.red, RGB_RED.green, RGB_RED.blue);
expect(red).toStrictEqual(CMYK_RED);
});
test('rgbToCmyk - green', () => {
const green = rgbToCmyk(RGB_GREEN.red, RGB_GREEN.green, RGB_GREEN.blue);
expect(green).toStrictEqual(CMYK_GREEN);
});
test('rgbToCmyk - blue', () => {
const blue = rgbToCmyk(RGB_BLUE.red, RGB_BLUE.green, RGB_BLUE.blue);
expect(blue).toStrictEqual(CMYK_BLUE);
});
test('rgbToCmyk - black', () => {
const black = rgbToCmyk(RGB_BLACK.red, RGB_BLACK.green, RGB_BLACK.blue);
expect(black).toStrictEqual(CMYK_BLACK);
});
});
|
super-effective/colorutil
|
src/tests/hexToHsv.test.ts
|
import hexToHsv from '../hexToHsv';
import {
HEX_TEAL,
HSV_TEAL,
HSV_WHITE,
HEX_WHITE,
HSV_BLACK,
HEX_BLACK,
HEX_RED,
HSV_RED,
HEX_YELLOW,
HSV_YELLOW,
HEX_GREEN,
HSV_GREEN,
HEX_CYAN,
HSV_CYAN,
HEX_BLUE,
HSV_BLUE,
HEX_MAGENTA,
HSV_MAGENTA,
} from './data/colors';
/**
* HEX to HSV
*/
describe('hexToHsv', () => {
test('hexToHsv - color', () => {
const teal = hexToHsv(HEX_TEAL);
expect(teal).toStrictEqual(HSV_TEAL);
});
test('hexToHsv - white short', () => {
const white = hexToHsv('#fff');
expect(white).toStrictEqual(HSV_WHITE);
});
test('hexToHsv - white long', () => {
const white = hexToHsv(HEX_WHITE);
expect(white).toStrictEqual(HSV_WHITE);
});
test('hexToHsv - black short', () => {
const white = hexToHsv('#000');
expect(white).toStrictEqual(HSV_BLACK);
});
test('hexToHsv - black long', () => {
const white = hexToHsv(HEX_BLACK);
expect(white).toStrictEqual(HSV_BLACK);
});
test('hexToHsv - short length throws an error', () => {
expect(() => hexToHsv('#00')).toThrow(Error);
});
test('hexToHsv - long length throws an error', () => {
expect(() => hexToHsv('#0000000')).toThrow(Error);
});
test('hexToHsv - invalid hex', () => {
expect(() => hexToHsv('#j@0000')).toThrow(Error);
});
test('hexToHsv - red', () => {
const teal = hexToHsv(HEX_RED);
expect(teal).toStrictEqual(HSV_RED);
});
test('hexToHsv - yellow', () => {
const teal = hexToHsv(HEX_YELLOW);
expect(teal).toStrictEqual(HSV_YELLOW);
});
test('hexToHsv - green', () => {
const teal = hexToHsv(HEX_GREEN);
expect(teal).toStrictEqual(HSV_GREEN);
});
test('hexToHsv - cyan', () => {
const teal = hexToHsv(HEX_CYAN);
expect(teal).toStrictEqual(HSV_CYAN);
});
test('hexToHsv - blue', () => {
const teal = hexToHsv(HEX_BLUE);
expect(teal).toStrictEqual(HSV_BLUE);
});
test('hexToHsv - magenta', () => {
const teal = hexToHsv(HEX_MAGENTA);
expect(teal).toStrictEqual(HSV_MAGENTA);
});
});
|
super-effective/colorutil
|
src/tests/getPerceivedLuminance.test.ts
|
<reponame>super-effective/colorutil
import getPerceivedLuminance from '../getPerceivedLuminance';
import {
RGB_TEAL,
RGB_WHITE,
RGB_BLACK,
} from './data/colors';
/**
* Get Perceptive Luminesces
*/
describe('getPerceivedLuminance', () => {
test('getPerceivedLuminance - color', () => {
const pl = getPerceivedLuminance(RGB_TEAL.red, RGB_TEAL.green, RGB_TEAL.blue);
expect(pl).toBe(0.6483607843137255);
});
test('getPerceivedLuminance - white', () => {
const pl = getPerceivedLuminance(RGB_WHITE.red, RGB_WHITE.green, RGB_WHITE.blue);
expect(pl).toBe(1);
});
test('getPerceivedLuminance - black', () => {
const pl = getPerceivedLuminance(RGB_BLACK.red, RGB_BLACK.green, RGB_BLACK.blue);
expect(pl).toBe(0);
});
});
|
super-effective/colorutil
|
src/tests/cmykToRgb.test.ts
|
<reponame>super-effective/colorutil
import cmykToRgb from '../cmykToRgb';
import {
CMYK_BLACK,
CMYK_BLUE,
CMYK_GREEN,
CMYK_RED,
CMYK_TEAL,
RGB_BLACK,
RGB_BLUE,
RGB_GREEN,
RGB_RED,
RGB_TEAL,
} from './data/colors';
/**
* CMYK to RGB
*/
describe('cmykToRgb', () => {
test('cmykToRgb - multi value', () => {
const teal = cmykToRgb(CMYK_TEAL.cyan, CMYK_TEAL.magenta, CMYK_TEAL.yellow, CMYK_TEAL.black);
expect(teal).toStrictEqual(RGB_TEAL);
});
test('cmykToRgb - red', () => {
const red = cmykToRgb(CMYK_RED.cyan, CMYK_RED.magenta, CMYK_RED.yellow, CMYK_RED.black);
expect(red).toStrictEqual(RGB_RED);
});
test('cmykToRgb - green', () => {
const green = cmykToRgb(CMYK_GREEN.cyan, CMYK_GREEN.magenta, CMYK_GREEN.yellow, CMYK_GREEN.black);
expect(green).toStrictEqual(RGB_GREEN);
});
test('cmykToRgb - blue', () => {
const blue = cmykToRgb(CMYK_BLUE.cyan, CMYK_BLUE.magenta, CMYK_BLUE.yellow, CMYK_BLUE.black);
expect(blue).toStrictEqual(RGB_BLUE);
});
test('cmykToRgb - black', () => {
const black = cmykToRgb(CMYK_BLACK.cyan, CMYK_BLACK.magenta, CMYK_BLACK.yellow, CMYK_BLACK.black);
expect(black).toStrictEqual(RGB_BLACK);
});
});
|
super-effective/colorutil
|
src/tests/hslToHex.test.ts
|
<gh_stars>1-10
import hslToHex from '../hslToHex';
import {
HEX_TEAL,
HEX_WHITE,
HEX_BLACK,
HSL_BLACK,
HSL_RED,
HSL_TEAL,
HSL_WHITE,
} from './data/colors';
/**
* HSL to HEX
*/
describe('hslToHex', () => {
test('hslToHex - color', () => {
const teal = hslToHex(HSL_TEAL.hue, HSL_TEAL.saturation, HSL_TEAL.lightness);
expect(teal).toBe(HEX_TEAL);
});
test('hslToHex - white', () => {
const white = hslToHex(HSL_WHITE.hue, HSL_WHITE.saturation, HSL_WHITE.lightness);
expect(white).toBe(HEX_WHITE);
});
test('hslToHex - black', () => {
const black = hslToHex(HSL_BLACK.hue, HSL_BLACK.saturation, HSL_BLACK.lightness);
expect(black).toBe(HEX_BLACK);
});
// Bounds checks
test('hslToHex - invalid hue, < 0', () => {
expect(() => hslToHex(-1, HSL_RED.saturation, HSL_RED.lightness)).toThrow(Error);
});
test('hslToHex - invalid hue, > 1', () => {
expect(() => hslToHex(361, HSL_RED.saturation, HSL_RED.lightness)).toThrow(Error);
});
test('hslToHex - invalid saturation, < 0', () => {
expect(() => hslToHex(HSL_RED.hue, -1, HSL_RED.lightness)).toThrow(Error);
});
test('hslToHex - invalid saturation, > 1', () => {
expect(() => hslToHex(HSL_RED.hue, 1.1, HSL_RED.lightness)).toThrow(Error);
});
test('hslToHex - invalid value, < 0', () => {
expect(() => hslToHex(HSL_RED.hue, HSL_RED.saturation, -1)).toThrow(Error);
});
test('hslToHex - invalid value, > 1', () => {
expect(() => hslToHex(HSL_RED.hue, HSL_RED.saturation, 1.1)).toThrow(Error);
});
});
|
super-effective/colorutil
|
src/tests/sanitizeHex.test.ts
|
import sanitizeHex from '../sanitizeHex';
import { HEX_BLACK } from './data/colors';
/**
* Sanitize Hex String
*/
describe('sanitizeHex', () => {
test('sanitizeHex - clean input', () => {
const validHex = '#ffffff';
const sanitizedHex = sanitizeHex(validHex);
expect(sanitizedHex).toStrictEqual(validHex);
});
test('sanitizeHex - empty', () => {
const empty = '';
const sanitizedHex = sanitizeHex(empty);
expect(sanitizedHex).toStrictEqual(HEX_BLACK);
});
test('sanitizeHex - 1 character', () => {
const one = '1';
const sanitizedHex = sanitizeHex(one);
expect(sanitizedHex).toStrictEqual('#111111');
});
test('sanitizeHex - 2 characters', () => {
const two = '12';
const sanitizedHex = sanitizeHex(two);
expect(sanitizedHex).toStrictEqual('#111222');
});
test('sanitizeHex - 3 characters', () => {
const three = '123';
const sanitizedHex = sanitizeHex(three);
expect(sanitizedHex).toStrictEqual('#112233');
});
test('sanitizeHex - 4 characters', () => {
const four = '1234';
const sanitizedHex = sanitizeHex(four);
expect(sanitizedHex).toStrictEqual('#112233');
});
test('sanitizeHex - > 6 characters', () => {
const tooLong = '#cedefffffffffe123';
const sanitizedHex = sanitizeHex(tooLong);
expect(sanitizedHex).toStrictEqual('#cedeff');
});
test('sanitizeHex - invalid chars', () => {
const invalidAtStart = 'Z`*(;3#%^21|/"32&1';
const sanitizedHex = sanitizeHex(invalidAtStart);
expect(sanitizedHex).toStrictEqual('#321321');
});
});
|
super-effective/colorutil
|
src/colorutils.ts
|
export {
Rgb,
Hsv,
} from './colorTypes';
export { default as cmykToRgb } from './cmykToRgb';
export { default as cmykToHex } from './cmykToHex';
export { default as getPerceivedLuminance } from './getPerceivedLuminance';
export { default as hexToCmyk } from './hexToCmyk'
export { default as hexToHsl } from './hexToHsl';
export { default as hexToHsv } from './hexToHsv';
export { default as hexToRgb } from './hexToRgb';
export { default as hslToHex } from './hslToHex';
export { default as hslToRgb } from './hslToRgb';
export { default as hsvToHex } from './hsvToHex';
export { default as hsvToRgb } from './hsvToRgb';
export { default as rgbToCmyk } from './rgbToCmyk';
export { default as rgbToHex } from './rgbToHex';
export { default as rgbToHsl } from './rgbToHsl';
export { default as rgbToHsv } from './rgbToHsv';
export { default as sanitizeHex } from './sanitizeHex';
|
zhangtao07/amis
|
examples/components/theme/crud.tsx
|
/**
* 给自定义组件预览用的 CRUD
*/
export default {
type: 'crud',
syncLocation: false,
data: {
items: [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
platform: 'Win 95+',
version: '4',
id: 1
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.0',
platform: 'Win 95+',
id: 2
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.5',
platform: 'Win 95+',
id: 3
},
{
engine: 'Trident',
browser: 'Internet Explorer 6',
platform: 'Win 98+',
id: 4
},
{
engine: 'Trident',
browser: 'Internet Explorer 7',
platform: 'Win XP SP2+',
id: 5
},
{
engine: 'Trident',
browser: 'AOL browser (AOL desktop)',
platform: 'Win XP',
id: 6
}
]
},
source: '${items}',
columns: [
{
name: 'id',
label: 'ID'
},
{
name: 'engine',
label: 'Rendering engine'
},
{
name: 'browser',
label: 'Browser'
},
{
name: 'platform',
label: 'Platform(s)'
}
]
};
|
zhangtao07/amis
|
src/actions/ContinueAction.ts
|
import { RendererEvent } from '../utils/renderer-event';
import {
RendererAction,
ListenerContext,
LoopStatus,
registerAction,
ILogicAction
} from './Action';
export interface IContinueAction extends ILogicAction {
actionType: 'continue';
}
/**
* continue
*
* @export
* @class ContinueAction
* @implements {Action}
*/
export class ContinueAction implements RendererAction {
async run(
action: IContinueAction,
renderer: ListenerContext,
event: RendererEvent<any>
) {
renderer.loopStatus = LoopStatus.CONTINUE;
}
}
registerAction('continue', new ContinueAction());
|
zhangtao07/amis
|
src/actions/AjaxAction.ts
|
<reponame>zhangtao07/amis
import omit from 'lodash/omit';
import {Api} from '../types';
import {normalizeApiResponseData} from '../utils/api';
import {ServerError} from '../utils/errors';
import {createObject, isEmpty} from '../utils/helper';
import {RendererEvent} from '../utils/renderer-event';
import {
RendererAction,
ListenerAction,
ListenerContext,
registerAction
} from './Action';
export interface IAjaxAction extends ListenerAction {
action: 'ajax';
args: {
api: Api;
messages?: {
success: string;
failed: string;
};
options?: Record<string, any>;
[propName: string]: any;
};
}
/**
* 发送请求动作
*
* @export
* @class AjaxAction
* @implements {Action}
*/
export class AjaxAction implements RendererAction {
async run(
action: IAjaxAction,
renderer: ListenerContext,
event: RendererEvent<any>
) {
if (!renderer.props.env?.fetcher) {
throw new Error('env.fetcher is required!');
}
const env = event.context.env;
try {
const result = await env.fetcher(
action.args?.api as string,
omit(action.args ?? {}, ['api', 'options', 'messages']),
action.args?.options ?? {}
);
if (!isEmpty(result.data) || result.ok) {
const responseData = normalizeApiResponseData(result.data);
// 记录请求返回的数据
event.setData(
createObject(
event.data,
action.outputVar
? {
[`${action.outputVar}`]: responseData
}
: responseData
)
);
}
if (!result.ok) {
throw new ServerError(
action.args?.messages?.failed ?? result.msg,
result
);
} else {
const msg = action.args?.messages?.success ?? result.msg;
msg &&
env.notify(
'success',
msg,
result.msgTimeout !== undefined
? {
closeButton: true,
timeout: result.msgTimeout
}
: undefined
);
}
return result.data;
} catch (e) {
if (e.type === 'ServerError') {
const result = (e as ServerError).response;
env.notify(
'error',
e.message,
result.msgTimeout !== undefined
? {
closeButton: true,
timeout: result.msgTimeout
}
: undefined
);
} else {
env.notify('error', e.message);
}
// 不阻塞后面执行
// throw e;
}
}
}
registerAction('ajax', new AjaxAction());
|
zhangtao07/amis
|
examples/components/theme/form.tsx
|
<reponame>zhangtao07/amis
/**
* @file 用于主题预览的表单样式
*/
export default {
type: 'form',
title: '表单项',
mode: 'horizontal',
wrapWithPanel: false,
autoFocus: true,
body: [
{
type: 'group',
body: [
{
type: 'input-text',
name: 'var1',
label: '输入框'
},
{
type: 'input-number',
name: 'number',
label: '数字',
placeholder: '',
inline: true,
value: 5,
min: 1,
max: 10
}
]
},
{
type: 'group',
body: [
{
type: 'input-tag',
name: 'tag',
label: '标签',
placeholder: '',
clearable: true,
// dropdown: false, 保留原来的展现方式。
// size: 'md',
// inline: true,
options: [
{
label: '诸葛亮',
value: 'zhugeliang'
},
{
label: '曹操',
value: 'caocao'
},
{
label: '钟无艳',
value: 'zhongwuyan'
},
{
label: '野核',
children: [
{
label: '李白',
value: 'libai'
},
{
label: '韩信',
value: 'hanxin'
},
{
label: '云中君',
value: 'yunzhongjun'
}
]
}
]
},
{
type: 'input-text',
disabled: true,
name: 'disabled',
label: '禁用状态',
placeholder: '这里禁止输入内容'
}
]
},
{
type: 'group',
body: [
{
type: 'input-text',
name: 'text-sug',
label: '文本提示',
options: ['lixiaolong', 'zhouxingxing', 'yipingpei', 'liyuanfang'],
addOn: {
type: 'input-text',
label: '$'
}
},
{
type: 'input-text',
name: 'text-sug-multiple',
label: '文本提示多选',
multiple: true,
options: ['lixiaolong', 'zhouxingxing', 'yipingpei', 'liyuanfang']
}
]
},
{
type: 'button-toolbar',
label: '按钮',
buttons: [
{
type: 'action',
label: '默认'
},
{
type: 'action',
label: '信息',
level: 'info'
},
{
type: 'action',
label: '主要',
level: 'primary'
},
{
type: 'action',
label: '次要',
level: 'secondary'
},
{
type: 'action',
label: '成功',
level: 'success'
},
{
type: 'action',
label: '警告',
level: 'warning'
},
{
type: 'action',
label: '危险',
level: 'danger'
},
{
type: 'action',
label: '浅色',
level: 'light'
},
{
type: 'action',
label: '深色',
level: 'dark'
},
{
type: 'action',
label: '链接',
level: 'link'
}
]
},
{
type: 'group',
body: [
{
type: 'radios',
name: 'radios',
label: '单选',
value: 3,
options: [
{
label: '选项1',
value: 1
},
{
label: '选项2',
value: 2
},
{
label: '选项3',
disabled: true,
value: 3
}
]
},
{
type: 'checkboxes',
name: 'checkboxes',
label: '多选框',
value: 3,
options: [
{
label: '选项1',
value: 1
},
{
label: '选项2',
value: 2
},
{
label: '选项3',
disabled: true,
value: 3
}
]
}
]
},
{
type: 'group',
body: [
{
type: 'switch',
name: 'switch',
onText: '开',
offText: '关',
label: '开关'
},
{
type: 'switch',
name: 'switch2',
value: true,
label: '开关开启'
},
{
type: 'switch',
name: 'switch3',
value: true,
disabled: true,
label: '开关禁用'
}
]
},
{
type: 'group',
body: [
{
type: 'button-group-select',
name: 'btn-group',
label: '按钮组',
options: [
{
label: '选项 A',
value: 1
},
{
label: '选项 B',
value: 2
},
{
label: '选项 C',
value: 3
}
]
},
{
type: 'list-select',
name: 'List',
label: 'List',
options: [
{
label: '选项 A',
value: 1
},
{
label: '选项 B',
value: 2
},
{
label: '选项 C',
value: 3
}
]
}
]
},
{
type: 'group',
body: [
{
type: 'select',
name: 'type',
label: '单选',
inline: true,
options: [
{
label: '选项1',
value: 1
},
{
label: '选项2',
value: 2
}
]
},
{
type: 'select',
name: 'type2',
label: '多选',
multiple: true,
inline: true,
options: [
{
label: '选项1',
value: 1
},
{
label: '选项2',
value: 2
}
]
}
]
},
{
type: 'group',
body: [
{
type: 'input-date',
name: 'date',
inline: true,
label: '日期'
},
{
type: 'input-time',
name: 'time',
inline: true,
label: '时间'
}
]
},
{
type: 'input-date-range',
name: 'daterangee',
inline: true,
label: '时间范围'
},
{
type: 'input-group',
size: 'sm',
inline: true,
label: 'Icon 组合',
body: [
{
type: 'icon',
addOnclassName: 'no-bg',
className: 'text-sm',
icon: 'search'
// "vendor": "iconfont"
},
{
type: 'input-text',
placeholder: '搜索作业ID/名称',
inputClassName: 'b-l-none p-l-none',
name: 'jobName'
}
]
},
{
type: 'input-tree',
name: 'tree',
label: '树',
options: [
{
label: 'Folder A',
value: 1,
children: [
{
label: 'file A',
value: 2
},
{
label: 'file B',
value: 3
}
]
},
{
label: 'file C',
value: 4
},
{
label: 'file D',
value: 5
}
]
},
{
type: 'group',
body: [
{
type: 'input-tree',
name: 'trees',
label: '树多选',
multiple: true,
options: [
{
label: 'Folder A',
value: 1,
children: [
{
label: 'file A',
value: 2
},
{
label: 'file B',
value: 3
}
]
},
{
label: 'file C',
value: 4
},
{
label: 'file D',
value: 5
}
]
},
{
type: 'nested-select',
name: 'nestedSelect',
label: '级联选择器',
options: [
{
label: '概念',
value: 'concepts',
children: [
{
label: '配置与组件',
value: 'schema'
},
{
label: '数据域与数据链',
value: 'scope'
},
{
label: '模板',
value: 'template'
},
{
label: '数据映射',
value: 'data-mapping'
},
{
label: '表达式',
value: 'expression'
},
{
label: '联动',
value: 'linkage'
},
{
label: '行为',
value: 'action'
},
{
label: '样式',
value: 'style'
}
]
},
{
label: '类型',
value: 'types',
children: [
{
label: 'SchemaNode',
value: 'schemanode'
},
{
label: 'API',
value: 'api'
},
{
label: 'Definitions',
value: 'definitions'
}
]
},
{
label: '组件',
value: 'zujian',
children: [
{
label: '布局',
value: 'buju',
children: [
{
label: 'Page 页面',
value: 'page'
},
{
label: 'Container 容器',
value: 'container'
},
{
label: 'Collapse 折叠器',
value: 'Collapse'
}
]
},
{
label: '功能',
value: 'gongneng',
children: [
{
label: 'Action 行为按钮',
value: 'action-type'
},
{
label: 'App 多页应用',
value: 'app'
},
{
label: 'Button 按钮',
value: 'button'
}
]
},
{
label: '数据输入',
value: 'shujushuru',
children: [
{
label: 'Form 表单',
value: 'form'
},
{
label: 'FormItem 表单项',
value: 'formitem'
},
{
label: 'Options 选择器表单项',
value: 'options'
}
]
},
{
label: '数据展示',
value: 'shujuzhanshi',
children: [
{
label: 'CRUD 增删改查',
value: 'crud'
},
{
label: 'Table 表格',
value: 'table'
},
{
label: 'Card 卡片',
value: 'card'
}
]
},
{
label: '反馈',
value: 'fankui'
}
]
}
]
}
]
},
{
type: 'matrix-checkboxes',
name: 'matrix',
label: '矩阵开关',
rowLabel: '行标题说明',
columns: [
{
label: '列1'
},
{
label: '列2'
}
],
rows: [
{
label: '行1'
},
{
label: '行2'
}
]
},
{
type: 'combo',
name: 'combo2',
label: '组合多条',
multiple: true,
value: [{}],
items: [
{
name: 'a',
type: 'input-text',
placeholder: 'A'
},
{
name: 'b',
type: 'select',
options: ['a', 'b', 'c']
}
]
},
{
type: 'input-file',
name: 'file',
label: '文件上传',
joinValues: false
},
{
type: 'input-range',
name: 'range',
label: '范围'
},
{
type: 'divider'
}
],
actions: []
};
|
zhangtao07/amis
|
src/components/Tag.tsx
|
<reponame>zhangtao07/amis<filename>src/components/Tag.tsx
/**
* @file Tag
*/
import React from 'react';
import {themeable, ThemeProps} from '../theme';
import {Icon, getIcon} from './icons';
import {generateIcon} from '../utils/icon';
import {autobind, noop} from '../utils/helper';
export interface TagProps extends ThemeProps {
style: React.CSSProperties;
color?: string;
label?: string | React.ReactNode;
displayMode?: 'normal' | 'rounded' | 'status';
icon?: string | React.ReactNode;
closable?: boolean;
disabled?: boolean;
closeIcon?: string | React.ReactNode;
onClose?: (e: React.MouseEvent) => void;
}
export interface CheckableTagProps extends TagProps {
onClick?: (e: React.MouseEvent) => void;
onChange?: (checked: boolean) => void;
checked?: boolean;
}
export type TagLevel =
| 'inactive'
| 'active'
| 'success'
| 'processing'
| 'error'
| 'warning';
const PRESET_COLOR: TagLevel[] = [
'inactive',
'active',
'success',
'processing',
'error',
'warning'
];
export class Tag extends React.Component<TagProps> {
static defaultProps: Partial<TagProps> = {
displayMode: 'normal'
};
renderCloseIcon() {
const {closeIcon, classnames: cx, closable} = this.props;
if (!closable) {
return null;
}
const icon =
typeof closeIcon === 'string' ? (
getIcon(closeIcon) ? (
<Icon icon={closeIcon} className="icon" />
) : (
generateIcon(cx, closeIcon, 'Icon')
)
) : React.isValidElement(closeIcon) ? (
closeIcon
) : (
<Icon icon="close" className="icon" />
);
return (
<span className={cx(`Tag--close`)} onClick={this.handleClose}>
{icon}
</span>
);
}
@autobind
handleClose(e: React.MouseEvent<HTMLElement>) {
const {onClose} = this.props;
e.stopPropagation();
onClose?.(e);
}
render() {
const {
children,
classnames: cx,
className,
displayMode,
disabled,
color,
icon,
style,
label
} = this.props;
const isPresetColor =
color && PRESET_COLOR.indexOf(color as TagLevel) !== -1;
const customColor = color && !isPresetColor ? color : undefined;
const tagStyle = {
backgroundColor: displayMode === 'normal' ? customColor : undefined,
borderColor: displayMode === 'rounded' ? customColor : undefined,
color: displayMode === 'rounded' ? customColor : undefined,
...style
};
const prevIcon = displayMode === 'status' && (
<span className={cx('Tag--prev')}>
{typeof icon === 'string' ? (
getIcon(icon) ? (
<Icon icon={icon} className="icon" />
) : (
generateIcon(cx, icon, 'Icon')
)
) : React.isValidElement(icon) ? (
icon
) : (
<Icon icon="dot" className="icon" />
)}
</span>
);
return (
<span
className={cx('Tag', `Tag--${displayMode}`, className, {
[`Tag--${displayMode}--${color}`]: isPresetColor,
[`Tag--${displayMode}--hasColor`]: color,
[`Tag--disabled`]: disabled
})}
style={tagStyle}
>
{prevIcon}
{label || children}
{this.renderCloseIcon()}
</span>
);
}
}
class CheckableTagComp extends React.Component<CheckableTagProps> {
@autobind
handleClick(e: React.MouseEvent) {
const {onChange, onClick, checked} = this.props;
onChange?.(!checked);
onClick?.(e);
}
render() {
const {
classnames: cx,
className,
disabled,
label,
children,
checked,
style = {}
} = this.props;
return (
<span
className={cx(className, 'Tag', 'Tag--checkable', {
'Tag--checkable--checked': checked,
'Tag--checkable--disabled': disabled
})}
onClick={disabled ? noop : this.handleClick}
style={style}
>
{label || children}
</span>
);
}
}
export const CheckableTag = themeable(CheckableTagComp);
export default themeable(Tag);
|
zhangtao07/amis
|
src/components/schema-editor/index.tsx
|
<reponame>zhangtao07/amis
/**
* 用来定义数据结构的编辑器
*/
import React from 'react';
import {localeable, LocaleProps} from '../../locale';
import {themeable, ThemeProps} from '../../theme';
import type {JSONSchema} from '../../utils/DataScope';
import {uncontrollable} from 'uncontrollable';
import {SchemaEditorItem} from './Item';
import type {JSONSchema7TypeName} from 'json-schema';
import {autobind} from '../../utils/helper';
export interface SchemaEditorProps extends LocaleProps, ThemeProps {
value?: JSONSchema;
onChange: (value: JSONSchema) => void;
disabled?: boolean;
defaultType: JSONSchema7TypeName;
renderExtraProps?: (
value: JSONSchema,
onChange: (value: JSONSchema) => void
) => JSX.Element;
renderModalProps?: (
value: JSONSchema,
onChange: (value: JSONSchema) => void
) => JSX.Element;
disabledTypes?: Array<string>;
/**
* 预设模板
*/
definitions?: {
[propName: string]: {
type:
| 'string'
| 'number'
| 'interger'
| 'object'
| 'array'
| 'boolean'
| 'null';
title: string;
[propName: string]: any;
};
};
/**
* 顶层是否允许修改类型
*/
rootTypeMutable: boolean;
/**
* 顶层类型信息是否隐藏
*/
showRootInfo: boolean;
}
export class SchemaEditor extends React.Component<SchemaEditorProps> {
static defaultProps: Pick<
SchemaEditorProps,
'defaultType' | 'rootTypeMutable' | 'showRootInfo' | 'disabledTypes'
> = {
defaultType: 'object',
rootTypeMutable: false,
showRootInfo: false,
disabledTypes: ['null']
};
defaultTypes: Array<any>;
constructor(props: SchemaEditorProps) {
super(props);
const __ = props.translate;
this.defaultTypes = [
{
label: __('SchemaType.string'),
value: 'string'
},
{
label: __('SchemaType.number'),
value: 'number'
},
{
label: __('SchemaType.interger'),
value: 'interger'
},
{
label: __('SchemaType.boolean'),
value: 'boolean'
},
{
label: __('SchemaType.null'),
value: 'null'
},
{
label: __('SchemaType.object'),
value: 'object'
},
{
label: __('SchemaType.array'),
value: 'array'
}
];
}
@autobind
handleTypeChange(type: string, value: any, origin: any) {
const {definitions} = this.props;
if (type === 'array') {
value.items = {
type: 'string'
};
}
if (definitions?.[type]) {
value = {
...value,
...definitions[type],
$ref: type
};
}
return value;
}
render() {
const {
defaultType,
classnames: cx,
onChange,
renderExtraProps,
renderModalProps,
translate,
locale,
classPrefix,
rootTypeMutable,
showRootInfo,
disabled,
definitions
} = this.props;
const value: JSONSchema = this.props.value || {
type: defaultType || 'object'
};
const disabledTypes = Array.isArray(this.props.disabledTypes)
? this.props.disabledTypes
: [];
let types = this.defaultTypes.concat();
if (definitions) {
const keys = Object.keys(definitions);
keys.forEach(key => {
const definition = definitions[key];
if (
definition?.type &&
definition.title &&
[
'string',
'number',
'interger',
'object',
'array',
'boolean',
'null'
].includes(definition.type)
) {
types.push({
value: key,
label: translate(definition.title)
});
}
});
}
if (disabledTypes.length) {
types = types.filter(item => !~disabledTypes.indexOf(item.value));
}
return (
<div className={cx('SchemaEditor')}>
<SchemaEditorItem
types={types}
typeMutable={rootTypeMutable}
showInfo={showRootInfo}
value={value}
onChange={onChange}
renderExtraProps={renderExtraProps}
renderModalProps={renderModalProps}
locale={locale}
translate={translate}
classnames={cx}
classPrefix={classPrefix}
disabled={disabled}
onTypeChange={this.handleTypeChange}
/>
</div>
);
}
}
export default themeable(
localeable(
uncontrollable(SchemaEditor, {
value: 'onChange'
})
)
);
|
zhangtao07/amis
|
src/components/schema-editor/Item.tsx
|
import React from 'react';
import {LocaleProps} from '../../locale';
import {ThemeProps} from '../../theme';
import type {JSONSchema} from '../../utils/DataScope';
import {autobind} from '../../utils/helper';
import Checkbox from '../Checkbox';
import InputBox from '../InputBox';
import Select from '../Select';
import {SchemaEditorItemArray} from './Array';
import {SchemaEditorItemCommon, SchemaEditorItemCommonProps} from './Common';
import {SchemaEditorItemObject} from './Object';
export interface SchemaEditorItemProps
extends SchemaEditorItemCommonProps,
LocaleProps,
ThemeProps {}
export class SchemaEditorItem extends React.Component<SchemaEditorItemProps> {
render() {
const {value} = this.props;
// 动态Component要用大写开头的才会被识别
let Renderer = SchemaEditorItemCommon;
switch (value?.type) {
case 'object':
Renderer = SchemaEditorItemObject as any;
break;
case 'array':
Renderer = SchemaEditorItemArray as any;
break;
}
return <Renderer {...this.props} />;
}
}
|
zhangtao07/amis
|
__tests__/renderers/Table.test.tsx
|
import React = require('react');
import {render} from '@testing-library/react';
import '../../src/themes/default';
import {render as amisRender} from '../../src/index';
import {makeEnv} from '../helper';
import rows from '../mockData/rows';
test('Renderer:table', () => {
const {container} = render(
amisRender(
{
type: 'table',
title: '表格1',
data: {
items: rows
},
columns: [
{
name: 'engine',
label: 'Engine'
},
{
name: 'version',
label: 'Version'
}
]
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:table align', () => {
const {container} = render(
amisRender(
{
type: 'table',
title: '表格1',
data: {
items: rows
},
columns: [
{
name: 'engine',
label: 'Engine'
},
{
name: 'version',
type: 'tpl',
tpl: '${version | number}',
align: 'right'
}
]
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:table classNameExpr', () => {
const {container} = render(
amisRender(
{
type: 'table',
title: '表格1',
data: {
items: rows
},
columns: [
{
name: 'engine',
label: 'Engine'
},
{
name: 'version',
label: 'Version',
classNameExpr: "<%= data.version > 5 ? 'text-danger' : '' %>"
}
]
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:table isHead fixed', () => {
const {container} = render(
amisRender(
{
type: 'table',
title: '表格1',
data: {
items: rows
},
columnsTogglable: false,
columns: [
{
name: 'engine',
label: 'Engine',
isHead: true
},
{
name: 'platform',
label: 'Platform',
fixed: 'right'
}
]
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:table children', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'service',
data: {
rows: [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
platform: 'Win 95+',
version: '4',
grade: 'X',
__id: 1,
children: [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
platform: 'Win 95+',
version: '4',
grade: 'X',
__id: 1001
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.0',
platform: 'Win 95+',
version: '5',
grade: 'C',
__id: 1002
}
]
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.0',
platform: 'Win 95+',
version: '5',
grade: 'C',
__id: 2,
children: [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
platform: 'Win 95+',
version: '4',
grade: 'X',
__id: 2001
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.0',
platform: 'Win 95+',
version: '5',
grade: 'C',
__id: 2002
}
]
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.5',
platform: 'Win 95+',
version: '5.5',
grade: 'A',
__id: 3,
children: [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
platform: 'Win 95+',
version: '4',
grade: 'X',
__id: 3001
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.0',
platform: 'Win 95+',
version: '5',
grade: 'C',
__id: 3002
}
]
},
{
engine: 'Trident',
browser: 'Internet Explorer 6',
platform: 'Win 98+',
version: '6',
grade: 'A',
__id: 4,
children: [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
platform: 'Win 95+',
version: '4',
grade: 'X',
__id: 4001
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.0',
platform: 'Win 95+',
version: '5',
grade: 'C',
__id: 4002
}
]
},
{
engine: 'Trident',
browser: 'Internet Explorer 7',
platform: 'Win XP SP2+',
version: '7',
grade: 'A',
__id: 5,
children: [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
platform: 'Win 95+',
version: '4',
grade: 'X',
__id: 5001
},
{
engine: 'Trident',
browser: 'Internet Explorer 5.0',
platform: 'Win 95+',
version: '5',
grade: 'C',
__id: 5002
}
]
}
]
},
body: [
{
type: 'table',
source: '$rows',
className: 'm-b-none',
columnsTogglable: false,
columns: [
{
name: 'engine',
label: 'Engine'
},
{
name: 'grade',
label: 'Grade'
},
{
name: 'version',
label: 'Version'
},
{
name: 'browser',
label: 'Browser'
},
{
name: '__id',
label: 'ID'
},
{
name: 'platform',
label: 'Platform'
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
// 合并单元格
test('Renderer:table combineNum', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'service',
data: {
rows
},
body: [
{
type: 'table',
source: '$rows',
className: 'm-b-none',
combineNum: 3,
columnsTogglable: false,
columns: [
{
name: 'engine',
label: 'Rendering engine'
},
{
name: 'browser',
label: 'Browser'
},
{
name: 'platform',
label: 'Platform(s)'
},
{
name: 'version',
label: 'Engine version'
},
{
name: 'grade',
label: 'CSS grade'
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
// 超级表头
test('Renderer:table groupName-default', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'service',
data: {
rows
},
body: [
{
type: 'table',
source: '$rows',
className: 'm-b-none',
columns: [
{
name: 'engine',
label: 'Engine',
groupName: '分组1'
},
{
name: 'grade',
label: 'Grade',
groupName: '分组1'
},
{
name: 'version',
label: 'Version',
groupName: '分组2'
},
{
name: 'browser',
label: 'Browser',
groupName: '分组2'
},
{
name: 'id',
label: 'ID',
toggled: false,
groupName: '分组2'
},
{
name: 'platform',
label: 'Platform',
groupName: '分组2'
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
// 超级表头,但是 tpl
test('Renderer:table groupName-withTpl', () => {
const {container} = render(
amisRender(
{
type: 'page',
data: {
groups: [
{
group: '分组1'
},
{
group: '分组1'
}
]
},
body: {
type: 'service',
data: {
rows
},
body: [
{
type: 'table',
source: '$rows',
className: 'm-b-none',
columns: [
{
name: 'engine',
label: 'Engine',
groupName: '${groups[0].group}'
},
{
name: 'grade',
label: 'Grade',
groupName: '${groups[1].group}'
},
{
name: 'version',
label: 'Version',
groupName: '分组2'
},
{
name: 'browser',
label: 'Browser',
groupName: '分组2'
},
{
name: 'id',
label: 'ID',
toggled: false,
groupName: '分组2'
},
{
name: 'platform',
label: 'Platform',
groupName: '分组2'
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
// 超级表头,但是 中间列未配置表头
test('Renderer:table groupName-middleNoGroupName', () => {
const {container} = render(
amisRender(
{
type: 'page',
data: {
groups: [
{
group: '分组1'
},
{
group: '分组1'
}
]
},
body: {
type: 'service',
data: {
rows
},
body: [
{
type: 'table',
source: '$rows',
className: 'm-b-none',
columns: [
{
name: 'engine',
label: 'Engine',
groupName: '分组1'
},
{
name: 'grade',
label: 'Grade'
// groupName: '分组1' // 这里没配置groupName
},
{
name: 'version',
label: 'Version'
// groupName: '分组2' // 这里没配置groupName
},
{
name: 'browser',
label: 'Browser',
groupName: '分组2'
},
{
name: 'id',
label: 'ID',
toggled: false,
groupName: '分组2'
},
{
name: 'platform',
label: 'Platform',
groupName: '分组2'
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:table column head style', () => {
const {container} = render(
amisRender(
{
type: 'table',
title: '表格1',
data: {
items: rows
},
columnsTogglable: false,
columns: [
{
name: 'engine',
label: 'Engine',
isHead: true
},
{
name: 'platform',
label: 'Platform',
fixed: 'right'
}
]
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:table list', () => {
const {container} = render(
amisRender(
{
type: 'table',
data: {
items: [
{
__id: '91264',
text: '衡 阎',
progress: 22,
type: 4,
boolean: true,
list: [
{
title: 'Forward Functionality Technician',
description: 'nisi ex eum'
},
{
title: 'District Applications Specialist',
description: 'ipsam ratione voluptas'
},
{
title: 'Future Operations Manager',
description: 'ducimus fugit debitis'
},
{
title: 'Dynamic Solutions Associate',
description: 'saepe consequatur aut'
}
],
audio:
'https://news-bos.cdn.bcebos.com/mvideo/%E7%9A%87%E5%90%8E%E5%A4%A7%E9%81%93%E4%B8%9C.aac',
carousel: [
{
image:
'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3893101144,2877209892&fm=23&gp=0.jpg'
},
{
html: '<div style="width: 100%; height: 200px; background: #e3e3e3; text-align: center; line-height: 200px;">carousel data in crud</div>'
},
{
image: 'https://video-react.js.org/assets/poster.png'
}
],
date: 1591270438,
image:
'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3893101144,2877209892&fm=23&gp=0.jpg',
json: {
__id: 1,
text: 'text'
}
},
{
__id: '34202',
text: '吉 卢汉市',
progress: 85,
type: 1,
boolean: true,
list: [
{
title: 'Dynamic Assurance Orchestrator',
description: 'ea ullam voluptates'
},
{
title: 'Internal Division Assistant',
description: 'illum deleniti qui'
},
{
title: 'International Usability Administrator',
description: 'sit voluptatem quia'
},
{
title: 'Lead Optimization Orchestrator',
description: 'autem et blanditiis'
},
{
title: 'Future Division Assistant',
description: 'dolor cupiditate sint'
},
{
title: 'Forward Program Orchestrator',
description: 'quia distinctio voluptas'
},
{
title: 'Human Implementation Technician',
description: 'consequatur quaerat ullam'
},
{
title: 'National Identity Administrator',
description: 'ipsa et reiciendis'
},
{
title: 'Regional Factors Planner',
description: 'sed deserunt natus'
},
{
title: 'Human Data Administrator',
description: 'rerum consequatur odit'
}
],
audio:
'https://news-bos.cdn.bcebos.com/mvideo/%E7%9A%87%E5%90%8E%E5%A4%A7%E9%81%93%E4%B8%9C.aac',
carousel: [
{
image:
'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3893101144,2877209892&fm=23&gp=0.jpg'
},
{
html: '<div style="width: 100%; height: 200px; background: #e3e3e3; text-align: center; line-height: 200px;">carousel data in crud</div>'
},
{
image: 'https://video-react.js.org/assets/poster.png'
}
],
date: 1591270438,
image:
'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3893101144,2877209892&fm=23&gp=0.jpg',
json: {
__id: 1,
text: 'text'
}
},
{
__id: '37701',
text: '立辉安市',
progress: 72,
type: 2,
boolean: false,
list: [
{
title: 'Corporate Metrics Liason',
description: 'aspernatur natus qui'
},
{
title: 'Central Paradigm Analyst',
description: 'sequi numquam ad'
},
{
title: 'International Data Administrator',
description: 'sed libero eum'
},
{
title: 'Forward Optimization Assistant',
description: 'officiis accusantium dolorem'
},
{
title: 'Senior Metrics Executive',
description: 'commodi sint quod'
},
{
title: 'Corporate Quality Facilitator',
description: 'aut aperiam est'
},
{
title: 'Forward Operations Producer',
description: 'sed corporis eaque'
},
{
title: 'National Integration Analyst',
description: 'quasi ab cumque'
}
],
audio:
'https://news-bos.cdn.bcebos.com/mvideo/%E7%9A%87%E5%90%8E%E5%A4%A7%E9%81%93%E4%B8%9C.aac',
carousel: [
{
image:
'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3893101144,2877209892&fm=23&gp=0.jpg'
},
{
html: '<div style="width: 100%; height: 200px; background: #e3e3e3; text-align: center; line-height: 200px;">carousel data in crud</div>'
},
{
image: 'https://video-react.js.org/assets/poster.png'
}
],
date: 1591270438,
image:
'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3893101144,2877209892&fm=23&gp=0.jpg',
json: {
__id: 1,
text: 'text'
}
}
]
},
affixHeader: false,
syncLocation: false,
columns: [
{
name: '__id',
label: 'ID',
type: 'text'
},
{
name: 'text',
label: '文本',
type: 'text'
},
{
type: 'image',
label: '图片',
name: 'image'
},
{
name: 'date',
type: 'date',
label: '日期'
},
{
name: 'progress',
label: '进度',
type: 'progress'
},
{
name: 'boolean',
label: '状态',
type: 'status'
},
{
name: 'boolean',
label: '开关',
type: 'switch'
},
{
name: 'type',
label: '映射',
type: 'mapping',
map: {
'1': "<span class='label label-info'>漂亮</span>",
'2': "<span class='label label-success'>开心</span>",
'3': "<span class='label label-danger'>惊吓</span>",
'4': "<span class='label label-warning'>紧张</span>",
'*': '其他:${type}'
}
},
{
name: 'list',
type: 'list',
label: 'List',
placeholder: '-',
listItem: {
title: '${title}',
subTitle: '${description}'
}
}
]
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
|
zhangtao07/amis
|
examples/components/Theme.tsx
|
import From from './theme/form';
import {
colorControls,
fontControls,
sizeControls,
borderControls,
linkControls
} from './theme/vars';
import CRUD from './theme/crud';
function updateTheme(theme: any) {
let varStyleTag = document.getElementById('customVars');
if (!varStyleTag) {
varStyleTag = document.createElement('style');
varStyleTag.id = 'customVars';
document.body.appendChild(varStyleTag);
}
const vars = [];
const names = new Set();
for (const type in theme) {
if (type.startsWith('_')) {
for (const name in theme[type]) {
const value = theme[type][name];
if (typeof value !== undefined && value !== '') {
names.add(name);
vars.push(`${name}: ${value.replace(/[;<>]*/g, '')};`);
}
}
}
}
// bca-disable-line
varStyleTag.innerHTML = `:root {
${[...vars].join('')}
}`;
// 如果是改自定义样式
let styleTag = document.getElementById('customStyle');
if (!styleTag) {
styleTag = document.createElement('style');
styleTag.id = 'customVars';
document.body.appendChild(styleTag);
}
if (theme?.style) {
// bca-disable-line
styleTag.innerHTML = theme.style;
}
}
export default {
type: 'form',
title:
'这是一个基于 amis 搭建较为复杂界面的例子,部分功能使用代码开发,请参考源码',
submitText: '',
persistData: 'amis-theme-editor',
actions: [],
onEvent: {
inited: {
actions: [
{
actionType: 'custom',
script: (context: any, doAction: any, event: any) => {
const theme = event.data.formData.config?.theme;
theme && updateTheme(theme);
}
}
]
}
},
// 用于主题修改的时候实时看效果
onChange: (values: any, diff: any) => {
const theme = diff.config?.theme;
theme && updateTheme(theme);
},
body: [
{
type: 'grid',
label: false,
columns: [
{
md: 4,
body: [
{
type: 'tabs',
tabs: [
{
title: '基础设置',
body: [
{
type: 'tpl',
tpl: '变量设置',
label: false
},
{
type: 'tabs',
mode: 'vertical',
subFormMode: 'normal',
tabs: [
{
title: '颜色',
body: colorControls
},
{
title: '字体',
body: fontControls
},
{
title: '间距',
body: sizeControls
},
{
title: '边框',
body: borderControls
},
{
title: '链接',
body: linkControls
},
{
title: '动画',
body: [
{
type: 'input-text',
label: '动画时长',
placeholder: '2s',
name: 'config.theme._vars["--animation-duration"]'
}
]
},
{
title: '其它变量',
body: [
{
type: 'combo',
multiple: true,
name: 'config.theme._otherVars',
body: [
{
type: 'input-text',
placeholder: '变量名',
required: true,
name: 'key'
},
{
type: 'input-text',
placeholder: '变量值',
required: true,
name: 'value'
}
]
}
]
}
]
}
]
},
{
title: '自定义 CSS',
body: [
{
label: false,
type: 'editor',
name: 'config.theme.style',
size: 'lg',
options: {
lineNumbers: 'off'
},
language: 'css'
}
]
},
{
title: '查看设置的变量',
body: [
{
type: 'static-tpl',
pipeIn: (value: any, data: any) => {
const vars = [];
const names = new Set();
const theme = data.data?.config?.theme || {};
for (const type in theme) {
if (type.startsWith('_')) {
for (const name in theme[type]) {
const value = theme[type][name];
if (typeof value !== undefined && value !== '') {
names.add(name);
vars.push(
`${name}: ${value.replace(/[;<>]*/g, '')};`
);
}
}
}
}
if (vars.length) {
return `<pre>${vars.join('\n')}</pre>`;
} else {
return '未设置变量';
}
}
}
]
}
]
}
]
},
{
md: 8,
type: 'container',
columnClassName: 'b-l',
body: [
{
type: 'tabs',
tabs: [
{
title: '表单预览',
tab: From
},
{
title: '表格预览',
tab: CRUD
}
]
}
]
}
]
}
]
};
|
zhangtao07/amis
|
src/components/table/HeadCellSelect.tsx
|
<reponame>zhangtao07/amis
/**
* @file table/HeadCellSelect
* @author fex
*/
import React from 'react';
import {findDOMNode} from 'react-dom';
import {themeable, ThemeProps} from '../../theme';
import {LocaleProps, localeable} from '../../locale';
import HeadCellDropDown, {FilterPayload} from './HeadCellDropDown';
import {RowSelectionOptionProps} from './index';
import {Icon} from '../icons';
export interface Props extends ThemeProps, LocaleProps {
selections: Array<RowSelectionOptionProps>;
keys: Array<string | number> | string;
popOverContainer?: () => Element | Text | null;
}
export interface State {
key: Array<string | number> | string;
}
export class HeadCellSelect extends React.Component<Props, State> {
static defaultProps = {
selections: []
};
constructor(props: Props) {
super(props);
this.state = {
key: ''
}
}
render() {
const {
selections,
keys: allKeys,
popOverContainer,
classnames: cx,
classPrefix: ns
} = this.props;
return (
<HeadCellDropDown
className={`${ns}TableCell-selectionBtn`}
layerClassName={`${ns}TableCell-selectionPopOver`}
filterIcon={<Icon icon="left-arrow" className="icon" />}
active={false}
popOverContainer={popOverContainer ? popOverContainer : () => findDOMNode(this)}
filterDropdown={({setSelectedKeys, selectedKeys, confirm, clearFilters}) => {
return <ul className={cx('DropDown-menu')}>
{selections.map((item, index) => (
<li
key={index}
onClick={() => {
item.onSelect && item.onSelect(allKeys);
this.handleClick(confirm, setSelectedKeys, item.key);
}}>
{item.text}
</li>
))}
</ul> ;
}}
setSelectedKeys={keys => this.setState({key: keys})}
selectedKeys={this.state.key}
>
</HeadCellDropDown>
);
}
handleClick(
confirm: (payload?: FilterPayload) => void,
setSelectedKeys?: (keys?: Array<string | number> | string) => void | undefined,
selectedKeys?: Array<string> | string
) {
setSelectedKeys && setSelectedKeys(selectedKeys);
confirm();
}
}
export default themeable(localeable(HeadCellSelect));
|
zhangtao07/amis
|
src/components/NumberInput.tsx
|
<reponame>zhangtao07/amis<filename>src/components/NumberInput.tsx
import React from 'react';
// @ts-ignore
import InputNumber from 'rc-input-number';
import getMiniDecimal, {
DecimalClass,
toFixed
} from 'rc-input-number/lib/utils/MiniDecimal';
import {getNumberPrecision} from 'rc-input-number/lib/utils/numberUtil';
import {Icon} from './icons';
import {ThemeProps, themeable} from '../theme';
import {autobind, ucFirst} from '../utils/helper';
export interface NumberProps extends ThemeProps {
placeholder?: string;
max?: number;
min?: number;
step?: number;
showSteps?: boolean;
precision?: number;
disabled?: boolean;
/**
* 只读
*/
readOnly?: boolean;
value?: number;
onChange?: (value: number) => void;
/**
* 边框模式,全边框,还是半边框,或者没边框。
*/
borderMode?: 'full' | 'half' | 'none';
/**
* 指定输入框展示值的格式
*/
formatter?: Function;
/**
* 指定从 formatter 里转换回数字的方式,和 formatter 搭配使用
*/
parser?: Function;
inputRef?: Function;
/**
* 获取焦点事件
*/
onFocus?: Function;
/**
* 失去焦点事件
*/
onBlur?: Function;
/**
* 指定输入框是基础输入框,增强输入框
*/
displayMode?: 'base' | 'enhance';
keyboard?: Boolean;
}
export class NumberInput extends React.Component<NumberProps, any> {
static defaultProps: Pick<NumberProps, 'step' | 'readOnly' | 'borderMode'> = {
step: 1,
readOnly: false,
borderMode: 'full'
};
@autobind
handleChange(value: any) {
const {min, max, onChange} = this.props;
if (typeof value === 'number') {
if (typeof min === 'number') {
value = Math.max(value, min);
}
if (typeof max === 'number') {
value = Math.min(value, max);
}
}
onChange?.(value);
}
@autobind
handleFocus(e: React.SyntheticEvent<HTMLElement>) {
const {onFocus} = this.props;
onFocus && onFocus(e);
}
@autobind
handleBlur(e: React.SyntheticEvent<HTMLElement>) {
const {onBlur} = this.props;
onBlur && onBlur(e);
}
@autobind
handleEnhanceModeChange(action: 'add' | 'subtract'): void {
const {value, step, disabled, readOnly, precision} = this.props;
// value为undefined会导致溢出错误
let val = Number(value) || 0;
if (disabled || readOnly) {
return;
}
if (isNaN(Number(step)) || !Number(step)) {
return;
}
let stepDecimal = getMiniDecimal(Number(step));
if (action !== 'add') {
stepDecimal = stepDecimal.negate();
}
const target = getMiniDecimal(val).add(stepDecimal.toString());
const getPrecision = (numStr: string) => {
if (precision! >= 0) {
return precision;
}
return Math.max(getNumberPrecision(numStr), getNumberPrecision(Number(step) || 1));
};
const triggerValueUpdate = (newValue: DecimalClass, userTyping: boolean): DecimalClass => {
let updateValue = newValue;
const numStr = updateValue.toString();
const mergedPrecision = getPrecision(numStr);
if (mergedPrecision! >= 0) {
updateValue = getMiniDecimal(toFixed(numStr, '.', mergedPrecision));
}
return updateValue;
};
const updatedValue = triggerValueUpdate(target, false);
val = Number(updatedValue.toString());
this.handleChange(val);
}
@autobind
renderBase() {
const {
className,
classPrefix: ns,
classnames: cx,
value,
step,
precision,
max,
min,
disabled,
placeholder,
onChange,
showSteps,
formatter,
parser,
borderMode,
readOnly,
displayMode,
inputRef,
keyboard
} = this.props;
let precisionProps: any = {};
if (typeof precision === 'number') {
precisionProps.precision = precision;
}
return <InputNumber
className={cx(className, showSteps === false ? 'no-steps' : '',
displayMode === 'enhance' ? 'Number--enhance-input' : '', {
[`Number--border${ucFirst(borderMode)}`]: borderMode
})}
ref={inputRef}
readOnly={readOnly}
prefixCls={`${ns}Number`}
value={value}
step={step}
max={max}
min={min}
formatter={formatter}
parser={parser}
onChange={this.handleChange}
disabled={disabled}
placeholder={placeholder}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
keyboard={keyboard}
{...precisionProps}
/>
}
render(): JSX.Element {
const {
classPrefix: ns,
classnames: cx,
value,
precision,
max,
min,
disabled,
showSteps,
borderMode,
readOnly,
displayMode
} = this.props;
let precisionProps: any = {};
if (typeof precision === 'number') {
precisionProps.precision = precision;
}
return (
<>
{displayMode === 'enhance' ?
<div className={cx('Number--enhance',
disabled ? 'Number--enhance-disabled' : '',
showSteps === false ? 'Number--enhance-no-steps' : '',
{
[`Number--enhance-border${ucFirst(borderMode)}`]: borderMode
})}>
<div
className={cx('Number--enhance-left-icon',
value && value === min ? 'Number--enhance-border-min': '',
disabled ? 'Number--enhance-border-disabled': '',
readOnly ? 'Number--enhance-border-readOnly': '')} onClick={() => this.handleEnhanceModeChange('subtract')}>
<Icon icon="minus" className="icon" />
</div>
{this.renderBase()}
<div
className={cx('Number--enhance-right-icon',
value && value === max ? 'Number--enhance-border-max': '',
disabled ? 'Number--enhance-border-disabled': '',
readOnly ? 'Number--enhance-border-readOnly': '')} onClick={() => this.handleEnhanceModeChange('add')}>
<Icon icon="plus" className="icon " />
</div>
</div> : this.renderBase()}
</>
);
}
}
export default themeable(NumberInput);
|
zhangtao07/amis
|
src/locale.tsx
|
// 多语言支持
import React from 'react';
import hoistNonReactStatic from 'hoist-non-react-statics';
import {resolveVariable} from './utils/tpl-builtin';
export type TranslateFn<T = any> = (str: T, data?: object) => T;
interface LocaleConfig {
[propsName: string]: string;
}
let defaultLocale: string = 'zh-CN';
const locales: {
[propName: string]: LocaleConfig;
} = {};
export function register(name: string, config: LocaleConfig) {
locales[name] = config;
}
const fns: {
[propName: string]: TranslateFn;
} = {};
function format(str: string, data?: object) {
return str.replace(/(\\)?\{\{([\s\S]+?)\}\}/g, (_, escape, key) => {
if (escape) {
return _.substring(1);
}
return resolveVariable(key, data || {});
});
}
export function makeTranslator(locale?: string): TranslateFn {
if (locale && fns[locale]) {
return fns[locale];
}
const fn = (str: any, ...args: any[]) => {
if (!str || typeof str !== 'string') {
return str;
}
const dict = locales[locale!] || locales[defaultLocale];
return format(dict?.[str] || str, ...args);
};
locale && (fns[locale] = fn);
return fn;
}
export function getDefaultLocale() {
return defaultLocale;
}
export function setDefaultLocale(loacle: string) {
defaultLocale = loacle;
}
export interface LocaleProps {
locale: string;
translate: TranslateFn;
}
export const LocaleContext = React.createContext('');
export function localeable<
T extends React.ComponentType<React.ComponentProps<T> & LocaleProps>
>(ComposedComponent: T) {
type OuterProps = JSX.LibraryManagedAttributes<
T,
Omit<React.ComponentProps<T>, keyof LocaleProps>
> & {
locale?: string;
translate?: (str: string, ...args: any[]) => string;
};
const result = hoistNonReactStatic(
class extends React.Component<OuterProps> {
static displayName = `I18N(${
ComposedComponent.displayName || ComposedComponent.name
})`;
static contextType = LocaleContext;
static ComposedComponent = ComposedComponent as React.ComponentType<T>;
constructor(props: OuterProps) {
super(props);
this.childRef = this.childRef.bind(this);
this.getWrappedInstance = this.getWrappedInstance.bind(this);
}
ref: any;
childRef(ref: any) {
while (ref && ref.getWrappedInstance) {
ref = ref.getWrappedInstance();
}
this.ref = ref;
}
getWrappedInstance() {
return this.ref;
}
render() {
const locale: string =
this.props.locale || this.context || defaultLocale;
const translate = this.props.translate || makeTranslator(locale);
const injectedProps: {
locale: string;
translate: TranslateFn;
} = {
locale,
translate: translate!
};
const refConfig = ComposedComponent.prototype?.isReactComponent
? {ref: this.childRef}
: {forwardedRef: this.childRef};
return (
<LocaleContext.Provider value={locale}>
<ComposedComponent
{...(this.props as JSX.LibraryManagedAttributes<
T,
React.ComponentProps<T>
>)}
{...injectedProps}
{...refConfig}
/>
</LocaleContext.Provider>
);
}
},
ComposedComponent
);
return result as typeof result & {
ComposedComponent: T;
};
}
|
zhangtao07/amis
|
src/actions/BreakAction.ts
|
import { RendererEvent } from '../utils/renderer-event';
import {
RendererAction,
ListenerContext,
LoopStatus,
registerAction,
ILogicAction
} from './Action';
export interface IBreakAction extends ILogicAction {
actionType: 'break';
}
/**
* breach
*
* @export
* @class BreakAction
* @implements {Action}
*/
export class BreakAction implements RendererAction {
async run(
action: IBreakAction,
renderer: ListenerContext,
event: RendererEvent<any>
) {
renderer.loopStatus = LoopStatus.BREAK;
}
}
registerAction('break', new BreakAction());
|
zhangtao07/amis
|
src/utils/DataSchema.ts
|
<filename>src/utils/DataSchema.ts
import {DataScope} from './DataScope';
import type {JSONSchema} from './DataScope';
import {guid} from './helper';
/**
* 用来定义数据本身的数据结构,比如有类型是什么,有哪些属性。
*/
export class DataSchema {
// 指向顶级数据作用域
readonly root: DataScope;
readonly idMap: {
[propName: string]: DataScope;
} = {};
// 这个经常变动,游离于整个链中
current: DataScope;
constructor(schema: JSONSchema | Array<JSONSchema>) {
this.root = new DataScope(schema, 'root');
this.idMap['root'] = this.root;
this.current = this.root;
}
setSchema(schemas: Array<JSONSchema>) {
this.current.setSchemas(schemas);
return this;
}
addSchema(schema: JSONSchema) {
this.current.addSchema(schema);
return this;
}
removeSchema(id: string) {
this.current.removeSchema(id);
delete this.idMap[id];
return this;
}
getSchemas() {
const schemas: Array<JSONSchema> = [];
let current: DataScope | void = this.current;
while (current) {
schemas.push(...current.schemas);
current = current.parent;
}
return schemas;
}
addScope(schema?: JSONSchema | Array<JSONSchema>, id: string = guid()) {
if (this.idMap[id]) {
throw new Error('scope id `' + id + '` already exists');
}
this.current = this.current.addChild(id, schema);
this.idMap[id] = this.current;
return this;
}
removeScope(idOrScope: string | DataScope) {
const scope = this.getScope(idOrScope);
if (!scope.parent) {
throw new Error('cannot remove root scope');
}
if (scope.contains(this.current)) {
this.current = scope.parent!;
}
scope.parent?.removeChild(scope);
delete this.idMap[scope.id];
return this;
}
hasScope(idOrScope: string | DataScope): idOrScope is string | DataScope {
const id = typeof idOrScope === 'string' ? idOrScope : idOrScope.id;
const scope = this.idMap[id];
return !!scope;
}
getScope(idOrScope: string | DataScope) {
const id = typeof idOrScope === 'string' ? idOrScope : idOrScope.id;
const scope = this.idMap[id];
if (!scope) {
throw new Error('scope not found!');
}
return scope;
}
switchToRoot() {
this.current = this.root;
return this;
}
switchTo(idOrScope: string | DataScope) {
const scope = this.getScope(idOrScope);
this.current = scope;
return this;
}
getDataPropsAsOptions() {
const variables: Array<any> = [];
let current: DataScope | void = this.current;
while (current) {
if (current.tag) {
variables.push({
label: current.tag,
children: current.getDataPropsAsOptions()
});
} else {
variables.push(...current.getDataPropsAsOptions());
}
current = current.parent;
}
return variables;
}
getSchemaByPath(path: string) {
let current: DataScope | void = this.current;
while (current) {
const schema = current.getSchemaByPath(path);
if (schema) {
return schema;
}
current = current.parent;
}
return null;
}
}
|
zhangtao07/amis
|
src/components/formula/VariableList.tsx
|
<gh_stars>0
import React from 'react';
import {themeable, ThemeProps} from '../../theme';
import GroupedSelection from '../GroupedSelection';
import Tabs, {Tab} from '../Tabs';
import TreeSelection from '../TreeSelection';
import SearchBox from '../SearchBox';
import {filterTree, flattenTree} from '../../utils/helper';
import type {VariableItem} from './Editor';
import type {ItemRenderStates} from '../Selection';
import type {Option} from '../Select';
import type {TabsMode} from '../Tabs';
export interface VariableListProps extends ThemeProps {
className?: string;
itemClassName?: string;
value?: any;
data: Array<VariableItem>;
selectMode?: 'list' | 'tree' | 'tabs';
tabsMode?: TabsMode;
itemRender?: (option: Option, states: ItemRenderStates) => JSX.Element;
onSelect?: (item: VariableItem) => void;
}
function VariableList(props: VariableListProps) {
const {
data: list,
className,
classnames: cx,
tabsMode = 'line',
classPrefix: themePrefix,
itemClassName,
selectMode,
onSelect
} = props;
const [filterVars, setFilterVars] = React.useState(list);
const classPrefix = `${themePrefix}FormulaEditor-VariableList`;
const itemRender =
props.itemRender && typeof props.itemRender === 'function'
? props.itemRender
: (option: Option, states: ItemRenderStates): JSX.Element => {
return (
<span className={cx(`${classPrefix}-item`, itemClassName)}>
<label>{option.label}</label>
{option?.tag ? (
<span className={cx(`${classPrefix}-item-tag`)}>
{option.tag}
</span>
) : null}
</span>
);
};
function onSearch(term: string) {
const flatten = flattenTree(list);
const filtered = flatten.filter(item => ~item.label.indexOf(term));
setFilterVars(!term ? list : filtered);
}
function renderSearchBox() {
return (
<div className={cx('FormulaEditor-VariableList-searchBox')}>
<SearchBox mini={false} onSearch={onSearch} />
</div>
);
}
return (
<div
className={cx(
className,
'FormulaEditor-VariableList',
selectMode && `FormulaEditor-VariableList-${selectMode}`
)}
>
{selectMode === 'tabs' ? (
<Tabs
tabsMode={tabsMode}
className={cx(`${classPrefix}-base ${classPrefix}-tabs`)}
>
{filterVars.map((item, index) => (
<Tab
className={cx(`${classPrefix}-tab`)}
eventKey={index}
key={index}
title={item.label}
>
<VariableList
classnames={cx}
classPrefix={`${classPrefix}-sub-`}
className={cx(`${classPrefix}-sub`)}
itemRender={itemRender}
selectMode={item.selectMode}
data={item.children!}
onSelect={onSelect}
/>
</Tab>
))}
</Tabs>
) : selectMode === 'tree' ? (
<div className={cx('FormulaEditor-VariableList-body')}>
{renderSearchBox()}
<TreeSelection
itemRender={itemRender}
className={cx(`${classPrefix}-base`, 'is-scrollable')}
multiple={false}
options={filterVars}
onChange={(item: any) => onSelect?.(item)}
/>
</div>
) : (
<div className={cx('FormulaEditor-VariableList-body')}>
{renderSearchBox()}
<GroupedSelection
itemRender={itemRender}
className={cx(`${classPrefix}-base`, 'is-scrollable')}
multiple={false}
options={filterVars}
onChange={(item: any) => onSelect?.(item)}
/>
</div>
)}
</div>
);
}
export default themeable(VariableList);
|
zhangtao07/amis
|
src/renderers/Form/wrapControl.tsx
|
<reponame>zhangtao07/amis<filename>src/renderers/Form/wrapControl.tsx
import React from 'react';
import {IFormStore, IFormItemStore} from '../../store/form';
import debouce from 'lodash/debounce';
import {RendererProps, Renderer} from '../../factory';
import {ComboStore, IComboStore, IUniqueGroup} from '../../store/combo';
import {
anyChanged,
promisify,
isObject,
guid,
isEmpty,
autobind,
getVariable,
createObject
} from '../../utils/helper';
import {IIRendererStore, IRendererStore} from '../../store';
import {ScopedContext, IScopedContext} from '../../Scoped';
import {reaction} from 'mobx';
import {FormItemStore} from '../../store/formItem';
import {isAlive} from 'mobx-state-tree';
import {observer} from 'mobx-react';
import hoistNonReactStatic from 'hoist-non-react-statics';
import {withRootStore} from '../../WithRootStore';
import {FormBaseControl, FormItemWrap} from './Item';
import {Api} from '../../types';
import {TableStore} from '../../store/table';
export interface ControlOutterProps extends RendererProps {
formStore?: IFormStore;
name?: string;
value?: any;
id?: string;
type?: string;
required?: boolean;
validations: string | {[propsName: string]: any};
validationErrors: {[propsName: string]: any};
validateOnChange: boolean;
multiple?: boolean;
delimiter?: string;
joinValues?: boolean;
extractValue?: boolean;
valueField?: string;
labelField?: string;
unique?: boolean;
selectFirst?: boolean;
autoFill?: any;
clearValueOnHidden?: boolean;
validateApi?: Api;
submitOnChange?: boolean;
validate?: (value: any, values: any, name: string) => any;
formItem?: IFormItemStore;
addHook?: (fn: () => any, type?: 'validate' | 'init' | 'flush') => void;
removeHook?: (fn: () => any, type?: 'validate' | 'init' | 'flush') => void;
$schema: {
pipeIn?: (value: any, data: any) => any;
pipeOut?: (value: any, originValue: any, data: any) => any;
[propName: string]: any;
};
store?: IIRendererStore;
onChange?: (
value: any,
name: string,
submit?: boolean,
changePristine?: boolean
) => void;
formItemDispatchEvent: (type: string, data: any) => void;
}
export interface ControlProps {
onBulkChange?: (values: Object) => void;
onChange?: (value: any, name: string, submit: boolean) => void;
store: IIRendererStore;
}
export function wrapControl<
T extends React.ComponentType<React.ComponentProps<T> & ControlProps>
>(ComposedComponent: T) {
type OuterProps = JSX.LibraryManagedAttributes<
T,
Omit<React.ComponentProps<T>, keyof ControlProps>
> &
ControlOutterProps;
const result = hoistNonReactStatic(
withRootStore(
observer(
class extends React.Component<OuterProps> {
public model: IFormItemStore | undefined;
control?: any;
value?: any = undefined;
hook?: () => any;
hook2?: () => any;
hook3?: () => any;
reaction?: () => void;
static contextType = ScopedContext;
static defaultProps = {};
lazyEmitChange = debouce(this.emitChange.bind(this), 250, {
trailing: true,
leading: false
});
constructor(props: OuterProps) {
super(props);
const {
formStore: form,
formItem,
rootStore,
store,
onChange,
data,
$schema: {
name,
id,
type,
required,
validations,
validationErrors,
unique,
value,
multiple,
delimiter,
valueField,
labelField,
joinValues,
extractValue,
selectFirst,
autoFill,
clearValueOnHidden,
validateApi,
minLength,
maxLength,
validateOnChange,
label
}
} = this.props;
this.getValue = this.getValue.bind(this);
this.setValue = this.setValue.bind(this);
this.handleChange = this.handleChange.bind(this);
this.setPrinstineValue = this.setPrinstineValue.bind(this);
this.controlRef = this.controlRef.bind(this);
this.handleBlur = this.handleBlur.bind(this);
if (!name) {
return;
}
let propValue = this.props.value;
const model = rootStore.addStore({
id: guid(),
path: this.props.$path,
storeType: FormItemStore.name,
parentId: store?.id,
name
}) as IFormItemStore;
this.model = model;
// @issue 打算干掉这个
formItem?.addSubFormItem(model);
model.config({
id,
type,
required,
unique,
value,
rules: validations,
messages: validationErrors,
multiple,
delimiter,
valueField,
labelField,
joinValues,
extractValue,
selectFirst,
autoFill,
clearValueOnHidden,
validateApi,
minLength,
maxLength,
validateOnChange,
label
});
// issue 这个逻辑应该在 combo 里面自己实现。
if (
this.model.unique &&
form?.parentStore?.storeType === ComboStore.name
) {
const combo = form.parentStore as IComboStore;
combo.bindUniuqueItem(model);
}
// 同步 value
model.changeTmpValue(
propValue ?? store?.getValueByName(model.name) ?? value
);
// 如果没有初始值,通过 onChange 设置过去
if (
onChange &&
typeof propValue === 'undefined' &&
typeof store?.getValueByName(model.name, false) === 'undefined' &&
// todo 后续再优化这个判断,
// 目前 input-table 中默认值会给冲掉,所以加上这个判断
// 对应 issue 为 https://github.com/baidu/amis/issues/2674
store?.storeType !== TableStore.name
) {
onChange(model.tmpValue, model.name, false, true);
}
}
componentDidMount() {
const {
store,
formStore: form,
$schema: {name, validate},
addHook
} = this.props;
// 提交前先把之前的 lazyEmit 执行一下。
this.hook3 = () => {
this.lazyEmitChange.flush();
};
addHook?.(this.hook3, 'flush');
const formItem = this.model as IFormItemStore;
if (formItem && validate) {
let finalValidate = promisify(validate.bind(formItem));
this.hook2 = () => {
formItem.clearError('control:valdiate');
return finalValidate(
this.props.data,
this.getValue(),
name
).then((ret: any) => {
if ((typeof ret === 'string' || Array.isArray(ret)) && ret) {
formItem.addError(ret, 'control:valdiate');
}
});
};
addHook?.(this.hook2);
}
}
componentDidUpdate(prevProps: OuterProps) {
const props = this.props;
const form = props.formStore;
const model = this.model;
if (
model &&
anyChanged(
[
'id',
'validations',
'validationErrors',
'value',
'required',
'unique',
'multiple',
'delimiter',
'valueField',
'labelField',
'joinValues',
'extractValue',
'selectFirst',
'autoFill',
'clearValueOnHidden',
'validateApi',
'minLength',
'maxLength',
'label'
],
prevProps.$schema,
props.$schema
)
) {
model.config({
required: props.$schema.required,
id: props.$schema.id,
unique: props.$schema.unique,
value: props.$schema.value,
rules: props.$schema.validations,
multiple: props.$schema.multiple,
delimiter: props.$schema.delimiter,
valueField: props.$schema.valueField,
labelField: props.$schema.labelField,
joinValues: props.$schema.joinValues,
extractValue: props.$schema.extractValue,
messages: props.$schema.validationErrors,
selectFirst: props.$schema.selectFirst,
autoFill: props.$schema.autoFill,
clearValueOnHidden: props.$schema.clearValueOnHidden,
validateApi: props.$schema.validateApi,
minLength: props.$schema.minLength,
maxLength: props.$schema.maxLength,
label: props.$schema.label
});
}
if (model && typeof props.value !== 'undefined') {
// 自己控制的 value 优先
if (
props.value !== prevProps.value &&
props.value !== model.tmpValue
) {
model.changeTmpValue(props.value);
}
} else if (
// 然后才是查看关联的 name 属性值是否变化
model &&
props.data !== prevProps.data &&
(!model.emitedValue || model.emitedValue === model.tmpValue)
) {
model.changeEmitedValue(undefined);
const value = getVariable(props.data, model.name);
const prevValue = getVariable(prevProps.data, model.name);
if (
(value !== prevValue ||
getVariable(props.data, model.name, false) !==
getVariable(prevProps.data, model.name, false)) &&
value !== model.tmpValue
) {
model.changeTmpValue(value);
}
}
}
componentWillUnmount() {
this.hook && this.props.removeHook?.(this.hook);
this.hook2 && this.props.removeHook?.(this.hook2);
this.hook3 && this.props.removeHook?.(this.hook3, 'flush');
// this.lazyEmitChange.flush();
this.lazyEmitChange.cancel();
this.reaction?.();
this.disposeModel();
}
disposeModel() {
const {formStore: form, formItem, rootStore} = this.props;
if (
this.model &&
this.model.unique &&
form?.parentStore &&
form?.parentStore.storeType === ComboStore.name
) {
const combo = form.parentStore as IComboStore;
combo.unBindUniuqueItem(this.model);
}
if (this.model) {
formItem &&
isAlive(formItem) &&
formItem.removeSubFormItem(this.model);
this.model.clearValueOnHidden &&
this.model.form?.deleteValueByName(this.model.name);
isAlive(rootStore) && rootStore.removeStore(this.model);
}
delete this.model;
}
controlRef(control: any) {
const {
addHook,
removeHook,
formStore: form,
$schema: {name}
} = this.props;
// 因为 control 有可能被 n 层 hoc 包裹。
while (control && control.getWrappedInstance) {
control = control.getWrappedInstance();
}
if (control && control.validate && this.model) {
const formItem = this.model as IFormItemStore;
let validate = promisify(control.validate.bind(control));
this.hook = () => {
formItem.clearError('component:valdiate');
return validate(this.props.data, this.getValue(), name).then(
ret => {
if (
(typeof ret === 'string' || Array.isArray(ret)) &&
ret
) {
formItem.setError(ret, 'component:valdiate');
}
}
);
};
addHook?.(this.hook);
} else if (!control && this.hook) {
removeHook?.(this.hook);
this.hook = undefined;
}
// 注册到 Scoped 上
const originRef = this.control;
this.control = control;
const scoped = this.context as IScopedContext;
if (control) {
scoped.registerComponent(this.control);
} else if (originRef) {
scoped.unRegisterComponent(originRef);
}
}
async validate() {
const {formStore: form, data, formItemDispatchEvent} = this.props;
let result;
if (this.model) {
if (
this.model.unique &&
form?.parentStore &&
form.parentStore.storeType === ComboStore.name
) {
const combo = form.parentStore as IComboStore;
const group = combo.uniques.get(
this.model.name
) as IUniqueGroup;
const validPromises = group.items.map(item =>
item.validate(data)
);
result = await Promise.all(validPromises);
} else {
const validPromises = form
?.getItemsByName(this.model.name)
.map(item => item.validate(data));
if (validPromises && validPromises.length) {
result = await Promise.all(validPromises);
}
}
}
if (result && result.length) {
if (result.indexOf(false) > -1) {
formItemDispatchEvent('formItemValidateError', data);
} else {
formItemDispatchEvent('formItemValidateSucc', data);
}
}
}
handleChange(
value: any,
submitOnChange: boolean = this.props.$schema.submitOnChange,
changeImmediately: boolean = false
) {
const {
formStore: form,
onChange,
$schema: {
type,
pipeOut,
changeImmediately: conrolChangeImmediately
},
formInited,
data
} = this.props;
if (
!this.model ||
// todo 以后想办法不要強耦合类型。
~[
'service',
'group',
'hbox',
'panel',
'grid',
'input-group'
].indexOf(type)
) {
onChange && onChange.apply(null, arguments as any);
return;
}
if (pipeOut) {
const oldValue = this.model.value;
value = pipeOut(value, oldValue, data);
}
this.model.changeTmpValue(value);
if (changeImmediately || conrolChangeImmediately || !formInited) {
this.emitChange(submitOnChange);
} else {
// this.props.onTmpValueChange?.(value, this.model.name);
this.lazyEmitChange(submitOnChange);
}
}
emitChange(
submitOnChange: boolean = this.props.$schema.submitOnChange
) {
const {
formStore: form,
onChange,
$schema: {
name,
id,
label,
type,
onChange: onFormItemChange,
maxLength,
minLength
},
data,
env,
validateOnChange,
formSubmited
} = this.props;
if (!this.model) {
return;
}
const value = this.model.tmpValue;
const oldValue = getVariable(data, this.model.name, false);
if (oldValue === value) {
return;
}
if (type !== 'input-password') {
env?.tracker(
{
eventType: 'formItemChange',
eventData: {
id,
name,
label,
type,
value
}
},
this.props
);
}
this.model.changeEmitedValue(value);
if (
onFormItemChange?.(value, oldValue, this.model, form) === false
) {
return;
}
const validated = this.model.validated;
onChange?.(value, name!, submitOnChange === true);
if (
// 如果配置了 minLength 或者 maxLength 就切成及时验证
// this.model.rules.minLength ||
// this.model.rules.maxLength ||
validateOnChange === true ||
(validateOnChange !== false && (formSubmited || validated))
) {
this.validate();
} else if (validateOnChange === false) {
this.model?.reset();
}
}
handleBlur(e: any) {
const {
onBlur,
$schema: {validateOnBlur}
} = this.props;
if (validateOnBlur && this.model) {
this.validate();
}
onBlur && onBlur(e);
}
setPrinstineValue(value: any) {
if (!this.model) {
return;
}
const {
formStore: form,
name,
$schema: {pipeOut},
onChange,
value: oldValue,
data
} = this.props;
if (pipeOut) {
value = pipeOut(value, oldValue, data);
}
onChange?.(value, name!, false, true);
}
getValue() {
const {formStore: data, $schema: control} = this.props;
let value: any = this.model ? this.model.tmpValue : control.value;
if (control.pipeIn) {
value = control.pipeIn(value, data);
}
return value;
}
// 兼容老版本用法,新版本直接用 onChange 就可以。
setValue(value: any, key?: string) {
const {
$schema: {name},
onBulkChange
} = this.props;
if (!key || key === name) {
this.handleChange(value);
} else {
onBulkChange &&
onBulkChange({
[key]: value
});
}
}
render() {
const {
controlWidth,
disabled,
formMode,
$schema: control,
store,
data,
invisible
} = this.props;
if (invisible) {
return null;
}
const value = this.getValue();
const model = this.model;
const injectedProps: any = {
defaultSize: controlWidth,
disabled: disabled || control.disabled,
formItem: this.model,
formMode: control.mode || formMode,
ref: this.controlRef,
data: data || store?.data,
value,
defaultValue: control.value,
formItemValue: value, // 为了兼容老版本的自定义组件
onChange: this.handleChange,
onBlur: this.handleBlur,
setValue: this.setValue,
getValue: this.getValue,
prinstine: model ? model.prinstine : undefined,
setPrinstineValue: this.setPrinstineValue
};
return (
<ComposedComponent
{...(this.props as JSX.LibraryManagedAttributes<
T,
React.ComponentProps<T>
>)}
{...injectedProps}
/>
);
}
}
) as any
),
ComposedComponent
);
return result as typeof result & {
ComposedComponent: T;
};
}
|
zhangtao07/amis
|
src/renderers/Form/Checkbox.tsx
|
<reponame>zhangtao07/amis
import React from 'react';
import {FormItem, FormControlProps, FormBaseControl} from './Item';
import cx from 'classnames';
import Checkbox from '../../components/Checkbox';
import {withBadge, BadgeSchema} from '../../components/Badge';
import {autobind, createObject} from '../../utils/helper';
import {Action} from '../../types';
/**
* Checkbox 勾选框。
* 文档:https://baidu.gitee.io/amis/docs/components/form/checkbox
*/
export interface CheckboxControlSchema extends FormBaseControl {
/**
* 指定为多行文本输入框
*/
type: 'checkbox';
/**
* 勾选值
*/
trueValue?: boolean | string | number;
/**
* 未勾选值
*/
falseValue?: boolean | string | number;
/**
* 选项说明
*/
option?: string;
/**
* 角标
*/
badge?: BadgeSchema;
partial?: boolean;
optionType?: 'default' | 'button';
checked?: boolean;
}
export interface CheckboxProps
extends FormControlProps,
Omit<
CheckboxControlSchema,
'type' | 'className' | 'descriptionClassName' | 'inputClassName'
> {}
export default class CheckboxControl extends React.Component<
CheckboxProps,
any
> {
static defaultProps: Partial<CheckboxProps> = {
trueValue: true,
falseValue: false
};
doAction(action: Action, data: object, throwErrors: boolean) {
const {resetValue, onChange} = this.props;
const actionType = action?.actionType as string;
if (actionType === 'clear') {
onChange('');
} else if (actionType === 'reset') {
onChange(resetValue ?? '');
}
}
@autobind
async dispatchChangeEvent(eventData: any = {}) {
const {dispatchEvent, data, onChange} = this.props;
const rendererEvent = await dispatchEvent(
'change',
createObject(data, {
value: eventData
})
);
if (rendererEvent?.prevented) {
return;
}
onChange && onChange(eventData);
}
render() {
const {
className,
value,
trueValue,
falseValue,
option,
onChange,
disabled,
render,
partial,
optionType,
checked,
classPrefix: ns
} = this.props;
return (
<div className={cx(`${ns}CheckboxControl`, className)}>
<Checkbox
inline
value={value || ''}
trueValue={trueValue}
falseValue={falseValue}
disabled={disabled}
onChange={(value: any) => this.dispatchChangeEvent(value)}
partial={partial}
optionType={optionType}
checked={checked}
>
{option ? render('option', option) : null}
</Checkbox>
</div>
);
}
}
// @ts-ignore
@withBadge
@FormItem({
type: 'checkbox',
sizeMutable: false
})
export class CheckboxControlRenderer extends CheckboxControl {}
|
zhangtao07/amis
|
src/actions/ToastAction.ts
|
import {RendererEvent} from '../utils/renderer-event';
import {
RendererAction,
ListenerContext,
registerAction,
ListenerAction
} from './Action';
export interface IToastAction extends ListenerAction {
actionType: 'toast';
args: {
msg: string;
msgType?: string;
position?:
| 'top-right'
| 'top-center'
| 'top-left'
| 'bottom-center'
| 'bottom-left'
| 'bottom-right'
| 'center';
closeButton?: boolean;
showIcon?: boolean;
timeout?: number;
};
}
/**
* 全局toast
*/
export class ToastAction implements RendererAction {
async run(
action: IToastAction,
renderer: ListenerContext,
event: RendererEvent<any>
) {
if (!renderer.props.env?.notify) {
throw new Error('env.notify is required!');
}
event.context.env.notify?.(
action.args?.msgType || 'info',
String(action.args?.msg),
action.args
);
}
}
registerAction('toast', new ToastAction());
|
zhangtao07/amis
|
src/components/schema-editor/SchemaVariableListPicker.tsx
|
import React from 'react';
import {localeable} from '../../locale';
import {themeable} from '../../theme';
import PickerContainer from '../PickerContainer';
import SchemaVariableList, {
SchemaVariableListProps
} from './SchemaVariableList';
export interface SchemaVariableListPickerProps extends SchemaVariableListProps {
children: (props: {
onClick: (e: React.MouseEvent) => void;
setState: (state: any) => void;
isOpened: boolean;
}) => JSX.Element;
value?: any;
title?: string;
onConfirm?: (value?: any) => void;
onCancel?: () => void;
onPickerOpen?: (props: any) => any;
}
export class SchemaVariableListPicker extends React.Component<SchemaVariableListPickerProps> {
render() {
const {
translate: __,
schemas,
value,
onConfirm,
onCancel,
children,
title,
selectMode,
beforeBuildVariables,
onPickerOpen
} = this.props;
return (
<PickerContainer
onPickerOpen={onPickerOpen}
title={title ?? __('Select.placeholder')}
bodyRender={({value, onChange, schemas: stateSchemas, isOpened}) => {
return isOpened ? (
<SchemaVariableList
value={value?.value ?? value}
onSelect={(value, schema) =>
onChange({
value,
schema
})
}
schemas={stateSchemas ?? schemas}
selectMode={selectMode}
beforeBuildVariables={beforeBuildVariables}
/>
) : (
<></>
);
}}
value={value}
onConfirm={onConfirm}
onCancel={onCancel}
>
{children}
</PickerContainer>
);
}
}
export default localeable(themeable(SchemaVariableListPicker));
|
zhangtao07/amis
|
src/components/Rating.tsx
|
<reponame>zhangtao07/amis<filename>src/components/Rating.tsx
/**
* @file Rating
* @description
* @author fex
*/
import React from 'react';
import cx from 'classnames';
import {ClassNamesFn, themeable} from '../theme';
import {isObject} from '../utils/helper';
import {
validations
} from '../utils/validations';
import {Icon} from './icons';
export type textPositionType = 'left' | 'right';
interface RatingProps {
id?: string;
key?: string | number;
style?: React.CSSProperties;
count: number;
half: boolean;
char: string | React.ReactNode;
className?: string;
charClassName?: string;
textClassName?: string;
onChange?: (value: number) => void;
onHoverChange?: (value: number) => void;
value: number;
containerClass?: string;
readOnly: boolean;
classPrefix: string;
disabled?: boolean;
allowClear?: boolean;
inactiveColor?: string;
colors?: string | {[propName: string]: string};
texts?: {[propName: string]: string};
textPosition?: textPositionType;
classnames: ClassNamesFn;
}
export class Rating extends React.Component<RatingProps, any> {
static defaultProps = {
containerClass: 'rating',
readOnly: false,
half: true,
allowClear: true,
value: 0,
count: 5,
char: <Icon icon="star" className="icon" />,
colors: {
'2': '#abadb1',
'3': '#787b81',
'5': '#ffa900'
},
textPosition: 'right' as textPositionType
};
starsNode: Record<string, any>;
constructor(props: RatingProps) {
super(props);
this.starsNode = {};
this.state = {
value: props.value || 0,
stars: [],
isClear: false,
halfStar: {
at: Math.floor(props.value),
hidden: props.half && props.value % 1 < 0.5
},
showColor: '',
showText: null,
hoverValue: null
};
this.getRate = this.getRate.bind(this);
this.getStars = this.getStars.bind(this);
this.moreThanHalf = this.moreThanHalf.bind(this);
this.mouseOver = this.mouseOver.bind(this);
this.mouseLeave = this.mouseLeave.bind(this);
this.handleClick = this.handleClick.bind(this);
this.saveRef = this.saveRef.bind(this);
this.handleStarMouseLeave = this.handleStarMouseLeave.bind(this);
}
componentDidMount() {
const {value} = this.state;
this.setState({
stars: this.getStars(value)
});
this.getShowColorAndText(value);
}
componentDidUpdate(prevProps: RatingProps) {
const props = this.props;
if (props.value !== prevProps.value) {
this.setState({
stars: this.getStars(props.value),
value: props.value,
halfStar: {
at: Math.floor(props.value),
hidden: props.half && props.value % 1 < 0.5
}
}, () => {
this.getShowColorAndText(props.value);
});
}
}
sortKeys(map: {[propName: number]: string}) {
// 需验证 key 是否是数字,需要过滤掉非数字key,如 $$id
return Object.keys(map).filter(item => validations.isNumeric({}, item)).sort(
(a: number | string, b: number | string) => Number(a) - Number(b)
);
}
getShowColorAndText(value: number) {
const {colors, texts, half} = this.props;
if (!value)
return this.setState({
showText: null
});
// 对 value 取整
if (half) {
value = Math.floor(Number(value) * 2) / 2;
} else {
value = Math.floor(value);
}
if (colors && typeof colors !== 'string') {
const keys: string[] = this.sortKeys(colors);
const showKey = keys.filter(item => Number(item) < value).length;
const showColor = keys[showKey] !== undefined && colors[keys[showKey]];
// 取最大 key 的颜色,避免如下情况:colors 只设置了 1-4,value 为 5,导致取不到颜色而无法显示
const lastColor = keys.length && colors[keys[keys.length - 1]];
this.setState({
showColor: showColor || lastColor || ''
});
} else if (colors && typeof colors === 'string') {
this.setState({
showColor: colors
});
}
if (texts && isObject(texts)) {
const keys: string[] = this.sortKeys(texts);
const showKey = keys.filter(item => Number(item) < value).length;
const showText =
keys[showKey] !== undefined &&
texts[keys[showKey] as keyof typeof texts];
this.setState({
showText: showText || ''
});
}
}
getRate() {
let stars;
const {value} = this.state;
const {half} = this.props;
if (half) {
stars = Math.floor(value);
} else {
stars = Math.round(value);
}
return stars;
}
getStars(activeCount?: number) {
if (typeof activeCount === 'undefined') {
activeCount = this.getRate();
}
let stars = [];
const {count} = this.props;
for (let i = 0; i < count; i++) {
stars.push({
active: i <= activeCount - 1
});
}
return stars;
}
saveRef(index: number) {
return (node: React.ReactNode) => {
this.starsNode[String(index)] = node;
};
}
mouseOver(event: React.ChangeEvent<any>, index: number) {
const {isClear} = this.state;
if (isClear) return;
const {readOnly, half} = this.props;
if (readOnly) return;
if (half) {
const isAtHalf = this.moreThanHalf(event, index);
const tmpValue = isAtHalf ? index + 1 : index + 0.5;
this.getShowColorAndText(tmpValue);
this.onHoverChange(tmpValue);
if (isAtHalf) index = index + 1;
this.setState({
halfStar: {
at: index,
hidden: isAtHalf
}
});
} else {
index = index + 1;
this.onHoverChange(index);
this.getShowColorAndText(index);
}
this.setState({
stars: this.getStars(index)
});
}
onHoverChange(value: number) {
const {onHoverChange} = this.props;
const {hoverValue} = this.state;
if (!hoverValue || (hoverValue && hoverValue !== value)) {
this.setState({
hoverValue: value
});
onHoverChange && onHoverChange(value);
}
}
moreThanHalf(event: any, index: number) {
const star = this.starsNode[index];
const leftPos = star.getBoundingClientRect().left;
return event.clientX - leftPos > star.clientWidth / 2;
}
mouseLeave() {
const {value, isClear} = this.state;
const {half, readOnly} = this.props;
if (readOnly) return;
if (isClear)
return this.setState({
isClear: false,
hoverValue: null
});
if (half) {
this.setState({
halfStar: {
at: Math.floor(value),
hidden: value % 1 === 0 // check value is decimal or not
}
});
}
this.setState({
stars: this.getStars(),
hoverValue: null
});
this.getShowColorAndText(value);
}
handleStarMouseLeave(event: any, index: number) {
const star = this.starsNode[index];
const leftSideX = star.getBoundingClientRect().left;
const {isClear} = this.state;
if (isClear) return this.setState({isClear: false});
// leave star from left side
if (event.clientX <= leftSideX) {
this.getShowColorAndText(index);
this.setState({
stars: this.getStars(index),
halfStar: {
at: index,
hidden: true
}
});
}
}
handleClick(event: React.ChangeEvent<any>, index: number) {
const {half, readOnly, onChange, allowClear} = this.props;
if (readOnly) return;
let value;
if (half) {
const isAtHalf = this.moreThanHalf(event, index);
if (isAtHalf) index = index + 1;
value = isAtHalf ? index : index + 0.5;
this.setState({
halfStar: {
at: index,
hidden: isAtHalf
}
});
} else {
value = index = index + 1;
}
const isClear = allowClear && value === this.state.value;
if (isClear) value = index = 0;
this.setState({
value,
stars: this.getStars(index),
isClear
});
this.getShowColorAndText(value);
onChange && onChange(value);
}
renderStars() {
const {halfStar, stars, showColor} = this.state;
const {
inactiveColor,
char,
half,
disabled,
readOnly,
charClassName,
classnames: cx
} = this.props;
return (
<ul onMouseLeave={this.mouseLeave}>
{stars.map((star: any, i: number) => {
const isThisHalf = half && !halfStar.hidden && halfStar.at === i;
return (
<li
ref={this.saveRef(i)}
className={cx('Rating-star', charClassName, {
'is-half': isThisHalf,
'is-active': star.active,
'is-disabled': readOnly || disabled
})}
key={i}
style={{
color: star.active ? showColor : inactiveColor
}}
onMouseOver={e => this.mouseOver(e, i)}
onMouseMove={e => this.mouseOver(e, i)}
onClick={e => this.handleClick(e, i)}
onMouseLeave={e => this.handleStarMouseLeave(e, i)}
>
{isThisHalf && (
<div
className={cx('Rating-star-half')}
style={{
color: showColor
}}
>
{char}
</div>
)}
{char}
</li>
);
})}
</ul>
);
}
renderText() {
const {showText} = this.state;
const {textClassName, textPosition, classnames: cx} = this.props;
if (!showText) return null;
return (
<span
className={cx('Rating-text', textClassName, {
[`Rating-text--${textPosition === 'left' ? 'left' : 'right'}`]:
textPosition
})}
>
{showText}
</span>
);
}
render() {
const {className, textPosition, classnames: cx} = this.props;
return (
<div className={cx('Rating', className)}>
{textPosition === 'left' ? (
<>
{this.renderText()}
{this.renderStars()}
</>
) : (
<>
{this.renderStars()}
{this.renderText()}
</>
)}
</div>
);
}
}
export default themeable(Rating);
|
zhangtao07/amis
|
src/renderers/Remark.tsx
|
<reponame>zhangtao07/amis<gh_stars>0
import React from 'react';
import {Renderer, RendererProps} from '../factory';
import {Api, SchemaNode, Schema, Action} from '../types';
import cx from 'classnames';
import TooltipWrapper, {TooltipObject} from '../components/TooltipWrapper';
import {filter} from '../utils/tpl';
import {ClassNamesFn, themeable} from '../theme';
import {hasIcon, Icon} from '../components/icons';
import {BaseSchema, SchemaClassName, SchemaIcon, SchemaTpl} from '../Schema';
import {autobind, isMobile} from '../utils/helper';
/**
* 提示渲染器,默认会显示个小图标,鼠标放上来的时候显示配置的内容。
*/
export interface RemarkSchema extends BaseSchema {
/**
* 指定为提示类型
*/
type: 'remark';
label?: string;
icon?: SchemaIcon;
tooltipClassName?: SchemaClassName;
/**
* 触发规则
*/
trigger?: Array<'click' | 'hover' | 'focus'>;
/**
* 提示标题
*/
title?: string;
/**
* 提示内容
*/
content: SchemaTpl;
/**
* 显示位置
*/
placement?: 'top' | 'right' | 'bottom' | 'left';
/**
* 点击其他内容时是否关闭弹框信息
*/
rootClose?: boolean;
/**
* icon的形状
*/
shape?: 'circle' | 'square';
}
export type SchemaRemark = string | Omit<RemarkSchema, 'type'>;
export function filterContents(
tooltip:
| string
| undefined
| {title?: string; children?: any; content?: string; body?: string},
data: any
) {
if (typeof tooltip === 'string') {
return filter(tooltip, data);
} else if (tooltip) {
return tooltip.title
? {
children: tooltip?.children,
title: filter(tooltip.title, data),
content:
tooltip.content || tooltip.body
? filter(tooltip.content || tooltip.body || '', data)
: undefined
}
: tooltip.content || tooltip.body
? filter(tooltip.content || tooltip.body || '', data)
: undefined;
}
return tooltip;
}
export interface RemarkProps
extends RendererProps,
Omit<RemarkSchema, 'type' | 'className'> {
icon: string;
trigger: Array<'hover' | 'click' | 'focus'>;
}
class Remark extends React.Component<RemarkProps> {
static propsList: Array<string> = [];
static defaultProps = {
icon: '',
trigger: ['hover', 'focus'] as Array<'hover' | 'click' | 'focus'>
};
@autobind
showModalTip(tooltip?: string | TooltipObject) {
let {onAction, data} = this.props;
return (e: React.MouseEvent) => {
onAction &&
onAction(
e,
{
actionType: 'dialog',
dialog: {
title:
tooltip && typeof tooltip !== 'string' ? tooltip.title : '',
body:
tooltip && typeof tooltip !== 'string'
? tooltip.content
: tooltip,
actions: []
}
},
data
);
};
}
renderLabel(finalIcon: any, finalLabel: string, cx: ClassNamesFn, shape?: 'circle'|'square') {
const shapeClass = shape ? `Remark-icon--${shape}` : undefined;
return (
<>
{finalLabel ? <span>{finalLabel}</span> : null}
{finalIcon ? (
hasIcon(finalIcon) ? (
<span className={cx('Remark-icon', shapeClass)}>
<Icon icon={finalIcon} />
</span>
) : (
<i className={cx('Remark-icon', finalIcon)} />
)
) : finalIcon === false && finalLabel ? null : (
<span className={cx('Remark-icon icon', shapeClass)}>
<Icon icon="question-mark" />
</span>
)}
</>
);
}
render() {
const {
className,
icon,
label,
shape,
tooltip,
placement,
rootClose,
trigger,
container,
classPrefix: ns,
classnames: cx,
content,
data,
env,
tooltipClassName,
useMobileUI
} = this.props;
const finalIcon = tooltip?.icon ?? icon;
const finalLabel = tooltip?.label ?? label;
const parsedTip = filterContents(tooltip || content, data);
// 移动端使用弹框提示
if (isMobile() && useMobileUI) {
return (
<div
className={cx(
`Remark`,
(tooltip && tooltip.className) || className || `Remark--warning`
)}
onClick={this.showModalTip(parsedTip)}
>
{this.renderLabel(finalIcon, finalLabel, cx, shape)}
</div>
);
}
return (
<TooltipWrapper
classPrefix={ns}
classnames={cx}
tooltip={parsedTip}
tooltipClassName={
(tooltip && tooltip.tooltipClassName) || tooltipClassName
}
placement={(tooltip && tooltip.placement) || placement}
rootClose={(tooltip && tooltip.rootClose) || rootClose}
trigger={(tooltip && tooltip.trigger) || trigger}
container={container || env.getModalContainer}
delay={tooltip && tooltip.delay}
>
<div
className={cx(
`Remark`,
(tooltip && tooltip.className) || className || `Remark--warning`
)}
>
{this.renderLabel(finalIcon, finalLabel, cx, shape)}
</div>
</TooltipWrapper>
);
}
}
export default themeable(Remark);
@Renderer({
type: 'remark'
})
export class RemarkRenderer extends Remark {}
|
zhangtao07/amis
|
__tests__/renderers/Form/chainedSelect.test.tsx
|
import React = require('react');
import {render, waitForElementToBeRemoved} from '@testing-library/react';
import '../../../src/themes/default';
import {render as amisRender} from '../../../src/index';
import {makeEnv, wait} from '../../helper';
test('Renderer:chained-select', async () => {
const {container, findByText} = render(
amisRender(
{
type: 'form',
debug: true,
api: '/api/mock2/form/saveForm',
body: [
{
name: 'select3',
type: 'chained-select',
label: '级联下拉',
source:
'/api/mock2/options/chainedOptions?parentId=$parentId&level=$level&maxLevel=4',
value: 'a,b'
}
]
},
{},
makeEnv({
fetcher: async (config: any) => {
return {
status: 200,
headers: {},
data: {
status: 0,
msg: '',
data: [
{label: 'A 0', value: 'a'},
{label: 'B 0', value: 'b'},
{label: 'C 0', value: 'c'},
{label: 'D 0', value: 'd'}
]
}
};
}
})
)
);
await wait(500);
expect(container).toMatchSnapshot();
});
|
zhangtao07/amis
|
examples/components/theme/vars.tsx
|
<gh_stars>0
/**
* 基础变量配置项,生成对应的 combo 配置项
*/
const colors = [
{
label: '文字颜色',
name: '--text-color',
cxdValue: '#666',
antdValue: 'rgba(0, 0, 0, 0.85)'
},
{
label: '文字置灰时的颜色',
name: '--text--muted-color',
cxdValue: '#a6a6a6',
antdValue: 'rgba(64, 64, 64, 0.85)'
},
{
label: '标题文字颜色',
name: '--text--loud-color',
cxdValue: '#4d4d4d',
antdValue: 'rgba(0, 0, 0, 0.85)'
},
{
label: '按钮文字颜色',
name: '--button-color',
cxdValue: '#fff',
antdValue: '#fff'
},
{label: '最浅色', name: '--light', cxdValue: '#eaf6fe', antdValue: '#d9d9d9'},
{label: '最深色', name: '--dark', cxdValue: '#343a40', antdValue: '#343a40'},
{
label: '全局背景色',
name: '--body-bg',
cxdValue: '#eaf6fe',
antdValue: '#d9d9d9'
},
{
label: '常用背景色',
name: '--background',
cxdValue: '#fff',
antdValue: '#fff'
},
{
label: '主颜色',
name: '--primary',
cxdValue: '#108cee',
antdValue: '#1890ff'
},
{
label: '主颜色鼠标放上去的颜色',
name: '--primary-onHover',
cxdValue: '#0e77ca',
antdValue: '#007df1'
},
{
label: '主颜色激活时的颜色',
name: '--primary-onActive',
cxdValue: '#0d70be',
antdValue: '#0076e4'
},
{
label: '次颜色',
name: '--secondary',
cxdValue: '#6c757d',
antdValue: '#6c757d'
},
{
label: '次颜色鼠标放上去的颜色',
name: '--secondary-onHover',
cxdValue: '#5a6268',
antdValue: '#5a6268'
},
{
label: '次颜色激活时的颜色',
name: '--secondary-onActive',
cxdValue: '#545b62',
antdValue: '#545b62'
},
{
label: '成功时的颜色',
name: '--success',
cxdValue: '#5fb333',
antdValue: '#52c41a'
},
{
label: '成功时在鼠标移上去后的颜色',
name: '--success-onHover',
cxdValue: '#4f952b',
antdValue: '#44a216'
},
{
label: '成功时激活的颜色',
name: '--success-onActive',
cxdValue: '#4a8b28',
antdValue: '#3f9714'
},
{
label: '信息的颜色',
name: '--info',
cxdValue: '#108cee',
antdValue: '#1890ff'
},
{
label: '信息在鼠标移上去后的颜色',
name: '--info-onHover',
cxdValue: '#0e77ca',
antdValue: '#007df1'
},
{
label: '信息在激活时的颜色',
name: '--info-onActive',
cxdValue: '#0d70be',
antdValue: '#0076e4'
},
{
label: '警告的颜色',
name: '--warning',
cxdValue: '#f39000',
antdValue: '#faad14'
},
{
label: '警告在鼠标移上去后的颜色',
name: '--warning-onHover',
cxdValue: '#cd7900',
antdValue: '#e39905'
},
{
label: '警告在鼠标移上去后的颜色',
name: '--warning-onActive',
cxdValue: '#c07200',
antdValue: '#d69005'
},
{
label: '错误的颜色',
name: '--danger',
cxdValue: '#ea2e2e',
antdValue: '#ff4d4f'
},
{
label: '错误在鼠标移上去后的颜色',
name: '--danger-onHover',
cxdValue: '#dc1616',
antdValue: '#ff2729'
},
{
label: '错误在激活时的颜色',
name: '--danger-onActive',
cxdValue: '#d01515',
antdValue: '#ff1a1d'
}
];
export const colorControls: any = [];
for (const color of colors) {
colorControls.push({
type: 'group',
controls: [
{
type: 'input-color',
label: color.label,
name: `config.theme._vars["${color.name}"]`
},
{
label: '云舍默认值',
type: 'static-color',
value: color.cxdValue,
visibleOn: 'data.config.theme.baseTheme === "cxd"',
inputClassName: 'text-xs'
},
{
label: 'AntD 默认值',
type: 'static-color',
value: color.antdValue,
visibleOn: 'data.config.theme.baseTheme === "antd"',
inputClassName: 'text-xs'
}
]
});
}
const fonts = [
{
label: '基础字体',
name: '--fontFamilyBase',
defaultValue:
"-apple-system, BlinkMacSystemFont, 'SF Pro SC', 'SF Pro Text', 'Helvetica Neue', Helvetica, 'PingFang SC', 'Segoe UI', Roboto, 'Hiragino Sans GB', 'Arial', 'microsoft yahei ui', 'Microsoft YaHei',SimSun, sans-serif"
},
{
label: '等宽字体',
name: '--fontFamilyMonospace',
defaultValue:
"SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"
},
{
label: '基础字体大小',
name: '--fontSizeBase',
defaultValue: '14px'
},
{
label: '最小字体大小',
name: '--fontSizeXs',
defaultValue: '11px'
},
{
label: '小字体大小',
name: '--fontSizeSm',
defaultValue: '12px'
},
{
label: '中型字体大小',
name: '--fontSizeMd',
defaultValue: '14px'
},
{
label: '大字体大小',
name: '--fontSizeLg',
defaultValue: '16px'
},
{
label: '超大字体大小',
name: '--fontSizeXl',
defaultValue: '20px'
},
{
label: '行高',
name: '--lineHeightBase',
defaultValue: '1.5'
}
];
export const fontControls: any = [];
for (const font of fonts) {
fontControls.push({
type: 'input-text',
label: font.label,
name: `config.theme._vars["${font.name}"]`,
placeholder: font.defaultValue
});
}
const sizes = [
{
label: '基础间距',
name: '--gap-base',
defaultValue: '12px'
},
{
label: '最小间距',
name: '--gap-xs',
defaultValue: '4px'
},
{
label: '小间距',
name: '--gap-sm',
defaultValue: '8px'
},
{
label: '中间距',
name: '--gap-md',
defaultValue: '16px'
},
{
label: '小间距',
name: '--gap-lg',
defaultValue: '20px'
},
{
label: '小间距',
name: '--gap-xl',
defaultValue: '24px'
}
];
export const sizeControls: any = [];
for (const size of sizes) {
sizeControls.push({
type: 'input-text',
label: size.label,
name: `config.theme._vars["${size.name}"]`,
placeholder: size.defaultValue
});
}
export const borderControls: any = [
{
type: 'input-color',
label: '边框颜色',
name: 'config.theme._vars["--buttonColor"]'
},
{
type: 'input-text',
label: '边框圆角大小',
placeholder: '2px',
name: 'config.theme._vars["--borderRadius"]'
}
];
export const linkControls: any = [
{
type: 'input-color',
label: '链接颜色',
name: 'config.theme._vars["--link-color"]'
},
{
type: 'input-color',
label: '链接在鼠标移上去的颜色',
name: 'config.theme._vars["--link-onHover-color"]'
},
{
type: 'input-text',
label: '链接下划线',
placeholder: 'none',
name: 'config.theme._vars["--link-decoration"]'
},
{
type: 'input-text',
label: '链接在鼠标移上去后端下划线',
placeholder: 'none',
name: 'config.theme._vars["--link-onHover-decoration"]'
}
];
|
zhangtao07/amis
|
src/renderers/Table-v2/TableCell.tsx
|
<reponame>zhangtao07/amis<gh_stars>0
import {Renderer} from '../../factory';
import {TableCell} from '../Table';
import QuickEdit from '../QuickEdit';
import Copyable from '../Copyable';
import PopOverable from '../PopOver';
@Renderer({
type: 'cell-field',
name: 'cell-field'
})
@PopOverable()
@Copyable()
@QuickEdit()
export class CellFieldRenderer extends TableCell {
static defaultProps = {
...TableCell.defaultProps,
wrapperComponent: 'div'
};
}
|
zhangtao07/amis
|
src/SchemaRenderer.tsx
|
import difference from 'lodash/difference';
import omit from 'lodash/omit';
import React from 'react';
import LazyComponent from './components/LazyComponent';
import {
filterSchema,
loadRenderer,
RendererComponent,
RendererConfig,
RendererEnv,
RendererProps,
resolveRenderer
} from './factory';
import {asFormItem} from './renderers/Form/Item';
import {renderChild, renderChildren} from './Root';
import {ScopedContext} from './Scoped';
import {Schema, SchemaNode} from './types';
import {DebugWrapper} from './utils/debug';
import getExprProperties from './utils/filter-schema';
import {anyChanged, chainEvents, autobind} from './utils/helper';
import {SimpleMap} from './utils/SimpleMap';
import {bindEvent, dispatchEvent, RendererEvent} from './utils/renderer-event';
import {isAlive} from 'mobx-state-tree';
import {reaction} from 'mobx';
import {resolveVariableAndFilter} from './utils/tpl-builtin';
interface SchemaRendererProps extends Partial<RendererProps> {
schema: Schema;
$path: string;
env: RendererEnv;
}
const defaultOmitList = [
'type',
'name',
'$ref',
'className',
'data',
'children',
'ref',
'visible',
'visibleOn',
'hidden',
'hiddenOn',
'disabled',
'disabledOn',
'component',
'detectField',
'defaultValue',
'defaultData',
'required',
'requiredOn',
'syncSuperStore',
'mode',
'body'
];
const componentCache: SimpleMap = new SimpleMap();
export class SchemaRenderer extends React.Component<SchemaRendererProps, any> {
static displayName: string = 'Renderer';
static contextType = ScopedContext;
rendererKey = '';
renderer: RendererConfig | null;
ref: any;
cRef: any;
schema: any;
path: string;
reaction: any;
unbindEvent: (() => void) | undefined = undefined;
constructor(props: SchemaRendererProps) {
super(props);
this.refFn = this.refFn.bind(this);
this.renderChild = this.renderChild.bind(this);
this.reRender = this.reRender.bind(this);
this.resolveRenderer(this.props);
this.dispatchEvent = this.dispatchEvent.bind(this);
// 监听rootStore更新
this.reaction = reaction(
() =>
`${props.rootStore.visibleState[props.schema.id || props.$path]}${
props.rootStore.disableState[props.schema.id || props.$path]
}`,
() => this.forceUpdate()
);
}
componentDidMount() {
// 这里无法区分监听的是不是广播,所以又bind一下,主要是为了绑广播
this.unbindEvent = bindEvent(this.cRef);
}
componentWillUnmount() {
this.reaction?.();
this.unbindEvent?.();
}
// 限制:只有 schema 除外的 props 变化,或者 schema 里面的某个成员值发生变化才更新。
shouldComponentUpdate(nextProps: SchemaRendererProps) {
const props = this.props;
const list: Array<string> = difference(Object.keys(nextProps), [
'schema',
'scope'
]);
if (
difference(Object.keys(props), ['schema', 'scope']).length !==
list.length ||
anyChanged(list, this.props, nextProps)
) {
return true;
} else {
const list: Array<string> = Object.keys(nextProps.schema);
if (
Object.keys(props.schema).length !== list.length ||
anyChanged(list, props.schema, nextProps.schema)
) {
return true;
}
}
return false;
}
resolveRenderer(props: SchemaRendererProps, force = false): any {
let schema = props.schema;
let path = props.$path;
if (schema && schema.$ref) {
schema = {
...props.resolveDefinitions(schema.$ref),
...schema
};
path = path.replace(/(?!.*\/).*/, schema.type);
}
if (
schema?.type &&
(force ||
!this.renderer ||
this.rendererKey !== `${schema.type}-${schema.$$id}`)
) {
const rendererResolver = props.env.rendererResolver || resolveRenderer;
this.renderer = rendererResolver(path, schema, props);
this.rendererKey = `${schema.type}-${schema.$$id}`;
} else {
// 自定义组件如果在节点设置了 label name 什么的,就用 formItem 包一层
// 至少自动支持了 valdiations, label, description 等逻辑。
if (schema.children && !schema.component && schema.asFormItem) {
schema.component = PlaceholderComponent;
schema.renderChildren = schema.children;
delete schema.children;
}
if (
schema.component &&
!schema.component.wrapedAsFormItem &&
schema.asFormItem
) {
const cache = componentCache.get(schema.component);
if (cache) {
schema.component = cache;
} else {
const cache = asFormItem({
strictMode: false,
...schema.asFormItem
})(schema.component);
componentCache.set(schema.component, cache);
cache.wrapedAsFormItem = true;
schema.component = cache;
}
}
}
return {path, schema};
}
getWrappedInstance() {
return this.cRef;
}
refFn(ref: any) {
this.ref = ref;
}
@autobind
childRef(ref: any) {
while (ref && ref.getWrappedInstance) {
ref = ref.getWrappedInstance();
}
this.cRef = ref;
}
async dispatchEvent(
e: React.MouseEvent<any>,
data: any
): Promise<RendererEvent<any> | void> {
return await dispatchEvent(e, this.cRef, this.context, data);
}
renderChild(
region: string,
node?: SchemaNode,
subProps: {
data?: object;
[propName: string]: any;
} = {}
) {
let {schema: _, $path: __, env, ...rest} = this.props;
let {path: $path} = this.resolveRenderer(this.props);
const omitList = defaultOmitList.concat();
if (this.renderer) {
const Component = this.renderer.component;
Component.propsList &&
omitList.push.apply(omitList, Component.propsList as Array<string>);
}
return renderChild(`${$path}${region ? `/${region}` : ''}`, node || '', {
...omit(rest, omitList),
...subProps,
data: subProps.data || rest.data,
env: env
});
}
reRender() {
this.resolveRenderer(this.props, true);
this.forceUpdate();
}
render(): JSX.Element | null {
let {$path: _, schema: __, rootStore, ...rest} = this.props;
if (__ == null) {
return null;
}
let {path: $path, schema} = this.resolveRenderer(this.props);
const theme = this.props.env.theme;
if (Array.isArray(schema)) {
return renderChildren($path, schema as any, rest) as JSX.Element;
}
const detectData =
schema &&
(schema.detectField === '&' ? rest : rest[schema.detectField || 'data']);
const exprProps: any = detectData
? getExprProperties(schema, detectData, undefined, rest)
: {};
// 控制显隐
const visible = isAlive(rootStore)
? rootStore.visibleState[schema.id || $path]
: undefined;
const disable = isAlive(rootStore)
? rootStore.disableState[schema.id || $path]
: undefined;
if (
visible === false ||
(visible !== true &&
exprProps &&
(exprProps.hidden ||
exprProps.visible === false ||
schema.hidden ||
schema.visible === false ||
rest.hidden ||
rest.visible === false))
) {
(rest as any).invisible = true;
}
if (schema.children) {
return rest.invisible
? null
: React.isValidElement(schema.children)
? schema.children
: (schema.children as Function)({
...rest,
...exprProps,
$path: $path,
$schema: schema,
render: this.renderChild,
forwardedRef: this.refFn
});
} else if (typeof schema.component === 'function') {
const isSFC = !(schema.component.prototype instanceof React.Component);
const {
data: defaultData,
value: defaultValue,
activeKey: defaultActiveKey,
key: propKey,
...restSchema
} = schema;
return rest.invisible
? null
: React.createElement(schema.component as any, {
...rest,
...restSchema,
...exprProps,
defaultData,
defaultValue,
defaultActiveKey,
propKey,
$path: $path,
$schema: schema,
ref: isSFC ? undefined : this.refFn,
forwardedRef: isSFC ? this.refFn : undefined,
render: this.renderChild
});
} else if (Object.keys(schema).length === 0) {
return null;
} else if (!this.renderer) {
return rest.invisible ? null : (
<LazyComponent
{...rest}
{...exprProps}
getComponent={async () => {
const result = await rest.env.loadRenderer(
schema,
$path,
this.reRender
);
if (result && typeof result === 'function') {
return result;
} else if (result && React.isValidElement(result)) {
return () => result;
}
this.reRender();
return () => loadRenderer(schema, $path);
}}
$path={$path}
$schema={schema}
retry={this.reRender}
/>
);
}
const renderer = this.renderer as RendererConfig;
schema = filterSchema(schema, renderer, rest);
const {
data: defaultData,
value: defaultValue,
key: propKey,
activeKey: defaultActiveKey,
...restSchema
} = schema;
const Component = renderer.component;
// 原来表单项的 visible: false 和 hidden: true 表单项的值和验证是有效的
// 而 visibleOn 和 hiddenOn 是无效的,
// 这个本来就是个bug,但是已经被广泛使用了
// 我只能继续实现这个bug了
if (
rest.invisible &&
(exprProps.hidden ||
exprProps.visible === false ||
!renderer.isFormItem ||
(schema.visible !== false && !schema.hidden))
) {
return null;
}
const isClassComponent = Component.prototype?.isReactComponent;
const $schema = {...schema, ...exprProps};
let props = {
...theme.getRendererConfig(renderer.name),
...restSchema,
...chainEvents(rest, restSchema),
...exprProps,
defaultData: restSchema.defaultData ?? defaultData,
defaultValue: restSchema.defaultValue ?? defaultValue,
defaultActiveKey: defaultActiveKey,
propKey: propKey,
$path: $path,
$schema: $schema,
ref: this.refFn,
render: this.renderChild,
rootStore: rootStore,
dispatchEvent: this.dispatchEvent
};
if (disable) {
(props as any).disabled = true;
}
// 自动解析变量模式,主要是方便直接引入第三方组件库,无需为了支持变量封装一层
if (renderer.autoVar) {
for (const key of Object.keys($schema)) {
if (typeof props[key] === 'string') {
props[key] = resolveVariableAndFilter(
props[key],
props.data,
'| raw'
);
}
}
}
const component = isClassComponent ? (
<Component {...props} ref={this.childRef} />
) : (
<Component {...props} />
);
return this.props.env.enableAMISDebug ? (
<DebugWrapper renderer={renderer}>{component}</DebugWrapper>
) : (
component
);
}
}
class PlaceholderComponent extends React.Component {
render() {
const {renderChildren, ...rest} = this.props as any;
if (typeof renderChildren === 'function') {
return renderChildren(rest);
}
return null;
}
}
|
zhangtao07/amis
|
src/actions/SwitchAction.ts
|
import { RendererEvent } from '../utils/renderer-event';
import { evalExpression } from '../utils/tpl';
import {
RendererAction,
ListenerContext,
registerAction,
runActions,
ILogicAction
} from './Action';
export interface ISwitchAction extends ILogicAction {
actionType: 'switch';
}
/**
* 排他动作
*/
export class SwitchAction implements RendererAction {
async run(
action: ISwitchAction,
renderer: ListenerContext,
event: RendererEvent<any>,
mergeData: any
) {
for (const branch of action.children || []) {
if (!branch.expression) {
continue;
}
if (evalExpression(branch.expression, mergeData)) {
await runActions(branch, renderer, event);
// 去掉runAllMatch,这里只做排他,多个可以直接通过expression
break;
}
}
}
}
registerAction('switch', new SwitchAction());
|
zhangtao07/amis
|
src/utils/DataScope.ts
|
<filename>src/utils/DataScope.ts<gh_stars>0
import type {JSONSchema7} from 'json-schema';
import {guid, keyToPath, mapTree} from './helper';
// 先只支持 JSONSchema draft07 好了
// https://json-schema.org/draft-07/json-schema-release-notes.html
export type JSONSchema = JSONSchema7;
export class DataScope {
// 指向父级
parent?: DataScope;
readonly children: Array<DataScope> = [];
// 全局不能重复,用来快速定位
readonly id: string;
// todo 如果想要跨过层级直接获取某一层的数据域,用这个字段
ref?: string;
// scope 的名字,同一个层级不允许重名
name?: string;
// scope 分类
tag?: string;
// scope 的描述信息
description?: string;
readonly schemas: Array<JSONSchema> = [];
constructor(schemas: JSONSchema | Array<JSONSchema>, id: string) {
this.setSchemas(Array.isArray(schemas) ? schemas : [schemas]);
this.id = id;
}
addChild(id: string, schema?: JSONSchema | Array<JSONSchema>): DataScope {
const child = new DataScope(
schema || {
type: 'object',
properties: {}
},
id
);
this.children.push(child);
child.parent = this;
return child;
}
removeChild(idOrScope: string | DataScope) {
const idx = this.children.findIndex(item =>
typeof idOrScope === 'string' ? idOrScope === item.id : item === idOrScope
);
if (~idx) {
const scope = this.children[idx];
delete scope.parent;
this.children.splice(idx, 1);
}
}
setSchemas(schemas: Array<JSONSchema>) {
this.schemas.splice(0, this.schemas.length);
for (let schema of schemas) {
if (schema.type !== 'object') {
throw new TypeError('data scope accept only object');
}
this.schemas.push({
$id: guid(),
...schema
});
}
return this;
}
addSchema(schema: JSONSchema) {
schema = {
$id: guid(),
...schema
};
this.schemas.push(schema);
return this;
}
removeSchema(id: string) {
const idx = this.schemas.findIndex(schema => schema.$id === id);
if (~idx) {
this.schemas.splice(idx, 1);
}
return this;
}
contains(scope: DataScope) {
let from: DataScope | undefined = scope;
while (from) {
if (this === from) {
return true;
}
from = from.parent;
}
return false;
}
getMergedSchema() {
const mergedSchema: any = {
type: 'object',
properties: {}
};
// todo 以后再来细化这一块,先粗略的写个大概
this.schemas.forEach(schema => {
const properties: any = schema.properties || {};
Object.keys(properties).forEach(key => {
const value = properties[key];
if (mergedSchema.properties[key]) {
if (Array.isArray(mergedSchema.properties[key].oneOf)) {
mergedSchema.properties[key].oneOf.push();
} else if (
mergedSchema.properties[key].type &&
mergedSchema.properties[key].type !== value.type
) {
mergedSchema.properties[key] = {
oneOf: [mergedSchema.properties[key], value]
};
}
} else {
mergedSchema.properties[key] = value;
}
});
});
return mergedSchema;
}
protected buildOptions(
options: Array<any>,
schema: JSONSchema,
path: string = '',
key: string = ''
) {
// todo 支持 oneOf, anyOf
const option: any = {
label: schema.title || key,
value: path,
type: schema.type,
description: schema.description
};
options.push(option);
if (schema.type === 'object' && schema.properties) {
option.children = [];
const keys = Object.keys(schema.properties);
keys.forEach(key => {
const child: any = schema.properties![key];
this.buildOptions(
option.children,
child,
path + (path ? '.' : '') + key,
key
);
});
} else if (schema.type === 'array' && schema.items) {
option.children = [];
this.buildOptions(
option.children,
{
title: 'Member',
...(schema.items as any)
},
path + (path ? '.' : '') + 'items',
'items'
);
option.children = mapTree(option.children, item => ({
...item,
disabled: true
}));
}
}
getDataPropsAsOptions() {
const variables: Array<any> = [];
this.buildOptions(variables, this.getMergedSchema());
return variables[0].children;
}
getSchemaByPath(path: string) {
const parts = keyToPath(path);
for (let schema of this.schemas) {
const result = parts.reduce((schema: JSONSchema, key: string) => {
if (schema && schema.type === 'object' && schema.properties) {
return schema.properties[key] as JSONSchema;
}
return null;
}, schema);
if (result) {
return result;
}
}
return null;
}
}
|
zhangtao07/amis
|
__tests__/renderers/Form/select.test.tsx
|
<gh_stars>0
import React = require('react');
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import '../../../src/themes/default';
import {render as amisRender} from '../../../src/index';
import {makeEnv, wait} from '../../helper';
test('Renderer:select menutpl', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'form',
body: [
{
label: '选项',
type: 'select',
name: 'select',
menuTpl:
'<div>${label} 值:${value}, 当前是否选中: ${checked}</div>',
options: [
{
label: 'A',
value: 'a'
},
{
label: 'B',
value: 'b'
},
{
label: 'C',
value: 'c'
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:select group', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'form',
api: '/api/mock2/form/saveForm',
body: [
{
label: '分组',
type: 'select',
name: 'a',
selectMode: 'group',
options: [
{
label: '法师',
children: [
{
label: '诸葛亮',
value: 'zhugeliang'
}
]
},
{
label: '战士',
children: [
{
label: '曹操',
value: 'caocao'
},
{
label: '钟无艳',
value: 'zhongwuyan'
}
]
},
{
label: '打野',
children: [
{
label: '李白',
value: 'libai'
},
{
label: '韩信',
value: 'hanxin'
},
{
label: '云中君',
value: 'yunzhongjun'
}
]
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:select table', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'form',
api: '/api/mock2/form/saveForm',
body: [
{
label: '表格形式',
type: 'select',
name: 'a',
selectMode: 'table',
columns: [
{
name: 'label',
label: '英雄'
},
{
name: 'position',
label: '位置'
}
],
options: [
{
label: '诸葛亮',
value: 'zhugeliang',
position: '中单'
},
{
label: '曹操',
value: 'caocao',
position: '上单'
},
{
label: '钟无艳',
value: 'zhongwuyan',
position: '上单'
},
{
label: '李白',
value: 'libai',
position: '打野'
},
{
label: '韩信',
value: 'hanxin',
position: '打野'
},
{
label: '云中君',
value: 'yunzhongjun',
position: '打野'
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:select table with labelField & valueField', async () => {
const onSubmit = jest.fn();
const {debug, container, findByText, getByText} = render(
amisRender(
{
type: 'form',
submitText: 'Submit',
body: [
{
label: '表格形式',
type: 'select',
name: 'a',
selectMode: 'table',
multiple: true,
labelField: 'text',
valueField: 'val',
columns: [
{
name: 'text',
label: '英雄'
},
{
name: 'position',
label: '位置'
}
],
options: [
{
text: '诸葛亮',
val: 'zhugeliang',
position: '中单'
},
{
text: '曹操',
val: 'caocao',
position: '上单'
},
{
text: '钟无艳',
val: 'zhongwuyan',
position: '上单'
},
{
text: '李白',
val: 'libai',
position: '打野'
},
{
text: '韩信',
val: 'hanxin',
position: '打野'
},
{
text: '云中君',
val: 'yunzhongjun',
position: '打野'
}
]
}
]
},
{
onSubmit
},
makeEnv({})
)
);
fireEvent.click(await findByText('请选择'));
await waitFor(() => {
expect(
container.querySelector('.cxd-TransferDropDown-popover')
).toBeInTheDocument();
});
fireEvent.click(await findByText('诸葛亮'));
await wait(500);
fireEvent.click(await findByText('李白'));
await wait(500);
expect(container).toMatchSnapshot();
fireEvent.click(await findByText('Submit'));
await wait(200);
expect(onSubmit).toBeCalled();
expect(onSubmit.mock.calls[0][0]).toMatchSnapshot();
});
test('Renderer:select tree', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'form',
api: '/api/mock2/form/saveForm',
body: [
{
label: '树型展示',
type: 'select',
name: 'a',
selectMode: 'tree',
options: [
{
label: '法师',
children: [
{
label: '诸葛亮',
value: 'zhugeliang'
}
]
},
{
label: '战士',
children: [
{
label: '曹操',
value: 'caocao'
},
{
label: '钟无艳',
value: 'zhongwuyan'
}
]
},
{
label: '打野',
children: [
{
label: '李白',
value: 'libai'
},
{
label: '韩信',
value: 'hanxin'
},
{
label: '云中君',
value: 'yunzhongjun'
}
]
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:select chained', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'form',
api: '/api/mock2/form/saveForm',
body: [
{
label: '级联选择',
type: 'select',
name: 'a',
selectMode: 'chained',
options: [
{
label: '法师',
children: [
{
label: '诸葛亮',
value: 'zhugeliang'
}
]
},
{
label: '战士',
children: [
{
label: '曹操',
value: 'caocao'
},
{
label: '钟无艳',
value: 'zhongwuyan'
}
]
},
{
label: '打野',
children: [
{
label: '李白',
value: 'libai'
},
{
label: '韩信',
value: 'hanxin'
},
{
label: '云中君',
value: 'yunzhongjun'
}
]
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer: chained select', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'form',
api: '/api/mock2/form/saveForm',
body: [
{
label: '带搜索',
type: 'select',
name: 'a',
selectMode: 'chained',
searchable: true,
sortable: true,
multiple: true,
options: [
{
label: '法师',
children: [
{
label: '诸葛亮',
value: 'zhugeliang'
}
]
},
{
label: '战士',
children: [
{
label: '曹操',
value: 'caocao'
},
{
label: '钟无艳',
value: 'zhongwuyan'
}
]
},
{
label: '打野',
children: [
{
label: '李白',
value: 'libai'
},
{
label: '韩信',
value: 'hanxin'
},
{
label: '云中君',
value: 'yunzhongjun'
}
]
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:select associated', () => {
const {container} = render(
amisRender(
{
type: 'page',
body: {
type: 'form',
api: '/api/mock2/form/saveForm',
body: [
{
label: '关联选择模式',
type: 'select',
name: 'b',
sortable: true,
searchable: true,
deferApi: '/api/mock2/form/deferOptions?label=${label}',
selectMode: 'associated',
leftMode: 'tree',
leftOptions: [
{
label: '法师',
children: [
{
label: '诸葛亮',
value: 'zhugeliang'
}
]
},
{
label: '战士',
children: [
{
label: '曹操',
value: 'caocao'
},
{
label: '钟无艳',
value: 'zhongwuyan'
}
]
},
{
label: '打野',
children: [
{
label: '李白',
value: 'libai'
},
{
label: '韩信',
value: 'hanxin'
},
{
label: '云中君',
value: 'yunzhongjun'
}
]
}
],
options: [
{
ref: 'zhugeliang',
children: [
{
label: 'A',
value: 'a'
}
]
},
{
ref: 'caocao',
children: [
{
label: 'B',
value: 'b'
},
{
label: 'C',
value: 'c'
}
]
},
{
ref: 'zhongwuyan',
children: [
{
label: 'D',
value: 'd'
},
{
label: 'E',
value: 'e'
}
]
},
{
ref: 'libai',
defer: true
},
{
ref: 'hanxin',
defer: true
},
{
ref: 'yunzhongjun',
defer: true
}
]
}
]
}
},
{},
makeEnv({})
)
);
expect(container).toMatchSnapshot();
});
test('Renderer:select virtual', async () => {
const options = [...Array(200)].map((_, i) => {
return 'option' + i;
});
const {container, queryByText, findByText} = render(
amisRender(
{
type: 'form',
body: [
{
label: '选项',
type: 'select',
name: 'select',
options: options
}
]
},
{},
makeEnv({})
)
);
const inputDate = await findByText('请选择');
fireEvent.click(inputDate);
const option12 = queryByText('option12');
expect(option12).toBeNull();
expect(container).toMatchSnapshot();
});
|
UsmanTariq02/quiz_player
|
src/modules/quiz/dto/CreateQuiz.dto.ts
|
<reponame>UsmanTariq02/quiz_player
import { IsNotEmpty, Length } from 'class-validator';
export class CreateQuizDto {
// Validations On Inputs of Data from User side
@IsNotEmpty({
message: "Title Required"
})
@Length(3)
title: string;
@IsNotEmpty({
message: "Description is required"
})
@Length(5, 50)
description: string;
}
|
UsmanTariq02/quiz_player
|
src/modules/quiz/quiz.entity.ts
|
<gh_stars>0
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
// Here Quizes is Table Name
@Entity('quizes')
export class Quiz extends BaseEntity {
// Primary Generated Column is for Auto Incremented Key ID
@PrimaryGeneratedColumn({
comment: 'The Quiz Unique Identifier',
})
id: number;
// @Column is used to create a new column in the table ....
@Column({
comment: 'Column For Title',
type: 'varchar'
})
title: string;
// Here are 2 columns title & description
@Column({
type: 'text' // Column Type is given here
})
description: string; // description is the column name
@Column({
type: 'boolean',
default: 1
})
isActive: boolean
}
|
UsmanTariq02/quiz_player
|
src/modules/quiz/quiz.service.ts
|
<reponame>UsmanTariq02/quiz_player
import { Injectable, Get } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateQuizDto } from './dto/CreateQuiz.dto';
import { QuizRepository } from './quiz.repository';
export class QuizService {
constructor(
@InjectRepository(QuizRepository) private quizRepository: QuizRepository
) {}
getAllQuiz(){
return [1 , 2 , 3 , 4 ,5];
}
async createNewQuiz(quiz: CreateQuizDto){
return await this.quizRepository.save(quiz);
}
}
|
UsmanTariq02/quiz_player
|
src/modules/quiz/quiz.repository.ts
|
import { EntityRepository, Repository } from "typeorm";
import {Quiz} from "./quiz.entity";
//EntityRepository is a Decorator and Quiz here is an Entity which we already crated to create a table in database
@EntityRepository(Quiz)
//Export Class QuizRepository extends with Repository class and inside the signs we are passing Module Class Name which is now Quiz
// In type ORM Module database will handle through Repository that's why we are extending class with repository class
export class QuizRepository extends Repository<Quiz> {
}
|
UsmanTariq02/quiz_player
|
src/modules/quiz/quiz.controller.ts
|
import { Controller , Get, Post, Body, HttpCode, UsePipes, ValidationPipe } from '@nestjs/common';
import { CreateQuizDto } from './dto/CreateQuiz.dto';
import { QuizService } from './quiz.service';
@Controller('quiz')
export class QuizController {
constructor(private quizService: QuizService) {}
@Get('/')
getAllQuiz() {
return this.quizService.getAllQuiz();
}
@Post('/create')
@HttpCode(200)
@UsePipes(ValidationPipe)
async createQuiz(@Body() quizData: CreateQuizDto){
//return {data: quizData};
return await this.quizService.createNewQuiz(quizData);
}
}
|
clarencetw/cdk-nyancat
|
test/default.test.ts
|
import * as ec2 from '@aws-cdk/aws-ec2';
import * as cdk from '@aws-cdk/core';
import { NyanCat } from '../src/index';
let app: cdk.App;
let env: { region: string; account: string };
let stack: cdk.Stack;
beforeEach(() => {
app = new cdk.App();
env = {
region: 'us-east-1',
account: '888888888888',
};
stack = new cdk.Stack(app, 'demo-stack', { env });
});
test('Snapshot - NyanCat', () => {
const vpc = ec2.Vpc.fromLookup(stack, 'VPC', {
isDefault: true,
});
new NyanCat(stack, 'NyanCat', {
vpc,
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.T3,
ec2.InstanceSize.SMALL,
),
});
expect(app.synth().getStackArtifact(stack.artifactId).template).toMatchSnapshot();
});
|
clarencetw/cdk-nyancat
|
src/integ.default.ts
|
<reponame>clarencetw/cdk-nyancat
import * as ec2 from '@aws-cdk/aws-ec2';
import * as cdk from '@aws-cdk/core';
import { NyanCat } from './index';
const app = new cdk.App();
const env = {
region: process.env.CDK_DEFAULT_REGION,
account: process.env.CDK_DEFAULT_ACCOUNT,
};
const stack = new cdk.Stack(app, 'stack', { env });
const vpc = ec2.Vpc.fromLookup(stack, 'VPC', {
isDefault: true,
});
new NyanCat(stack, 'NyanCat', {
vpc,
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.T3,
ec2.InstanceSize.SMALL,
),
});
|
clarencetw/cdk-nyancat
|
src/index.ts
|
import * as path from 'path';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as assets from '@aws-cdk/aws-s3-assets';
import * as cdk from '@aws-cdk/core';
/**
* The interface for NyanCat
*/
export interface NyanCatProps {
/**
* The VPC
*/
readonly vpc?: ec2.IVpc;
/**
* The Instance Type
*
* @default - t3.nano
*
*/
readonly instanceType?: ec2.InstanceType;
}
export class NyanCat extends cdk.Construct {
constructor(scope: cdk.Construct, id: string, props: NyanCatProps = {}) {
super(scope, id);
const vpc = props.vpc ?? new ec2.Vpc(this, 'Vpc', { maxAzs: 3, natGateways: 0 });
const asset = new assets.Asset(this, 'Asset', { path: path.join(__dirname, '../ec2-configure/configure.sh') });
const instance = new ec2.Instance(this, 'Instance', {
vpc,
instanceType: props.instanceType ?? ec2.InstanceType.of(
ec2.InstanceClass.T3,
ec2.InstanceSize.NANO,
),
machineImage: new ec2.AmazonLinuxImage({ generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2 }),
vpcSubnets: {
subnetType: ec2.SubnetType.PUBLIC,
},
});
instance.connections.allowFromAnyIpv4(ec2.Port.tcp(80));
const localPath = instance.userData.addS3DownloadCommand({
bucket: asset.bucket,
bucketKey: asset.s3ObjectKey,
});
instance.userData.addExecuteFileCommand({
filePath: localPath,
arguments: '--verbose -y',
});
asset.grantRead(instance.role);
new cdk.CfnOutput(this, 'InstanceIP', {
value: `http://${instance.instancePublicDnsName}`,
});
}
}
|
AndreLSnyk/snyk-user-sync-tool
|
test/inputUtils.test.ts
|
import { validateUserMembership } from '../src/lib/inputUtils'
import { Membership } from '../src/lib/types'
import * as customErrors from '../src/lib/customErrors'
const membershipWithInvalidRole: Membership = {
"userEmail": "<EMAIL>",
"role": "administrator",
"org": "Starfighter Corps Gold Squadron",
"group": "Rebel Alliance"
}
const membershipWithCustomRole: Membership = {
"userEmail": "<EMAIL>",
"role": "restrictedCollaborator",
"org": "Starfighter Corps Gold Squadron",
"group": "Rebel Alliance"
}
const membershipWithInvalidEmail: Membership = {
"userEmail": "<EMAIL>",
"role": "admin",
"org": "Starfighter Corps Gold Squadron",
"group": "Rebel Alliance"
}
describe('input validation', () => {
it('catch invalid role in membership file', async () => {
await expect(validateUserMembership(membershipWithInvalidRole)).rejects.toThrow(customErrors.InvalidRole)
})
it('catch invalid email address in membership file', async () => {
await expect(validateUserMembership(membershipWithInvalidEmail)).rejects.toThrow(customErrors.InvalidEmail)
})
it('validate custom role (from conf/roles.json)', async () => {
expect(await validateUserMembership(membershipWithCustomRole)).resolves
})
})
|
AndreLSnyk/snyk-user-sync-tool
|
src/lib/snykGroupsMetadata.ts
|
import { requestsManager } from 'snyk-request-manager';
import * as debugLib from 'debug';
import { GroupMetadata, GroupOrg } from './types';
import * as common from './common';
const debug = debugLib('snyk:snykGroupsMetadata');
export class snykGroupsMetadata {
snykKeys: string;
private _groupsMetadata: GroupMetadata[] = [];
private _buffer: number = 250;
constructor(snykKeys: string) {
this.snykKeys = snykKeys;
}
async init() {
let result: GroupMetadata = {
groupName: '',
groupId: '',
groupKey: '',
groupStatus: '',
};
for (const key of this.snykKeys.split(',')) {
let keySplit = key.split(':');
let groupName = keySplit[0];
let groupKey = keySplit[1];
let _requestManager = new requestsManager({
snykToken: groupKey,
userAgentPrefix: 'onprem-user-sync-tool',
});
try {
//sleep(this._buffer)
let response = await _requestManager.request({
verb: 'GET',
url: `/orgs`,
});
//debug(JSON.stringify(response.data, null,2));
let filteredOrgs = response.data.orgs.filter(function(org: GroupOrg) {
if (org.group != null) {
return (
org.group.name === groupName ||
`'${org.group.name}'` === groupName
);
}
});
let org = filteredOrgs[0];
debug('filtered org -> ' + JSON.stringify(org, null, 2));
result = {
groupName: org.group.name,
groupId: org.group.id,
groupKey: groupKey,
groupStatus: 'enabled',
};
} catch (err) {
if (err.name == 'RequestsManagerApiAuthenticationError') {
debug('we are handling api auth 401');
result = {
groupName: groupName,
groupId: '',
groupKey: groupKey,
groupStatus: 'disabled',
groupStatusReason: 'API Authentication Error (401)',
};
} else if (
err.name == 'Unknown' &&
err.message == 'Error: Request failed with status code 403'
) {
debug('we are handling 403');
result = {
groupName: groupName,
groupId: '',
groupKey: groupKey,
groupStatus: 'disabled',
groupStatusReason: 'API Authentication Error (403)',
};
} else {
debug('we are handling generic error');
result = {
groupName: groupName,
groupId: '',
groupKey: groupKey,
groupStatus: 'disabled',
groupStatusReason: `${err.message}`,
};
}
}
this._groupsMetadata.push(result);
}
}
async getAllGroupsMetadata() {
return this._groupsMetadata;
}
async getGroupStatusByName(groupName: string): Promise<string[]> {
debug(`groupName: ${groupName}`);
debug(this._groupsMetadata);
for (const gmd of this._groupsMetadata) {
debug(`gmd.groupName: ${gmd.groupName}`);
if (
gmd.groupName.toUpperCase() == groupName.toUpperCase() ||
gmd.groupName.toUpperCase() == "'" + groupName.toUpperCase() + "'"
) {
return [gmd.groupStatus, gmd.groupStatusReason || ''];
}
}
return ['groupNotFound', 'Group name not Found'];
}
async getGroupIdByName(groupName: string): Promise<string> {
debug(`groupName: ${groupName}`);
debug(this._groupsMetadata);
for (const gmd of this._groupsMetadata) {
debug(`gmd.groupName: ${gmd.groupName}`);
if (
gmd.groupName.toUpperCase() == groupName.toUpperCase() ||
gmd.groupName.toUpperCase() == "'" + groupName.toUpperCase() + "'"
) {
return gmd.groupId;
}
}
return '';
}
async getGroupKeyByName(groupName: string) {
debug(`groupName: ${groupName}`);
debug(`snykKeys: ${this.snykKeys}`);
for (const key of this.snykKeys.split(',')) {
let keySplit = key.split(':');
debug(`key: ${key}`);
debug(`keySplit: ${keySplit}`);
let keyGroupName = keySplit[0];
let keyGroupKey = keySplit[1];
if (
keyGroupName.toUpperCase() == groupName.toUpperCase() ||
keyGroupName.toUpperCase() == "'" + groupName.toUpperCase() + "'"
) {
return keyGroupKey;
}
}
}
}
|
AndreLSnyk/snyk-user-sync-tool
|
src/lib/common.ts
|
<gh_stars>1-10
// to catch base directory variations on both windows and *nix
export const BASE_DIR = __dirname.replace(
/(\/|\\)(dist$|dist(\/|\\).*|src\/lib$)/,
'/',
);
//export const DB_DIR = BASE_DIR.concat('db');
export const DB_DIR = 'db';
//export const PREV_DIR = BASE_DIR.concat('prev/');
export const PREV_DIR = 'prev/';
export const LOG_DIR = 'log/';
export const PENDING_INVITES_FILE = DB_DIR.concat('/pending_invites.json');
export const VALID_ROLES_FILE = BASE_DIR.concat('conf/roles.json');
export const LOG_LIMIT = 25;
export var DRY_RUN_FLAG: boolean = false;
export var ADD_NEW_FLAG: boolean = false;
export var INVITE_TO_ALL_ORGS_FLAG: boolean = false;
export var DELETE_MISSING_FLAG: boolean = false;
export var V2_FORMAT_FLAG: boolean;
export var API_KEYS: string;
export var MEMBERSHIP_FILE: string;
export var API_BASE_URI: string;
export function setEnvironment(
dryRunFlag: boolean,
addNewFlag: boolean,
inviteToAllOrgsFlag: boolean,
deleteMissingFlag: boolean,
v2FormatFlag: boolean,
apiKeys: string,
membershipFile: string,
apiBaseUri: string,
) {
DRY_RUN_FLAG = dryRunFlag;
ADD_NEW_FLAG = addNewFlag;
INVITE_TO_ALL_ORGS_FLAG = inviteToAllOrgsFlag;
DELETE_MISSING_FLAG = deleteMissingFlag;
V2_FORMAT_FLAG = v2FormatFlag;
API_KEYS = apiKeys;
MEMBERSHIP_FILE = membershipFile;
API_BASE_URI = apiBaseUri;
}
var m = new Date();
export var LOG_ID =
m.getUTCFullYear() +
'_' +
('0' + (m.getUTCMonth() + 1)).slice(-2) +
'_' +
('0' + m.getUTCDate()).slice(-2) +
'_' +
('0' + m.getUTCHours()).slice(-2) +
'_' +
('0' + m.getUTCMinutes()).slice(-2) +
'_' +
('0' + m.getUTCSeconds()).slice(-2);
export const LOG_FILE = LOG_DIR.concat(`user-sync-run-${LOG_ID}.log`);
|
AndreLSnyk/snyk-user-sync-tool
|
src/lib/types.ts
|
export interface PendingInvite {
groupName: string;
groupId: string;
orgName: string;
orgId: string;
userEmail: string;
date: Date;
}
export interface Membership {
userEmail: string;
role: string;
org: string;
group: string;
}
export interface GroupMember {
id: string;
username: string;
name: string;
email: string;
orgs: Org[];
groupRole: string;
}
export interface Org {
name: string;
role: string;
}
export interface GroupMetadata {
groupName: string;
groupId: string;
groupKey: string;
groupStatus: string;
groupStatusReason?: string;
}
export interface PendingMembership {
userEmail: string;
role: string;
org: string;
group: string;
userExistsInOrg: string;
}
export interface GroupOrg {
name: string;
id: string;
slug: string;
url: string;
group: OrgGroup;
}
export interface OrgGroup {
name: string;
id: string;
}
export interface v1Group {
members: Membership[];
}
export interface v2Group {
groupName: string;
admins?: v2User[];
orgs?: v2Org[];
}
export interface v2User {
fullName: string;
email: string;
}
export interface v2Org {
orgName: string;
collaborators?: v2User[];
admins?: v2User[];
}
|
AndreLSnyk/snyk-user-sync-tool
|
src/lib/index.ts
|
#!/usr/bin/env node
import * as yargs from 'yargs';
import * as debugLib from 'debug';
import { processMemberships } from './app';
import * as utils from './utils';
import { printKeys, initializeDb, backupUserMemberships } from './inputUtils';
import {
PREV_DIR,
PENDING_INVITES_FILE,
DRY_RUN_FLAG,
INVITE_TO_ALL_ORGS_FLAG,
V2_FORMAT_FLAG,
setEnvironment,
ADD_NEW_FLAG,
DELETE_MISSING_FLAG,
} from './common';
import { exit } from 'process';
const debug = debugLib('snyk:index');
const argv = yargs
.usage(
`\nUsage: $0 [OPTIONS]
If no arguments are specified, values will be picked up from environment variables.\n
If pointing to a self-hosted or on-premise instance of Snyk,
SNYK_API is required to be set in your environment,
e.g. SNYK_API=https://my.snyk.domain/api. If omitted, then Snyk SaaS is used.`,
)
.options({
'add-new': {
describe: `add memberships if they are found in the
membership-file and are not in Snyk`,
demandOption: false,
},
'delete-missing': {
describe: `delete memberships from Snyk if they are found
to be missing from the membership-file (use with caution)`,
demandOption: false,
},
v2: {
describe: `use v2 file format`,
demandOption: false,
},
'membership-file': {
describe: `path to membership file
if not specified, taken from SNYK_IAM_MEMBERSHIP_FILE`,
demandOption: false,
},
'api-keys': {
describe: `list of api keys per group
if not specified, taken from SNYK_IAM_API_KEYS`,
demandOption: false,
},
'dry-run': {
describe: `print/log the execution plan without making any updates to Snyk`,
demandOption: false,
},
'invite-to-all-orgs': {
describe: `send new users an invite to every org, rather than only the first`,
demandOption: false,
},
debug: {
describe: `enable debug mode`,
demandOption: false,
type: 'boolean',
},
})
.help().argv;
function checkEnvironment() {
//console.log(`DEBUG mode is ${debug}`)
const snykKeys: string = String(
argv['api-keys'] ? argv['api-keys'] : process.env.SNYK_IAM_API_KEYS,
);
const snykMembershipFile: string = String(
argv['membership-file']
? argv['membership-file']
: process.env.SNYK_IAM_MEMBERSHIP_FILE,
);
const snykApiBaseUri: string = String(process.env.SNYK_API);
const addNewFlag: boolean = Boolean(
argv['add-new'] ? argv['add-new'] : false,
);
const deleteMissingFlag: boolean = Boolean(
argv['delete-missing'] ? argv['delete-missing'] : false,
);
const dryRunFlag = Boolean(argv['dry-run'] ? argv['dry-run'] : false);
const inviteToAllOrgsFlag: boolean = Boolean(
argv['invite-to-all-orgs'] ? argv['invite-to-all-orgs'] : false,
);
const v2FormatFlag: boolean = Boolean(argv['v2'] ? argv['v2'] : false);
utils.log(`dry run: ${dryRunFlag}`);
if (snykApiBaseUri == 'undefined') {
utils.log('snykApiBaseUri: not specified, default to SaaS');
} else {
utils.log(`snykApiBaseUri: ${snykApiBaseUri}`);
}
utils.log(`v2 format enabled?: ${v2FormatFlag}`);
utils.log(`Delete Missing enabled?: ${deleteMissingFlag}`);
utils.log(`Invite to all orgs enabled?: ${inviteToAllOrgsFlag}`);
debug('SNYK_IAM_API_KEYS: ');
for (const key of snykKeys.split(',')) {
debug(` ${key}`);
}
debug('SNYK_IAM_MEMBERSHIP_FILE: ' + snykMembershipFile);
debug('SNYK_API: ' + snykApiBaseUri);
debug('--delete-missing flag: ' + deleteMissingFlag);
if (snykKeys == 'undefined' || snykMembershipFile == 'undefined') {
utils.log('environment not set\n');
utils.log('snykKeys:');
printKeys(snykKeys);
utils.log(`snykMembershipFile: ${snykMembershipFile}`);
utils.log(`addNewFlag: ${addNewFlag}`);
utils.log(`deleteMissingFlag: ${deleteMissingFlag}`);
yargs.showHelp();
process.exit(1);
}
utils.log(`\nPending invites file: ${PENDING_INVITES_FILE}`);
setEnvironment(
dryRunFlag,
addNewFlag,
inviteToAllOrgsFlag,
deleteMissingFlag,
v2FormatFlag,
snykKeys,
snykMembershipFile,
snykApiBaseUri,
);
}
async function main() {
await initializeDb();
checkEnvironment();
await processMemberships();
await backupUserMemberships();
}
main();
|
AndreLSnyk/snyk-user-sync-tool
|
src/lib/customErrors.ts
|
export class InvalidRole extends Error {
constructor(message: string) {
super(message);
this.name = 'InvalidRole';
}
}
export class InvalidEmail extends Error {
constructor(message: string) {
super(message);
this.name = 'InvalidEmailAddress';
}
}
export class OrgIdNotFound extends Error {
constructor(message: string) {
super(message);
this.name = 'OrgIdNotFound';
}
}
|
AndreLSnyk/snyk-user-sync-tool
|
src/lib/utils.ts
|
import { requestsManager } from 'snyk-request-manager';
import * as debugLib from 'debug';
import * as fs from 'fs';
import * as path from 'path';
import { snykGroup } from './snykGroup';
import {
GroupMember,
PendingInvite,
Membership,
PendingMembership,
GroupOrg,
v2Group,
} from './types';
import * as inputUtils from './inputUtils';
import * as common from './common';
import * as utils from './utils';
import * as customErrors from './customErrors';
import { umask } from 'process';
const readline = require('readline');
const debug = debugLib('snyk:utils');
const { execSync } = require('child_process');
export async function recordPendingInvite(
groupName: string,
groupId: string,
orgName: string,
org: string,
email: string,
) {
let result = [];
//const pendingInvitesFile: string = 'db/pending_invites.json';
const pendingInvitesFile: string = common.PENDING_INVITES_FILE;
let pendingInvites = await inputUtils.readFileToJson(pendingInvitesFile);
debug(`pendingInvites length: ${pendingInvites.length}`);
if (pendingInvites.length > 0) {
result = pendingInvites;
}
result.push({
groupName: groupName,
groupId: groupId,
orgName: orgName,
orgId: org,
userEmail: email,
date: String(new Date()),
});
debug('writing invites to file: ');
debug(result);
fs.writeFileSync(pendingInvitesFile, JSON.stringify(result, null, 4));
}
export async function isPendingInvite(userEmail: string, groupId: string) {
let pendingInvites: PendingInvite[] = await inputUtils.readFileToJson(
common.PENDING_INVITES_FILE,
);
debug(pendingInvites);
debug(
`checking if pending invitation exists for ${userEmail} in group ${groupId}`,
);
for (const pi of pendingInvites) {
if (pi.userEmail == userEmail && pi.groupId == groupId) {
debug(`Invite is pending for ${userEmail} in group ${groupId}`);
return true;
}
}
debug(`NO invite is pending for ${userEmail} in group ${groupId}`);
return false;
}
export function log(message: string) {
console.log(message);
var m = new Date();
const LOG_TIMESTAMP =
m.getUTCFullYear() +
'/' +
('0' + (m.getUTCMonth() + 1)).slice(-2) +
'/' +
('0' + m.getUTCDate()).slice(-2) +
' ' +
('0' + m.getUTCHours()).slice(-2) +
':' +
('0' + m.getUTCMinutes()).slice(-2) +
':' +
('0' + m.getUTCSeconds()).slice(-2) +
':' +
('0' + m.getUTCMilliseconds()).slice(-2) +
' ';
fs.appendFileSync(
common.LOG_FILE,
LOG_TIMESTAMP.concat(message.replace(/^\s+|\s+$/g, '')).concat('\n'),
);
}
export function printProgress(progress: string) {
readline.cursorTo(process.stdout, 0)
process.stdout.write(`${progress}`);
}
|
AndreLSnyk/snyk-user-sync-tool
|
src/lib/inputUtils.ts
|
<reponame>AndreLSnyk/snyk-user-sync-tool
import * as fs from 'fs';
import * as debugLib from 'debug';
import * as path from 'path';
import { snykGroup } from './snykGroup';
import * as common from './common';
import * as utils from './utils';
import { GroupMember, Membership, PendingInvite } from './types';
import * as customErrors from './customErrors';
const debug = debugLib('snyk:inputUtils');
/*export async function sortUserMemberships(userMemberships: Membership[]) {
userMemberships.sort((a: any, b: any) =>
a.group > b.group ? 1 : a.group === b.group ? (a.org > b.org ? 1 : -1) : -1,
);
return userMemberships;
}*/
export async function backupUserMemberships() {
//store existing input file in prev directory
let filename: string = path.basename(common.MEMBERSHIP_FILE);
let destination: string = common.PREV_DIR.concat(
`${filename}-${common.LOG_ID}`,
);
fs.copyFile(common.MEMBERSHIP_FILE, destination, (err) => {
if (err) throw err;
debug(`membership file backed up to ${destination}`);
return true;
});
}
export async function getUniqueOrgs(userMemberships: Membership[]) {
const result = [];
const map = new Map();
for (const um of userMemberships) {
//console.log(item.Group)
let groupOrg = um.group + '-' + um.org;
if (!map.has(groupOrg)) {
map.set(groupOrg, true); // set any value to Map
result.push({
groupOrg: groupOrg,
group: um.group,
org: um.org,
});
}
}
debug('Unique Group-Orgs in input file');
debug(result);
return result;
}
async function getPendingInvites(): Promise<PendingInvite[]> {
let pendingInvites: PendingInvite[] = [];
utils.log(`Checking status of pending invites... `);
if (fs.statSync(common.PENDING_INVITES_FILE)['size'] == 0) {
debug('None Found (0 byte file)');
return [];
}
try {
pendingInvites = await readFileToJson(common.PENDING_INVITES_FILE);
debug(pendingInvites);
} catch (err) {
if (err instanceof SyntaxError) {
utils.log('Invalid JSON, skipping...');
} else {
utils.log(err.name);
}
}
return pendingInvites;
}
export async function removeAcceptedPendingInvites(
groupId: string,
groupMembers: GroupMember[],
) {
let result: PendingInvite[] = [];
// get pendingInvites for this group
let pendingInvites: PendingInvite[] = await getPendingInvites();
debug(`pending invites: ${JSON.stringify(pendingInvites, null, 2)}`);
if (pendingInvites.length > 0) {
for (const pi of pendingInvites) {
let found: boolean = false;
for (const gm of groupMembers) {
if (gm.groupRole != 'admin' && gm.groupRole != 'viewer') {
if (
groupId == pi.groupId &&
gm.email.toUpperCase() == pi.userEmail.toUpperCase()
) {
found = true;
utils.log(
`found accepted invite for ${pi.userEmail} in ${pi.groupName}`,
);
break;
}
}
}
if (found == false) {
debug('pushing invite to result:');
debug(pi);
result.push(pi);
}
}
debug(`writing ${result.length} invites to pending invite file`);
if (!common.DRY_RUN_FLAG) {
fs.writeFileSync(
common.PENDING_INVITES_FILE,
JSON.stringify(result, null, 4),
);
}
}
}
export async function getUniqueGroups(userMemberships: Membership[]) {
const result = [];
const map = new Map();
for (const um of userMemberships) {
let group = um.group;
if (!map.has(group)) {
map.set(group, true); // set any value to Map
result.push({
name: um.group,
});
}
}
debug(`unique groups found: ${JSON.stringify(result, null, 2)}`);
return result;
}
export function printKeys(snykKeys: string) {
for (const snykKey of snykKeys.split(',')) {
utils.log(snykKey);
}
}
export async function initializeDb() {
debug(`BASE_DIR: ${common.BASE_DIR}`);
debug('Checking for local DB files...');
if (!fs.existsSync(common.DB_DIR)) {
//create DB_DIR
debug(`db dir does not exist, creating ${common.DB_DIR} ...`);
fs.mkdirSync(common.DB_DIR);
} else {
debug(`db dir (${common.DB_DIR}) already exists`);
}
if (!fs.existsSync(common.PENDING_INVITES_FILE)) {
//create empty PENDING_INVITES_FILE
debug(
`pending invites file does not exist, initializing ${common.PENDING_INVITES_FILE} ...`,
);
fs.writeFileSync(common.PENDING_INVITES_FILE, '[]');
} else {
debug(
`pending invites file (${common.PENDING_INVITES_FILE}) already exists`,
);
}
if (!fs.existsSync(common.PREV_DIR)) {
//create PREV_DIR
debug(`prev dir does not exist, creating ${common.PREV_DIR} ...`);
fs.mkdirSync(common.PREV_DIR);
} else {
debug(`prev dir ${common.PREV_DIR} already exists`);
}
if (!fs.existsSync(common.LOG_DIR)) {
//create PREV_DIR
debug(`log dir does not exist, creating ${common.LOG_DIR} ...`);
fs.mkdirSync(common.LOG_DIR);
} else {
debug(`log dir ${common.LOG_DIR} already exists`);
}
pruneDir(common.LOG_DIR);
pruneDir(common.PREV_DIR);
}
function pruneDir(dir: string) {
let files = fs.readdirSync(dir);
let filesSorted = files.sort(function(a, b) {
return (
fs.statSync(dir + b).mtime.getTime() -
fs.statSync(dir + a).mtime.getTime()
);
});
let counter = 0;
for (const file of filesSorted) {
//console.log(file)
if (counter >= common.LOG_LIMIT) {
fs.unlinkSync(dir.concat('/').concat(file));
utils.log(`pruning ${file}`);
}
counter++;
}
}
export async function readFileToJson(filePath: string) {
try {
const data = await fs.promises.readFile(filePath, 'utf8');
if (data.length > 0) {
try {
return JSON.parse(data);
} catch (err) {
utils.log(`Error parsing file ${filePath}`);
utils.log(` - ${err.message}`);
throw err;
}
} else return [];
} catch (err) {
if (err.code === 'ENOENT') {
utils.log(`file ${filePath} not found, exiting...`);
process.exit(1);
} else {
throw err;
}
}
}
export async function validateUserMembership(snykMembership: {
userEmail: string;
role: string;
org: string;
}) {
var reEmail: RegExp = /\S+@\S+\.\S+/;
// default valid roles
let validRoles: string[] = [
'admin',
'collaborator',
'restrictedCollaborator',
];
//override default valid roles when conf/roles.json is present
if (fs.existsSync(common.VALID_ROLES_FILE)) {
let validRoles: string[] = await readFileToJson(common.VALID_ROLES_FILE);
}
if (
!(
validRoles
.map((x) => {
return x.toUpperCase();
})
.indexOf(snykMembership.role.toUpperCase()) >= 0
)
) {
throw new customErrors.InvalidRole(
`Invalid value for role. Acceptable values are one of [${validRoles}]`,
);
}
if (reEmail.test(snykMembership.userEmail) == false) {
//console.log('email regex = false')
throw new customErrors.InvalidEmail(
'Invalid email address format. Please verify',
);
}
return true;
}
|
blu-world/shengji
|
frontend/src/Confetti.tsx
|
import * as React from "react";
import Timeout from "./Timeout";
import * as confetti from "canvas-confetti";
interface IProps {
confetti: string;
clearConfetti: () => void;
}
const Confetti = (props: IProps): JSX.Element => {
const duration = 30000;
const canvasRef = React.useCallback((canvas) => {
if (canvas !== null) {
const c = confetti.create(canvas, {
resize: true,
});
const animationEnd = Date.now() + duration;
const defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 4 };
const randomInRange = (min: number, max: number): number => {
return Math.random() * (max - min) + min;
};
const interval = setInterval(() => {
const timeLeft = animationEnd - Date.now();
if (timeLeft < 0) {
// Don't clear the interval here; it'll get cleared when the
// component is unmounted.
return;
}
const percentDone = timeLeft / duration;
const particleCount = 200 * percentDone;
// since the particles fall down, start a bit higher than random
const number = Math.random() * 4 * percentDone * percentDone;
for (let i = 1; i < number; i++) {
c({
...defaults,
particleCount: particleCount,
origin: { x: randomInRange(0.2, 0.8), y: Math.random() - 0.2 },
angle: randomInRange(65, 115),
}).then(
() => {},
() => {}
);
}
}, 500);
return () => {
clearInterval(interval);
c.reset();
};
}
}, []);
return (
<div
style={{
position: "fixed",
height: "100%",
width: "100%",
background: "rgba(255, 255, 255, 0.8)",
zIndex: 2,
}}
onClick={() => props.clearConfetti()}
>
<Timeout timeout={duration} callback={() => props.clearConfetti()} />
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
style={{ height: "100%", width: "100%" }}
/>
<h1
style={{
position: "fixed",
textAlign: "center",
zIndex: 3,
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
}}
>
{props.confetti}
</h1>
</div>
);
};
export default Confetti;
|
blu-world/shengji
|
frontend/src/ReadyCheck.tsx
|
<gh_stars>10-100
import * as React from "react";
import { WebsocketContext } from "./WebsocketProvider";
const ReadyCheck = (): JSX.Element => {
const { send } = React.useContext(WebsocketContext);
return (
<button
onClick={() =>
confirm("Are you ready to start the game?") && send("ReadyCheck")
}
>
Check if everyone is ready!
</button>
);
};
export default ReadyCheck;
|
blu-world/shengji
|
frontend/src/Draw.tsx
|
/* tslint:disable:max-classes-per-file variable-name forin */
import * as React from "react";
import { IDrawPhase, IPlayer } from "./types";
import Header from "./Header";
import Players from "./Players";
import LabeledPlay from "./LabeledPlay";
import BeepButton from "./BeepButton";
import BidArea from "./BidArea";
import InlineCard from "./InlineCard";
interface IDrawProps {
state: IDrawPhase;
playDrawCardSound: boolean;
name: string;
setTimeout: (fn: () => void, timeout: number) => number;
clearTimeout: (id: number) => void;
}
interface IDrawState {
autodraw: boolean;
}
class Draw extends React.Component<IDrawProps, IDrawState> {
private could_draw: boolean = false;
private timeout: number | null = null;
private drawCardAudio: HTMLAudioElement | null = null;
constructor(props: IDrawProps) {
super(props);
this.state = {
autodraw: true,
};
this.drawCard = this.drawCard.bind(this);
this.pickUpKitty = this.pickUpKitty.bind(this);
this.revealCard = this.revealCard.bind(this);
this.onAutodrawClicked = this.onAutodrawClicked.bind(this);
}
drawCard(): void {
const canDraw =
this.props.state.propagated.players[this.props.state.position].name ===
this.props.name;
if (this.timeout !== null) {
this.props.clearTimeout(this.timeout);
this.timeout = null;
}
if (canDraw) {
if (this.props.playDrawCardSound) {
if (this.drawCardAudio === null) {
this.drawCardAudio = new Audio(
"434472_dersuperanton_taking-card.mp3"
);
}
// eslint-disable-next-line
this.drawCardAudio.play();
}
(window as any).send({ Action: "DrawCard" });
}
}
pickUpKitty(evt: React.SyntheticEvent): void {
evt.preventDefault();
(window as any).send({ Action: "PickUpKitty" });
}
revealCard(evt: React.SyntheticEvent): void {
evt.preventDefault();
(window as any).send({ Action: "RevealCard" });
}
onAutodrawClicked(evt: React.ChangeEvent<HTMLInputElement>): void {
this.setState({
autodraw: evt.target.checked,
});
if (evt.target.checked) {
this.drawCard();
} else {
if (this.timeout !== null) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
}
render(): JSX.Element {
const canDraw =
this.props.state.propagated.players[this.props.state.position].name ===
this.props.name && this.props.state.deck.length > 0;
if (
canDraw &&
!this.could_draw &&
this.timeout === null &&
this.state.autodraw
) {
this.timeout = this.props.setTimeout(() => {
this.drawCard();
}, 250);
}
this.could_draw = canDraw;
let next =
this.props.state.propagated.players[this.props.state.position].id;
if (
this.props.state.deck.length === 0 &&
this.props.state.bids.length > 0
) {
next = this.props.state.bids[this.props.state.bids.length - 1].id;
}
const players: { [playerId: number]: IPlayer } = {};
let playerId = -1;
this.props.state.propagated.players.forEach((p) => {
players[p.id] = p;
if (p.name === this.props.name) {
playerId = p.id;
}
});
const landlord = this.props.state.propagated.landlord;
return (
<div>
<Header
gameMode={this.props.state.game_mode}
chatLink={this.props.state.propagated.chat_link}
/>
<Players
players={this.props.state.propagated.players}
observers={this.props.state.propagated.observers}
landlord={this.props.state.propagated.landlord}
next={next}
name={this.props.name}
/>
<BidArea
bids={this.props.state.bids}
autobid={this.props.state.autobid}
hands={this.props.state.hands}
epoch={0}
name={this.props.name}
landlord={this.props.state.propagated.landlord}
players={this.props.state.propagated.players}
bidPolicy={this.props.state.propagated.bid_policy}
bidReinforcementPolicy={
this.props.state.propagated.bid_reinforcement_policy
}
jokerBidPolicy={this.props.state.propagated.joker_bid_policy}
numDecks={this.props.state.num_decks}
header={
<>
<h2>
Bids ({this.props.state.deck.length} cards remaining in the
deck)
</h2>
{this.props.state.removed_cards.length > 0 ? (
<p>
Note:{" "}
{this.props.state.removed_cards.map((c) => (
<InlineCard key={c} card={c} />
))}{" "}
have been removed from the deck
</p>
) : null}
</>
}
prefixButtons={
<>
<button
onClick={(evt: React.SyntheticEvent) => {
evt.preventDefault();
this.drawCard();
}}
disabled={!canDraw}
>
Draw card
</button>
<label>
auto-draw
<input
type="checkbox"
name="autodraw"
checked={this.state.autodraw}
onChange={this.onAutodrawClicked}
/>
</label>
</>
}
suffixButtons={
<>
<button
onClick={this.pickUpKitty}
disabled={
this.props.state.deck.length > 0 ||
(this.props.state.bids.length === 0 &&
this.props.state.autobid === null) ||
(landlord !== null && landlord !== playerId) ||
(landlord === null &&
((this.props.state.propagated
.first_landlord_selection_policy === "ByWinningBid" &&
this.props.state.bids[this.props.state.bids.length - 1]
.id !== playerId) ||
(this.props.state.propagated
.first_landlord_selection_policy === "ByFirstBid" &&
this.props.state.bids[0].id !== playerId)))
}
>
Pick up cards from the bottom
</button>
<button
onClick={this.revealCard}
disabled={
this.props.state.propagated.landlord == null ||
this.props.state.deck.length > 0 ||
this.props.state.bids.length > 0 ||
this.props.state.autobid !== null ||
this.props.state.revealed_cards >=
this.props.state.kitty.length
}
>
Reveal card from the bottom
</button>
<BeepButton />
</>
}
bidTakeBacksEnabled={
this.props.state.propagated.bid_takeback_policy ===
"AllowBidTakeback"
}
/>
<LabeledPlay
className="kitty"
cards={this.props.state.kitty}
label="底牌"
/>
</div>
);
}
}
export default Draw;
|
blu-world/shengji
|
frontend/src/WasmContext.tsx
|
<reponame>blu-world/shengji
import * as React from "react";
import {
ITrump,
ITrickUnit,
IBid,
IHands,
IPlayer,
IUnitLike,
ITrickFormat,
BidPolicy,
BidReinforcementPolicy,
IDeck,
ITrick,
TrickDrawPolicy,
IGameScoringParameters,
JokerBidPolicy,
ITractorRequirements,
} from "./types";
interface Context {
findViablePlays: (
trump: ITrump,
tractorRequirements: ITractorRequirements,
cards: string[]
) => IFoundViablePlay[];
findValidBids: (req: IFindValidBidsRequest) => IBid[];
sortAndGroupCards: (
req: ISortAndGroupCardsRequest
) => ISortedAndGroupedCards[];
decomposeTrickFormat: (
req: IDecomposeTrickFormatRequest
) => IDecomposedTrickFormat[];
canPlayCards: (req: ICanPlayCardsRequest) => boolean;
explainScoring: (req: IExplainScoringRequest) => IExplainScoringResponse;
nextThresholdReachable: (req: INextThresholdReachableRequest) => boolean;
computeScore: (req: IComputeScoreRequest) => IComputeScoreResponse;
computeDeckLen: (req: IDeck[]) => number;
decodeWireFormat: (req: any) => any;
}
export interface IFoundViablePlay {
grouping: ITrickUnit[];
description: string;
}
interface IFindValidBidsRequest {
id: number;
bids: IBid[];
hands: IHands;
players: IPlayer[];
landlord: number | null;
epoch: number;
bid_policy: BidPolicy;
bid_reinforcement_policy: BidReinforcementPolicy;
joker_bid_policy: JokerBidPolicy;
num_decks: number;
}
interface ISortAndGroupCardsRequest {
trump: ITrump | null;
cards: string[];
}
export interface ISortedAndGroupedCards {
suit: string;
cards: string[];
}
interface IDecomposedTrickFormat {
description: string;
format: IUnitLike[];
playable: string[];
}
interface IDecomposeTrickFormatRequest {
trick_format: ITrickFormat;
hands: IHands;
player_id: number;
trick_draw_policy: TrickDrawPolicy;
}
interface ICanPlayCardsRequest {
trick: ITrick;
id: number;
hands: IHands;
cards: string[];
trick_draw_policy: TrickDrawPolicy;
}
interface IExplainScoringRequest {
decks: IDeck[];
params: IGameScoringParameters;
smaller_landlord_team_size: boolean;
}
interface INextThresholdReachableRequest {
decks: IDeck[];
params: IGameScoringParameters;
non_landlord_points: number;
observed_points: number;
}
export interface IScoreSegment {
point_threshold: number;
results: IGameScoreResult;
}
interface IGameScoreResult {
landlord_won: boolean;
landlord_bonus: boolean;
landlord_delta: number;
non_landlord_delta: number;
}
interface IComputeScoreRequest {
decks: IDeck[];
params: IGameScoringParameters;
smaller_landlord_team_size: boolean;
non_landlord_points: number;
}
interface IComputeScoreResponse {
score: IGameScoreResult;
next_threshold: number;
}
interface IExplainScoringResponse {
results: IScoreSegment[];
step_size: number;
total_points: number;
}
export const WasmContext = React.createContext<Context>({
findViablePlays: (_, __) => [],
findValidBids: (_) => [],
sortAndGroupCards: (_) => [],
decomposeTrickFormat: (_) => [],
canPlayCards: (_) => false,
explainScoring: (_) => ({ results: [], step_size: 0, total_points: 0 }),
nextThresholdReachable: (_) => true,
computeScore: (_) => ({
score: {
landlord_won: true,
landlord_bonus: false,
landlord_delta: 0,
non_landlord_delta: 0,
},
next_threshold: 0,
}),
computeDeckLen: (_) => 0,
decodeWireFormat: (_) => {},
});
export default WasmContext;
|
blu-world/shengji
|
frontend/src/DebugInfo.tsx
|
<filename>frontend/src/DebugInfo.tsx
import * as React from "react";
import { AppStateContext } from "./AppStateProvider";
export const DebugInfo = (_props: {}): JSX.Element => {
const appState = React.useContext(AppStateContext);
return (
<pre>
{JSON.stringify(
{
gameState: appState.state.gameState,
settings: appState.state.settings,
roomName: appState.state.roomName,
},
null,
2
)}
</pre>
);
};
export default DebugInfo;
|
blu-world/shengji
|
frontend/src/Card.tsx
|
import * as React from "react";
import classNames from "classnames";
import memoize from "./memoize";
import InlineCard from "./InlineCard";
import { cardLookup } from "./util/cardHelpers";
import { SettingsContext } from "./AppStateProvider";
import { ISuitOverrides } from "./state/Settings";
const SvgCard = React.lazy(async () => await import("./SvgCard"));
interface IProps {
card: string;
smaller?: boolean;
className?: string;
onClick?: (event: React.MouseEvent) => void;
onMouseEnter?: (event: React.MouseEvent) => void;
onMouseLeave?: (event: React.MouseEvent) => void;
}
const Card = (props: IProps): JSX.Element => {
const settings = React.useContext(SettingsContext);
if (!(props.card in cardLookup)) {
const nonSVG = (
<span className={classNames("card", "unknown", props.className)}>
<CardCanvas
card={props.card}
height={props.smaller ? 95 : 120}
suit={classNames(
"unknown",
settings.fourColor ? "four-color" : null,
settings.darkMode ? "dark-mode" : null
)}
backgroundColor={settings.darkMode ? "#000" : "#fff"}
/>
</span>
);
if (settings.svgCards) {
return (
<React.Suspense fallback={nonSVG}>
<span
className={classNames("card", "svg", "unknown", props.className)}
>
<SvgCard
fourColor={settings.fourColor}
smaller={props.smaller}
card={"🂠"}
/>
</span>
</React.Suspense>
);
} else {
return nonSVG;
}
} else {
const cardInfo = cardLookup[props.card];
const nonSVG = (
<span
className={classNames("card", cardInfo.typ, props.className)}
onClick={props.onClick}
onMouseEnter={props.onMouseEnter}
onMouseLeave={props.onMouseLeave}
>
<div className="card-label">
<InlineCard card={props.card} />
</div>
<CardCanvas
card={cardInfo.display_value}
height={props.smaller ? 95 : 120}
suit={classNames(
cardInfo.typ,
settings.fourColor ? "four-color" : null,
settings.darkMode ? "dark-mode" : null
)}
colorOverride={
settings.suitColorOverrides[cardInfo.typ as keyof ISuitOverrides]
}
backgroundColor={settings.darkMode ? "#000" : "#fff"}
/>
</span>
);
if (settings.svgCards) {
return (
<React.Suspense fallback={nonSVG}>
<span
className={classNames("card", "svg", cardInfo.typ, props.className)}
onClick={props.onClick}
onMouseEnter={props.onMouseEnter}
onMouseLeave={props.onMouseLeave}
>
<div className="card-label">
<InlineCard card={props.card} />
</div>
<SvgCard
fourColor={settings.fourColor}
smaller={props.smaller}
card={props.card}
/>
</span>
</React.Suspense>
);
} else {
return nonSVG;
}
}
};
const computeCanvasBounds = (font: string, dpr: number): TextMetrics => {
const c = document.createElement("canvas");
c.style.display = "none";
document.body.appendChild(c);
const ctx = c.getContext("2d");
ctx.scale(dpr, dpr);
ctx.font = font;
const text = "🂠";
const textMetrics = ctx.measureText(text);
document.body.removeChild(c);
return textMetrics;
};
const computeSuitColor = (suit: string): string => {
const c = document.createElement("span");
c.className = suit;
c.style.display = "none";
document.body.appendChild(c);
const color = getComputedStyle(c).color;
document.body.removeChild(c);
return color;
};
const cardBoundsCache: { [font: string]: () => TextMetrics } = {};
const suitColorCache: { [suit: string]: () => string } = {};
interface ICardCanvasProps {
card: string;
height: number;
suit: string;
backgroundColor?: string;
colorOverride?: string;
}
const CardCanvas = (props: ICardCanvasProps): JSX.Element => {
const font = `${props.height}px solid`;
if (!(font in cardBoundsCache)) {
cardBoundsCache[font] = memoize(() => computeCanvasBounds(font, 1));
}
if (!(props.suit in suitColorCache)) {
suitColorCache[props.suit] = memoize(() => computeSuitColor(props.suit));
}
const textMetrics = cardBoundsCache[font]();
const style = suitColorCache[props.suit]();
const effectiveHeight = Math.round(
textMetrics.actualBoundingBoxAscent +
textMetrics.actualBoundingBoxDescent +
2
);
const effectiveWidth = Math.round(
textMetrics.actualBoundingBoxRight +
Math.min(textMetrics.actualBoundingBoxLeft, 0) +
2
);
return (
<svg
focusable="false"
role="img"
xmlns="http://www.w3.org/2000/svg"
height={effectiveHeight}
width={effectiveWidth}
>
<rect
fill={
props.backgroundColor !== undefined ? props.backgroundColor : "#fff"
}
x={textMetrics.actualBoundingBoxLeft}
y={0}
width={textMetrics.width - 2}
height={effectiveHeight}
></rect>
<text
fill={props.colorOverride !== undefined ? props.colorOverride : style}
fontSize={`${props.height}px`}
textLength={`${textMetrics.width}px`}
x={Math.min(textMetrics.actualBoundingBoxLeft, 0) + 1}
y={effectiveHeight - textMetrics.actualBoundingBoxDescent - 1}
>
{props.card}
</text>
</svg>
);
};
export default Card;
|
blu-world/shengji
|
frontend/src/WasmProvider.tsx
|
import * as React from "react";
import * as Shengji from "../shengji-wasm/pkg/shengji-core.js";
import WasmContext from "./WasmContext";
import { ITrump, ITractorRequirements } from "./types";
interface IProps {
children: React.ReactNode;
}
const ShengjiProvider = (props: IProps): JSX.Element => {
(window as any).shengji = Shengji;
return (
<WasmContext.Provider
value={{
findViablePlays: (
trump: ITrump,
tractorRequirements: ITractorRequirements,
cards: string[]
) => {
return Shengji.find_viable_plays({
trump,
cards,
tractor_requirements: tractorRequirements,
}).results;
},
findValidBids: (req) => {
return Shengji.find_valid_bids(req).results;
},
sortAndGroupCards: (req) => {
return Shengji.sort_and_group_cards(req).results;
},
decomposeTrickFormat: (req) => {
return Shengji.decompose_trick_format(req).results;
},
canPlayCards: (req) => {
return Shengji.can_play_cards(req).playable;
},
explainScoring: (req) => {
return Shengji.explain_scoring(req);
},
nextThresholdReachable: (req) => {
return Shengji.next_threshold_reachable(req);
},
computeScore: (req) => {
return Shengji.compute_score(req);
},
computeDeckLen: (req) => {
return Shengji.compute_deck_len(req);
},
decodeWireFormat: (req) => {
return JSON.parse(Shengji.zstd_decompress(req));
},
}}
>
{props.children}
</WasmContext.Provider>
);
};
export default ShengjiProvider;
|
blu-world/shengji
|
frontend/src/Exchange.tsx
|
/* tslint:disable:max-classes-per-file variable-name forin */
import * as React from "react";
import BeepButton from "./BeepButton";
import BidArea from "./BidArea";
import Trump from "./Trump";
import FriendSelect from "./FriendSelect";
import InlineCard from "./InlineCard";
import Card from "./Card";
import Header from "./Header";
import Friends from "./Friends";
import Players from "./Players";
import LabeledPlay from "./LabeledPlay";
import { IExchangePhase, IFriend } from "./types";
import Cards from "./Cards";
interface IExchangeProps {
state: IExchangePhase;
name: string;
}
interface IExchangeState {
friends: IFriend[];
}
class Exchange extends React.Component<IExchangeProps, IExchangeState> {
constructor(props: IExchangeProps) {
super(props);
this.moveCardToKitty = this.moveCardToKitty.bind(this);
this.moveCardToHand = this.moveCardToHand.bind(this);
this.startGame = this.startGame.bind(this);
this.pickUpKitty = this.pickUpKitty.bind(this);
this.putDownKitty = this.putDownKitty.bind(this);
this.pickFriends = this.pickFriends.bind(this);
this.state = {
friends: [],
};
this.fixFriends = this.fixFriends.bind(this);
}
fixFriends(): void {
if (this.props.state.game_mode !== "Tractor") {
const gameMode = this.props.state.game_mode.FindingFriends;
const numFriends = gameMode.num_friends;
const propFriends = gameMode.friends;
if (numFriends !== this.state.friends.length) {
if (propFriends.length !== numFriends) {
const friends = [...this.state.friends];
while (friends.length < numFriends) {
friends.push({
card: "",
skip: 0,
initial_skip: 0,
player_id: null,
});
}
while (friends.length > numFriends) {
friends.pop();
}
this.setState({ friends });
} else {
this.setState({ friends: propFriends });
}
}
} else {
if (this.state.friends.length !== 0) {
this.setState({ friends: [] });
}
}
}
componentDidMount(): void {
this.fixFriends();
}
componentDidUpdate(): void {
this.fixFriends();
}
moveCardToKitty(card: string): void {
(window as any).send({ Action: { MoveCardToKitty: card } });
}
moveCardToHand(card: string): void {
(window as any).send({ Action: { MoveCardToHand: card } });
}
startGame(evt: React.SyntheticEvent): void {
evt.preventDefault();
(window as any).send({ Action: "BeginPlay" });
}
pickUpKitty(evt: React.SyntheticEvent): void {
evt.preventDefault();
(window as any).send({ Action: "PickUpKitty" });
}
putDownKitty(evt: React.SyntheticEvent): void {
evt.preventDefault();
(window as any).send({ Action: "PutDownKitty" });
}
pickFriends(evt: React.SyntheticEvent): void {
evt.preventDefault();
if (
this.props.state.game_mode !== "Tractor" &&
this.props.state.game_mode.FindingFriends.num_friends ===
this.state.friends.length
) {
(window as any).send({
Action: {
SetFriends: this.state.friends,
},
});
} else {
this.fixFriends();
}
}
render(): JSX.Element {
const exchanger =
this.props.state.exchanger === null
? this.props.state.landlord
: this.props.state.exchanger;
let landlordIdx = -1;
let exchangerIdx = -1;
let playerId = -1;
this.props.state.propagated.players.forEach((player, idx) => {
if (player.id === this.props.state.landlord) {
landlordIdx = idx;
}
if (player.id === exchanger) {
exchangerIdx = idx;
}
if (player.name === this.props.name) {
playerId = player.id;
}
});
const isLandlord =
this.props.state.propagated.players[landlordIdx].name === this.props.name;
const isExchanger =
this.props.state.propagated.players[exchangerIdx].name ===
this.props.name;
const kittyTheftEnabled =
this.props.state.propagated.kitty_theft_policy === "AllowKittyTheft";
const nextPlayer =
kittyTheftEnabled &&
!this.props.state.finalized &&
this.props.state.exchanger !== null
? this.props.state.exchanger
: this.props.state.landlord;
const exchangeUI =
isExchanger && !this.props.state.finalized ? (
<>
<h2>Your hand</h2>
<Cards
hands={this.props.state.hands}
playerId={playerId}
onCardClick={(c) => this.moveCardToKitty(c)}
trump={this.props.state.trump}
/>
<h2>
Discarded cards {this.props.state.kitty.length} /{" "}
{this.props.state.kitty_size}
</h2>
<div className="kitty">
{this.props.state.kitty.map((c, idx) => (
<Card key={idx} onClick={() => this.moveCardToHand(c)} card={c} />
))}
</div>
{kittyTheftEnabled ? (
<button
onClick={this.putDownKitty}
disabled={
this.props.state.kitty.length !== this.props.state.kitty_size
}
>
Finalize exchanged cards
</button>
) : null}
</>
) : null;
const lastBid = this.props.state.bids[this.props.state.bids.length - 1];
const startGame = (
<button
onClick={this.startGame}
disabled={
this.props.state.kitty.length !== this.props.state.kitty_size ||
(kittyTheftEnabled &&
!this.props.state.finalized &&
this.props.state.autobid === null)
}
>
Start game
</button>
);
const bidUI =
kittyTheftEnabled &&
this.props.state.finalized &&
this.props.state.autobid === null &&
(!isExchanger || lastBid.epoch + 1 !== this.props.state.epoch) ? (
<>
<BidArea
bids={this.props.state.bids}
autobid={this.props.state.autobid}
hands={this.props.state.hands}
epoch={this.props.state.epoch}
name={this.props.name}
landlord={this.props.state.propagated.landlord}
players={this.props.state.propagated.players}
bidPolicy={this.props.state.propagated.bid_policy}
bidReinforcementPolicy={
this.props.state.propagated.bid_reinforcement_policy
}
jokerBidPolicy={this.props.state.propagated.joker_bid_policy}
numDecks={this.props.state.num_decks}
header={
<h2>Bids (round {this.props.state.epoch + 1} of bidding)</h2>
}
suffixButtons={
<>
<button
onClick={this.pickUpKitty}
disabled={
lastBid.id !== playerId ||
lastBid.epoch !== this.props.state.epoch
}
>
Pick up cards from the bottom
</button>
{isLandlord ? startGame : null}
</>
}
bidTakeBacksEnabled={
this.props.state.propagated.bid_takeback_policy ===
"AllowBidTakeback"
}
/>
<LabeledPlay
className="kitty"
cards={this.props.state.kitty}
label="底牌"
/>
</>
) : null;
const friendUI =
this.props.state.game_mode !== "Tractor" && isLandlord ? (
<div>
<Friends gameMode={this.props.state.game_mode} showPlayed={false} />
{this.state.friends.map((friend, idx) => {
const onChange = (x: IFriend): void => {
const newFriends = [...this.state.friends];
newFriends[idx] = x;
this.setState({ friends: newFriends });
this.fixFriends();
};
return (
<FriendSelect
onChange={onChange}
key={idx}
friend={friend}
trump={this.props.state.trump}
friend_selection_policy={
this.props.state.propagated.friend_selection_policy
}
num_decks={this.props.state.num_decks}
/>
);
})}
<button onClick={this.pickFriends}>Pick friends</button>
</div>
) : null;
return (
<div>
<Header
gameMode={this.props.state.game_mode}
chatLink={this.props.state.propagated.chat_link}
/>
<Players
players={this.props.state.propagated.players}
observers={this.props.state.propagated.observers}
landlord={this.props.state.landlord}
next={this.props.state.landlord}
name={this.props.name}
/>
<Trump trump={this.props.state.trump} />
{this.props.state.removed_cards.length > 0 ? (
<p>
Note:{" "}
{this.props.state.removed_cards.map((c) => (
<InlineCard key={c} card={c} />
))}{" "}
have been removed from the deck
</p>
) : null}
{friendUI}
{exchangeUI}
{exchangeUI === null && bidUI === null && playerId >= 0 ? (
<>
<Cards
hands={this.props.state.hands}
playerId={playerId}
trump={this.props.state.trump}
/>
<p>Waiting...</p>
</>
) : null}
{playerId !== nextPlayer && <BeepButton />}
{isLandlord && bidUI === null ? startGame : null}
{bidUI}
</div>
);
}
}
export default Exchange;
|
blu-world/shengji
|
frontend/src/ScoringSettings.tsx
|
<gh_stars>10-100
import * as React from "react";
import { IGameScoringParameters, IDeck } from "./types";
import { WebsocketContext } from "./WebsocketProvider";
import { WasmContext, IScoreSegment } from "./WasmContext";
interface IProps {
params: IGameScoringParameters;
decks: IDeck[];
}
export const GameScoringSettings = (props: IProps): JSX.Element => {
const { send } = React.useContext(WebsocketContext);
const { explainScoring } = React.useContext(WasmContext);
const [highlighted, setHighlighted] = React.useState<number | null>(null);
const updateSettings = (updates: Partial<IGameScoringParameters>): void => {
send({
Action: {
SetGameScoringParameters: { ...props.params, ...updates },
},
});
};
const bonusEnabled =
props.params.bonus_level_policy === "BonusLevelForSmallerLandlordTeam";
const {
results: scoreTransitions,
step_size: stepSize,
total_points: totalPoints,
} = explainScoring({
params: props.params,
smaller_landlord_team_size: false,
decks: props.decks,
});
const bonusScoreTransitions = bonusEnabled
? explainScoring({
params: props.params,
smaller_landlord_team_size: true,
decks: props.decks,
}).results
: scoreTransitions;
const scoreSegments: Array<{
span: number;
segment: IScoreSegment;
bonusSegment: IScoreSegment | null;
}> = [];
let maxPts = 0;
let maxLandlordDelta = 0;
let maxNonLandlordDelta = 0;
for (let i = 1; i < scoreTransitions.length; i++) {
const span = Math.max(
scoreTransitions[i].point_threshold -
scoreTransitions[i - 1].point_threshold,
10
);
const segment = scoreTransitions[i - 1];
maxLandlordDelta = Math.max(
segment.results.landlord_delta,
maxLandlordDelta
);
maxNonLandlordDelta = Math.max(
segment.results.non_landlord_delta,
maxNonLandlordDelta
);
scoreSegments.push({
span,
segment,
bonusSegment: bonusScoreTransitions[i - 1].results.landlord_bonus
? bonusScoreTransitions[i - 1]
: null,
});
maxPts += span;
}
const last = scoreTransitions.length - 1;
scoreSegments.push({
span: 5 * props.decks.length,
segment: scoreTransitions[last],
bonusSegment: bonusScoreTransitions[last].results.landlord_bonus
? bonusScoreTransitions[last]
: null,
});
maxPts += 5 * props.decks.length;
maxNonLandlordDelta = Math.max(
scoreTransitions[last].results.non_landlord_delta,
maxNonLandlordDelta
);
maxLandlordDelta = Math.max(
scoreTransitions[last].results.landlord_delta,
maxLandlordDelta
);
const text = (idx: number): JSX.Element => {
let txt = "Attacking team wins, but doesn't level up.";
const segment = scoreSegments[idx];
if (segment.segment.results.landlord_won) {
txt = `Defending team wins, and goes up ${
segment.segment.results.landlord_delta
} level${segment.segment.results.landlord_delta === 1 ? "" : "s"}.`;
if (segment.bonusSegment !== null) {
txt += ` If the team is unexpectedly small, they go up ${
segment.bonusSegment.results.landlord_delta
} level${
segment.bonusSegment.results.landlord_delta === 1 ? "" : "s"
}.`;
}
} else if (segment.segment.results.non_landlord_delta > 0) {
txt = `Attacking team wins, and goes up ${
segment.segment.results.non_landlord_delta
} level${segment.segment.results.non_landlord_delta === 1 ? "" : "s"}.`;
}
return <>{txt}</>;
};
const validStepSizes = [];
for (
let curStepSize = 0;
curStepSize <= totalPoints / 3;
curStepSize += 5 * props.decks.length
) {
if (curStepSize === 0) {
continue;
}
if (totalPoints % curStepSize === 0) {
validStepSizes.push(`${curStepSize}`);
}
}
const maxSteps = Math.floor(totalPoints / stepSize);
return (
<>
<div>
<div style={{ width: "95%", padding: "5px 0 5px 0" }}>
{scoreSegments.map((segment, idx) => {
const frac = segment.span / maxPts;
let bg = "rgb(255, 255, 0)";
if (segment.segment.results.landlord_won) {
const f =
segment.segment.results.landlord_delta / maxLandlordDelta;
bg = `rgba(0, 255, 0, ${f})`;
} else if (segment.segment.results.non_landlord_delta > 0) {
const f =
segment.segment.results.non_landlord_delta /
maxNonLandlordDelta;
bg = `rgba(255, 0, 0, ${f})`;
}
return (
<div
key={idx}
onMouseEnter={(_) => {
setHighlighted(idx);
}}
onMouseLeave={(_) => {
setHighlighted(null);
}}
style={{
width: `${100 * frac}%`,
background: bg,
padding: "5px 0 5px 0",
display: "inline-block",
cursor: "pointer",
}}
>
{segment.segment.point_threshold}
</div>
);
})}
{highlighted !== null ? (
<p> {text(highlighted)}</p>
) : (
<p>Hover over the scores above for more details.</p>
)}
</div>
<div>
<label>Step size: {stepSize} points</label>
</div>
<div>
<label>Base step size: </label>
<select
value={`${props.params.step_size_per_deck * props.decks.length}`}
onChange={(evt) => {
evt.preventDefault();
const perDeck =
parseInt(evt.target.value, 10) / props.decks.length;
updateSettings({
step_size_per_deck: perDeck,
});
}}
>
{validStepSizes.map((ss, idx) => (
<option key={idx}>{ss}</option>
))}
</select>{" "}
(default: {20 * props.decks.length})
</div>
<div>
<label>
Adjustment to step size for {props.decks.length} decks:{" "}
</label>
<select
value={
props.params.step_adjustments[props.decks.length] !== undefined
? props.params.step_adjustments[props.decks.length]
: "none"
}
onChange={(evt) => {
evt.preventDefault();
if (evt.target.value === "none") {
const { [props.decks.length]: _, ...adjustments } =
props.params.step_adjustments;
updateSettings({ step_adjustments: adjustments });
} else {
const adjustments = {
...props.params.step_adjustments,
[props.decks.length]: parseInt(evt.target.value, 10),
};
updateSettings({ step_adjustments: adjustments });
}
}}
>
<option key="none">none</option>
{Array((props.params.step_size_per_deck * props.decks.length) / 5)
.fill(undefined)
.map((_, idx) => (
<option key={idx}>{(idx + 1) * 5}</option>
))}
</select>{" "}
(default: none)
</div>
<div>
<label>Number of steps where nobody gains a level: </label>
<select
value={`${props.params.deadzone_size}`}
onChange={(evt) => {
evt.preventDefault();
const deadzoneSize = parseInt(evt.target.value, 10);
updateSettings({
deadzone_size: deadzoneSize,
});
}}
>
{Array(Math.max(maxSteps, props.params.deadzone_size))
.fill(undefined)
.map((_, idx) => (
<option key={idx}>{idx}</option>
))}
</select>{" "}
(default: 1)
</div>
<div>
<label>Number of steps for the attacking team to win: </label>
<select
value={`${props.params.num_steps_to_non_landlord_turnover}`}
onChange={(evt) => {
evt.preventDefault();
const steps = parseInt(evt.target.value, 10);
updateSettings({
num_steps_to_non_landlord_turnover: steps,
});
}}
>
{Array(
Math.max(
maxSteps,
props.params.num_steps_to_non_landlord_turnover
)
)
.fill(undefined)
.map((_, idx) => (
<option key={idx + 1}>{idx + 1}</option>
))}
</select>{" "}
(default: 2)
</div>
<div>
<label>Grant a bonus level for unexpectedly small team</label>{" "}
<input
id="small-team-bonus"
type="checkbox"
onChange={(evt) => {
evt.preventDefault();
updateSettings({
bonus_level_policy: evt.target.checked
? "BonusLevelForSmallerLandlordTeam"
: "NoBonusLevel",
});
}}
checked={bonusEnabled}
/>
</div>
</div>
</>
);
};
|
blu-world/shengji
|
frontend/src/state/Settings.ts
|
<filename>frontend/src/state/Settings.ts
import { State, combineState } from "../State";
import {
booleanLocalStorageState,
JSONLocalStorageState,
} from "../localStorageState";
export interface Settings {
fourColor: boolean;
darkMode: boolean;
showCardLabels: boolean;
showLastTrick: boolean;
beepOnTurn: boolean;
reverseCardOrder: boolean;
unsetAutoPlayWhenWinnerChanges: boolean;
showTrickInPlayerOrder: boolean;
separateCardsBySuit: boolean;
disableSuitHighlights: boolean;
svgCards: boolean;
playDrawCardSound: boolean;
suitColorOverrides: ISuitOverrides;
showDebugInfo: boolean;
}
export interface ISuitOverrides {
"♢"?: string;
"♡"?: string;
"♤"?: string;
"♧"?: string;
"🃟"?: string;
"🃏"?: string;
"🂠"?: string;
}
const fourColor: State<boolean> = booleanLocalStorageState("four_color");
const darkMode: State<boolean> = booleanLocalStorageState("dark_mode");
const svgCards: State<boolean> = booleanLocalStorageState("svg_cards");
const showCardLabels: State<boolean> =
booleanLocalStorageState("show_card_labels");
const showLastTrick: State<boolean> =
booleanLocalStorageState("show_last_trick");
const beepOnTurn: State<boolean> = booleanLocalStorageState("beep_on_turn");
const reverseCardOrder: State<boolean> =
booleanLocalStorageState("reverse_card_order");
const unsetAutoPlayWhenWinnerChanges: State<boolean> = booleanLocalStorageState(
"unset_autoplay_on_winner_change"
);
const showTrickInPlayerOrder: State<boolean> = booleanLocalStorageState(
"show_trick_in_player_order"
);
const separateCardsBySuit: State<boolean> = booleanLocalStorageState(
"separate_cards_by_suit"
);
const disableSuitHighlights: State<boolean> = booleanLocalStorageState(
"disable_suit_highlights"
);
const suitColorOverrides: State<ISuitOverrides> = JSONLocalStorageState(
"suit_color_overrides",
{}
);
const playDrawCardSound: State<boolean> = booleanLocalStorageState(
"play_draw_card_sound"
);
const showDebugInfo: State<boolean> =
booleanLocalStorageState("show_debug_info");
const settings: State<Settings> = combineState({
fourColor,
darkMode,
showCardLabels,
showLastTrick,
beepOnTurn,
reverseCardOrder,
unsetAutoPlayWhenWinnerChanges,
showTrickInPlayerOrder,
svgCards,
separateCardsBySuit,
disableSuitHighlights,
suitColorOverrides,
playDrawCardSound,
showDebugInfo,
});
export default settings;
|
blu-world/shengji
|
frontend/src/RandomizePlayersButton.tsx
|
<reponame>blu-world/shengji<filename>frontend/src/RandomizePlayersButton.tsx
import * as React from "react";
import { IPlayer } from "./types";
import { WebsocketContext } from "./WebsocketProvider";
import ArrayUtils from "./util/array";
interface Props {
players: IPlayer[];
children: string | JSX.Element | JSX.Element[];
}
export const RandomizePlayersButton = (props: Props): JSX.Element => {
const { players } = props;
const { send } = React.useContext(WebsocketContext);
const randomize = (): void => {
send({
Action: { ReorderPlayers: ArrayUtils.shuffled(players.map((p) => p.id)) },
});
};
return <button onClick={randomize}>{props.children}</button>;
};
|
weikinhuang/nbd.js
|
Class.d.ts
|
export interface ClassBuilder<I> {
new(...args: any[]): I;
extend<T extends I, G extends {} = {}>(proto: T, statics?: G): ClassBuilder<T> & G;
mixin<T>(this: T, ...args: any[]): T;
inherits(superclass: any): boolean;
}
declare const _default: ClassBuilder<any>;
export default _default;
|
weikinhuang/nbd.js
|
View/Entity.d.ts
|
<reponame>weikinhuang/nbd.js
export * from '../View';
export { default } from '../View';
|
weikinhuang/nbd.js
|
util/construct.d.ts
|
export default function construct<T = any>(this: T): T;
|
weikinhuang/nbd.js
|
View/Element.d.ts
|
<filename>View/Element.d.ts
import {
ViewConstructorProps,
ViewConstructor as NbdViewConstructor,
ViewInstance as NbdViewInstance,
NbdElement,
} from '../View';
export { ViewConstructorProps } from '../View';
export interface ViewInstance extends NbdViewInstance {
$parent: NbdElement;
}
export interface ViewConstructor<I extends ViewInstance> extends ViewConstructorProps, NbdViewConstructor<I> {
new(...args: any[]): I;
// we have to override here because we want to return a classbuilder that has additional props
extend<T extends I, G extends {} = {}>(a: T, b?: G): ViewConstructor<T> & G & ViewConstructorProps;
}
declare const _default: ViewConstructor<ViewInstance>;
export default _default;
|
weikinhuang/nbd.js
|
trait/responsive.d.ts
|
<reponame>weikinhuang/nbd.js<filename>trait/responsive.d.ts
import { ViewInstance } from '../View';
export interface ResponsiveTrait {
requestView(ViewClass: ViewInstance): void;
}
declare const _default: ResponsiveTrait;
export default _default;
|
weikinhuang/nbd.js
|
util/media.d.ts
|
<filename>util/media.d.ts
export default function media(options: any, query: string): any;
|
weikinhuang/nbd.js
|
Controller/Entity.d.ts
|
export * from '../Controller';
export { default } from '../Controller';
|
weikinhuang/nbd.js
|
Model.d.ts
|
import { ClassBuilder } from './Class';
import { PubSubTrait } from './trait/pubsub';
export interface ModelInstance extends PubSubTrait {
new(id: string, data: any): this;
// from nbd class
_super(...args: any[]): any;
init(id: string, data: any): void;
_id: string;
_data: any;
_dirty: number;
default: any;
destroy(): void;
id(): void;
data(): any;
get(prop: string): any;
set(prop: string, value: any): this;
set(map: Object): this;
toJSON(): any;
}
export interface ModelConstructorProps {
displayName: string;
}
export interface ModelConstructor<I extends ModelInstance = ModelInstance> extends ModelConstructorProps, ClassBuilder<I> {
new(...args: any[]): I;
// we have to override here because we want to return a classbuilder that has additional props
extend<T extends I, G extends {} = {}>(a: T, b?: G): ModelConstructor<T> & G;
}
declare const Model: ModelConstructor;
export default Model;
|
weikinhuang/nbd.js
|
util/throttle.d.ts
|
export default function throttle<T>(fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T>;
|
weikinhuang/nbd.js
|
util/diff.d.ts
|
export default function diff(cur: Object, prev: Object, callback?: (key: string, lhs: any, rhs: any) => void): { [k: string]: any; };
|
weikinhuang/nbd.js
|
util/extend.d.ts
|
// copied over from Object.assign
export default function assign<T, U>(target: T, source: U): T & U;
|
weikinhuang/nbd.js
|
Promise.d.ts
|
// for now, let's assume nbd/Promise is exactly the same as a native one
export default Promise;
|
weikinhuang/nbd.js
|
util/pipe.d.ts
|
export default function pipe<T = any>(...args: Function[]): T;
|
weikinhuang/nbd.js
|
trait/promise.d.ts
|
<filename>trait/promise.d.ts
export interface PromiseTrait<T> {
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
finally(onAny: (data?: any) => any): Promise<T>;
resolve(value: T): this;
reject(value: any): this;
thenable(): any;
promise(): Promise<T>;
}
declare const _default: PromiseTrait<any>;
export default _default;
|
weikinhuang/nbd.js
|
Logger.d.ts
|
import { PubSubTrait } from './trait/pubsub';
export interface Logger extends PubSubTrait {
new(name: any): this;
levels: string[];
name: string;
container: any;
level: string;
destroy(): void;
setLevel(level: string): void;
attach(route: any): void;
remove(route: any): void;
debug(...args: any[]): void;
log(...args: any[]): void;
info(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
_log(level: string): void;
_name(): string;
}
interface LoggerConstructor {
get(name: string): Logger;
attach(handler: Function): void;
setLevel(levelOrMap: any): void;
global(level: string, message: string): any;
console(level: string, message: string): any;
displayName: string;
}
declare const _default: LoggerConstructor;
export default _default;
|
weikinhuang/nbd.js
|
util/mixin.d.ts
|
<filename>util/mixin.d.ts
export default function mixin(target: any, abstract: any): void;
|
weikinhuang/nbd.js
|
util/deparam.d.ts
|
<reponame>weikinhuang/nbd.js<filename>util/deparam.d.ts<gh_stars>0
export default function deparam(params: string, coerce?: boolean): { [k:string]: any; };
|
weikinhuang/nbd.js
|
View.d.ts
|
import { ClassBuilder } from './Class';
import { PubSubTrait } from './trait/pubsub';
export type NbdElement = JQuery | HTMLElement;
export interface ViewInstance extends PubSubTrait {
new(model?: any): this;
// from nbd class
_super(...args: any[]): any;
init(config?: any): void;
_model: any;
nests: any;
id(): string;
$view: JQuery;
destroy(): void;
//template(templateData?: any): string;
template: any; // cannot use able definition because we use hgn-loader, and causes ts to be confused
templateData(): any;
render($parent: NbdElement): JQuery;
prerender(): void;
rendered($view: NbdElement): void;
postrender($view: NbdElement): void;
_switchNested(key: string, val: any, old: any): void;
}
export interface ViewConstructorProps {
displayName: string;
appendTo($child: NbdElement, $parent: NbdElement): JQuery;
find($root: NbdElement, selector: string): JQuery;
replace($old: NbdElement, $new: NbdElement): JQuery;
remove($el: NbdElement): JQuery;
}
export interface ViewConstructor<I extends ViewInstance = ViewInstance> extends ViewConstructorProps, ClassBuilder<I> {
new(...args: any[]): I;
// we have to override here because we want to return a classbuilder that has additional props
extend<T extends I, G extends {} = {}>(a: T, b?: G): ViewConstructor<T> & G;
domify(html: string): string;
}
declare const View: ViewConstructor;
export default View;
|
weikinhuang/nbd.js
|
Controller/Responsive.d.ts
|
import { ResponsiveTrait } from '../trait/responsive';
import {
ControllerConstructorProps,
ControllerConstructor as NbdControllerConstructor,
ControllerInstance as NbdControllerInstance,
} from '../Controller';
export { ControllerConstructorProps } from '../Controller';
export interface ControllerInstance extends NbdControllerInstance, ResponsiveTrait {
new(id: string, data: any, ...args: any[]): this;
}
export interface ControllerConstructor<I extends ControllerInstance> extends NbdControllerConstructor<I> {
// we have to override here because we want to return a classbuilder that has additional props
extend<T extends I, G extends {} = {}>(a: T, b?: G): ControllerConstructor<T> & G & ControllerConstructorProps<T>;
}
declare const _default: ControllerConstructor<ControllerInstance>;
export default _default;
|
weikinhuang/nbd.js
|
util/async.d.ts
|
<filename>util/async.d.ts
export default function async(handler: (...args: any[]) => void): void;
|
weikinhuang/nbd.js
|
trait/log.d.ts
|
<reponame>weikinhuang/nbd.js
import { Logger } from '../Logger';
export { Logger } from '../Logger';
export interface LogTrait {
log: Logger;
}
declare const _default: LogTrait;
export default _default;
|
weikinhuang/nbd.js
|
Controller.d.ts
|
import { ClassBuilder } from './Class';
import { ModelInstance, ModelConstructor } from './Model';
import { ViewInstance, ViewConstructor } from './View';
import { PubSubTrait } from './trait/pubsub';
export interface ControllerInstance extends PubSubTrait {
new(...args: any[]): this;
// from nbd class
_super(...args: any[]): any;
init(config?: any): void;
_view: ViewInstance;
_model: any;
readonly id: string;
readonly data: any;
render($parent: JQuery | HTMLElement, ViewClass: ViewInstance): Promise<JQuery>;
destroy(): void;
_initModel(...args: any[]): void;
_initView(...args: any[]): void;
switchView(...args: any[]): void;
requestView(ViewClass: ViewInstance): void;
toJSON(): any;
}
export interface ControllerConstructorProps<V = ViewConstructor, M = ModelConstructor> {
displayName: string;
VIEW_CLASS: V;
MODEL_CLASS: M;
}
export interface ControllerConstructor<I extends ControllerInstance = ControllerInstance> extends ControllerConstructorProps, ClassBuilder<I> {
new(...args: any[]): I;
// we have to override here because we want to return a classbuilder that has additional props
extend<T extends I, G extends {} = {}>(a: T, b?: G): ControllerConstructor<T> & G & ControllerConstructorProps<T>;
}
declare const Controller: ControllerConstructor;
export default Controller;
|
weikinhuang/nbd.js
|
trait/pubsub.d.ts
|
export type evtCallback = (...args: any[]) => any;
export interface PubSubTrait {
on(event: string, callback: evtCallback, context?: any): this;
one(event: string, callback: evtCallback, context?: any): this;
off(event: string, callback?: evtCallback, context?: any): this;
trigger(event: string, ...args: any[]): this;
listenTo(object: PubSubTrait, events: string | { [event: string]: evtCallback }, callback?: evtCallback): this;
listenOnce(object: PubSubTrait, events: string | { [event: string]: evtCallback }, callback?: evtCallback): this;
stopListening(object: PubSubTrait, events?: string, callback?: evtCallback): this;
relay(object: PubSubTrait, events: string): this;
}
declare const _default: PubSubTrait;
export default _default;
|
maplecloudy/shopizer-admin
|
src/app/pages/content/content-routing.module.ts
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContentComponent } from './content.component';
import { PageComponent } from './pages/page.component';
import { BoxesComponent } from './boxes/boxes.component';
import { AddPageComponent } from './pages/add-page.component';
import { AddBoxComponent } from './boxes/add-box.component';
import { ImagesComponent } from './images/images.component';
import { UploadComponent } from './upload/upload.component';
import { FilesComponent } from './files/files.component';
import { PromotionComponent } from './promotion/promotion.component';
// import { ImagesComponent } from './images/images.component';
const routes: Routes = [{
path: '',
component: ContentComponent,
children: [
{
path: 'pages/list',
component: PageComponent,
},
{
path: 'pages/add/:code',
component: AddPageComponent,
},
{
path: 'pages/add',
component: AddPageComponent,
},
{
path: 'boxes/list',
component: BoxesComponent,
},
{
path: 'boxes/add/:code',
component: AddBoxComponent,
},
{
path: 'boxes/add',
component: AddBoxComponent,
},
{
path: 'images/list',
component: ImagesComponent,
},
{
path: 'files/list',
component: FilesComponent,
},
{
path: 'promotion',
component: PromotionComponent,
}
],
}];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class ContentRoutingModule { }
export const routedComponents = [
ContentComponent,
PageComponent,
AddPageComponent,
BoxesComponent,
AddBoxComponent,
ImagesComponent,
UploadComponent,
PromotionComponent,
FilesComponent
];
|
maplecloudy/shopizer-admin
|
src/app/pages/user-management/users-list/button-render-user.component.ts
|
import { Component, Input } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { UserService } from '../../shared/services/user.service';
import { StorageService } from '../../shared/services/storage.service';
import { NbDialogService } from '@nebular/theme';
import { ShowcaseDialogComponent } from '../../shared/components/showcase-dialog/showcase-dialog.component';
@Component({
template: `
<input type="checkbox" [checked]="value" (click)="clicked()"/>
`,
})
export class ButtonRenderUserComponent {
@Input() value: string | number;
@Input() rowData: any;
constructor(
private userService: UserService,
private translate: TranslateService,
private toastr: ToastrService,
private storageService: StorageService,
private dialogService: NbDialogService,
) {
}
clicked() {
this.rowData.active = !this.value;
if(this.rowData.id === parseInt(this.storageService.getUserId())) {
this.dialogService.open(ShowcaseDialogComponent, {
context: {
title: '',
text: '',
actionText : this.translate.instant('USER_FORM.CANT_UPDATE_YOUR_PROFILE')
}
})
} else {
this.userService.updateUserEnabled(this.rowData)
.subscribe(res => {
this.toastr.success(this.translate.instant('AVAILABILITY.AVAILABILITY'));
});
}
}
}
|
maplecloudy/shopizer-admin
|
src/app/pages/store-management/models/store.ts
|
<gh_stars>10-100
export class Store {
id: number;
name: string;
code: string;
retailer: boolean;
}
|
maplecloudy/shopizer-admin
|
src/app/pages/store-management/models/logo.ts
|
<filename>src/app/pages/store-management/models/logo.ts
export class Logo {
id: number;
name: string;
path: string;
defaultImage: boolean;
externalUrl: string;
imageName: string;
imageType: string;
imageUrl: string;
videoUrl: string;
}
|
maplecloudy/shopizer-admin
|
src/app/pages/catalogue/options/services/option-value-image.service.ts
|
<filename>src/app/pages/catalogue/options/services/option-value-image.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { CrudService } from '../../../shared/services/crud.service';
@Injectable({
providedIn: 'root'
})
export class OptionValueImageService {
constructor(
private crudService: CrudService
) {
}
createImage(optionValueId, option): Observable<any> {
return this.crudService.post(`/v1/private/product/option/value/${optionValueId}/image`, option);
}
deleteImage(optionValueId): Observable<any> {
return this.crudService.delete(`/v1/private/product/option/value/${optionValueId}/image`);
}
}
|
maplecloudy/shopizer-admin
|
src/app/@theme/components/error/error.component.ts
|
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Router } from '@angular/router';
@Component({
selector: 'ngx-error',
templateUrl: './error.component.html',
styleUrls: ['./error.component.scss']
})
export class ErrorComponent implements OnInit {
constructor(
private translate: TranslateService,
private router: Router,
) { }
ngOnInit() {
}
goToHome() {
this.router.navigate(['/']);
}
}
|
maplecloudy/shopizer-admin
|
src/app/pages/tax-management/services/tax.service.ts
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { environment } from '../../../../environments/environment';
import { Observable } from 'rxjs';
import { CrudService } from '../../shared/services/crud.service';
@Injectable({
providedIn: 'root'
})
export class TaxService {
constructor(
private crudService: CrudService
) {
}
// Tax Classes Services
getTaxClass(params): Observable<any> {
return this.crudService.get('/v1/private/tax/class', params);
}
deleteTaxClass(id): Observable<any> {
return this.crudService.delete(`/v1/private/tax/class/${id}`);
}
getUniqueTax(code) {
return this.crudService.get(`/v1/private/tax/class/unique?code=${code}`);
}
addTaxClasses(param) {
return this.crudService.post(`/v1/private/tax/class`, param);
}
updateTaxClasses(taxClassID, params) {
return this.crudService.put('/v1/private/tax/class/' + taxClassID, params);
}
getTaxClassesDetails(param): Observable<any> {
return this.crudService.get('/v1/private/tax/class/' + param);
}
// Country & State
getCountry(): Observable<any> {
return this.crudService.get('/v1/country')
}
getBillingZone(value): Observable<any> {
return this.crudService.get('/v1/zones?code=' + value)
}
// Tax Rate Services
getTaxRate(params): Observable<any> {
return this.crudService.get('/v1/private/tax/rates', params);
}
getUniqueRate(code) {
return this.crudService.get(`/v1/private/tax/rate/unique?code=${code}`);
}
addTaxRate(param) {
return this.crudService.post(`/v1/private/tax/rate`, param);
}
deleteTaxRate(id): Observable<any> {
return this.crudService.delete(`/v1/private/tax/rate/${id}`);
}
getTaxRateDetails(param, lan): Observable<any> {
return this.crudService.get('/v1/private/tax/rate/' + param + '/?lang=' + lan);
}
updateTaxRate(taxrateID, params) {
return this.crudService.put('/v1/private/tax/rate/' + taxrateID, params);
}
}
|
maplecloudy/shopizer-admin
|
src/app/pages/shared/components/image-uploading/image-uploading-adapter.ts
|
import {
HttpRequest,
HttpClient,
HttpEvent,
HttpEventType
} from "@angular/common/http";
import { catchError, map } from "rxjs/operators";
import { Observable, of } from "rxjs";
import {
FilePickerAdapter,
UploadResponse,
UploadStatus,
FilePreviewModel
} from "ngx-awesome-uploader";
export class ImageUploadingAdapter extends FilePickerAdapter {
//add entity api
//remove api - what is the id
addImage: string
constructor(
private http: HttpClient, addImageUrl: string) {
super();
this.addImage = addImageUrl;
}
public uploadFile(fileItem: FilePreviewModel): Observable<UploadResponse> {
/** add api */
//must parent class
console.log('UPLOAD ADAPT ' + this.addImage);
const form = new FormData();
form.append("file", fileItem.file);
const api = this.addImage;
console.log(api, '-----------')
const req = new HttpRequest("POST", api, form, { reportProgress: true });
return this.http.request(req).pipe(
map((res: HttpEvent<any>) => {
console.log(JSON.stringify(res));
if (res.type === HttpEventType.Response) {
const responseFromBackend = res.body;
return {
body: responseFromBackend,
status: UploadStatus.UPLOADED
};
} else if (res.type === HttpEventType.UploadProgress) {
/** Compute and show the % done: */
const uploadProgress = +Math.round((100 *
res.loaded) / res.total);
return {
status: UploadStatus.IN_PROGRESS,
progress: uploadProgress
};
}
}),
catchError(er => {
console.log(JSON.stringify(er));
return of({ status: UploadStatus.ERROR, body: er });
})
);
}
public removeFile(fileItem: FilePreviewModel): Observable<any> {
/** remove api */
const id = 50;
const responseFromBackend = fileItem.uploadResponse;
console.log(fileItem);
const removeApi = '';
return this.http.post(removeApi, { id });
}
}
|
maplecloudy/shopizer-admin
|
src/app/@theme/components/image-browser/image-browser.component.ts
|
<filename>src/app/@theme/components/image-browser/image-browser.component.ts<gh_stars>10-100
import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { CrudService } from '../../../pages/shared/services/crud.service';
import { NbDialogRef } from '@nebular/theme';
@Component({
selector: 'ngx-image-browser',
templateUrl: './image-browser.component.html',
styleUrls: ['./image-browser.component.scss']
})
export class ImageBrowserComponent implements OnInit {
uploadedFiles: any[] = [];
loadingList = false;
constructor(
private crudService: CrudService,
protected ref: NbDialogRef<ImageBrowserComponent>
) {
}
ngOnInit() {
this.getImages();
}
getImages() {
this.loadingList = true;
this.crudService.get('/v1/content/images')
.subscribe(data => {
this.uploadedFiles = data.content;
this.loadingList = false;
}, error => {
this.loadingList = false;
});
}
cancel() {
this.ref.close();
}
openImage(value) {
this.ref.close(value.path + value.name);
}
}
|
maplecloudy/shopizer-admin
|
src/app/pages/store-management/store-management.module.ts
|
<filename>src/app/pages/store-management/store-management.module.ts
import { NgModule } from '@angular/core';
import { StoreManagementComponent } from './store-management.component';
import { SharedModule } from '../shared/shared.module';
import { StoreManagementRoutingModule } from './store-management-routing.module';
import { StoreDetailsComponent } from './store-details/store-details.component';
import { StoreCreationComponent } from './store-creation/store-creation.component';
import { StoresListComponent } from './stores-list/stores-list.component';
import { StoreFormComponent } from './store-form/store-form.component';
import { AgmCoreModule } from '@agm/core';
import { environment } from '../../../environments/environment';
import { StoreLandingPageComponent } from './store-landing-page/store-landing-page.component';
import { NgxSummernoteModule } from 'ngx-summernote';
import { StoreDetailInfoComponent } from './store-detail-info/store-detail-info.component';
import { StoreBrandingComponent } from './store-branding/store-branding.component';
import { RetailerComponent } from './retailer/retailer.component';
import { RetailerListComponent } from './retailer-list/retailer-list.component';
import { RetailerStoresComponent } from './retailer-stores/retailer-stores.component';
import { NbDialogModule } from '@nebular/theme';
@NgModule({
declarations: [
StoreManagementComponent,
StoreDetailsComponent,
StoreCreationComponent,
StoresListComponent,
StoreFormComponent,
StoreBrandingComponent,
StoreFormComponent,
StoreLandingPageComponent,
StoreDetailInfoComponent,
RetailerComponent,
RetailerListComponent,
RetailerStoresComponent
],
imports: [
StoreManagementRoutingModule,
AgmCoreModule.forRoot({
apiKey: environment.googleApiKey,
libraries: ['places'],
language: 'en'
}),
SharedModule,
NbDialogModule.forChild(),
NgxSummernoteModule
]
})
export class StoreManagementModule {
}
|
maplecloudy/shopizer-admin
|
src/app/pages/payment/payment-routing.module.ts
|
<gh_stars>10-100
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PaymentComponent } from './payment.component';
import { PaymentMethodsComponent } from './methods/methods.component';
import { ConfigureComponent } from './configure-form/configure.component';
import { NotFoundComponent } from '../shared/components/not-found/not-found.component';
const routes: Routes = [
{
path: '', component: PaymentComponent, children: [
{
path: '',
redirectTo: 'payment-methods',
pathMatch: 'full',
},
{
path: 'methods',
component: PaymentMethodsComponent,
},
{
path: 'configure/:id',
component: ConfigureComponent
},
// {
// path: 'classes-add',
// component: TaxClassAddComponent,
// },
// {
// path: 'rate-list',
// component: TaxRateListComponent,
// },
// {
// path: 'rate-add',
// component: TaxRateAddComponent,
// },
{
path: '**',
component: NotFoundComponent
}
],
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PaymentRoutingModule {
}
|
maplecloudy/shopizer-admin
|
src/app/pages/catalogue/products/products-list/products-list.component.ts
|
<gh_stars>0
import { Component, OnInit } from '@angular/core';
import { ProductService } from '../services/product.service';
import { LocalDataSource } from 'ng2-smart-table';
import { AvailableButtonComponent } from './available-button.component';
import { ShowcaseDialogComponent } from '../../../shared/components/showcase-dialog/showcase-dialog.component';
import { NbDialogService } from '@nebular/theme';
import { StoreService } from '../../../store-management/services/store.service';
import { UserService } from '../../../shared/services/user.service';
import { TranslateService } from '@ngx-translate/core';
import { StorageService } from '../../../shared/services/storage.service';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
import { ListingService } from '../../../shared/services/listing.service';
@Component({
selector: 'ngx-products-list',
templateUrl: './products-list.component.html',
styleUrls: ['./products-list.component.scss']
})
export class ProductsListComponent implements OnInit {
products = [];
source: LocalDataSource = new LocalDataSource();
listingService: ListingService;
loadingList = false;
loading: boolean = false;
stores = [];
isSuperadmin: boolean;
selectedStore: String = '';
// paginator
perPage = 15;
currentPage = 1;
totalCount;
merchant;
// server params
params = this.loadParams();
settings = {};
constructor(
private userService: UserService,
private productService: ProductService,
private dialogService: NbDialogService,
private storeService: StoreService,
private translate: TranslateService,
private storageService: StorageService,
private toastr: ToastrService,
private router: Router
) {
this.selectedStore = this.storageService.getMerchant()
this.isSuperadmin = this.storageService.getUserRoles().isSuperadmin;
this.listingService = new ListingService();
}
loadParams() {
return {
store: this.storageService.getMerchant(),
lang: this.storageService.getLanguage(),
count: this.perPage,
page: 0
};
}
ngOnInit() {
this.getStore();
this.getList();
this.translate.onLangChange.subscribe((lang) => {
this.params.lang = this.storageService.getLanguage();
this.getList();
});
//ng2-smart-table server side filter //list in field
this.source.onChanged().subscribe((change) => {
if (!this.loadingList) {//listing service
this.listingService.filterDetect(this.params, change, this.loadList.bind(this), this.resetList.bind(this));
}
});
}
fetchTableData(){
this.loadingList = true;
this.productService.getListOfProducts(this.params)
.subscribe(res => {
const products = res.products;
this.totalCount = res.recordsTotal;
products.forEach(el => {
el.name = el.description.name;
});
this.products = [...products];
this.source.load(products);
this.loadingList = false;
});
}
/** callback methods for table list*/
private loadList(newParams: any) {
this.currentPage = 1; //back to page 1
this.params = newParams;
this.fetchTableData();
}
private resetList() {
this.currentPage = 1;//back to page 1
this.params = this.loadParams();
this.getList();
}
/** */
getStore() {
this.storeService.getListOfStores({ code: 'DEFAULT' })
.subscribe(res => {
let storeData = []
res.data.forEach((store) => {
storeData.push(store.code);
});
this.stores = storeData;
});
}
getList() {
const startFrom = this.currentPage - 1;
this.params.page = startFrom;
this.fetchTableData();
this.setSettings();
}
setSettings() {
this.settings = {
actions: {
columnTitle: this.translate.instant('ORDER.ACTIONS'),
add: false,
edit: false,
delete: false,
position: 'right',
sort: true,
custom: [
{ name: 'edit', title: '<i class="nb-edit"></i>' },
{ name: 'remove', title: '<i class="nb-trash"></i>' }
],
},
pager: {
display: false
},
columns: {
id: {
title: this.translate.instant('COMMON.ID'),
type: 'number',
editable: false,
filter: false
},
sku: {
title: this.translate.instant('PRODUCT.SKU'),
type: 'string',
editable: false,
filter: true
},
name: {
title: this.translate.instant('PRODUCT.PRODUCT_NAME'),
type: 'html',
filter: true,
editable: false
},
quantity: {
title: this.translate.instant('PRODUCT.QTY'),
type: 'number',
editable: true,
filter: false
},
available: {
filter: false,
title: this.translate.instant('COMMON.AVAILABLE'),
type: 'custom',
renderComponent: AvailableButtonComponent,
defaultValue: false,
editable: true,
editor: {
type: 'checkbox'
}
},
price: {
title: this.translate.instant('PRODUCT.PRICE'),
type: 'string',
editable: true,
filter: false
},
creationDate: {
title: this.translate.instant('PRODUCT.CREATION_DATE'),
type: 'string',
editable: false,
filter: false
},
},
};
}
updateRecord(event) {
const product = {
available: event.newData.available,
price: event.newData.price,
quantity: event.newData.quantity
};
event.confirm.resolve(event.newData);
this.productService.updateProductFromTable(event.newData.id, product)
.subscribe(res => {
event.confirm.resolve(event.newData);
this.toastr.success(this.translate.instant('PRODUCT.PRODUCT_UPDATED'));
}, error => {
console.log(error.error.message);
});
}
deleteRecord(event) {
this.dialogService.open(ShowcaseDialogComponent, {})
.onClose.subscribe(res => {
if (res) {
this.productService.deleteProduct(event.data.id)
.subscribe(result => {
this.toastr.success(this.translate.instant('PRODUCT.PRODUCT_REMOVED'));
this.getList();
// event.confirm.resolve();
});
} else {}
});
}
choseStore(event) {
this.params.store = event;
this.getList();
}
// paginator
changePage(event) {
switch (event.action) {
case 'onPage': {
this.currentPage = event.data;
break;
}
case 'onPrev': {
this.currentPage--;
break;
}
case 'onNext': {
this.currentPage++;
break;
}
case 'onFirst': {
this.currentPage = 1;
break;
}
case 'onLast': {
this.currentPage = event.data;
break;
}
}
this.getList();
}
route(e) {
//console.log(e)
if (e.action == 'remove') {
this.deleteRecord(e)
} else {
this.router.navigate(['pages/catalogue/products/product/' + e.data.id]);
}
}
}
|
maplecloudy/shopizer-admin
|
src/app/pages/catalogue/catalogues/catalogues-routing.module.ts
|
<filename>src/app/pages/catalogue/catalogues/catalogues-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CataloguesComponent } from './catalogues.component';
import { CataloguesListComponent } from './catalogues-list/catalogues-list.component';
import { CatalogueFormComponent } from './catalogue-form/catalogue-form.component';
import { ProductToCatalogueComponent } from './product-to-catalogue/product-to-catalogue.component';
const routes: Routes = [
{
path: '',
component: CataloguesComponent,
children: [
{
path: 'create-catalogue',
component: CatalogueFormComponent,
},
{
path: 'catalogue/:catalogId',
component: CatalogueFormComponent,
},
{
path: 'catalogues-list',
component: CataloguesListComponent,
},
{
path: ':catalogId/catalogues-products',
component: ProductToCatalogueComponent,
},
],
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class CataloguesRoutingModule {
}
|
maplecloudy/shopizer-admin
|
src/app/pages/catalogue/products/services/product-properties.ts
|
import { Injectable } from '@angular/core';
import { CrudService } from '../../../shared/services/crud.service';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PropertiesService {
constructor(
private crudService: CrudService
) {
}
getProductProperties(productType, lang): Observable<any> {
const params = {
productType: productType,
lang: lang
};
return this.crudService.get(`/v1/private/product/property/set`, params);
}
}
|
maplecloudy/shopizer-admin
|
src/app/pages/catalogue/types/services/types.service.ts
|
<gh_stars>10-100
import { Injectable } from '@angular/core';
import { CrudService } from '../../../shared/services/crud.service';
import { Observable } from 'rxjs';
import { StorageService } from '../../../shared/services/storage.service';
@Injectable({
providedIn: 'root'
})
export class TypesService {
constructor(
private crudService: CrudService,
private storageService: StorageService
) { }
getListOfTypes(params): Observable<any> {
return this.crudService.get(`/v1/private/products/types`, params);
}
getType(id, params): Observable<any> {
return this.crudService.get(`/v1/private/products/type/${id}`, params);
}
createType(req): Observable<any> {
const reqparams = {
store: this.storageService.getMerchant(),
lang: this.storageService.getLanguage()
};
return this.crudService.post('/v1/private/products/type', req, reqparams);
}
updateType(id, req): Observable<any> {
const reqparams = {
store: this.storageService.getMerchant(),
lang: this.storageService.getLanguage()
};
return this.crudService.put(`/v1/private/products/type/${id}`, req, reqparams);
}
deleteType(id): Observable<any> {
const reqparams = {
store: this.storageService.getMerchant(),
lang: this.storageService.getLanguage()
};
return this.crudService.delete(`/v1/private/products/type/${id}`, reqparams);
}
checkCode(code): Observable<any> {
const reqparams = {
store: this.storageService.getMerchant(),
lang: this.storageService.getLanguage()
};
return this.crudService.get('/v1/private/products/type/unique?code=' + code, reqparams);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.