repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
yyzclyang/algae-ui
site/componentExample/ButtonExample/index.ts
export { default } from './button.example';
yyzclyang/algae-ui
site/componentExample/AffixExample/affix.codeDemo1.tsx
<gh_stars>1-10 import React from 'react'; import { Affix, Button } from 'algae-ui'; export default () => { const el = document.querySelectorAll('.site-main')[0]; return ( <div className="affix-example-list"> <Affix target={() => el as HTMLElement}> <Button>Affix Top</Button> </Affix> </div> ); };
yyzclyang/algae-ui
components/checkbox/index.ts
export { default } from './checkbox'; export { default as CheckboxGroup } from './checkboxGroup';
yyzclyang/algae-ui
components/utils/validator.ts
<reponame>yyzclyang/algae-ui import { FormValue, Field, Rule, FormMessageType } from '../form'; interface ValidateFormMessage { type: FormMessageType; message: string; } export interface ValidateFormMessageGroup { [key: string]: ValidateFormMessage[]; } const validator = ( formValue: FormValue, fields: Field[] ): Promise<ValidateFormMessageGroup> => Promise.all( fields.map((field) => Promise.all( [ Promise.resolve({ type: 'success', message: field.type }) as Promise< ValidateFormMessage > ].concat( field.rules ? field.rules.map((rule) => validateMethod(formValue[field.type], rule) ) : [] ) ) ) ).then((allValidateMessages) => allValidateMessages .map((validateMessages) => ({ [validateMessages[0].message]: validateMessages .slice(1) .filter((validateMessage) => validateMessage.message) })) .reduce((validateMessageGroup, singleValidateMessageGroup) => ({ ...validateMessageGroup, ...singleValidateMessageGroup })) ); const validateMethod = ( data: string, rule: Rule ): Promise<ValidateFormMessage> => { switch (rule.type) { case 'required': { return Promise.resolve({ type: rule.messageType || 'error', message: rule.match && !data ? rule.message : '' }); } case 'minLength': { return Promise.resolve({ type: rule.messageType || 'error', message: data.length < rule.match ? rule.message : '' }); } case 'maxLength': { return Promise.resolve({ type: rule.messageType || 'error', message: data.length > rule.match ? rule.message : '' }); } case 'pattern': { return Promise.resolve({ type: rule.messageType || 'error', message: !rule.match.test(data) ? rule.message : '' }); } case 'custom': { const matchResult = rule.match(data); return matchResult instanceof Promise ? matchResult.then( () => { return { type: rule.messageType || 'error', message: '' }; }, () => { return { type: rule.messageType || 'error', message: rule.message }; } ) : Promise.resolve({ type: rule.messageType || 'error', message: !matchResult ? rule.message : '' }); } default: { return Promise.resolve({ type: 'error', message: '验证类型错误' }); } } }; export default validator;
yyzclyang/algae-ui
site/componentExample/LayoutExample/index.ts
<reponame>yyzclyang/algae-ui export { default } from './layout.example';
yyzclyang/algae-ui
site/componentExample/CheckboxExample/checkbox.codeDemo4.tsx
import React, { useState } from 'react'; import { Checkbox, CheckboxGroup } from 'algae-ui'; export default () => { const [checkedList, setCheckedList] = useState<string[]>([]); return ( <div className="checkbox-example-list"> <CheckboxGroup value={checkedList} onChange={(value) => { setCheckedList(value); }} > <Checkbox value="A">A</Checkbox> <Checkbox value="B">B</Checkbox> <Checkbox value="C">C</Checkbox> </CheckboxGroup> </div> ); };
yyzclyang/algae-ui
site/componentExample/CommonDispalyComponents/index.ts
<gh_stars>1-10 export * from './api'; export * from './codeDemo';
yyzclyang/algae-ui
site/componentExample/FormExample/form.example.tsx
<filename>site/componentExample/FormExample/form.example.tsx import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './form.example.scss'; import CodeDemo1 from './form.codeDemo1'; const code1 = require('!!raw-loader!./form.codeDemo1.tsx'); import CodeDemo2 from './form.codeDemo2'; const code2 = require('!!raw-loader!./form.codeDemo2.tsx'); import CodeDemo3 from './form.codeDemo3'; const code3 = require('!!raw-loader!./form.codeDemo3.tsx'); import CodeDemo4 from './form.codeDemo4'; const code4 = require('!!raw-loader!./form.codeDemo4.tsx'); const SwitchExample: React.FunctionComponent = () => { return ( <div className="switch-example-page"> <section> <h1>Form 表单</h1> <p>具有数据收集、校验和提交功能的表单</p> </section> <section> <h2>何时使用</h2> <p>用于创建一个实体或收集信息。</p> <p>需要对输入的数据类型进行校验时。</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础使用" content={<p>最简单的用法</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="自定义检测规则" content={<p>除了内置的几种检测项,还可以自定义规则进行检测。</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="规则检测" content={ <p> 可设置规则对输入的字符串进行检测,并可自定义提示信息内容及提示等级。 </p> } code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="异步检测" content={<p>可对输入的字符进行异步检测。</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <Api data={[ [ 'value', <> <code>Form</code>表单的数据 </>, '{ [key: string]: string }', '-' ], ['fields', '渲染输入框的规则', 'Field[]', '-'], [ 'buttons', <> <code>Form</code>表单的按钮组,提交按钮需要设置 <code>type = &quot;submit&quot;</code> </>, 'React.ReactNode', '-' ], [ 'onSubmit', <> <code>Form</code>提交时的回调 </>, 'React.FormEventHandler<HTMLFormElement>', '-' ], [ 'onChange', <> <code>Form</code>中输入框变化时的回调 </>, '(formValue: FormValue) => void', '-' ] ]} /> <h3>Field</h3> <p> <code>Field</code>是输入框的检测规程,其类型如下: </p> <Api data={[ [ 'type', '检测的类型', 'required | minLength | maxLength | pattern | custom', '-' ], [ 'match', '具体的检测规则', 'boolean | number | number | RegExp | (value: string) => boolean | Promise<boolean>', '-' ], [ 'messageType', '当检测结果为假时提示消息的类型', ' success | warning | error', 'error' ], ['message', '当检测结果为假时提示消息的内容', 'string', '-'] ]} /> </section> </div> ); }; export default SwitchExample;
yyzclyang/algae-ui
site/componentExample/CheckboxExample/checkbox.codeDemo5.tsx
import React, { useState } from 'react'; import { CheckboxGroup } from 'algae-ui'; export default () => { const [checkedList1, setCheckedList1] = useState<string[]>([]); const [checkedList2, setCheckedList2] = useState<string[]>([]); const [checkedList3, setCheckedList3] = useState<string[]>([]); const options = ['A', 'B', 'C']; const options2 = [ { label: 'A', value: 'A' }, { label: 'b', value: 'B' }, { label: 'C', value: 'C' } ]; const options3 = [ { label: 'A', value: 'A' }, { label: 'B', value: 'B' }, { label: 'C', value: 'C', disabled: true } ]; return ( <div className="checkbox-example-list"> <CheckboxGroup options={options} value={checkedList1} onChange={(value) => { setCheckedList1(value); }} /> <br /> <CheckboxGroup options={options2} value={checkedList2} onChange={(value) => { setCheckedList2(value); }} /> <br /> <CheckboxGroup options={options3} value={checkedList3} onChange={(value) => { setCheckedList3(value); }} /> </div> ); };
yyzclyang/algae-ui
site/componentExample/SwitchExample/switch.example.tsx
<reponame>yyzclyang/algae-ui import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './switch.example.scss'; import CodeDemo1 from './switch.codeDemo1'; const code1 = require('!!raw-loader!./switch.codeDemo1.tsx'); import CodeDemo2 from './switch.codeDemo2'; const code2 = require('!!raw-loader!./switch.codeDemo2.tsx'); import CodeDemo3 from './switch.codeDemo3'; const code3 = require('!!raw-loader!./switch.codeDemo3.tsx'); import CodeDemo4 from './switch.codeDemo4'; const code4 = require('!!raw-loader!./switch.codeDemo4.tsx'); const SwitchExample: React.FunctionComponent = () => { return ( <div className="switch-example-page"> <section> <h1>Switch 开关</h1> <p>开关选择器</p> </section> <section> <h2>何时使用</h2> <p>需要表示开关状态/两种状态之间的切换时。</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础使用" content={<p>最简单的用法</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="文字和图标" content={<p>用文字和图标来表示当前的状态</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="不可用状态" content={<p>Switch 不可用状态</p>} code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="加载中" content={<p>表示相关操作正在进行中</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <Api data={[ [ 'className', <> <code>Switch</code>的类名 </>, 'string', '-' ], [ 'check', <> 表示当前<code>Switch</code>的状态 </>, 'boolean', '-' ], [ 'defaultChecked', <> 表示当前<code>Switch</code>的默认值。 </>, 'boolean', '-' ], [ 'disabled', <> 是否禁用<code>Switch</code> </>, 'boolean', 'false' ], [ 'loading', <> 表示加载状态中的<code>Switch</code> </>, 'boolean', 'false' ], [ 'onClick', <> <code>Switch</code>开关点击时的回调 </>, 'React.MouseEventHandler', '-' ], [ 'onChange', <> <code>Switch</code>状态改变时的回调,参数为即将变化到的状态值 </>, '(arg1?: boolean) => void', '-' ], [ 'checkedEl', <> <code>Switch</code>选中状态时的内容 </>, 'string | React.ReactElement', '-' ], [ 'uncheckedEl', <> <code>Switch</code>未选中状态时的内容 </>, 'string | React.ReactElement', '-' ] ]} /> </section> </div> ); }; export default SwitchExample;
yyzclyang/algae-ui
components/utils/useControlState.ts
<filename>components/utils/useControlState.ts import React, { useState } from 'react'; import useUpdate from './useUpdate'; const useControlState: <S>( defaultState: S | (() => S), controlState?: S | (() => S) ) => [S, React.Dispatch<React.SetStateAction<S>>] = ( initialState, controlState? ) => { const [state, setState] = useState(controlState ?? initialState); useUpdate(() => { if (controlState !== undefined) { setState(controlState); } }, [controlState]); return [ state, (setStateAction) => { if (setStateAction instanceof Function) { setStateAction(state); } if (controlState === undefined) { setState(setStateAction); } } ]; }; export default useControlState;
yyzclyang/algae-ui
site/componentExample/RadioExample/radio.codeDemo1.tsx
<reponame>yyzclyang/algae-ui import React from 'react'; import { Radio } from 'algae-ui'; export default () => { return ( <div className="radio-example-list"> <Radio>Radio</Radio> </div> ); };
yyzclyang/algae-ui
site/componentExample/RateExample/index.ts
export { default } from './rate.example';
yyzclyang/algae-ui
site/componentExample/CheckboxExample/checkbox.example.tsx
import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './checkbox.example.scss'; import CodeDemo1 from './checkbox.codeDemo1'; const code1 = require('!!raw-loader!./checkbox.codeDemo1.tsx'); import CodeDemo2 from './checkbox.codeDemo2'; const code2 = require('!!raw-loader!./checkbox.codeDemo2.tsx'); import CodeDemo3 from './checkbox.codeDemo3'; const code3 = require('!!raw-loader!./checkbox.codeDemo3.tsx'); import CodeDemo4 from './checkbox.codeDemo4'; const code4 = require('!!raw-loader!./checkbox.codeDemo4.tsx'); import CodeDemo5 from './checkbox.codeDemo5'; const code5 = require('!!raw-loader!./checkbox.codeDemo5.tsx'); import CodeDemo6 from './checkbox.codeDemo6'; const code6 = require('!!raw-loader!./checkbox.codeDemo6.tsx'); const CheckboxExample: React.FunctionComponent = () => { return ( <div className="checkbox-example-page"> <section> <h1>Checkbox 多选框</h1> <p>多选框</p> </section> <section> <h2>何时使用</h2> <p>在一组可选项中进行多项选择时</p> <p>单独使用可以表示两种状态之间的切换</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础使用" content={<p>最简单的用法</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="受控组件" content={<p>受控的 Checkbox</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> <CodeDemo title="CheckboxGroup" content={<p>通过 options 生成 CheckboxGroup</p>} code={code5.default} > <CodeDemo5 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="Disabled" content={<p>Checkbox 不可用状态</p>} code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="CheckboxGroup" content={<p>多个 Checkbox 组成的 CheckboxGroup</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> <CodeDemo title="全选框" content={<p>实现全选框</p>} code={code6.default} > <CodeDemo6 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <h3>Checkbox</h3> <p> <code>Checkbox</code>拓展自 <code>&lt;input type=&quot;checkbox&quot; /&gt;</code>,除了以下 <code>Api</code> ,还支持<code>input</code>的其他<code>Api</code>。 </p> <Api data={[ ['checked', '是否选中', 'boolean', '-'], ['defaultChecked', '默认是否选中', 'boolean', 'false'], ['disabled', '是否禁用', 'boolean', 'false'], [ 'indeterminate', '设置半选中模式,用于设置全选框', 'boolean', 'false' ], ['onChange', '选取时的回调', 'React.ChangeEventHandler', '-'] ]} /> <h3>CheckboxGroup</h3> <p> 用于设置一组<code>Checkbox</code>。 </p> <Api data={[ [ 'value', <> 用于设置当前激活的<code>Checkbox</code> </>, 'string', '-' ], [ 'name', <> 为被包裹的<code>Checkbox</code>添加<code>name</code>属性 </>, 'string', '-' ], [ 'disabled', <> 禁用所有的子<code>Checkbox</code> </>, 'boolean', 'false' ], [ 'options', <> 使用配置模式配置子<code>Checkbox</code>。 </>, 'Array<{ label: string, value: string, disabled?: boolean } | string>', '-' ], ['onChange', '选项变化时的回调', 'React.ChangeEventHandler', '-'] ]} /> </section> </div> ); }; export default CheckboxExample;
yyzclyang/algae-ui
components/icon/style/index.ts
<reponame>yyzclyang/algae-ui<filename>components/icon/style/index.ts import './icon.scss';
yyzclyang/algae-ui
site/componentExample/ButtonExample/button.codeDemo1.tsx
<reponame>yyzclyang/algae-ui<gh_stars>1-10 import React from 'react'; import { Button } from 'algae-ui'; export default () => { return ( <div className="button-list"> <Button buttonType="primary">Primary</Button> <Button>Default</Button> <Button buttonType="success">Success</Button> <Button buttonType="danger">Danger</Button> </div> ); };
yyzclyang/algae-ui
site/componentExample/SwitchExample/switch.codeDemo3.tsx
<gh_stars>1-10 import React from 'react'; import { Switch, Icon } from 'algae-ui'; export default () => { return ( <div className="switch-example-list"> <Switch defaultChecked checkedEl="开" uncheckedEl="关" /> <br /> <br /> <Switch defaultChecked checkedEl="1" uncheckedEl="0" /> <br /> <br /> <Switch defaultChecked checkedEl={<Icon type="check" />} uncheckedEl={<Icon type="close" />} /> </div> ); };
yyzclyang/algae-ui
site/componentExample/TreeExample/index.ts
<reponame>yyzclyang/algae-ui export { default } from './tree.example';
yyzclyang/algae-ui
site/componentExample/ButtonExample/button.codeDemo4.tsx
<filename>site/componentExample/ButtonExample/button.codeDemo4.tsx import React, { useState } from 'react'; import { Button } from 'algae-ui'; export default () => { const [loading, setLoading] = useState<boolean>(false); const [iconLoading, setIconLoading] = useState<boolean>(false); return ( <div className="button-list"> <div> <Button buttonType="primary" loading> Loading </Button> <Button icon="setting" loading> Loading </Button> </div> <div> <Button buttonType="primary" loading={loading} onClick={() => { setLoading(true); }} > Click me ! </Button> <Button icon="setting" loading={iconLoading} onClick={() => { setIconLoading(true); }} > Click me ! </Button> </div> <div> <Button buttonType="primary" loading /> <Button loading /> </div> </div> ); };
yyzclyang/algae-ui
site/componentExample/StepsExample/steps.codeDemo2.tsx
<gh_stars>1-10 import React from 'react'; import { Steps, Step, Icon } from 'algae-ui'; export default () => { return ( <div className="steps-example-list"> <Steps> <Step title="edit" status="success" icon={<Icon type="edit" />} /> <Step title="form" status="process" icon={<Icon type="form" />} /> <Step title="delete" status="waiting" icon={<Icon type="delete" />} /> </Steps> </div> ); };
yyzclyang/algae-ui
site/componentExample/MessageExample/message.codeDemo1.tsx
import React from 'react'; import { Button, message } from 'algae-ui'; export default () => { return ( <div className="message-example-list"> <Button buttonType="primary" onClick={() => { message.info('这是一条普通消息'); }} > normal message </Button> </div> ); };
yyzclyang/algae-ui
components/checkbox/checkboxGroup.tsx
import React, { useState, useEffect } from 'react'; import { classNames, scopedClassMaker } from '../utils'; import Checkbox from './checkbox'; const sc = scopedClassMaker('algae-ui-checkbox-group'); interface Option { label: string; value: string; disabled?: boolean; } interface CheckboxGroupProps { className?: string; value?: string[]; name?: string; disabled?: boolean; options?: Array<Option | string>; children?: React.ReactNode; onChange?: (checkedList: string[]) => void; } const CheckboxGroup: React.FunctionComponent<CheckboxGroupProps> = ( props: CheckboxGroupProps ) => { const { className, value: checkboxGroupValueArray, name, disabled, options, onChange, children } = props; const [checkboxCheckedList, setCheckboxCheckedList] = useState<string[]>( checkboxGroupValueArray !== undefined ? checkboxGroupValueArray : [] ); useEffect(() => { setCheckboxCheckedList(checkboxGroupValueArray || []); }, [checkboxGroupValueArray]); const handleChange: React.ChangeEventHandler<HTMLInputElement> = ( e: React.ChangeEvent ) => { const currentValue = (e.target as HTMLInputElement).value || ''; const currentCheckedListSet = new Set(checkboxCheckedList); if (currentCheckedListSet.has(currentValue)) { currentCheckedListSet.delete(currentValue); } else { currentCheckedListSet.add(currentValue); } onChange && onChange(Array.from(currentCheckedListSet)); }; return ( <div className={classNames(sc(), disabled ? sc('disabled') : '', className)} > {React.Children.map(children, (child) => { return React.isValidElement(child) ? React.cloneElement( child, Object.assign( {}, { checked: child.props.value !== undefined && checkboxCheckedList.includes(child.props.value), onChange: handleChange }, name ? { name } : {}, disabled ? { disabled: true } : {} ) ) : child; })} {options && options.map((item) => { return typeof item !== 'string' ? ( <Checkbox key={Math.random()} value={item.value} checked={checkboxCheckedList.includes(item.value)} disabled={ disabled ? true : item.disabled !== undefined ? item.disabled : false } onChange={handleChange} > {item.label} </Checkbox> ) : ( <Checkbox key={Math.random()} value={item} checked={checkboxCheckedList.includes(item)} disabled={disabled} onChange={handleChange} > {item} </Checkbox> ); })} </div> ); }; CheckboxGroup.displayName = 'CheckboxGroup'; CheckboxGroup.defaultProps = { disabled: false }; export default CheckboxGroup;
yyzclyang/algae-ui
site/componentExample/ProgressExample/progress.codeDemo1.tsx
import React from 'react'; import { Progress } from 'algae-ui'; export default () => { return ( <div className="progress-list"> <Progress percent={30} /> <Progress percent={50} /> <Progress percent={20} status="fail" /> <Progress percent={70} status="success" /> <Progress percent={50} showInfo={false} /> </div> ); };
yyzclyang/algae-ui
site/componentExample/StepsExample/index.ts
export { default } from './steps.example';
yyzclyang/algae-ui
site/componentExample/InputExample/input.codeDemo4.tsx
<reponame>yyzclyang/algae-ui import React, { useState } from 'react'; import { TextArea } from 'algae-ui'; export default () => { const [value, setValue] = useState<string>(''); return ( <div className="input-example-list"> <TextArea defaultValue="default input" value={value} onChange={(e) => { setValue(e.currentTarget.value); console.log(e.currentTarget.value); }} /> </div> ); };
yyzclyang/algae-ui
components/layout/index.ts
export { default } from './layout'; export { default as Header } from './header'; export { default as Side } from './side'; export { default as Content } from './content'; export { default as Footer } from './footer';
yyzclyang/algae-ui
site/componentExample/CommonDispalyComponents/codeDemo/codeDemo.tsx
<reponame>yyzclyang/algae-ui import React, { useState, useEffect } from 'react'; import copy from 'copy-to-clipboard'; import Highlight, { defaultProps } from 'prism-react-renderer'; import oceanicNext from './customTheme'; import { Icon } from 'algae-ui'; import './codeDemo.scss'; interface CodeDemoProps { title: string; content: React.ReactNode; code: string; children: React.ReactNode; } const CodeDemo: React.FunctionComponent<CodeDemoProps> = ( props: CodeDemoProps ) => { const { title, content, code, children } = props; const [codeVisible, setCodeVisible] = useState<boolean>(false); const [copyFlagVisible, setCopyFlagVisible] = useState<boolean>(false); const [resetCopyFlagVisible, setResetCopyFlagVisible] = useState< ReturnType<typeof setTimeout> >(); useEffect(() => { return () => { resetCopyFlagVisible && clearTimeout(resetCopyFlagVisible); }; }, [resetCopyFlagVisible]); return ( <div className="code-demo"> <div className="component-list">{children}</div> <div className="title"> <span>{title}</span> </div> <div className="content"> <span>{content}</span> </div> <div className="code-control"> {!copyFlagVisible && ( <div className="copy" onClick={() => { copy(code); setCopyFlagVisible(true); setResetCopyFlagVisible( setTimeout(() => { setCopyFlagVisible(false); }, 2000) ); }} > <Icon type="copy" /> </div> )} {copyFlagVisible && ( <div className="check"> <Icon type="check" style={{ fill: '#20baa4' }} /> </div> )} {!codeVisible && ( <div className="code-show" onClick={() => { setCodeVisible(true); }} > <Icon type="code-show" /> </div> )} {codeVisible && ( <div className="code-hidden" onClick={() => { setCodeVisible(false); }} > <Icon type="code-hidden" /> </div> )} </div> <> {codeVisible && ( <div className="code"> <Highlight {...defaultProps} code={code} language="jsx" theme={oceanicNext} > {({ className, style, tokens, getLineProps, getTokenProps }) => ( <pre className={className} style={style}> {tokens.map((line, i) => ( <div key={i} {...getLineProps({ line, key: i })}> {line.map((token, key) => ( <span key={key} {...getTokenProps({ token, key })} /> ))} </div> ))} </pre> )} </Highlight> </div> )} </> </div> ); }; export default CodeDemo;
yyzclyang/algae-ui
site/componentExample/AffixExample/affix.example.tsx
import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './affix.example.scss'; import CodeDemo1 from './affix.codeDemo1'; const code1 = require('!!raw-loader!./affix.codeDemo1.tsx'); import CodeDemo2 from './affix.codeDemo2'; const code2 = require('!!raw-loader!./affix.codeDemo2.tsx'); import CodeDemo3 from './affix.codeDemo3'; const code3 = require('!!raw-loader!./affix.codeDemo3.tsx'); const LayoutExample: React.FunctionComponent = () => { return ( <div className="affix-example-page"> <h1>Affix 固钉</h1> <p>将页面元素钉在可视范围内。</p> <section> <h2>何时使用</h2> <p> 当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。 </p> <p>页面可视范围过小时,慎用此功能以免遮挡页面内容。</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础" content={<p>最基本的用法</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="滚动容器" content={ <p> 设置<code>Affix</code>需要监听的元素,默认为 <code>window</code>。 </p> } code={code3.default} > <CodeDemo3 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="固定状态改变时添加回调" content={<p>可以获得是否固定的状态信息</p>} code={code2.default} > <CodeDemo2 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <Api data={[ [ 'offsetTop', <> 距离窗口顶部达到指定偏移量后触发,单位为<code>px</code> </>, 'number', 0 ], [ 'target', <> 返回值为需要设置<code>Affix</code> 监听其滚动事件的元素的一个函数。 </>, '() => HTMLElement', '() => window' ], [ 'onChange', <> 固定状态触发时的回调函数,参数为固定状态的<code>boolean</code>值 </>, '(isAffixed) => void', '-' ], ['children', '需要触发固定的组件', 'React.ReactNode', '-'] ]} /> </section> </div> ); }; export default LayoutExample;
yyzclyang/algae-ui
components/modal/confirm.tsx
<filename>components/modal/confirm.tsx import React from 'react'; import ReactDOM from 'react-dom'; import Button from '../button'; import Icon from '../icon'; import { classNames } from '../utils'; interface ConfirmDialogProps { visible: boolean; className?: string; iconType?: string; iconStyle?: React.CSSProperties; title?: string; onClose: React.MouseEventHandler; closeOnClickMask?: boolean; buttons?: React.ReactElement[]; children: React.ReactNode; } const ConfirmDialog: React.FunctionComponent<ConfirmDialogProps> = ( props: ConfirmDialogProps ) => { const { visible, iconType, iconStyle, title, className, buttons, children } = props; const dialogDom = visible ? ( <React.Fragment> <div className="algae-ui-confirm-dialog-mask" /> <div className={classNames('algae-ui-confirm-dialog', className)}> <main> {iconType && ( <div className="icon"> <Icon type={iconType} style={iconStyle} /> </div> )} <div className="confirm-dialog-message"> <div className="title">{title}</div> <div className="content">{children}</div> </div> </main> <footer>{buttons}</footer> </div> </React.Fragment> ) : null; return ReactDOM.createPortal(dialogDom, document.body); }; ConfirmDialog.displayName = 'Dialog'; ConfirmDialog.defaultProps = { visible: false, title: '温馨提示', closeOnClickMask: false, children: null }; interface ConfirmButtonProps { buttonType?: 'default' | 'primary' | 'success' | 'danger'; ghost?: boolean; onClick: React.MouseEventHandler; content: string; } export interface ConfirmProps { type?: string; title?: string; content: React.ReactNode; iconType?: string; iconStyle?: React.CSSProperties; okButton?: ConfirmButtonProps; cancelButton?: ConfirmButtonProps; } export interface UpdateProps { title: string; content: React.ReactNode; } const confirm = ({ type, title, content, iconType, iconStyle, okButton, cancelButton }: ConfirmProps) => { const onClose = () => { ReactDOM.render( React.cloneElement(confirmCom, { visible: false }), mountNode ); ReactDOM.unmountComponentAtNode(mountNode); mountNode.remove(); }; const update = ({ title, content }: UpdateProps) => { ReactDOM.render( React.cloneElement(confirmCom, { title }, content), mountNode ); }; const onOkClick: React.MouseEventHandler = ( e: React.MouseEvent<HTMLButtonElement, MouseEvent> ) => { onClose(); okButton && okButton.onClick(e); }; const onCancelClick: React.MouseEventHandler = ( e: React.MouseEvent<HTMLButtonElement, MouseEvent> ) => { onClose(); cancelButton && cancelButton.onClick(e); }; const OkButton: React.ReactElement[] = !!okButton ? [ <Button key="btn1" buttonType={okButton.buttonType} ghost={okButton.ghost} onClick={onOkClick} > {okButton.content} </Button> ] : []; const CancelButton: React.ReactElement[] = !!cancelButton ? [ <Button key="btn2" buttonType={cancelButton.buttonType} ghost={cancelButton.ghost} onClick={onCancelClick} > {cancelButton.content} </Button> ] : []; const buttons = CancelButton.concat(OkButton); const confirmCom = ( <ConfirmDialog visible className={type} title={title} iconType={iconType} iconStyle={iconStyle} onClose={onClose} buttons={buttons} > {content} </ConfirmDialog> ); const mountNode = document.createElement('div'); document.body.append(mountNode); ReactDOM.render(confirmCom, mountNode); return { destroy: onClose, update }; }; export default confirm;
yyzclyang/algae-ui
site/componentExample/RadioExample/radio.codeDemo2.tsx
import React, { useState } from 'react'; import { Radio, Button } from 'algae-ui'; export default () => { const [disabled, setDisabled] = useState<boolean>(true); return ( <div className="radio-example-list"> <Radio disabled={disabled}>Radio Disabled</Radio> <br /> <Radio checked disabled={disabled}> Radio Disabled </Radio> <br /> <Button buttonType="primary" onClick={() => { setDisabled(!disabled); }} > Toggle disabled </Button> </div> ); };
yyzclyang/algae-ui
components/rate/rate.tsx
<filename>components/rate/rate.tsx import React, { useState } from 'react'; import Star from './star'; import { classNames, scopedClassMaker, useControlState } from '../utils'; const sc = scopedClassMaker('algae-ui-rate'); interface RateProps { className?: string; style?: React.CSSProperties; count?: number; value?: number; defaultValue?: number; disabled?: boolean; tips?: string[]; allowClear?: boolean; allowHalf?: boolean; onChange?: (value: number) => void; onHoverChange?: (value: number) => void; } const Rate: React.FunctionComponent<RateProps> = (props: RateProps) => { const { className, style, count, value, defaultValue, disabled, tips, allowClear, allowHalf, onChange, onHoverChange } = props; const [rateValue, setRateValue] = useControlState<number>( defaultValue!, value ); const [hoverRateValue, setHoverRateValue] = useState<number>(0); const renderStar = (count: number, rateStarsValue: number) => { const starMouseEnterGenerator = ( index: number ): React.MouseEventHandler<SVGSVGElement> => ( e: React.MouseEvent<SVGSVGElement> ) => { if (disabled) { return; } const currentStarValue = !allowHalf ? 1 : e.nativeEvent.offsetX / e.currentTarget.clientWidth > 0.5 ? 1 : 0.5; const newRateValue = index + currentStarValue; if (hoverRateValue !== newRateValue) { setHoverRateValue(newRateValue); onHoverChange && onHoverChange(hoverRateValue); } }; const starMouseMoveGenerator = ( index: number ): React.MouseEventHandler<SVGSVGElement> => ( e: React.MouseEvent<SVGSVGElement> ) => { if (disabled) { return; } const currentStarValue = !allowHalf ? 1 : e.nativeEvent.offsetX / e.currentTarget.clientWidth > 0.5 ? 1 : 0.5; const newRateValue = index + currentStarValue; if (hoverRateValue !== newRateValue) { setHoverRateValue(newRateValue); onHoverChange && onHoverChange(hoverRateValue); } }; const starOnClickGenerator = ( index: number ): React.MouseEventHandler<SVGSVGElement> => ( e: React.MouseEvent<SVGSVGElement> ) => { if (disabled) { return; } const currentStarValue = !allowHalf ? 1 : e.nativeEvent.offsetX / e.currentTarget.clientWidth > 0.5 ? 1 : 0.5; const newRateValue = allowClear && index + currentStarValue === rateValue ? 0 : index + currentStarValue; setRateValue(newRateValue); onChange && onChange(newRateValue); }; return Array.from({ length: count }).map((v, i) => { const currentStarValue = (hoverRateValue ? hoverRateValue : rateStarsValue) - i; const type = currentStarValue > 0 ? allowHalf ? currentStarValue > 0.5 ? 'full' : 'half' : 'full' : 'none'; const starTips = tips ? tips[Math.ceil(i)] : undefined; return ( <span key={i} data-tips={starTips ? starTips : undefined} className={classNames( sc('star-wrapper'), starTips ? sc('star-wrapper-tips') : '' )} > <Star type={type} onMouseEnter={starMouseEnterGenerator(i)} onMouseMove={starMouseMoveGenerator(i)} onClick={starOnClickGenerator(i)} /> </span> ); }); }; const rateMouseLeave: React.MouseEventHandler<HTMLDivElement> = () => { if (disabled) { return; } setHoverRateValue(0); onHoverChange && onHoverChange(0); }; return ( <div className={classNames(sc(), disabled ? sc('disabled') : '', className)} style={style} onMouseLeave={rateMouseLeave} > {renderStar(count!, rateValue)} </div> ); }; Rate.displayName = 'Rate'; Rate.defaultProps = { count: 5, defaultValue: 0, disabled: false, allowClear: false, allowHalf: false }; export default Rate;
yyzclyang/algae-ui
components/layout/side.tsx
<reponame>yyzclyang/algae-ui import React from 'react'; import { classNames, scopedClassMaker } from '../utils'; const sc = scopedClassMaker('algae-ui-layout'); interface SideProps extends React.HtmlHTMLAttributes<HTMLElement> {} const Side: React.FunctionComponent<SideProps> = (props: SideProps) => { const { className, style, children, ...rest } = props; return ( <div className={classNames(sc('side'), className)} style={style} {...rest}> {children} </div> ); }; export default Side;
yyzclyang/algae-ui
components/progress/normalProgress.tsx
import React from 'react'; import Icon from '../icon'; import { classNames, scopedClassMaker } from '../utils'; const sc = scopedClassMaker('algae-ui-progress'); interface NormalProgressProps { backgroundColor?: string; strokeColor?: string; strokeLinecap?: 'round' | 'square'; percent: number; value?: string; showInfo?: boolean; status?: 'normal' | 'success' | 'fail'; } const NormalProgress: React.FunctionComponent<NormalProgressProps> = ( props: NormalProgressProps ) => { const { backgroundColor, strokeColor, strokeLinecap, percent, value, showInfo, status } = props; return ( <div className={classNames(sc('normal'))}> <div className={classNames(sc('rail'))} style={{ background: backgroundColor }} > <div className={classNames(sc())} style={{ background: strokeColor, width: `${percent}%`, borderRadius: strokeLinecap === 'round' ? '4px' : '0' }} /> </div> {showInfo && (status === 'normal' ? ( <span className={classNames(sc('text'), sc('content'))}> {value !== undefined ? value : `${Math.floor(percent)}%`} </span> ) : status === 'success' ? ( <span className={classNames(sc('icon'), sc('content'))}> <Icon type="check-circle" style={{ background: '#52c41a' }} /> </span> ) : ( <span className={classNames(sc('icon'), sc('content'))}> <Icon type="close-circle" style={{ background: '#f5222d' }} /> </span> ))} </div> ); }; NormalProgress.displayName = 'NormalProgress'; NormalProgress.defaultProps = { backgroundColor: '#E5E5E5', strokeColor: '#506DFE' }; export default NormalProgress;
yyzclyang/algae-ui
site/componentExample/CheckboxExample/checkbox.codeDemo2.tsx
import React from 'react'; import { Checkbox } from 'algae-ui'; export default () => { return ( <div className="checkbox-example-list"> <Checkbox disabled>Checkbox Disabled</Checkbox> <br /> <br /> <Checkbox checked disabled> Checkbox Checked Disabled </Checkbox> <br /> <br /> <Checkbox indeterminate disabled> Checkbox Indeterminate Disabled </Checkbox> </div> ); };
yyzclyang/algae-ui
site/componentExample/AvatarExample/avatar.codeDemo2.tsx
<gh_stars>1-10 import React from 'react'; import { Avatar } from 'algae-ui'; export default () => { return ( <div className="avatar-list"> <Avatar /> <Avatar>User</Avatar> <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" /> <Avatar style={{ color: 'red', background: '#FADFC9' }}>U</Avatar> <Avatar style={{ background: '#FADFC9' }} /> </div> ); };
yyzclyang/algae-ui
components/switch/style/index.ts
// style dependencies import '../../icon/style'; import './switch.scss';
yyzclyang/algae-ui
components/icon/icon.tsx
import React from 'react'; import { classNames } from '../utils'; import importSvg from './importSvg'; interface SvgProps extends React.SVGAttributes<SVGElement> { type?: string; component?: React.ReactElement; style?: React.CSSProperties; rotate?: number; } const SvgIcon: React.FunctionComponent<SvgProps> = (props: SvgProps) => { const { className, type, component, style, rotate, ...restProps } = props; const rotateStyle = rotate ? { transform: `rotate(${rotate}deg)` } : {}; return !!component ? ( React.cloneElement(component, { className: classNames('algae-ui-icon', className), style: { ...style, ...rotateStyle }, ...restProps }) ) : ( <svg className={classNames('algae-ui-icon', className)} style={{ ...style, ...rotateStyle }} {...restProps} > <use xlinkHref={`#${type}`} /> </svg> ); }; SvgIcon.displayName = 'SvgIcon'; interface IconProps extends SvgProps {} interface CreateFromIconfontCNProps { scriptUrl: string; } class Icon extends React.Component<IconProps> { constructor(props: IconProps) { super(props); importSvg(); } static displayName = 'Icon'; static createFromIconfontCN: ( props: CreateFromIconfontCNProps ) => React.FunctionComponent<SvgProps>; render() { return <SvgIcon {...this.props} />; } } Icon.createFromIconfontCN = ({ scriptUrl }) => { if (document.getElementById(scriptUrl)) { return SvgIcon; } const script = document.createElement('script'); script.id = scriptUrl; script.type = 'text/javascript'; script.src = scriptUrl; document.body.appendChild(script); return SvgIcon; }; export default Icon;
yyzclyang/algae-ui
site/componentExample/FormExample/form.codeDemo2.tsx
import React, { useState } from 'react'; import { Button, Form, FormValue, Field } from 'algae-ui'; export default () => { const [formData, setFormData] = useState<FormValue>({ username: '', password: '' }); const [fields] = useState<Field[]>([ { type: 'username', label: '用户名', input: { type: 'text' }, rules: [ { type: 'required', match: true, message: '不能为空' }, { type: 'minLength', match: 6, message: '不能少于 6 个字' } ] }, { type: 'password', label: '密码', input: { type: 'password' }, rules: [ { type: 'required', match: true, messageType: 'warning', message: '不能为空' }, { type: 'minLength', match: 6, messageType: 'warning', message: '不能少于 6 个字' } ] } ]); const onSubmit = () => { console.log('formData', formData); }; const onChange = (newValue: FormValue) => { setFormData(newValue); }; return ( <div className="form-example-list"> <Form value={formData} fields={fields} buttons={ <Button full type="submit" buttonType="primary"> 提交 </Button> } onSubmit={onSubmit} onChange={onChange} /> </div> ); };
yyzclyang/algae-ui
site/componentExample/RateExample/rate.codeDemo3.tsx
<gh_stars>1-10 import React, { useState } from 'react'; import { Rate } from 'algae-ui'; export default () => { const [value, setValue] = useState<number>(2); const tips = ['terrible', 'bad', 'normal', 'good', 'wonderful']; return ( <div className="rate-example-list"> <div className="rate-example"> <Rate value={value} allowHalf onChange={(value) => { setValue(value); }} tips={tips} /> <span className="tips">{tips[Math.ceil(value) - 1]}</span> </div> </div> ); };
yyzclyang/algae-ui
site/pages/index.ts
<reponame>yyzclyang/algae-ui export { default as GetStart } from './GetStart'; export { default as Introduction } from './Introduction';
yyzclyang/algae-ui
components/icon/importIcons.ts
try { ((requireContext) => requireContext.keys().forEach(requireContext))( require.context('./icons/', true, /\.svg$/) ); } catch (error) {}
yyzclyang/algae-ui
site/componentExample/CommonDispalyComponents/codeDemo/customTheme.ts
<filename>site/componentExample/CommonDispalyComponents/codeDemo/customTheme.ts // https://github.com/voronianski/oceanic-next-color-scheme interface PrismThemeEntry { color?: string; backgroundColor?: string; fontStyle?: 'normal' | 'italic'; fontWeight?: | 'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'; textDecorationLine?: | 'none' | 'underline' | 'line-through' | 'underline line-through'; opacity?: number; [styleKey: string]: string | number | void; } type Language = | 'markup' | 'bash' | 'clike' | 'c' | 'cpp' | 'css' | 'javascript' | 'jsx' | 'coffeescript' | 'actionscript' | 'css-extr' | 'diff' | 'git' | 'go' | 'graphql' | 'handlebars' | 'json' | 'less' | 'makefile' | 'markdown' | 'objectivec' | 'ocaml' | 'python' | 'reason' | 'sass' | 'scss' | 'sql' | 'stylus' | 'typescript' | 'wasm' | 'yaml'; interface PrismTheme { plain: PrismThemeEntry; styles: Array<{ types: string[]; style: PrismThemeEntry; languages?: Language[]; }>; } const colors = { char: '#D8DEE9', comment: '#999999', keyword: '#008dff', primitive: '#5a9bcf', string: '#0b8235', variable: '#d7deea', boolean: '#ff8b50', punctuation: '#999999', tag: '#f81d22', function: '#f81d22', className: '#f81d22', method: '#6699CC', operator: 'rgb(11, 130, 53)' }; const theme: PrismTheme = { plain: { backgroundColor: 'transparent', color: 'rgba(0, 0, 0, 0.85)' }, styles: [ { types: ['attr-name'], style: { color: colors.keyword } }, { types: ['attr-value'], style: { color: colors.string } }, { types: ['comment', 'block-comment', 'prolog', 'doctype', 'cdata'], style: { color: colors.comment } }, { types: [ 'property', 'number', 'function-name', 'constant', 'symbol', 'deleted' ], style: { color: colors.primitive } }, { types: ['boolean'], style: { color: colors.boolean } }, { types: ['tag'], style: { color: colors.tag } }, { types: ['string'], style: { color: colors.string } }, { types: ['punctuation'], style: { color: colors.punctuation } }, { types: ['selector', 'char', 'builtin', 'inserted'], style: { color: colors.char } }, { types: ['function'], style: { color: colors.function } }, { types: ['operator', 'entity', 'url', 'variable'], style: { color: colors.operator } }, { types: ['keyword'], style: { color: colors.keyword } }, { types: ['at-rule', 'class-name'], style: { color: colors.className } }, { types: ['important'], style: { fontWeight: '400' } }, { types: ['bold'], style: { fontWeight: 'bold' } }, { types: ['italic'], style: { fontStyle: 'italic' } }, { types: ['namespace'], style: { opacity: 0.7 } } ] }; export default theme;
yyzclyang/algae-ui
site/componentExample/MessageExample/message.codeDemo3.tsx
<gh_stars>1-10 import React from 'react'; import { Button, message } from 'algae-ui'; export default () => { return ( <div className="message-example-list"> <Button onClick={() => { message.success( 'This is a prompt message for success, and it will disappear in 10 seconds', 10000 ); }} > Customized display duration </Button> </div> ); };
yyzclyang/algae-ui
components/radio/style/inedx.ts
<reponame>yyzclyang/algae-ui import './radio.scss';
yyzclyang/algae-ui
site/componentExample/RateExample/rate.codeDemo1.tsx
<reponame>yyzclyang/algae-ui import React from 'react'; import { Rate } from 'algae-ui'; export default () => { return ( <div className="rate-example-list"> <Rate /> </div> ); };
yyzclyang/algae-ui
components/badge/badge.tsx
import React from 'react'; import { classNames, scopedClassMaker } from '../utils'; const sc = scopedClassMaker('algae-ui-badge'); interface BadgeProps { count?: number | React.ReactElement; showZero?: boolean; overflowCount?: number; dot?: boolean; style?: React.CSSProperties; children?: React.ReactNode; } const Badge: React.FunctionComponent<BadgeProps> = (props: BadgeProps) => { const { count, showZero, overflowCount, dot, style, children } = props; return ( <span className={classNames(sc('wrapper'))}> {children} {(dot || !!count || (count === 0 && showZero)) && ( <span className={classNames( sc(), children !== undefined ? sc('has-children') : '', dot ? sc('dot') : '' )} style={{ ...{ background: React.isValidElement(count) ? '#FFFFFF' : '' }, ...style }} > {React.isValidElement(count) ? ( count ) : ( <span className={classNames(sc('content'))}> {dot ? null : overflowCount !== undefined && count !== undefined && count > overflowCount ? overflowCount + '+' : count} </span> )} </span> )} </span> ); }; Badge.displayName = 'Badge'; Badge.defaultProps = { showZero: false, overflowCount: 99 }; export default Badge;
yyzclyang/algae-ui
site/componentExample/IconExample/icon.example.tsx
<reponame>yyzclyang/algae-ui import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import IconDisplay, { IconData } from './iconDisplay'; import './icon.example.scss'; import CodeDemo1 from './icon.codeDemo1'; const code1 = require('!!raw-loader!./icon.codeDemo1.tsx'); import CodeDemo2 from './icon.codeDemo2'; const code2 = require('!!raw-loader!./icon.codeDemo2.tsx'); import CodeDemo3 from './icon.codeDemo3'; const code3 = require('!!raw-loader!./icon.codeDemo3.tsx'); const IconExample: React.FunctionComponent = () => { const iconDisplayData: IconData[] = [ { title: '方向性图标', data: [ 'top', 'down', 'left', 'right', 'arrow-top', 'arrow-down', 'arrow-left', 'arrow-right' ] }, { title: '提示建议性图标', data: [ 'question', 'question-circle', 'info', 'info-circle', 'close', 'close-circle', 'check', 'check-circle', 'warning', 'warning-circle' ] }, { title: '编辑类图标', data: ['edit', 'form', 'copy', 'delete'] }, { title: '品牌和标识', data: [ 'android', 'apple', 'windows', 'facebook', 'github', 'gitlab', 'google', 'qq', 'alipay', 'wechat' ] }, { title: '网站通用图标', data: [ 'alert', 'api', 'bell', 'calendar', 'camera', 'cloud', 'terminal', 'code-show', 'code-hidden', 'gift', 'like', 'lock', 'setting', 'tag' ] } ]; return ( <div className="icon-example-page"> <section> <h1>Icon 图标</h1> <p>语义化的矢量图形。</p> </section> <section> <h2>图标列表</h2> <div> <IconDisplay iconDisplayData={iconDisplayData} /> </div> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基本用法" content={ <p> 使用 <code>{`<Icon />`}</code>标签声明组件,指定图标对应的 <code>type</code>属性。可以通过<code>rotate</code> 属性来设置图标的旋转角度,也可以传入<code>style</code> 来控制图标的样式。 </p> } code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="使用 iconfont.cn" content={ <p> 对于使用 <a href="https://www.iconfont.cn/" target="_Blank" rel="noopener noreferrer" > iconfont.cn </a> 的用户,通过设置<code>createFromIconfontCN</code> 方法参数对象中的<code>scriptUrl </code>字段, 即可轻松地使用已有项目中的图标。 </p> } code={code3.default} > <CodeDemo3 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="自定义图标" content={ <p> 使用<code>component</code> 属性可以传入一个自定义的组件进行渲染,满足个性化的需求。 </p> } code={code2.default} > <CodeDemo2 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <Api data={[ ['type', '图标类型。', 'string', '-'], [ 'style', <> 设置图标的样式,例如<code>fill</code>和<code>color</code>。 </>, 'CSSProperties', '-' ], ['rotate', '图标旋转角度。', 'number', '-'] ]} /> <p> 支持原生<code>svg</code>的其他所有属性。 </p> </section> </div> ); }; export default IconExample;
yyzclyang/algae-ui
site/componentExample/BadgeExample/badge.codeDemo4.tsx
import React from 'react'; import { Badge, Avatar, Icon } from 'algae-ui'; export default () => { return ( <div className="badge-list"> <Badge count={5} dot> <Avatar shape="square" /> </Badge> <Badge dot> <Icon type="bell" /> </Badge> <Badge dot style={{ background: '#56BF14' }}> something </Badge> </div> ); };
yyzclyang/algae-ui
components/tree/treeItem.tsx
import React, { useState, useRef } from 'react'; import Icon from '../icon'; import Checkbox from '../checkbox'; import { classNames, scopedClassMaker, useToggle, useUpdate } from '../utils'; const sc = scopedClassMaker('algae-ui-tree-item'); /** * 收集后代所有元素的值 * @param sourceData 当前元素的 sourceData * @param excludesDisabled 是否排除不可选择元素的值 */ const collectDescendantValues = ( sourceData: TreeItemSourceData, excludesDisabled: boolean = false ): string[] => { return ( sourceData.children?.reduce((result: string[], childSourceData) => { return result.concat( excludesDisabled && childSourceData.disabledCheckbox ? [] : childSourceData.value, childSourceData.children ? collectDescendantValues(childSourceData, excludesDisabled) : [] ); }, []) ?? [] ); }; /** * 计算已选中的值与后代元素的值的交集,判断后代的选择情况。全部选中?部分选中?全都没选中? * @param selectedValues 已选中的值 * @param descendantValues 后代元素的值 */ const calculatorCommonValues = ( selectedValues: string[], descendantValues: string[] ): string[] => { return descendantValues.filter((descendantValue) => selectedValues.includes(descendantValue) ); }; type CheckedStatus = 'checked' | 'indeterminate' | 'none'; /** * 根据后代元素的选择情况来判断当前元素的状态子影响父 * @param selectedValues 已选中的值 * @param descendantValues 后代元素的值 */ const judgeCheckedStatus = ( selectedValues: string[], descendantValues: string[] ): CheckedStatus => { const commonValuesLength = calculatorCommonValues( selectedValues, descendantValues ).length; return commonValuesLength > 0 ? commonValuesLength < descendantValues.length ? 'indeterminate' : 'checked' : 'none'; }; export interface TreeItemSourceData { text: string; value: string; expanded?: boolean; icon?: string | React.ReactElement; disabledCheckbox?: boolean; children?: TreeItemSourceData[]; } interface TreeItemProps { className?: string; sourceData: TreeItemSourceData; level: number; autoCheck?: boolean; switcherIcons: [string | React.ReactElement, string | React.ReactElement]; checkable: boolean; checked: boolean; selectedValues: string[]; onTreeItemSelect: (selectedValues: string[]) => void; } const TreeItem: React.FC<TreeItemProps> = (props: TreeItemProps) => { const { className, sourceData, sourceData: { value, text, expanded: initialExpand = true, icon, disabledCheckbox }, level, autoCheck, switcherIcons, checkable, checked, selectedValues } = props; const [isIndeterminate, setIsIndeterminate] = useState<boolean>(false); const [expanded, toggleExpanded] = useToggle(initialExpand); const expandSwitcherOnClick: React.MouseEventHandler<HTMLInputElement> = () => { toggleExpanded(); }; const onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => { const descendantValues = autoCheck ? collectDescendantValues(sourceData, true) : []; const newSelectedValues = e.target.checked ? Array.from(new Set([...selectedValues, value, ...descendantValues])) : selectedValues.filter( (selectedValue) => selectedValue !== value && !descendantValues.includes(selectedValue) ); setIsIndeterminate(false); props.onTreeItemSelect(newSelectedValues); }; const onTreeItemSelect = (selectedValues: string[]) => { if (!autoCheck) { props.onTreeItemSelect(selectedValues); return; } // 自动选取的状态下根据后代的选中情况来影响自身的选中情况 const descendantValues = collectDescendantValues(sourceData); const checkedStatus = judgeCheckedStatus(selectedValues, descendantValues); props.onTreeItemSelect( checkedStatus === 'checked' ? [...selectedValues, ...(disabledCheckbox ? [] : [value])] : selectedValues.filter((selectedValue) => selectedValue !== value) ); setIsIndeterminate(!disabledCheckbox && checkedStatus === 'indeterminate'); }; const childrenRef = useRef<HTMLDivElement>(null); useUpdate(() => { if (!childrenRef.current) { return; } const afterExpand = () => { if (!childrenRef.current) { return; } childrenRef.current.style.height = 'auto'; childrenRef.current.removeEventListener('transitionend', afterExpand); }; if (expanded) { childrenRef.current.style.height = 'auto'; const { height } = childrenRef.current.getBoundingClientRect(); childrenRef.current.style.height = '0px'; childrenRef.current.getBoundingClientRect(); childrenRef.current.style.height = height + 'px'; childrenRef.current.addEventListener('transitionend', afterExpand); } else { childrenRef.current.style.height = 'auto'; const { height } = childrenRef.current.getBoundingClientRect(); childrenRef.current.style.height = height + 'px'; childrenRef.current.getBoundingClientRect(); childrenRef.current.style.height = '0px'; } return () => { childrenRef.current?.removeEventListener('transitionend', afterExpand); }; }, [expanded]); const renderSwitcherIcon = ( icon: string | React.ReactElement ): React.ReactElement => { return typeof icon === 'string' ? ( <Icon className={classNames(sc('switch'))} type={icon} /> ) : ( icon ); }; return ( <div className={classNames(sc(), className)}> <div className={sc('content')}> {sourceData.children ? ( <span className={classNames(sc('switcher'))} onClick={expandSwitcherOnClick} > {expanded ? renderSwitcherIcon(switcherIcons[0]) : renderSwitcherIcon(switcherIcons[1])} </span> ) : ( <span className={sc('switcher-empty')} /> )} {checkable && ( <span className={sc('checker')}> <Checkbox className={sc('check-box')} checked={checked} disabled={disabledCheckbox} onChange={onChange} indeterminate={isIndeterminate} /> </span> )} {typeof icon === 'string' ? <Icon type={icon} /> : icon} <span className={sc('text')}>{text}</span> </div> {sourceData.children && ( <div ref={childrenRef} className={classNames(sc('children'), expanded ? 'open' : 'close')} > {sourceData.children.map((childrenTreeData) => ( <TreeItem key={childrenTreeData.value} sourceData={childrenTreeData} level={level + 1} autoCheck={autoCheck} switcherIcons={switcherIcons} checkable={checkable} checked={selectedValues!.includes(childrenTreeData.value)} selectedValues={selectedValues} onTreeItemSelect={onTreeItemSelect} /> ))} </div> )} </div> ); }; TreeItem.displayName = 'TreeItem'; TreeItem.defaultProps = { checkable: false, checked: false }; export default TreeItem;
yyzclyang/algae-ui
site/componentExample/InputExample/input.codeDemo2.tsx
import React, { useState } from 'react'; import { Input } from 'algae-ui'; export default () => { const [value, setValue] = useState<string>(''); return ( <div className="input-example-list"> <Input placeholder="input with clear icon" allowClear value={value} onChange={(e) => { setValue(e.currentTarget.value); }} /> </div> ); };
yyzclyang/algae-ui
components/layout/footer.tsx
<filename>components/layout/footer.tsx import React from 'react'; import { classNames, scopedClassMaker } from '../utils'; const sc = scopedClassMaker('algae-ui-layout'); interface FooterProps extends React.HtmlHTMLAttributes<HTMLElement> {} const Footer: React.FunctionComponent<FooterProps> = (props: FooterProps) => { const { className, style, children, ...rest } = props; return ( <div className={classNames(sc('footer'), className)} style={style} {...rest} > {children} </div> ); }; export default Footer;
yyzclyang/algae-ui
components/radio/radio.tsx
<gh_stars>1-10 import React, { useState, useEffect } from 'react'; import { classNames } from '../utils'; interface RadioProps extends React.InputHTMLAttributes<HTMLInputElement> { className?: string; value?: string; defaultChecked?: boolean; checked?: boolean; disabled?: boolean; onChange?: React.ChangeEventHandler<HTMLInputElement>; children?: React.ReactNode; } const Radio: React.FunctionComponent<RadioProps> = (props: RadioProps) => { const { className, checked, defaultChecked, disabled, onChange, children, style, ...restProps } = props; const [radioChecked, setRadioChecked] = useState<boolean>( checked !== undefined ? checked : defaultChecked! ); useEffect(() => { if (checked !== undefined) { setRadioChecked(checked); } }, [checked]); const radioOnChange: React.ChangeEventHandler = ( e: React.ChangeEvent<HTMLInputElement> ) => { if (disabled) { return; } onChange && onChange(e); if (checked === undefined) { setRadioChecked(e.target.checked); } }; return ( <label className={classNames( 'algae-ui-radio-wrapper', radioChecked ? 'algae-ui-radio-checked' : '', disabled ? 'algae-ui-radio-disabled' : '', className )} style={style} > <span className={classNames('algae-ui-radio')}> <input className="algae-ui-radio-input" type="radio" checked={radioChecked} disabled={disabled} onChange={radioOnChange} {...restProps} /> <span className="algae-ui-radio-inner" /> </span> {children ? ( <span className="algae-ui-radio-text">{children}</span> ) : null} </label> ); }; Radio.displayName = 'Radio'; Radio.defaultProps = { defaultChecked: false, disabled: false }; export default Radio;
yyzclyang/algae-ui
site/componentExample/FormExample/index.ts
<filename>site/componentExample/FormExample/index.ts export { default } from './form.example';
yyzclyang/algae-ui
components/badge/style/index.ts
<reponame>yyzclyang/algae-ui import './badge.scss';
yyzclyang/algae-ui
site/componentExample/AvatarExample/avatar.codeDemo1.tsx
<filename>site/componentExample/AvatarExample/avatar.codeDemo1.tsx import React from 'react'; import { Avatar } from 'algae-ui'; export default () => { return ( <div className="avatar-list"> <div> <Avatar size={48} /> <Avatar /> </div> <div> <Avatar size={48} shape="square" /> <Avatar shape="square" /> </div> </div> ); };
yyzclyang/algae-ui
components/tree/style/index.ts
// style dependencies import '../../icon/style'; import '../../checkbox/style'; import './tree.scss'; import './treeItem.scss';
yyzclyang/algae-ui
site/componentExample/InputExample/input.example.tsx
import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './input.example.scss'; import CodeDemo1 from './input.codeDemo1'; const code1 = require('!!raw-loader!./input.codeDemo1.tsx'); import CodeDemo2 from './input.codeDemo2'; const code2 = require('!!raw-loader!./input.codeDemo2.tsx'); import CodeDemo3 from './input.codeDemo3'; const code3 = require('!!raw-loader!./input.codeDemo3.tsx'); import CodeDemo4 from './input.codeDemo4'; const code4 = require('!!raw-loader!./input.codeDemo4.tsx'); const InputExample: React.FunctionComponent = () => { return ( <div className="input-example-page"> <section> <h1>Input 输入框</h1> <p>通过鼠标或键盘输入内容,是最基础的表单域的包装。</p> </section> <section> <h2>何时使用</h2> <p>需要用户输入表单内容时。</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础使用" content={<p>第一个输入框</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="搜索框" content={<p>带有搜索按钮的输入框。</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="带清除图标" content={<p>带清除图标的输入框。</p>} code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="文本域" content={<p>用于多行文本输入。</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <h3>Input</h3> <p> <code>Input</code>为一个单独的输入框。拓展自<code>input</code> ,除了以下<code>API</code>,还支持<code>input</code>的所有 <code>API</code>。 </p> <Api data={[ [ 'value', <> <code>Input</code>输入框的值。 </>, 'string', '-' ], [ 'onChange', <> <code>Input</code>输入时的回调。 </>, 'React.ChangeEventHandler', '-' ], ['allowClear', '是否附带清除按钮。', 'boolean', 'false'], [ 'clearFn', '点击清除按钮时的回调。', 'React.MouseEventHandler', '-' ], [ 'wrapperClassName', <> <code>Input</code>输入框包裹容器的<code>className</code> </>, 'string', '-' ], [ 'className', <> <code>Input</code>输入框的<code>className</code> </>, 'string', '-' ] ]} /> <h3>Search</h3> <p> <code>Search</code>为一个带有搜索按钮的输入框,是从<code>Input</code> 的基础上拓展来的,所以除了以下的<code>API</code>,还支持 <code>Input</code>所有的<code>API</code>。 </p> <Api data={[ [ 'searchButton', <> 搜索按钮的类型。值为<code>string</code>时为<code>primary</code> 按钮;值为<code>boolean</code>类型且为<code>true</code>时为 <code>icon</code>按钮。 </>, 'string | boolean', '-' ], [ 'onSearch', '点击搜索按钮时的回调。', '( inputValue ) => void', '-' ] ]} /> <h3>TextArea</h3> <p> <code>TextArea</code>为一个文本输入域。拓展自<code>textarea</code> ,所以除了以下<code>API</code>,还支持<code>textarea</code>的所有 <code>API</code>。 </p> <Api data={[ [ 'value', <> <code>TextArea</code>输入框的值。 </>, 'string', '-' ], [ 'onChange', <> <code>TextArea</code>输入时的回调。 </>, 'React.ChangeEventHandler', '-' ], [ 'defaultValue', <> <code>TextArea</code>的默认值。 </>, 'string', '-' ], [ 'cols', <> <code>TextArea</code>的列数。 </>, 'number', '32' ], [ 'rows', <> <code>TextArea</code>的行数。 </>, 'number', '4' ] ]} /> </section> </div> ); }; export default InputExample;
yyzclyang/algae-ui
site/componentExample/CheckboxExample/index.ts
<filename>site/componentExample/CheckboxExample/index.ts<gh_stars>1-10 export { default } from './checkbox.example';
yyzclyang/algae-ui
site/componentExample/StepsExample/steps.example.tsx
<filename>site/componentExample/StepsExample/steps.example.tsx import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './steps.example.scss'; import CodeDemo1 from './steps.codeDemo1'; const code1 = require('!!raw-loader!./steps.codeDemo1.tsx'); import CodeDemo2 from './steps.codeDemo2'; const code2 = require('!!raw-loader!./steps.codeDemo2.tsx'); import CodeDemo3 from './steps.codeDemo3'; const code3 = require('!!raw-loader!./steps.codeDemo3.tsx'); import CodeDemo4 from './steps.codeDemo4'; const code4 = require('!!raw-loader!./steps.codeDemo4.tsx'); import CodeDemo5 from './steps.codeDemo5'; const code5 = require('!!raw-loader!./steps.codeDemo5.tsx'); import CodeDemo6 from './steps.codeDemo6'; const code6 = require('!!raw-loader!./steps.codeDemo6.tsx'); const StepsExample: React.FunctionComponent = () => { return ( <div className="scroll-example-page"> <section> <h1>Steps 步骤条</h1> <p>引导用户按照流程完成任务的导航条</p> </section> <section> <h2>何时使用</h2> <p>当任务复杂或者存在先后关系时,将其分解成一系列步骤,从而简化任务</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础使用" content={<p>基础步骤条</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="带图标的步骤条" content={ <p> 通过设置<code>Step</code>的<code>icon</code> 属性,可以启用自定义图标 </p> } code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="步骤切换" content={<p>通常用来表示一个流程的处理</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> <CodeDemo title="错误的 Step" content={ <p> 使用<code>Step</code>的<code>status</code> 属性来制定当前步骤的状态 </p> } code={code4.default} > <CodeDemo4 /> </CodeDemo> <CodeDemo title="可点击的 Step" content={ <p> 通过点击<code>Step</code>来改变当前的步骤和状态 </p> } code={code5.default} > <CodeDemo5 /> </CodeDemo> <CodeDemo title="垂直的步骤条" content={ <p> 通过设置<code>direction</code>来变化步骤条的方向 </p> } code={code6.default} > <CodeDemo6 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <h3>Steps</h3> <Api data={[ ['className', '类名', 'string', '-'], ['current', '指定当前的步骤', 'number', '0'], [ 'status', '指定当前步骤的状态', 'waiting | process | success | fail', '-' ], [ 'direction', '制定步骤条的方向', 'horizontal | vertical', 'horizontal' ], [ 'onChange', '点击切换步骤时的回调', '(current: number) => void', '-' ] ]} /> <h3>Step</h3> <Api data={[ ['className', '类名', 'string', '-'], ['style', '样式', 'React.CSSProperties', '-'], ['title', '标题', 'string', '-'], ['subTitle', '子标题', 'string', '-'], ['description', '详情描述', 'string', '-'], ['status', '制定状态', 'waiting | process | success | fail', '-'], ['icon', '图标的类型', 'string | ReactNode', '-'], ['disabled', '禁用点击', 'boolean', '-'] ]} /> </section> </div> ); }; export default StepsExample;
yyzclyang/algae-ui
site/componentExample/CheckboxExample/checkbox.codeDemo3.tsx
import React, { useState } from 'react'; import { Checkbox, Button, ButtonGroup } from 'algae-ui'; export default () => { const [disabled, setDisabled] = useState<boolean>(false); const [checked, setChecked] = useState<boolean>(false); return ( <div className="checkbox-example-list"> <Checkbox disabled={disabled} checked={checked}> Checkbox Disabled </Checkbox> <br /> <br /> <ButtonGroup> <Button buttonType="primary" full onClick={() => { setDisabled(!disabled); }} > toggle disabled </Button> <Button buttonType="primary" full onClick={() => { setChecked(!checked); }} > toggle checked </Button> </ButtonGroup> </div> ); };
yyzclyang/algae-ui
components/steps/steps.tsx
<filename>components/steps/steps.tsx import React from 'react'; import { StatusTypes } from './step'; import { classNames, scopedClassMaker } from '../utils'; const sc = scopedClassMaker('algae-ui-steps'); interface StepsProps { className?: string; current?: number; status?: StatusTypes; direction?: 'horizontal' | 'vertical'; onChange?: (current: number) => void; children: React.ReactNode; } const Steps: React.FunctionComponent<StepsProps> = (props: StepsProps) => { const { className, current, status, direction, onChange, children } = props; return ( <div className={classNames(sc(), sc(direction), className)}> {React.Children.map(children, (child, index) => { return React.isValidElement(child) ? index < current! ? React.cloneElement(child, { status: 'success', icon: String(index + 1), disabled: !(onChange || child.props.onClick), ...child.props, onClick: (e: React.MouseEvent<HTMLDivElement>) => { child.props.onClick && child.props.onClick(e); onChange && onChange(index); } }) : index === current ? React.cloneElement(child, { status: status || 'process', icon: String(index + 1), disabled: !(onChange || child.props.onClick), ...child.props, onClick: (e: React.MouseEvent<HTMLDivElement>) => { child.props.onClick && child.props.onClick(e); onChange && onChange(index); }, className: `algae-ui-step-current${ child.props.className ? ` ${child.props.className}` : '' }` }) : React.cloneElement(child, { status: 'waiting', icon: String(index + 1), disabled: !(onChange || child.props.onClick), ...child.props, onClick: (e: React.MouseEvent<HTMLDivElement>) => { child.props.onClick && child.props.onClick(e); onChange && onChange(index); } }) : child; })} </div> ); }; Steps.displayName = 'Steps'; Steps.defaultProps = { current: 0, direction: 'horizontal' }; export default Steps;
yyzclyang/algae-ui
site/componentExample/ScrollExample/scroll.codeDemo1.tsx
<filename>site/componentExample/ScrollExample/scroll.codeDemo1.tsx<gh_stars>1-10 import React from 'react'; import { Scroll } from 'algae-ui'; export default () => { return ( <div className="scroll-example-list"> <Scroll className="scroll-example1" style={{ height: '300px' }}> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>6</p> <p>7</p> <p>8</p> <p>9</p> <p>10</p> <p>11</p> <p>12</p> <p>13</p> <p>14</p> <p>15</p> <p>16</p> <p>17</p> <p>18</p> <p>19</p> <p>20</p> </Scroll> </div> ); };
yyzclyang/algae-ui
site/componentExample/TreeExample/tree.example.tsx
import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './tree.example.scss'; import CodeDemo1 from './tree.codeDemo1'; const code1 = require('!!raw-loader!./tree.codeDemo1.tsx'); import CodeDemo2 from './tree.codeDemo2'; const code2 = require('!!raw-loader!./tree.codeDemo2.tsx'); import CodeDemo3 from './tree.codeDemo3'; const code3 = require('!!raw-loader!./tree.codeDemo3.tsx'); import CodeDemo4 from './tree.codeDemo4'; const code4 = require('!!raw-loader!./tree.codeDemo4.tsx'); import CodeDemo5 from './tree.codeDemo5'; const code5 = require('!!raw-loader!./tree.codeDemo5.tsx'); const TreeExample: React.FunctionComponent = () => { return ( <div className="tree-example-page"> <section> <h1>Tree 树形控件</h1> <p>多层次的结构列表</p> </section> <section> <h2>何时使用</h2> <p> 使用树控件可以完整展现数据之间的层级关系,并具有展开收起选择等交互功能 </p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础使用" content={<p>最基础的用法,展示勾选,禁用,展开等功能。</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="自动选取" content={<p>节点在选取的时候会影响父子节点。</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> <CodeDemo title="自定义展开折叠图标" content={<p>自定义展开折叠图标</p>} code={code5.default} > <CodeDemo5 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="受控使用" content={<p>受控用法</p>} code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="自定义 Icon" content={<p>节点可自定义 Icon</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <h3>Tree</h3> <Api data={[ [ 'autoCheck', '节点在选取的时候是否影响父子节点', 'boolean', 'false' ], ['checkable', '是否出现选取框', 'boolean', 'false'], [ 'switcherIcons', '自定义展开折叠的图标', '[string | ReactElement, string | ReactElement]', '默认三角图标' ], ['defaultValues', '默认勾选的值', 'Array<string>', '[]'], ['selectedValues', '勾选的值', 'Array<string>', '[]'], [ 'onSelect', '节点勾选时的回调', '(selectedValues: Array<string>) => void', '-' ], ['sourceData', '节点数据列表', 'Array<TreeItemSourceData>', '[]'] ]} /> <h3>TreeItemSourceData</h3> <Api data={[ ['text', '节点需要展示的文字', 'string', '-'], ['value', '节点代表的值', 'string', '-'], ['expanded', '节点是否展开', 'boolean', 'true'], ['icon', '节点的图标类型', 'string | ReactElement', '-'], ['disabledCheckbox', '节点是否禁止选取', 'boolean', 'false'], ['children', '节点子代的值', 'Array<TreeItemSourceData>', '[]'] ]} /> </section> </div> ); }; export default TreeExample;
yyzclyang/algae-ui
site/componentExample/ProgressExample/progress.example.tsx
import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './progress.example.scss'; import CodeDemo1 from './progress.codeDemo1'; const code1 = require('!!raw-loader!./progress.codeDemo1.tsx'); import CodeDemo2 from './progress.codeDemo2'; const code2 = require('!!raw-loader!./progress.codeDemo2.tsx'); import CodeDemo3 from './progress.codeDemo3'; const code3 = require('!!raw-loader!./progress.codeDemo3.tsx'); import CodeDemo4 from './progress.codeDemo4'; const code4 = require('!!raw-loader!./progress.codeDemo4.tsx'); import CodeDemo5 from './progress.codeDemo5'; const code5 = require('!!raw-loader!./progress.codeDemo5.tsx'); import CodeDemo6 from './progress.codeDemo6'; const code6 = require('!!raw-loader!./progress.codeDemo6.tsx'); import CodeDemo7 from './progress.codeDemo7'; const code7 = require('!!raw-loader!./progress.codeDemo7.tsx'); import CodeDemo8 from './progress.codeDemo8'; const code8 = require('!!raw-loader!./progress.codeDemo8.tsx'); const ProgressExample: React.FunctionComponent = () => { return ( <div className="progress-example-page"> <section> <h1>Progress 进度条</h1> <p>展示操作的当前进度。</p> </section> <section> <h2>何时使用</h2> <p>在操作需要较长时间才能完成时,为用户显示该操作的当前进度和状态。</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="进度条" content={<p>普通进度条。</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="仪表盘" content={<p>仪表盘样式的圆形进度条。</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> <CodeDemo title="自定义文案" content={ <p> 可自定义进度条的文案。(默认的文案只展示整数进度,需要小数或其他展示文案的请使用自定义文案。) </p> } code={code5.default} > <CodeDemo5 /> </CodeDemo> <CodeDemo title="自定义文案" content={ <p> 可自定义进度条的文案。(默认的文案只展示整数进度,需要小数或其他展示文案的请使用自定义文案。) </p> } code={code7.default} > <CodeDemo7 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="进度圈" content={<p>圆形的进度条。</p>} code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="动态化" content={<p>进度条变化动画。</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> <CodeDemo title="圆角/方角边缘" content={ <p> 通过设置<code>strokeLinecap=&quot;square|round&quot;</code> 可以调整进度条边缘的形状,默认为<code>round</code> </p> } code={code6.default} > <CodeDemo6 /> </CodeDemo> <CodeDemo title="自定义颜色" content={<p>可自定义背景色和进度条颜色</p>} code={code8.default} > <CodeDemo8 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <Api data={[ ['type', '进度条的类型', 'normal | circle | dashboard', 'normal'], ['percent', '进度条的百分比', 'number', '-'], ['showInfo', '是否展示进度条数值或图标', 'boolean', 'true'], ['value', '自定义展示的文案', 'string', '-'], ['status', '进度条的状态', 'normal | success | fail', 'normal'], ['strokeLinecap', '进度条的边缘样式', 'square | round', 'round'], ['backgroundColor', '进度条的背景色', 'string', '#E5E5E5'], [ 'strokeColor', <> 自定义进度条的颜色,优先级比<code>status</code>默认的颜色高 </>, 'string', '-' ] ]} /> </section> </div> ); }; export default ProgressExample;
yyzclyang/algae-ui
site/componentExample/LayoutExample/layout.codeDemo3.tsx
import React from 'react'; import { Layout, Header, Content, Footer, Side } from 'algae-ui'; export default () => { return ( <div className="layout-list"> <Layout> <Side>side</Side> <Layout> <Header>header</Header> <Content>content</Content> <Footer>footer</Footer> </Layout> </Layout> </div> ); };
yyzclyang/algae-ui
site/componentExample/RateExample/rate.example.tsx
import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './rate.example.scss'; import CodeDemo1 from './rate.codeDemo1'; const code1 = require('!!raw-loader!./rate.codeDemo1.tsx'); import CodeDemo2 from './rate.codeDemo2'; const code2 = require('!!raw-loader!./rate.codeDemo2.tsx'); import CodeDemo3 from './rate.codeDemo3'; const code3 = require('!!raw-loader!./rate.codeDemo3.tsx'); import CodeDemo4 from './rate.codeDemo4'; const code4 = require('!!raw-loader!./rate.codeDemo4.tsx'); import CodeDemo5 from './rate.codeDemo5'; const code5 = require('!!raw-loader!./rate.codeDemo5.tsx'); const RateExample: React.FunctionComponent = () => { return ( <div className="rate-example-page"> <section> <h1>Rate 评分</h1> <p>评分组件</p> </section> <section> <h2>何时使用</h2> <p>对评价进行展示</p> <p>对事物进行快速的评级操作</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础" content={<p>最基础的用法</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="文案展示" content={<p>hover 时展示文案</p>} code={code3.default} > <CodeDemo3 /> </CodeDemo> <CodeDemo title="清除" content={<p>允许重复点击时清除</p>} code={code5.default} > <CodeDemo5 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="半星" content={<p>支持选中半星</p>} code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="只读" content={<p>不可改变状态</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <Api data={[ ['className', '自定义类名', 'string', '-'], ['style', '自定义样式', 'React.CSSProperties', '-'], ['count', '星星的总数', 'number', '5'], ['value', '当前激活的星星个数,受控值', 'number', '-'], ['defaultValue', '默认激活的星星个数', 'number', '0'], ['disabled', '星星状态只读,不可改变', 'boolean', 'false'], ['tips', '自定义每个星星的提示信息', 'string[]', '-'], [ 'allowClear', '是否允许再次点击相同的星星时清除状态', 'boolean', 'false' ], ['allowHalf', '是否允许激活半颗星星', 'boolean', 'false'], ['onChange', '点击星星时的回调', '(value: number) => void', '-'], [ 'onHoverChange', '鼠标滑过星星时激活数量变化的回调', '(value: number) => void', '-' ] ]} /> </section> </div> ); }; export default RateExample;
yyzclyang/algae-ui
components/tree/index.ts
<reponame>yyzclyang/algae-ui<gh_stars>1-10 export { default } from './tree'; export { TreeItemSourceData } from './treeItem';
yyzclyang/algae-ui
site/componentExample/CommonDispalyComponents/api/api.tsx
import React from 'react'; import './api.scss'; type Api = Array<string | React.ReactNode>; interface ApiProps { data: Api[]; } const Api: React.FunctionComponent<ApiProps> = (props: ApiProps) => { const { data } = props; const parameterType = ['参数', '说明', '类型', '默认值']; return ( <table className="algae-ui-api"> <thead> <tr> {parameterType.map((item, index) => ( <td key={index}>{item}</td> ))} </tr> </thead> <tbody> {data.map((api, index) => ( <tr key={index}> {api.map((item, index) => ( <td key={index}>{item}</td> ))} </tr> ))} </tbody> </table> ); }; export default Api;
yyzclyang/algae-ui
site/componentExample/BadgeExample/index.ts
<filename>site/componentExample/BadgeExample/index.ts export { default } from './badge.example';
yyzclyang/algae-ui
site/componentExample/RadioExample/radio.codeDemo4.tsx
<gh_stars>1-10 import React, { useState } from 'react'; import { Radio, RadioGroup } from 'algae-ui'; export default () => { const [value, setValue] = useState<string>('1'); const radioStyle = { display: 'block' }; return ( <div className="radio-example-list"> <RadioGroup value={value} onChange={(e) => { setValue(e.currentTarget.value); console.log(e.currentTarget.value); }} > <Radio style={radioStyle} value="1"> Radio </Radio> <Radio style={radioStyle} value="2"> Radio </Radio> <Radio style={radioStyle} value="3"> Radio </Radio> </RadioGroup> </div> ); };
yyzclyang/algae-ui
site/componentExample/AvatarExample/avatar.example.tsx
<gh_stars>1-10 import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './avatar.example.scss'; import CodeDemo1 from './avatar.codeDemo1'; const code1 = require('!!raw-loader!./avatar.codeDemo1.tsx'); import CodeDemo2 from './avatar.codeDemo2'; const code2 = require('!!raw-loader!./avatar.codeDemo2.tsx'); const AvatarExample: React.FunctionComponent = () => { return ( <div className="avatar-example-page"> <section> <h1>Avatar 头像</h1> <p>用来代表用户或事物,支持图片、图标或者字符。</p> </section> <section> <h2>何时使用</h2> <p>展示用户头像信息。</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基本使用" content={<p>可设置形状和大小。</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="自定义类型" content={ <p> 可设置图片、字符串和<code>icon</code> ,字符串支持自定义颜色和背景色,<code>icon</code> 支持自定义背景色。 </p> } code={code2.default} > <CodeDemo2 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <Api data={[ ['icon', '设置头像图标的类型', 'string', 'avatar'], ['size', '设置头像的大小', 'number', '32'], ['shape', '设置头像的形状', 'circle | square', 'circle'], ['src', '设置头像的图片地址', 'string', '-'], ['alt', '设置图片的 alt', 'string', '-'], ['style', '设置头像的 style', 'React.CSSProperties', '-'], ['children', '设置文字类型图像', 'string', '-'] ]} /> </section> </div> ); }; export default AvatarExample;
yyzclyang/algae-ui
site/componentExample/PaginationExample/index.ts
export { default } from './pagination.example';
yyzclyang/algae-ui
site/componentExample/BadgeExample/badge.codeDemo2.tsx
import React from 'react'; import { Badge } from 'algae-ui'; export default () => { return ( <div className="badge-list"> <Badge count={5} /> <Badge count={0} showZero style={{ background: '#FFFFFF', color: '#8F8F8F', boxShadow: '0 0 0 1px #d9d9d9 inset' }} /> <Badge count={100} style={{ background: '#56BF14' }} /> </div> ); };
yyzclyang/algae-ui
site/componentExample/RateExample/rate.codeDemo5.tsx
import React from 'react'; import { Rate } from 'algae-ui'; export default () => { return ( <div className="rate-example-list"> <div className="rate-example"> <Rate allowClear defaultValue={3} /> <span className="tips">allowClear: true</span> </div> <br /> <div className="rate-example"> <Rate defaultValue={3} /> <span className="tips">allowClear: false</span> </div> </div> ); };
yyzclyang/algae-ui
site/componentExample/PaginationExample/pagination.codeDemo2.tsx
<reponame>yyzclyang/algae-ui<filename>site/componentExample/PaginationExample/pagination.codeDemo2.tsx import React from 'react'; import { Pagination } from 'algae-ui'; export default () => { return ( <div className="pagination-list"> <Pagination pageSize={10} total={150} onChange={(page) => { console.log(page); }} /> </div> ); };
yyzclyang/algae-ui
site/pages/Introduction/introduction.tsx
import React from 'react'; import './index.scss'; import '../../img/logo.svg'; import '../../img/react.svg'; const Introduction: React.FunctionComponent = () => ( <div className="introduction-page"> <section className="introduction"> <h1>Algae-UI of React</h1> <p> <code>algae-ui</code>是为 React 制作的一套 UI 组件库,主要用来学习。 </p> <div className="logo"> <svg> <use xlinkHref="#logo" /> </svg> <span>&</span> <svg> <use xlinkHref="#react" /> </svg> </div> </section> <section> <h2>支持环境</h2> <p> 由于本库采用了 React 的新特性 <a href="https://reactjs.org/docs/hooks-intro.html" target="_Blank" rel="noopener noreferrer" > Hook </a> , 所以请保证 React 的版本为 16.8 及以上。 </p> </section> <section> <h2>使用 TypeScript</h2> <p> <code>algae-ui</code>使用 <a href="https://www.typescriptlang.org/" target="_Blank" rel="noopener noreferrer" > TypeScript </a> 编写。 <a href="https://www.typescriptlang.org/" target="_Blank" rel="noopener noreferrer" > TypeScript </a> 带来了可选的静态类型检查以及最新的 ECMAScript 特性,有效增强代码的健壮性。 </p> </section> <section> <h2>依赖</h2> <p> <code>algae-ui</code>只依赖 React、ReactDOM 两个核心库。 </p> </section> </div> ); export default Introduction;
yyzclyang/algae-ui
components/modal/modal.tsx
<gh_stars>1-10 import React from 'react'; import Dialog, { DialogProps } from './dialog'; import confirm, { ConfirmProps, UpdateProps } from './confirm'; type ButtonType = 'default' | 'primary' | 'success' | 'danger'; interface ModalFuncProps { title: string; content: React.ReactNode; buttonType?: ButtonType; buttonText?: string; onClick?: React.MouseEventHandler; } type ModalFunc = ( props: ModalFuncProps ) => { destroy: () => void; update: (props: UpdateProps) => void }; type ModalConfirmFunc = ( props: ConfirmProps ) => { destroy: () => void; update: (props: UpdateProps) => void }; interface ModalProps extends DialogProps {} class Modal extends React.Component<ModalProps> { static displayName = 'Modal'; static defaultProps = { visible: false, closeOnClickMask: false, children: null }; static alert: ModalConfirmFunc; static info: ModalFunc; static success: ModalFunc; static error: ModalFunc; static warning: ModalFunc; render() { return <Dialog {...this.props} />; } } Modal.alert = (props) => { return confirm(props); }; type modalType = 'info' | 'success' | 'error' | 'warning'; interface ModalFuncBaseProps { type: modalType; iconType: string; iconStyle?: React.CSSProperties; defaultButtonType: ButtonType; defaultButtonText: string; } const modalExpandFunc = ( baseConfig: ModalFuncBaseProps, customConfig: ModalFuncProps ) => { const { title, content, buttonType, buttonText, onClick } = customConfig; const { type, iconType, iconStyle, defaultButtonType, defaultButtonText } = baseConfig; return confirm({ type, title, content, iconType, iconStyle, okButton: { buttonType: buttonType || defaultButtonType, content: buttonText || defaultButtonText, onClick: (e) => { onClick && onClick(e); } } }); }; Modal.info = (props) => { const defaultConfig = { type: 'info' as modalType, iconType: 'info-circle', iconStyle: { fill: '#1890ff' }, defaultButtonType: 'primary' as ButtonType, defaultButtonText: '知道了' }; return modalExpandFunc(defaultConfig, props); }; Modal.success = (props) => { const defaultConfig = { type: 'success' as modalType, iconType: 'check-circle', iconStyle: { fill: '#52c41a' }, defaultButtonType: 'success' as ButtonType, defaultButtonText: '知道了' }; return modalExpandFunc(defaultConfig, props); }; Modal.error = (props) => { const defaultConfig = { type: 'error' as modalType, iconType: 'close-circle', iconStyle: { fill: '#f5222d' }, defaultButtonType: 'danger' as ButtonType, defaultButtonText: '知道了' }; return modalExpandFunc(defaultConfig, props); }; Modal.warning = (props) => { const defaultConfig = { type: 'warning' as modalType, iconType: 'warning-circle', iconStyle: { fill: '#faad14' }, defaultButtonType: 'default' as ButtonType, defaultButtonText: '知道了' }; return modalExpandFunc(defaultConfig, props); }; export default Modal;
vumdao/cloudstructs
src/ecs-service-roller/index.ts
import { Stack } from 'aws-cdk-lib'; import * as ecs from 'aws-cdk-lib/aws-ecs'; import * as events from 'aws-cdk-lib/aws-events'; import * as targets from 'aws-cdk-lib/aws-events-targets'; import * as iam from 'aws-cdk-lib/aws-iam'; import { Construct } from 'constructs'; /** * Properties for a EcsServiceRoller */ export interface EcsServiceRollerProps { /** * The ECS cluster where the services run */ readonly cluster: ecs.ICluster; /** * The ECS service for which tasks should be rolled */ readonly service: ecs.IService; /** * The rule or schedule that should trigger a roll * * @default - roll everyday at midnight */ readonly trigger?: RollTrigger; } /** * The rule or schedule that should trigger a roll */ export abstract class RollTrigger { /** * Schedule that should trigger a roll */ public static fromSchedule(schedule: events.Schedule): RollTrigger { return { schedule }; } /** * Rule that should trigger a roll */ public static fromRule(rule: events.Rule): RollTrigger { return { rule }; } /** * Roll schedule * * @default - roll everyday at midnight */ public abstract readonly schedule?: events.Schedule; /** * Roll rule * * @default - roll everyday at midnight */ public abstract readonly rule?: events.Rule; } /** * Roll your ECS service tasks on schedule or with a rule */ export class EcsServiceRoller extends Construct { constructor(scope: Construct, id: string, props: EcsServiceRollerProps) { super(scope, id); const rule = props.trigger?.rule ?? new events.Rule(this, 'Rule', { schedule: props.trigger?.schedule ?? events.Schedule.cron({ minute: '0', hour: '0', }), }); rule.addTarget(new targets.AwsApi({ service: 'ECS', action: 'updateService', parameters: { service: props.service.serviceName, cluster: props.cluster.clusterName, forceNewDeployment: true, } as AWS.ECS.UpdateServiceRequest, // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-supported-iam-actions-resources.html // arn:aws:ecs:<region>:<account>:service/<cluster-name>/<service-name> policyStatement: new iam.PolicyStatement({ actions: ['ecs:UpdateService'], resources: [Stack.of(this).formatArn({ service: 'ecs', resource: 'service', resourceName: `${props.cluster.clusterName}/${props.service.serviceName}`, })], }), })); } }
vumdao/cloudstructs
test/static-website/origin-request-handler.test.ts
<reponame>vumdao/cloudstructs import { handler } from '../../src/static-website/origin-request-handler'; test('without extension', async () => { const request = await handler({ Records: [ { cf: { request: { uri: '/my-uri', }, }, }, ], } as AWSLambda.CloudFrontRequestEvent); expect(request.uri).toBe('/index.html'); }); test('with extension', async () => { const request = await handler({ Records: [ { cf: { request: { uri: '/style/cool.css', }, }, }, ], } as AWSLambda.CloudFrontRequestEvent); expect(request.uri).toBe('/style/cool.css'); });
vumdao/cloudstructs
test/saml-identity-provider/saml-identity-provider.test.ts
import { Stack } from 'aws-cdk-lib'; import { Template } from 'aws-cdk-lib/assertions'; import * as iam from 'aws-cdk-lib/aws-iam'; import { SamlFederatedPrincipal, SamlIdentityProvider } from '../../src'; let stack: Stack; beforeEach(() => { stack = new Stack(); }); test('SamlIdentityProvider', () => { const identityProvider = new SamlIdentityProvider(stack, 'IdentityProvider', { metadataDocument: '<?xml version="1.0" encoding="utf-8"?><EntityDescriptor ID="ID" entityID="ID"</EntityDescriptor>', }); new iam.Role(stack, 'Role', { assumedBy: new SamlFederatedPrincipal(identityProvider), }); expect(Template.fromStack(stack).toJSON()).toMatchSnapshot(); });
vumdao/cloudstructs
test/slack-events/signature.test.ts
<reponame>vumdao/cloudstructs import crypto from 'crypto'; import { verifyRequestSignature } from '../../src/slack-events/signature'; console.error = jest.fn(); test('with valid signature', () => { expect(verifyRequestSignature({ body: 'hello', requestSignature: 'v0=495018ea2506b8ab02682a3aa5237aa029f37f0589cf7bb6309a35178975e18c', requestTimestamp: 9999999999, signingSecret: 'secret', })).toBe(true); }); test('invalid signature', () => { expect(verifyRequestSignature({ body: 'hello', requestSignature: 'v0=invalid', requestTimestamp: 9999999999, signingSecret: 'secret', })).toBe(false); }); test('outdated signature', () => { const createHmacSpy = jest.spyOn(crypto, 'createHmac'); expect(verifyRequestSignature({ body: 'hello', requestSignature: 'v0=495018ea2506b8ab02682a3aa5237aa029f37f0589cf7bb6309a35178975e18c', requestTimestamp: 100, signingSecret: 'secret', })).toBe(false); expect(createHmacSpy).not.toHaveBeenCalled(); createHmacSpy.mockRestore(); });
vumdao/cloudstructs
test/url-shortener/url-shortener.test.ts
import { Duration, Stack } from 'aws-cdk-lib'; import { Template } from 'aws-cdk-lib/assertions'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import * as route53 from 'aws-cdk-lib/aws-route53'; import { UrlShortener } from '../../src'; let stack: Stack; beforeEach(() => { stack = new Stack(); }); test('UrlShortener', () => { const hostedZone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'cstructs.com' }); new UrlShortener(stack, 'UrlShortener', { hostedZone, expiration: Duration.days(60), }); expect(Template.fromStack(stack).toJSON()).toMatchSnapshot(); }); test('UrlShortener with API gateway endpoint', () => { const hostedZone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'cstructs.com' }); const vpc = new ec2.Vpc(stack, 'Vpc'); const apiGatewayEndpoint = new ec2.InterfaceVpcEndpoint(stack, 'ApiGatewayEndpoint', { service: ec2.InterfaceVpcEndpointAwsService.APIGATEWAY, vpc, }); new UrlShortener(stack, 'UrlShortener', { hostedZone, apiGatewayEndpoint, }); expect(Template.fromStack(stack).toJSON()).toMatchSnapshot(); });
vumdao/cloudstructs
test/email-receiver/s3-handler.test.ts
import { handler } from '../../src/email-receiver/s3.lambda'; console.log = jest.fn(); test('it extracts the message', async () => { const response = await handler({ Records: [ { EventSource: 'sns', EventSubscriptionArn: 'arn', EventVersion: '1.0', Sns: { Message: '{"key":"value"}', MessageAttributes: {}, MessageId: 'id', Signature: 'signature', SignatureVersion: '1.0', SigningCertUrl: 'url', Subject: 'subject', Timestamp: 'timestamp', TopicArn: 'arn', Type: 'type', UnsubscribeUrl: 'url', }, }, ], }); expect(response).toEqual({ key: 'value' }); });
vumdao/cloudstructs
src/email-receiver/receiver.ts
<filename>src/email-receiver/receiver.ts import { Duration } from 'aws-cdk-lib'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as destinations from 'aws-cdk-lib/aws-lambda-destinations'; import * as logs from 'aws-cdk-lib/aws-logs'; import * as s3 from 'aws-cdk-lib/aws-s3'; import * as ses from 'aws-cdk-lib/aws-ses'; import * as actions from 'aws-cdk-lib/aws-ses-actions'; import * as sns from 'aws-cdk-lib/aws-sns'; import * as subscriptions from 'aws-cdk-lib/aws-sns-subscriptions'; import { Construct } from 'constructs'; import { S3Function } from './s3-function'; import { WhitelistFunction } from './whitelist-function'; /** * Properties for an EmailReceiver */ export interface EmailReceiverProps { /** * The SES receipt rule set where a receipt rule will be added */ readonly receiptRuleSet: ses.IReceiptRuleSet; /** * The recipients for which emails should be received */ readonly recipients: string[]; /** * A Lambda function to invoke after the message is saved to S3. The Lambda * function will be invoked with a SESMessage as event. */ readonly function: lambda.IFunction; /** * A regular expression to whitelist source email addresses * * @default - no whitelisting of source email addresses */ readonly sourceWhitelist?: string; /** * An existing rule after which the new rule will be placed in the rule set. * * @default - The new rule is inserted at the beginning of the rule list. */ readonly afterRule?: ses.IReceiptRule; } /** * Receive emails through SES, save them to S3 and invokes a * Lambda function */ export class EmailReceiver extends Construct { constructor(scope: Construct, id: string, props: EmailReceiverProps) { super(scope, id); const receiptRule = new ses.ReceiptRule(this, 'ReceiptRule', { ruleSet: props.receiptRuleSet, recipients: props.recipients, after: props.afterRule, }); const bucket = new s3.Bucket(this, 'Bucket', { blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, encryption: s3.BucketEncryption.S3_MANAGED, lifecycleRules: [{ expiration: Duration.days(1) }], }); bucket.grantRead(props.function); // Download email const topic = new sns.Topic(this, 'Topic'); // Actions if (props.sourceWhitelist) { const whitelistHandler = new WhitelistFunction(this, 'whitelist', { environment: { SOURCE_WHITELIST: props.sourceWhitelist, }, logRetention: logs.RetentionDays.ONE_MONTH, }); receiptRule.addAction(new actions.Lambda({ function: whitelistHandler, invocationType: actions.LambdaInvocationType.REQUEST_RESPONSE, })); } receiptRule.addAction(new actions.S3({ bucket, topic, })); const s3Handler = new S3Function(this, 's3', { logRetention: logs.RetentionDays.ONE_MONTH, onSuccess: new destinations.LambdaDestination(props.function, { responseOnly: true, }), }); topic.addSubscription(new subscriptions.LambdaSubscription(s3Handler)); // Notify } }
vumdao/cloudstructs
src/state-machine-cr-provider/runtime/index.ts
<filename>src/state-machine-cr-provider/runtime/index.ts<gh_stars>10-100 import { StepFunctions } from 'aws-sdk'; // eslint-disable-line import/no-extraneous-dependencies import { respond } from './http'; export const CREATE_FAILED_PHYSICAL_ID_MARKER = 'AWSCDK::StateMachineProvider::CREATE_FAILED'; interface Output { PhysicalResourceId?: string; Data?: { [Key: string]: any }; NoEcho?: boolean; } interface ExecutionResult { ExecutionArn: string; Input: AWSLambda.CloudFormationCustomResourceEvent & { PhysicalResourceId?: string }; Name: string; Output?: Output; StartDate: number; StateMachineArn: string; Status: 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'TIMED_OUT' | 'ABORTED'; StopDate: number; } interface FailedExecutionEvent { Error: string; Cause: string; } export async function cfnResponseSuccess(event: ExecutionResult) { console.log('Event: %j', event); await respond('SUCCESS', { ...event.Input, PhysicalResourceId: event.Output?.PhysicalResourceId ?? event.Input.PhysicalResourceId ?? event.Input.RequestId, Data: event.Output?.Data ?? {}, NoEcho: event.Output?.NoEcho, }); } export async function cfnResponseFailed(event: FailedExecutionEvent) { console.log('Event: %j', event); const parsedCause = JSON.parse(event.Cause); const executionResult: ExecutionResult = { ...parsedCause, Input: JSON.parse(parsedCause.Input), }; console.log('Execution result: %j', executionResult); let physicalResourceId = executionResult.Output?.PhysicalResourceId ?? executionResult.Input.PhysicalResourceId; if (!physicalResourceId) { // special case: if CREATE fails, which usually implies, we usually don't // have a physical resource id. in this case, the subsequent DELETE // operation does not have any meaning, and will likely fail as well. to // address this, we use a marker so the provider framework can simply // ignore the subsequent DELETE. if (executionResult.Input.RequestType === 'Create') { console.log('CREATE failed, responding with a marker physical resource id so that the subsequent DELETE will be ignored'); physicalResourceId = CREATE_FAILED_PHYSICAL_ID_MARKER; } else { console.log(`ERROR: Malformed event. "PhysicalResourceId" is required: ${JSON.stringify(event)}`); } } await respond('FAILED', { ...executionResult.Input, Reason: `${event.Error}: ${event.Cause}`, PhysicalResourceId: physicalResourceId, }); } export async function startExecution(event: AWSLambda.CloudFormationCustomResourceEvent) { try { console.log('Event: %j', event); if (!process.env.STATE_MACHINE_ARN) { throw new Error('Missing STATE_MACHINE_ARN.'); } // ignore DELETE event when the physical resource ID is the marker that // indicates that this DELETE is a subsequent DELETE to a failed CREATE // operation. if (event.RequestType === 'Delete' && event.PhysicalResourceId === CREATE_FAILED_PHYSICAL_ID_MARKER) { console.log('ignoring DELETE event caused by a failed CREATE event'); await respond('SUCCESS', event); return; } const stepFunctions = new StepFunctions(); await stepFunctions.startExecution({ stateMachineArn: process.env.STATE_MACHINE_ARN, input: JSON.stringify(event), }).promise(); } catch (err) { console.log(err); await respond('FAILED', { ...event, Reason: err.message, }); } }
vumdao/cloudstructs
src/slack-app/index.ts
export * from './slack-app'; export * from './manifest';
vumdao/cloudstructs
test/state-machine-cr-provider/runtime.test.ts
<reponame>vumdao/cloudstructs<filename>test/state-machine-cr-provider/runtime.test.ts import * as AWS from 'aws-sdk-mock'; import * as runtime from '../../src/state-machine-cr-provider/runtime'; import * as http from '../../src/state-machine-cr-provider/runtime/http'; jest.mock('../../src/state-machine-cr-provider/runtime/http'); console.log = jest.fn(); beforeEach(() => { AWS.restore(); jest.clearAllMocks(); process.env.STATE_MACHINE_ARN = 'state-machine-arn'; }); const cfEvent: AWSLambda.CloudFormationCustomResourceEvent & { PhysicalResourceId?: string } = { RequestType: 'Create', ServiceToken: 'service-token', ResponseURL: 'response-url', StackId: 'stack-id', RequestId: 'request-id', LogicalResourceId: 'logical-resource-id', ResourceType: 'Custom::StateMachine', ResourceProperties: { ServiceToken: 'service-token', PropKey: 'PropValue', }, }; test('cfnResponseSuccess with CREATE', async () => { await runtime.cfnResponseSuccess({ ExecutionArn: 'execution-arn', Input: cfEvent, Name: 'execution-name', Output: { PhysicalResourceId: 'physical-resource-id', Data: { DataKey: 'DataValue', }, }, StartDate: 12345678, StateMachineArn: 'state-machine-arn', Status: 'SUCCEEDED', StopDate: 12345679, }); expect(http.respond).toHaveBeenCalledWith('SUCCESS', expect.objectContaining({ Data: { DataKey: 'DataValue', }, LogicalResourceId: 'logical-resource-id', PhysicalResourceId: 'physical-resource-id', RequestId: 'request-id', RequestType: 'Create', ResponseURL: 'response-url', })); }); test('cfnResponseSuccess with Create and no physical resource id', async () => { await runtime.cfnResponseSuccess({ ExecutionArn: 'execution-arn', Input: cfEvent, Name: 'execution-name', Output: { Data: { DataKey: 'DataValue', }, }, StartDate: 12345678, StateMachineArn: 'state-machine-arn', Status: 'SUCCEEDED', StopDate: 12345679, }); expect(http.respond).toHaveBeenCalledWith('SUCCESS', expect.objectContaining({ PhysicalResourceId: 'request-id', })); }); test('cfnResponseFailed with Create', async () => { const cause = { Input: JSON.stringify(cfEvent), }; await runtime.cfnResponseFailed({ Cause: JSON.stringify(cause), Error: 'CreateError', }); expect(http.respond).toHaveBeenCalledWith('FAILED', expect.objectContaining({ LogicalResourceId: 'logical-resource-id', PhysicalResourceId: runtime.CREATE_FAILED_PHYSICAL_ID_MARKER, RequestId: 'request-id', RequestType: 'Create', ResponseURL: 'response-url', Reason: expect.stringMatching(/^CreateError:/), })); }); test('cfnResponseFailed with Update', async () => { const cause = { Input: JSON.stringify({ ...cfEvent, RequestType: 'Update', PhysicalResourceId: 'physical-resource-id', }), }; await runtime.cfnResponseFailed({ Cause: JSON.stringify(cause), Error: 'UpdateError', }); expect(http.respond).toHaveBeenCalledWith('FAILED', expect.objectContaining({ LogicalResourceId: 'logical-resource-id', PhysicalResourceId: 'physical-resource-id', RequestId: 'request-id', RequestType: 'Update', ResponseURL: 'response-url', Reason: expect.stringMatching(/^UpdateError:/), })); }); test('startExecution with Create', async () => { const startExecutionMock = jest.fn(); AWS.mock('StepFunctions', 'startExecution', (params: any, callback: (p: any) => void) => callback(startExecutionMock(params)), ); await runtime.startExecution(cfEvent); expect(startExecutionMock).toHaveBeenCalledWith({ stateMachineArn: 'state-machine-arn', input: JSON.stringify(cfEvent), }); }); test('startExecution with Delete after failed Create', async () => { const startExecutionMock = jest.fn(); AWS.mock('StepFunctions', 'startExecution', (params: any, callback: any) => callback(null, startExecutionMock(params)), ); await runtime.startExecution({ ...cfEvent, RequestType: 'Delete', PhysicalResourceId: runtime.CREATE_FAILED_PHYSICAL_ID_MARKER, }); expect(startExecutionMock).not.toHaveBeenCalled(); expect(http.respond).toHaveBeenCalledWith('SUCCESS', expect.anything()); }); test('startExecution with error', async () => { AWS.mock('StepFunctions', 'startExecution', (_params: any, callback: (p: any) => void) => callback(new Error('UnknownError')), ); await runtime.startExecution(cfEvent); expect(http.respond).toHaveBeenCalledWith('FAILED', expect.objectContaining({ Reason: 'UnknownError', })); });
vumdao/cloudstructs
test/slack-app/slack-app.integ.ts
import { App, CfnOutput, Stack, StackProps } from 'aws-cdk-lib'; import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager'; import { Construct } from 'constructs'; import { SlackApp, SlackAppManifestDefinition } from '../../src'; class TestStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); const app = new SlackApp(this, 'MyApp', { configurationTokenSecret: secretsmanager.Secret.fromSecretNameV2(this, 'Secret', 'slack-app-config-token'), manifest: SlackAppManifestDefinition.fromManifest({ name: 'My App', description: 'A very cool Slack App deployed with CDK', }), }); new CfnOutput(this, 'AppId', { value: app.appId, }); } } const app = new App(); new TestStack(app, 'slack-app-integ'); app.synth();
vumdao/cloudstructs
test/slack-events/handler.test.ts
<filename>test/slack-events/handler.test.ts import * as AWS from 'aws-sdk-mock'; import { handler } from '../../src/slack-events/events.lambda'; import * as signature from '../../src/slack-events/signature'; process.env.SLACK_SIGNING_SECRET = 'secret'; console.log = jest.fn(); beforeEach(() => { AWS.restore(); }); test('returns 403 on invalid signature', async () => { jest.spyOn(signature, 'verifyRequestSignature').mockReturnValueOnce(false); const response = await handler({ body: '{}', headers: { 'X-Slack-Signature': 'signature', 'X-Slack-Request-Timestamp': '1000', }, } as unknown as AWSLambda.APIGatewayProxyEvent); expect(response).toEqual<AWSLambda.APIGatewayProxyResult>({ body: '', statusCode: 403, }); }); test('url verification', async () => { jest.spyOn(signature, 'verifyRequestSignature').mockReturnValueOnce(true); const response = await handler({ body: JSON.stringify({ type: 'url_verification', challenge: 'challenge', }), headers: { 'X-Slack-Signature': 'signature', 'X-Slack-Request-Timestamp': '1000', }, } as unknown as AWSLambda.APIGatewayProxyEvent); expect(response).toEqual<AWSLambda.APIGatewayProxyResult>({ body: JSON.stringify({ challenge: 'challenge' }), statusCode: 200, }); }); test('puts events', async () => { jest.spyOn(signature, 'verifyRequestSignature').mockReturnValueOnce(true); const putEventsMock = jest.fn().mockReturnValue({}); AWS.mock('EventBridge', 'putEvents', (params: any, callback: any) => { callback(null, putEventsMock(params)); }); const body = JSON.stringify({ type: 'event', api_app_id: 'app-id', event_time: '2020-12-01T12:00:00.000Z', }); const response = await handler({ body, headers: { 'X-Slack-Signature': 'signature', 'X-Slack-Request-Timestamp': '1000', }, } as unknown as AWSLambda.APIGatewayProxyEvent); expect(putEventsMock).toHaveBeenCalledWith({ Entries: [ { Detail: body, DetailType: 'Slack Event', Source: 'slack', Resources: ['app-id'], EventBusName: undefined, Time: new Date('2020-12-01T12:00:00.000Z'), }, ], }); expect(response).toEqual<AWSLambda.APIGatewayProxyResult>({ body: '', statusCode: 200, }); });
vumdao/cloudstructs
test/email-receiver/email-receiver.test.ts
<gh_stars>0 import { Stack } from 'aws-cdk-lib'; import { Template } from 'aws-cdk-lib/assertions'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as ses from 'aws-cdk-lib/aws-ses'; import { EmailReceiver } from '../../src'; let stack: Stack; beforeEach(() => { stack = new Stack(); }); test('EmailReceiver', () => { const fn = new lambda.Function(stack, 'Fn', { code: lambda.Code.fromInline('export.handler=() => void;'), runtime: lambda.Runtime.NODEJS_14_X, handler: 'index.handler', }); const ruleSet = ses.ReceiptRuleSet.fromReceiptRuleSetName(stack, 'RuleSet', 'rule-set'); new EmailReceiver(stack, 'EmailReceiver', { recipients: ['<EMAIL>'], sourceWhitelist: '@amazon.com$', function: fn, receiptRuleSet: ruleSet, }); expect(Template.fromStack(stack).toJSON()).toMatchSnapshot(); });
vumdao/cloudstructs
src/slack-events/events.lambda.ts
/* eslint-disable no-console */ import { EventBridge } from 'aws-sdk'; // eslint-disable-line import/no-extraneous-dependencies import { verifyRequestSignature } from './signature'; /** * Handle Slack events */ export async function handler(event: AWSLambda.APIGatewayProxyEvent): Promise<AWSLambda.APIGatewayProxyResult> { console.log('Event: %j', event); // Base API gateway response const response: AWSLambda.APIGatewayProxyResult = { statusCode: 200, body: '', }; try { if (!process.env.SLACK_SIGNING_SECRET) throw new Error('The environment variable SLACK_SIGNING_SECRET is not defined'); if (!event.body) throw new Error('Missing body'); if (!event.headers['X-Slack-Signature']) throw new Error('Missing X-Slack-Signature'); if (!event.headers['X-Slack-Request-Timestamp']) throw new Error('Missing X-Slack-Request-Timestamp'); if (!verifyRequestSignature({ body: event.body, requestSignature: event.headers['X-Slack-Signature'], requestTimestamp: parseInt(event.headers['X-Slack-Request-Timestamp'], 10), signingSecret: process.env.SLACK_SIGNING_SECRET, })) { response.statusCode = 403; return response; } const body = JSON.parse(event.body); console.log('Body: %j', body); if (body.type === 'url_verification') { // Slack URL verification, respond with challenge console.log('URL verification'); response.body = JSON.stringify({ challenge: body.challenge }); return response; } const eventBridge = new EventBridge({ apiVersion: '2015-10-07' }); const putEvents = await eventBridge.putEvents({ Entries: [ { Detail: event.body, DetailType: 'Slack Event', Source: 'slack', Resources: [body.api_app_id], EventBusName: process.env.EVENT_BUS_NAME, Time: new Date(body.event_time), }, ], }).promise(); console.log('Put events: %j', putEvents); return response; } catch (err) { console.log(err); response.statusCode = 500; return response; } }
vumdao/cloudstructs
src/toolkit-cleaner/clean-images.lambda.ts
<gh_stars>0 import { ECR } from 'aws-sdk'; // eslint-disable-line import/no-extraneous-dependencies const ecr = new ECR(); export async function handler(assetHashes: string[]) { if (!process.env.REPOSITORY_NAME) { throw new Error('Missing REPOSITORY_NAME'); } let deleted = 0; let reclaimed = 0; let nextToken: string | undefined; let finished = false; while (!finished) { const response = await ecr.describeImages({ repositoryName: process.env.REPOSITORY_NAME, nextToken, }).promise(); const toDelete = response.imageDetails?.filter(x => { let pred = x.imageTags && !assetHashes.includes(x.imageTags[0]); if (process.env.RETAIN_MILLISECONDS) { const limitDate = new Date(Date.now() - parseInt(process.env.RETAIN_MILLISECONDS)); pred = pred && x.imagePushedAt && x.imagePushedAt < limitDate; } return pred; }); if (toDelete && toDelete.length !== 0) { if (process.env.RUN) { await ecr.batchDeleteImage({ repositoryName: process.env.REPOSITORY_NAME, imageIds: toDelete.map(x => ({ imageTag: x.imageTags![0] })), }).promise(); } deleted += toDelete.length; reclaimed += toDelete.reduce((acc, x) => acc + (x.imageSizeInBytes ?? 0), 0); } nextToken = response.nextToken; if (nextToken === undefined) { finished = true; } } return { Deleted: deleted, Reclaimed: reclaimed, }; }
vumdao/cloudstructs
src/slack-app/slack-app.ts
import * as fs from 'fs'; import { CustomResource } from 'aws-cdk-lib'; import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager'; import { Construct, IConstruct } from 'constructs'; import { SlackAppManifest, SlackAppManifestProps } from './manifest'; import { SlackAppProvider } from './provider'; /** * Properties for a SlackApp */ export interface SlackAppProps { /** * The definition of the app manifest * * @see https://api.slack.com/reference/manifests */ readonly manifest: SlackAppManifestDefinition; /** * An AWS Secrets Manager secret containing the app configuration token * * Must use the following JSON format: * * ``` * { * "refreshToken": "<token>" * } * ``` */ readonly configurationTokenSecret: secretsmanager.ISecret; /** * The AWS Secrets Manager secret where to store the app credentials * * @default - a new secret is created */ readonly credentialsSecret?: secretsmanager.ISecret; } /** * A Slack app manifest definition */ export abstract class SlackAppManifestDefinition { /** * Create a Slack app manifest from a JSON app manifest encoded as a string */ public static fromString(manifest: string): SlackAppManifestDefinition { return new StringManifest(manifest); } /** * Creates a Slack app manifest from a file containg a JSON app manifest */ public static fromFile(file: string): SlackAppManifestDefinition { return new FileManifest(file); } /** * Creates a Slack app manifest by specifying properties */ public static fromManifest(props: SlackAppManifestProps): SlackAppManifestDefinition { return new SlackAppManifest(props); } /** * Renders the JSON app manifest encoded as a string */ public abstract render(construct: IConstruct): string; } class StringManifest extends SlackAppManifestDefinition { constructor(private readonly manifest: string) { super(); } public render(_construct: IConstruct): string { return this.manifest; } } class FileManifest extends SlackAppManifestDefinition { constructor(private readonly file: string) { super(); } public render(_construct: IConstruct): string { return fs.readFileSync(this.file, 'utf8'); } } /** * A Slack application deployed with a manifest * * @see https://api.slack.com/reference/manifests */ export class SlackApp extends Construct { /** * The ID of the application */ public readonly appId: string; /** * An AWS Secrets Manager secret containing the credentials of the application. * * ``` * { * "appId": "...", * "clientId": "...", * "clientSecret": "...", * "verificationToken": "...", * "signingSecret": "..." * } * ``` */ public readonly credentials: secretsmanager.ISecret; /** * A dynamic reference to the client ID of the app */ public readonly clientId: string; /** * A dynamic reference to the client secret of the app */ public readonly clientSecret: string; /** * A dynamic reference to the verification token of the app */ public readonly verificationToken: string; /** * A dynamic reference to the signing secret of the app */ public readonly signingSecret: string; constructor(scope: Construct, id: string, props: SlackAppProps) { super(scope, id); const provider = SlackAppProvider.getOrCreate(this); props.configurationTokenSecret.grantRead(provider.handler); props.configurationTokenSecret.grantWrite(provider.handler); this.credentials = props.credentialsSecret ?? new secretsmanager.Secret(this, 'Credentials', { description: `Credentials for Slack App ${this.node.id}`, }); this.credentials.grantWrite(provider.handler); const resource = new CustomResource(this, 'Resource', { serviceToken: provider.serviceToken, resourceType: 'Custom::SlackApp', properties: { manifest: props.manifest.render(this), configurationTokenSecretArn: props.configurationTokenSecret.secretArn, credentialsSecretArn: this.credentials.secretArn, }, }); this.appId = resource.getAttString('appId'); this.clientId = this.credentials.secretValueFromJson('clientId').toString(); this.clientSecret = this.credentials.secretValueFromJson('clientSecret').toString(); this.verificationToken = this.credentials.secretValueFromJson('verificationToken').toString(); this.signingSecret = this.credentials.secretValueFromJson('signingSecret').toString(); } }
vumdao/cloudstructs
src/slack-app/provider.ts
<filename>src/slack-app/provider.ts import { Stack } from 'aws-cdk-lib'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as logs from 'aws-cdk-lib/aws-logs'; import * as cr from 'aws-cdk-lib/custom-resources'; import { Construct } from 'constructs'; import { ProviderFunction } from './provider-function'; export class SlackAppProvider extends Construct { /** * Creates a stack-singleton resource provider */ public static getOrCreate(scope: Construct): SlackAppProvider { const stack = Stack.of(scope); const uid = 'SlackAppProvider'; return stack.node.tryFindChild(uid) as SlackAppProvider ?? new SlackAppProvider(stack, uid); } public readonly serviceToken: string; public readonly handler: lambda.Function; constructor(scope: Construct, id: string) { super(scope, id); this.handler = new ProviderFunction(this, 'handler', { logRetention: logs.RetentionDays.ONE_MONTH, }); const provider = new cr.Provider(this, 'Resource', { onEventHandler: this.handler, }); this.serviceToken = provider.serviceToken; } }
vumdao/cloudstructs
test/slack-textract/handler.test.ts
<reponame>vumdao/cloudstructs<gh_stars>0 import { WebClient } from '@slack/web-api'; import { Textract } from 'aws-sdk'; import got from 'got'; import { handler, FilesInfoResult } from '../../src/slack-textract/detect.lambda'; process.env.SLACK_TOKEN = 'token'; console.log = jest.fn(); jest.mock('@slack/web-api'); jest.mock('got'); jest.mock('aws-sdk'); const gotMock = got as unknown as jest.Mock; test('handler', async () => { const fileInfo: FilesInfoResult = { ok: true, file: { mimetype: 'image/jpg', filetype: 'image', url_private: 'url-private', shares: { public: { C12345XYZ: [{ ts: 'ts', }], }, }, }, }; const filesInfoMock = jest.fn().mockResolvedValue(fileInfo); const postMessageMock = jest.fn().mockResolvedValue({ ok: true }); (WebClient as unknown as jest.Mock).mockImplementation(() => { return { files: { info: filesInfoMock }, chat: { postMessage: postMessageMock }, }; }); gotMock.mockImplementation(() => { return { buffer: () => Buffer.from('image-buffer') }; }); const detected: Textract.DetectDocumentTextResponse = { Blocks: [ { BlockType: 'LINE', Text: 'Hello', }, { BlockType: 'ZZZ', Text: 'Not', }, { BlockType: 'LINE', Text: 'World!', }, ], }; const detectDocumentTextMock = jest.fn(() => { return { promise: () => detected }; }); (Textract as unknown as jest.Mock).mockImplementation(() => { return { detectDocumentText: detectDocumentTextMock }; }); await handler({ channel_id: 'C12345XYZ', file_id: 'F1234567XYZ', }); expect(filesInfoMock).toHaveBeenCalledWith({ file: 'F1234567XYZ', }); expect(gotMock).toHaveBeenCalledWith('url-private', { headers: { Authorization: 'Bearer token', }, }); expect(detectDocumentTextMock).toHaveBeenLastCalledWith({ Document: { Bytes: Buffer.from('image-buffer') }, }); expect(postMessageMock).toHaveBeenLastCalledWith({ channel: 'C12345XYZ', text: 'Hello\nWorld!', thread_ts: 'ts', }); });
vumdao/cloudstructs
src/codecommit-mirror/index.ts
import * as path from 'path'; import * as codecommit from 'aws-cdk-lib/aws-codecommit'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import * as ecs from 'aws-cdk-lib/aws-ecs'; import * as events from 'aws-cdk-lib/aws-events'; import * as targets from 'aws-cdk-lib/aws-events-targets'; import * as iam from 'aws-cdk-lib/aws-iam'; import * as logs from 'aws-cdk-lib/aws-logs'; import { Construct } from 'constructs'; /** * Properties for a CodeCommitMirror */ export interface CodeCommitMirrorProps { /** * The source repository */ readonly repository: CodeCommitMirrorSourceRepository; /** * The ECS cluster where to run the mirroring operation */ readonly cluster: ecs.ICluster; /** * The schedule for the mirroring operation * * @default - everyday at midnight */ readonly schedule?: events.Schedule; /** * Where to run the mirroring Fargate tasks * * @default - public subnets */ readonly subnetSelection?: ec2.SubnetSelection; } /** * A source repository for AWS CodeCommit mirroring */ export abstract class CodeCommitMirrorSourceRepository { /** * Public GitHub repository */ public static gitHub(owner: string, name: string): CodeCommitMirrorSourceRepository { return { name, plainTextUrl: `https://github.com/${owner}/${name}`, }; } /** * Private repository with HTTPS clone URL stored in a AWS Secrets Manager secret or * a AWS Systems Manager secure string parameter. * * @param name the repository name * @param url the secret containing the HTTPS clone URL */ public static private(name: string, url: ecs.Secret): CodeCommitMirrorSourceRepository { return { name, secretUrl: url, }; } /** * The name of the repository */ public abstract readonly name: string; /** The HTTPS clone URL in plain text, used for a public repository */ public abstract readonly plainTextUrl?: string; /** * The HTTPS clone URL if the repository is private. * * The secret should contain the username and/or token. * * @example * `https://TOKEN@github.com/owner/name` * `https://USERNAME:TOKEN@bitbucket.org/owner/name.git` */ public abstract readonly secretUrl?: ecs.Secret; } /** * Mirror a repository to AWS CodeCommit on schedule */ export class CodeCommitMirror extends Construct { constructor(scope: Construct, id: string, props: CodeCommitMirrorProps) { super(scope, id); const destination = new codecommit.Repository(this, 'Repository', { repositoryName: props.repository.name, description: `Mirror of ${props.repository.name}`, }); const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDefinition'); taskDefinition.addContainer('Container', { image: ecs.ContainerImage.fromAsset(path.join(__dirname, '..', '..', 'assets', 'codecommit-mirror', 'docker')), logging: new ecs.AwsLogDriver({ streamPrefix: props.repository.name, logRetention: logs.RetentionDays.TWO_MONTHS, }), environment: { NAME: props.repository.name, DESTINATION: destination.repositoryCloneUrlGrc, ...props.repository.plainTextUrl ? { SOURCE: props.repository.plainTextUrl } : {}, }, secrets: props.repository.secretUrl ? { SOURCE: props.repository.secretUrl } : undefined, }); taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({ actions: ['codecommit:GitPush'], resources: [destination.repositoryArn], })); const rule = new events.Rule(this, 'Rule', { schedule: props.schedule ?? events.Schedule.cron({ minute: '0', hour: '0', }), }); rule.addTarget(new targets.EcsTask({ cluster: props.cluster, taskDefinition, subnetSelection: props.subnetSelection ?? { subnetType: ec2.SubnetType.PUBLIC }, })); } }
vumdao/cloudstructs
src/slack-app/manifest.ts
<gh_stars>0 import * as nodeUrl from 'url'; import { Stack, Token } from 'aws-cdk-lib'; import { IConstruct } from 'constructs'; /** * Properties for a Slack app manifest * * @see https://api.slack.com/reference/manifests */ export interface SlackAppManifestProps { /** * The name of the app. * * Maximum length is 35 characters. */ readonly name: string; /** * A short description of the app for display to users. * * Maximum length is 140 characters. * * @default - no short description */ readonly description?: string; /** * A longer version of the description of the app. * * Maximum length is 4000 characters. */ readonly longDescription?: string; /** * A hex color value that specifies the background color used on hovercards * that display information about your app. * * Can be 3-digit (#000) or 6-digit (#000000) hex values with or without # */ readonly backgroundColor?: string; /** * The major version of the manifest schema to target. * * @default - do not target a specific major version */ readonly majorVersion?: number; /** * The minor version of the manifest schema to target * * @default - do not target a specific minor version */ readonly minorVersion?: number; /** * An array of IP addresses that conform to the Allowed IP Ranges feature * * @see https://api.slack.com/authentication/best-practices#ip_allowlisting */ readonly allowedIpAddressRanges?: string[]; /** * Events API configuration for the app * * @see https://api.slack.com/events-api */ readonly eventSubscriptions?: SlackAppManifestEventSubscriptions; /** * Interactivity configuration for the app */ readonly interactivity?: SlackAppManifestInteractivity; /** * Whether org-wide deploy is enabled. * * @see https://api.slack.com/enterprise/apps * * @default false */ readonly orgDeploy?: boolean; /** * Whether Socket Mode is enabled * * @see https://api.slack.com/apis/connections/socket * * @default false */ readonly socketMode?: boolean; /** * App Home configuration * * @see https://api.slack.com/surfaces/tabs */ readonly appHome?: SlackAppManifestAppHome; /** * Bot user configuration * * @see https://api.slack.com/bot-users */ readonly botUser?: SlackkAppManifestBotUser; /** * Shortcuts configuration. * * A maximum of 5 shortcuts can be included. * * @see https://api.slack.com/interactivity/shortcuts */ readonly shortcuts?: SlackAppManifestShortcut[]; /** * Slash commands configuration. * * A maximum of 5 slash commands can be included. * * @see https://api.slack.com/interactivity/slash-commands */ readonly slashCommands?: SlackAppManifestSlashCommand[]; /** * Workflow steps. * * A maximum of 10 workflow steps can be included. * * @see https://api.slack.com/workflows/steps */ readonly workflowSteps?: SlackAppManifestWorkflowStep[]; /** * Valid unfurl domains to register. * * A maximum of 5 unfurl domains can be included. * * @see https://api.slack.com/reference/messaging/link-unfurling#configuring_domains */ readonly unfurlDomains?: string[]; /** * OAuth configuration for the app */ readonly oauthConfig?: SlackAppManifestOauthConfig; } /** * Settings section of the app config pages */ export interface SlackAppManifestSettings { /** * An array of IP addresses that conform to the Allowed IP Ranges feature * * @see https://api.slack.com/authentication/best-practices#ip_allowlisting */ readonly allowedIpAddressRanges?: string[]; /** * Events API configuration for the app * * @see https://api.slack.com/events-api */ readonly eventSubscriptions?: SlackAppManifestEventSubscriptions; /** * Interactivity configuration for the app */ readonly interactivity?: SlackAppManifestInteractivity; /** * Whether org-wide deploy is enabled. * * @see https://api.slack.com/enterprise/apps * * @default false */ readonly orgDeploy?: boolean; /** * Whether Socket Mode is enabled * * @see https://api.slack.com/apis/connections/socket * * @default false */ readonly socketMode?: boolean; } /** * Events API configuration for the app * * @see https://api.slack.com/events-api */ export interface SlackAppManifestEventSubscriptions { /** * The full https URL that acts as the Events API request URL * * @see https://api.slack.com/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls */ readonly requestUrl: string; /** * Event types you want the app to subscribe to. * * A maximum of 100 event types can be used * * @see https://api.slack.com/events */ readonly botEvents?: string[]; /** * Event types you want the app to subscribe to on behalf of authorized users. * * A maximum of 100 event types can be used. */ readonly userEvents?: string[]; } /** * Interactivity configuration for the app * * @see https://api.slack.com/interactivity/handling#setup */ export interface SlackAppManifestInteractivity { /** * Whether or not interactivity features are enabled * * @default true */ readonly enabled?: boolean; /** * The full https URL that acts as the interactive Request URL */ readonly requestUrl?: string; /** * The full https URL that acts as th interactive Options Load URL */ readonly messageMenuOptionsUrl?: string; } /** * App Home configuration * * @see https://api.slack.com/surfaces/tabs */ export interface SlackAppManifestAppHome { /** * Wether the Home tab is enabled * * @default false */ readonly homeTab?: boolean; /** * Wether the Messages is enabled * * @default false */ readonly messagesTab?: boolean; /** * Whether the users can send messages to your app in the * Messages tab of your App Home * * @default false */ readonly messagesTabReadOnly?: boolean; } /** * Bot user configuration * * @see https://api.slack.com/bot-users */ export interface SlackkAppManifestBotUser { /** * The display name of the bot user. * * Maximum length is 80 characters. */ readonly displayName: string; /** * Whether the bot user will always appear to be online * * @default false */ readonly alwaysOnline?: boolean; } /** * Shortcut configuration * * @see https://api.slack.com/interactivity/shortcuts */ export interface SlackAppManifestShortcut { /** * The name of the shortcut */ readonly name: string; /** * The type of shortcut * * @see https://api.slack.com/interactivity/shortcuts */ readonly type: SlackAppManifestShortcutType; /** * The callback ID of the shortcut. * * Maximum length is 255 characters. */ readonly callbackId: string; /** * A short description of the shortcut * * Maximum length is 150 characters */ readonly description: string; } /** * Type of shortcuts * * @see https://api.slack.com/interactivity/shortcuts */ export enum SlackAppManifestShortcutType { /** * Message shortcuts are shown to users in the context menus of messages within Slack * * @see https://api.slack.com/interactivity/shortcuts/using#message_shortcuts */ MESSAGE = 'message', /** * Global shortcuts are available to users via the shortcuts button in the composer, * and when using search in Slack * * @see https://api.slack.com/interactivity/shortcuts/using#global_shortcuts */ GLOBAL = 'global', } /** * Slash command configuration * * @see https://api.slack.com/interactivity/slash-commands */ export interface SlackAppManifestSlashCommand { /** * The actual slash command. * * Maximum length is 32 characters */ readonly command: string; /** * The description of the slash command. * * Maximum length is 2000 characters. */ readonly description: string; /** * The full https URL that acts as the slash command's request URL * * @see https://api.slack.com/interactivity/slash-commands#creating_commands */ readonly url?: string; /** * The short usage hint about the slash command for users. * * Maximum length is 1000 characters. */ readonly usageHint?: string; /** * Whether channels, users, and links typed with the slash command should be escaped * * @default false */ readonly shouldEscape?: boolean; } /** * Workflow step * * @see https://api.slack.com/workflows/steps */ export interface SlackAppManifestWorkflowStep { /** * The name of the workflow step. * * Maximum length of 50 characters. */ readonly name: string; /** * The callback ID of the workflow step. * * Maximum length of 50 characters. */ readonly callbackId: string; }; /** * OAuth configuration for the app */ export interface SlackAppManifestOauthConfig { /** * OAuth redirect URLs * * A maximum of 1000 redirect URLs can be included. * * @see https://api.slack.com/authentication/oauth-v2#redirect_urls */ readonly redirectUrls?: string[]; /** * Bot scopes to request upon app installation. * * A maximum of 255 scopes can be included. * * @see https://api.slack.com/scopes */ readonly botScopes?: string[]; /** * User scopes to request upon app installation. * * A maximum of 255 scopes can be included. * * @see https://api.slack.com/scopes */ readonly userScopes?: string[]; } /** * A Slack app manifest * * @see https://api.slack.com/reference/manifests */ export class SlackAppManifest { constructor(private readonly props: SlackAppManifestProps) { validateLength('app name', 35, props.name); validateLength('app description', 140, props.description); validateLength('app long description', 4000, props.longDescription); validateColor(props.backgroundColor); validateUrl(props.eventSubscriptions?.requestUrl); validateItems('bot events', 100, props.eventSubscriptions?.botEvents); validateItems('users events', 100, props.eventSubscriptions?.userEvents); validateUrl(props.interactivity?.requestUrl); validateUrl(props.interactivity?.messageMenuOptionsUrl); validateLength('bot display name', 80, props.botUser?.displayName); validateItems('shortcuts', 5, props.shortcuts); props.shortcuts?.forEach((shortcut) => { validateLength('shortcut callback ID', 255, shortcut.callbackId); validateLength('shortcut description', 150, shortcut.description); }); validateItems('slash commands', 5, props.slashCommands); props.slashCommands?.forEach((command) => { validateLength('slash command', 32, command.command); validateLength('slash command description', 2000, command.description), validateUrl(command.url); validateLength('slash command use hint', 1000, command.usageHint); }); validateItems('workflow steps', 10, props.workflowSteps); props.workflowSteps?.forEach((step) => { validateLength('workflow step name', 50, step.name); validateLength('workflow step callback ID', 50, step.callbackId); }); validateItems('unfurls domains', 5, props.unfurlDomains); validateItems('OAuth redirect URLs', 1000, props.oauthConfig?.redirectUrls); props.oauthConfig?.redirectUrls?.forEach((url) => { validateUrl(url, false); }); validateItems('bot scopes', 255, props.oauthConfig?.botScopes); validateItems('user scopes', 255, props.oauthConfig?.userScopes); } public render(construct: IConstruct): string { const schema: SlackAppManifestSchema = { _metadata: { major_version: this.props.majorVersion, minor_version: this.props.minorVersion, }, display_information: { name: this.props.name, description: this.props.description, long_description: this.props.longDescription, background_color: prefixWith('#', this.props.backgroundColor)?.toLowerCase(), }, settings: { allowed_ip_address_ranges: this.props.allowedIpAddressRanges, event_subscriptions: { request_url: this.props.eventSubscriptions?.requestUrl, bot_events: this.props.eventSubscriptions?.botEvents, user_events: this.props.eventSubscriptions?.userEvents, }, interactivity: this.props.interactivity ? { is_enabled: this.props.interactivity?.enabled ?? true, request_url: this.props.interactivity?.requestUrl, message_menu_options_url: this.props.interactivity?.messageMenuOptionsUrl, } : undefined, org_deploy_enabled: this.props.orgDeploy, socket_mode_enabled: this.props.socketMode, }, features: { app_home: { home_tab_enabled: this.props.appHome?.homeTab, messages_tab_enabled: this.props.appHome?.messagesTab, messages_tab_read_only_enabled: this.props.appHome?.messagesTabReadOnly, }, bot_user: this.props.botUser ? { display_name: this.props.botUser?.displayName, always_online: this.props.botUser?.alwaysOnline, } : undefined, shortcuts: this.props.shortcuts?.map((shortcut) => ({ name: shortcut.name, type: shortcut.type, callback_id: shortcut.callbackId, description: shortcut.description, })), slash_commands: this.props.slashCommands?.map((command) => ({ command: prefixWith('/', command.command), description: command.description, url: command.url, usage_hint: command.usageHint, should_escape: command.shouldEscape, })), workflow_steps: this.props.workflowSteps?.map((step) => ({ name: step.name, callback_id: step.callbackId, })), unfurl_domains: this.props.unfurlDomains, }, oauth_config: { redirect_urls: this.props.oauthConfig?.redirectUrls, scopes: { bot: this.props.oauthConfig?.botScopes, users: this.props.oauthConfig?.userScopes, }, }, }; return Stack.of(construct).toJsonString(removeUndefined(schema)); } } interface SlackAppManifestSchema { _metadata?: { major_version?: number; minor_version?: number; }; display_information: { name: string; description?: string; long_description?: string; background_color?: string; }; settings?: { allowed_ip_address_ranges?: string[]; event_subscriptions?: { request_url?: string; bot_events?: string[]; user_events?: string[]; }; interactivity?: { is_enabled: boolean; request_url?: string; message_menu_options_url?: string; }; org_deploy_enabled?: boolean; socket_mode_enabled?: boolean; }; features?: { app_home?: { home_tab_enabled?: boolean; messages_tab_enabled?: boolean; messages_tab_read_only_enabled?: boolean; }; bot_user?: { display_name: string; always_online?: boolean; }; shortcuts?: { name: string; type: string; callback_id: string; description: string; }[]; slash_commands?: { command: string; description: string; url?: string; usage_hint?: string; should_escape?: boolean; }[]; workflow_steps?: { name: string; callback_id: string; }[]; unfurl_domains?: string[]; }; oauth_config?: { redirect_urls?: string[]; scopes?: { bot?: string[]; users?: string[]; }; }; } function prefixWith<T extends string | undefined>(prefix: string, string: T): T { if (!string) { return undefined as T; } if (string.startsWith(prefix)) { return string; } return `${prefix}${string}` as T; } function validateLength(description: string, max: number, xs?: string): void { if (xs && !Token.isUnresolved(xs) && xs.length > max) { throw new Error(`Maximum length for ${description} is ${max}, got ${xs.length}: ${xs}`); } } function validateItems<T>(description: string, max: number, xs?: T[]): void { if (xs && !Token.isUnresolved(xs) && xs.length > max) { throw new Error(`Maximum number of items for ${description} is ${max}, got ${xs.length}`); } } function validateColor(color?: string): void { if (color && !Token.isUnresolved(color) && !/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color)) { throw new Error(`Invalid hex color: ${color}`); } } function validateUrl(url?: string, https = true): void { if (url && !Token.isUnresolved(url)) { try { const parsed = new nodeUrl.URL(url); if (https && parsed.protocol !== 'https:') { throw new Error('Invalid protocol'); } } catch (err) { throw new Error(`${url} is not a valid${https ? ' HTTPS' : ''} url`); } } } function removeUndefined(obj: any): any { if (typeof obj === 'string') { return obj; } if (Array.isArray(obj)) { const ret = obj .map(v => (v && typeof v === 'object') ? removeUndefined(v) : v) .filter(v => !(v == null)); return ret.length !== 0 ? ret : undefined; } const ret = Object.entries(obj) .map(([k, v]) => [k, v && typeof v === 'object' ? removeUndefined(v) : v]) .reduce((a: any, [k, v]) => (v == null ? a : (a[k]=v, a)), {}); return Object.keys(ret).length !== 0 ? ret : undefined; }
vumdao/cloudstructs
src/saml-identity-provider/index.ts
<gh_stars>0 import { Names, Stack } from 'aws-cdk-lib'; import * as iam from 'aws-cdk-lib/aws-iam'; import * as cr from 'aws-cdk-lib/custom-resources'; import { IAM } from 'aws-sdk'; // eslint-disable-line import/no-extraneous-dependencies import { Construct } from 'constructs'; /** * Properties for a SamlProvider * * @deprecated use `SamlProviderProps` from `aws-cdk-lib/aws-iam` */ export interface SamlIdentityProviderProps { /** * A name for the SAML identity provider * * @default - derived for the node's unique id */ readonly name?: string; /** * An XML document generated by an identity provider (IdP) that supports SAML 2.0. * * The document includes the issuer's name, expiration information, and keys that * can be used to validate the SAML authentication response (assertions) that are * received from the IdP. You must generate the metadata document using the identity * management software that is used as your organization's IdP. */ readonly metadataDocument: string; } /** * Create a SAML identity provider * * @deprecated use `SamlProvider` from `aws-cdk-lib/aws-iam` */ export class SamlIdentityProvider extends Construct { /** * The ARN of the SAML identity provider */ public readonly samlIdentityProviderArn: string; constructor(scope: Construct, id: string, props: SamlIdentityProviderProps) { super(scope, id); const name = props.name ?? `${Names.uniqueId(this)}IdentityProvider`; const arn = Stack.of(this).formatArn({ service: 'iam', region: '', resource: 'saml-provider', resourceName: name, }); const idp = new cr.AwsCustomResource(this, 'Resource', { resourceType: 'Custom::SamlIdentityProvider', onCreate: { service: 'IAM', action: 'createSAMLProvider', parameters: { Name: name, SAMLMetadataDocument: props.metadataDocument, } as IAM.CreateSAMLProviderRequest, physicalResourceId: cr.PhysicalResourceId.fromResponse('SAMLProviderArn'), }, onUpdate: { service: 'IAM', action: 'updateSAMLProvider', parameters: { SAMLProviderArn: new cr.PhysicalResourceIdReference().toJSON(), SAMLMetadataDocument: props.metadataDocument, } as IAM.UpdateSAMLProviderRequest, physicalResourceId: cr.PhysicalResourceId.fromResponse('SAMLProviderArn'), }, onDelete: { service: 'IAM', action: 'deleteSAMLProvider', parameters: { SAMLProviderArn: new cr.PhysicalResourceIdReference().toJSON(), } as IAM.DeleteSAMLProviderRequest, }, policy: cr.AwsCustomResourcePolicy.fromStatements([ new iam.PolicyStatement({ actions: [ 'iam:createSAMLProvider', 'iam:updateSAMLProvider', 'iam:deleteSAMLProvider', ], resources: [arn], }), ]), }); this.samlIdentityProviderArn = idp.getResponseField('SAMLProviderArn'); } } /** * Principal entity that represents a SAML federated identity provider. * * @deprecated use `SamlPrincipal` from `aws-cdk-lib/aws-iam` */ export class SamlFederatedPrincipal extends iam.FederatedPrincipal { constructor(identityProvider: SamlIdentityProvider) { super( identityProvider.samlIdentityProviderArn, { StringEquals: { 'SAML:aud': 'https://signin.aws.amazon.com/saml', }, }, 'sts:AssumeRoleWithSAML', ); } }
vumdao/cloudstructs
src/toolkit-cleaner/clean-objects.lambda.ts
import * as path from 'path'; import { S3 } from 'aws-sdk'; // eslint-disable-line import/no-extraneous-dependencies const s3 = new S3(); export async function handler(assetHashes: string[]) { if (!process.env.BUCKET_NAME) { throw new Error('Missing BUCKET_NAME'); } let deleted = 0; let reclaimed = 0; let nextToken: string | undefined; let finished = false; while (!finished) { const response = await s3.listObjectsV2({ Bucket: process.env.BUCKET_NAME, ContinuationToken: nextToken, }).promise(); const toDelete = response.Contents?.filter(x => { let pred = x.Key && !assetHashes.includes(path.basename(x.Key)); if (process.env.RETAIN_MILLISECONDS) { const limitDate = new Date(Date.now() - parseInt(process.env.RETAIN_MILLISECONDS)); pred = pred && x.LastModified && x.LastModified < limitDate; } return pred; }); if (toDelete && toDelete.length !== 0) { if (process.env.RUN) { await s3.deleteObjects({ Bucket: process.env.BUCKET_NAME, Delete: { Objects: toDelete.map(x => ({ Key: x.Key! })), }, }).promise(); } deleted += toDelete.length; reclaimed += toDelete.reduce((acc, x) => acc + (x.Size ?? 0), 0); } nextToken = response.NextContinuationToken; if (nextToken === undefined) { finished = true; } } return { Deleted: deleted, Reclaimed: reclaimed, }; }
vumdao/cloudstructs
src/slack-app/provider.lambda.ts
<reponame>vumdao/cloudstructs /* eslint-disable no-console */ import { OnEventRequest, OnEventResponse } from 'aws-cdk-lib/custom-resources/lib/provider-framework/types'; import { SecretsManager } from 'aws-sdk'; // eslint-disable-line import/no-extraneous-dependencies import got from 'got'; interface SlackSecret { accessToken?: string; refreshToken?: string; exp?: number; } interface RotateResponse { ok: boolean; error?: string; token: string; refresh_token: string; team_id: string; user_id: string; iat: number; exp: number; } interface ManifestCreateRequest { manifest: string; } interface ManifestUpdateRequest extends ManifestCreateRequest { app_id: string; } interface ManifestDeleteRequest { app_id: string; } type ManifestRequest = ManifestCreateRequest | ManifestUpdateRequest | ManifestDeleteRequest; interface ManifestResponse { ok: boolean; error?: string; errors?: { message: string; pointer: string; }[]; app_id?: string; credentials?: { client_id: string; client_secret: string; verification_token: string; signing_secret: string; }; } const secretsmanager = new SecretsManager({ apiVersion: '2017-10-17' }); const slackClient = got.extend({ prefixUrl: 'https://slack.com/api', }); export async function handler(event: OnEventRequest): Promise<OnEventResponse> { console.log('Event: %j', event); const data = await secretsmanager.getSecretValue({ SecretId: event.ResourceProperties.configurationTokenSecretArn, }).promise(); if (!data.SecretString) { throw new Error('No secret string found in configuration token secret'); } const secret: SlackSecret = JSON.parse(data.SecretString); let accessToken = secret.accessToken; if (!accessToken || isExpired(secret.exp ?? 0)) { if (!secret.refreshToken) { throw new Error('No refresh token found in configuration token secret'); } console.log('Refreshing access token'); const rotate = await slackClient.get('tooling.tokens.rotate', { searchParams: { refresh_token: secret.refreshToken }, }).json<RotateResponse>(); if (!rotate.ok) { throw new Error(`Failed to refresh access token: ${rotate.error}`); } console.log('Access token refreshed'); accessToken = rotate.token; console.log('Saving access token'); const putSecretValue = await secretsmanager.putSecretValue({ SecretId: event.ResourceProperties.configurationTokenSecretArn, SecretString: JSON.stringify({ accessToken, refreshToken: rotate.refresh_token, exp: rotate.exp, }), }).promise(); console.log(`Successfully saved access token in secret ${putSecretValue.ARN}`); } const operation = event.RequestType.toLowerCase(); const request = getManifestRequest(event); console.log(`Calling ${operation} manifest API: %j`, request); const response = await slackClient.post(`apps.manifest.${operation}`, { headers: { Authorization: `Bearer ${accessToken}` }, json: request, }).json<ManifestResponse>(); if (!response.ok) { const errors = response.errors ? response.errors.map((err) => `${err.message} at ${err.pointer}`).join('\n') : ''; throw new Error(`Failed to ${operation} manifest: ${response.error}.${errors ? `\n${errors}}` : ''}`); } console.log(`Successfully ${operation}d Slack app ${event.PhysicalResourceId ?? response.app_id}`); if (event.RequestType === 'Create' && response.credentials) { console.log('Saving app credentials'); const putSecretValue = await secretsmanager.putSecretValue({ SecretId: event.ResourceProperties.credentialsSecretArn, SecretString: JSON.stringify({ appId: response.app_id, clientId: response.credentials.client_id, clientSecret: response.credentials.client_secret, verificationToken: response.credentials.verification_token, signingSecret: response.credentials.signing_secret, }), }).promise(); console.log(`Successfully saved app credentials in secret ${putSecretValue.ARN}`); } return { PhysicalResourceId: response.app_id, Data: { appId: response.app_id, }, }; } function isExpired(iat: number) { return (iat - (Date.now() / 1000)) < 0; } function getManifestRequest(event: OnEventRequest): ManifestRequest { switch (event.RequestType) { case 'Create': return { manifest: event.ResourceProperties.manifest, }; case 'Update': return { app_id: event.PhysicalResourceId, manifest: event.ResourceProperties.manifest, }; case 'Delete': return { app_id: event.PhysicalResourceId!, }; } }