nanoid#nanoid JavaScript Examples
The following examples show how to use
nanoid#nanoid.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Accordion.js From basis with MIT License | 6 votes |
function Item(props) {
const theme = useTheme();
const { itemGap } = useAccordion();
const [headerId] = useState(() => `accordion-item-header-${nanoid()}`);
const [contentId] = useState(() => `accordion-item-content-${nanoid()}`);
const mergedProps = mergeProps(
props,
DEFAULT_ITEM_PROPS,
{},
{
initiallyOpen: (initiallyOpen) => typeof initiallyOpen === "boolean",
}
);
const { initiallyOpen, children, testId } = mergedProps;
const [isOpen, setIsOpen] = useState(initiallyOpen);
const toggleAccordionItem = useCallback(() => {
setIsOpen((isOpen) => !isOpen);
}, []);
const accordionItemInfo = useMemo(
() => ({
headerId,
contentId,
isOpen,
toggleAccordionItem,
}),
[headerId, contentId, isOpen, toggleAccordionItem]
);
return (
<AccordionItemProvider value={accordionItemInfo}>
<div
css={theme.accordion.getCSS({ targetElement: "item", itemGap })}
data-testid={testId}
>
{children}
</div>
</AccordionItemProvider>
);
}
Example #2
Source File: RoomView.jsx From airboardgame with MIT License | 6 votes |
RoomView = ({ roomId }) => {
const [room, setRoom] = React.useState(() => ({
sessions: [{ id: nanoid() }, { id: nanoid() }, { id: nanoid() }],
}));
return (
<>
<Switch>
<Route path="/room/:roomId/" exact>
<Room roomId={roomId} room={room} setRoom={setRoom} />
</Route>
<Route path="/room/:roomId/session/:sessionId">
{({
match: {
params: { sessionId },
},
}) => {
return <Session sessionId={sessionId} />;
}}
</Route>
</Switch>
<SubscribeRoomEvents room={room} setRoom={setRoom} />
</>
);
}
Example #3
Source File: chartHelper.js From sqliteviz with Apache License 2.0 | 6 votes |
export function getHtml (options) {
const chartId = nanoid()
return `
<script src="https://cdn.plot.ly/plotly-latest.js" charset="UTF-8"></script>
<div id="${chartId}"></div>
<script>
const el = document.getElementById("${chartId}")
let timeout
function debounceResize() {
clearTimeout(timeout)
timeout = setTimeout(() => {
var r = el.getBoundingClientRect()
Plotly.relayout(el, {width: r.width, height: r.height})
}, 200)
}
const resizeObserver = new ResizeObserver(debounceResize)
resizeObserver.observe(el)
Plotly.newPlot(el, ${JSON.stringify(options.data)}, ${JSON.stringify(options.layout)})
</script>
`
}
Example #4
Source File: runner.js From playwright-test with MIT License | 6 votes |
/**
*
* @param {Partial<import('./types').RunnerOptions>} [options]
*/
constructor(options = {}) {
/** @type {RunnerOptions} */
this.options = merge(defaultOptions, options)
/** @type {import('polka').Polka["server"] | undefined} */
this.server = undefined
this.dir = path.join(__dirname, '../.tmp', nanoid())
mkdirSync(this.dir, {
recursive: true,
})
this.browserDir = temporaryDirectory()
this.url = ''
this.stopped = false
this.watching = false
this.env = merge(JSON.parse(JSON.stringify(process.env)), {
PW_TEST: this.options,
})
this.extensions = this.options.extensions.split(',')
this.beforeTestsOutput = undefined
this.tests = findTests({
cwd: this.options.cwd,
extensions: this.extensions,
filePatterns: this.options.input
? this.options.input
: defaultTestPatterns(this.extensions),
})
if (this.tests.length === 0) {
this.stop(false, 'No test files were found.')
}
process.env.DEBUG += ',-pw:*'
}
Example #5
Source File: random.js From dm2 with Apache License 2.0 | 6 votes |
/**
* Unique hash generator
* @param {number} lgth
*/
export function guidGenerator(lgth) {
let uniqueID = nanoid(10);
if (lgth) {
uniqueID = nanoid(lgth);
}
return uniqueID;
}
Example #6
Source File: UploadService.js From 1km.co.il with MIT License | 6 votes |
export async function uploadImage({ base64File, protestId, date }) {
try {
const fileId = nanoid();
const formData = new FormData();
formData.append('upload_preset', 'public_upload');
formData.append('file', base64File);
formData.append('public_id', `${protestId}/${date}/${fileId}`);
const response = await fetch('https://api.cloudinary.com/v1_1/onekm/upload', { method: 'POST', body: formData });
const data = await response.json();
console.log(data);
return { ...data, fileId };
} catch (err) {
console.error(err);
}
}
Example #7
Source File: Checkbox.js From flume with MIT License | 6 votes |
Checkbox = ({ label, value, onChange }) => {
const id = React.useRef(nanoid(10));
return (
<div className="checkbox-wrapper">
<input
type="checkbox"
value={value}
checked={value}
id={id.current}
onChange={e => onChange(e.target.checked)}
/>
<label htmlFor={id.current} className="checkbox-box"></label>
<label htmlFor={id.current} className="checkbox-label">{label}</label>
</div>
);
}
Example #8
Source File: index.js From uid with MIT License | 6 votes |
size_25 = {
'cuid': cuid,
'hashids/fixed': new HashID('', 25),
'nanoid/non-secure': nanoid2.bind(nanoid2, 25),
'nanoid': nanoid.bind(nanoid, 25),
'uid/secure': secure.bind(secure, 25),
'uid/single': single.bind(single, 25),
'uid': uid.bind(uid, 25),
}
Example #9
Source File: controller.js From Docker-for-Developers with MIT License | 6 votes |
async createGame(req, res) {
try {
const id = nanoid();
const started_on = new Date().getTime();
var redis = await RedisService.set(id, started_on);
l.debug({ msg: 'Redis SET complete', key: id, value: redis });
return res.status(201).json({
id: id,
started_on: started_on,
});
} catch (err) {
l.error({ msg: 'createGame Redis SET errored', error: err });
return res.status(500);
}
}
Example #10
Source File: CheckboxesSetting.js From basis with MIT License | 6 votes |
function Checkbox({ value, checked, label, onChange }) {
const theme = useTheme();
const [id] = useState(`checkbox-${nanoid()}`);
return (
<div
css={{
paddingTop: theme.space[1],
paddingBottom: theme.space[1],
whiteSpace: "nowrap",
}}
>
<input
id={id}
type="checkbox"
value={value}
checked={checked}
onChange={onChange}
/>
<label
css={{ marginLeft: theme.space[2], verticalAlign: "middle" }}
htmlFor={id}
>
{label}
</label>
</div>
);
}
Example #11
Source File: docx-document.js From html-to-docx with MIT License | 6 votes |
createMediaFile(base64String) {
// eslint-disable-next-line no-useless-escape
const matches = base64String.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
if (matches.length !== 3) {
throw new Error('Invalid base64 string');
}
const base64FileContent = matches[2];
// matches array contains file type in base64 format - image/jpeg and base64 stringified data
const fileExtension =
matches[1].match(/\/(.*?)$/)[1] === 'octet-stream' ? 'png' : matches[1].match(/\/(.*?)$/)[1];
const fileNameWithExtension = `image-${nanoid()}.${fileExtension}`;
this.lastMediaId += 1;
return { id: this.lastMediaId, fileContent: base64FileContent, fileNameWithExtension };
}
Example #12
Source File: ConnectionList.jsx From tinkerun with MIT License | 6 votes |
ConnectionList = () => {
const [, setLocation] = useLocation()
const connections = useAtomValue(connectionListAtom)
const createConnection = useUpdateAtom(createConnectionAtom)
useEffect(() => {
const onClone = onCloneConnection(connection => {
const connectionNew = {
...connection,
id: nanoid(),
}
createConnection(connectionNew)
setLocation(`/connections/${connectionNew.id}`)
})
return () => onClone.dispose()
}, [])
return (
<Pane>
<DeleteConnectionConfirm/>
{connections.map(connection => (
<ConnectionItem
key={connection.id}
connection={connection}
/>
))}
</Pane>
)
}
Example #13
Source File: Login.js From airdrop with MIT License | 6 votes |
guest = () => (dispatch) => {
firebase
.auth()
.signInAnonymously()
.then((result) => {
dispatch({ type: 'LOGIN_WAITING' });
const { user } = result;
const name = `G-${nanoid(5)}`;
const photoURL = Math.floor(Math.random() * 2) === 0 ? photo1 : photh2;
const object = {
uid: user.uid,
displayName: name,
isAnonymous: user.isAnonymous,
photoURL,
joinedAt: firebase.firestore.FieldValue.serverTimestamp(),
};
// Add the user to the database if not exits
check(user, object, dispatch, true);
})
.catch((error) => {
// Handle Errors here.
dispatch({ type: 'LOGIN_ERROR', error });
// ...
});
}
Example #14
Source File: createProjectScripts.js From zubhub with GNU Affero General Public License v3.0 | 6 votes |
uploadImageToLocal = (image, state, props, handleSetState) => {
let url =
process.env.REACT_APP_NODE_ENV === 'production'
? process.env.REACT_APP_BACKEND_PRODUCTION_URL + '/api/'
: process.env.REACT_APP_BACKEND_DEVELOPMENT_URL + '/api/';
url = url + 'upload-file-to-local/';
const formData = new FormData();
formData.append('file', image);
formData.append('key', `project_images/${nanoid()}`);
return new Promise((resolve, reject) => {
const um = new UploadMedia(
'image',
url,
formData,
state,
props,
handleSetState,
resolve,
reject,
);
um.upload();
});
}
Example #15
Source File: RandomIdProvider.js From nhs-virtual-visit with MIT License | 5 votes |
generate(length = null) {
if (length) {
return nanoid(length);
}
return nanoid();
}
Example #16
Source File: commentsScripts.js From zubhub with GNU Affero General Public License v3.0 | 5 votes |
addComment = (
props,
comment_text_el,
parent_id,
context,
handleSetState,
) => {
if (!props.auth.token) {
props.history.push('/login');
} else {
const comment_text = comment_text_el.current.value;
comment_text_el.current.value = '';
const comment = {
id: nanoid(),
creator: {
username: props.auth.username,
avatar: props.auth.avatar,
},
text: comment_text,
parent_id: parent_id ? parent_id : null,
created_on: new Date().toISOString(),
replies: [],
};
parseComments([comment]);
parent_id
? tempAddComment(comment, context.body.comments, parent_id)
: context.body.comments.unshift(comment);
handleSetState({ [context.name]: context.body });
Promise.resolve(
props.addComment({
id: context.body.id,
token: props.auth.token,
parent_id: parent_id,
text: comment_text,
t: props.t,
}),
).then(obj => {
if (obj[context.name]) {
parseComments(obj[context.name].comments);
}
handleSetState(obj);
});
}
}
Example #17
Source File: snippets.js From tinkerun with MIT License | 5 votes |
newSnippet = snippet => ({
id: nanoid(),
code: '',
name: 'New Snippet',
...snippet,
})
Example #18
Source File: index.js From uid with MIT License | 5 votes |
size_16 = {
'hashids/fixed': new HashID('', 16),
'nanoid/non-secure': nanoid2.bind(nanoid2, 16),
'nanoid': nanoid.bind(nanoid, 16),
'uid/secure': secure.bind(secure, 16),
'uid/single': single.bind(single, 16),
'uid': uid.bind(uid, 16),
}
Example #19
Source File: CreateButton.jsx From tinkerun with MIT License | 5 votes |
CreateButton = () => {
const [, setLocation] = useLocation()
const createConnection = useUpdateAtom(createConnectionAtom)
const config = useAtomValue(configAtom)
const intl = useIntl()
useEffect(() => {
const listener = e => {
const tagName = e.target.tagName
const isInputField = tagName.isContentEditable ||
tagName === 'INPUT' ||
tagName === 'SELECT' ||
tagName === 'TEXTAREA'
if (
!isInputField &&
isMatchShortcut(e, config.shortcut_new_connection)
) {
handleClick()
return false
}
return true
}
document.addEventListener('keydown', listener, false)
return () => {
document.removeEventListener('keydown', listener, false)
}
}, [config.shortcut_new_connection])
const handleClick = () => {
const connection = {
id: nanoid(),
tag: 'local',
name: intl.formatMessage({id: 'connections.name_default'}),
is_over_ssh: false,
path: '',
command: '',
}
createConnection(connection)
setLocation(`/connections/${connection.id}`)
}
return (
<Tooltip
content={(
<FormattedMessage id='connections.create'/>
)}
>
<IconButton
icon={PlusIcon}
height={majorScale(3)}
onClick={handleClick}
appearance='minimal'
>
<FormattedMessage id='connections.create'/>
</IconButton>
</Tooltip>
)
}
Example #20
Source File: createProjectScripts.js From zubhub with GNU Affero General Public License v3.0 | 5 votes |
uploadImageToDO = (image, state, props, handleSetState) => {
return new Promise((resolve, reject) => {
const params = {
Bucket: `${doConfig.bucketName}`,
Key: `${doConfig.project_images}/${nanoid()}`,
Body: image,
ContentType: image.type,
ACL: 'public-read',
};
DO.upload(params, err => {
reject(err.message);
})
.on('httpUploadProgress', e => {
const progress = Math.round((e.loaded * 100.0) / e.total);
const { media_upload } = state;
const upload_info = JSON.parse(
JSON.stringify(media_upload.upload_info),
);
upload_info[image.name] = progress;
let total = 0;
Object.keys(upload_info).forEach(each => {
total = total + upload_info[each];
});
total = total / Object.keys(upload_info).length;
handleSetState({
media_upload: {
...media_upload,
upload_info,
upload_percent: total,
},
});
})
.send((err, data) => {
if (err) {
if (err.message.startsWith('Unexpected')) {
const error = props.t('createProject.errors.unexpected');
reject(error);
} else {
reject(err.message);
}
} else {
const secure_url = data.Location;
const public_id = data.Key;
resolve({ image_url: secure_url, public_id });
}
});
});
}
Example #21
Source File: index.js From uid with MIT License | 5 votes |
size_11 = {
'hashids/fixed': new HashID('', 11),
'nanoid/non-secure': nanoid2.bind(nanoid2, 11),
'nanoid': nanoid.bind(nanoid, 11),
'uid/secure': secure.bind(secure, 11),
'uid/single': single.bind(single, 11),
'uid': uid.bind(uid, 11),
}
Example #22
Source File: Qrcode.jsx From airdrop with MIT License | 5 votes |
function Qrcode({ user }) {
const [created, setCreated] = useState(false);
const [show, setShow] = useState(false);
const [id, setId] = useState('');
useEffect(() => {
const nId = nanoid();
setId(`${nId}`);
setCreated(true);
console.log(`${window.location.origin}/join/${nId}`);
// send that data to server
socket.emit('create qrcode', {
nId,
fromuID: user.uid,
});
}, [user.uid]);
const handleClick = (e) => {
const target = e.target.id;
if (
target === 'closeButtons' ||
target === 'generateURl' ||
target === 'popupmain' ||
target === 'generateURlWrapper' ||
target === 'generateURlspan'
) {
setShow(!show);
}
};
return !created ? (
<>
<Helmet>
<title>Relp / Connect with QRcode</title>
</Helmet>
<div className="w-auto h-auto flex items-center justify-center">
<Ring color="#00B2D2" />
</div>
</>
) : (
<div className="w-auto h-auto m-5 flex items-center justify-center flex-col">
<Helmet>
<title>Relp / Connect with QRcode</title>
</Helmet>
<QRCode
value={`${window.location.origin}/join/${id}`}
size={160}
fill="#F4F4F9"
/>
<h3 className="m-4 font-sans text-light text-md">
And Open the link in a browser
</h3>
<p className="text-light text-md font-semibold"> --OR-- </p>
<GenerateUrl onClicks={handleClick} show={show} />
<Popup onClicks={handleClick} show={show} />
</div>
);
}
Example #23
Source File: useUniqueIdentifier.js From rainbow-modules with MIT License | 5 votes |
export default function useUniqueIdentifier(prefix) {
return useMemo(() => {
return prefix ? `${prefix}-${nanoid(5)}` : nanoid(5);
}, [prefix]);
}
Example #24
Source File: useOpenVidu.jsx From airboardgame with MIT License | 5 votes |
defaultSetData = () => nanoid()
Example #25
Source File: useCubeStore.js From minecraft-react with MIT License | 5 votes |
useSetCube = () => {
const setCubes = useSetRecoilState($cubes);
return (x, y, z) =>
setCubes(cubes => [...cubes, <Cube key={nanoid()} position={[x, y, z]} />]);
}
Example #26
Source File: Peer.js From airdrop with MIT License | 5 votes |
SendFile = (FileList, url, shareID, channelID) => (dispatch, getState) => {
const { finalTo: to, uid } = getId(channelID, getState);
if (Peer === null) {
dispatch({ type: 'ERROR_WHILE_SENDING', payload: 'NOT_CONNECTED' });
return;
}
const messageId = nanoid(25);
const obj = {
messages: {
type: FileList.type,
name: FileList.name,
time: Date.now(),
url,
shareID,
from: uid,
messageId,
to,
},
channel: channelID,
};
dispatch({ type: 'ON_MESSAGE', payload: obj });
// Send meta data
Peer.Send({
type: 'text/relp',
payload: {
channel: obj.channel,
messages: {
url: 'placeholder',
type: FileList.type,
name: FileList.name,
size: FileList.size,
time: Date.now(),
shareID,
from: uid,
messageId,
to,
},
},
});
Peer.Send(false, FileList, shareID);
dispatch({ type: 'PROGRESS', payload: { sentBytes: 0, shareID } });
Peer.on('send progress', (data) => {
dispatch({ type: 'PROGRESS', payload: { sentBytes: data, shareID } });
});
}
Example #27
Source File: unpublishedGame.js From airboardgame with MIT License | 5 votes |
genGame = () => {
const items = [...Array(2000)].map((e, index) => ({
type: "rect",
x: 10 + index,
y: 10 + index,
width: 100,
height: 100,
id: nanoid(),
}));
return {
items,
availableItems: [
{
groupId: "Group",
label: "Rect",
type: "rect",
color: "#00D022",
width: 80,
height: 80,
},
],
board: {
size: 4000,
scale: 0.5,
name: "Unpublished Game",
published: false,
keepTitle: true,
translations: [
{
language: "fr",
name: "2 Jeu non publié",
description: "Un jeu non publié pour tester",
},
],
playerCount: [1, 9],
defaultName: "2 Unpublished Game",
defaultLanguage: "en",
defaultDescription: "A non published game",
materialLanguage: "Multi-lang",
minAge: "10",
duration: [30, 90],
imageUrl: "/game_assets/default.png",
gridSize: 1,
},
id: "unpublished",
};
}
Example #28
Source File: Login.js From neighborhood-chef-fe with MIT License | 5 votes |
Login = () => {
const cardClass = cardStyles();
const buttonClass = buttonStyles();
const handleClick = (e) => {
e.preventDefault();
ls.set("code_verifier", nanoid(43));
const hash = crypto
.createHash("sha256")
.update(ls.get("code_verifier"))
.digest("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
const query = {
client_id: "0oa9qxckmhGd2aLsZ4x6",
response_type: "code",
scope: "openid",
redirect_uri: `${process.env.REACT_APP_FRONT_END_BASE_URL}/login-redirect-url`,
state: "state-bsaWCD8F0dkd85REyU87",
code_challenge_method: "S256",
code_challenge: hash,
};
const redirectURL = `https://dev-599411.okta.com/oauth2/default/v1/authorize?${qs.stringify(
query
)}`;
window.location.replace(`${redirectURL}`);
};
return (
<>
<AuthHeader />
<div className="landing-page-container">
<div className="landing-page-left">
<Card className={`${cardClass.root} ${cardClass.landingPage}`}>
<CardContent style={{ marginTop: "2%" }}>
<Typography variant="h3">Login to Neighborhood Chef</Typography>
<Typography style={{ marginTop: "20px" }} variant="caption">
<span style={{ opacity: ".6" }}>Choose to eat comfortably</span>
</Typography>
<div
style={{ marginTop: "10%" }}
className={`${buttonClass.root} ${buttonClass.single}`}
onClick={handleClick}
>
<Typography variant="h5">Login Securely with Okta</Typography>
</div>
</CardContent>
</Card>
</div>
<div className="landing-page-right" style={{ overflow: "hidden" }}>
<img src={food} alt="food community" height="100%" />
</div>
</div>
</>
);
}
Example #29
Source File: perfGame.js From airboardgame with MIT License | 5 votes |
genGame = () => {
const items = [...Array(2000)].map((e, index) => ({
type: "rect",
x: 10 + index,
y: 10 + index,
width: 100,
height: 100,
id: nanoid(),
}));
return {
items,
availableItems: [
{
groupId: "Group",
label: "Rect",
type: "rect",
color: "#00D022",
width: 80,
height: 80,
},
],
board: {
size: 4000,
scale: 0.5,
name: "Perf Game",
published: true,
keepTitle: true,
translations: [
{
language: "fr",
name: "1 Jeu test de performances et des extrêmes",
baseline:
"Un jeu pour tester les performances mais également les limites des différentes saisies. Le texte est tellement long qu'il doit être caché au final.",
},
],
playerCount: [1, 9],
defaultName: "1 Performance game to test strange things and other",
defaultLanguage: "en",
defaultBaseline:
"A very long baseline to show how it can going is someone wants to write a book.",
materialLanguage: "Multi-lang",
minAge: "10",
duration: [30, 90],
imageUrl: "/game_assets/default.png",
gridSize: 1,
},
id: "perf",
};
}