fix: Deepsource style fixes.

This commit is contained in:
Sam Tolmay 2023-10-14 16:10:17 +02:00
parent 2086f5d2e8
commit e0804b8799
No known key found for this signature in database
88 changed files with 201 additions and 198 deletions

View File

@ -18,7 +18,7 @@ import createAuthorize from './createAuthorize.js';
import { ServerError } from './errors.js';
test('authorize public object', async () => {
test('authorize public object', () => {
const auth = { public: true };
let authorize = createAuthorize({});
expect(authorize({ auth })).toBe(true);
@ -27,7 +27,7 @@ test('authorize public object', async () => {
expect(authorize({ auth })).toBe(true);
});
test('authorize protected object, no roles', async () => {
test('authorize protected object, no roles', () => {
const auth = { public: false };
let authorize = createAuthorize({});
@ -37,7 +37,7 @@ test('authorize protected object, no roles', async () => {
expect(authorize({ auth })).toBe(true);
});
test('authorize role protected object', async () => {
test('authorize role protected object', () => {
const auth = { public: false, roles: ['role1'] };
let authorize = createAuthorize({});
@ -59,7 +59,7 @@ test('authorize role protected object', async () => {
expect(authorize({ auth })).toBe(true);
});
test('invalid auth config', async () => {
test('invalid auth config', () => {
const authorize = createAuthorize({});
expect(() => authorize({ auth: { other: 'value' } })).toThrow(ServerError);
expect(() => authorize({ auth: {} })).toThrow(ServerError);

View File

@ -30,7 +30,7 @@ function createRedirectCallback({ authConfig, plugins }) {
}
const [plugin] = redirectCallbackPlugins;
async function redirectCallback({ url, baseUrl }) {
function redirectCallback({ url, baseUrl }) {
return plugin.fn({
properties: plugin.properties ?? {},
baseUrl,

View File

@ -27,7 +27,7 @@ async function mockStartUpImp({ context, options = {} }) {
log: jest.fn(),
};
context.configDirectory = options.configDirectory || 'configDirectory';
context.configDirectory = options.configDirectory ?? 'configDirectory';
context.cliConfig = {};
context.lowdefyVersion = 'lowdefyVersion';

View File

@ -35,7 +35,7 @@ async function logError({ error, context = {} }) {
stack: error.stack,
},
});
} catch (error) {
} catch (_) {
// pass
}
}

View File

@ -35,7 +35,7 @@ jest.unstable_mockModule('decompress', () => {
jest.unstable_mockModule('axios', () => {
return {
default: {
get: (url) => {
get(url) {
if (url === 'https://registry.npmjs.org/valid-package') {
return Promise.resolve({
data: {
@ -89,6 +89,7 @@ jest.unstable_mockModule('axios', () => {
if (url === 'https://registry.npmjs.org/undefined') {
return;
}
return;
},
},
};

View File

@ -49,7 +49,7 @@
import net from 'net';
async function findPort() {
function findPort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.on('error', reject);

View File

@ -55,6 +55,7 @@ test('getCliJson, file exists', async () => {
if (filePath === path.resolve(process.cwd(), '.lowdefy/cli.json')) {
return '{"appId": "appId"}';
}
return null;
});
const res = await getCliJson({ configDirectory });
expect(res).toEqual({ appId: 'appId' });

View File

@ -18,12 +18,12 @@ import { jest } from '@jest/globals';
import path from 'path';
jest.unstable_mockModule('./getLowdefyYaml.js', () => ({
default: jest.fn(async () =>
default: jest.fn(() =>
Promise.resolve({ cliConfig: { cliConfig: true }, lowdefyVersion: 'lowdefyVersion' })
),
}));
jest.unstable_mockModule('./getCliJson.js', () => ({
default: async () => Promise.resolve({ appId: 'appId' }),
default: () => Promise.resolve({ appId: 'appId' }),
}));
jest.unstable_mockModule('./createPrint.js', () => ({
default: () => ({

View File

@ -35,7 +35,7 @@ const ErrorPage = ({ code, description, message, name }) => (
paddingRight: 30,
}}
>
{code || 500}
{code ?? 500}
</div>
<div
style={{
@ -46,9 +46,9 @@ const ErrorPage = ({ code, description, message, name }) => (
}}
>
<div style={{ fontSize: '1.3em', fontWeight: '300', paddingBottom: 10 }}>
{name || 'Error'}
{name ?? 'Error'}
</div>
<div style={{ fontSize: '0.9em' }}>{message || 'An error has occurred.'}</div>
<div style={{ fontSize: '0.9em' }}>{message ?? 'An error has occurred.'}</div>
<div style={{ fontSize: '0.9em' }}>{description}</div>
<div style={{ paddingTop: 20 }}>
<a href="/">Return to home page</a>

View File

@ -9,7 +9,7 @@ const createLinkComponent = (lowdefy, Link) => {
id={id}
className={className}
rel={rel}
aria-label={ariaLabel || 'back'}
aria-label={ariaLabel ?? 'back'}
onClick={(...params) => {
lowdefy._internal.router.back();
onClick(...params);
@ -36,15 +36,15 @@ const createLinkComponent = (lowdefy, Link) => {
id={id}
aria-label={ariaLabel}
className={className}
href={href || `${url}${query ? `?${query}` : ''}`}
rel={rel || (newTab && 'noopener noreferrer')}
href={href ?? `${url}${query ? `?${query}` : ''}`}
rel={rel ?? (newTab && 'noopener noreferrer')}
target={newTab && '_blank'}
onClick={async (...params) => {
await onClick(...params);
return true;
}}
>
{type.isFunction(children) ? children(pageId || url || id) : children}
{type.isFunction(children) ? children(pageId ?? url ?? id) : children}
</a>
);
};
@ -74,14 +74,14 @@ const createLinkComponent = (lowdefy, Link) => {
href={`${window.location.origin}${lowdefy.basePath}${pathname}${
query ? `?${query}` : ''
}`}
rel={rel || 'noopener noreferrer'}
rel={rel ?? 'noopener noreferrer'}
target="_blank"
onClick={async (...params) => {
await onClick(...params);
return true;
}}
>
{type.isFunction(children) ? children(pageId || url || id) : children}
{type.isFunction(children) ? children(pageId ?? url ?? id) : children}
</a>
);
}
@ -100,7 +100,7 @@ const createLinkComponent = (lowdefy, Link) => {
onClick(...params);
}}
>
{type.isFunction(children) ? children(pageId || url || id) : children}
{type.isFunction(children) ? children(pageId ?? url ?? id) : children}
</Link>
);
};

View File

@ -53,7 +53,7 @@ class Events {
this.events[name] = this.initEvent(actions);
}
async triggerEvent({ name, event, progress }) {
triggerEvent({ name, event, progress }) {
const eventDescription = this.events[name];
const result = {
blockId: this.block.blockId,

View File

@ -50,7 +50,7 @@ class Requests {
return Promise.all(requests);
}
async callRequest({ actions, arrayIndices, blockId, event, requestId }) {
callRequest({ actions, arrayIndices, blockId, event, requestId }) {
const requestConfig = this.requestConfig[requestId];
if (!this.context.requests[requestId]) {
this.context.requests[requestId] = [];

View File

@ -34,7 +34,7 @@ const getActions = () => {
return {
ActionSync: jest.fn(({ params }) => params),
ActionAsync: jest.fn(async ({ params }) => {
await timeout(params.ms || 1);
await timeout(params.ms ?? 1);
return params;
}),
ActionError: jest.fn(() => {
@ -44,7 +44,7 @@ const getActions = () => {
throw new Error('Test catch error');
}),
ActionAsyncError: jest.fn(async ({ params }) => {
await timeout(params.ms || 1);
await timeout(params.ms ?? 1);
throw new Error('Test error');
}),
};

View File

@ -82,7 +82,7 @@ const getLowdefy = () => {
return testLowdefy;
};
test('page is required input', async () => {
test('page is required input', () => {
const resetContext = { reset: true, setReset: () => {} };
const lowdefy = getLowdefy();
expect(() => getContext({ lowdefy, resetContext })).toThrow(
@ -90,7 +90,7 @@ test('page is required input', async () => {
);
});
test('memoize context and reset', async () => {
test('memoize context and reset', () => {
const lowdefy = getLowdefy();
const page = {
id: 'pageId',
@ -132,7 +132,7 @@ test('create context', () => {
expect(context._internal.update).toBeDefined();
});
test('create context, initialize input', async () => {
test('create context, initialize input', () => {
const resetContext = { reset: true, setReset: () => {} };
const lowdefy = getLowdefy();
const page = {
@ -144,7 +144,7 @@ test('create context, initialize input', async () => {
expect(context._internal.lowdefy.inputs['page:pageId']).toEqual({});
});
test('update memoized context', async () => {
test('update memoized context', () => {
const lowdefy = getLowdefy();
const page = {
id: 'pageId',

View File

@ -20,7 +20,7 @@ import CallMethod from './CallMethod.js';
const mockCallMethod = jest.fn();
const methods = { callMethod: mockCallMethod };
test('CallMethod mock test', async () => {
test('CallMethod mock test', () => {
CallMethod({
methods,
params: { blockId: 'blockId', method: 'method', args: ['arg1', 'arg2'] },

View File

@ -14,7 +14,7 @@
limitations under the License.
*/
async function CopyToClipboard({ globals, params }) {
function CopyToClipboard({ globals, params }) {
const { window } = globals;
const { copy } = params;
window.navigator.clipboard.writeText(copy);

View File

@ -27,7 +27,7 @@ const window = {
const globals = { window };
test('CopyToClipboard mock test', async () => {
test('CopyToClipboard mock test', () => {
CopyToClipboard({
globals,
params: { copy: 'Copy content.' },

View File

@ -20,7 +20,7 @@ import Login from './Login.js';
const mockLogin = jest.fn();
const methods = { login: mockLogin };
test('Login action invocation', async () => {
test('Login action invocation', () => {
Login({ methods, params: { providerId: 'provider' } });
expect(mockLogin.mock.calls).toEqual([[{ providerId: 'provider' }]]);
});

View File

@ -20,7 +20,7 @@ import Request from './Request.js';
const mockRequest = jest.fn();
const methods = { request: mockRequest };
test('Request action invocation', async () => {
test('Request action invocation', () => {
Request({ methods, params: 'requestId' });
expect(mockRequest.mock.calls).toEqual([['requestId']]);
});

View File

@ -20,7 +20,7 @@ import Reset from './Reset.js';
const mockReset = jest.fn();
const methods = { reset: mockReset };
test('Reset action invocation', async () => {
test('Reset action invocation', () => {
Reset({ methods });
expect(mockReset.mock.calls).toEqual([[]]);
});

View File

@ -20,7 +20,7 @@ import ResetValidation from './ResetValidation.js';
const mockResetValidation = jest.fn();
const methods = { resetValidation: mockResetValidation };
test('ResetValidation action invocation', async () => {
test('ResetValidation action invocation', () => {
ResetValidation({ methods, params: 'blockId' });
expect(mockResetValidation.mock.calls).toEqual([['blockId']]);
});

View File

@ -36,13 +36,13 @@ const window = {
const globals = { document, window };
test('ScrollTo with no params', async () => {
test('ScrollTo with no params', () => {
expect(() => ScrollTo({ globals })).toThrow(
'Invalid ScrollTo, check action params. Received "undefined".'
);
});
test('ScrollTo with no blockId', async () => {
test('ScrollTo with no blockId', () => {
ScrollTo({ globals, params: { behavior: 'smooth', top: 0 } });
expect(mockWindowScrollTo.mock.calls).toEqual([
[
@ -54,7 +54,7 @@ test('ScrollTo with no blockId', async () => {
]);
});
test('ScrollTo with blockId', async () => {
test('ScrollTo with blockId', () => {
mockDocGetElementById.mockImplementation((id) => {
if (id === 'blockId') return { id, scrollIntoView: mockElemScrollIntoView };
});
@ -63,7 +63,7 @@ test('ScrollTo with blockId', async () => {
expect(mockElemScrollIntoView.mock.calls).toEqual([[undefined]]);
});
test('ScrollTo with blockId and options', async () => {
test('ScrollTo with blockId and options', () => {
mockDocGetElementById.mockImplementation((id) => {
if (id === 'blockId') return { id, scrollIntoView: mockElemScrollIntoView };
});
@ -72,7 +72,7 @@ test('ScrollTo with blockId and options', async () => {
expect(mockElemScrollIntoView.mock.calls).toEqual([[{ behavior: 'smooth' }]]);
});
test('ScrollTo with blockId, block not found', async () => {
test('ScrollTo with blockId, block not found', () => {
mockDocGetElementById.mockImplementation((id) => {
if (id === 'blockId') return { id, scrollIntoView: mockElemScrollIntoView };
});

View File

@ -20,7 +20,7 @@ import SetGlobal from './SetGlobal.js';
const mockSetGlobal = jest.fn();
const methods = { setGlobal: mockSetGlobal };
test('SetGlobal action invocation', async () => {
test('SetGlobal action invocation', () => {
SetGlobal({ methods, params: { key: 'value' } });
expect(mockSetGlobal.mock.calls).toEqual([[{ key: 'value' }]]);
});

View File

@ -20,7 +20,7 @@ import SetState from './SetState.js';
const mockSetState = jest.fn();
const methods = { setState: mockSetState };
test('SetState action invocation', async () => {
test('SetState action invocation', () => {
SetState({ methods, params: { key: 'value' } });
expect(mockSetState.mock.calls).toEqual([[{ key: 'value' }]]);
});

View File

@ -20,7 +20,7 @@ import Validate from './Validate.js';
const mockValidate = jest.fn();
const methods = { validate: mockValidate };
test('Validate action invocation', async () => {
test('Validate action invocation', () => {
Validate({ methods, params: 'blockId' });
expect(mockValidate.mock.calls).toEqual([['blockId']]);
});

View File

@ -33,11 +33,11 @@ test('wait set ms before continuing', async () => {
expect(flag).toBe(true);
});
test('Wait params undefined', async () => {
test('Wait params undefined', () => {
expect(() => Wait({})).toThrow('Wait action "ms" param should be an integer.');
});
test('Wait params.ms not an integer', async () => {
test('Wait params.ms not an integer', () => {
expect(() => Wait({ params: { key: 'value' } })).toThrow(
'Wait action "ms" param should be an integer.'
);

View File

@ -24,7 +24,7 @@ const AgGridAlpine = ({ blockId, events, loading, methods, properties }) => (
id={blockId}
className={`ag-theme-alpine ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -24,7 +24,7 @@ const AgGridAlpineDark = ({ blockId, events, loading, methods, properties }) =>
id={blockId}
className={`ag-theme-alpine-dark ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -24,7 +24,7 @@ const AgGridBalham = ({ blockId, events, loading, methods, properties }) => (
id={blockId}
className={`ag-theme-balham ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -24,7 +24,7 @@ const AgGridBalhamDark = ({ blockId, events, loading, methods, properties }) =>
id={blockId}
className={`ag-theme-balham-dark ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -33,7 +33,7 @@ const AgGridInputAlpine = ({
id={blockId}
className={`ag-theme-alpine ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -33,7 +33,7 @@ const AgGridInputAlpineDark = ({
id={blockId}
className={`ag-theme-alpine-dark ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -33,7 +33,7 @@ const AgGridInputBalham = ({
id={blockId}
className={`ag-theme-balham ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -33,7 +33,7 @@ const AgGridInputBalhamDark = ({
id={blockId}
className={`ag-theme-balham-dark ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -33,7 +33,7 @@ const AgGridInputMaterial = ({
id={blockId}
className={`ag-theme-material ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -24,7 +24,7 @@ const AgGridMaterial = ({ blockId, events, loading, methods, properties }) => (
id={blockId}
className={`ag-theme-material ${methods.makeCssClass({
width: '100%',
height: properties.height || 500,
height: properties.height ?? 500,
...properties.style,
})}`}
>

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -52,7 +52,7 @@ const AutoCompleteInput = ({
className={methods.makeCssClass([{ width: '100%' }, properties.inputStyle])}
defaultOpen={properties.defaultOpen}
disabled={properties.disabled || loading}
placeholder={properties.placeholder || 'Type or select item'}
placeholder={properties.placeholder ?? 'Type or select item'}
allowClear={properties.allowClear !== false}
size={properties.size}
filterOption={(input, option) =>

View File

@ -33,11 +33,11 @@ const ConfirmModal = ({ blockId, events, content, components: { Icon }, methods,
title: renderHtml({ html: properties.title, methods }),
bodyStyle: methods.makeCssClass(properties.bodyStyle, true),
content:
(content.content && content.content()) ||
(content.content && content.content()) ??
renderHtml({ html: properties.content, methods }),
className: methods.makeCssClass(properties.modalStyle),
closable: properties.closable,
okText: properties.okText || 'Ok',
okText: properties.okText ?? 'Ok',
okButtonProps: properties.okButton?.icon
? {
...properties.okButton,
@ -62,10 +62,10 @@ const ConfirmModal = ({ blockId, events, content, components: { Icon }, methods,
),
}
: properties.cancelButton,
cancelText: properties.cancelText || 'Cancel',
centered: properties.centered || false,
cancelText: properties.cancelText ?? 'Cancel',
centered: properties.centered ?? false,
mask: properties.mask !== undefined ? properties.mask : true,
maskClosable: properties.maskClosable || false,
maskClosable: properties.maskClosable ?? false,
width: properties.width,
zIndex: properties.zIndex,
onOk: async () => {

View File

@ -73,7 +73,7 @@ const ControlledListBlock = ({
properties={{
icon: 'AiOutlinePlus',
size: properties.size,
title: get(properties, 'addItemButton.title ') || 'Add Item',
title: get(properties, 'addItemButton.title ') ?? 'Add Item',
type: 'default',
...properties.addItemButton,
}}
@ -95,7 +95,7 @@ const ControlledListBlock = ({
properties={{
icon: 'AiOutlinePlus',
size: properties.size,
title: get(properties, 'addItemButton.title ') || 'Add Item',
title: get(properties, 'addItemButton.title ') ?? 'Add Item',
type: 'dashed',
...properties.addItemButton,
}}
@ -105,7 +105,7 @@ const ControlledListBlock = ({
)
}
bordered
locale={{ emptyText: properties.noDataTitle || 'No Items' }}
locale={{ emptyText: properties.noDataTitle ?? 'No Items' }}
dataSource={list}
renderItem={(item, i) => (
<List.Item

View File

@ -62,22 +62,22 @@ const DateRangeSelector = ({
className={methods.makeCssClass([{ width: '100%' }, properties.inputStyle])}
disabled={properties.disabled || loading}
disabledDate={disabledDate(properties.disabledDates)}
format={properties.format || 'YYYY-MM-DD'}
format={properties.format ?? 'YYYY-MM-DD'}
getPopupContainer={() => document.getElementById(`${blockId}_popup`)}
separator={properties.separator || '~'}
separator={properties.separator ?? '~'}
size={properties.size}
status={validation.status}
placeholder={
(type.isArray(properties.placeholder) && [
properties.placeholder[0] || 'Start Date',
properties.placeholder[1] || 'End Date',
]) || ['Start Date', 'End Date']
properties.placeholder[0] ?? 'Start Date',
properties.placeholder[1] ?? 'End Date',
]) ?? ['Start Date', 'End Date']
}
suffixIcon={
<Icon
blockId={`${blockId}_suffixIcon`}
events={events}
properties={properties.suffixIcon || 'AiOutlineCalendar'}
properties={properties.suffixIcon ?? 'AiOutlineCalendar'}
/>
}
onChange={(newVal) => {

View File

@ -53,9 +53,9 @@ const DateSelector = ({
bordered={properties.bordered}
className={methods.makeCssClass([{ width: '100%' }, properties.inputStyle])}
disabled={properties.disabled || loading}
format={properties.format || 'YYYY-MM-DD'}
format={properties.format ?? 'YYYY-MM-DD'}
getPopupContainer={() => document.getElementById(`${blockId}_popup`)}
placeholder={properties.placeholder || 'Select Date'}
placeholder={properties.placeholder ?? 'Select Date'}
showToday={properties.showToday}
size={properties.size}
status={validation.status}
@ -63,7 +63,7 @@ const DateSelector = ({
<Icon
blockId={`${blockId}_suffixIcon`}
events={events}
properties={properties.suffixIcon || 'AiOutlineCalendar'}
properties={properties.suffixIcon ?? 'AiOutlineCalendar'}
/>
}
disabledDate={disabledDate(properties.disabledDates)}

View File

@ -72,9 +72,9 @@ const DateTimeSelector = ({
className={methods.makeCssClass([{ width: '100%' }, properties.inputStyle])}
disabled={properties.disabled || loading}
disabledDate={disabledDate(properties.disabledDates)}
format={properties.format || 'YYYY-MM-DD HH:mm'}
format={properties.format ?? 'YYYY-MM-DD HH:mm'}
getPopupContainer={() => document.getElementById(`${blockId}_popup`)}
placeholder={properties.placeholder || 'Select Date & Time'}
placeholder={properties.placeholder ?? 'Select Date & Time'}
showNow={properties.showNow}
showToday={properties.showToday}
size={properties.size}
@ -83,14 +83,14 @@ const DateTimeSelector = ({
<Icon
blockId={`${blockId}_suffixIcon`}
events={events}
properties={properties.suffixIcon || 'AiOutlineCalendar'}
properties={properties.suffixIcon ?? 'AiOutlineCalendar'}
/>
}
showTime={{
format: properties.timeFormat || 'HH:mm',
hourStep: properties.hourStep || 1,
minuteStep: properties.minuteStep || 5,
secondStep: properties.secondStep || 30,
format: properties.timeFormat ?? 'HH:mm',
hourStep: properties.hourStep ?? 1,
minuteStep: properties.minuteStep ?? 5,
secondStep: properties.secondStep ?? 30,
}}
onChange={onChange}
onSelect={

View File

@ -27,7 +27,7 @@ const labelLogic = ({
required = false,
validation = {
messages: [],
status: null, // enum: [null, 'success', 'warning', 'error', 'validating']
status: null, // enum: [null, 'success', 'warning', 'error', 'validating'
},
}) => {
const wrapperCol = getWrapperCol(properties, properties.inline);
@ -45,8 +45,8 @@ const labelLogic = ({
label = label.replace(/[:|]\s*$/u, '');
}
const rowClassName = classNames({
['ant-form-item']: true,
['ant-form-item-with-help']: false,
'ant-form-item': true,
'ant-form-item-with-help': false,
[methods.makeCssClass({
flexWrap: properties.inline && 'inherit', // wrap extra content below input
marginBottom: 0,
@ -54,8 +54,8 @@ const labelLogic = ({
});
const labelColClassName = classNames({
['ant-form-item-label']: true,
['ant-form-item-label-left']: properties.align === 'left' || !properties.align, // default align left
'ant-form-item-label': true,
'ant-form-item-label-left': properties.align === 'left' || !properties.align, // default align left
[methods.makeCssClass({
overflow: properties.inline && 'inherit', // wrap label content below input
whiteSpace: !properties.inline && 'normal', // set label title wrap for long labels
@ -65,8 +65,8 @@ const labelLogic = ({
});
const labelClassName = classNames({
['ant-form-item-required']: required,
['ant-form-item-no-colon']: properties.colon === false,
'ant-form-item-required': required,
'ant-form-item-no-colon': properties.colon === false,
[methods.makeCssClass([
{
height: 'fit-content !important',
@ -90,10 +90,10 @@ const labelLogic = ({
});
const feedbackClassName = classNames({
['ant-form-item-explain-success']: validation.status === 'success',
['ant-form-item-explain-warning']: validation.status === 'warning',
['ant-form-item-explain-error']: validation.status === 'error',
['ant-form-item-explain-validating']: validation.status === 'validating',
'ant-form-item-explain-success': validation.status === 'success',
'ant-form-item-explain-warning': validation.status === 'warning',
'ant-form-item-explain-error': validation.status === 'error',
'ant-form-item-explain-validating': validation.status === 'validating',
[methods.makeCssClass([
{
marginTop: properties.size === 'small' ? -4 : 0, // in size small reduce extra top margin
@ -104,10 +104,10 @@ const labelLogic = ({
const iconClassName = classNames({
'ant-form-item-feedback-icon': true,
['ant-form-item-feedback-icon-success']: validation.status === 'success',
['ant-form-item-feedback-icon-warning']: validation.status === 'warning',
['ant-form-item-feedback-icon-error']: validation.status === 'error',
['ant-form-item-feedback-icon-validating']: validation.status === 'validating',
'ant-form-item-feedback-icon-success': validation.status === 'success',
'ant-form-item-feedback-icon-warning': validation.status === 'warning',
'ant-form-item-feedback-icon-error': validation.status === 'error',
'ant-form-item-feedback-icon-validating': validation.status === 'validating',
'ldf-feedback-icon': true,
});

View File

@ -172,7 +172,7 @@ const MenuComp = ({
<Menu.Divider
key={`${subLink.id}_${k}`}
className={methods.makeCssClass([subLink.style])}
dashed={subLink.properties && subLink.properties.dashed}
dashed={subLink.properties?.dashed}
/>
);
}

View File

@ -22,16 +22,16 @@ import { blockDefaultProps, renderHtml } from '@lowdefy/block-utils';
const MessageBlock = ({ blockId, components: { Icon }, events, methods, properties }) => {
useEffect(() => {
methods.registerMethod('open', (args = {}) => {
return message[args.status || properties.status || 'success']({
return message[args.status ?? properties.status ?? 'success']({
id: `${blockId}_message`,
content: renderHtml({ html: args.content || properties.content || blockId, methods }),
content: renderHtml({ html: args.content ?? properties.content ?? blockId, methods }),
duration: type.isNone(args.duration) ? properties.duration : args.duration,
onClose: () => methods.triggerEvent({ name: 'onClose' }),
icon: (args.icon || properties.icon) && (
icon: (args.icon ?? properties.icon) && (
<Icon
blockId={`${blockId}_icon`}
events={events}
properties={args.icon || properties.icon}
properties={args.icon ?? properties.icon}
/>
),
className: methods.makeCssClass(properties.messageStyle),

View File

@ -53,7 +53,7 @@ const ModalBlock = ({ blockId, content, events, methods, properties }) => {
afterClose={() => methods.triggerEvent({ name: 'afterClose' })}
bodyStyle={methods.makeCssClass(properties.bodyStyle, true)}
cancelButtonProps={properties.cancelButtonProps}
cancelText={properties.cancelText || 'Cancel'}
cancelText={properties.cancelText ?? 'Cancel'}
centered={!!properties.centered}
closable={properties.closable !== undefined ? properties.closable : true}
confirmLoading={get(events, 'onOk.loading')}
@ -61,8 +61,8 @@ const ModalBlock = ({ blockId, content, events, methods, properties }) => {
maskClosable={properties.maskClosable !== undefined ? properties.maskClosable : true}
maskStyle={methods.makeCssClass(properties.maskStyle, true)}
okButtonProps={properties.okButtonProps}
okText={properties.okText || 'Ok'}
okType={properties.okButtonType || 'primary'}
okText={properties.okText ?? 'Ok'}
okType={properties.okButtonType ?? 'primary'}
title={renderHtml({ html: properties.title, methods })}
visible={openState}
width={properties.width}

View File

@ -56,9 +56,9 @@ const MonthSelector = ({
className={methods.makeCssClass([{ width: '100%' }, properties.inputStyle])}
disabled={properties.disabled || loading}
disabledDate={disabledDate(properties.disabledDates)}
format={properties.format || 'YYYY-MM'}
format={properties.format ?? 'YYYY-MM'}
getPopupContainer={() => document.getElementById(`${blockId}_popup`)}
placeholder={properties.placeholder || 'Select Month'}
placeholder={properties.placeholder ?? 'Select Month'}
size={properties.size}
status={validation.status}
value={type.isDate(value) ? moment.utc(value).startOf('month') : null}
@ -66,7 +66,7 @@ const MonthSelector = ({
<Icon
blockId={`${blockId}_suffixIcon`}
events={events}
properties={properties.suffixIcon || 'AiOutlineCalendar'}
properties={properties.suffixIcon ?? 'AiOutlineCalendar'}
/>
}
onChange={(newVal) => {

View File

@ -35,9 +35,9 @@ const tagRender = (props, option, methods, components) => {
onClose={onClose}
properties={{
title: label,
...(option?.tag || {}),
...(option?.tag ?? {}),
closable,
style: { marginRight: 3, ...(option.tag?.style || {}) },
style: { marginRight: 3, ...(option.tag?.style ?? {}) },
}}
/>
);
@ -55,7 +55,7 @@ const MultipleSelector = ({
value,
}) => {
const [fetchState, setFetch] = useState(false);
const uniqueValueOptions = getUniqueValues(properties.options || []);
const uniqueValueOptions = getUniqueValues(properties.options ?? []);
return (
<Label
blockId={blockId}

View File

@ -89,12 +89,12 @@ const RatingSlider = ({
if (type.isString(propertiesIconMax)) {
propertiesIconMax = { name: propertiesIconMax };
}
const minMax = [get(properties, 'max', { default: 10 }), properties.min || 0].sort(
const minMax = [get(properties, 'max', { default: 10 }), properties.min ?? 0].sort(
(a, b) => a - b
);
// round to fix floating point error
const minMin = parseFloat((minMax[0] - (properties.step || 1)).toPrecision(8));
const minMin = parseFloat((minMax[0] - (properties.step ?? 1)).toPrecision(8));
const validationColor =
validation.status === 'error' ? '#ff4d4f' : validation.status === 'warning' ? '#faad14' : null;
return (
@ -123,7 +123,7 @@ const RatingSlider = ({
properties={mergeObjects([
{
label: { disabled: true },
options: [{ value: true, label: properties.notApplicableLabel || 'N/A' }],
options: [{ value: true, label: properties.notApplicableLabel ?? 'N/A' }],
color: properties.color,
disabled: properties.disabled || loading,
},
@ -135,7 +135,7 @@ const RatingSlider = ({
setValue: (val) => {
if (val[0] === true) {
unCheck(true);
methods.setValue(properties.notApplicableLabel || 'N/A');
methods.setValue(properties.notApplicableLabel ?? 'N/A');
} else {
unCheck(false);
}
@ -196,15 +196,15 @@ const RatingSlider = ({
}
tipFormatter={(val) => `${val}`}
marks={
properties.marks ||
properties.marks ??
(get(properties, 'showMarks', { default: true })
? includeMarks(minMax, minMin, properties.step || 1)
? includeMarks(minMax, minMin, properties.step ?? 1)
: undefined)
}
min={minMin}
max={minMax[1]}
range={false}
step={properties.step || 1}
step={properties.step ?? 1}
onChange={(val) => {
if (val === minMin) {
methods.setValue(null);

View File

@ -42,7 +42,7 @@ const StatisticBlock = ({ blockId, components: { Icon }, events, properties, met
properties={properties.prefixIcon}
/>
) : (
properties.prefix || ''
properties.prefix ?? ''
)
}
suffix={
@ -53,7 +53,7 @@ const StatisticBlock = ({ blockId, components: { Icon }, events, properties, met
properties={properties.suffixIcon}
/>
) : (
properties.suffix || ''
properties.suffix ?? ''
)
}
{...additionalProps}

View File

@ -47,13 +47,13 @@ const TabsBlock = ({ blockId, components: { Icon }, events, content, methods, pr
return (
<Tabs
animated={properties.animated !== undefined ? properties.animated : true}
defaultActiveKey={properties.defaultActiveKey || tabs[0].key}
defaultActiveKey={properties.defaultActiveKey ?? tabs[0].key}
id={blockId}
onChange={(activeKey) => methods.triggerEvent({ name: 'onChange', event: { activeKey } })}
size={properties.size || 'default'}
size={properties.size ?? 'default'}
tabBarStyle={methods.makeCssClass(properties.tabBarStyle, true)}
tabPosition={properties.tabPosition || 'top'}
type={properties.tabType || 'line'}
tabPosition={properties.tabPosition ?? 'top'}
type={properties.tabType ?? 'line'}
onTabScroll={({ direction }) =>
methods.triggerEvent({ name: 'onTabScroll', event: { direction } })
}
@ -69,7 +69,7 @@ const TabsBlock = ({ blockId, components: { Icon }, events, content, methods, pr
{tab.icon && (
<Icon blockId={`${blockId}_icon`} events={events} properties={tab.icon} />
)}
{tab.title || tab.key}
{tab.title ?? tab.key}
</span>
}
>

View File

@ -45,21 +45,21 @@ const TimelineList = ({ blockId, components: { Icon }, events, list, methods, pr
{...other}
>
{(list || []).map((child, i) => {
let icon = serializer.copy(get(value, `${i}.${properties.iconField || 'icon'}`));
let style = get(value, `${i}.${properties.styleField || 'style'}`);
let icon = serializer.copy(get(value, `${i}.${properties.iconField ?? 'icon'}`));
let style = get(value, `${i}.${properties.styleField ?? 'style'}`);
if (type.isString(icon)) {
icon = { name: icon };
}
if (!type.isObject(style)) {
style = {};
}
const color = get(value, `${i}.${properties.colorField || 'color'}`);
const color = get(value, `${i}.${properties.colorField ?? 'color'}`);
return (
<Timeline.Item
key={`${blockId}_${i}`}
color={color}
position={get(value, `${i}.${properties.positionField || 'position'}`)}
label={get(value, `${i}.${properties.labelField || 'label'}`)}
position={get(value, `${i}.${properties.positionField ?? 'position'}`)}
label={get(value, `${i}.${properties.labelField ?? 'label'}`)}
dot={
icon && (
<Icon

View File

@ -31,7 +31,7 @@ const TooltipBlock = ({ blockId, content, properties, methods }) => (
mouseEnterDelay={properties.mouseEnterDelay}
mouseLeaveDelay={properties.mouseLeaveDelay}
placement={properties.placement}
trigger={properties.trigger || 'hover'}
trigger={properties.trigger ?? 'hover'}
zIndex={properties.zIndex}
onVisibleChange={() => methods.triggerEvent({ name: 'onVisibleChange' })}
>

View File

@ -56,16 +56,16 @@ const WeekSelector = ({
className={methods.makeCssClass([{ width: '100%' }, properties.inputStyle])}
disabled={properties.disabled || loading}
disabledDate={disabledDate(properties.disabledDates)}
format={properties.format || 'YYYY-wo'}
format={properties.format ?? 'YYYY-wo'}
getPopupContainer={() => document.getElementById(`${blockId}_popup`)}
placeholder={properties.placeholder || 'Select Week'}
placeholder={properties.placeholder ?? 'Select Week'}
size={properties.size}
status={validation.status}
suffixIcon={
<Icon
blockId={`${blockId}_suffixIcon`}
events={events}
properties={properties.suffixIcon || 'AiOutlineCalendar'}
properties={properties.suffixIcon ?? 'AiOutlineCalendar'}
/>
}
onChange={(newVal) => {

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -66,7 +66,7 @@ export const ColorPicker = ({
'ant-input-sm': size === 'small',
'ant-input-lg': size === 'large',
})}
color={value || ''}
color={value ?? ''}
onChange={(newColor) => {
onChange(newColor);
}}
@ -76,7 +76,7 @@ export const ColorPicker = ({
)}
{isOpen && (
<div className="color-picker-popover" ref={popover}>
<HexColorPicker color={value || DEFAULT_COLOR} onChange={onChange} />
<HexColorPicker color={value ?? DEFAULT_COLOR} onChange={onChange} />
</div>
)}
</div>

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -18,15 +18,15 @@
import { runBlockSchemaTests } from '@lowdefy/block-dev';
// import { runBlockSchemaTests, runRenderTests } from '@lowdefy/block-dev';
import Block from './EChart.js';
// import Block from './EChart.js';
import examples from './examples.yaml';
import schema from './schema.json';
const testConfig = {
validation: true,
required: true,
values: [],
};
// const testConfig = {
// validation: true,
// required: true,
// values: [],
// };
// runRenderTests({ Block, examples, schema, testConfig });
runBlockSchemaTests({ examples, schema });

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -23,7 +23,7 @@ import Map from '../Map.js';
function updateHeatmap(data) {
if (data.location) {
const latLng = new window.google.maps.LatLng(data.location);
latLng.weight = data.weight || 1;
latLng.weight = data.weight ?? 1;
return latLng;
}
return new window.google.maps.LatLng(data);

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -21,7 +21,7 @@ const Skeleton = ({ properties, methods }) => {
return (
<div
className={'skeleton ' + methods.makeCssClass(properties.style)}
style={{ width: properties.width || '100%', height: properties.height || '100%' }}
style={{ width: properties.width ?? '100%', height: properties.height ?? '100%' }}
/>
);
};

View File

@ -21,7 +21,7 @@ import { blockDefaultProps } from '@lowdefy/block-utils';
import Skeleton from '../Skeleton/Skeleton.js';
const SkeletonAvatar = ({ properties, methods }) => {
let size = properties.size || 32;
let size = properties.size ?? 32;
if (type.isString(size)) {
switch (properties.size) {
case 'small':

View File

@ -39,7 +39,7 @@ const SkeletonButton = ({ properties, methods }) => {
...{ borderRadius: properties.shape === 'round' && height / 2 },
...(properties.style || {}),
},
width: properties.width || '100%',
width: properties.width ?? '100%',
height,
}}
/>

View File

@ -37,8 +37,8 @@ const SkeletonInput = ({ properties, methods }) => {
<Skeleton
methods={methods}
properties={{
width: properties.labelWidth || properties.width || '30%',
height: properties.labelHeight || 20,
width: properties.labelWidth ?? properties.width ?? '30%',
height: properties.labelHeight ?? 20,
style: { ...{ marginBottom: 10 }, ...(properties.labelStyle || {}) },
}}
/>
@ -46,8 +46,8 @@ const SkeletonInput = ({ properties, methods }) => {
<Skeleton
methods={methods}
properties={{
width: properties.width || '100%',
height: properties.inputHeight || inputHeight,
width: properties.width ?? '100%',
height: properties.inputHeight ?? inputHeight,
style: properties.inputStyle || {},
}}
/>

View File

@ -20,9 +20,9 @@ import { blockDefaultProps } from '@lowdefy/block-utils';
import Skeleton from '../Skeleton/Skeleton.js';
const SkeletonParagraph = ({ properties, methods }) => {
const lines = [...Array(properties.lines || 4).keys()];
const lines = [...Array(properties.lines ?? 4).keys()];
return (
<div style={{ width: properties.width || '100%' }}>
<div style={{ width: properties.width ?? '100%' }}>
{lines.map((key) => (
<Skeleton
key={key}

View File

@ -19,7 +19,7 @@ import { type } from '@lowdefy/helpers';
import { blockDefaultProps } from '@lowdefy/block-utils';
const Spinner = ({ properties, methods }) => {
let size = properties.size || 20;
let size = properties.size ?? 20;
if (type.isString(size)) {
switch (properties.size) {
case 'small':

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -56,7 +56,7 @@ class QRScanner extends React.Component {
if (!this.scanning) {
this.scanning = true;
this.html5QrCode?.start(
{ facingMode: this.props.properties.facingMode || 'environment' },
{ facingMode: this.props.properties.facingMode ?? 'environment' },
{
...{ aspectRatio: 1 },
...this.props.properties,

View File

@ -20,8 +20,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -30,7 +30,7 @@ async function GoogleSheetGetOne({ request, connection }) {
if (filter) {
rows = mingoFilter({ input: rows, filter });
}
return rows[0] || null;
return rows[0] ?? null;
}
GoogleSheetGetOne.schema = schema;

View File

@ -18,7 +18,7 @@ import knex from 'knex';
import { type } from '@lowdefy/helpers';
import schema from './schema.js';
async function KnexBuilder({ request, connection }) {
function KnexBuilder({ request, connection }) {
let client = knex(connection);
if (request.tableName) {
client = client(request.tableName);

View File

@ -31,6 +31,7 @@ beforeAll(async () => {
test('redis command with connection as an object', async () => {
const Redis = (await import('./Redis.js')).default;
const response = 'responseValue';
const client = {
on: jest.fn(),
connect: jest.fn().mockImplementation(() => Promise.resolve()),
@ -55,7 +56,6 @@ test('redis command with connection as an object', async () => {
b: false,
},
};
const response = 'responseValue';
const res = await Redis({ request, connection });
expect(mockedCreateClient.mock.calls).toEqual([[connection.connection]]);
expect(client.connect).toHaveBeenCalledTimes(1);
@ -66,6 +66,7 @@ test('redis command with connection as an object', async () => {
test('redis command with connection as a string', async () => {
const Redis = (await import('./Redis.js')).default;
const response = 'responseValue';
const client = {
on: jest.fn(),
connect: jest.fn().mockImplementation(() => Promise.resolve()),
@ -84,7 +85,6 @@ test('redis command with connection as a string', async () => {
b: false,
},
};
const response = 'responseValue';
const res = await Redis({ request, connection });
expect(mockedCreateClient.mock.calls).toEqual([[{ url: connection.connection }]]);
expect(client.connect).toHaveBeenCalledTimes(1);
@ -101,7 +101,7 @@ test('connection error', async () => {
cb(new Error('connection error'));
}
}),
connect: jest.fn().mockImplementation(() => Promise.reject()),
connect: jest.fn().mockImplementation(() => Promise.reject(new Error('connection error'))),
};
mockedCreateClient.mockImplementationOnce(() => client);
const connection = {

View File

@ -18,7 +18,7 @@ import { get } from '@lowdefy/helpers';
import Stripe from 'stripe';
import schema from './schema.js';
async function StripeRequest({ request, connection }) {
function StripeRequest({ request, connection }) {
const stripe = new Stripe(connection.secretKey, {
apiVersion: connection.apiVersion,
maxNetworkRetries: connection.maxNetworkRetries,

View File

@ -23,7 +23,7 @@ const connection = {
jest.unstable_mockModule('stripe', () => {
return {
default: function () {
default() {
return {
customers: {
list(...args) {

View File

@ -54,7 +54,7 @@ const prepRegex = (prop, location) => {
);
}
try {
return new RegExp(regex.pattern, regex.flags || 'gm');
return new RegExp(regex.pattern, regex.flags ?? 'gm');
} catch (e) {
throw new Error(
`Operator Error: ${e.message}. Received: ${JSON.stringify(prop)} at ${location}.`

View File

@ -34,7 +34,7 @@ function aggregate(data, pipeline) {
return agg.run(data);
}
function expr(data, expr) {
function expr(data, expression) {
if (data === null) {
data = {};
}
@ -44,7 +44,7 @@ function expr(data, expr) {
const agg = new mingo.Aggregator([
{
$project: {
value: expr,
value: expression,
},
},
]);
@ -52,17 +52,17 @@ function expr(data, expr) {
return get(res, '0.value', { default: null });
}
function test(data, test) {
function test(data, testQuery) {
if (data === null) {
data = {};
}
if (!type.isObject(data)) {
throw new Error('Data must be of type object.');
}
if (!type.isObject(test)) {
if (!type.isObject(testQuery)) {
throw new Error('Query test must be of type object.');
}
const query = new mingo.Query(test);
const query = new mingo.Query(testQuery);
return query.test(data);
}

View File

@ -15,7 +15,7 @@
*/
import { jest } from '@jest/globals';
jest.unstable_mockModule('uuid', async () => {
jest.unstable_mockModule('uuid', () => {
return {
v1: jest.fn(() => 'ABC-v1'),
v3: jest.fn(() => 'ABC-v3'),
@ -104,7 +104,6 @@ test('_uuid.v5: {"name":"hello", "namespace":"world"}', async () => {
});
test('_uuid: error', async () => {
const uuid = await import('uuid');
const _uuid = (await import('./uuid.js')).default;
expect(() => _uuid({ params: 'error', location: 'locationId' })).toThrow();
});

View File

@ -44,6 +44,7 @@ const getDisabled = ({ properties, value }) => {
const getCustomRequest =
({ methods, setS3Parameters }) =>
async ({ file, onError, onProgress, onSuccess }) => {
let meta;
try {
const { name, size, type, uid } = file;
@ -58,7 +59,7 @@ const getCustomRequest =
const { url, fields } = s3PostPolicyResponse.responses.__getS3PostPolicy.response[0];
const { bucket, key } = fields;
const meta = { bucket, key, filename: name, size, type, uid };
meta = { bucket, key, filename: name, size, type, uid };
setS3Parameters((prevState) => {
const ret = { ...prevState };
@ -98,7 +99,7 @@ const getCustomRequest =
xhr.send(formData);
} catch (error) {
console.error(error);
await methods.triggerEvent({ name: 'onError', event: { meta, event } });
await methods.triggerEvent({ name: 'onError', event: { meta, error } });
onError(error);
}
};

View File

@ -37,6 +37,7 @@ const makeOnChangeValue = (s3Parameters, changeEvent) => {
const getCustomRequest =
({ methods, setS3Parameters, setLoading }) =>
async ({ file, onError, onProgress, onSuccess }) => {
let meta;
try {
setLoading(true);
const { name, size, type, uid } = file;
@ -53,7 +54,7 @@ const getCustomRequest =
const { url, fields } = s3PostPolicyResponse.responses.__getS3PostPolicy.response[0];
const { bucket, key } = fields;
const meta = { bucket, key, filename: name, size, type, uid };
meta = { bucket, key, filename: name, size, type, uid };
setS3Parameters((prevState) => {
const ret = { ...prevState };
@ -94,7 +95,7 @@ const getCustomRequest =
xhr.send(formData);
} catch (error) {
console.error(error);
await methods.triggerEvent({ name: 'onError', event: { meta, event } });
await methods.triggerEvent({ name: 'onError', event: { meta, error } });
onError(error);
}
};

View File

@ -21,8 +21,8 @@ import * as blocks from './blocks.js';
const icons = {};
const styles = {};
Object.keys(blocks).forEach((block) => {
icons[block] = blocks[block].meta.icons || [];
styles[block] = blocks[block].meta.styles || [];
icons[block] = blocks[block].meta.icons ?? [];
styles[block] = blocks[block].meta.styles ?? [];
});
export default {
blocks: Object.keys(blocks),

View File

@ -14,7 +14,7 @@
limitations under the License.
*/
async function wait(ms) {
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

View File

@ -49,7 +49,7 @@ const dateFilter = (date, format, ...args) => {
if (obj[format] && type.isFunction(obj[format])) {
result = obj[format](...args);
} else {
result = obj.format(format || dateFilterDefaultFormat);
result = obj.format(format ?? dateFilterDefaultFormat);
}
} catch (err) {
errs.push(err);
@ -69,7 +69,7 @@ dateFilter.setDefaultFormat = (format) => {
// install the filter to nunjucks environment
dateFilter.install = (env, customName) => {
(env || nunjucks.configure()).addFilter(customName || 'date', dateFilter);
(env || nunjucks.configure()).addFilter(customName ?? 'date', dateFilter);
};
export default dateFilter;

View File

@ -36,7 +36,7 @@ const testDefFormat = 'YYYY-MM-DD';
const env = new nunjucks.Environment();
const renderNunjucks = (filter, str) => {
if (str === undefined) {
str = '{{ my_date | ' + (filter || 'date') + ' }}';
str = `{{ my_date | ${filter ?? 'date'} }}`;
}
return env.renderString(str, { my_date: testDate });
};