hooks#usePrevious JavaScript Examples
The following examples show how to use
hooks#usePrevious.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js From monday-ui-react-core with MIT License | 5 votes |
export default function useSetFocus({ ref, focusCallback, blurCallback }) {
const [isFocused, setIsFocused] = useState(false);
const isFocusedPrev = usePrevious(isFocused);
useEffect(() => {
if (isFocusedPrev === undefined) {
// Don't call callback on first render
return;
}
// Calling back from here to be sure that isFocused value have already been updated
if (isFocused) {
focusCallback && focusCallback();
} else {
blurCallback && blurCallback();
}
}, [blurCallback, focusCallback, isFocused, isFocusedPrev]);
const focus = useCallback(() => {
ref.current.focus();
}, [ref]);
const blur = useCallback(() => {
ref.current.blur();
}, [ref]);
const onFocus = () => {
setIsFocused(true);
};
const onBlur = () => {
setIsFocused(false);
};
useEventListener({
eventName: "focus",
ref,
callback: onFocus
});
useEventListener({
eventName: "blur",
ref,
callback: onBlur
});
return { isFocused, focus, blur };
}
Example #2
Source File: index.js From dstack-server with Apache License 2.0 | 4 votes |
Details = ({
data,
fetch,
update,
currentUser,
deleteDashboard,
insertCard,
deleteCard,
updateCard,
requestStatus,
loading,
}: Props) => {
const {items, moveItem, setItems} = useContext(DnDGridContext);
const {t} = useTranslation();
const [isShowStacksModal, setIsShowStacksModal] = useState(false);
const [titleValue, setTitleValue] = useState(data ? data.title : '');
const [view, setView] = useState('grid');
const {form, setForm, onChange} = useForm({});
const [fields, setFields] = useState({});
const prevData = usePrevious(data);
const params = useParams();
const {push} = useHistory();
const isDidMount = useRef(true);
const updateDebounce = useCallback(_debounce(update, 300), []);
const cards = data?.cards;
const setGridItems = cardsItems => setItems(cardsItems.map(card => ({id: card.index, card})));
useEffect(() => {
if (!data || data.id !== params.id)
fetch(params.user, params.id);
else
setGridItems(cards);
}, []);
useEffect(() => {
if (window)
window.dispatchEvent(new Event('resize'));
}, [view]);
useEffect(() => {
if (cards && !isEqual(prevData, data))
setGridItems(cards);
return () => setGridItems([]);
}, [cards]);
useEffect(() => {
if (!prevData && data || (prevData && data && prevData.id !== data.id))
setTitleValue(data.title);
if ((!isEqual(prevData, data) || isDidMount.current) && data)
parseParams();
if (isDidMount.current)
isDidMount.current = false;
}, [data]);
const onChangeTitle = event => {
setTitleValue(event.target.value);
updateDebounce({
user: params.user,
id: data.id,
title: event.target.value,
});
};
const moveCard = (indexFrom, indexTo) => {
if (indexTo < 0 || indexFrom < 0)
return;
const {stack} = items[indexFrom].card;
updateCard({
user: params.user,
dashboard: data.id,
stack,
index: indexTo,
});
moveItem(indexFrom, indexTo);
};
const onClickAdd = event => {
event.preventDefault();
setIsShowStacksModal(true);
};
const closeModal = () => setIsShowStacksModal(false);
const onClickDelete = () => {
deleteDashboard(
{
user: params.user,
id: data.id,
},
() => {
push(routes.dashboards(params.user));
}
);
};
const getDeleteCardAction = stack => () => {
deleteCard({
user: params.user,
dashboard: data.id,
stack,
});
};
const getUpdateCardAction = stack => fields => {
updateCard({
user: params.user,
dashboard: data.id,
stack,
...fields,
});
};
const addStacksToDashboard = stacks => {
stacks.forEach((stack, index) => {
insertCard({
user: params.user,
dashboard: params.id,
stack,
index: cards.length + index,
});
});
};
const parseParams = () => {
if (!cards)
return;
const fields = cards.reduce((result, card) => {
const cardFields = parseStackParams(get(card, 'head.attachments', [])) || {};
Object.keys(cardFields).forEach(fieldName => {
if (result[fieldName]) {
if (cardFields[fieldName].type === 'select') {
result[fieldName].options = unionBy(
result[fieldName].options,
cardFields[fieldName].options, 'value');
}
if (cardFields[fieldName].type === 'slider') {
result[fieldName].options = {
...result[fieldName].options,
...cardFields[fieldName].options,
};
result[fieldName].min = Math.min(result[fieldName].min, cardFields[fieldName].min);
result[fieldName].max = Math.max(result[fieldName].max, cardFields[fieldName].max);
}
} else {
result[fieldName] = cardFields[fieldName];
}
});
return result;
}, {});
const defaultFilterValues = Object.keys(fields).reduce((result, fieldName) => {
if (fields[fieldName].type === 'select')
result[fieldName] = fields[fieldName].options[0].value;
if (fields[fieldName].type === 'slider')
result[fieldName] = fields[fieldName].options[0];
if (fields[fieldName].type === 'checkbox')
result[fieldName] = false;
return result;
}, {});
setForm(defaultFilterValues);
setFields(fields);
};
const renderFilters = () => {
if (!Object.keys(fields).length)
return null;
const hasSelectField = Object.keys(fields).some(key => fields[key].type === 'select');
return (
<Filters
fields={fields}
form={form}
onChange={onChange}
className={cx(css.filters, {'with-select': hasSelectField})}
/>
);
};
if (loading)
return <Loader />;
if (requestStatus === 403)
return <AccessForbidden>
{t('youDontHaveAnAccessToThisDashboard')}.
{isSignedIn() && (
<Fragment>
<br />
<Link to={routes.dashboards(currentUser)}>
{t('goToMyDashboards')}
</Link>
</Fragment>
)}
</AccessForbidden>;
if (requestStatus === 404)
return <NotFound>
{t('theDashboardYouAreRookingForCouldNotBeFound')}
{' '}
{isSignedIn() && (
<Fragment>
<Link to={routes.dashboards(currentUser)}>
{t('goToMyDashboards')}
</Link>.
</Fragment>
)}
</NotFound>;
if (!data)
return null;
return (
<div className={css.details}>
<div className={css.header}>
<div className={css.title}>
<StretchTitleField
className={css.edit}
value={titleValue}
onChange={onChangeTitle}
readOnly={currentUser !== data.user}
placeholder={t('newDashboard')}
/>
<span className={`mdi mdi-lock${data.private ? '' : '-open'}`} />
</div>
{/*<Button*/}
{/* className={css.pdf}*/}
{/* color="secondary"*/}
{/*>*/}
{/* <span className="mdi mdi-download" />*/}
{/* PDF*/}
{/*</Button>*/}
{currentUser === data.user && <Dropdown
className={css.dropdown}
items={[
{
title: t('delete'),
onClick: onClickDelete,
},
]}
>
<Button
className={css['dropdown-button']}
color="secondary"
>
<span className="mdi mdi-dots-horizontal" />
</Button>
</Dropdown>}
</div>
{Boolean(items.length) && (
<Fragment>
<div className={css.section}>
<div className={css.fields}>
{renderFilters()}
</div>
<div className={css.controls}>
{currentUser === data.user && (
<a
className={css.addButton}
onClick={onClickAdd}
href="#"
>
<span className="mdi mdi-plus" />
{t('addStack')}
</a>
)}
<ViewSwitcher
value={view}
className={css.viewSwitcher}
onChange={view => setView(view)}
/>
</div>
</div>
<div className={cx(css.cards, view)}>
{items.map(item => (
currentUser === data.user
? <DnDItem
id={item.id}
key={item.card.stack}
onMoveItem={moveCard}
>
<Card
filters={form}
deleteCard={getDeleteCardAction(item.card.stack)}
data={item.card}
type={view}
updateCard={getUpdateCardAction(item.card.stack)}
/>
</DnDItem>
: <Card
key={item.card.stack}
filters={form}
data={item.card}
type={view}
/>
))}
</div>
</Fragment>
)}
{!items.length && (
<div className={css.empty}>
{t('thereAreNoStacksYet')} <br/>
{t('youCanSendStacksYouWantToBeHereLaterOrAddItRightNow')}
{currentUser === data.user && (
<Fragment>
{' '}
<a
className={css.addButton}
onClick={onClickAdd}
href="#"
>{t('addStack')}</a>.
</Fragment>
)}
</div>
)}
{isShowStacksModal && <SelectStacks
isShow={isShowStacksModal}
onClose={closeModal}
onAddStacks={addStacksToDashboard}
/>}
</div>
);
}
Example #3
Source File: index.js From dstack-server with Apache License 2.0 | 4 votes |
Details = ({
attachment,
attachmentRequestStatus,
fetchDetails,
fetchFrame,
downloadAttachment,
clearDetails,
update,
data = {},
listData = {},
frame,
frameRequestStatus,
loading,
requestStatus,
currentUser,
}: Props) => {
let parsedAttachmentIndex;
const params = useParams();
const {push} = useHistory();
const location = useLocation();
const searchParams = parseSearch(location.search);
if (searchParams.a)
parsedAttachmentIndex = parseInt(searchParams.a);
const [attachmentIndex, setAttachmentIndex] = useState(parsedAttachmentIndex);
const [selectedFrame, setSelectedFrame] = useState(searchParams.f);
const [headId, setHeadId] = useState(null);
const {t} = useTranslation();
const didMountRef = useRef(false);
const {form, setForm, onChange} = useForm({});
const [fields, setFields] = useState({});
const prevFrame = usePrevious(frame);
const [isShowHowToModal, setIsShowHowToModal] = useState(false);
const [isShowUploadModal, setIsShowUploadModal] = useState(false);
const isFirstChangeSearch = useRef(false);
const showHowToModal = event => {
event.preventDefault();
setIsShowHowToModal(true);
};
const hideHowToModal = () => setIsShowHowToModal(false);
const onClickDownloadAttachment = event => {
event.preventDefault();
downloadAttachment(`${params.user}/${params.stack}`, selectedFrame || headId, attachmentIndex || 0);
};
useEffect(() => {
if (isFirstChangeSearch.current) {
let parsedAttachmentIndex;
if (searchParams.a)
parsedAttachmentIndex = parseInt(searchParams.a);
if (parsedAttachmentIndex !== attachmentIndex)
setAttachmentIndex(parsedAttachmentIndex);
if (searchParams.f !== selectedFrame)
setSelectedFrame(searchParams.f);
} else {
isFirstChangeSearch.current = true;
}
}, [location.search]);
useEffect(() => {
let searchParams = {};
if (attachmentIndex)
searchParams.a = attachmentIndex;
if (selectedFrame && selectedFrame !== headId)
searchParams.f = selectedFrame;
const searchString = Object
.keys(searchParams)
.map(key => `${key}=${searchParams[key]}`)
.join('&');
if (location.search.replace('?', '') !== searchString)
push({search: searchString.length ? `?${searchString}` : ''});
}, [attachmentIndex, selectedFrame, headId]);
const fetchData = () => {
fetchDetails(params.user, params.stack);
};
useEffect(() => {
if (!data.head || !listData || (data.head.id !== listData.head))
fetchData();
return () => clearDetails();
}, []);
const setHeadFrame = frameId => {
update({
stack: `${data.user}/${data.name}`,
noUpdateStore: true,
head: frameId,
}, () => setHeadId(frameId));
};
useEffect(() => {
if (selectedFrame)
fetchFrame(params.user, params.stack, selectedFrame);
}, [selectedFrame]);
useEffect(() => {
if ((!isEqual(prevFrame, frame) || !didMountRef.current) && frame)
parseParams();
}, [frame]);
useEffect(() => {
if (data && data.head)
setHeadId(data.head.id);
}, [data]);
const onChangeFrame = frameId => {
setSelectedFrame(frameId);
setAttachmentIndex(undefined);
};
const findAttach = (form, attachmentIndex) => {
const attachments = get(frame, 'attachments');
const fields = Object.keys(form);
if (!attachments)
return;
if (fields.length) {
attachments.some((attach, index) => {
let valid = true;
fields.forEach(key => {
if (!attach.params || !isEqual(attach.params[key], form[key]))
valid = false;
});
if (valid && !(attachmentIndex === undefined && index === 0))
setAttachmentIndex(index);
return valid;
});
}
};
const findAttachDebounce = useCallback(_debounce(findAttach, 300), [data, frame]);
useEffect(() => {
if (didMountRef.current)
findAttachDebounce(form, attachmentIndex);
else
didMountRef.current = true;
}, [form]);
const parseParams = () => {
const attachments = get(frame, 'attachments');
if (!attachments || !attachments.length)
return;
const fields = parseStackParams(attachments);
setFields(fields);
if (attachmentIndex !== undefined) {
if (attachments[attachmentIndex])
setForm(attachments[attachmentIndex].params);
} else
setForm(attachments[0].params);
};
const renderFields = () => {
if (!Object.keys(fields).length)
return null;
const hasSelectField = Object.keys(fields).some(key => fields[key].type === 'select');
return (
<Filters
fields={fields}
form={form}
onChange={onChange}
className={cx(css.filters, {'with-select': hasSelectField})}
/>
);
};
if (loading)
return <Loader />;
if (requestStatus === 403)
return <AccessForbidden>
{t('youDontHaveAnAccessToThisStack')}.
{isSignedIn() && (
<Fragment>
<br />
<Link to={routes.stacks(currentUser)}>
{t('goToMyStacks')}
</Link>
</Fragment>
)}
</AccessForbidden>;
if (requestStatus === 404)
return <NotFound>
{t('theStackYouAreRookingForCouldNotBeFound')}
{' '}
{isSignedIn() && (
<Fragment>
<Link to={routes.stacks(currentUser)}>
{t('goToMyStacks')}
</Link>.
</Fragment>
)}
</NotFound>;
const currentFrame = selectedFrame ? selectedFrame : get(data, 'head.id');
return (
<div className={css.details}>
<Helmet>
<title>dstack.ai | {params.user} | {params.stack}</title>
</Helmet>
<section className={css.section}>
<div className={css.header}>
<div className={css.title}>
{data.name}
<span className={`mdi mdi-lock${data.private ? '' : '-open'}`} />
</div>
{data && data.user === currentUser && (
<Dropdown
className={css.dropdown}
items={[
{
title: t('upload'),
onClick: () => setIsShowUploadModal(true),
},
]}
>
<Button
className={css['dropdown-button']}
color="secondary"
>
<span className="mdi mdi-dots-horizontal" />
</Button>
</Dropdown>
)}
</div>
<Frames
frames={get(data, 'frames', [])}
frame={currentFrame}
headId={headId}
onMarkAsHead={setHeadFrame}
onChange={onChangeFrame}
className={css.revisions}
/>
{!frameRequestStatus && renderFields()}
{attachment && (
<div className={css['attachment-head']}>
{attachment.description && (
<div className={css.description}>
<MarkdownRender source={attachment.description} />
</div>
)}
{attachment.type === 'text/csv' && (
<div className={css.actions}>
<a href="#" onClick={showHowToModal}>{t('useThisStackViaAPI')}</a>
{' '}
{t('or')}
{' '}
<a href="#" onClick={onClickDownloadAttachment}>{t('download')}</a>
{' '}
{attachment.length && (
<span className={css.size}>({formatBytes(attachment.length)})</span>
)}
</div>
)}
</div>
)}
{attachmentRequestStatus === 404 || frameRequestStatus === 404 && (
<div className={css.empty}>{t('noMatch')}</div>
)}
{(frame && !attachmentRequestStatus && !frameRequestStatus) && (
<Attachment
className={css.attachment}
withLoader
stack={`${params.user}/${params.stack}`}
frameId={currentFrame}
id={attachmentIndex || 0}
/>
)}
</section>
<Upload
stack={params.stack}
isShow={isShowUploadModal}
onClose={() => setIsShowUploadModal(false)}
refresh={fetchData}
/>
<Modal
isShow={isShowHowToModal}
withCloseButton
onClose={hideHowToModal}
size="big"
title={t('howToFetchDataUsingTheAPI')}
className={css.modal}
>
<HowToFetchData
data={{
stack: `${params.user}/${params.stack}`,
params: form,
}}
modalMode
/>
</Modal>
</div>
);
}
Example #4
Source File: index.js From dstack-server with Apache License 2.0 | 4 votes |
Attachment = ({
fetchAttachment,
error,
attachment,
requestStatus,
id,
className,
frameId,
isList,
loading,
withLoader,
stack,
}: Props) => {
const {t} = useTranslation();
const [tableScale, setTableScale] = useState(1);
const [loadingFullAttachment, setLoadingFullAttachment] = useState(false);
const [fullAttachment, setFullAttachment] = useState(null);
const viewRef = useRef(null);
const prevAttachment = usePrevious(attachment);
useEffect(() => {
if (window && isList)
window.addEventListener('resize', onResizeCard);
return () => {
if (window && isList)
window.removeEventListener('resize', onResizeCard);
};
}, []);
const fetchFullAttachment = async () => {
setLoadingFullAttachment(true);
try {
const url = config.STACK_ATTACHMENT(stack, frameId, id) + '?download=true';
const {data} = await api.get(url);
setFullAttachment(data.attachment);
} catch (e) {
console.log(e);
}
setLoadingFullAttachment(false);
};
useEffect(() => {
if (!isList && attachment
&& !isEqual(prevAttachment, attachment)
&& attachment.preview
&& isImageType(attachment.type)
) {
fetchFullAttachment();
}
}, [attachment]);
useEffect(() => {
if (!isList
&& (typeof id === 'number' && frameId)
&& ((!attachment.data && !error) || (attachment?.index !== id))
) {
fetchAttachment(stack, frameId, id);
}
}, [id, frameId]);
const [ref] = useIntersectionObserver(() => {
if (isList && !loading && (
(!attachment.data && !error)
|| (attachment.data && attachment.index !== id)
))
fetchAttachment(stack, frameId, id);
}, {}, [id, frameId, attachment]);
useEffect(() => {
if (attachment && attachment.type === 'bokeh' && Bokeh) {
const json = base64ToJSON(attachment.data);
if (json && document.querySelector(`#bokeh-${frameId}`))
Bokeh.embed.embed_item(json, `bokeh-${frameId}`);
}
if (isList)
setTimeout(() => onResizeCard(), 10);
}, [attachment]);
const onResizeCard = () => {
if (ref.current && viewRef.current) {
const containerWidth = ref.current.offsetWidth;
const viewWidth = viewRef.current.offsetWidth / tableScale;
let newScale = containerWidth / viewWidth;
if (newScale > 1)
newScale = 1;
setTableScale(newScale);
}
};
const renderImage = () => {
if (!attachment.preview)
return (
<img src={`${base64ImagePrefixes[attachment.type]}base64,${attachment.data}`} alt=""/>
);
else if (fullAttachment) {
if (fullAttachment['download_url']) {
return (
<img src={fullAttachment['download_url']} alt=""/>
);
} else
return (
<img src={`${base64ImagePrefixes[attachment.type]}base64,${attachment.data}`} alt=""/>
);
}
return null;
};
const renderCSV = () => {
const decodeCSV = unicodeBase64Decode(attachment.data);
if (decodeCSV) {
const data = CSV.parse(decodeCSV);
if (Array.isArray(data))
return (
<Table
data={data}
/>
);
}
return (
<div className={css.text}>{t('notSupportedAttachment')}</div>
);
};
const renderPlotly = () => {
const json = base64ToJSON(attachment.data);
if (!json)
return null;
json.layout.width = '100%';
json.layout.margin = 0;
json.layout.autosize = true;
json.config = {responsive: true};
return (
<Plot
{...json}
style={{
width: '100%',
height: '100%',
}}
useResizeHandler
/>
);
};
const renderBokeh = () => <div id={`bokeh-${frameId}`} />;
const renderAttachment = () => {
if (loading)
return null;
if (requestStatus === 404 && isList)
return <div className={css.message}>{t('notFound')}</div>;
if (requestStatus === 404 && !isList)
return <div className={css.text}>{t('noPreview')}</div>;
if (attachment.preview && isList && isImageType(attachment.type))
return <div className={css.message}>{t('noPreview')}</div>;
switch (attachment.type) {
case 'image/svg+xml':
case 'image/png':
case 'image/jpeg':
return renderImage();
case 'text/csv':
return renderCSV();
case 'plotly':
return renderPlotly();
case 'bokeh':
return renderBokeh();
case undefined:
return null;
default:
return <div className={isList ? css.message : css.text}>{t('notSupportedAttachment')}</div>;
}
};
return (
<div
ref={ref}
className={cx(css.attachment, className, {
'is-list': isList,
loading: loading && withLoader || loadingFullAttachment,
})}
>
<div
ref={viewRef}
className={cx(css.view, {
'table': (attachment && attachment.data && attachment.type === 'text/csv'),
'bokeh': (attachment && attachment.data && attachment.type === 'bokeh'),
})}
style={
(attachment && attachment.type === 'text/csv')
? {transform: `scale(${tableScale})`}
: {}
}
>
{renderAttachment()}
</div>
</div>
);
}
Example #5
Source File: index.js From dstack-server with Apache License 2.0 | 4 votes |
ProgressBar = ({className, isActive, progress: globalProgress}: Props) => {
const [progress, setProgress] = useState(0);
const [width, setWidth] = useState(1000);
const prevIsActive = usePrevious(isActive);
const step = useRef(0.01);
const currentProgress = useRef(0);
const requestFrame = useRef(null);
const ref = useRef(null);
useEffect(() => {
if (isActive) {
setProgress(0);
step.current = 0.01;
currentProgress.current = 0;
startCalculateProgress();
}
if (prevIsActive === true && isActive === false) {
if (requestFrame.current)
cancelAnimationFrame(requestFrame.current);
setProgress(100);
setTimeout(() => setProgress(0), 800);
}
if (isActive === null) {
if (requestFrame.current)
cancelAnimationFrame(requestFrame.current);
setProgress(0);
}
}, [isActive]);
useEffect(() => {
if (globalProgress !== null)
setProgress(globalProgress);
else {
setProgress(0);
}
}, [globalProgress]);
useEffect(() => {
window.addEventListener('resize', onResize);
if (ref.current)
setWidth(ref.current.offsetWidth);
return () => window.removeEventListener('resize', onResize);
}, []);
const startCalculateProgress = () => {
requestAnimationFrame(calculateProgress);
};
const calculateProgress = useCallback(() => {
currentProgress.current += step.current;
const progress = Math.round(Math.atan(currentProgress.current) / (Math.PI / 2) * 100 * 1000) / 1000;
setProgress(progress);
if (progress > 70)
step.current = 0.005;
if (progress >= 100)
cancelAnimationFrame(requestFrame.current);
requestFrame.current = requestAnimationFrame(calculateProgress);
}, [isActive]);
const onResize = () => {
if (ref.current)
setWidth(ref.current.offsetWidth);
};
return (
<div ref={ref} className={cx(css.bar, className)}>
<div
className={css.progress}
style={{
width: `${progress}%`,
backgroundSize: `${width}px 5px`,
}}
/>
</div>
);
}