repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
ErwinYou/react-blog
|
src/utils/apis/setData.ts
|
<filename>src/utils/apis/setData.ts
import { db } from '../cloudBase';
export const setData = (config: {
DBName: string;
name: string;
email: string;
link: string;
content: string;
date: number;
avatar: string;
postTitle: string;
replyId: string;
}) => {
const { DBName, name, email, link, content, date, avatar, postTitle, replyId } = config;
return db
.collection(DBName)
.add({
name,
email,
link,
content,
date,
avatar,
postTitle,
replyId
})
.then(() => true)
.catch(() => false);
};
|
ErwinYou/react-blog
|
src/pages/Home/Aside/SiteCard/useRunTime.ts
|
import { useMount,useSafeState } from 'ahooks';
import dayjs from 'dayjs';
import { time } from '@/utils/constant';
export const useRunTime = () => {
const [runTime, setRunTime] = useSafeState(0);
useMount(() => {
const nowTime = new Date().getTime();
const startTime = new Date(time).getTime();
const runTime = dayjs(nowTime).diff(dayjs(startTime), 'days');
setRunTime(runTime);
});
return { runTime };
};
|
ErwinYou/react-blog
|
src/components/Comment/EditBox/PreShow/index.tsx
|
<reponame>ErwinYou/react-blog
import { useMemoizedFn } from 'ahooks';
import classNames from 'classnames';
import React from 'react';
import sanitizeHtml from 'sanitize-html';
import MarkDown from '@/components/MarkDown';
import s from './index.scss';
interface Props {
closePre?: Function;
content?: string;
className?: string;
}
const PreShow: React.FC<Props> = ({ closePre, content, className }) => {
const handleClose = useMemoizedFn(() => closePre?.());
return (
<div className={classNames(s.preShow, className)}>
<div className={s.closeBtn} onClick={handleClose}>
×
</div>
<MarkDown className={s.preMarked} content={sanitizeHtml(content!)} />
</div>
);
};
export default PreShow;
|
ErwinYou/react-blog
|
src/redux/reducers/index.ts
|
import { combineReducers } from 'redux';
import artSum from './artSum';
import avatar from './avatar';
import email from './email';
import link from './link';
import mode from './mode';
import name from './name';
import navShow from './navShow';
export default combineReducers({
navShow,
artSum,
avatar,
email,
link,
name,
mode
});
|
ErwinYou/react-blog
|
src/pages/Home/Aside/DataCard/index.tsx
|
import { useRequest } from 'ahooks';
import React from 'react';
import { connect } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import Card from '@/components/Card';
import { setArtSum } from '@/redux/actions';
import { DB } from '@/utils/apis/dbConfig';
import { staleTime } from '@/utils/constant';
import { fetchData } from './fetchData';
import s from './index.scss';
interface Props {
setArtSum?: Function;
}
const DataCard: React.FC<Props> = ({ setArtSum }) => {
const navigate = useNavigate();
const { data, loading } = useRequest(fetchData, {
retryCount: 3,
cacheKey: `DataCard-count-${DB.Article}-${DB.Class}-${DB.Tag}`,
staleTime,
onSuccess: data => setArtSum!(data?.articles.total)
});
return (
<Card className={s.card} loading={loading}>
<div className={s.blogData} onClick={() => navigate('/articles')}>
<div className={s.name}>文章</div>
<div className={s.num}>{data?.articles.total}</div>
</div>
<div className={s.blogData} onClick={() => navigate('/classes')}>
<div className={s.name}>分类</div>
<div className={s.num}>{data?.classes.total}</div>
</div>
<div className={s.blogData} onClick={() => navigate('/tags')}>
<div className={s.name}>标签</div>
<div className={s.num}>{data?.tags.total}</div>
</div>
</Card>
);
};
export default connect(() => ({}), {
setArtSum
})(DataCard);
|
ErwinYou/react-blog
|
src/pages/Home/Aside/AccountCard/Csdn/index.tsx
|
<reponame>ErwinYou/react-blog
import React from 'react';
import s from './index.scss';
const Csdn: React.FC = () => (
<svg className={s.csdn} viewBox='0 0 1024 1024'>
<path d='M512 0c282.784 0 512 229.216 512 512s-229.216 512-512 512S0 794.784 0 512 229.216 0 512 0z m189.952 752l11.2-108.224c-31.904 9.536-100.928 16.128-147.712 16.128-134.464 0-205.728-47.296-195.328-146.304 11.584-110.688 113.152-145.696 232.64-145.696 54.784 0 122.432 8.8 151.296 18.336L768 272.704C724.544 262.24 678.272 256 599.584 256c-203.2 0-388.704 94.88-406.4 263.488C178.336 660.96 303.584 768 535.616 768c80.672 0 138.464-6.432 166.336-16z' />
</svg>
);
export default Csdn;
|
ErwinYou/react-blog
|
src/components/Comment/EditBox/index.tsx
|
import useUrlState from '@ahooksjs/use-url-state';
import { UserOutlined } from '@ant-design/icons';
import {
useBoolean,
useKeyPress,
useLocalStorageState,
useMemoizedFn,
useMount,
useRequest,
useSafeState
} from 'ahooks';
import { message } from 'antd';
import classNames from 'classnames';
import React, { useRef } from 'react';
import { connect } from 'react-redux';
import sanitizeHtml from 'sanitize-html';
import { setAvatar, setEmail, setLink, setName } from '@/redux/actions';
import { storeState } from '@/redux/interface';
import { axiosAPI } from '@/utils/apis/axios';
import { DB } from '@/utils/apis/dbConfig';
import { setData } from '@/utils/apis/setData';
import { auth } from '@/utils/cloudBase';
import {
adminUid,
avatarArrLen,
defaultCommentAvatarArr,
emailApi,
myAvatar70,
myEmail,
myLink,
myName,
QQ
} from '@/utils/constant';
import { getRandomNum } from '@/utils/function';
import AdminBox from './AdminBox';
import Emoji from './Emoji';
import s from './index.scss';
import PreShow from './PreShow';
interface Props {
msgRun?: Function;
replyRun?: Function;
isReply?: boolean;
name?: string;
link?: string;
email?: string;
avatar?: string;
setAvatar?: Function;
setEmail?: Function;
setLink?: Function;
setName?: Function;
closeReply?: Function;
className?: string;
replyName?: string;
replyId?: string;
title?: string;
ownerEmail?: string;
}
const EditBox: React.FC<Props> = ({
msgRun,
replyRun,
isReply = false,
name,
link,
email,
avatar,
setAvatar,
setEmail,
setLink,
setName,
closeReply,
replyName,
replyId,
className,
title,
ownerEmail
}) => {
const [search] = useUrlState();
const nameRef = useRef(null);
const [showAdmin, setShowAdmin] = useSafeState(false);
const [showPre, { toggle: togglePre, setFalse: closePre }] = useBoolean(false);
const [text, setText] = useSafeState('');
const [localName, setLocalName] = useLocalStorageState('name');
const [localEmail, setLocalEmail] = useLocalStorageState('email');
const [localLink, setLocalLink] = useLocalStorageState('link');
const [localAvatar, setLocalAvatar] = useLocalStorageState('avatar');
const validateConfig = {
name: {
check: /^[\u4e00-\u9fa5_a-zA-Z0-9]{2,8}$/,
content: name,
errText: '昵称仅限中文、数字、字母,长度2~8!'
},
email: {
check: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
content: email,
errText: '请输入正确的邮箱地址!'
},
link: {
check: /^$|^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/,
content: link,
errText: '请输入正确的url,或不填!'
},
text: {
check: /^[\s\S]*.*[^\s][\s\S]*$/,
content: text,
errText: '请输入内容再发布~'
}
};
const validate = useMemoizedFn(() => {
Object.keys(validateConfig).forEach(item => {
const { check, errText, content } =
validateConfig[item as keyof typeof validateConfig];
if (!check.test(content!)) {
message.error(errText);
throw new Error('breakForEach');
}
});
});
const checkAdmin = useMemoizedFn(() => {
if (
!adminLogined() &&
(name === myName ||
name === QQ ||
email === myEmail ||
link?.indexOf(myLink) !== -1)
) {
message.warning('未登录不可以使用管理员账户(昵称、邮箱、网址)哦~');
throw new Error('Not Admin');
}
});
const submit = useMemoizedFn(async () => {
try {
validate();
checkAdmin();
const config = {
DBName: DB.Msg,
name: sanitizeHtml(name!),
email: sanitizeHtml(email!),
link: sanitizeHtml(link!),
content: sanitizeHtml(text),
date: new Date().getTime(),
avatar: avatar
? avatar
: defaultCommentAvatarArr[getRandomNum(0, avatarArrLen - 1)],
postTitle: search.title || '',
replyId: replyId || ''
};
const isTrue = await setData(config);
if (isTrue) {
if (isReply) {
closeReply?.();
replyRun?.();
email !== ownerEmail && informUser();
informAdminReply();
} else {
msgRun?.();
informAdminMsg();
}
} else {
message.error('发布失败,请重试!');
}
} catch {}
});
const adminLogined = useMemoizedFn(() => {
if (!auth.hasLoginState()) return false;
if (auth.currentUser?.uid === adminUid) return true;
return false;
});
useMount(() => {
if (adminLogined()) {
// 管理员已登录
setName?.(myName);
setEmail?.(myEmail);
setLink?.(myLink);
setAvatar?.(myAvatar70);
return;
}
localName && localName !== myName && setName?.(localName);
localEmail && localEmail !== myEmail && setEmail?.(localEmail);
localLink && localLink.indexOf(myLink) === -1 && setLink?.(localLink);
localAvatar && setAvatar?.(localAvatar);
});
const handleName = useMemoizedFn(() => {
const regQQ = /[1-9][0-9]{4,11}/;
if (name === 'admin') {
setShowAdmin(true);
setName?.('');
return;
}
if (!adminLogined() && (name === myName || name === QQ)) {
message.warning('未登录不可以使用管理员账户哦~');
setName?.('');
return;
}
if (regQQ.test(name!)) {
const avatarUrl = `https://q1.qlogo.cn/g?b=qq&nk=${name}&s=100`;
const QQEmail = <EMAIL>`;
setEmail?.(QQEmail);
setAvatar?.(avatarUrl);
setLocalEmail(QQEmail);
setLocalAvatar(avatarUrl);
setName?.('');
return;
}
setLocalName(name);
});
useKeyPress(13, handleName, {
target: nameRef
});
const openPreShow = useMemoizedFn(() => {
if (!showPre && !text) {
message.info('请写点什么再预览~');
return;
}
togglePre();
});
const handleCloseReply = useMemoizedFn(() => {
closeReply?.();
});
const { run: informAdminMsg } = useRequest(
() =>
axiosAPI(emailApi, 'POST', {
flag: 0,
name,
search: search.title || '',
content: text,
title
}),
{
manual: true,
onSuccess: () => {
setText('');
message.success(`发布${search.title ? '评论' : '留言'}成功!`);
}
}
);
const { run: informAdminReply } = useRequest(
() =>
axiosAPI(emailApi, 'POST', {
flag: 1,
owner: replyName,
name,
search: search.title || '',
content: text,
title
}),
{
manual: true,
onSuccess: () => {
setText('');
message.success('已通知站长!');
}
}
);
const { run: informUser } = useRequest(
() =>
axiosAPI(emailApi, 'POST', {
flag: 2,
owner: replyName,
email: ownerEmail,
name,
search: search.title || '',
content: text,
title
}),
{
manual: true,
onSuccess: () => {
message.success(`已通知${search.title ? '评论' : '留言'}者!`);
}
}
);
return (
<div className={classNames(s.editBox, className)}>
{isReply && (
<div className={s.replyNameBox}>
回复给「<span>{replyName}</span>」:
</div>
)}
<div className={s.flex}>
<AdminBox
showAdmin={showAdmin}
setShowAdmin={setShowAdmin}
setName={setName}
setEmail={setEmail}
setLink={setLink}
setAvatar={setAvatar}
/>
<div className={s.avatarBoxCol}>
<div className={s.avatarBox}>
{avatar ? (
<img src={avatar} className={s.editAvatar} />
) : (
<UserOutlined className={s.noAvatar} />
)}
</div>
</div>
<div className={s.editInputBox}>
<div className={s.inputBox}>
<div className={classNames(s.inputInfo, s.flex2)}>
<div className={s.inputKey}>昵称</div>
<input
ref={nameRef}
type='text'
className={s.inputValue}
placeholder='QQ号'
value={name}
onChange={e => setName?.(e.target.value)}
onBlur={handleName}
/>
</div>
<div className={classNames(s.inputInfo, s.flex3)}>
<div className={s.inputKey}>邮箱</div>
<input
type='text'
className={s.inputValue}
placeholder='必填'
value={email}
onChange={e => setEmail?.(e.target.value)}
onBlur={e => setLocalEmail(e.target.value)}
/>
</div>
<div className={classNames(s.inputInfo, s.flex3)}>
<div className={s.inputKey}>网址</div>
<input
type='text'
className={s.inputValue}
placeholder='选填'
value={link}
onChange={e => setLink?.(e.target.value)}
onBlur={e => setLocalLink(e.target.value)}
/>
</div>
</div>
<div className={s.textareaBox}>
<textarea
className={s.textarea}
value={text}
onChange={e => setText(e.target.value)}
placeholder='写点什么吗?支持markdown格式! 可以在「昵称」处填写QQ号,自动获取「头像」和「QQ邮箱」!'
/>
</div>
<div className={s.commentBtns}>
<Emoji />
{isReply && (
<div className={s.cancelBtn} onClick={handleCloseReply}>
取消
</div>
)}
<div className={s.previewBtn} onClick={openPreShow}>
预览
</div>
<div className={s.sendBtn} onClick={submit}>
{isReply ? '回复' : ' 发布'}
</div>
</div>
</div>
</div>
<PreShow
closePre={closePre}
content={text}
className={classNames({ [s.preShowHidden]: !showPre })}
/>
</div>
);
};
export default connect(
(state: storeState) => ({
name: state.name,
link: state.link,
email: state.email,
avatar: state.avatar
}),
{
setAvatar,
setEmail,
setLink,
setName
}
)(EditBox);
|
ErwinYou/react-blog
|
src/components/Comment/Placehold/index.tsx
|
import React from 'react';
import s from './index.scss';
interface Props {
msgCount?: number;
isMsg?: boolean;
}
const Placehold: React.FC<Props> = ({ msgCount, isMsg }) => {
return (
<>
{msgCount ? (
<div className={s.hasMag}>
{msgCount}条{isMsg ? '留言' : '评论'}
</div>
) : (
<div className={s.noMag}>暂时没有{isMsg ? '留言' : '评论'} ~</div>
)}
</>
);
};
export default Placehold;
|
ErwinYou/react-blog
|
src/pages/Say/SayPop/index.tsx
|
<reponame>ErwinYou/react-blog
import dayjs from 'dayjs';
import React from 'react';
import { myAvatar70 } from '@/utils/constant';
import s from './index.scss';
interface Props {
content?: string;
date?: number;
}
const SayPop: React.FC<Props> = ({ content, date }) => (
<div className={s.sayItem}>
<div className={s.avatarBox}>
<img src={myAvatar70} className={s.avatar} />
</div>
<div className={s.contentBox}>
<div className={s.content}>
{content}
<span className={s.date}>{dayjs(date).format('YYYY-MM-DD HH:mm:ss')}</span>
</div>
</div>
</div>
);
export default SayPop;
|
ErwinYou/react-blog
|
src/utils/apis/getSum.ts
|
<reponame>ErwinYou/react-blog
import { db } from '../cloudBase';
export const getSum = (dbName: string) =>
db
.collection(dbName)
.count()
.then(res => res)
.catch(err => err);
|
ErwinYou/react-blog
|
src/utils/function.ts
|
<reponame>ErwinYou/react-blog<filename>src/utils/function.ts<gh_stars>0
/**
* 生成指定范围内的随机整数,左闭右闭
* @param {Number} Min
* @param {Number} Max
* @return {Number}
*/
export const getRandomNum = (Min: number, Max: number) => {
const Range = Max - Min + 1;
const Rand = Math.random();
return Min + Math.floor(Rand * Range);
};
/**
* 打乱数组
* @param {any[]} array
* @return {any[]}
*/
export const shuffleArray = (array: any[]) => {
if (!array) return [];
const res = [...array];
const len = res.length;
for (let i = len - 1; i > 0; i--) {
const randomPos = Math.floor(Math.random() * (i + 1));
[res[i], res[randomPos]] = [res[randomPos], res[i]];
}
return res;
};
|
ErwinYou/react-blog
|
src/redux/constant.ts
|
<filename>src/redux/constant.ts
export const SET_NAV_SHOW = 'setNavShow';
export const SET_ART_SUM = 'setArtSum';
export const SET_NAME = 'setName';
export const SET_EMAIL = 'setEmail';
export const SET_LINK = 'setLink';
export const SET_AVATAR = 'setAvatar';
export const SET_MODE = 'setMode';
|
ErwinYou/react-blog
|
src/components/Nav/config.ts
|
<reponame>ErwinYou/react-blog
export const useLinkList = () => {
const navArr = [
{ name: '图库', to: '/gallery' },
{ name: '说说', to: '/say' },
{ name: '留言', to: '/msg' },
{ name: '友链', to: '/link' },
{ name: '作品', to: '/show' },
{ name: '建站', to: '/log' },
{ name: '关于', to: '/about' }
];
const secondNavArr = [
{ name: '找文章', to: '/articles' },
{ name: '分类', to: '/classes' },
{ name: '标签', to: '/tags' }
];
const mobileNavArr = [
{ name: '主页', to: '/' },
{ name: '文章', to: '/articles' },
{ name: '分类', to: '/classes' },
{ name: '标签', to: '/tags' },
{ name: '图库', to: '/gallery' },
{ name: '说说', to: '/say' },
{ name: '留言', to: '/msg' },
{ name: '友链', to: '/link' },
{ name: '作品', to: '/show' },
{ name: '建站', to: '/log' },
{ name: '关于', to: '/about' }
];
return {
navArr,
secondNavArr,
mobileNavArr
};
};
|
ErwinYou/react-blog
|
src/utils/hooks/useLazyImg.ts
|
import { useInViewport, useSafeState } from 'ahooks';
import { useEffect, useRef } from 'react';
export const useLazyImg = (avatar: string, loading: string) => {
const imgRef = useRef(null);
// eslint-disable-next-line no-unused-vars
const [_, ratio] = useInViewport(imgRef, {
threshold: [1]
});
const [imgUrl, setImgUrl] = useSafeState(loading);
useEffect(() => {
if (ratio !== 1) return;
setImgUrl(avatar);
}, [ratio]);
return { imgRef, imgUrl };
};
|
ErwinYou/react-blog
|
src/utils/apis/dbConfig.ts
|
/* eslint-disable no-unused-vars */
export enum DB {
About = 'about',
Msg = 'allComments',
Article = 'articles',
Class = 'classes',
Drafe = 'drafts',
Gallery = 'galleries',
Link = 'links',
Log = 'logs',
Notice = 'notice',
Say = 'says',
Show = 'shows',
Count = 'siteCount',
Tag = 'tags'
}
|
ErwinYou/react-blog
|
src/pages/Img/ImgView/index.tsx
|
<reponame>ErwinYou/react-blog
import classNames from 'classnames';
import React, { MouseEventHandler } from 'react';
import s from './index.scss';
interface Props {
viewUrl?: string;
isViewShow?: boolean;
onClick?: MouseEventHandler<HTMLDivElement>;
}
const ImgView: React.FC<Props> = ({ viewUrl, isViewShow, onClick }) => {
return (
<div className={classNames(s.view, { [s.show]: isViewShow })} onClick={onClick!}>
<img className={s.img} src={viewUrl} />
</div>
);
};
export default ImgView;
|
ErwinYou/react-blog
|
src/pages/Gallery/ImgCard/index.tsx
|
<filename>src/pages/Gallery/ImgCard/index.tsx
import React from 'react';
import { useNavigate } from 'react-router-dom';
import s from './index.scss';
interface Props {
cover?: string;
title?: string;
descr?: string;
}
const ImgCard: React.FC<Props> = ({ cover, title, descr }) => {
const navigate = useNavigate();
return (
<div
style={{ backgroundImage: `url(${cover})` }}
onClick={() => navigate(`/img?title=${encodeURIComponent(title!)}`)}
className={s.imgItem}
>
<div className={s.title}>{title}</div>
<div className={s.descr}>{descr}</div>
<div className={s.mask} />
</div>
);
};
export default ImgCard;
|
ErwinYou/react-blog
|
src/pages/Home/Section/PostCard/index.tsx
|
import dayjs from 'dayjs';
import React, { MouseEventHandler } from 'react';
import Card from '@/components/Card';
import s from './index.scss';
import PostCardLoading from './PostCardLoading';
interface Props {
title?: string;
content?: string;
date?: number;
tags?: string[];
loading?: boolean;
onClick?: MouseEventHandler<HTMLDivElement>;
}
const PostCard: React.FC<Props> = ({ title, content, date, tags, loading, onClick }) => {
return (
<Card className={s.card} isStatic={true} onClick={onClick}>
{loading ? (
<PostCardLoading />
) : (
<>
<div className={s.title}>{title}</div>
<p className={s.content}>
{content!.replace(/<a(.*?)>(.*?)<\/a>/g, '$2').replace(/[# |**|`|>]/g, '')}
</p>
<div className={s.info}>
<span className={s.date}>{dayjs(date!).format('YYYY-MM-DD')}</span>
<div className={s.tags}>
{tags!.map(tag => (
<span className={s.tag} key={tag}>
{tag}
</span>
))}
</div>
</div>
</>
)}
</Card>
);
};
export default PostCard;
|
ErwinYou/react-blog
|
src/components/Comment/EditBox/Emoji/EmojiItem/index.tsx
|
import { message } from 'antd';
import copy from 'copy-to-clipboard';
import React from 'react';
import s from './index.scss';
interface Props {
emojiStr: string[];
}
const EmojiItem: React.FC<Props> = ({ emojiStr }) => {
return (
<>
{emojiStr.map((item: string, index: number) => (
<div
className={s.emoji}
key={index}
onClick={() => {
copy(item) && message.success('已复制到剪切板!');
}}
>
{item}
</div>
))}
</>
);
};
export default EmojiItem;
|
ErwinYou/react-blog
|
src/utils/hooks/useTime.ts
|
<filename>src/utils/hooks/useTime.ts
// import { useMount, useSafeState } from 'ahooks';
export const useTime = () => {
const hour = new Date().getHours();
const timeText =
hour < 6
? '凌晨好'
: hour < 9
? '早上好'
: hour < 11
? '上午好'
: hour < 13
? '中午好'
: hour < 17
? '下午好'
: hour < 19
? '傍晚好'
: '晚上好';
return { timeText };
};
|
ErwinYou/react-blog
|
src/components/Main/index.tsx
|
<filename>src/components/Main/index.tsx<gh_stars>0
import React, { lazy, Suspense } from 'react';
import { Navigate, Route, Routes } from 'react-router-dom';
import ErrorBoundary from '@/components/ErrorBoundary';
import s from './index.scss';
const Home = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Home'));
const Articles = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Articles'));
const Classes = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Classes'));
const Tags = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Tags'));
const Gallery = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Gallery'));
const Img = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Img'));
const Say = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Say'));
const Msg = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Msg'));
const Link = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Link'));
const Show = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Show'));
const Log = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Log'));
const About = lazy(() => import(/* webpackPrefetch:true */ '@/pages/About'));
const Post = lazy(() => import(/* webpackPrefetch:true */ '@/pages/Post'));
const ArtDetail = lazy(() => import(/* webpackPrefetch:true */ '@/pages/ArtDetail'));
const Main: React.FC = () => {
return (
<main className={s.main}>
<div className={s.center}>
<ErrorBoundary>
<Suspense fallback={<></>}>
<Routes>
<Route path='/' element={<Home />} />
<Route path='articles' element={<Articles />} />
<Route path='classes' element={<Classes />} />
<Route path='tags' element={<Tags />} />
<Route path='gallery' element={<Gallery />} />
<Route path='img' element={<Img />} />
<Route path='say' element={<Say />} />
<Route path='msg' element={<Msg />} />
<Route path='link' element={<Link />} />
<Route path='show' element={<Show />} />
<Route path='log' element={<Log />} />
<Route path='about' element={<About />} />
<Route path='post' element={<Post />} />
<Route path='artDetail' element={<ArtDetail />} />
<Route path='*' element={<Navigate to='/' replace />} />
</Routes>
</Suspense>
</ErrorBoundary>
</div>
</main>
);
};
export default Main;
|
ErwinYou/react-blog
|
src/redux/actions.ts
|
import {
SET_ART_SUM,
SET_AVATAR,
SET_EMAIL,
SET_LINK,
SET_MODE,
SET_NAME,
SET_NAV_SHOW
} from './constant';
export const setNavShow = (data: boolean) => ({
type: SET_NAV_SHOW,
data
});
export const setArtSum = (data: number) => ({
type: SET_ART_SUM,
data
});
export const setName = (data: string) => ({
type: SET_NAME,
data
});
export const setEmail = (data: string) => ({
type: SET_EMAIL,
data
});
export const setLink = (data: string) => ({
type: SET_LINK,
data
});
export const setAvatar = (data: string) => ({
type: SET_AVATAR,
data
});
export const setMode = (data: number) => ({
type: SET_MODE,
data
});
|
ErwinYou/react-blog
|
src/pages/Home/Aside/ClockCard/index.tsx
|
import { useInterval } from 'ahooks';
import React from 'react';
import Card from '@/components/Card';
import s from './index.scss';
import { useClock } from './useClock';
const ClockCard: React.FC = () => {
const { hour, minute, second, runPerSecond } = useClock();
useInterval(runPerSecond, 1000);
return (
<Card className={s.card}>
<div className={s.dial}>
<div className={s.zero} />
<div className={s.six} />
<div className={s.three} />
<div className={s.nine} />
</div>
<div className={s.container}>
<div className={s.dot} />
<div
className={s.clockMinuteLine}
style={{ transform: `rotateZ(${minute}deg)` }}
/>
<div className={s.clockHourLine} style={{ transform: `rotateZ(${hour}deg)` }} />
<div
className={s.clockSecondLine}
style={{ transform: `rotateZ(${second}deg)` }}
/>
</div>
</Card>
);
};
export default ClockCard;
|
ErwinYou/react-blog
|
src/components/PageTitle/index.tsx
|
<reponame>ErwinYou/react-blog<gh_stars>0
import classNames from 'classnames';
import React from 'react';
import s from './index.scss';
interface Props {
title?: string;
desc?: string;
className?: string;
}
const PageTitle: React.FC<Props> = ({ title, desc, className, children }) => {
return (
<div className={classNames(s.box, className)}>
<div className={s.title}>{title}</div>
{desc && <div className={s.desc}>{desc}</div>}
{children}
</div>
);
};
export default PageTitle;
|
ErwinYou/react-blog
|
src/components/LayoutLoading/index.tsx
|
import { Skeleton } from 'antd';
import React from 'react';
interface Props {
rows?: number;
}
const LayoutLoading: React.FC<Props> = ({ rows = 10 }) => (
<Skeleton paragraph={{ rows }} />
);
export default LayoutLoading;
|
ErwinYou/react-blog
|
src/components/Layout/index.tsx
|
import { useTitle } from 'ahooks';
import classNames from 'classnames';
import dayjs from 'dayjs';
import React from 'react';
import { connect } from 'react-redux';
import { setNavShow } from '@/redux/actions';
import { siteTitle } from '@/utils/constant';
import useTop from '@/utils/hooks/useTop';
import Card from '../Card';
import LayoutLoading from '../LayoutLoading';
import PageTitle from '../PageTitle';
import s from './index.scss';
interface Props {
title?: string;
className?: string;
setNavShow?: Function;
loading?: boolean;
isPost?: boolean;
classes?: string;
date?: number;
rows?: number;
}
const Layout: React.FC<Props> = ({
title,
className,
setNavShow,
loading,
children,
classes,
date,
isPost = false,
rows
}) => {
useTitle(`${siteTitle} | ${title || ''}`);
useTop(setNavShow!);
return (
<>
<PageTitle title={title} className={classNames({ [s.postTitle]: isPost })}>
{isPost && (
<div>
<span className={s.articleClass}>{classes}</span>
<span className={s.articleDate}>
{dayjs(date).format('YYYY-MM-DD HH:mm:ss')}
</span>
</div>
)}
</PageTitle>
<Card isStatic={true} className={classNames(s.layoutCard, className)}>
{loading ? <LayoutLoading rows={rows} /> : children}
</Card>
</>
);
};
export default connect(() => ({}), { setNavShow })(Layout);
|
ErwinYou/react-blog
|
src/components/Footer/index.tsx
|
import React from 'react';
import { icp_no, icp_site, source_github } from '@/utils/constant';
import s from './index.scss';
const Footer: React.FC = () => {
const frameArr = [
'React',
'React Router',
'Redux',
'Webpack',
'AntD',
'ahooks',
'CloudBase'
];
return (
<footer className={s.footer}>
<span>
个人博客系统
<a href={source_github} target='_blank' rel='noreferrer' className={s.text}>
「源代码」
</a>
</span>
<span>
<a href={icp_site} target='_blank' rel='noreferrer' className={s.text}>
{icp_no}
</a>
</span>
<span>
{frameArr.map((item, index) => (
<span className={s.siteFrame} key={index}>
{item}
</span>
))}
</span>
</footer>
);
};
export default Footer;
|
ErwinYou/react-blog
|
src/pages/About/AboutSite/Chart/useOption.ts
|
import { ClassType } from '..';
const getChartData = (classes: ClassType[], artSum: number) => {
let sum = 0;
const res = classes.map(obj => {
sum += obj.count;
return { name: obj.class, value: obj.count };
});
const leave = artSum - sum;
leave &&
res.push({
name: '未分类',
value: leave
});
return res;
};
export const useOption = (classes: ClassType[], artSum: number, mode: number) => {
const data = getChartData(classes!, artSum!);
const labelColor = ['rgb(255, 255, 255)', 'rgb(53, 53, 53)', 'rgb(53, 53, 53)'];
const backgroundColor = ['rgb(22, 54, 51)', 'rgb(157, 222, 255)', 'rgb(194, 209, 223)'];
return {
tooltip: {
trigger: 'item',
backgroundColor: backgroundColor[mode],
borderColor: backgroundColor[mode],
textStyle: {
color: labelColor[mode],
fontSize: 16,
fontFamily: 'dengxian'
}
},
series: [
{
type: 'pie',
radius: '88%',
height: '400px',
data,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
},
label: {
color: labelColor[mode],
fontSize: 18,
fontFamily: 'dengxian'
}
}
]
};
};
|
ErwinYou/react-blog
|
src/components/Card/index.tsx
|
<gh_stars>0
import { Skeleton } from 'antd';
import classNames from 'classnames';
import React, { MouseEventHandler } from 'react';
import s from './index.scss';
interface Props {
className?: string;
loading?: boolean;
isStatic?: boolean;
onClick?: MouseEventHandler<HTMLDivElement>;
}
const Card: React.FC<Props> = ({ children, className, loading, isStatic, onClick }) => {
return (
<div
className={classNames(
s.card,
{ [s.center]: loading },
{ [s.active]: !isStatic },
className
)}
onClick={onClick}
>
{loading ? <Skeleton paragraph={{ rows: 1 }} /> : children}
</div>
);
};
export default Card;
|
ErwinYou/react-blog
|
src/pages/Classes/ClassBar/index.tsx
|
import classNames from 'classnames';
import React, { MouseEventHandler } from 'react';
import s from './index.scss';
interface Props {
content: string;
num: number;
className?: string;
onClick?: MouseEventHandler<HTMLDivElement>;
}
const ClassBar: React.FC<Props> = ({ content, num, onClick, className }) => {
return (
<div className={classNames(s.classBar, className)} onClick={onClick}>
{content}
<div className={s.classNum}>{num}</div>
</div>
);
};
export default ClassBar;
|
ErwinYou/react-blog
|
src/pages/Post/Navbar/index.tsx
|
<reponame>ErwinYou/react-blog
import './index.custom.scss';
import { MenuFoldOutlined } from '@ant-design/icons';
import { useBoolean } from 'ahooks';
import { Drawer } from 'antd';
import classNames from 'classnames';
import MarkNav from 'markdown-navbar';
import React from 'react';
import { connect } from 'react-redux';
import { setNavShow } from '@/redux/actions';
import s from './index.scss';
interface Props {
content?: string;
setNavShow?: Function;
}
const Navbar: React.FC<Props> = ({ content, setNavShow }) => {
const [visible, { setTrue: openDrawer, setFalse: closeDrawer }] = useBoolean(false);
return (
<>
{/* 正常的目录 */}
<MarkNav
className={classNames('postNavBar', s.navBar)}
source={content || ''}
headingTopOffset={15}
ordered={false}
updateHashAuto={false}
onNavItemClick={() => setNavShow?.(false)}
/>
{/* 中屏显示的按钮 */}
<div className={s.hoverBar} onClick={openDrawer}>
<MenuFoldOutlined />
</div>
{/* 中屏抽屉 */}
<Drawer
placement='right'
onClose={closeDrawer}
visible={visible}
className={classNames(s.drawer, 'mobile-navBar-box')}
width={340}
>
<MarkNav
className='postNavBar'
source={content || ''}
headingTopOffset={15 + 60}
ordered={false}
updateHashAuto={false}
onNavItemClick={() => setNavShow?.(true)}
/>
</Drawer>
</>
);
};
export default connect(() => ({}), {
setNavShow
})(Navbar);
|
ErwinYou/react-blog
|
src/components/Comment/Divider/index.tsx
|
<reponame>ErwinYou/react-blog
import React from 'react';
import s from './index.scss';
const Divider: React.FC = () => <div className={s.divider} />;
export default Divider;
|
keyboard-clacker/vscode
|
src/vs/editor/contrib/goToDeclaration/browser/clickLinkGesture.ts
|
<gh_stars>0
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./goToDeclarationMouse';
import { KeyCode } from 'vs/base/common/keyCodes';
import * as browser from 'vs/base/browser/browser';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ICodeEditor, IEditorMouseEvent, IMouseTarget } from 'vs/editor/browser/editorBrowser';
import { Disposable } from 'vs/base/common/lifecycle';
import { ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents';
import Event, { Emitter } from 'vs/base/common/event';
import * as platform from 'vs/base/common/platform';
function hasModifier(e: { ctrlKey: boolean; shiftKey: boolean; altKey: boolean; metaKey: boolean }, modifier: 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey'): boolean {
return !!e[modifier];
}
/**
* An event that encapsulates the various trigger modifiers logic needed for go to definition.
*/
export class ClickLinkMouseEvent {
public readonly target: IMouseTarget;
public readonly hasTriggerModifier: boolean;
public readonly hasSideBySideModifier: boolean;
public readonly isNoneOrSingleMouseDown: boolean;
constructor(source: IEditorMouseEvent, opts: ClickLinkOptions) {
this.target = source.target;
this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier);
this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier);
this.isNoneOrSingleMouseDown = (browser.isIE || source.event.detail <= 1); // IE does not support event.detail properly
}
}
/**
* An event that encapsulates the various trigger modifiers logic needed for go to definition.
*/
export class ClickLinkKeyboardEvent {
public readonly keyCodeIsTriggerKey: boolean;
public readonly keyCodeIsSideBySideKey: boolean;
public readonly hasTriggerModifier: boolean;
constructor(source: IKeyboardEvent, opts: ClickLinkOptions) {
this.keyCodeIsTriggerKey = (source.keyCode === opts.triggerKey);
this.keyCodeIsSideBySideKey = (source.keyCode === opts.triggerSideBySideKey);
this.hasTriggerModifier = hasModifier(source, opts.triggerModifier);
}
}
export class ClickLinkOptions {
public readonly triggerKey: KeyCode;
public readonly triggerModifier: 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey';
public readonly triggerSideBySideKey: KeyCode;
public readonly triggerSideBySideModifier: 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey';
constructor(
triggerKey: KeyCode,
triggerModifier: 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey',
triggerSideBySideKey: KeyCode,
triggerSideBySideModifier: 'ctrlKey' | 'shiftKey' | 'altKey' | 'metaKey'
) {
this.triggerKey = triggerKey;
this.triggerModifier = triggerModifier;
this.triggerSideBySideKey = triggerSideBySideKey;
this.triggerSideBySideModifier = triggerSideBySideModifier;
}
public equals(other: ClickLinkOptions): boolean {
return (
this.triggerKey === other.triggerKey
&& this.triggerModifier === other.triggerModifier
&& this.triggerSideBySideKey === other.triggerSideBySideKey
&& this.triggerSideBySideModifier === other.triggerSideBySideModifier
);
}
}
function createOptions(multicursorModifier: 'altKey' | 'ctrlKey' | 'metaKey'): ClickLinkOptions {
if (multicursorModifier === 'altKey') {
if (platform.isMacintosh) {
return new ClickLinkOptions(KeyCode.Meta, 'metaKey', KeyCode.Alt, 'altKey');
}
return new ClickLinkOptions(KeyCode.Ctrl, 'ctrlKey', KeyCode.Alt, 'altKey');
}
if (platform.isMacintosh) {
return new ClickLinkOptions(KeyCode.Alt, 'altKey', KeyCode.Meta, 'metaKey');
}
return new ClickLinkOptions(KeyCode.Alt, 'altKey', KeyCode.Ctrl, 'ctrlKey');
}
export class ClickLinkGesture extends Disposable {
private readonly _onMouseMoveOrRelevantKeyDown: Emitter<[ClickLinkMouseEvent, ClickLinkKeyboardEvent]> = this._register(new Emitter<[ClickLinkMouseEvent, ClickLinkKeyboardEvent]>());
public readonly onMouseMoveOrRelevantKeyDown: Event<[ClickLinkMouseEvent, ClickLinkKeyboardEvent]> = this._onMouseMoveOrRelevantKeyDown.event;
private readonly _onExecute: Emitter<ClickLinkMouseEvent> = this._register(new Emitter<ClickLinkMouseEvent>());
public readonly onExecute: Event<ClickLinkMouseEvent> = this._onExecute.event;
private readonly _onCancel: Emitter<void> = this._register(new Emitter<void>());
public readonly onCancel: Event<void> = this._onCancel.event;
private readonly _editor: ICodeEditor;
private _opts: ClickLinkOptions;
private lastMouseMoveEvent: ClickLinkMouseEvent;
private hasTriggerKeyOnMouseDown: boolean;
constructor(editor: ICodeEditor) {
super();
this._editor = editor;
this._opts = createOptions(this._editor.getConfiguration().multicursorModifier);
this.lastMouseMoveEvent = null;
this.hasTriggerKeyOnMouseDown = false;
this._register(this._editor.onDidChangeConfiguration((e) => {
if (e.multicursorModifier) {
const newOpts = createOptions(this._editor.getConfiguration().multicursorModifier);
if (this._opts.equals(newOpts)) {
return;
}
this._opts = newOpts;
this.lastMouseMoveEvent = null;
this.hasTriggerKeyOnMouseDown = false;
this._onCancel.fire();
}
}));
this._register(this._editor.onMouseMove((e: IEditorMouseEvent) => this.onEditorMouseMove(new ClickLinkMouseEvent(e, this._opts))));
this._register(this._editor.onMouseDown((e: IEditorMouseEvent) => this.onEditorMouseDown(new ClickLinkMouseEvent(e, this._opts))));
this._register(this._editor.onMouseUp((e: IEditorMouseEvent) => this.onEditorMouseUp(new ClickLinkMouseEvent(e, this._opts))));
this._register(this._editor.onKeyDown((e: IKeyboardEvent) => this.onEditorKeyDown(new ClickLinkKeyboardEvent(e, this._opts))));
this._register(this._editor.onKeyUp((e: IKeyboardEvent) => this.onEditorKeyUp(new ClickLinkKeyboardEvent(e, this._opts))));
this._register(this._editor.onMouseDrag(() => this.resetHandler()));
this._register(this._editor.onDidChangeCursorSelection((e) => this.onDidChangeCursorSelection(e)));
this._register(this._editor.onDidChangeModel((e) => this.resetHandler()));
this._register(this._editor.onDidChangeModelContent(() => this.resetHandler()));
this._register(this._editor.onDidScrollChange((e) => {
if (e.scrollTopChanged || e.scrollLeftChanged) {
this.resetHandler();
}
}));
}
private onDidChangeCursorSelection(e: ICursorSelectionChangedEvent): void {
if (e.selection && e.selection.startColumn !== e.selection.endColumn) {
this.resetHandler(); // immediately stop this feature if the user starts to select (https://github.com/Microsoft/vscode/issues/7827)
}
}
private onEditorMouseMove(mouseEvent: ClickLinkMouseEvent): void {
this.lastMouseMoveEvent = mouseEvent;
this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]);
}
private onEditorMouseDown(mouseEvent: ClickLinkMouseEvent): void {
// We need to record if we had the trigger key on mouse down because someone might select something in the editor
// holding the mouse down and then while mouse is down start to press Ctrl/Cmd to start a copy operation and then
// release the mouse button without wanting to do the navigation.
// With this flag we prevent goto definition if the mouse was down before the trigger key was pressed.
this.hasTriggerKeyOnMouseDown = mouseEvent.hasTriggerModifier;
}
private onEditorMouseUp(mouseEvent: ClickLinkMouseEvent): void {
if (this.hasTriggerKeyOnMouseDown) {
this._onExecute.fire(mouseEvent);
}
}
private onEditorKeyDown(e: ClickLinkKeyboardEvent): void {
if (
this.lastMouseMoveEvent
&& (
e.keyCodeIsTriggerKey // User just pressed Ctrl/Cmd (normal goto definition)
|| (e.keyCodeIsSideBySideKey && e.hasTriggerModifier) // User pressed Ctrl/Cmd+Alt (goto definition to the side)
)
) {
this._onMouseMoveOrRelevantKeyDown.fire([this.lastMouseMoveEvent, e]);
} else if (e.hasTriggerModifier) {
this._onCancel.fire(); // remove decorations if user holds another key with ctrl/cmd to prevent accident goto declaration
}
}
private onEditorKeyUp(e: ClickLinkKeyboardEvent): void {
if (e.keyCodeIsTriggerKey) {
this._onCancel.fire();
}
}
private resetHandler(): void {
this.lastMouseMoveEvent = null;
this.hasTriggerKeyOnMouseDown = false;
this._onCancel.fire();
}
}
|
keyboard-clacker/vscode
|
extensions/emmet/src/selectItemStylesheet.ts
|
<filename>extensions/emmet/src/selectItemStylesheet.ts
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { getNode, getDeepestNode, findNextWord, findPrevWord } from './util';
import Node from '@emmetio/node';
export function nextItemStylesheet(selection: vscode.Selection, editor: vscode.TextEditor, rootNode: Node): vscode.Selection {
let startOffset = editor.document.offsetAt(selection.anchor);
let endOffset = editor.document.offsetAt(selection.active);
let currentNode = getNode(rootNode, endOffset, true);
// Full property is selected, so select full property value next
if (currentNode.type === 'property' && startOffset === currentNode.start && endOffset === currentNode.end) {
return getSelectionFromProperty(currentNode, editor.document, startOffset, endOffset, true, 'next');
}
// Part or whole of propertyValue is selected, so select the next word in the propertyValue
if (currentNode.type === 'property' && startOffset >= currentNode.valueToken.start && endOffset <= currentNode.valueToken.end) {
let singlePropertyValue = getSelectionFromProperty(currentNode, editor.document, startOffset, endOffset, false, 'next');
if (singlePropertyValue) {
return singlePropertyValue;
}
}
// Cursor is in the selector or in a property
if ((currentNode.type === 'rule' && endOffset < currentNode.selectorToken.end)
|| (currentNode.type === 'property' && endOffset < currentNode.valueToken.end)) {
return getSelectionFromNode(currentNode, editor.document);
}
// Get the first child of current node which is right after the cursor
let nextNode = currentNode.firstChild;
while (nextNode && endOffset >= nextNode.end) {
nextNode = nextNode.nextSibling;
}
// Get next sibling of current node or the parent
while (!nextNode && currentNode) {
nextNode = currentNode.nextSibling;
currentNode = currentNode.parent;
}
return getSelectionFromNode(nextNode, editor.document);
}
export function prevItemStylesheet(selection: vscode.Selection, editor: vscode.TextEditor, rootNode: Node): vscode.Selection {
let startOffset = editor.document.offsetAt(selection.anchor);
let endOffset = editor.document.offsetAt(selection.active);
let currentNode = getNode(rootNode, startOffset);
if (!currentNode) {
currentNode = rootNode;
}
// Full property value is selected, so select the whole property next
if (currentNode.type === 'property' && startOffset === currentNode.valueToken.start && endOffset === currentNode.valueToken.end) {
return getSelectionFromNode(currentNode, editor.document);
}
// Part of propertyValue is selected, so select the prev word in the propertyValue
if (currentNode.type === 'property' && startOffset >= currentNode.valueToken.start && endOffset <= currentNode.valueToken.end) {
let singlePropertyValue = getSelectionFromProperty(currentNode, editor.document, startOffset, endOffset, false, 'prev');
if (singlePropertyValue) {
return singlePropertyValue;
}
}
if (currentNode.type === 'property' || !currentNode.firstChild || (currentNode.type === 'rule' && startOffset <= currentNode.firstChild.start)) {
return getSelectionFromNode(currentNode, editor.document);
}
// Select the child that appears just before the cursor
let prevNode = currentNode.firstChild;
while (prevNode.nextSibling && prevNode.nextSibling.end <= startOffset) {
prevNode = prevNode.nextSibling;
}
prevNode = getDeepestNode(prevNode);
return getSelectionFromProperty(prevNode, editor.document, startOffset, endOffset, false, 'prev');
}
function getSelectionFromNode(node: Node, document: vscode.TextDocument): vscode.Selection {
if (!node) {
return;
}
let nodeToSelect = node.type === 'rule' ? node.selectorToken : node;
return new vscode.Selection(document.positionAt(nodeToSelect.start), document.positionAt(nodeToSelect.end));
}
function getSelectionFromProperty(node: Node, document: vscode.TextDocument, selectionStart: number, selectionEnd: number, selectFullValue: boolean, direction: string): vscode.Selection {
if (!node || node.type !== 'property') {
return;
}
let propertyValue = node.valueToken.stream.substring(node.valueToken.start, node.valueToken.end);
selectFullValue = selectFullValue || (direction === 'prev' && selectionStart === node.valueToken.start && selectionEnd < node.valueToken.end);
if (selectFullValue) {
return new vscode.Selection(document.positionAt(node.valueToken.start), document.positionAt(node.valueToken.end));
}
let pos;
if (direction === 'prev') {
if (selectionStart === node.valueToken.start) {
return;
}
pos = selectionStart > node.valueToken.end ? propertyValue.length : selectionStart - node.valueToken.start;
}
if (direction === 'next') {
if (selectionEnd === node.valueToken.end && (selectionStart > node.valueToken.start || propertyValue.indexOf(' ') === -1)) {
return;
}
pos = selectionEnd === node.valueToken.end ? -1 : selectionEnd - node.valueToken.start - 1;
}
let [newSelectionStart, newSelectionEnd] = direction === 'prev' ? findPrevWord(propertyValue, pos) : findNextWord(propertyValue, pos);
if (!newSelectionStart && !newSelectionEnd) {
return;
}
newSelectionStart += node.valueToken.start;
newSelectionEnd += node.valueToken.start;
return new vscode.Selection(document.positionAt(newSelectionStart), document.positionAt(newSelectionEnd));
}
|
keyboard-clacker/vscode
|
src/vs/base/common/objects.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Types from 'vs/base/common/types';
export function clone<T>(obj: T): T {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (obj instanceof RegExp) {
// See https://github.com/Microsoft/TypeScript/issues/10990
return obj as any;
}
var result = (Array.isArray(obj)) ? <any>[] : <any>{};
Object.keys(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = clone(obj[key]);
} else {
result[key] = obj[key];
}
});
return result;
}
export function deepClone<T>(obj: T): T {
if (!obj || typeof obj !== 'object') {
return obj;
}
var result = (Array.isArray(obj)) ? <any>[] : <any>{};
Object.getOwnPropertyNames(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key]);
} else {
result[key] = obj[key];
}
});
return result;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
export function cloneAndChange(obj: any, changer: (orig: any) => any): any {
return _cloneAndChange(obj, changer, []);
}
function _cloneAndChange(obj: any, changer: (orig: any) => any, encounteredObjects: any[]): any {
if (Types.isUndefinedOrNull(obj)) {
return obj;
}
var changed = changer(obj);
if (typeof changed !== 'undefined') {
return changed;
}
if (Types.isArray(obj)) {
var r1: any[] = [];
for (var i1 = 0; i1 < obj.length; i1++) {
r1.push(_cloneAndChange(obj[i1], changer, encounteredObjects));
}
return r1;
}
if (Types.isObject(obj)) {
if (encounteredObjects.indexOf(obj) >= 0) {
throw new Error('Cannot clone recursive data-structure');
}
encounteredObjects.push(obj);
var r2 = {};
for (var i2 in obj) {
if (hasOwnProperty.call(obj, i2)) {
r2[i2] = _cloneAndChange(obj[i2], changer, encounteredObjects);
}
}
encounteredObjects.pop();
return r2;
}
return obj;
}
// DON'T USE THESE FUNCTION UNLESS YOU KNOW HOW CHROME
// WORKS... WE HAVE SEEN VERY WEIRD BEHAVIOUR WITH CHROME >= 37
///**
// * Recursively call Object.freeze on object and any properties that are objects.
// */
//export function deepFreeze(obj:any):void {
// Object.freeze(obj);
// Object.keys(obj).forEach((key) => {
// if(!(typeof obj[key] === 'object') || Object.isFrozen(obj[key])) {
// return;
// }
//
// deepFreeze(obj[key]);
// });
// if(!Object.isFrozen(obj)) {
// console.log('too warm');
// }
//}
//
//export function deepSeal(obj:any):void {
// Object.seal(obj);
// Object.keys(obj).forEach((key) => {
// if(!(typeof obj[key] === 'object') || Object.isSealed(obj[key])) {
// return;
// }
//
// deepSeal(obj[key]);
// });
// if(!Object.isSealed(obj)) {
// console.log('NOT sealed');
// }
//}
/**
* Copies all properties of source into destination. The optional parameter "overwrite" allows to control
* if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
*/
export function mixin(destination: any, source: any, overwrite: boolean = true): any {
if (!Types.isObject(destination)) {
return source;
}
if (Types.isObject(source)) {
Object.keys(source).forEach((key) => {
if (key in destination) {
if (overwrite) {
if (Types.isObject(destination[key]) && Types.isObject(source[key])) {
mixin(destination[key], source[key], overwrite);
} else {
destination[key] = source[key];
}
}
} else {
destination[key] = source[key];
}
});
}
return destination;
}
export function assign(destination: any, ...sources: any[]): any {
sources.forEach(source => Object.keys(source).forEach((key) => destination[key] = source[key]));
return destination;
}
export function toObject<T>(arr: T[], keyMap: (t: T) => string): { [key: string]: T } {
return arr.reduce((o, d) => assign(o, { [keyMap(d)]: d }), Object.create(null));
}
export function equals(one: any, other: any): boolean {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
if (typeof one !== typeof other) {
return false;
}
if (typeof one !== 'object') {
return false;
}
if ((Array.isArray(one)) !== (Array.isArray(other))) {
return false;
}
var i: number,
key: string;
if (Array.isArray(one)) {
if (one.length !== other.length) {
return false;
}
for (i = 0; i < one.length; i++) {
if (!equals(one[i], other[i])) {
return false;
}
}
} else {
var oneKeys: string[] = [];
for (key in one) {
oneKeys.push(key);
}
oneKeys.sort();
var otherKeys: string[] = [];
for (key in other) {
otherKeys.push(key);
}
otherKeys.sort();
if (!equals(oneKeys, otherKeys)) {
return false;
}
for (i = 0; i < oneKeys.length; i++) {
if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
return false;
}
}
}
return true;
}
export function ensureProperty(obj: any, property: string, defaultValue: any) {
if (typeof obj[property] === 'undefined') {
obj[property] = defaultValue;
}
}
export function arrayToHash(array: any[]) {
var result: any = {};
for (var i = 0; i < array.length; ++i) {
result[array[i]] = true;
}
return result;
}
/**
* Given an array of strings, returns a function which, given a string
* returns true or false whether the string is in that array.
*/
export function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
var hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
/**
* Started from TypeScript's __extends function to make a type a subclass of a specific class.
* Modified to work with properties already defined on the derivedClass, since we can't get TS
* to call this method before the constructor definition.
*/
export function derive(baseClass: any, derivedClass: any): void {
for (var prop in baseClass) {
if (baseClass.hasOwnProperty(prop)) {
derivedClass[prop] = baseClass[prop];
}
}
derivedClass = derivedClass || function () { };
var basePrototype = baseClass.prototype;
var derivedPrototype = derivedClass.prototype;
derivedClass.prototype = Object.create(basePrototype);
for (var prop in derivedPrototype) {
if (derivedPrototype.hasOwnProperty(prop)) {
// handle getters and setters properly
Object.defineProperty(derivedClass.prototype, prop, Object.getOwnPropertyDescriptor(derivedPrototype, prop));
}
}
// Cast to any due to Bug 16188:PropertyDescriptor set and get function should be optional.
Object.defineProperty(derivedClass.prototype, 'constructor', <any>{ value: derivedClass, writable: true, configurable: true, enumerable: true });
}
/**
* Calls JSON.Stringify with a replacer to break apart any circular references.
* This prevents JSON.stringify from throwing the exception
* "Uncaught TypeError: Converting circular structure to JSON"
*/
export function safeStringify(obj: any): string {
var seen: any[] = [];
return JSON.stringify(obj, (key, value) => {
if (Types.isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
} else {
seen.push(value);
}
}
return value;
});
}
export function getOrDefault<T, R>(obj: T, fn: (obj: T) => R, defaultValue: R = null): R {
const result = fn(obj);
return typeof result === 'undefined' ? defaultValue : result;
}
/**
* Returns an object that has keys for each value that is different in the base object. Keys
* that do not exist in the target but in the base object are not considered.
*
* Note: This is not a deep-diffing method, so the values are strictly taken into the resulting
* object if they differ.
*
* @param base the object to diff against
* @param obj the object to use for diffing
*/
export type obj = { [key: string]: any; };
export function distinct(base: obj, target: obj): obj {
const result = Object.create(null);
if (!base || !target) {
return result;
}
const targetKeys = Object.keys(target);
targetKeys.forEach(k => {
const baseValue = base[k];
const targetValue = target[k];
if (!equals(baseValue, targetValue)) {
result[k] = targetValue;
}
});
return result;
}
|
keyboard-clacker/vscode
|
extensions/typescript/src/utils/buildStatus.ts
|
<filename>extensions/typescript/src/utils/buildStatus.ts
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import vscode = require('vscode');
const statusItem: vscode.StatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, Number.MIN_VALUE);
export interface BuildInfo {
queueLength: number;
}
export function update(info: BuildInfo): void {
if (info.queueLength === 0) {
statusItem.hide();
return;
}
statusItem.text = info.queueLength.toString();
statusItem.show();
}
|
keyboard-clacker/vscode
|
extensions/emmet/src/emmetCompletionProvider.ts
|
<reponame>keyboard-clacker/vscode
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { expand, createSnippetsRegistry } from '@emmetio/expand-abbreviation';
import { getSyntax, isStyleSheet, getProfile, extractAbbreviation } from './util';
const field = (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`;
const snippetCompletionsCache = new Map<string, vscode.CompletionItem[]>();
export class EmmetCompletionItemProvider implements vscode.CompletionItemProvider {
public provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable<vscode.CompletionList> {
if (!vscode.workspace.getConfiguration('emmet')['useModules']) {
return Promise.resolve(null);
}
let currentWord = getCurrentWord(document, position);
let expandedAbbr = getExpandedAbbreviation(document, position);
let abbreviationSuggestions = getAbbreviationSuggestions(getSyntax(document), currentWord, (expandedAbbr && currentWord === expandedAbbr.label));
let completionItems = expandedAbbr ? [expandedAbbr, ...abbreviationSuggestions] : abbreviationSuggestions;
return Promise.resolve(new vscode.CompletionList(completionItems, true));
}
}
function getExpandedAbbreviation(document: vscode.TextDocument, position: vscode.Position): vscode.CompletionItem {
if (!vscode.workspace.getConfiguration('emmet')['suggestExpandedAbbreviation']) {
return;
}
let [rangeToReplace, wordToExpand] = extractAbbreviation(position);
if (!rangeToReplace || !wordToExpand) {
return;
}
let syntax = getSyntax(document);
let expandedWord = expand(wordToExpand, {
field: field,
syntax: syntax,
profile: getProfile(syntax)
});
let completionitem = new vscode.CompletionItem(wordToExpand);
completionitem.insertText = new vscode.SnippetString(expandedWord);
completionitem.documentation = removeTabStops(expandedWord);
completionitem.range = rangeToReplace;
completionitem.detail = 'Expand Emmet Abbreviation';
// In non stylesheet like syntax, this extension returns expanded abbr plus posssible abbr completions
// To differentiate between the 2, the former is given CompletionItemKind.Value so that it gets a different icon
if (!isStyleSheet(syntax)) {
completionitem.kind = vscode.CompletionItemKind.Value;
}
return completionitem;
}
function getCurrentWord(document: vscode.TextDocument, position: vscode.Position): string {
let wordAtPosition = document.getWordRangeAtPosition(position);
let currentWord = '';
if (wordAtPosition && wordAtPosition.start.character < position.character) {
let word = document.getText(wordAtPosition);
currentWord = word.substr(0, position.character - wordAtPosition.start.character);
}
return currentWord;
}
function removeTabStops(expandedWord: string): string {
return expandedWord.replace(/\$\{\d+\}/g, '').replace(/\$\{\d+:([^\}]+)\}/g, '$1');
}
function getAbbreviationSuggestions(syntax: string, prefix: string, skipExactMatch: boolean) {
if (!vscode.workspace.getConfiguration('emmet')['suggestAbbreviations'] || !prefix || isStyleSheet(syntax)) {
return [];
}
if (!snippetCompletionsCache.has(syntax)) {
let registry = createSnippetsRegistry(syntax);
let completions: vscode.CompletionItem[] = registry.all({ type: 'string' }).map(snippet => {
let expandedWord = expand(snippet.value, {
field: field,
syntax: syntax
});
let item = new vscode.CompletionItem(snippet.key);
item.documentation = removeTabStops(expandedWord);
item.detail = 'Complete Emmet Abbreviation';
item.insertText = snippet.key;
return item;
});
snippetCompletionsCache.set(syntax, completions);
}
let snippetCompletions = snippetCompletionsCache.get(syntax);
snippetCompletions = snippetCompletions.filter(x => x.label.startsWith(prefix) && (!skipExactMatch || x.label !== prefix));
return snippetCompletions;
}
|
keyboard-clacker/vscode
|
extensions/typescript/src/features/documentSymbolProvider.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DocumentSymbolProvider, SymbolInformation, SymbolKind, TextDocument, Range, Location, CancellationToken, Uri } from 'vscode';
import * as Proto from '../protocol';
import * as PConst from '../protocol.const';
import { ITypescriptServiceClient } from '../typescriptService';
const outlineTypeTable: { [kind: string]: SymbolKind } = Object.create(null);
outlineTypeTable[PConst.Kind.module] = SymbolKind.Module;
outlineTypeTable[PConst.Kind.class] = SymbolKind.Class;
outlineTypeTable[PConst.Kind.enum] = SymbolKind.Enum;
outlineTypeTable[PConst.Kind.interface] = SymbolKind.Interface;
outlineTypeTable[PConst.Kind.memberFunction] = SymbolKind.Method;
outlineTypeTable[PConst.Kind.memberVariable] = SymbolKind.Property;
outlineTypeTable[PConst.Kind.memberGetAccessor] = SymbolKind.Property;
outlineTypeTable[PConst.Kind.memberSetAccessor] = SymbolKind.Property;
outlineTypeTable[PConst.Kind.variable] = SymbolKind.Variable;
outlineTypeTable[PConst.Kind.const] = SymbolKind.Variable;
outlineTypeTable[PConst.Kind.localVariable] = SymbolKind.Variable;
outlineTypeTable[PConst.Kind.variable] = SymbolKind.Variable;
outlineTypeTable[PConst.Kind.function] = SymbolKind.Function;
outlineTypeTable[PConst.Kind.localFunction] = SymbolKind.Function;
function textSpan2Range(value: Proto.TextSpan): Range {
return new Range(value.start.line - 1, value.start.offset - 1, value.end.line - 1, value.end.offset - 1);
}
export default class TypeScriptDocumentSymbolProvider implements DocumentSymbolProvider {
public constructor(
private client: ITypescriptServiceClient) { }
public provideDocumentSymbols(resource: TextDocument, token: CancellationToken): Promise<SymbolInformation[]> {
const filepath = this.client.normalizePath(resource.uri);
if (!filepath) {
return Promise.resolve<SymbolInformation[]>([]);
}
const args: Proto.FileRequestArgs = {
file: filepath
};
if (this.client.apiVersion.has206Features()) {
return this.client.execute('navtree', args, token).then((response) => {
const result: SymbolInformation[] = [];
if (response.body) {
// The root represents the file. Ignore this when showing in the UI
let tree = response.body;
if (tree.childItems) {
tree.childItems.forEach(item => TypeScriptDocumentSymbolProvider.convertNavTree(resource.uri, result, item));
}
}
return result;
}, (err) => {
this.client.error(`'navtree' request failed with error.`, err);
return [];
});
} else {
return this.client.execute('navbar', args, token).then((response) => {
const result: SymbolInformation[] = [];
if (response.body) {
let foldingMap: ObjectMap<SymbolInformation> = Object.create(null);
response.body.forEach(item => TypeScriptDocumentSymbolProvider.convertNavBar(resource.uri, 0, foldingMap, result, item));
}
return result;
}, (err) => {
this.client.error(`'navbar' request failed with error.`, err);
return [];
});
}
}
private static convertNavBar(resource: Uri, indent: number, foldingMap: ObjectMap<SymbolInformation>, bucket: SymbolInformation[], item: Proto.NavigationBarItem, containerLabel?: string): void {
let realIndent = indent + item.indent;
let key = `${realIndent}|${item.text}`;
if (realIndent !== 0 && !foldingMap[key] && TypeScriptDocumentSymbolProvider.shouldInclueEntry(item.text)) {
let result = new SymbolInformation(item.text,
outlineTypeTable[item.kind] || SymbolKind.Variable,
containerLabel ? containerLabel : '',
new Location(resource, textSpan2Range(item.spans[0])));
foldingMap[key] = result;
bucket.push(result);
}
if (item.childItems && item.childItems.length > 0) {
for (let child of item.childItems) {
TypeScriptDocumentSymbolProvider.convertNavBar(resource, realIndent + 1, foldingMap, bucket, child, item.text);
}
}
}
private static convertNavTree(resource: Uri, bucket: SymbolInformation[], item: Proto.NavigationTree, containerLabel?: string): void {
const result = new SymbolInformation(item.text,
outlineTypeTable[item.kind] || SymbolKind.Variable,
containerLabel ? containerLabel : '',
new Location(resource, textSpan2Range(item.spans[0]))
);
if (item.childItems && item.childItems.length > 0) {
for (const child of item.childItems) {
TypeScriptDocumentSymbolProvider.convertNavTree(resource, bucket, child, result.name);
}
}
if (TypeScriptDocumentSymbolProvider.shouldInclueEntry(result.name)) {
bucket.push(result);
}
}
private static shouldInclueEntry(name: string): boolean {
return !!(name && name !== '<function>' && name !== '<class>');
}
}
|
keyboard-clacker/vscode
|
src/vs/workbench/parts/tasks/browser/quickOpen.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import nls = require('vs/nls');
import Filters = require('vs/base/common/filters');
import { TPromise } from 'vs/base/common/winjs.base';
import { Action, IAction } from 'vs/base/common/actions';
import Quickopen = require('vs/workbench/browser/quickopen');
import QuickOpen = require('vs/base/parts/quickopen/common/quickOpen');
import Model = require('vs/base/parts/quickopen/browser/quickOpenModel');
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
import { Task, TaskSourceKind, computeLabel } from 'vs/workbench/parts/tasks/common/tasks';
import { ITaskService } from 'vs/workbench/parts/tasks/common/taskService';
import { ActionBarContributor, ContributableActionProvider } from 'vs/workbench/browser/actions';
export class TaskEntry extends Model.QuickOpenEntry {
private _label: string;
constructor(protected taskService: ITaskService, protected _task: Task, highlights: Model.IHighlight[] = []) {
super(highlights);
this._label = computeLabel(_task);
}
public getLabel(): string {
return this._label;
}
public getAriaLabel(): string {
return nls.localize('entryAriaLabel', "{0}, tasks", this.getLabel());
}
public get task(): Task {
return this._task;
}
}
export class TaskGroupEntry extends Model.QuickOpenEntryGroup {
constructor(entry: TaskEntry, groupLabel: string, withBorder: boolean) {
super(entry, groupLabel, withBorder);
}
}
export abstract class QuickOpenHandler extends Quickopen.QuickOpenHandler {
private tasks: TPromise<Task[]>;
constructor(
protected quickOpenService: IQuickOpenService,
protected taskService: ITaskService,
) {
super();
this.quickOpenService = quickOpenService;
this.taskService = taskService;
}
public onOpen(): void {
this.tasks = this.getTasks();
}
public onClose(canceled: boolean): void {
this.tasks = undefined;
}
public getResults(input: string): TPromise<Model.QuickOpenModel> {
return this.tasks.then((tasks) => {
let entries: Model.QuickOpenEntry[] = [];
if (tasks.length === 0) {
return new Model.QuickOpenModel(entries);
}
tasks = tasks.sort((a, b) => {
let aKind = a._source.kind;
let bKind = b._source.kind;
if (aKind === bKind) {
if (aKind === TaskSourceKind.Extension) {
let compare = a._source.label.localeCompare(b._source.label);
if (compare !== 0) {
return compare;
}
}
return a.name.localeCompare(b.name);
}
if (aKind === TaskSourceKind.Workspace) {
return -1;
} else {
return +1;
}
});
let hasWorkspace: boolean = tasks[0]._source.kind === TaskSourceKind.Workspace;
let hasExtension: boolean = tasks[tasks.length - 1]._source.kind === TaskSourceKind.Extension;
let groupWorkspace = hasWorkspace && hasExtension;
let groupExtension = groupWorkspace;
let hadWorkspace = false;
for (let task of tasks) {
let highlights = Filters.matchesContiguousSubString(input, task.name);
if (!highlights) {
continue;
}
if (task._source.kind === TaskSourceKind.Workspace && groupWorkspace) {
groupWorkspace = false;
hadWorkspace = true;
entries.push(new TaskGroupEntry(this.createEntry(this.taskService, task, highlights), nls.localize('configured', 'Configured Tasks'), false));
} else if (task._source.kind === TaskSourceKind.Extension && groupExtension) {
groupExtension = false;
entries.push(new TaskGroupEntry(this.createEntry(this.taskService, task, highlights), nls.localize('detected', 'Detected Tasks'), hadWorkspace));
} else {
entries.push(this.createEntry(this.taskService, task, highlights));
}
}
return new Model.QuickOpenModel(entries, new ContributableActionProvider());
});
}
protected abstract getTasks(): TPromise<Task[]>;
protected abstract createEntry(taskService: ITaskService, task: Task, highlights: Model.IHighlight[]): TaskEntry;
public getAutoFocus(input: string): QuickOpen.IAutoFocus {
return {
autoFocusFirstEntry: !!input
};
}
}
class CustomizeTaskAction extends Action {
private static ID = 'workbench.action.tasks.customizeTask';
private static LABEL = nls.localize('customizeTask', "Customize Task");
constructor(private taskService: ITaskService, private quickOpenService: IQuickOpenService, private task: Task) {
super(CustomizeTaskAction.ID, CustomizeTaskAction.LABEL);
this.updateClass();
}
public updateClass(): void {
this.class = 'quick-open-task-configure';
}
public run(context: any): TPromise<any> {
return this.taskService.customize(this.task, true).then(() => {
this.quickOpenService.close();
});
}
}
export class QuickOpenActionContributor extends ActionBarContributor {
constructor( @ITaskService private taskService: ITaskService, @IQuickOpenService private quickOpenService: IQuickOpenService) {
super();
}
public hasActions(context: any): boolean {
let task = this.getTask(context);
return !!task;
}
public getActions(context: any): IAction[] {
let actions: Action[] = [];
let task = this.getTask(context);
if (task && task._source.kind === TaskSourceKind.Extension) {
actions.push(new CustomizeTaskAction(this.taskService, this.quickOpenService, task));
}
return actions;
}
private getTask(context: any): Task {
if (!context) {
return undefined;
}
let element = context.element;
if (element instanceof TaskEntry) {
return element.task;
} else if (element instanceof TaskGroupEntry) {
return (element.getEntry() as TaskEntry).task;
}
return undefined;
}
}
|
keyboard-clacker/vscode
|
src/vs/code/node/keyboard.ts
|
<filename>src/vs/code/node/keyboard.ts
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as nativeKeymap from 'native-keymap';
import { IDisposable } from 'vs/base/common/lifecycle';
import { isMacintosh } from 'vs/base/common/platform';
import { Emitter } from 'vs/base/common/event';
export class KeyboardLayoutMonitor {
public static readonly INSTANCE = new KeyboardLayoutMonitor();
private _emitter: Emitter<boolean>;
private _registered: boolean;
private _isISOKeyboard: boolean;
private constructor() {
this._emitter = new Emitter<boolean>();
this._registered = false;
this._isISOKeyboard = this._readIsISOKeyboard();
}
public onDidChangeKeyboardLayout(callback: (isISOKeyboard: boolean) => void): IDisposable {
if (!this._registered) {
this._registered = true;
nativeKeymap.onDidChangeKeyboardLayout(() => {
this._emitter.fire(this._isISOKeyboard);
});
if (isMacintosh) {
// See https://github.com/Microsoft/vscode/issues/24153
// On OSX, on ISO keyboards, Chromium swaps the scan codes
// of IntlBackslash and Backquote.
//
// The C++ methods can give the current keyboard type (ISO or not)
// only after a NSEvent was handled.
//
// We therefore poll.
setInterval(() => {
let newValue = this._readIsISOKeyboard();
if (this._isISOKeyboard === newValue) {
// no change
return;
}
this._isISOKeyboard = newValue;
this._emitter.fire(this._isISOKeyboard);
}, 3000);
}
}
return this._emitter.event(callback);
}
private _readIsISOKeyboard(): boolean {
if (isMacintosh) {
return nativeKeymap.isISOKeyboard();
}
return false;
}
public isISOKeyboard(): boolean {
return this._isISOKeyboard;
}
}
|
keyboard-clacker/vscode
|
src/vs/workbench/parts/debug/electron-browser/debugViews.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import { RunOnceScheduler } from 'vs/base/common/async';
import * as dom from 'vs/base/browser/dom';
import * as builder from 'vs/base/browser/builder';
import { TPromise } from 'vs/base/common/winjs.base';
import * as errors from 'vs/base/common/errors';
import { EventType } from 'vs/base/common/events';
import { IActionRunner, IAction } from 'vs/base/common/actions';
import { prepareActions } from 'vs/workbench/browser/actions';
import { IHighlightEvent, ITree } from 'vs/base/parts/tree/browser/tree';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { CollapsibleState } from 'vs/base/browser/ui/splitview/splitview';
import { CollapsibleViewletView, AdaptiveCollapsibleViewletView, CollapseAction } from 'vs/workbench/browser/viewlet';
import { IDebugService, State, IBreakpoint, IExpression, CONTEXT_BREAKPOINTS_FOCUSED, CONTEXT_WATCH_EXPRESSIONS_FOCUSED, CONTEXT_VARIABLES_FOCUSED } from 'vs/workbench/parts/debug/common/debug';
import { Expression, Variable, ExceptionBreakpoint, FunctionBreakpoint, Thread, StackFrame, Breakpoint, ThreadAndProcessIds } from 'vs/workbench/parts/debug/common/debugModel';
import * as viewer from 'vs/workbench/parts/debug/electron-browser/debugViewer';
import { AddWatchExpressionAction, RemoveAllWatchExpressionsAction, AddFunctionBreakpointAction, ToggleBreakpointsActivatedAction, RemoveAllBreakpointsAction } from 'vs/workbench/parts/debug/browser/debugActions';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { MenuId } from 'vs/platform/actions/common/actions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IMessageService } from 'vs/platform/message/common/message';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IListService } from 'vs/platform/list/browser/listService';
import { attachListStyler } from 'vs/platform/theme/common/styler';
import { IThemeService } from 'vs/platform/theme/common/themeService';
function renderViewTree(container: HTMLElement): HTMLElement {
const treeContainer = document.createElement('div');
dom.addClass(treeContainer, 'debug-view-content');
container.appendChild(treeContainer);
return treeContainer;
}
const $ = builder.$;
const twistiePixels = 20;
export class VariablesView extends CollapsibleViewletView {
private static MEMENTO = 'variablesview.memento';
private onFocusStackFrameScheduler: RunOnceScheduler;
private variablesFocusedContext: IContextKey<boolean>;
constructor(
actionRunner: IActionRunner,
private settings: any,
@IMessageService messageService: IMessageService,
@IContextMenuService contextMenuService: IContextMenuService,
@ITelemetryService private telemetryService: ITelemetryService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService private listService: IListService,
@IThemeService private themeService: IThemeService
) {
super(actionRunner, !!settings[VariablesView.MEMENTO], nls.localize('variablesSection', "Variables Section"), messageService, keybindingService, contextMenuService);
this.variablesFocusedContext = CONTEXT_VARIABLES_FOCUSED.bindTo(contextKeyService);
// Use schedulre to prevent unnecessary flashing
this.onFocusStackFrameScheduler = new RunOnceScheduler(() => {
// Always clear tree highlight to avoid ending up in a broken state #12203
this.tree.clearHighlight();
this.tree.refresh().then(() => {
const stackFrame = this.debugService.getViewModel().focusedStackFrame;
if (stackFrame) {
return stackFrame.getScopes().then(scopes => {
if (scopes.length > 0 && !scopes[0].expensive) {
return this.tree.expand(scopes[0]);
}
return undefined;
});
}
return undefined;
}).done(null, errors.onUnexpectedError);
}, 400);
}
public renderHeader(container: HTMLElement): void {
const titleDiv = $('div.title').appendTo(container);
$('span').text(nls.localize('variables', "Variables")).appendTo(titleDiv);
super.renderHeader(container);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-variables');
this.treeContainer = renderViewTree(container);
this.tree = new Tree(this.treeContainer, {
dataSource: new viewer.VariablesDataSource(),
renderer: this.instantiationService.createInstance(viewer.VariablesRenderer),
accessibilityProvider: new viewer.VariablesAccessibilityProvider(),
controller: this.instantiationService.createInstance(viewer.VariablesController, new viewer.VariablesActionProvider(this.instantiationService), MenuId.DebugVariablesContext)
}, {
ariaLabel: nls.localize('variablesAriaTreeLabel', "Debug Variables"),
twistiePixels,
keyboardSupport: false
});
this.toDispose.push(attachListStyler(this.tree, this.themeService));
this.toDispose.push(this.listService.register(this.tree, [this.variablesFocusedContext]));
const viewModel = this.debugService.getViewModel();
this.tree.setInput(viewModel);
const collapseAction = this.instantiationService.createInstance(CollapseAction, this.tree, false, 'explorer-action collapse-explorer');
this.toolBar.setActions(prepareActions([collapseAction]))();
this.toDispose.push(viewModel.onDidFocusStackFrame(sf => {
// Refresh the tree immediatly if it is not visible.
// Otherwise postpone the refresh until user stops stepping.
if (!this.tree.getContentHeight()) {
this.onFocusStackFrameScheduler.schedule(0);
} else {
this.onFocusStackFrameScheduler.schedule();
}
}));
this.toDispose.push(this.debugService.onDidChangeState(state => {
collapseAction.enabled = state === State.Running || state === State.Stopped;
}));
this.toDispose.push(this.debugService.getViewModel().onDidSelectExpression(expression => {
if (!expression || !(expression instanceof Variable)) {
return;
}
this.tree.refresh(expression, false).then(() => {
this.tree.setHighlight(expression);
this.tree.addOneTimeListener(EventType.HIGHLIGHT, (e: IHighlightEvent) => {
if (!e.highlight) {
this.debugService.getViewModel().setSelectedExpression(null);
}
});
}).done(null, errors.onUnexpectedError);
}));
}
public shutdown(): void {
this.settings[VariablesView.MEMENTO] = (this.state === CollapsibleState.COLLAPSED);
super.shutdown();
}
}
export class WatchExpressionsView extends CollapsibleViewletView {
private static MEMENTO = 'watchexpressionsview.memento';
private onWatchExpressionsUpdatedScheduler: RunOnceScheduler;
private toReveal: IExpression;
private watchExpressionsFocusedContext: IContextKey<boolean>;
constructor(
actionRunner: IActionRunner,
private settings: any,
@IMessageService messageService: IMessageService,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService private listService: IListService,
@IThemeService private themeService: IThemeService
) {
super(actionRunner, !!settings[WatchExpressionsView.MEMENTO], nls.localize('expressionsSection', "Expressions Section"), messageService, keybindingService, contextMenuService);
this.toDispose.push(this.debugService.getModel().onDidChangeWatchExpressions(we => {
// only expand when a new watch expression is added.
if (we instanceof Expression) {
this.expand();
}
}));
this.watchExpressionsFocusedContext = CONTEXT_WATCH_EXPRESSIONS_FOCUSED.bindTo(contextKeyService);
this.onWatchExpressionsUpdatedScheduler = new RunOnceScheduler(() => {
this.tree.refresh().done(() => {
return this.toReveal instanceof Expression ? this.tree.reveal(this.toReveal) : TPromise.as(true);
}, errors.onUnexpectedError);
}, 50);
}
public renderHeader(container: HTMLElement): void {
const titleDiv = $('div.title').appendTo(container);
$('span').text(nls.localize('watch', "Watch")).appendTo(titleDiv);
super.renderHeader(container);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-watch');
this.treeContainer = renderViewTree(container);
const actionProvider = new viewer.WatchExpressionsActionProvider(this.instantiationService);
this.tree = new Tree(this.treeContainer, {
dataSource: new viewer.WatchExpressionsDataSource(),
renderer: this.instantiationService.createInstance(viewer.WatchExpressionsRenderer, actionProvider, this.actionRunner),
accessibilityProvider: new viewer.WatchExpressionsAccessibilityProvider(),
controller: this.instantiationService.createInstance(viewer.WatchExpressionsController, actionProvider, MenuId.DebugWatchContext),
dnd: this.instantiationService.createInstance(viewer.WatchExpressionsDragAndDrop)
}, {
ariaLabel: nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'watchAriaTreeLabel' }, "Debug Watch Expressions"),
twistiePixels,
keyboardSupport: false
});
this.toDispose.push(attachListStyler(this.tree, this.themeService));
this.toDispose.push(this.listService.register(this.tree, [this.watchExpressionsFocusedContext]));
this.tree.setInput(this.debugService.getModel());
const addWatchExpressionAction = this.instantiationService.createInstance(AddWatchExpressionAction, AddWatchExpressionAction.ID, AddWatchExpressionAction.LABEL);
const collapseAction = this.instantiationService.createInstance(CollapseAction, this.tree, true, 'explorer-action collapse-explorer');
const removeAllWatchExpressionsAction = this.instantiationService.createInstance(RemoveAllWatchExpressionsAction, RemoveAllWatchExpressionsAction.ID, RemoveAllWatchExpressionsAction.LABEL);
this.toolBar.setActions(prepareActions([addWatchExpressionAction, collapseAction, removeAllWatchExpressionsAction]))();
this.toDispose.push(this.debugService.getModel().onDidChangeWatchExpressions(we => {
if (!this.onWatchExpressionsUpdatedScheduler.isScheduled()) {
this.onWatchExpressionsUpdatedScheduler.schedule();
}
this.toReveal = we;
}));
this.toDispose.push(this.debugService.getViewModel().onDidSelectExpression(expression => {
if (!expression || !(expression instanceof Expression)) {
return;
}
this.tree.refresh(expression, false).then(() => {
this.tree.setHighlight(expression);
this.tree.addOneTimeListener(EventType.HIGHLIGHT, (e: IHighlightEvent) => {
if (!e.highlight) {
this.debugService.getViewModel().setSelectedExpression(null);
}
});
}).done(null, errors.onUnexpectedError);
}));
}
public shutdown(): void {
this.settings[WatchExpressionsView.MEMENTO] = (this.state === CollapsibleState.COLLAPSED);
super.shutdown();
}
}
export class CallStackView extends CollapsibleViewletView {
private static MEMENTO = 'callstackview.memento';
private pauseMessage: builder.Builder;
private pauseMessageLabel: builder.Builder;
private onCallStackChangeScheduler: RunOnceScheduler;
constructor(
actionRunner: IActionRunner,
private settings: any,
@IMessageService messageService: IMessageService,
@IContextMenuService contextMenuService: IContextMenuService,
@ITelemetryService private telemetryService: ITelemetryService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IListService private listService: IListService,
@IThemeService private themeService: IThemeService
) {
super(actionRunner, !!settings[CallStackView.MEMENTO], nls.localize('callstackSection', "Call Stack Section"), messageService, keybindingService, contextMenuService);
// Create scheduler to prevent unnecessary flashing of tree when reacting to changes
this.onCallStackChangeScheduler = new RunOnceScheduler(() => {
let newTreeInput: any = this.debugService.getModel();
const processes = this.debugService.getModel().getProcesses();
if (!this.debugService.getViewModel().isMultiProcessView() && processes.length) {
const threads = processes[0].getAllThreads();
// Only show the threads in the call stack if there is more than 1 thread.
newTreeInput = threads.length === 1 ? threads[0] : processes[0];
}
// Only show the global pause message if we do not display threads.
// Otherwsie there will be a pause message per thread and there is no need for a global one.
if (newTreeInput instanceof Thread && newTreeInput.stoppedDetails) {
this.pauseMessageLabel.text(newTreeInput.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", newTreeInput.stoppedDetails.reason));
if (newTreeInput.stoppedDetails.text) {
this.pauseMessageLabel.title(newTreeInput.stoppedDetails.text);
}
newTreeInput.stoppedDetails.reason === 'exception' ? this.pauseMessageLabel.addClass('exception') : this.pauseMessageLabel.removeClass('exception');
this.pauseMessage.show();
} else {
this.pauseMessage.hide();
}
(this.tree.getInput() === newTreeInput ? this.tree.refresh() : this.tree.setInput(newTreeInput))
.done(() => this.updateTreeSelection(), errors.onUnexpectedError);
}, 50);
}
public renderHeader(container: HTMLElement): void {
const title = $('div.debug-call-stack-title').appendTo(container);
$('span.title').text(nls.localize('callStack', "Call Stack")).appendTo(title);
this.pauseMessage = $('span.pause-message').appendTo(title);
this.pauseMessage.hide();
this.pauseMessageLabel = $('span.label').appendTo(this.pauseMessage);
super.renderHeader(container);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-call-stack');
this.treeContainer = renderViewTree(container);
const actionProvider = this.instantiationService.createInstance(viewer.CallStackActionProvider);
const controller = this.instantiationService.createInstance(viewer.CallStackController, actionProvider, MenuId.DebugCallStackContext);
this.tree = new Tree(this.treeContainer, {
dataSource: this.instantiationService.createInstance(viewer.CallStackDataSource),
renderer: this.instantiationService.createInstance(viewer.CallStackRenderer),
accessibilityProvider: this.instantiationService.createInstance(viewer.CallstackAccessibilityProvider),
controller
}, {
ariaLabel: nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'callStackAriaLabel' }, "Debug Call Stack"),
twistiePixels,
keyboardSupport: false
});
this.toDispose.push(attachListStyler(this.tree, this.themeService));
this.toDispose.push(this.listService.register(this.tree));
this.toDispose.push(this.tree.addListener('selection', event => {
if (event && event.payload && event.payload.origin === 'keyboard') {
const element = this.tree.getFocus();
if (element instanceof ThreadAndProcessIds) {
controller.showMoreStackFrames(this.tree, element);
} else if (element instanceof StackFrame) {
controller.focusStackFrame(element, event, false);
}
}
}));
this.toDispose.push(this.debugService.getModel().onDidChangeCallStack(() => {
if (!this.onCallStackChangeScheduler.isScheduled()) {
this.onCallStackChangeScheduler.schedule();
}
}));
this.toDispose.push(this.debugService.getViewModel().onDidFocusStackFrame(() =>
this.updateTreeSelection().done(undefined, errors.onUnexpectedError)));
// Schedule the update of the call stack tree if the viewlet is opened after a session started #14684
if (this.debugService.state === State.Stopped) {
this.onCallStackChangeScheduler.schedule();
}
}
private updateTreeSelection(): TPromise<void> {
if (!this.tree.getInput()) {
// Tree not initialitized yet
return TPromise.as(null);
}
const stackFrame = this.debugService.getViewModel().focusedStackFrame;
const process = this.debugService.getViewModel().focusedProcess;
if (!stackFrame) {
if (!process) {
this.tree.clearSelection();
return TPromise.as(null);
}
this.tree.setSelection([process]);
return this.tree.reveal(process);
}
const thread = stackFrame.thread;
return this.tree.expandAll([thread.process, thread]).then(() => {
this.tree.setSelection([stackFrame]);
return this.tree.reveal(stackFrame);
});
}
public shutdown(): void {
this.settings[CallStackView.MEMENTO] = (this.state === CollapsibleState.COLLAPSED);
super.shutdown();
}
}
export class BreakpointsView extends AdaptiveCollapsibleViewletView {
private static MAX_VISIBLE_FILES = 9;
private static MEMENTO = 'breakopintsview.memento';
private breakpointsFocusedContext: IContextKey<boolean>;
constructor(
actionRunner: IActionRunner,
private settings: any,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService private instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService private listService: IListService,
@IThemeService private themeService: IThemeService
) {
super(actionRunner, BreakpointsView.getExpandedBodySize(
debugService.getModel().getBreakpoints().length + debugService.getModel().getFunctionBreakpoints().length + debugService.getModel().getExceptionBreakpoints().length),
!!settings[BreakpointsView.MEMENTO], nls.localize('breakpointsSection', "Breakpoints Section"), keybindingService, contextMenuService);
this.breakpointsFocusedContext = CONTEXT_BREAKPOINTS_FOCUSED.bindTo(contextKeyService);
this.toDispose.push(this.debugService.getModel().onDidChangeBreakpoints(() => this.onBreakpointsChange()));
}
public renderHeader(container: HTMLElement): void {
const titleDiv = $('div.title').appendTo(container);
$('span').text(nls.localize('breakpoints', "Breakpoints")).appendTo(titleDiv);
super.renderHeader(container);
}
public renderBody(container: HTMLElement): void {
dom.addClass(container, 'debug-breakpoints');
this.treeContainer = renderViewTree(container);
const actionProvider = new viewer.BreakpointsActionProvider(this.instantiationService, this.debugService);
const controller = this.instantiationService.createInstance(viewer.BreakpointsController, actionProvider, MenuId.DebugBreakpointsContext);
this.tree = new Tree(this.treeContainer, {
dataSource: new viewer.BreakpointsDataSource(),
renderer: this.instantiationService.createInstance(viewer.BreakpointsRenderer, actionProvider, this.actionRunner),
accessibilityProvider: this.instantiationService.createInstance(viewer.BreakpointsAccessibilityProvider),
controller,
sorter: {
compare(tree: ITree, element: any, otherElement: any): number {
const first = <IBreakpoint>element;
const second = <IBreakpoint>otherElement;
if (first instanceof ExceptionBreakpoint) {
return -1;
}
if (second instanceof ExceptionBreakpoint) {
return 1;
}
if (first instanceof FunctionBreakpoint) {
return -1;
}
if (second instanceof FunctionBreakpoint) {
return 1;
}
if (first.uri.toString() !== second.uri.toString()) {
return paths.basename(first.uri.fsPath).localeCompare(paths.basename(second.uri.fsPath));
}
if (first.lineNumber === second.lineNumber) {
return first.column - second.column;
}
return first.lineNumber - second.lineNumber;
}
}
}, {
ariaLabel: nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'breakpointsAriaTreeLabel' }, "Debug Breakpoints"),
twistiePixels,
keyboardSupport: false
});
this.toDispose.push(attachListStyler(this.tree, this.themeService));
this.toDispose.push(this.listService.register(this.tree, [this.breakpointsFocusedContext]));
this.toDispose.push(this.tree.addListener('selection', event => {
if (event && event.payload && event.payload.origin === 'keyboard') {
const element = this.tree.getFocus();
if (element instanceof Breakpoint) {
controller.openBreakpointSource(element, event, false);
}
}
}));
const debugModel = this.debugService.getModel();
this.tree.setInput(debugModel);
this.toDispose.push(this.debugService.getViewModel().onDidSelectFunctionBreakpoint(fbp => {
if (!fbp || !(fbp instanceof FunctionBreakpoint)) {
return;
}
this.tree.refresh(fbp, false).then(() => {
this.tree.setHighlight(fbp);
this.tree.addOneTimeListener(EventType.HIGHLIGHT, (e: IHighlightEvent) => {
if (!e.highlight) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(null);
}
});
}).done(null, errors.onUnexpectedError);
}));
}
public getActions(): IAction[] {
return [
this.instantiationService.createInstance(AddFunctionBreakpointAction, AddFunctionBreakpointAction.ID, AddFunctionBreakpointAction.LABEL),
this.instantiationService.createInstance(ToggleBreakpointsActivatedAction, ToggleBreakpointsActivatedAction.ID, ToggleBreakpointsActivatedAction.ACTIVATE_LABEL),
this.instantiationService.createInstance(RemoveAllBreakpointsAction, RemoveAllBreakpointsAction.ID, RemoveAllBreakpointsAction.LABEL)
];
}
private onBreakpointsChange(): void {
const model = this.debugService.getModel();
this.expandedBodySize = BreakpointsView.getExpandedBodySize(
model.getBreakpoints().length + model.getExceptionBreakpoints().length + model.getFunctionBreakpoints().length);
if (this.tree) {
this.tree.refresh();
}
}
private static getExpandedBodySize(length: number): number {
return Math.min(BreakpointsView.MAX_VISIBLE_FILES, length) * 22;
}
public shutdown(): void {
this.settings[BreakpointsView.MEMENTO] = (this.state === CollapsibleState.COLLAPSED);
super.shutdown();
}
}
|
keyboard-clacker/vscode
|
src/vs/workbench/parts/views/browser/views.ts
|
<reponame>keyboard-clacker/vscode
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import Event, { Emitter } from 'vs/base/common/event';
import { IActionRunner } from 'vs/base/common/actions';
import { IViewletView as IView } from 'vs/workbench/browser/viewlet';
export class ViewLocation {
static readonly Explorer = new ViewLocation('explorer');
constructor(private _id: string) {
}
get id(): string {
return this._id;
}
}
export enum TreeItemCollapsibleState {
None = 0,
Collapsed = 1,
Expanded = 2
}
export interface IViewOptions {
name: string;
actionRunner: IActionRunner;
collapsed: boolean;
}
export interface IViewConstructorSignature {
new (id: string, options: IViewOptions, ...services: { _serviceBrand: any; }[]): IView;
}
export interface IViewDescriptor {
readonly id: string;
readonly name: string;
readonly location: ViewLocation;
readonly ctor: IViewConstructorSignature;
readonly order?: number;
}
export interface ITreeItem {
handle: number;
label: string;
icon?: string;
iconDark?: string;
contextValue?: string;
commandId?: string;
children?: ITreeItem[];
collapsibleState?: TreeItemCollapsibleState;
}
export interface ITreeViewDataProvider {
onDidChange: Event<ITreeItem | undefined | null>;
getElements(): TPromise<ITreeItem[]>;
getChildren(element: ITreeItem): TPromise<ITreeItem[]>;
}
export interface IViewsRegistry {
readonly onViewsRegistered: Event<IViewDescriptor[]>;
readonly onTreeViewDataProviderRegistered: Event<string>;
registerViews(views: IViewDescriptor[]): void;
registerTreeViewDataProvider(id: string, factory: ITreeViewDataProvider): void;
getViews(loc: ViewLocation): IViewDescriptor[];
getTreeViewDataProvider(id: string): ITreeViewDataProvider;
}
export const ViewsRegistry: IViewsRegistry = new class {
private _onViewsRegistered: Emitter<IViewDescriptor[]> = new Emitter<IViewDescriptor[]>();
readonly onViewsRegistered: Event<IViewDescriptor[]> = this._onViewsRegistered.event;
private _onTreeViewDataProviderRegistered: Emitter<string> = new Emitter<string>();
readonly onTreeViewDataProviderRegistered: Event<string> = this._onTreeViewDataProviderRegistered.event;
private _views: Map<ViewLocation, IViewDescriptor[]> = new Map<ViewLocation, IViewDescriptor[]>();
private _treeViewDataPoviders: Map<string, ITreeViewDataProvider> = new Map<string, ITreeViewDataProvider>();
registerViews(viewDescriptors: IViewDescriptor[]): void {
if (viewDescriptors.length) {
for (const viewDescriptor of viewDescriptors) {
let views = this._views.get(viewDescriptor.location);
if (!views) {
views = [];
this._views.set(viewDescriptor.location, views);
}
views.push(viewDescriptor);
}
this._onViewsRegistered.fire(viewDescriptors);
}
}
registerTreeViewDataProvider<T>(id: string, factory: ITreeViewDataProvider) {
if (!this.isViewRegistered(id)) {
// TODO: throw error
}
this._treeViewDataPoviders.set(id, factory);
this._onTreeViewDataProviderRegistered.fire(id);
}
getViews(loc: ViewLocation): IViewDescriptor[] {
return this._views.get(loc) || [];
}
getTreeViewDataProvider(id: string): ITreeViewDataProvider {
return this._treeViewDataPoviders.get(id);
}
private isViewRegistered(id: string): boolean {
let registered = false;
this._views.forEach(views => registered = registered || views.some(view => view.id === id));
return registered;
}
};
|
keyboard-clacker/vscode
|
src/vs/workbench/browser/parts/activitybar/activitybarActions.ts
|
<gh_stars>0
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./media/activityaction';
import nls = require('vs/nls');
import DOM = require('vs/base/browser/dom');
import { TPromise } from 'vs/base/common/winjs.base';
import { Builder, $ } from 'vs/base/browser/builder';
import { DelayedDragHandler } from 'vs/base/browser/dnd';
import { Action } from 'vs/base/common/actions';
import { BaseActionItem, Separator, IBaseActionItemOptions } from 'vs/base/browser/ui/actionbar/actionbar';
import { IActivityBarService, ProgressBadge, TextBadge, NumberBadge, IconBadge, IBadge } from 'vs/workbench/services/activity/common/activityBarService';
import Event, { Emitter } from 'vs/base/common/event';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ViewletDescriptor } from 'vs/workbench/browser/viewlet';
import { IActivity, IGlobalActivity } from 'vs/workbench/browser/activity';
import { dispose } from 'vs/base/common/lifecycle';
import { IViewletService, } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { IThemeService, ITheme, registerThemingParticipant, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
import { ACTIVITY_BAR_BADGE_FOREGROUND, ACTIVITY_BAR_BADGE_BACKGROUND, ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND, ACTIVITY_BAR_FOREGROUND } from 'vs/workbench/common/theme';
import { contrastBorder, activeContrastBorder, focusBorder } from 'vs/platform/theme/common/colorRegistry';
import { StandardMouseEvent } from "vs/base/browser/mouseEvent";
export interface IViewletActivity {
badge: IBadge;
clazz: string;
}
export class ActivityAction extends Action {
private badge: IBadge;
private _onDidChangeBadge = new Emitter<this>();
constructor(private _activity: IActivity) {
super(_activity.id, _activity.name, _activity.cssClass);
this.badge = null;
}
public get activity(): IActivity {
return this._activity;
}
public get onDidChangeBadge(): Event<this> {
return this._onDidChangeBadge.event;
}
public activate(): void {
if (!this.checked) {
this._setChecked(true);
}
}
public deactivate(): void {
if (this.checked) {
this._setChecked(false);
}
}
public getBadge(): IBadge {
return this.badge;
}
public setBadge(badge: IBadge): void {
this.badge = badge;
this._onDidChangeBadge.fire(this);
}
}
export class ViewletActivityAction extends ActivityAction {
private static preventDoubleClickDelay = 300;
private lastRun: number = 0;
constructor(
private viewlet: ViewletDescriptor,
@IViewletService private viewletService: IViewletService,
@IPartService private partService: IPartService
) {
super(viewlet);
}
public run(event): TPromise<any> {
if (event instanceof MouseEvent && event.button === 2) {
return TPromise.as(false); // do not run on right click
}
// prevent accident trigger on a doubleclick (to help nervous people)
const now = Date.now();
if (now > this.lastRun /* https://github.com/Microsoft/vscode/issues/25830 */ && now - this.lastRun < ViewletActivityAction.preventDoubleClickDelay) {
return TPromise.as(true);
}
this.lastRun = now;
const sideBarVisible = this.partService.isVisible(Parts.SIDEBAR_PART);
const activeViewlet = this.viewletService.getActiveViewlet();
// Hide sidebar if selected viewlet already visible
if (sideBarVisible && activeViewlet && activeViewlet.getId() === this.viewlet.id) {
return this.partService.setSideBarHidden(true);
}
return this.viewletService.openViewlet(this.viewlet.id, true)
.then(() => this.activate());
}
}
export class ActivityActionItem extends BaseActionItem {
protected $container: Builder;
protected $label: Builder;
protected $badge: Builder;
private $badgeContent: Builder;
private mouseUpTimeout: number;
constructor(
action: ActivityAction,
options: IBaseActionItemOptions,
@IThemeService protected themeService: IThemeService
) {
super(null, action, options);
this.themeService.onThemeChange(this.onThemeChange, this, this._callOnDispose);
action.onDidChangeBadge(this.handleBadgeChangeEvenet, this, this._callOnDispose);
}
protected get activity(): IActivity {
return (this._action as ActivityAction).activity;
}
protected updateStyles(): void {
const theme = this.themeService.getTheme();
// Label
if (this.$label) {
const background = theme.getColor(ACTIVITY_BAR_FOREGROUND);
this.$label.style('background-color', background ? background.toString() : null);
}
// Badge
if (this.$badgeContent) {
const badgeForeground = theme.getColor(ACTIVITY_BAR_BADGE_FOREGROUND);
const badgeBackground = theme.getColor(ACTIVITY_BAR_BADGE_BACKGROUND);
const contrastBorderColor = theme.getColor(contrastBorder);
this.$badgeContent.style('color', badgeForeground ? badgeForeground.toString() : null);
this.$badgeContent.style('background-color', badgeBackground ? badgeBackground.toString() : null);
this.$badgeContent.style('border-style', contrastBorderColor ? 'solid' : null);
this.$badgeContent.style('border-width', contrastBorderColor ? '1px' : null);
this.$badgeContent.style('border-color', contrastBorderColor ? contrastBorderColor.toString() : null);
}
}
public render(container: HTMLElement): void {
super.render(container);
// Make the container tab-able for keyboard navigation
this.$container = $(container).attr({
tabIndex: '0',
role: 'button',
title: this.activity.name
});
// Try hard to prevent keyboard only focus feedback when using mouse
this.$container.on(DOM.EventType.MOUSE_DOWN, () => {
this.$container.addClass('clicked');
});
this.$container.on(DOM.EventType.MOUSE_UP, () => {
if (this.mouseUpTimeout) {
clearTimeout(this.mouseUpTimeout);
}
this.mouseUpTimeout = setTimeout(() => {
this.$container.removeClass('clicked');
}, 800); // delayed to prevent focus feedback from showing on mouse up
});
// Label
this.$label = $('a.action-label').appendTo(this.builder);
if (this.activity.cssClass) {
this.$label.addClass(this.activity.cssClass);
}
this.$badge = this.builder.clone().div({ 'class': 'badge' }, (badge: Builder) => {
this.$badgeContent = badge.div({ 'class': 'badge-content' });
});
this.$badge.hide();
this.updateStyles();
}
private onThemeChange(theme: ITheme): void {
this.updateStyles();
}
public setBadge(badge: IBadge): void {
this.updateBadge(badge);
}
protected updateBadge(badge: IBadge): void {
this.$badgeContent.empty();
this.$badge.hide();
if (badge) {
// Number
if (badge instanceof NumberBadge) {
if (badge.number) {
this.$badgeContent.text(badge.number > 99 ? '99+' : badge.number.toString());
this.$badge.show();
}
}
// Text
else if (badge instanceof TextBadge) {
this.$badgeContent.text(badge.text);
this.$badge.show();
}
// Text
else if (badge instanceof IconBadge) {
this.$badge.show();
}
// Progress
else if (badge instanceof ProgressBadge) {
this.$badge.show();
}
this.$label.attr('aria-label', `${this.activity.name} - ${badge.getDescription()}`);
}
}
private handleBadgeChangeEvenet(): void {
const action = this.getAction();
if (action instanceof ActivityAction) {
this.updateBadge(action.getBadge());
}
}
public dispose(): void {
super.dispose();
if (this.mouseUpTimeout) {
clearTimeout(this.mouseUpTimeout);
}
this.$badge.destroy();
}
}
export class ViewletActionItem extends ActivityActionItem {
private static manageExtensionAction: ManageExtensionAction;
private static toggleViewletPinnedAction: ToggleViewletPinnedAction;
private static draggedViewlet: ViewletDescriptor;
private _keybinding: string;
private cssClass: string;
constructor(
private action: ViewletActivityAction,
@IContextMenuService private contextMenuService: IContextMenuService,
@IActivityBarService private activityBarService: IActivityBarService,
@IKeybindingService private keybindingService: IKeybindingService,
@IInstantiationService instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService
) {
super(action, { draggable: true }, themeService);
this.cssClass = action.class;
this._keybinding = this.getKeybindingLabel(this.viewlet.id);
if (!ViewletActionItem.manageExtensionAction) {
ViewletActionItem.manageExtensionAction = instantiationService.createInstance(ManageExtensionAction);
}
if (!ViewletActionItem.toggleViewletPinnedAction) {
ViewletActionItem.toggleViewletPinnedAction = instantiationService.createInstance(ToggleViewletPinnedAction, void 0);
}
}
private get viewlet(): ViewletDescriptor {
return this.action.activity as ViewletDescriptor;
}
private getKeybindingLabel(id: string): string {
const kb = this.keybindingService.lookupKeybinding(id);
if (kb) {
return kb.getLabel();
}
return null;
}
public render(container: HTMLElement): void {
super.render(container);
this.$container.on('contextmenu', e => {
DOM.EventHelper.stop(e, true);
this.showContextMenu(container);
});
// Allow to drag
this.$container.on(DOM.EventType.DRAG_START, (e: DragEvent) => {
e.dataTransfer.effectAllowed = 'move';
this.setDraggedViewlet(this.viewlet);
// Trigger the action even on drag start to prevent clicks from failing that started a drag
if (!this.getAction().checked) {
this.getAction().run();
}
});
// Drag enter
let counter = 0; // see https://github.com/Microsoft/vscode/issues/14470
this.$container.on(DOM.EventType.DRAG_ENTER, (e: DragEvent) => {
const draggedViewlet = ViewletActionItem.getDraggedViewlet();
if (draggedViewlet && draggedViewlet.id !== this.viewlet.id) {
counter++;
this.updateFromDragging(container, true);
}
});
// Drag leave
this.$container.on(DOM.EventType.DRAG_LEAVE, (e: DragEvent) => {
const draggedViewlet = ViewletActionItem.getDraggedViewlet();
if (draggedViewlet) {
counter--;
if (counter === 0) {
this.updateFromDragging(container, false);
}
}
});
// Drag end
this.$container.on(DOM.EventType.DRAG_END, (e: DragEvent) => {
const draggedViewlet = ViewletActionItem.getDraggedViewlet();
if (draggedViewlet) {
counter = 0;
this.updateFromDragging(container, false);
ViewletActionItem.clearDraggedViewlet();
}
});
// Drop
this.$container.on(DOM.EventType.DROP, (e: DragEvent) => {
DOM.EventHelper.stop(e, true);
const draggedViewlet = ViewletActionItem.getDraggedViewlet();
if (draggedViewlet && draggedViewlet.id !== this.viewlet.id) {
this.updateFromDragging(container, false);
ViewletActionItem.clearDraggedViewlet();
this.activityBarService.move(draggedViewlet.id, this.viewlet.id);
}
});
// Keybinding
this.keybinding = this._keybinding; // force update
// Activate on drag over to reveal targets
[this.$badge, this.$label].forEach(b => new DelayedDragHandler(b.getHTMLElement(), () => {
if (!ViewletActionItem.getDraggedViewlet() && !this.getAction().checked) {
this.getAction().run();
}
}));
this.updateStyles();
}
private updateFromDragging(element: HTMLElement, isDragging: boolean): void {
const theme = this.themeService.getTheme();
const dragBackground = theme.getColor(ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND);
element.style.backgroundColor = isDragging && dragBackground ? dragBackground.toString() : null;
}
public static getDraggedViewlet(): ViewletDescriptor {
return ViewletActionItem.draggedViewlet;
}
private setDraggedViewlet(viewlet: ViewletDescriptor): void {
ViewletActionItem.draggedViewlet = viewlet;
}
public static clearDraggedViewlet(): void {
ViewletActionItem.draggedViewlet = void 0;
}
private showContextMenu(container: HTMLElement): void {
const actions: Action[] = [ViewletActionItem.toggleViewletPinnedAction];
if (this.viewlet.extensionId) {
actions.push(new Separator());
actions.push(ViewletActionItem.manageExtensionAction);
}
const isPinned = this.activityBarService.isPinned(this.viewlet.id);
if (isPinned) {
ViewletActionItem.toggleViewletPinnedAction.label = nls.localize('removeFromActivityBar', "Remove from Activity Bar");
} else {
ViewletActionItem.toggleViewletPinnedAction.label = nls.localize('keepInActivityBar', "Keep in Activity Bar");
}
this.contextMenuService.showContextMenu({
getAnchor: () => container,
getActionsContext: () => this.viewlet,
getActions: () => TPromise.as(actions)
});
}
public focus(): void {
this.$container.domFocus();
}
public set keybinding(keybinding: string) {
this._keybinding = keybinding;
if (!this.$label) {
return;
}
let title: string;
if (keybinding) {
title = nls.localize('titleKeybinding', "{0} ({1})", this.activity.name, keybinding);
} else {
title = this.activity.name;
}
this.$label.title(title);
this.$badge.title(title);
}
protected _updateClass(): void {
if (this.cssClass) {
this.$badge.removeClass(this.cssClass);
}
this.cssClass = this.getAction().class;
this.$badge.addClass(this.cssClass);
}
protected _updateChecked(): void {
if (this.getAction().checked) {
this.$container.addClass('active');
} else {
this.$container.removeClass('active');
}
}
protected _updateEnabled(): void {
if (this.getAction().enabled) {
this.builder.removeClass('disabled');
} else {
this.builder.addClass('disabled');
}
}
public dispose(): void {
super.dispose();
ViewletActionItem.clearDraggedViewlet();
this.$label.destroy();
}
}
export class ViewletOverflowActivityAction extends ActivityAction {
constructor(
private showMenu: () => void
) {
super({
id: 'activitybar.additionalViewlets.action',
name: nls.localize('additionalViews', "Additional Views"),
cssClass: 'toggle-more'
});
}
public run(event): TPromise<any> {
this.showMenu();
return TPromise.as(true);
}
}
export class ViewletOverflowActivityActionItem extends ActivityActionItem {
private name: string;
private cssClass: string;
private actions: OpenViewletAction[];
constructor(
action: ActivityAction,
private getOverflowingViewlets: () => ViewletDescriptor[],
private getBadge: (viewlet: ViewletDescriptor) => IBadge,
@IInstantiationService private instantiationService: IInstantiationService,
@IViewletService private viewletService: IViewletService,
@IContextMenuService private contextMenuService: IContextMenuService,
@IThemeService themeService: IThemeService
) {
super(action, null, themeService);
this.cssClass = action.class;
this.name = action.label;
}
protected updateStyles(): void {
const theme = this.themeService.getTheme();
// Label
if (this.$label) {
const background = theme.getColor(ACTIVITY_BAR_FOREGROUND);
this.$label.style('background-color', background ? background.toString() : null);
}
}
public render(container: HTMLElement): void {
super.render(container);
this.$label = $('a.action-label').attr({
tabIndex: '0',
role: 'button',
title: this.name,
class: this.cssClass
}).appendTo(this.builder);
this.updateStyles();
}
public showMenu(): void {
if (this.actions) {
dispose(this.actions);
}
this.actions = this.getActions();
this.contextMenuService.showContextMenu({
getAnchor: () => this.builder.getHTMLElement(),
getActions: () => TPromise.as(this.actions),
onHide: () => dispose(this.actions)
});
}
private getActions(): OpenViewletAction[] {
const activeViewlet = this.viewletService.getActiveViewlet();
return this.getOverflowingViewlets().map(viewlet => {
const action = this.instantiationService.createInstance(OpenViewletAction, viewlet);
action.radio = activeViewlet && activeViewlet.getId() === action.id;
const badge = this.getBadge(action.viewlet);
let suffix: string | number;
if (badge instanceof NumberBadge) {
suffix = badge.number;
} else if (badge instanceof TextBadge) {
suffix = badge.text;
}
if (suffix) {
action.label = nls.localize('numberBadge', "{0} ({1})", action.viewlet.name, suffix);
} else {
action.label = action.viewlet.name;
}
return action;
});
}
public dispose(): void {
super.dispose();
this.actions = dispose(this.actions);
}
}
class ManageExtensionAction extends Action {
constructor(
@ICommandService private commandService: ICommandService
) {
super('activitybar.manage.extension', nls.localize('manageExtension', "Manage Extension"));
}
public run(viewlet: ViewletDescriptor): TPromise<any> {
return this.commandService.executeCommand('_extensions.manage', viewlet.extensionId);
}
}
class OpenViewletAction extends Action {
constructor(
private _viewlet: ViewletDescriptor,
@IPartService private partService: IPartService,
@IViewletService private viewletService: IViewletService
) {
super(_viewlet.id, _viewlet.name);
}
public get viewlet(): ViewletDescriptor {
return this._viewlet;
}
public run(): TPromise<any> {
const sideBarVisible = this.partService.isVisible(Parts.SIDEBAR_PART);
const activeViewlet = this.viewletService.getActiveViewlet();
// Hide sidebar if selected viewlet already visible
if (sideBarVisible && activeViewlet && activeViewlet.getId() === this.viewlet.id) {
return this.partService.setSideBarHidden(true);
}
return this.viewletService.openViewlet(this.viewlet.id, true);
}
}
export class ToggleViewletPinnedAction extends Action {
constructor(
private viewlet: ViewletDescriptor,
@IActivityBarService private activityBarService: IActivityBarService
) {
super('activitybar.show.toggleViewletPinned', viewlet ? viewlet.name : nls.localize('toggle', "Toggle View Pinned"));
this.checked = this.viewlet && this.activityBarService.isPinned(this.viewlet.id);
}
public run(context?: ViewletDescriptor): TPromise<any> {
const viewlet = this.viewlet || context;
if (this.activityBarService.isPinned(viewlet.id)) {
this.activityBarService.unpin(viewlet.id);
} else {
this.activityBarService.pin(viewlet.id);
}
return TPromise.as(true);
}
}
export class GlobalActivityAction extends ActivityAction {
constructor(activity: IGlobalActivity) {
super(activity);
}
}
export class GlobalActivityActionItem extends ActivityActionItem {
constructor(
action: GlobalActivityAction,
@IThemeService themeService: IThemeService,
@IContextMenuService protected contextMenuService: IContextMenuService
) {
super(action, { draggable: false }, themeService);
}
public onClick(e: MouseEvent): void {
const globalAction = this._action as GlobalActivityAction;
const activity = globalAction.activity as IGlobalActivity;
const actions = activity.getActions();
const event = new StandardMouseEvent(e);
event.stopPropagation();
event.preventDefault();
this.contextMenuService.showContextMenu({
getAnchor: () => ({ x: event.posx, y: event.posy }),
getActions: () => TPromise.as(actions),
onHide: () => dispose(actions)
});
}
}
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
// Styling with Outline color (e.g. high contrast theme)
const outline = theme.getColor(activeContrastBorder);
if (outline) {
collector.addRule(`
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:before {
content: "";
position: absolute;
top: 9px;
left: 9px;
height: 32px;
width: 32px;
opacity: 0.6;
}
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item.active:before,
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item.active:hover:before {
outline: 1px solid;
}
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:hover:before {
outline: 1px dashed;
}
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item.active:before,
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:hover:before {
opacity: 1;
}
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:focus:before {
border-left-color: ${outline};
}
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item.active:before,
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item.active:hover:before,
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:hover:before {
outline-color: ${outline};
}
`);
}
// Styling without outline color
else {
const focusBorderColor = theme.getColor(focusBorder);
collector.addRule(`
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item.active .action-label,
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:focus .action-label,
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:hover .action-label {
opacity: 1;
}
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item .action-label {
opacity: 0.6;
}
.monaco-workbench > .activitybar > .content .monaco-action-bar .action-item:focus:before {
border-left-color: ${focusBorderColor};
}
`);
}
});
|
keyboard-clacker/vscode
|
extensions/emmet/src/toggleComment.ts
|
<reponame>keyboard-clacker/vscode<gh_stars>0
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { getNode, isStyleSheet } from './util';
import parse from '@emmetio/html-matcher';
import parseStylesheet from '@emmetio/css-parser';
import Node from '@emmetio/node';
const startCommentStylesheet = '/*';
const endCommentStylesheet = '*/';
const startCommentHTML = '<!--';
const endCommentHTML = '-->';
export function toggleComment() {
let editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('No editor is active');
return;
}
let toggleCommentInternal;
let startComment;
let endComment;
let parseContent;
if (isStyleSheet(editor.document.languageId)) {
parseContent = parseStylesheet;
toggleCommentInternal = toggleCommentStylesheet;
startComment = startCommentStylesheet;
endComment = endCommentStylesheet;
} else {
parseContent = parse;
toggleCommentInternal = toggleCommentHTML;
startComment = startCommentHTML;
endComment = endCommentHTML;
}
let rootNode = parseContent(editor.document.getText());
editor.edit(editBuilder => {
editor.selections.reverse().forEach(selection => {
let [rangesToUnComment, positionForCommentStart, positionForCommentEnd] = toggleCommentInternal(editor.document, selection, rootNode);
rangesToUnComment.forEach(rangeToDelete => {
editBuilder.delete(rangeToDelete);
});
if (positionForCommentStart) {
editBuilder.insert(positionForCommentStart, startComment);
}
if (positionForCommentEnd) {
editBuilder.insert(positionForCommentEnd, endComment);
}
});
});
}
function toggleCommentHTML(document: vscode.TextDocument, selection: vscode.Selection, rootNode: Node): [vscode.Range[], vscode.Position, vscode.Position] {
let offset = document.offsetAt(selection.start);
let nodeToUpdate = getNode(rootNode, offset);
let rangesToUnComment = getRangesToUnCommentHTML(nodeToUpdate, document);
if (nodeToUpdate.type === 'comment') {
return [rangesToUnComment, null, null];
}
let positionForCommentStart = document.positionAt(nodeToUpdate.start);
let positionForCommentEnd = document.positionAt(nodeToUpdate.end);
return [rangesToUnComment, positionForCommentStart, positionForCommentEnd];
}
function getRangesToUnCommentHTML(node: Node, document: vscode.TextDocument): vscode.Range[] {
let rangesToUnComment = [];
// If current node is commented, then uncomment and return
if (node.type === 'comment') {
rangesToUnComment.push(new vscode.Range(document.positionAt(node.start), document.positionAt(node.start + startCommentHTML.length)));
rangesToUnComment.push(new vscode.Range(document.positionAt(node.end), document.positionAt(node.end - endCommentHTML.length)));
return rangesToUnComment;
}
// All children of current node should be uncommented
node.children.forEach(childNode => {
rangesToUnComment = rangesToUnComment.concat(getRangesToUnCommentHTML(childNode, document));
});
return rangesToUnComment;
}
function toggleCommentStylesheet(document: vscode.TextDocument, selection: vscode.Selection, rootNode: Node): [vscode.Range[], vscode.Position, vscode.Position] {
let selectionStart = document.offsetAt(selection.anchor);
let selectionEnd = document.offsetAt(selection.active);
// If current node is commented, then uncomment and return
let rangesToUnComment = getRangesToUnCommentStylesheet(rootNode, selectionStart, selectionEnd, document, true);
if (rangesToUnComment.length > 0) {
return [rangesToUnComment, null, null];
}
// Uncomment children of current node and then comment the node
let nodeToComment = getNode(rootNode, selectionStart);
rangesToUnComment = getRangesToUnCommentStylesheet(rootNode, nodeToComment.start, nodeToComment.end, document, false);
let positionForCommentStart = document.positionAt(nodeToComment.start);
let positionForCommentEnd = document.positionAt(nodeToComment.end);
return [rangesToUnComment, positionForCommentStart, positionForCommentEnd];
}
function getRangesToUnCommentStylesheet(rootNode: Node, selectionStart: number, selectionEnd: number, document: vscode.TextDocument, selectionInsideComment: boolean): vscode.Range[] {
if (!rootNode.comments || rootNode.comments.length === 0) {
return [];
}
let rangesToUnComment = [];
rootNode.comments.forEach(comment => {
let foundComment = false;
if (selectionInsideComment) {
foundComment = comment.start <= selectionStart && comment.end >= selectionEnd;
} else {
foundComment = selectionStart <= comment.start && selectionEnd >= comment.end;
}
if (foundComment) {
rangesToUnComment.push(new vscode.Range(document.positionAt(comment.start), document.positionAt(comment.start + startCommentStylesheet.length)));
rangesToUnComment.push(new vscode.Range(document.positionAt(comment.end), document.positionAt(comment.end - endCommentStylesheet.length)));
}
});
return rangesToUnComment;
}
|
keyboard-clacker/vscode
|
src/vs/workbench/api/node/extHostTask.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise } from 'vs/base/common/winjs.base';
import * as UUID from 'vs/base/common/uuid';
import { asWinJsPromise } from 'vs/base/common/async';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import * as TaskSystem from 'vs/workbench/parts/tasks/common/tasks';
import { IThreadService } from 'vs/workbench/services/thread/common/threadService';
import { MainContext, MainThreadTaskShape, ExtHostTaskShape } from 'vs/workbench/api/node/extHost.protocol';
import * as types from 'vs/workbench/api/node/extHostTypes';
import * as vscode from 'vscode';
interface StringMap<V> {
[key: string]: V;
}
/*
namespace ProblemPattern {
export function from(value: vscode.ProblemPattern | vscode.MultiLineProblemPattern): Problems.ProblemPattern | Problems.MultiLineProblemPattern {
if (value === void 0 || value === null) {
return undefined;
}
if (Array.isArray(value)) {
let result: Problems.ProblemPattern[] = [];
for (let pattern of value) {
let converted = fromSingle(pattern);
if (!converted) {
return undefined;
}
result.push(converted);
}
return result;
} else {
return fromSingle(value);
}
}
function copyProperty(target: Problems.ProblemPattern, source: vscode.ProblemPattern, tk: keyof Problems.ProblemPattern) {
let sk: keyof vscode.ProblemPattern = tk;
let value = source[sk];
if (typeof value === 'number') {
target[tk] = value;
}
}
function getValue(value: number, defaultValue: number): number {
if (value !== void 0 && value === null) {
return value;
}
return defaultValue;
}
function fromSingle(problemPattern: vscode.ProblemPattern): Problems.ProblemPattern {
if (problemPattern === void 0 || problemPattern === null || !(problemPattern.regexp instanceof RegExp)) {
return undefined;
}
let result: Problems.ProblemPattern = {
regexp: problemPattern.regexp
};
copyProperty(result, problemPattern, 'file');
copyProperty(result, problemPattern, 'location');
copyProperty(result, problemPattern, 'line');
copyProperty(result, problemPattern, 'character');
copyProperty(result, problemPattern, 'endLine');
copyProperty(result, problemPattern, 'endCharacter');
copyProperty(result, problemPattern, 'severity');
copyProperty(result, problemPattern, 'code');
copyProperty(result, problemPattern, 'message');
if (problemPattern.loop === true || problemPattern.loop === false) {
result.loop = problemPattern.loop;
}
if (result.location) {
result.file = getValue(result.file, 1);
result.message = getValue(result.message, 0);
} else {
result.file = getValue(result.file, 1);
result.line = getValue(result.line, 2);
result.character = getValue(result.character, 3);
result.message = getValue(result.message, 0);
}
return result;
}
}
namespace ApplyTo {
export function from(value: vscode.ApplyToKind): Problems.ApplyToKind {
if (value === void 0 || value === null) {
return Problems.ApplyToKind.allDocuments;
}
switch (value) {
case types.ApplyToKind.OpenDocuments:
return Problems.ApplyToKind.openDocuments;
case types.ApplyToKind.ClosedDocuments:
return Problems.ApplyToKind.closedDocuments;
}
return Problems.ApplyToKind.allDocuments;
}
}
namespace FileLocation {
export function from(value: vscode.FileLocationKind | string): { kind: Problems.FileLocationKind; prefix?: string } {
if (value === void 0 || value === null) {
return { kind: Problems.FileLocationKind.Auto };
}
if (typeof value === 'string') {
return { kind: Problems.FileLocationKind.Relative, prefix: value };
}
switch (value) {
case types.FileLocationKind.Absolute:
return { kind: Problems.FileLocationKind.Absolute };
case types.FileLocationKind.Relative:
return { kind: Problems.FileLocationKind.Relative, prefix: '${workspaceRoot}' };
}
return { kind: Problems.FileLocationKind.Auto };
}
}
namespace WatchingPattern {
export function from(value: RegExp | vscode.BackgroundPattern): Problems.WatchingPattern {
if (value === void 0 || value === null) {
return undefined;
}
if (value instanceof RegExp) {
return { regexp: value };
}
if (!(value.regexp instanceof RegExp)) {
return undefined;
}
let result: Problems.WatchingPattern = {
regexp: value.regexp
};
if (typeof value.file === 'number') {
result.file = value.file;
}
return result;
}
}
namespace BackgroundMonitor {
export function from(value: vscode.BackgroundMonitor): Problems.WatchingMatcher {
if (value === void 0 || value === null) {
return undefined;
}
let result: Problems.WatchingMatcher = {
activeOnStart: !!value.activeOnStart,
beginsPattern: WatchingPattern.from(value.beginsPattern),
endsPattern: WatchingPattern.from(value.endsPattern)
};
return result;
}
}
namespace ProblemMatcher {
export function from(values: (string | vscode.ProblemMatcher)[]): (string | Problems.ProblemMatcher)[] {
if (values === void 0 || values === null) {
return undefined;
}
let result: (string | Problems.ProblemMatcher)[] = [];
for (let value of values) {
let converted = typeof value === 'string' ? value : fromSingle(value);
if (converted) {
result.push(converted);
}
}
return result;
}
function fromSingle(problemMatcher: vscode.ProblemMatcher): Problems.ProblemMatcher {
if (problemMatcher === void 0 || problemMatcher === null) {
return undefined;
}
let location = FileLocation.from(problemMatcher.fileLocation);
let result: Problems.ProblemMatcher = {
owner: typeof problemMatcher.owner === 'string' ? problemMatcher.owner : UUID.generateUuid(),
applyTo: ApplyTo.from(problemMatcher.applyTo),
fileLocation: location.kind,
filePrefix: location.prefix,
pattern: ProblemPattern.from(problemMatcher.pattern),
severity: fromDiagnosticSeverity(problemMatcher.severity),
};
return result;
}
}
*/
namespace TaskRevealKind {
export function from(value: vscode.TaskRevealKind): TaskSystem.RevealKind {
if (value === void 0 || value === null) {
return TaskSystem.RevealKind.Always;
}
switch (value) {
case types.TaskRevealKind.Silent:
return TaskSystem.RevealKind.Silent;
case types.TaskRevealKind.Never:
return TaskSystem.RevealKind.Never;
}
return TaskSystem.RevealKind.Always;
}
}
namespace TerminalBehaviour {
export function from(value: vscode.TaskTerminalBehavior): TaskSystem.TerminalBehavior {
if (value === void 0 || value === null) {
return { reveal: TaskSystem.RevealKind.Always, echo: false };
}
return { reveal: TaskRevealKind.from(value.reveal), echo: !!value.echo };
}
}
namespace Strings {
export function from(value: string[]): string[] {
if (value === void 0 || value === null) {
return undefined;
}
for (let element of value) {
if (typeof element !== 'string') {
return [];
}
}
return value;
}
}
namespace CommandOptions {
function isShellOptions(value: any): value is vscode.ShellTaskOptions {
return value && typeof value.executable === 'string';
}
export function from(value: vscode.ShellTaskOptions | vscode.ProcessTaskOptions): TaskSystem.CommandOptions {
if (value === void 0 || value === null) {
return undefined;
}
let result: TaskSystem.CommandOptions = {
};
if (typeof value.cwd === 'string') {
result.cwd = value.cwd;
}
if (value.env) {
result.env = Object.create(null);
Object.keys(value.env).forEach(key => {
let envValue = value.env[key];
if (typeof envValue === 'string') {
result.env[key] = envValue;
}
});
}
if (isShellOptions(value)) {
result.shell = ShellConfiguration.from(value);
}
return result;
}
}
namespace ShellConfiguration {
export function from(value: { executable?: string, args?: string[] }): TaskSystem.ShellConfiguration {
if (value === void 0 || value === null || !value.executable) {
return undefined;
}
let result: TaskSystem.ShellConfiguration = {
executable: value.executable,
args: Strings.from(value.args)
};
return result;
}
}
namespace Tasks {
export function from(tasks: vscode.Task[], extension: IExtensionDescription, uuidMap: UUIDMap): TaskSystem.Task[] {
if (tasks === void 0 || tasks === null) {
return [];
}
let result: TaskSystem.Task[] = [];
try {
uuidMap.start();
for (let task of tasks) {
let converted = fromSingle(task, extension, uuidMap);
if (converted) {
result.push(converted);
}
}
} finally {
uuidMap.finish();
}
return result;
}
function fromSingle(task: vscode.Task, extension: IExtensionDescription, uuidMap: UUIDMap): TaskSystem.Task {
if (typeof task.name !== 'string') {
return undefined;
}
let command: TaskSystem.CommandConfiguration;
if (task instanceof types.ProcessTask) {
command = getProcessCommand(task);
} else if (task instanceof types.ShellTask) {
command = getShellCommand(task);
} else {
return undefined;
}
if (command === void 0) {
return undefined;
}
let result: TaskSystem.Task = {
_id: uuidMap.getUUID(task.identifier),
_source: {
kind: TaskSystem.TaskSourceKind.Extension,
label: typeof task.source === 'string' ? task.source : extension.name,
detail: extension.id
},
name: task.name,
identifier: task.identifier ? task.identifier : `${extension.id}.${task.name}`,
group: types.TaskGroup.is(task.group) ? task.group : undefined,
command: command,
isBackground: !!task.isBackground,
suppressTaskName: true,
problemMatchers: task.problemMatchers.slice()
};
return result;
}
function getProcessCommand(value: vscode.ProcessTask): TaskSystem.CommandConfiguration {
if (typeof value.process !== 'string') {
return undefined;
}
let result: TaskSystem.CommandConfiguration = {
name: value.process,
args: Strings.from(value.args),
type: TaskSystem.CommandType.Process,
terminal: TerminalBehaviour.from(value.terminal)
};
if (value.options) {
result.options = CommandOptions.from(value.options);
}
return result;
}
function getShellCommand(value: vscode.ShellTask): TaskSystem.CommandConfiguration {
if (typeof value.commandLine !== 'string') {
return undefined;
}
let result: TaskSystem.CommandConfiguration = {
name: value.commandLine,
type: TaskSystem.CommandType.Shell,
terminal: TerminalBehaviour.from(value.terminal)
};
if (value.options) {
result.options = CommandOptions.from(value.options);
}
return result;
}
}
class UUIDMap {
private _map: StringMap<string>;
private _unused: StringMap<boolean>;
constructor() {
this._map = Object.create(null);
}
public start(): void {
this._unused = Object.create(null);
Object.keys(this._map).forEach(key => this._unused[key] = true);
}
public getUUID(identifier: string): string {
delete this._unused[identifier];
let result = this._map[identifier];
if (result) {
return result;
}
result = UUID.generateUuid();
this._map[identifier] = result;
return result;
}
public finish(): void {
Object.keys(this._unused).forEach(key => delete this._map[key]);
this._unused = null;
}
}
interface HandlerData {
provider: vscode.TaskProvider;
extension: IExtensionDescription;
}
export class ExtHostTask extends ExtHostTaskShape {
private _proxy: MainThreadTaskShape;
private _handleCounter: number;
private _handlers: Map<number, HandlerData>;
private _idMaps: Map<string, UUIDMap>;
constructor(threadService: IThreadService) {
super();
this._proxy = threadService.get(MainContext.MainThreadTask);
this._handleCounter = 0;
this._handlers = new Map<number, HandlerData>();
this._idMaps = new Map<string, UUIDMap>();
};
public registerTaskProvider(extension: IExtensionDescription, provider: vscode.TaskProvider): vscode.Disposable {
if (!provider) {
return new types.Disposable(() => { });
}
let handle = this.nextHandle();
this._handlers.set(handle, { provider, extension });
this._proxy.$registerTaskProvider(handle);
return new types.Disposable(() => {
this._handlers.delete(handle);
this._proxy.$unregisterTaskProvider(handle);
});
}
public $provideTasks(handle: number): TPromise<TaskSystem.TaskSet> {
let handler = this._handlers.get(handle);
if (!handler) {
return TPromise.wrapError<TaskSystem.TaskSet>(new Error('no handler found'));
}
return asWinJsPromise(token => handler.provider.provideTasks(token)).then(value => {
return {
tasks: Tasks.from(value, handler.extension, this.getUUIDMap(handler.extension.id)),
extension: handler.extension
};
});
}
private nextHandle(): number {
return this._handleCounter++;
}
private getUUIDMap(extensionId: string): UUIDMap {
let result = this._idMaps.get(extensionId);
if (result) {
return result;
}
result = new UUIDMap();
this._idMaps.set(extensionId, result);
return result;
}
}
|
keyboard-clacker/vscode
|
src/vs/editor/common/config/fontInfo.ts
|
<reponame>keyboard-clacker/vscode<filename>src/vs/editor/common/config/fontInfo.ts<gh_stars>0
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as platform from 'vs/base/common/platform';
import { EditorZoom } from 'vs/editor/common/config/editorZoom';
import { EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions';
/**
* Determined from empirical observations.
* @internal
*/
const GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35;
function safeParseFloat(n: number | string, defaultValue: number): number {
if (typeof n === 'number') {
return n;
}
let r = parseFloat(n);
if (isNaN(r)) {
return defaultValue;
}
return r;
}
function safeParseInt(n: number | string, defaultValue: number): number {
if (typeof n === 'number') {
return Math.round(n);
}
let r = parseInt(n);
if (isNaN(r)) {
return defaultValue;
}
return r;
}
function clamp(n: number, min: number, max: number): number {
if (n < min) {
return min;
}
if (n > max) {
return max;
}
return n;
}
function _string(value: any, defaultValue: string): string {
if (typeof value !== 'string') {
return defaultValue;
}
return value;
}
export class BareFontInfo {
readonly _bareFontInfoBrand: void;
/**
* @internal
*/
public static createFromRawSettings(opts: {
fontFamily?: string;
fontWeight?: string;
fontSize?: number | string;
lineHeight?: number | string;
letterSpacing?: number | string;
}, zoomLevel: number): BareFontInfo {
let fontFamily = _string(opts.fontFamily, EDITOR_FONT_DEFAULTS.fontFamily);
let fontWeight = _string(opts.fontWeight, EDITOR_FONT_DEFAULTS.fontWeight);
let fontSize = safeParseFloat(opts.fontSize, EDITOR_FONT_DEFAULTS.fontSize);
fontSize = clamp(fontSize, 0, 100);
if (fontSize === 0) {
fontSize = EDITOR_FONT_DEFAULTS.fontSize;
} else if (fontSize < 8) {
fontSize = 8;
}
let lineHeight = safeParseInt(opts.lineHeight, 0);
lineHeight = clamp(lineHeight, 0, 150);
if (lineHeight === 0) {
lineHeight = Math.round(GOLDEN_LINE_HEIGHT_RATIO * fontSize);
} else if (lineHeight < 8) {
lineHeight = 8;
}
let letterSpacing = safeParseFloat(opts.letterSpacing, 0);;
letterSpacing = clamp(letterSpacing, -20, 20);
let editorZoomLevelMultiplier = 1 + (EditorZoom.getZoomLevel() * 0.1);
fontSize *= editorZoomLevelMultiplier;
lineHeight *= editorZoomLevelMultiplier;
return new BareFontInfo({
zoomLevel: zoomLevel,
fontFamily: fontFamily,
fontWeight: fontWeight,
fontSize: fontSize,
lineHeight: lineHeight,
letterSpacing: letterSpacing
});
}
readonly zoomLevel: number;
readonly fontFamily: string;
readonly fontWeight: string;
readonly fontSize: number;
readonly lineHeight: number;
readonly letterSpacing: number;
/**
* @internal
*/
protected constructor(opts: {
zoomLevel: number;
fontFamily: string;
fontWeight: string;
fontSize: number;
lineHeight: number;
letterSpacing: number;
}) {
this.zoomLevel = opts.zoomLevel;
this.fontFamily = String(opts.fontFamily);
this.fontWeight = String(opts.fontWeight);
this.fontSize = opts.fontSize;
this.lineHeight = opts.lineHeight | 0;
this.letterSpacing = opts.letterSpacing;
}
/**
* @internal
*/
public getId(): string {
return this.zoomLevel + '-' + this.fontFamily + '-' + this.fontWeight + '-' + this.fontSize + '-' + this.lineHeight + '-' + this.letterSpacing;
}
}
export class FontInfo extends BareFontInfo {
readonly _editorStylingBrand: void;
readonly isTrusted: boolean;
readonly isMonospace: boolean;
readonly typicalHalfwidthCharacterWidth: number;
readonly typicalFullwidthCharacterWidth: number;
readonly spaceWidth: number;
readonly maxDigitWidth: number;
/**
* @internal
*/
constructor(opts: {
zoomLevel: number;
fontFamily: string;
fontWeight: string;
fontSize: number;
lineHeight: number;
letterSpacing: number;
isMonospace: boolean;
typicalHalfwidthCharacterWidth: number;
typicalFullwidthCharacterWidth: number;
spaceWidth: number;
maxDigitWidth: number;
}, isTrusted: boolean) {
super(opts);
this.isTrusted = isTrusted;
this.isMonospace = opts.isMonospace;
this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth;
this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth;
this.spaceWidth = opts.spaceWidth;
this.maxDigitWidth = opts.maxDigitWidth;
}
/**
* @internal
*/
public equals(other: FontInfo): boolean {
return (
this.fontFamily === other.fontFamily
&& this.fontWeight === other.fontWeight
&& this.fontSize === other.fontSize
&& this.lineHeight === other.lineHeight
&& this.letterSpacing === other.letterSpacing
&& this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth
&& this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth
&& this.spaceWidth === other.spaceWidth
&& this.maxDigitWidth === other.maxDigitWidth
);
}
}
|
keyboard-clacker/vscode
|
extensions/markdown/src/previewContentProvider.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as vscode from 'vscode';
import * as path from 'path';
import { MarkdownEngine } from './markdownEngine';
import * as nls from 'vscode-nls';
import { Logger } from "./logger";
const localize = nls.loadMessageBundle();
export interface ContentSecurityPolicyArbiter {
isEnhancedSecurityDisableForWorkspace(rootPath: string): boolean;
addTrustedWorkspace(rootPath: string): Thenable<void>;
removeTrustedWorkspace(rootPath: string): Thenable<void>;
}
const previewStrings = {
cspAlertMessageText: localize('preview.securityMessage.text', 'Scripts have been disabled in this document'),
cspAlertMessageTitle: localize('preview.securityMessage.title', 'Scripts are disabled in the markdown preview. Change the Markdown preview secuirty setting to enable scripts'),
cspAlertMessageLabel: localize('preview.securityMessage.label', 'Scripts Disabled Security Warning')
};
export function isMarkdownFile(document: vscode.TextDocument) {
return document.languageId === 'markdown'
&& document.uri.scheme !== 'markdown'; // prevent processing of own documents
}
export function getMarkdownUri(uri: vscode.Uri) {
if (uri.scheme === 'markdown') {
return uri;
}
return uri.with({
scheme: 'markdown',
path: uri.path + '.rendered',
query: uri.toString()
});
}
class MarkdownPreviewConfig {
public static getCurrentConfig() {
return new MarkdownPreviewConfig();
}
public readonly scrollBeyondLastLine: boolean;
public readonly wordWrap: boolean;
public readonly previewFrontMatter: string;
public readonly doubleClickToSwitchToEditor: boolean;
public readonly scrollEditorWithPreview: boolean;
public readonly scrollPreviewWithEditorSelection: boolean;
public readonly markEditorSelection: boolean;
public readonly lineHeight: number;
public readonly fontSize: number;
public readonly fontFamily: string | undefined;
public readonly styles: string[];
private constructor() {
const editorConfig = vscode.workspace.getConfiguration('editor');
const markdownConfig = vscode.workspace.getConfiguration('markdown');
this.scrollBeyondLastLine = editorConfig.get<boolean>('scrollBeyondLastLine', false);
this.wordWrap = editorConfig.get<string>('wordWrap', 'off') !== 'off';
this.previewFrontMatter = markdownConfig.get<string>('previewFrontMatter', 'hide');
this.scrollPreviewWithEditorSelection = !!markdownConfig.get<boolean>('preview.scrollPreviewWithEditorSelection', true);
this.scrollEditorWithPreview = !!markdownConfig.get<boolean>('preview.scrollEditorWithPreview', true);
this.doubleClickToSwitchToEditor = !!markdownConfig.get<boolean>('preview.doubleClickToSwitchToEditor', true);
this.markEditorSelection = !!markdownConfig.get<boolean>('preview.markEditorSelection', true);
this.fontFamily = markdownConfig.get<string | undefined>('preview.fontFamily', undefined);
this.fontSize = +markdownConfig.get<number>('preview.fontSize', NaN);
this.lineHeight = +markdownConfig.get<number>('preview.lineHeight', NaN);
this.styles = markdownConfig.get<string[]>('styles', []);
}
public isEqualTo(otherConfig: MarkdownPreviewConfig) {
for (let key in this) {
if (this.hasOwnProperty(key) && key !== 'styles') {
if (this[key] !== otherConfig[key]) {
return false;
}
}
}
// Check styles
if (this.styles.length !== otherConfig.styles.length) {
return false;
}
for (let i = 0; i < this.styles.length; ++i) {
if (this.styles[i] !== otherConfig.styles[i]) {
return false;
}
}
return true;
}
[key: string]: any;
}
export class MDDocumentContentProvider implements vscode.TextDocumentContentProvider {
private _onDidChange = new vscode.EventEmitter<vscode.Uri>();
private _waiting: boolean = false;
private config: MarkdownPreviewConfig;
private extraStyles: Array<vscode.Uri> = [];
private extraScripts: Array<vscode.Uri> = [];
constructor(
private engine: MarkdownEngine,
private context: vscode.ExtensionContext,
private cspArbiter: ContentSecurityPolicyArbiter,
private logger: Logger
) {
this.config = MarkdownPreviewConfig.getCurrentConfig();
}
public addScript(resource: vscode.Uri): void {
this.extraScripts.push(resource);
}
public addStyle(resource: vscode.Uri): void {
this.extraStyles.push(resource);
}
private getMediaPath(mediaFile: string): string {
return vscode.Uri.file(this.context.asAbsolutePath(path.join('media', mediaFile))).toString();
}
private fixHref(resource: vscode.Uri, href: string): string {
if (!href) {
return href;
}
// Use href if it is already an URL
const hrefUri = vscode.Uri.parse(href);
if (['file', 'http', 'https'].indexOf(hrefUri.scheme) >= 0) {
return hrefUri.toString();
}
// Use href as file URI if it is absolute
if (path.isAbsolute(href)) {
return vscode.Uri.file(href).toString();
}
// use a workspace relative path if there is a workspace
let rootPath = vscode.workspace.rootPath;
if (rootPath) {
return vscode.Uri.file(path.join(rootPath, href)).toString();
}
// otherwise look relative to the markdown file
return vscode.Uri.file(path.join(path.dirname(resource.fsPath), href)).toString();
}
private computeCustomStyleSheetIncludes(uri: vscode.Uri): string {
if (this.config.styles && Array.isArray(this.config.styles)) {
return this.config.styles.map((style) => {
return `<link rel="stylesheet" class="code-user-style" data-source="${style.replace(/"/g, '"')}" href="${this.fixHref(uri, style)}" type="text/css" media="screen">`;
}).join('\n');
}
return '';
}
private getSettingsOverrideStyles(nonce: string): string {
return `<style nonce="${nonce}">
body {
${this.config.fontFamily ? `font-family: ${this.config.fontFamily};` : ''}
${this.config.fontSize > 0 ? `font-size: ${this.config.fontSize}px;` : ''}
${this.config.lineHeight > 0 ? `line-height: ${this.config.lineHeight};` : ''}
}
</style>`;
}
private getStyles(uri: vscode.Uri, nonce: string): string {
const baseStyles = [
this.getMediaPath('markdown.css'),
this.getMediaPath('tomorrow.css')
].concat(this.extraStyles.map(resource => resource.toString()));
return `${baseStyles.map(href => `<link rel="stylesheet" type="text/css" href="${href}">`).join('\n')}
${this.getSettingsOverrideStyles(nonce)}
${this.computeCustomStyleSheetIncludes(uri)}`;
}
private getScripts(nonce: string): string {
const scripts = [this.getMediaPath('main.js')].concat(this.extraScripts.map(resource => resource.toString()));
return scripts
.map(source => `<script async src="${source}" nonce="${nonce}"></script>`)
.join('\n');
}
public provideTextDocumentContent(uri: vscode.Uri): Thenable<string> {
const sourceUri = vscode.Uri.parse(uri.query);
let initialLine: number | undefined = undefined;
const editor = vscode.window.activeTextEditor;
if (editor && editor.document.uri.fsPath === sourceUri.fsPath) {
initialLine = editor.selection.active.line;
}
return vscode.workspace.openTextDocument(sourceUri).then(document => {
this.config = MarkdownPreviewConfig.getCurrentConfig();
const initialData = {
previewUri: uri.toString(),
source: sourceUri.toString(),
line: initialLine,
scrollPreviewWithEditorSelection: this.config.scrollPreviewWithEditorSelection,
scrollEditorWithPreview: this.config.scrollEditorWithPreview,
doubleClickToSwitchToEditor: this.config.doubleClickToSwitchToEditor
};
this.logger.log('provideTextDocumentContent', initialData);
// Content Security Policy
const nonce = new Date().getTime() + '' + new Date().getMilliseconds();
let csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' http: https: data:; media-src 'self' http: https: data:; child-src 'none'; script-src 'nonce-${nonce}'; style-src 'self' 'unsafe-inline' http: https: data:; font-src 'self' http: https: data:;">`;
if (this.cspArbiter.isEnhancedSecurityDisableForWorkspace(vscode.workspace.rootPath || sourceUri.toString())) {
csp = '';
}
const body = this.engine.render(sourceUri, this.config.previewFrontMatter === 'hide', document.getText());
return `<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
${csp}
<meta id="vscode-markdown-preview-data" data-settings="${JSON.stringify(initialData).replace(/"/g, '"')}" data-strings="${JSON.stringify(previewStrings).replace(/"/g, '"')}">
<script src="${this.getMediaPath('csp.js')}" nonce="${nonce}"></script>
<script src="${this.getMediaPath('loading.js')}" nonce="${nonce}"></script>
${this.getStyles(uri, nonce)}
<base href="${document.uri.toString(true)}">
</head>
<body class="vscode-body ${this.config.scrollBeyondLastLine ? 'scrollBeyondLastLine' : ''} ${this.config.wordWrap ? 'wordWrap' : ''} ${this.config.markEditorSelection ? 'showEditorSelection' : ''}">
${body}
<div class="code-line" data-line="${document.lineCount}"></div>
${this.getScripts(nonce)}
</body>
</html>`;
});
}
public updateConfiguration() {
const newConfig = MarkdownPreviewConfig.getCurrentConfig();
if (!this.config.isEqualTo(newConfig)) {
this.config = newConfig;
// update all generated md documents
vscode.workspace.textDocuments.forEach(document => {
if (document.uri.scheme === 'markdown') {
this.update(document.uri);
}
});
}
}
get onDidChange(): vscode.Event<vscode.Uri> {
return this._onDidChange.event;
}
public update(uri: vscode.Uri) {
if (!this._waiting) {
this._waiting = true;
setTimeout(() => {
this._waiting = false;
this._onDidChange.fire(uri);
}, 300);
}
}
}
|
keyboard-clacker/vscode
|
extensions/typescript/src/features/referenceProvider.ts
|
<gh_stars>0
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ReferenceProvider, Location, TextDocument, Position, Range, CancellationToken } from 'vscode';
import * as Proto from '../protocol';
import { ITypescriptServiceClient } from '../typescriptService';
export default class TypeScriptReferenceSupport implements ReferenceProvider {
public constructor(
private client: ITypescriptServiceClient) { }
public provideReferences(document: TextDocument, position: Position, options: { includeDeclaration: boolean }, token: CancellationToken): Promise<Location[]> {
const filepath = this.client.normalizePath(document.uri);
if (!filepath) {
return Promise.resolve<Location[]>([]);
}
const args: Proto.FileLocationRequestArgs = {
file: filepath,
line: position.line + 1,
offset: position.character + 1
};
const apiVersion = this.client.apiVersion;
return this.client.execute('references', args, token).then((msg) => {
const result: Location[] = [];
if (!msg.body) {
return result;
}
const refs = msg.body.refs;
for (let i = 0; i < refs.length; i++) {
const ref = refs[i];
if (!options.includeDeclaration && apiVersion.has203Features() && ref.isDefinition) {
continue;
}
const url = this.client.asUrl(ref.file);
const location = new Location(
url,
new Range(ref.start.line - 1, ref.start.offset - 1, ref.end.line - 1, ref.end.offset - 1));
result.push(location);
}
return result;
}, (err) => {
this.client.error(`'references' request failed with error.`, err);
return [];
});
}
}
|
sandy081/vscode-emacs-mcx
|
src/commands/rectangle.ts
|
import * as vscode from "vscode";
import { TextEditor } from "vscode";
import { EmacsCommand, IEmacsCommandInterrupted } from ".";
import { IEmacsCommandRunner, IMarkModeController } from "../emulator";
import { getNonEmptySelections, makeSelectionsEmpty } from "./helpers/selection";
import { convertSelectionToRectSelections } from "../rectangle";
import { revealPrimaryActive } from "./helpers/reveal";
import { KillRing } from "../kill-yank/kill-ring";
/**
* This command is assigned to `C-x r` and sets `emacs-mcx.acceptingRectCommand` context
* to simulate the original keybindings like `C-x r k` as VSCode does not natively support
* such continuous key sequences without modifiers.
* In the example above, `kill-rectangle` command is assigned to a single `k` key
* with `{ "when": "emacs-mcx.acceptingRectCommand" }` condition.
* Then, `kill-rectangle` can be executed through `C-x r k`.
*/
export class StartAcceptingRectCommand extends EmacsCommand implements IEmacsCommandInterrupted {
public readonly id = "startAcceptingRectCommand";
private acceptingRectCommand = false;
public startAcceptingRectCommand(): void {
this.acceptingRectCommand = true;
vscode.commands.executeCommand("setContext", "emacs-mcx.acceptingRectCommand", true);
}
private stopAcceptingRectCommand(): void {
this.acceptingRectCommand = false;
vscode.commands.executeCommand("setContext", "emacs-mcx.acceptingRectCommand", false);
}
public execute(): void {
this.startAcceptingRectCommand();
}
public onDidInterruptTextEditor(): void {
if (this.acceptingRectCommand) {
this.stopAcceptingRectCommand();
}
}
}
type KilledRectangle = string[];
export interface RectangleState {
latestKilledRectangle: KilledRectangle; // multi-cursor is not supported
}
export abstract class RectangleKillYankCommand extends EmacsCommand {
protected rectangleState: RectangleState;
public constructor(
afterExecute: () => void,
emacsController: IMarkModeController & IEmacsCommandRunner,
rectangleState: RectangleState
) {
super(afterExecute, emacsController);
this.rectangleState = rectangleState;
}
}
async function deleteRanges(textEditor: vscode.TextEditor, ranges: vscode.Range[], maxTrials = 3): Promise<boolean> {
let success = false;
let trial = 0;
while (!success && trial < maxTrials) {
success = await textEditor.edit((editBuilder) => {
ranges.forEach((range) => {
editBuilder.delete(range);
});
});
trial++;
}
return success;
}
abstract class EditRectangle extends RectangleKillYankCommand {
protected copy = false;
protected delete = false;
public async execute(
textEditor: TextEditor,
isInMarkMode: boolean,
prefixArgument: number | undefined
): Promise<void> {
const selections = getNonEmptySelections(textEditor);
if (selections.length === 0) {
return;
}
const selection = selections[0]; // multi-cursor is not supported
const notReversedSelection = new vscode.Selection(selection.start, selection.end);
const rectSelections = convertSelectionToRectSelections(textEditor.document, notReversedSelection);
// Copy
if (this.copy) {
const rectText = rectSelections.map((lineSelection) => textEditor.document.getText(lineSelection));
this.rectangleState.latestKilledRectangle = rectText;
}
// Delete
if (this.delete) {
await deleteRanges(textEditor, rectSelections);
revealPrimaryActive(textEditor);
this.emacsController.exitMarkMode();
makeSelectionsEmpty(textEditor);
}
}
}
export class DeleteRectangle extends EditRectangle {
public readonly id = "deleteRectangle";
protected delete = true;
protected copy = false;
}
export class CopyRectangleAsKill extends EditRectangle {
public readonly id = "copyRectangleAsKill";
protected delete = false;
protected copy = true;
}
export class KillRectangle extends EditRectangle {
public readonly id = "killRectangle";
protected delete = true;
protected copy = true;
}
const getEolChar = (eol: vscode.EndOfLine): string | undefined => {
switch (eol) {
case vscode.EndOfLine.CRLF:
return "\r\n";
case vscode.EndOfLine.LF:
return "\n";
default:
return "\n";
}
};
export class YankRectangle extends RectangleKillYankCommand {
public readonly id = "yankRectangle";
public async execute(
textEditor: TextEditor,
isInMarkMode: boolean,
prefixArgument: number | undefined
): Promise<void> {
const killedRect = this.rectangleState.latestKilledRectangle;
if (killedRect.length === 0) {
return;
}
const rectHeight = killedRect.length - 1;
const rectWidth = killedRect[rectHeight].length;
const active = textEditor.selection.active; // Multi-cursor is not supported
await textEditor.edit((edit) => {
const maxLine = textEditor.document.lineCount - 1;
const insertColumn = active.character;
const eolChar = getEolChar(textEditor.document.eol);
let rectLine = 0;
while (rectLine <= rectHeight) {
const insertLine = active.line + rectLine;
if (insertLine > maxLine) {
break;
}
const additionalColumns = Math.max(
0,
insertColumn - textEditor.document.lineAt(insertLine).range.end.character
);
const insertText = " ".repeat(additionalColumns) + killedRect[rectLine];
edit.insert(new vscode.Position(insertLine, insertColumn), insertText);
++rectLine;
}
if (rectLine <= rectHeight) {
const additionalText = killedRect
.slice(rectLine)
.map((lineText) => eolChar + " ".repeat(insertColumn) + lineText)
.join("");
const lastPoint = textEditor.document.lineAt(maxLine).range.end;
edit.insert(lastPoint, additionalText);
}
});
const newActive = active.translate(rectHeight, rectWidth);
textEditor.selection = new vscode.Selection(newActive, newActive);
}
}
export class OpenRectangle extends EmacsCommand {
public readonly id = "openRectangle";
public async execute(textEditor: TextEditor, isInMarkMode: boolean, prefixArgument: number | undefined) {
const selections = getNonEmptySelections(textEditor);
if (selections.length === 0) {
return;
}
const starts = textEditor.selections.map((selection) => selection.start);
const rectSelections = selections
.map(convertSelectionToRectSelections.bind(null, textEditor.document))
.reduce((a, b) => a.concat(b), []);
await textEditor.edit((edit) => {
rectSelections.forEach((rectSelection) => {
const length = rectSelection.end.character - rectSelection.start.character;
edit.insert(rectSelection.start, " ".repeat(length));
});
});
this.emacsController.exitMarkMode();
textEditor.selections = starts.map((s) => new vscode.Selection(s, s));
}
}
export class ClearRectangle extends EmacsCommand {
public readonly id = "clearRectangle";
public async execute(textEditor: TextEditor, isInMarkMode: boolean, prefixArgument: number | undefined) {
const selections = getNonEmptySelections(textEditor);
if (selections.length === 0) {
return;
}
const rectSelections = selections
.map(convertSelectionToRectSelections.bind(null, textEditor.document))
.reduce((a, b) => a.concat(b), []);
await textEditor.edit((edit) => {
rectSelections.forEach((rectSelection) => {
const length = rectSelection.end.character - rectSelection.start.character;
edit.replace(rectSelection, " ".repeat(length));
});
});
this.emacsController.exitMarkMode();
makeSelectionsEmpty(textEditor);
}
}
export class ReplaceKillRingToRectangle extends EmacsCommand {
public readonly id = "replaceKillRingToRectangle";
private killring: KillRing | null;
public constructor(
afterExecute: () => void,
emacsController: IMarkModeController & IEmacsCommandRunner,
killring: KillRing | null
) {
super(afterExecute, emacsController);
this.killring = killring;
}
public async execute(
textEditor: TextEditor,
isInMarkMode: boolean,
prefixArgument: number | undefined
): Promise<void> {
if (this.killring === null) {
return;
}
const top = this.killring.getTop();
if (top === null) {
return;
}
const text = top.asString();
// only support one line which isn't empty
if (text === "" || text.indexOf("\n") !== -1) {
return;
}
const selections = getNonEmptySelections(textEditor);
if (selections.length !== 1) {
// multiple cursor not supported
return;
}
const insertChar = Math.min(selections[0].start.character, selections[0].end.character);
const finalCursorLine = selections[0].active.line;
let finalCursorChar = insertChar;
if (selections[0].active.character >= selections[0].anchor.character) {
finalCursorChar = insertChar + text.length;
}
const currentRect = convertSelectionToRectSelections(textEditor.document, selections[0]);
// rect is reversed in previous convert,
// so we reverse it again as we need to traverse from smaller line number
if (selections[0].active.line < selections[0].anchor.line) {
currentRect.reverse();
}
const lineStart = Math.max(selections[0].start.line, 0);
const lineEnd = Math.min(selections[0].end.line, textEditor.document.lineCount - 1);
await textEditor.edit((edit) => {
for (let i = lineStart; i <= lineEnd; i++) {
const rgn = currentRect[i - lineStart];
if (rgn.end.character < insertChar) {
const fill = insertChar - rgn.end.character;
edit.insert(new vscode.Position(i, rgn.end.character), " ".repeat(fill) + text);
} else {
edit.replace(rgn, text);
}
}
});
this.emacsController.exitMarkMode();
const finalCursor = new vscode.Position(finalCursorLine, finalCursorChar);
textEditor.selections = [new vscode.Selection(finalCursor, finalCursor)];
}
}
|
sandy081/vscode-emacs-mcx
|
src/test/suite/commands/kill-yank/kill-whole-line.test.ts
|
import assert from "assert";
import * as vscode from "vscode";
import { Position, Selection } from "vscode";
import { EmacsEmulator } from "../../../../emulator";
import { assertTextEqual, cleanUpWorkspace, clearTextEditor, setupWorkspace } from "../../utils";
suite("Emulator.killWholeLine", () => {
let activeTextEditor: vscode.TextEditor;
suite("with non-empty initial text", () => {
setup(async () => {
const initialText = `0123456789
abcdefghij
ABCDEFGHIJ`;
activeTextEditor = await setupWorkspace(initialText);
});
teardown(cleanUpWorkspace);
suite("single cursor in the middle line of the document", () => {
const cursorLineNum = 1;
const cursorCharNums = [0, 5, 10]; // beginning, middle, end
cursorCharNums.forEach((cursorCharNum) => {
test(`it works with single cursor at (${cursorLineNum}, ${cursorCharNum})`, async () => {
const emulator = new EmacsEmulator(activeTextEditor);
activeTextEditor.selections = [
new Selection(new Position(cursorLineNum, cursorCharNum), new Position(cursorLineNum, cursorCharNum)),
];
await emulator.runCommand("killWholeLine");
assertTextEqual(
activeTextEditor,
`0123456789
ABCDEFGHIJ`
);
// Check the cut text
await clearTextEditor(activeTextEditor);
activeTextEditor.selections = [new Selection(new Position(0, 0), new Position(0, 0))];
await emulator.runCommand("yank");
assert.strictEqual(activeTextEditor.document.getText(), "abcdefghij\n");
});
});
});
suite("single cursor in the last line of the document", () => {
const cursorLineNum = 2; // the last line
const cursorCharNums = [0, 5, 10]; // beginning, middle, end
cursorCharNums.forEach((cursorCharNum) => {
test(`it works with single cursor at (${cursorLineNum}, ${cursorCharNum})`, async () => {
const emulator = new EmacsEmulator(activeTextEditor);
activeTextEditor.selections = [
new Selection(new Position(cursorLineNum, cursorCharNum), new Position(cursorLineNum, cursorCharNum)),
];
await emulator.runCommand("killWholeLine");
assertTextEqual(
activeTextEditor,
`0123456789
abcdefghij
`
);
// Check the cut text
await clearTextEditor(activeTextEditor);
activeTextEditor.selections = [new Selection(new Position(0, 0), new Position(0, 0))];
await emulator.runCommand("yank");
assert.strictEqual(activeTextEditor.document.getText(), "ABCDEFGHIJ");
});
});
});
});
});
|
deividr/nlw-01
|
web/src/pages/CreatePoint/index.tsx
|
import React, { useEffect, useState, ChangeEvent, FormEvent } from 'react';
import Dropzone from '../../components/Dropzone/index';
import { Link, useHistory } from 'react-router-dom';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import { FiArrowLeft } from 'react-icons/fi';
import axios from 'axios';
import api from '../../services/api';
import './styles.css';
import logo from '../../assets/logo.svg';
import { LeafletMouseEvent } from 'leaflet';
interface State {
name: string;
email: string;
whatsapp: string;
items?: [];
}
interface Item {
id: number;
image: string;
title: string;
}
interface IBGEUFResponse {
sigla: string;
}
interface IBGECityResponse {
nome: string;
}
const CreatePoint = () => {
const [formData, setFormData] = useState<State>({
name: '',
email: '',
whatsapp: '',
});
const [position, setPosition] = useState<[number, number]>([0, 0]);
const [items, setItems] = useState<Item[]>([]);
const [ufs, setUfs] = useState<string[]>([]);
const [cities, setCities] = useState<string[]>([]);
const [selectedFile, setSelectedFile] = useState<File>();
const [selectedUf, setSelectedUf] = useState<string>('0');
const [selectedCity, setSelectedCity] = useState<string>('0');
const [selectedItems, setSelectedItems] = useState<number[]>([]);
const history = useHistory();
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
const { latitude, longitude } = position.coords;
setPosition([latitude, longitude]);
});
}, []);
useEffect(() => {
api.get('/items').then((response) => {
setItems(response.data);
});
}, []);
useEffect(() => {
axios
.get<IBGEUFResponse[]>(
'https://servicodados.ibge.gov.br/api/v1/localidades/estados'
)
.then((response) => {
const ufsInitials = response.data.map((uf) => uf.sigla);
setUfs(ufsInitials);
});
}, []);
useEffect(() => {
if (selectedUf === '0') return;
axios
.get<IBGECityResponse[]>(
`https://servicodados.ibge.gov.br/api/v1/localidades/estados/${selectedUf}/municipios`
)
.then((response) => {
const cityInitials = response.data.map((city) => city.nome);
setCities(cityInitials);
});
}, [selectedUf]);
const handleSelectPosition = (event: LeafletMouseEvent) => {
setPosition([event.latlng.lat, event.latlng.lng]);
};
const handleSelectUf = (event: ChangeEvent<HTMLSelectElement>) => {
setSelectedUf(event.target.value);
};
const handleSelectCity = (event: ChangeEvent<HTMLSelectElement>) => {
setSelectedCity(event.target.value);
};
const handleInputEvent = (event: ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setFormData({ ...formData, [name]: value });
};
const handleSelectItem = (id: number) => {
const pos = selectedItems.indexOf(id);
if (pos >= 0) {
setSelectedItems(selectedItems.filter((item) => item !== id));
} else {
setSelectedItems([...selectedItems, id]);
}
};
const handleSubmit = async (event: FormEvent) => {
event.preventDefault();
const [latitude, longitude] = position;
const { name, email, whatsapp } = formData;
const data = new FormData();
data.append('name', name);
data.append('email', email);
data.append('whatsapp', whatsapp);
data.append('latitude', String(latitude));
data.append('longitude', String(longitude));
data.append('uf', selectedUf);
data.append('city', selectedCity);
data.append('items', selectedItems.join(','));
data.append('image', selectedFile ? selectedFile : 'null');
await api.post('points', data);
alert('Colect Point create success...');
history.push('/');
};
return (
<div id='page-create-point'>
<header>
<img src={logo} alt='Ecoleta' />
<Link to='/'>
<FiArrowLeft />
Voltar para home
</Link>
</header>
<form onSubmit={handleSubmit}>
<h1>
Cadastro do <br /> ponto de coleta
</h1>
<Dropzone onFileUploaded={setSelectedFile} />
<fieldset>
<legend>
<h2>Dados da entidade</h2>
</legend>
<div className='field'>
<label htmlFor='name'>Nome da Entidade</label>
<input
type='text'
name='name'
id='name'
value={formData.name}
onChange={handleInputEvent}
/>
</div>
<div className='field-group'>
<div className='field'>
<label htmlFor='email'>E-mail</label>
<input
type='email'
name='email'
id='email'
value={formData.email}
onChange={handleInputEvent}
/>
</div>
<div className='field'>
<label htmlFor='whatsapp'>Whatsapp</label>
<input
type='number'
name='whatsapp'
id='whatsapp'
value={formData.whatsapp}
onChange={handleInputEvent}
/>
</div>
</div>
</fieldset>
<fieldset>
<legend>
<h2>Endereço de coleta</h2>
<span>Selecione o endereço no mapa</span>
</legend>
<Map center={position} zoom={15} onClick={handleSelectPosition}>
<TileLayer
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position}>
<Popup>Casa do meu sogro.</Popup>
</Marker>
</Map>
<div className='field-group'>
<div className='field'>
<label htmlFor='uf'>Estado</label>
<select name='uf' id='uf' onChange={handleSelectUf}>
<option value='0'>Selecione um Estado</option>
{ufs.map((uf) => (
<option key={uf} value={uf}>
{uf}
</option>
))}
</select>
</div>
<div className='field'>
<label htmlFor='city'>Cidade</label>
<select
name='city'
id='city'
value={selectedCity}
onChange={handleSelectCity}
>
<option value='0'>Selecione uma Cidade</option>
{cities.map((city) => (
<option key={city} value={city}>
{city}
</option>
))}
</select>
</div>
</div>
</fieldset>
<fieldset>
<legend>
<h2>Itens de coleta</h2>
<span>Selecione um ou mais itens abaixo</span>
</legend>
<ul className='items-grid'>
{items.map((item) => (
<li
key={item.id}
className={selectedItems.includes(item.id) ? 'selected' : ''}
onClick={() => handleSelectItem(item.id)}
>
<img src={item.image} alt={item.title} />
<span>Lâmpadas</span>
</li>
))}
</ul>
</fieldset>
<button type='submit'>Cadastrar ponto de coleta</button>
</form>
</div>
);
};
export default CreatePoint;
|
deividr/nlw-01
|
server/src/routes.ts
|
<reponame>deividr/nlw-01
import express from 'express';
import itemsRoutes from './routers/items';
import itemsPoints from './routers/points';
const routes = express.Router();
routes.use(itemsRoutes);
routes.use(itemsPoints);
export default routes;
|
deividr/nlw-01
|
server/src/routers/points.ts
|
import { Router } from 'express';
import PointsController from '../controllers/PointsController';
import multer from 'multer';
import storage from '../config/multer';
import path from 'path';
import { celebrate, Joi } from 'celebrate';
const uploads = multer({
storage,
fileFilter: (request, file, callback) => {
const extensionFile = path.extname(file.originalname);
if (
extensionFile !== '.jpg' &&
extensionFile !== '.jpeg' &&
extensionFile !== '.png' &&
extensionFile !== '.gif'
) {
return callback(null, false);
}
callback(null, true);
},
});
const routes = Router();
const pointsController = new PointsController();
routes.get('/points', pointsController.index);
routes.get('/points/:id', pointsController.show);
routes.post(
'/points',
uploads.single('image'),
celebrate(
{
body: Joi.object().keys({
name: Joi.string().required(),
email: Joi.string().email().required(),
whatsapp: Joi.number().required(),
longitude: Joi.number().required(),
latitude: Joi.number().required(),
uf: Joi.string().max(2).required(),
city: Joi.string().required(),
items: Joi.string().required(),
}),
},
{ abortEarly: false }
),
pointsController.create
);
export default routes;
|
deividr/nlw-01
|
server/src/routers/items.ts
|
import { Router } from 'express';
import ItemsController from '../controllers/ItemsController';
const routes = Router();
const itemsController = new ItemsController();
routes.get('/items', itemsController.index);
export default routes;
|
viniciusflv/gatsby-ts
|
src/components/Lang/index.tsx
|
import React, { FC, memo } from 'react';
import { IntlProvider } from 'gatsby-plugin-intl';
import { LangProvider } from './context';
import { useHooks } from './hooks';
import { RootElementArgs } from '../../../gatsby-api';
export const Lang: FC<RootElementArgs> = memo(({ children, loadPageSync }) => {
const {
locale,
toggleLocale,
navigatorLocale,
messages,
defaultLocale
} = useHooks(loadPageSync);
return (
<IntlProvider
locale={navigatorLocale}
messages={messages}
defaultLocale={defaultLocale}
>
<LangProvider value={{ toggleLocale, locale }}>{children}</LangProvider>
</IntlProvider>
);
});
|
viniciusflv/gatsby-ts
|
src/components/Core/Text/index.tsx
|
<gh_stars>0
import React, { ComponentType, FC, memo } from 'react';
import { TextProps, TextTypes } from './interface';
import * as TextStyles from './style';
export const Text: FC<TextProps> = memo(
({ children, text, type = TextTypes.Span, ...props }) => {
const Tag = TextStyles[type];
const content = children ?? text;
return typeof content === 'string' ? (
<Tag dangerouslySetInnerHTML={{ __html: content }} {...props} />
) : (
<Tag {...props}>{content}</Tag>
);
}
);
|
viniciusflv/gatsby-ts
|
src/components/Core/Svg/style.ts
|
<filename>src/components/Core/Svg/style.ts
import styled from 'styled-components';
import { Flex } from '../Flex';
export const WrapperStyle = Flex;
export const SvgStyle = styled.svg`
width: 100%;
height: 100%;
`;
|
viniciusflv/gatsby-ts
|
src/components/Core/Grid/interface.ts
|
<filename>src/components/Core/Grid/interface.ts
import { ContainerProps } from '../Container/interface';
export type GridProps<T = {}> = ContainerProps<
T & {
areas?: string;
columns?: string;
rows?: string;
gap?: string;
}
>;
|
viniciusflv/gatsby-ts
|
src/components/Theme/models.ts
|
<filename>src/components/Theme/models.ts
import { ThemeType } from './interfaces';
export const light: ThemeType = {
headline: {
size: '3rem',
color: '#222222',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
subhead: {
size: '2rem',
color: '#222222',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
title: {
size: '1.5rem',
color: '#222222',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
subtitle: {
size: '1rem',
color: '#222222',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
paragraph: {
size: '.8rem',
color: '#222222',
weight: 'normal',
family: 'Montserrat, arial, sans-serif',
},
span: {
size: '12px',
color: '#222222',
weight: 'normal',
family: 'Montserrat, arial, sans-serif',
},
primaryColor: 'rgb(40,41,54)',
secondaryColor: '#6272a4',
backgroundColor: '#f0f0f0',
code: {
size: '1rem',
family:
'\'Fira Code\', Consolas, Monaco, \'Andale Mono\', \'Ubuntu Mono\', monospace;',
boxShadow: '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)',
color: 'rgb(40,41,54)',
backgroundColor: '#ffffff',
commentColor: 'rgba(98, 114, 164, 1)',
punctuationColor: 'rgba(98, 114, 164, 1)',
parameterColor: 'rgb(255,121,86)',
boolNumberColor: '#ae81ff',
stringColor: '#6272a4',
functionColor: 'rgb(52,204,8)',
variableColor: 'rgb(40,41,54)',
classColor: 'rgb(0,188,204)',
keywordColor: '#ff79c6',
},
};
export const dark: ThemeType = {
headline: {
size: '3rem',
color: '#ffffff',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
subhead: {
size: '2rem',
color: '#f0f0f0',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
title: {
size: '1.5rem',
color: '#ffffff',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
subtitle: {
size: '1rem',
color: '#f0f0f0',
weight: 'bold',
family: 'Raleway, arial, sans-serif',
},
paragraph: {
size: '.8rem',
color: '#ffffff',
weight: 'normal',
family: 'Montserrat, arial, sans-serif',
},
span: {
size: '12px',
color: '#ffffff',
weight: 'normal',
family: 'Montserrat, arial, sans-serif',
},
primaryColor: 'rgb(40,41,54)',
secondaryColor: '#6272a4',
backgroundColor: '#222222',
code: {
size: '1rem',
family:
'\'Fira Code\', Consolas, Monaco, \'Andale Mono\', \'Ubuntu Mono\', monospace;',
boxShadow: '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)',
color: '#f8f8f2',
backgroundColor: 'rgb(40,41,54)',
commentColor: 'rgba(98, 114, 164, 1)',
punctuationColor: '#f8f8f2',
parameterColor: 'rgba(255, 184, 108, 1)',
boolNumberColor: '#ae81ff',
stringColor: 'rgba(241, 250, 140, 1)',
functionColor: 'rgba(80, 250, 123, 1)',
variableColor: '#f8f8f2',
classColor: 'rgba(139, 233, 253, 1)',
keywordColor: '#ff79c6',
},
};
|
viniciusflv/gatsby-ts
|
src/components/Core/IconText/style.ts
|
import { Flex } from '../Flex';
import { Svg } from '../Svg';
import { Text } from '../Text';
export const WrapperStyle = Flex;
export const FirstIconStyle = Svg;
export const LastIconStyle = Svg;
export const TextStyle = Text;
|
viniciusflv/gatsby-ts
|
src/assets/index.ts
|
<filename>src/assets/index.ts
import vectors from './vectors.json';
export default vectors;
|
viniciusflv/gatsby-ts
|
src/components/Theme/index.tsx
|
import React, { memo, useState } from 'react';
import { ThemeProvider } from 'styled-components';
import { dark, light } from './models';
export const Theme = memo(({ children }) => {
const [toggle, setToggle] = useState(true);
const toggleTheme = () => setToggle(!toggle);
const applyThemeSwitcher = (theme: any) => ({ ...theme, toggleTheme });
const hour = new Date().getHours();
const themes =
hour > 17 || hour < 9 ? (toggle ? dark : light) : toggle ? light : dark;
return (
<ThemeProvider theme={applyThemeSwitcher(themes)}>{children}</ThemeProvider>
);
});
|
viniciusflv/gatsby-ts
|
src/components/Core/Container/index.tsx
|
<filename>src/components/Core/Container/index.tsx
export { ContainerStyle as Container } from './style';
|
viniciusflv/gatsby-ts
|
src/components/Core/IconText/interface.ts
|
import { SvgProps, VectorTypes } from '../Svg/interface';
import { TextProps } from '../Text/interface';
export type IconProps = VectorTypes | SvgProps;
export interface IconTextProps extends Omit<TextProps, 'size'> {
first?: IconProps;
last?: IconProps;
size?: number;
fill?: string;
}
|
viniciusflv/gatsby-ts
|
src/components/TopBar/model.ts
|
<reponame>viniciusflv/gatsby-ts
import { useTheme } from 'styled-components';
import { FlexProps } from '../Core/Flex/interface';
import { PaperProps } from '../Core/Paper/interface';
export class TopBarModels {
HeaderModel: FlexProps;
FixedModel: PaperProps;
NavModel: FlexProps;
constructor() {
const { primaryColor } = useTheme() as any;
this.HeaderModel = {
as: 'header',
id: 'aaa',
};
this.FixedModel = {
alignItems: 'center',
position: 'fixed',
width: '100%',
height: '60px',
backgroundColor: primaryColor,
// backgroundImage: 'linear-gradient(90deg, #008F11 0%, rgba(0,44,53,0) 50%, #008F11 100%);',
borderRadius: 'none',
elevation: 2,
zIndex: '666',
};
this.NavModel = {
as: 'nav',
height: '100%',
width: '100%',
};
}
}
|
viniciusflv/gatsby-ts
|
src/components/Core/Flex/index.tsx
|
export { FlexStyle as Flex } from './style';
|
viniciusflv/gatsby-ts
|
src/components/Markdown/style.ts
|
<gh_stars>0
import styled from 'styled-components';
const CodeStyle = styled.section`
code[class*='language-'],
pre[class*='language-'] {
color: ${({ theme }) => theme.code.color};
background: none;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
font-family: ${({ theme }) => theme.code.family};
font-size: 1em;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
/* Code blocks */
pre[class*='language-'] {
padding: 1em;
margin: 0.5em 0;
overflow: auto;
border-radius: 4px;
height: 100%;
max-height: 600px;
max-width: 100vw;
}
:not(pre) > code[class*='language-'],
pre[class*='language-'] {
background: ${({ theme }) => theme.code.backgroundColor};
box-shadow: ${({ theme }) => theme.code.boxShadow};
}
/* Inline code */
:not(pre) > code[class*='language-'] {
padding: 0.1em;
border-radius: 4px;
white-space: normal;
}
img {
border-radius: 4px;
box-shadow: ${({ theme }) => theme.code.boxShadow} !important;
}
.gatsby-code-button {
position: absolute;
right: 10px;
top: -10px;
fill: ${({ theme }) => theme.secondaryColor};
background: ${({ theme }) => theme.code.backgroundColor};
:active {
opacity: 0.5;
}
:after {
display: none !important;
}
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: ${({ theme }) => theme.code.commentColor};
}
.token.punctuation {
color: ${({ theme }) => theme.code.punctuationColor};
}
.token.namespace {
opacity: 0.7;
}
.token.parameter,
.token.property,
.token.tag,
.token.constant,
.token.symbol,
.token.regex,
.token.important,
.token.deleted {
color: ${({ theme }) => theme.code.parameterColor};
}
.token.boolean,
.token.number {
color: ${({ theme }) => theme.code.boolNumberColor};
}
.token.string {
color: ${({ theme }) => theme.code.stringColor};
}
.token.selector,
.token.attr-name,
.token.char,
.token.builtin,
.token.function,
.token.inserted {
color: ${({ theme }) => theme.code.functionColor};
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable {
color: ${({ theme }) => theme.code.variableColor};
}
.token.builtin,
.token.atrule,
.token.attr-value,
.token.class-name {
color: ${({ theme }) => theme.code.classColor};
}
.token.operator,
.token.keyword {
color: ${({ theme }) => theme.code.keywordColor};
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
`;
export const MarkdownStyle = styled(CodeStyle)`
font-stretch: inherit;
font-family: inherit;
word-spacing: inherit;
text-align: inherit;
text-indent: inherit;
text-shadow: inherit;
text-transform: inherit;
text-decoration: none;
font-size: 12px;
font-weight: inherit;
font-style: inherit;
color: inherit;
word-break: inherit;
white-space: inherit;
direction: inherit;
letter-spacing: inherit;
line-height: unset;
font-family: ${({ theme }) => theme.span.family};
font-size: ${({ theme }) => theme.span.size};
font-weight: ${({ theme }) => theme.span.weight};
color: ${({ theme }) => theme.span.color};
h1 {
font-family: ${({ theme }) => theme.headline.family};
font-size: ${({ theme }) => theme.headline.size};
font-weight: ${({ theme }) => theme.headline.weight};
color: ${({ theme }) => theme.headline.color};
}
h2 {
font-family: ${({ theme }) => theme.subhead.family};
font-size: ${({ theme }) => theme.subhead.size};
font-weight: ${({ theme }) => theme.subhead.weight};
color: ${({ theme }) => theme.subhead.color};
}
h3 {
font-family: ${({ theme }) => theme.title.family};
font-size: ${({ theme }) => theme.title.size};
font-weight: ${({ theme }) => theme.title.weight};
color: ${({ theme }) => theme.title.color};
}
h4 {
font-family: ${({ theme }) => theme.subtitle.family};
font-size: ${({ theme }) => theme.subtitle.size};
font-weight: ${({ theme }) => theme.subtitle.weight};
color: ${({ theme }) => theme.subtitle.color};
}
p {
font-family: ${({ theme }) => theme.paragraph.family};
font-size: ${({ theme }) => theme.paragraph.size};
font-weight: ${({ theme }) => theme.paragraph.weight};
color: ${({ theme }) => theme.paragraph.color};
}
`;
|
viniciusflv/gatsby-ts
|
src/components/SEO/hooks.ts
|
import { graphql, useStaticQuery } from 'gatsby';
import { useLang } from '../Lang/context';
export function useHooks() {
const { messages } = useLang();
const {
site: { siteMetadata: data },
} = useStaticQuery(
graphql`
query {
site {
siteMetadata {
siteUrl
siteName
title
titles
titleTemplate
description
keywords
author
locale
image {
path
type
size
}
}
}
}
`
);
return { ...data, ...messages };
}
|
viniciusflv/gatsby-ts
|
src/components/Core/Link/index.tsx
|
<reponame>viniciusflv/gatsby-ts<gh_stars>0
import React, { FC } from 'react';
import { join } from 'path';
import { LinkStyle, TextStyle } from './style';
import { useLang } from '../../Lang/context';
export const Link: FC<any> = ({ children, to }) => {
const { locale } = useLang();
return (
<LinkStyle to={join(`/${locale}`, to)}>
<TextStyle color='white'>{children}</TextStyle>
</LinkStyle>
);
};
|
viniciusflv/gatsby-ts
|
src/components/Core/Base/index.tsx
|
export { BaseStyle as Base } from './style';
|
viniciusflv/gatsby-ts
|
src/components/TopBar/style.ts
|
import { TopBarModels } from './model';
import { Flex } from '../Core/Flex';
import { Paper } from '../Core/Paper';
export const HeaderStyle = Flex;
export const FixedStyle = Paper;
export const NavStyle = Flex;
|
viniciusflv/gatsby-ts
|
src/components/Theme/interfaces.ts
|
interface TextThemeType {
size: string;
family: string;
color: string;
weight: string;
}
interface Code {
boxShadow: string;
family: string;
size: string;
color: string;
backgroundColor: string;
commentColor: string;
punctuationColor: string;
parameterColor: string;
boolNumberColor: string;
stringColor: string;
functionColor: string;
variableColor: string;
classColor: string;
keywordColor: string;
}
export type ThemeType<T = {}> = T & {
span: TextThemeType;
headline: TextThemeType;
subhead: TextThemeType;
title: TextThemeType;
subtitle: TextThemeType;
paragraph: TextThemeType;
code: Code;
primaryColor: string;
secondaryColor: string;
backgroundColor: string;
};
|
viniciusflv/gatsby-ts
|
src/components/Core/Text/interface.ts
|
import { ComponentType } from 'react';
import * as TextStyles from './style';
import { ContainerProps } from '../Container/interface';
export enum TextTypes {
Span = 'SpanStyle',
H1 = 'H1Style',
H2 = 'H2Style',
H3 = 'H3Style',
H4 = 'H4Style',
// Hr = 'HrStyle',
// Caption = 'CaptionStyle',
// Th = 'ThStyle',
// Td = 'TdStyle',
// Li = 'ListItemStyle',
P = 'ParagraphStyle',
// A = 'AnchorStyle',
// Label = 'LabelStyle',
// Option = 'OptionStyle',
// I = 'ItalicStyle',
}
export interface TextProps extends ContainerProps {
type?: TextTypes;
text?: ComponentType<any> | string;
align?: string;
indent?: string;
shadow?: string;
transform?: string;
decoration?: string;
size?: string;
weight?: string;
family?: string;
fontStyle?: string;
color?: string;
wordBreak?: string;
whiteSpace?: string;
direction?: string;
spacing?: string;
lineHeight?: string;
stroke?: string;
}
|
viniciusflv/gatsby-ts
|
src/components/Core/Base/interface.ts
|
<gh_stars>0
export type BaseProps<T = {}> = T &
React.HTMLAttributes<T> & {
as?: keyof JSX.IntrinsicElements | React.ComponentType<any>;
theme?: any;
content?: string;
grow?: string;
outline?: string;
transition?: string;
cursor?: string;
pointerEvents?: string;
opacity?: string;
display?: string;
visibility?: string;
zIndex?: string;
alignSelf?: string;
};
|
viniciusflv/gatsby-ts
|
src/components/Pages/index.tsx
|
import React, { Fragment, memo } from 'react';
import { FormattedMessage } from 'gatsby-plugin-intl';
import assets from '../../assets';
import { Flex } from '../Core/Flex';
import { IconText } from '../Core/IconText';
import { Svg } from '../Core/Svg';
import { Text } from '../Core/Text';
import { TextTypes } from '../Core/Text/interface';
import { useLang } from '../Lang/context';
import { SEO } from '../SEO';
export default memo(() => {
const { messages } = useLang();
return (
<Fragment>
<SEO title={messages.title as string} />
<Flex direction='column'>
<FormattedMessage id='title' />
<Text text='Headline Style' type={TextTypes.H1} />
<Text text='Subhead Style' type={TextTypes.H2} />
<Text text='Title Style' type={TextTypes.H3} />
<Text text='Subtitle Style' type={TextTypes.H4} />
<Text text='Paragraph Style' type={TextTypes.P} />
<Text>aaa</Text>
<Flex gap='20px' wrap='wrap'>
{Object.keys(assets).map<any>((key: any) => (
<Svg key={key} vector={key} height='50px' width='50px' />
))}
</Flex>
<Flex>
<IconText
direction='column'
color='blue'
fill='red'
text='IconText'
size={1}
first={'person'}
last={'person'}
/>
</Flex>
</Flex>
</Fragment>
);
});
|
viniciusflv/gatsby-ts
|
src/components/App/style.ts
|
<filename>src/components/App/style.ts
import { createGlobalStyle } from 'styled-components';
import { ThemeType } from '../Theme/interfaces';
export const GlobalStyle = createGlobalStyle<{ theme: ThemeType }>`
* {
box-sizing: border-box;
outline-color: ${({ theme }) => theme.secondaryColor};
}
html, body {
margin: 0;
padding: 0;
min-width: max-content;
min-width: 100%;
min-height: 100%;
width: 100%;
height: 100%;
background-color: ${({ theme }) => theme.backgroundColor};
}
#___gatsby, #gatsby-focus-wrapper {
min-width: 100%;
min-height: 100%;
width: 100%;
height: 100%;
display: grid;
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background-color: rgba(0,0,0,.2);
}
::-webkit-scrollbar-thumb {
background-color: ${({ theme }) => theme.secondaryColor};
}
`;
|
viniciusflv/gatsby-ts
|
src/components/TopBar/index.tsx
|
<gh_stars>0
import React, { memo } from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import { useTheme } from 'styled-components';
import { TopBarModels } from './model';
import { FixedStyle, HeaderStyle, NavStyle } from './style';
import { useLang } from '../Lang/context';
import { Menu } from '../Menu';
export const TopBar = memo(() => {
const { FixedModel, HeaderModel, NavModel } = new TopBarModels();
const { toggleTheme } = useTheme() as any;
const { toggleLocale } = useLang();
return (
<HeaderStyle {...HeaderModel}>
<FixedStyle {...FixedModel}>
<NavStyle {...NavModel}>
<button onClick={toggleTheme}>Toggle Theme</button>
<button onClick={toggleLocale}>Toggle Locale</button>
<Menu />
</NavStyle>
</FixedStyle>
</HeaderStyle>
);
});
|
viniciusflv/gatsby-ts
|
gatsby-api.tsx
|
<reponame>viniciusflv/gatsby-ts
import React from 'react';
import {
ReplaceComponentRendererArgs,
WrapPageElementBrowserArgs,
WrapPageElementNodeArgs,
WrapRootElementBrowserArgs,
WrapRootElementNodeArgs,
} from 'gatsby';
import { IntlConfig } from 'gatsby-plugin-intl';
import { App } from './src/components/App';
import { Layout } from './src/components/Layout';
export type LoadPageSync = (
pathname: typeof window.location.pathname
) => {
json: Omit<ReplaceComponentRendererArgs['props'], 'pageContext'> & {
pageContext: { intl: IntlConfig & { defaultLanguage: string } };
};
};
export type RootElementArgs = (
| WrapRootElementBrowserArgs
| WrapRootElementNodeArgs
) & { loadPageSync: LoadPageSync };
export type PageElementArgs = (
| WrapPageElementBrowserArgs
| WrapPageElementNodeArgs
) & ReplaceComponentRendererArgs;
export const wrapRootElement = (props: RootElementArgs) => {
return <App {...props}>{props.element}</App>;
};
export const wrapPageElement = ({ element, props }: PageElementArgs) => {
return props.path ? <Layout {...props}>{element}</Layout> : element;
};
|
viniciusflv/gatsby-ts
|
src/components/Core/Flex/interface.ts
|
<filename>src/components/Core/Flex/interface.ts<gh_stars>0
import { ContainerProps } from '../Container/interface';
export type FlexProps<T = {}> = ContainerProps<
T & {
direction?: string;
justifyContent?: string;
alignItems?: string;
wrap?: string;
gap?: string;
}
>;
|
viniciusflv/gatsby-ts
|
src/components/Core/Svg/interface.ts
|
<filename>src/components/Core/Svg/interface.ts<gh_stars>0
import assets from '../../../assets';
import { FlexProps } from '../Flex/interface';
export interface Stop {
offset: string;
stopColor: string;
}
export interface Gradient {
stops: Array<Stop>;
}
export interface Animate {
fill: string;
begin: string;
dur: string;
repeatCount: string;
attributeName: string;
to: string;
}
export interface Path {
d: string;
fill?: string;
animates?: Array<Animate>;
}
export interface SvgAsset {
paths: Array<Path>;
viewBox: string;
fill?: string;
linearGradient?: Gradient;
radialGradient?: Gradient;
}
export type VectorTypes = keyof typeof assets;
export interface SvgProps extends FlexProps {
vector: VectorTypes;
color?: string;
}
|
viniciusflv/gatsby-ts
|
src/components/Core/IconText/index.tsx
|
import React, { FC, memo } from 'react';
import { IconTextProps } from './interface';
import { IconTextModel } from './model';
import {
FirstIconStyle,
LastIconStyle,
TextStyle,
WrapperStyle,
} from './style';
export const IconText: FC<IconTextProps> = memo((props) => {
const { first, last } = props;
const {
WrapperModel,
FirstIconModel,
TextModel,
LastIconModel,
} = new IconTextModel(props);
return (
<WrapperStyle {...WrapperModel}>
{first && <FirstIconStyle {...FirstIconModel} />}
<TextStyle {...TextModel} />
{last && <LastIconStyle {...LastIconModel} />}
</WrapperStyle>
);
});
|
viniciusflv/gatsby-ts
|
src/components/Core/Paper/interface.ts
|
import { FlexProps } from '../Flex/interface';
export type PaperProps<T = {}> = FlexProps<
T & {
elevation?: number;
}
>;
|
viniciusflv/gatsby-ts
|
src/components/Menu/index.tsx
|
<reponame>viniciusflv/gatsby-ts<filename>src/components/Menu/index.tsx
import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import { useTheme } from 'styled-components';
import { Link } from '../Core/Link';
export const Menu = () => {
const {
allSitePage: { nodes },
} = useStaticQuery(graphql`
query {
allSitePage {
nodes {
path
}
}
}
`);
function startsWith(str: string, searchStrings: Array<string>) {
return searchStrings.reduce(
(acc, searchString) => acc || str.startsWith(searchString),
false
);
}
function getPathsFromNodes(nodeArr: Array<any>): Array<string> {
return nodeArr
.map(({ path }: any) => path)
.filter(
(path: string) => !startsWith(path, ['/en', '/pt', '/404', '/dev'])
);
}
return (
<div>
{getPathsFromNodes(nodes).map((path) => (
<Link key={path} to={path}>
path
</Link>
))}
</div>
);
};
|
viniciusflv/gatsby-ts
|
src/components/Markdown/index.tsx
|
<gh_stars>0
import React, { FC, memo } from 'react';
import { MarkdownStyle } from './style';
export const Markdown: FC<{ html: string }> = memo(({ html }) => {
return <MarkdownStyle dangerouslySetInnerHTML={{ __html: html }} />;
});
|
viniciusflv/gatsby-ts
|
src/components/Core/Paper/style.ts
|
<reponame>viniciusflv/gatsby-ts<filename>src/components/Core/Paper/style.ts<gh_stars>0
import styled from 'styled-components';
import { PaperProps } from './interface';
import { Flex } from '../Flex';
const getElevation = (ele: number) => {
switch (ele) {
case 1:
return '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)';
case 2:
return '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)';
case 3:
return '0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23)';
case 4:
return '0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22)';
case 5:
return '0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22)';
default:
return '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)';
}
};
export const PaperStyle = styled(Flex).attrs(props => ({
backgroundColor: '#ffffff',
borderRadius: '4px',
...props,
}))<PaperProps>`
${({ elevation }) => elevation && `box-shadow: ${getElevation(elevation)};`}
`;
|
viniciusflv/gatsby-ts
|
src/components/Lang/context.ts
|
<filename>src/components/Lang/context.ts<gh_stars>0
import { createContext, useContext } from 'react';
import { useIntl } from 'gatsby-plugin-intl';
export const LangContext = createContext({});
export const LangProvider = LangContext.Provider;
export function useLang() {
return Object.assign(useIntl(), useContext(LangContext));
}
|
viniciusflv/gatsby-ts
|
src/components/Core/Base/style.ts
|
<gh_stars>0
import styled from 'styled-components';
import { BaseProps } from './interface';
export const BaseStyle = styled.div<BaseProps>`
${({ content }) => content && `content: ${content};`}
${({ grow }) => grow && `flex-grow: ${grow};`}
${({ outline }) => outline && `outline: ${outline};`}
${({ transition }) => transition && `transition: ${transition};`}
${({ cursor }) => cursor && `cursor: ${cursor};`}
${({ pointerEvents }) => pointerEvents && `pointer-events: ${pointerEvents};`}
${({ opacity }) => opacity && `opacity: ${opacity};`}
${({ display }) => display && `display: ${display};`}
${({ visibility }) => visibility && `visibility: ${visibility};`}
${({ zIndex }) => zIndex && `z-index: ${zIndex};`}
${({ alignSelf }) => alignSelf && `align-self: ${alignSelf};`}
`;
|
viniciusflv/gatsby-ts
|
src/components/SEO/index.tsx
|
<gh_stars>0
import React, { FC, memo } from 'react';
import { Helmet } from 'react-helmet';
import { join } from 'path';
import { useHooks } from './hooks';
export const SEO: FC<{
title?: string;
description?: string;
path?: string;
}> = memo(({ title, description, path }) => {
const data = useHooks();
const pageTitle = title ?? new Map(data?.titles).get(path) ?? data?.title;
return (
<Helmet
defaultTitle={data?.title}
titleTemplate={data?.titleTemplate}
defer={false}
>
<title>{pageTitle}</title>
<meta content={pageTitle} property='og:title' />
<meta content={description ?? data?.description} name='description' />
<meta content={description ?? data?.description} itemProp='description' />
<meta
content={description ?? data?.description}
property='og:description'
/>
<meta content={data?.keywords} name='keywords' />
<meta content={data?.author} name='author' />
<meta content={data?.siteName} itemProp='name' />
<meta content={data?.siteName} property='og:site_name' />
<meta content={data?.siteUrl} property='og:url' />
<meta content={join(data?.siteUrl, data?.image?.path)} itemProp='image' />
<meta
content={join(data?.siteUrl, data?.image?.path)}
property='og:image'
/>
<meta content={data?.image?.type} property='og:image:type' />
<meta content={data?.image?.size} property='og:image:width' />
<meta content={data?.image?.size} property='og:image:height' />
<meta content={data?.locale} property='og:locale' />
<meta content='website' property='og:type' />
<meta content='index, follow' name='robots' />
</Helmet>
);
});
|
viniciusflv/gatsby-ts
|
src/components/Core/Grid/index.tsx
|
<gh_stars>0
export { GridStyle as Grid } from './style';
|
viniciusflv/gatsby-ts
|
src/components/Pages/style.ts
|
<filename>src/components/Pages/style.ts
import styled from 'styled-components';
export const HeadlineStyle = styled.h1`
font-size: ${({ theme }) => theme.headline.size};
font-family: ${({ theme }) => theme.headline.family};
font-weight: ${({ theme }) => theme.headline.weight};
color: ${({ theme }) => theme.headline.color};
`;
export const SubheadStyle = styled.h2`
font-size: ${({ theme }) => theme.subhead.size};
font-family: ${({ theme }) => theme.subhead.family};
font-weight: ${({ theme }) => theme.subhead.weight};
color: ${({ theme }) => theme.subhead.color};
`;
export const TitleStyle = styled.h3`
font-size: ${({ theme }) => theme.title.size};
font-family: ${({ theme }) => theme.title.family};
font-weight: ${({ theme }) => theme.title.weight};
color: ${({ theme }) => theme.title.color};
`;
export const SubtitleStyle = styled.h4`
font-size: ${({ theme }) => theme.subtitle.size};
font-family: ${({ theme }) => theme.subtitle.family};
font-weight: ${({ theme }) => theme.subtitle.weight};
color: ${({ theme }) => theme.subtitle.color};
`;
export const ParagraphStyle = styled.p`
font-size: ${({ theme }) => theme.paragraph.size};
font-family: ${({ theme }) => theme.paragraph.family};
font-weight: ${({ theme }) => theme.paragraph.weight};
color: ${({ theme }) => theme.paragraph.color};
`;
|
viniciusflv/gatsby-ts
|
src/components/App/index.tsx
|
import React, { FC, memo, useEffect, useState } from 'react';
import { WrapRootElementBrowserArgs, WrapRootElementNodeArgs } from 'gatsby';
import { GlobalStyle } from './style';
import { RootElementArgs } from '../../../gatsby-api';
import { Lang } from '../Lang';
import { SEO } from '../SEO';
import { Theme } from '../Theme';
export const App: FC<RootElementArgs> = memo(({ children, ...props }) => {
return (
<Lang {...props}>
<Theme>
<SEO />
{children}
<GlobalStyle />
</Theme>
</Lang>
);
});
|
viniciusflv/gatsby-ts
|
src/components/Core/Grid/style.ts
|
import styled from 'styled-components';
import { GridProps } from './interface';
import { Container } from '../Container';
export const GridStyle = styled(Container).attrs(({ display }: GridProps) => ({
display: display || 'grid',
}))<GridProps>`
${({ columns }) => columns && `grid-template-columns:${columns};`}
${({ rows }) => rows && `grid-template-rows:${rows};`}
${({ areas }) => areas && `grid-template-areas:${areas};`}
${({ gap }) => gap && `grid-gap:${gap};`}
`;
|
viniciusflv/gatsby-ts
|
src/components/Core/Text/style.ts
|
<reponame>viniciusflv/gatsby-ts
import styled from 'styled-components';
import { TextProps } from './interface';
import { Container } from '../Container';
export const TextStyle = styled(Container).attrs({ as: 'span' })<TextProps>`
font-stretch: inherit;
font-family: inherit;
word-spacing: inherit;
text-align: inherit;
text-indent: inherit;
text-shadow: inherit;
text-transform: inherit;
text-decoration: none;
font-size: 12px;
font-weight: inherit;
font-style: inherit;
color: inherit;
word-break: inherit;
white-space: inherit;
direction: inherit;
letter-spacing: inherit;
line-height: unset;
${({ wordBreak }) => wordBreak && 'word-break: break-all;'}
${({ whiteSpace }) => whiteSpace && `white-space: ${whiteSpace};`}
${({ family }) => family && `font-family: ${family};`}
${({ size }) => size && `font-size: ${size};`}
${({ weight }) => weight && `font-weight: ${weight};`}
${({ color }) => color && `color: ${color};`}
${({ align }) => align && `text-align: ${align};`}
${({ decoration }) => decoration && `text-decoration: ${decoration};`}
${({ transform }) => transform && `text-transform: ${transform};`}
${({ indent }) => indent && `text-indent: ${indent};`}
${({ shadow }) => shadow && `text-shadow: ${shadow};`}
${({ spacing }) => spacing && `letter-spacing: ${spacing};`}
${({ direction }) => direction && `direction: ${direction};`}
${({ lineHeight }) => lineHeight && `line-height: ${lineHeight};`}
${({ margin }) => margin && `margin: ${margin};`}
${({ padding }) => padding && `padding: ${padding};`}
${({ maxWidth }) => maxWidth && `max-width: ${maxWidth};`}
${({ minWidth }) => minWidth && `min-width: ${minWidth};`}
${({ stroke }) =>
stroke &&
`
text-shadow:
-1px 0 ${stroke},
0 1px ${stroke},
1px 0 ${stroke},
0 -1px ${stroke};
`}
`;
export const SpanStyle = styled(TextStyle).attrs(({ theme, ...props }) => ({
...theme.span,
...props,
}))``;
export const H1Style = styled(SpanStyle).attrs(({ theme }) => ({
...theme.headline,
as: 'h1',
}))``;
export const H2Style = styled(SpanStyle).attrs(({ theme }) => ({
...theme.subhead,
as: 'h2',
}))``;
export const H3Style = styled(SpanStyle).attrs(({ theme }) => ({
...theme.title,
as: 'h3',
}))``;
export const H4Style = styled(SpanStyle).attrs(({ theme }) => ({
...theme.subtitle,
as: 'h4',
}))``;
export const ParagraphStyle = styled(SpanStyle).attrs(({ theme }) => ({
...theme.paragraph,
as: 'p',
}))``;
|
viniciusflv/gatsby-ts
|
src/components/Layout/index.tsx
|
<gh_stars>0
import React, { FC, memo, useEffect } from 'react';
import { useTheme } from 'styled-components';
import { Flex } from '../Core/Flex';
import { Grid } from '../Core/Grid';
import { SEO } from '../SEO';
import { TopBar } from '../TopBar';
export const Layout: FC<any> = memo(({ children, path }) => {
const { backgroundColor } = useTheme() as any;
return (
<Grid
as='section'
backgroundColor={backgroundColor}
width='100%'
height='100%'
rows='60px 1fr'
>
<SEO path={path} />
<TopBar />
<Flex
as='main'
minWidth='100%'
minHeight='100% '
width='100%'
height='100%'
direction='column'
grow='2'
padding='20px'
margin='0 auto'
>
{children}
</Flex>
</Grid>
);
});
|
viniciusflv/gatsby-ts
|
src/components/Templates/Blog/index.tsx
|
<reponame>viniciusflv/gatsby-ts
import React, { Fragment, memo } from 'react';
import { graphql } from 'gatsby';
import { Flex } from '../../Core/Flex';
import { Text } from '../../Core/Text';
import { TextTypes } from '../../Core/Text/interface';
import { Markdown } from '../../Markdown';
import { SEO } from '../../SEO';
export const query = graphql`
query($slug: String!, $language: String!) {
markdownRemark(
fields: { slug: { eq: $slug }, language: { eq: $language } }
) {
frontmatter {
title
date
}
html
}
}
`;
export default memo(
({
data: {
markdownRemark: {
frontmatter: { title, date },
html,
},
},
}: any) => {
return (
<Fragment>
<SEO title={title} />
<Flex
direction='column'
grow='2'
maxWidth='1200px'
width='100%'
margin='auto'
>
<Text text={title} type={TextTypes.H1} />
<Text text={date} type={TextTypes.P} />
<Markdown html={html} />
</Flex>
</Fragment>
);
}
);
|
viniciusflv/gatsby-ts
|
src/components/Core/Container/style.ts
|
<gh_stars>0
import styled from 'styled-components';
import { Border, BorderRadius, ContainerProps, X, XY, Y } from './interface';
import { Base } from '../Base';
const getXYRadius = (
yKey: keyof Y<string>,
xKey: keyof X<string>,
xy: string
) => {
return `
border-${yKey}-${xKey}-radius: ${xy};
border-${yKey}-${xKey}-radius: ${xy};
`;
};
const getYRadius = (key: keyof Y<string>, x: X<string> | string) => {
if (x === 'string') {
return `
border-${key}-left-radius: ${x};
border-${key}-right-radius: ${x};
`;
}
const { left, right } = x as X<string>;
let xy = '';
if (left) xy += getXYRadius(key, 'left', left);
if (right) xy += getXYRadius(key, 'right', right);
return xy;
};
const getTopRadius = (top: X<string> | string) => {
return getYRadius('top', top);
};
const getBottomRadius = (bottom: X<string> | string) => {
return getYRadius('bottom', bottom);
};
const getRadius = (radius: BorderRadius | string) => {
if (typeof radius === 'string') return `border-radius: ${radius};`;
const { top, bottom } = radius;
let xyRadius = '';
if (top) xyRadius += getTopRadius(top);
if (bottom) xyRadius += getBottomRadius(bottom);
return xyRadius;
};
const getXY = (key: string, props: XY<string> | string) => {
if (typeof props === 'string') return `${[key]}: ${props};`;
const { top, bottom, left, right } = props;
let xy = '';
if (top) xy += `${[key]}-top: ${top};`;
if (bottom) xy += `${[key]}-bottom: ${bottom};`;
if (left) xy += `${[key]}-left: ${left};`;
if (right) xy += `${[key]}-right: ${right};`;
return xy;
};
const getBorder = (border: Border | string) => {
let borderAcc = getXY('border', border);
if (typeof border !== 'string' && border.radius) {
borderAcc += getRadius(border.radius as Border);
}
return borderAcc;
};
const getMargin = (margin: XY<string> | string) => {
return getXY('margin', margin);
};
const getPadding = (padding: XY<string> | string) => {
return getXY('padding', padding);
};
export const ContainerStyle = styled(Base)<ContainerProps>`
margin: 0;
padding: 0;
border: none;
background-color: transparent;
${({ outline }) => outline && `outline: ${outline};`}
${({ top }) => top && `top: ${top};`}
${({ bottom }) => bottom && `bottom: ${bottom};`}
${({ right }) => right && `right: ${right};`}
${({ left }) => left && `left: ${left};`}
${({ position }) => position && `position: ${position};`}
${({ transform }) => transform && `transform: ${transform};`}
${({ objectFit }) => objectFit && `object-fit: ${objectFit};`}
${({ area }) => area && `grid-area: ${area};`}
${({ height }) => height && `height: ${height};`}
${({ minHeight }) => minHeight && `min-height: ${minHeight};`}
${({ maxHeight }) => maxHeight && `max-height: ${maxHeight};`}
${({ width }) => width && `width: ${width};`}
${({ minWidth }) => minWidth && `min-width: ${minWidth};`}
${({ maxWidth }) => maxWidth && `max-width: ${maxWidth};`}
${({ fullWidth }) => fullWidth && `width: 100%;`}
${({ overflow }) => overflow && `overflow: ${overflow};`}
${({ color }) => color && `color: ${color};`}
${({ font }) => font && `font: ${font};`}
${({ backgroundImage }) =>
backgroundImage && `background-image: ${backgroundImage};`}
${({ backgroundColor }) =>
backgroundColor && `background-color: ${backgroundColor};`}
${({ boxShadow }) => boxShadow && `box-shadow: ${boxShadow};`}
${({ borderCollapse }) =>
borderCollapse && `border-collapse: ${borderCollapse};`}
${({ border }) => border && getBorder(border)}
${({ borderRadius }) => borderRadius && getRadius(borderRadius)}
${({ align }) => align && `text-align: ${align};`}
${({ contain }) =>
contain &&
`
width: 100%;
max-width: 1024px;
margin: 0 auto;
padding: 0 20px;
`}
${({ margin }) => margin && getMargin(margin)}
${({ padding }) => padding && getPadding(padding)}
`;
|
viniciusflv/gatsby-ts
|
src/components/Pages/404/index.tsx
|
import React, { memo } from 'react';
import { Svg } from '../../Core/Svg';
export default memo(() => {
return <Svg vector='close' />;
});
|
viniciusflv/gatsby-ts
|
src/components/Lang/hooks.ts
|
<reponame>viniciusflv/gatsby-ts
import { useEffect, useState } from 'react';
import { changeLocale } from 'gatsby-plugin-intl';
import { LoadPageSync } from '../../../gatsby-api';
export function useHooks(loadPageSync: LoadPageSync) {
const initialLocale = 'en';
const [locale, setLocale] = useState<string>();
const [navigatorLocale, setNavigatorLocale] = useState(initialLocale);
const [defaultLocale, setDefaultLocale] = useState(initialLocale);
const [messages, setMessages] = useState({});
useEffect(() => {
if (locale) changeLocale(locale);
}, [locale]);
useEffect(() => {
const page = loadPageSync(window?.location?.pathname);
const { intl } = page?.json?.pageContext;
const navigatorLanguage = window.navigator.language.split('-')[0];
if (navigatorLanguage !== initialLocale) changeLocale(navigatorLanguage);
setNavigatorLocale(navigatorLanguage);
setDefaultLocale(intl.defaultLanguage);
setMessages(intl.messages);
}, []);
function toggleLocale() {
setLocale((locale ?? navigatorLocale) === 'pt' ? 'en' : 'pt');
}
return {
locale: locale ?? navigatorLocale,
toggleLocale,
navigatorLocale,
messages,
defaultLocale,
};
}
|
viniciusflv/gatsby-ts
|
src/components/Core/Container/interface.ts
|
<filename>src/components/Core/Container/interface.ts
import { BaseProps } from '../Base/interface';
export interface Y<T> {
top?: T;
bottom?: T;
}
export interface X<T> {
left?: T;
right?: T;
}
export interface XY<T> extends X<T>, Y<T> {}
export interface BorderRadius extends Y<X<string> | string> {}
export interface Border extends XY<string> {
radius?: BorderRadius | string;
}
export type ContainerProps<T = {}> = BaseProps<
T &
XY<string> & {
outline?: string;
position?: string;
transform?: string;
objectFit?: string;
area?: string;
height?: string;
minHeight?: string;
maxHeight?: string;
width?: string;
minWidth?: string;
maxWidth?: string;
fullWidth?: boolean;
overflow?: string;
color?: string;
backgroundImage?: string;
backgroundColor?: string;
boxShadow?: string;
font?: string;
borderCollapse?: string;
contain?: boolean;
align?: string;
borderRadius?: BorderRadius | string;
border?: Border | string;
margin?: XY<string> | string;
padding?: XY<string> | string;
}
>;
|
viniciusflv/gatsby-ts
|
src/components/Core/Paper/index.tsx
|
<reponame>viniciusflv/gatsby-ts
export { PaperStyle as Paper } from './style';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.