nanoid#nanoid TypeScript 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: Door.ts    From ble with Apache License 2.0 6 votes vote down vote up
Door = types.model({
	id: types.optional(types.identifier, nanoid),
	type: types.literal('endpoint'),
	params: DoorParams,
}).actions((self) => ({
	remove(): void {
		const parent = (getParent(self, 2) as ILevel);
		parent.removeEntity(self as IDoor);
	},
})).views(() => ({
	get displayName(): string {
		return 'Door';
	},
}))
Example #2
Source File: SidebarItem.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
export default function SidebarItem({ label, idx }: Props) {
  const onDragStart = (event: React.DragEvent<HTMLDivElement>) => {
    const id = nanoid()
    const dataString = JSON.stringify({ id, label })
    event.dataTransfer.setData("application/reactflow", dataString)
    event.dataTransfer.effectAllowed = "move"
  }

  const ref: React.RefObject<HTMLInputElement> = React.createRef()
  return (
    <div
      data-name={`SideBarItem-${idx}`}
      ref={ref}
      className="mb-3 draggable-container"
      draggable={true}
      onDragStart={onDragStart}
    >
      <ChartNode label={label} />
    </div>
  )
}
Example #3
Source File: command.base.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
constructor(props: CommandProps<unknown>) {
    if (Guard.isEmpty(props)) {
      throw new ArgumentNotProvidedException(
        'Command props should not be empty',
      );
    }
    this.correlationId = props.correlationId || nanoid(8);
    this.id = props.id || UUID.generate().unpack();
  }
Example #4
Source File: snapshot.ts    From ble with Apache License 2.0 6 votes vote down vote up
export function levelPreProcessor(snapshot: SerializedLevel): SnapshotInBaseLevel {
	const entities = snapshot.entities.map((entity) => ({
		...entity,
		type: entity.type as BlockType,
		id: nanoid(),
	}));

	return {
		...snapshot,
		timings: snapshot.timings || [0, 0],
		entities,
	};
}
Example #5
Source File: NekotonController.ts    From ever-wallet-browser-extension with GNU General Public License v3.0 6 votes vote down vote up
private _addConnection(
        origin: string,
        tabId: number | undefined,
        { engine }: AddConnectionOptions
    ) {
        if (origin === 'nekoton') {
            return null
        }

        const id = nanoid()
        this._connections[id] = {
            engine,
        }

        let originIds = this._originToConnectionIds[origin]
        if (originIds == null) {
            originIds = new Set()
            this._originToConnectionIds[origin] = originIds
        }
        originIds.add(id)

        if (tabId != null) {
            let tabIds = this._tabToConnectionIds[tabId]
            if (tabIds == null) {
                tabIds = new Set()
                this._tabToConnectionIds[tabId] = tabIds
            }
            tabIds.add(id)

            let originTabs = this._originToTabIds[origin]
            if (originTabs == null) {
                originTabs = new Set()
                this._originToTabIds[origin] = originTabs
            }
            originTabs.add(tabId)
        }

        return id
    }
Example #6
Source File: global.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
export async function runPythonAsync(code: string, runtime: Runtime) {
  if (!pyodideLoadSingleton) return;

  if (getPluginOpts().runInMainThread) {
    if (mainThreadPyodideRunner) {
      const result = await mainThreadPyodideRunner.runCode(code);
      return await convertResult(result, runtime);
    } else {
      console.error("Missing main thread pyodide");
      return null;
    }
  } else {
    const kernelId = await pyodideLoadSingleton;
    const id = nanoid();
    return new Promise((resolve, reject) => {
      runningCode.set(id, (result) => {
        convertResult(result, runtime).then((v) => resolve(v));
        runningCode.delete(id);
      });

      try {
        kernelManager.postMessage({
          type: "run",
          kernelId: kernelId,
          id: id,
          code: code,
        } as KernelManagerMessage);
      } catch (e) {
        console.warn(e, code);
        reject(e);
        runningCode.delete(id);
      }
    });
  }
}
Example #7
Source File: Block.ts    From ble with Apache License 2.0 6 votes vote down vote up
Block = types.model({
	id: types.optional(types.identifier, nanoid),
	type: types.enumeration(Object.values(BlockType)),
	params: types.compose(
		StaticParams,
		VerticesParams,
	),
}).views((self) => ({
	get displayName(): string {
		return `${blockAliases[self.type]} polygon`;
	},
})).actions((self) => ({
	remove(): void {
		const parent = (getParent(self, 2) as ILevel);
		parent.removeEntity(self as IBlock);
	},
}))
Example #8
Source File: StreamProvider.ts    From ever-wallet-browser-extension with GNU General Public License v3.0 6 votes vote down vote up
sendAsync(
        payload: JsonRpcRequest<unknown>,
        callback: (error: Error | null, response: unknown) => void
    ) {
        const originalId = payload.id
        const id = nanoid()
        payload.id = id
        this._payloads[id] = [callback, originalId]
        this.push(payload)
    }
Example #9
Source File: useTestimonyAttachment.ts    From advocacy-maps with MIT License 6 votes vote down vote up
function useUpload(
  { uid }: State,
  dispatch: Dispatch<Action>,
  setTestimony: SetTestimony
) {
  return useCallback(
    async (file: File) => {
      const id = nanoid()
      const uploadTask = uploadBytesResumable(draftAttachment(uid, id), file, {
        contentDisposition: 'inline; filename="Testimony.pdf"',
        contentType: file.type,
        cacheControl: "private, max-age=3600",
        customMetadata: {
          originalFilename: file.name
        }
      })

      dispatch({ type: "loading" })
      uploadTask.on(
        "state_changed",
        () => {},
        error => {
          dispatch({ type: "error", error })
        },
        () => {
          resolveAttachment(uploadTask.snapshot.ref, dispatch, setTestimony)
        }
      )
    },
    [dispatch, setTestimony, uid]
  )
}
Example #10
Source File: blob.ts    From excalidraw with MIT License 6 votes vote down vote up
generateIdFromFile = async (file: File): Promise<FileId> => {
  try {
    const hashBuffer = await window.crypto.subtle.digest(
      "SHA-1",
      await blobToArrayBuffer(file),
    );
    return bytesToHexString(new Uint8Array(hashBuffer)) as FileId;
  } catch (error: any) {
    console.error(error);
    // length 40 to align with the HEX length of SHA-1 (which is 160 bit)
    return nanoid(40) as FileId;
  }
}
Example #11
Source File: helpers.ts    From backendless-ecommerce-platform with MIT License 6 votes vote down vote up
addListenerToInstances = (buyNowInstances: HTMLCollectionOf<HTMLDivElement>) => {
  try {
    for (let index = 0; index < buyNowInstances.length; index++) {
      const currentInstance = buyNowInstances[index];
      if (currentInstance?.id) return;

      if (currentInstance.dataset?.dolaCartaction === 'true') {
        currentInstance.id = nanoid();
        currentInstance.addEventListener('click', () => {
          return attachDolaToCart(currentInstance.dataset, buyNowInstances);
        });
      } else if (currentInstance.dataset?.dolaBuynow === 'true') {
        currentInstance.id = nanoid();
        currentInstance.addEventListener('click', () => {
          return attachDolaToOne(currentInstance.dataset);
        });
      }

      currentInstance.classList.remove('dola-bep-loading');
    }
  } catch (error) {
    throw new Error('error attaching dola action to instance');
  }
}
Example #12
Source File: createDebugSessions.ts    From web with MIT License 6 votes vote down vote up
export function createDebugSessions(sessions: TestSession[]): DebugTestSession[] {
  const debugSessions = [];

  for (const session of sessions) {
    const debugSession: DebugTestSession = {
      ...session,
      id: nanoid(),
      debug: true,
    };

    debugSessions.push(debugSession);
  }

  return debugSessions;
}
Example #13
Source File: namespace.ts    From one-platform with MIT License 6 votes vote down vote up
NamespaceSchema: Schema = new Schema(
  {
    name: {
      type: String,
      unique: true,
    },
    description: {
      type: String,
    },
    slug: {
      type: String,
      unique: true,
      default: () => nanoid(6),
    },
    tags: [String],
    owners: [
      {
        mid: {
          type: String,
        },
        group: {
          type: String,
          enum: ['MAILING_LIST', 'USER'],
        },
      },
    ],
    schemas: [SpecSheetSchema],
    createdBy: {
      type: String,
    },
    updatedBy: {
      type: String,
    },
  },
  { timestamps: { createdAt: 'createdOn', updatedAt: 'updatedOn' } },
)
Example #14
Source File: misc.ts    From keycaplendar with MIT License 6 votes vote down vote up
generateAliases = functions.https.onCall((data, context) => {
  return admin
    .firestore()
    .collection("keysets")
    .get()
    .then((querySnapshot) => {
      const promises: Promise<any>[] = [];
      querySnapshot.forEach((doc) => {
        if (doc.data().alias) {
          promises.push(Promise.resolve());
        } else {
          const setPromise = admin
            .firestore()
            .collection("keysets")
            .doc(doc.id)
            .set({ alias: nanoid(10) }, { merge: true });
          setPromise
            .then(() => {
              return console.log("Generated alias for id:" + doc.id);
            })
            .catch((error) => {
              console.log("Failed to generate alias:" + error);
            });
          promises.push(setPromise);
        }
      });
      return Promise.all(promises);
    })
    .catch((error) => {
      console.log("Failed to generate alias:" + error);
    });
})
Example #15
Source File: index.tsx    From tanfu.js with MIT License 6 votes vote down vote up
createRenderView(view: any, props: any, type: number, engine?: CoreEngine) {
        const tId = props?.['t-id']
        let RenderUI = view;
        const reactProps: any = {}
        Object.keys(props ?? {}).forEach(key => {
            if(key === 'class'){
                reactProps['className'] = props['class']
            }
            else reactProps[formatToHump(key)] = props?.[key]
        })
        if (Tanfu.isTanfuView(view)) {
            const { view: ui, engine: tanfuEngine } = Tanfu.translateTanfuView(view, props)
            RenderUI = React.memo(function (props: any) {
                return <ReactView props={props} engine={tanfuEngine} children={ui} />
            })
            if(tId) RenderUI = createElement(RenderUI, engine)
            return <RenderUI key={nanoid()} {...reactProps} />
        }
        if (type === Node.TEXT_NODE) {
            return view
        } else if (type === Node.ELEMENT_NODE && view) {
            if (tId) RenderUI = createElement(view, engine)
            return <RenderUI key={nanoid()} {...reactProps} />
        }
        return <React.Fragment key={nanoid()}></React.Fragment>;
    }
Example #16
Source File: background.ts    From TabMerger with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sets the first group with corresponding data.
 * Additionally, sets the active group information
 */
export function setDefaultData(): void {
  // Get all the user's current open windows into the Now Open group
  chrome.windows.getAll(WINDOW_QUERY_OPTIONS, (windows) => {
    const activeId = nanoid(10);
    const active = { id: activeId, index: 0 };
    const { sortedWindows } = sortWindowsByFocus(windows);

    const available: IGroupItemState[] = [
      {
        name: FIRST_GROUP_TITLE,
        id: activeId,
        windows: sortedWindows,
        color: DEFAULT_GROUP_COLOR,
        updatedAt: Date.now(),
        permanent: true
      }
    ];

    chrome.storage.local.set({ active, available }, () => "");
  });
}
Example #17
Source File: utils.ts    From dashboard with Apache License 2.0 6 votes vote down vote up
parseDocumentRequest = (
  request: string,
  exampleRequest: string
) => {
  let text = ""
  const uris: string[] = []
  const rows: string[] = []
  const keys: { [key: string]: string } = {}
  const values: { [key: string]: string } = {}
  const placeholders: { [key: string]: string } = {}

  try {
    const parsed = JSON.parse(request)
    const parsedExample = JSON.parse(exampleRequest)

    if (parsed?.data)
      parsed.data.forEach((item: any) => {
        if (item.text) text += item.text + "\n"
        if (item.uri) uris.push(item.uri)
      })

    Object.entries(parsedExample).forEach(([key, value]) => {
      if (key === "data") return
      const id = nanoid()

      rows.push(id)
      keys[id] = key

      let formattedValue: any

      if (typeof value === "object" && value !== null) {
        formattedValue = JSON.stringify(value as any)
      } else formattedValue = value

      placeholders[id] = formattedValue
    })

    Object.entries(parsed).forEach(([key, value]) => {
      if (key === "data") return

      let id: any

      Object.entries(keys).forEach(([k, v]) => {
        if (v === key) {
          id = k
        }
      })

      if (!id) {
        id = nanoid()
        rows.push(id)
        keys[id] = key
      }

      let formattedValue: any

      if (typeof value === "object" && value !== null) {
        formattedValue = JSON.stringify(value as any)
      } else formattedValue = value
      values[id] = formattedValue
    })
  } catch (e) {
    console.log("ERROR:", e)
  }
  return { text, uris, keys, values, rows, placeholders }
}
Example #18
Source File: useSyncStorage.ts    From TabMerger with GNU General Public License v3.0 6 votes vote down vote up
export function useSyncStorageDownload(currentData: ISyncDataItem[], available: IGroupItemState[]) {
  const dispatch = useDispatch();

  const syncDownload = useCallback(() => {
    // Create groups that are properly formatted using the limited sync data
    const newAvailable = currentData.map((item) => {
      const group = createGroup(nanoid(10), item.name, item.color);
      item.windows.forEach((w) => {
        const tabs: chrome.tabs.Tab[] = [];

        w.tabs.forEach((t) => {
          tabs.push(createTabFromTitleAndUrl(t.title, t.url));
        });

        group.windows.push(createWindowWithTabs(tabs, w.name, w.incognito, w.starred));
      });

      return group;
    });

    dispatch(updateAvailable([available[0], ...newAvailable]));

    // Update local storage download sync timestamp
    chrome.storage.local.set({ lastSyncDownload: getReadableTimestamp() }, () => "");
  }, [dispatch, currentData, available]);

  return syncDownload;
}
Example #19
Source File: browserstackManager.ts    From web with MIT License 5 votes vote down vote up
localId = `web-test-runner-${nanoid()}`
Example #20
Source File: paper.ts    From netless-app with MIT License 5 votes vote down vote up
pointerDown = (ev: PointerEvent) => {
    if (ev.isPrimary) {
      this.currentPathUID = nanoid();
      this.onDraw(this.currentPathUID, pointFromEvent(ev, this.target), ev.timeStamp);
    }
  };
Example #21
Source File: random.ts    From excalidraw with MIT License 5 votes vote down vote up
randomId = () => (isTestEnv() ? `id${testIdBase++}` : nanoid())
Example #22
Source File: Hoppi.ts    From ble with Apache License 2.0 5 votes vote down vote up
Hoppi = types.model({
	id: types.optional(types.identifier, nanoid),
	type: types.literal('player'),
	params: types.union(
		{
			dispatcher: (snapshot) => {
				if(Object.prototype.hasOwnProperty.call(snapshot, 'infiniteAmmo')) return InfiniteParams;
				return FiniteParams;
			},
		},
		FiniteParams,
		InfiniteParams,
	),
}).actions((self) => ({
	makeFinite(): void {
		self.params = FiniteParams.create({
			...self.params,
			magazine: [
				AmmoType.grenade,
				AmmoType.empty,
				AmmoType.bullet,
				AmmoType.bullet,
			],
		});
	},
	makeInfinite(): void {
		self.params = InfiniteParams.create({
			...self.params,
			infiniteAmmo: AmmoType.bullet,
		});
	},
	remove(): void {
		const parent = (getParent(self, 2) as ILevel);
		parent.removeEntity(self as IHoppi);
	},
})).views((self) => ({
	get entityType(): 'finite' | 'infinite' {
		if (InfiniteParams.is(self.params)) {
			return 'infinite';
		}
		if (FiniteParams.is(self.params)) {
			return 'finite';
		}

		throw new Error('Invalid param type');
	},
	get displayName(): string {
		return 'Hoppi';
	},
}))
Example #23
Source File: __helpers.ts    From tutorial with MIT License 5 votes vote down vote up
function prismaTestContext() {
  const prismaBinary = join(__dirname, '..', 'node_modules', '.bin', 'prisma')
  let schema = ''
  let databaseUrl = ''
  let prismaClient: null | PrismaClient = null

  return {
    async before() {
      // Generate a unique schema identifier for this test context
      schema = `test_${nanoid()}`
      // Generate the pg connection string for the test schema
      databaseUrl = `postgres://postgres:postgres@localhost:5432/testing?schema=${schema}`

      // Set the required environment variable to contain the connection string
      // to our database test schema
      process.env.DATABASE_URL = databaseUrl

      // Run the migrations to ensure our schema has the required structure
      execSync(`${prismaBinary} migrate up --create-db --experimental`, {
        env: {
          ...process.env,
          DATABASE_URL: databaseUrl,
        },
      })

      // Construct a new Prisma Client connected to the generated Postgres schema
      prismaClient = new PrismaClient()

      return prismaClient
    },
    async after() {
      // Drop the schema after the tests have completed
      const client = new Client({
        connectionString: databaseUrl,
      })
      await client.connect()
      await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)
      await client.end()

      // Release the Prisma Client connection
      await prismaClient?.$disconnect()
    },
  }
}
Example #24
Source File: withApollo.tsx    From NextJS-NestJS-GraphQL-Starter with MIT License 5 votes vote down vote up
withApolloWithSubscriptions = nextWithApollo(
  ({ initialState, headers, ...rest }) => {
    const clientId = nanoid();

    const wsLink = !IS_SERVER
      ? new WebSocketLink({
          uri: WEBSOCKET_API_URL,
          options: {
            reconnect: true,
            connectionParams: {
              clientId
            }
          }
        })
      : null;

    const httpLink = new HttpLink({
      uri: IS_SERVER ? SERVER_API_ENDPOINT : BROWSER_API_ENDPOINT,
      headers: {
        ...headers
      },
      credentials: 'include'
    });

    /*
     * Only create a split link on the browser
     * The server can not use websockets and is therefore
     * always a http link
     */
    const splitLink = !IS_SERVER
      ? split(
          ({ query }) => {
            const definition = getMainDefinition(query);
            return (
              definition.kind === 'OperationDefinition' &&
              definition.operation === 'subscription'
            );
          },
          wsLink,
          httpLink
        )
      : httpLink;

    return new ApolloClient({
      ssrMode: IS_SERVER,
      link: splitLink,
      cache: new InMemoryCache().restore(initialState || {}),
      // A hack to get ctx oin the page's props on the initial render
      // @ts-ignore
      defaultOptions: { ...rest, clientId }
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page
            {...props}
            {...props.apollo.defaultOptions.ctx}
            clientId={props.apollo.defaultOptions.clientId}
          />
        </ApolloProvider>
      );
    }
  }
)
Example #25
Source File: object-proxy.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
/** Creates a valid, random id for a given object */
  private getId(value: any) {
    return nanoid() + "-" + (typeof value === "function" ? "f" : "o");
  }
Example #26
Source File: ExportToExcalidrawPlus.tsx    From excalidraw with MIT License 5 votes vote down vote up
exportToExcalidrawPlus = async (
  elements: readonly NonDeletedExcalidrawElement[],
  appState: AppState,
  files: BinaryFiles,
) => {
  const firebase = await loadFirebaseStorage();

  const id = `${nanoid(12)}`;

  const encryptionKey = (await generateEncryptionKey())!;
  const encryptedData = await encryptData(
    encryptionKey,
    serializeAsJSON(elements, appState, files, "database"),
  );

  const blob = new Blob(
    [encryptedData.iv, new Uint8Array(encryptedData.encryptedBuffer)],
    {
      type: MIME_TYPES.binary,
    },
  );

  await firebase
    .storage()
    .ref(`/migrations/scenes/${id}`)
    .put(blob, {
      customMetadata: {
        data: JSON.stringify({ version: 2, name: appState.name }),
        created: Date.now().toString(),
      },
    });

  const filesMap = new Map<FileId, BinaryFileData>();
  for (const element of elements) {
    if (isInitializedImageElement(element) && files[element.fileId]) {
      filesMap.set(element.fileId, files[element.fileId]);
    }
  }

  if (filesMap.size) {
    const filesToUpload = await encodeFilesForUpload({
      files: filesMap,
      encryptionKey,
      maxBytes: FILE_UPLOAD_MAX_BYTES,
    });

    await saveFilesToFirebase({
      prefix: `/migrations/files/scenes/${id}`,
      files: filesToUpload,
    });
  }

  window.open(
    `https://plus.excalidraw.com/import?excalidraw=${id},${encryptionKey}`,
  );
}
Example #27
Source File: paper.ts    From netless-app with MIT License 5 votes vote down vote up
export function simulateDrawing(paper: Paper, curves: CurveShape[]): void {
  curves = curves.map(curve => curve.map(point => ({ ...point }))) as CurveShape[];
  const id = nanoid();
  tasks.set(id, points => startDrawing(paper, points));
  bezierQ.postMessage({ id, curves, step: DrawingStep });
}
Example #28
Source File: canvasSlideRenderer.ts    From excalideck with MIT License 5 votes vote down vote up
canvasSlideRenderer: SlideRenderer<HTMLCanvasElement> = {
    renderSlide: lruMemoize(
        (deck: Deck, slideId: string): HTMLCanvasElement => {
            const slide = DeckOperations.getSlide(deck, slideId);
            const { printableArea } = deck;
            const containingPerimeter = makeContainingPerimeter(printableArea);
            const excalidrawElements = [
                ...slide.excalidrawElements,
                ...(slide.shouldRenderWithCommonExcalidrawElements
                    ? deck.commonExcalidrawElements
                    : []),
                containingPerimeter,
            ];

            const drawingBoardCanvas = exportToCanvas({
                elements: excalidrawElements as any,
            });

            const slideCanvas = cropCanvas(
                drawingBoardCanvas,
                EXCALIDRAW_EXPORT_DEFAULT_PADDING - FAR_POINT.x,
                EXCALIDRAW_EXPORT_DEFAULT_PADDING - FAR_POINT.y,
                printableArea.width,
                printableArea.height
            );
            slideCanvas.attributes.setNamedItem;
            // Assign a random id so tests can distinguish between canvases
            slideCanvas.setAttribute("data-testid", nanoid());

            return slideCanvas;
        },
        {
            maxSize: 100,
            getCacheKey: (deck, slideId) =>
                Hash.excalidrawElements(deck.commonExcalidrawElements) +
                Hash.printableArea(deck.printableArea) +
                Hash.slide(DeckOperations.getSlide(deck, slideId)),
        }
    ),
}
Example #29
Source File: passport.ts    From hakka with MIT License 5 votes vote down vote up
async function getUserByProviderProfile(profile: Profile, provider: 'github') {
  let email = profile.emails && profile.emails[0].value
  const avatar = profile.photos && profile.photos[0].value

  if (!email) {
    email = `${provider}_${profile.id}@placeholder.tld`
  }

  const providerKey = `${provider}UserId`

  // Find one by provider user id
  let existing = await prisma.user.findUnique({
    where: {
      [providerKey]: profile.id,
    },
  })
  // Otherwise find one with the same email and link them
  if (!existing) {
    existing = await prisma.user.findUnique({
      where: {
        email,
      },
    })
    if (existing) {
      await prisma.user.update({
        where: {
          id: existing.id,
        },
        data: {
          [providerKey]: profile.id,
        },
      })
    }
  }

  if (!existing) {
    existing = await prisma.user.create({
      data: {
        email,
        username: profile.username || `user_${nanoid(5)}`,
        [providerKey]: profile.id,
        avatar,
      },
    })
  }

  if (avatar && existing.avatar !== avatar) {
    await prisma.user.update({
      where: {
        id: existing.id,
      },
      data: {
        avatar,
      },
    })
  }

  return existing
}