Socket
Socket
Sign inDemoInstall

webdev-essentials

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

webdev-essentials - npm Package Compare versions

Comparing version 1.1.0 to 1.2.0

development/README.md

7

dist/hooks/useBreakPoint.jsx
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var useWindowResize_1 = __importDefault(require("./useWindowResize"));
var useWindowResize_1 = require("./useWindowResize");
var Breakpoint;

@@ -14,3 +11,3 @@ (function (Breakpoint) {

function useBreakPoint(limit, start, end) {
var windowWidth = (0, useWindowResize_1.default)().width;
var windowWidth = (0, useWindowResize_1.useWindowResize)().width;
if (limit === 'only') {

@@ -17,0 +14,0 @@ return windowWidth === Breakpoint[start];

@@ -1,9 +0,17 @@

/**
* Listens for `resize`-event of the window and returns window.innerWidth.
* Note: every width-change is a state-change and hence a re-render!
* @returns current window width and height
*/
export default function useWindowSize(): {
declare type Props = {
selector?: string;
};
declare type Dimensions = {
width: number;
height: number;
};
/**
* Subscribes to `window.onresize`-event and notifies about dimension-changes.
* @param {string} [selector] - An optional CSS-Selector
* @returns {Dimensions} either current innerWidth and innerHeight of window or the clientWidth and clientHeight of the element specified by selector every time a window-resize-event happens.
*
* @example
* const { width, height } = useWindowResize({ selector: "#root main > article[tabIndex='-1']" })
*/
export declare function useWindowResize(options?: Props): Dimensions;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useWindowResize = void 0;
var react_1 = require("react");
/**
* Listens for `resize`-event of the window and returns window.innerWidth.
* Note: every width-change is a state-change and hence a re-render!
* @returns current window width and height
* Subscribes to `window.onresize`-event and notifies about dimension-changes.
* @param {string} [selector] - An optional CSS-Selector
* @returns {Dimensions} either current innerWidth and innerHeight of window or the clientWidth and clientHeight of the element specified by selector every time a window-resize-event happens.
*
* @example
* const { width, height } = useWindowResize({ selector: "#root main > article[tabIndex='-1']" })
*/
function useWindowSize() {
function useWindowResize(options) {
if (options === void 0) { options = { selector: '' }; }
var selector = options.selector;
var _a = (0, react_1.useState)({
width: 0,
height: 0,
}), windowSize = _a[0], setWindowSize = _a[1];
}), dimensions = _a[0], setDimensions = _a[1];
(0, react_1.useEffect)(function () {
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
function updateDimensions() {
var element;
if (selector) {
element = document.querySelector(selector);
}
setDimensions({
width: (element === null || element === void 0 ? void 0 : element.clientWidth) || window.innerWidth,
height: (element === null || element === void 0 ? void 0 : element.clientHeight) || window.innerHeight,
});
}
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return function () { return window.removeEventListener('resize', handleResize); };
}, []);
return windowSize;
window.addEventListener('resize', updateDimensions);
updateDimensions();
return function () { return window.removeEventListener('resize', updateDimensions); };
}, [selector]);
return dimensions;
}
exports.default = useWindowSize;
exports.useWindowResize = useWindowResize;

@@ -1,9 +0,22 @@

interface Options {
timeout?: number;
interface FetchOptions {
[rest: string]: any;
}
export default function fetchWithTimeout(url: string, options?: Options): Promise<{
interface Params {
url: string;
timeout?: number;
options?: FetchOptions;
}
/**
* Wraps the standard fetch-method and cancels the request after a timeout.
* Default timeout is set to 8000 milliseconds.
*
* @param {string} [required] url the fetch-url
* @param {number} [optional] timeout the timeout in milliseconds
* @param {FetchOptions} [optional = 8000] options the fetch options
* @returns the `fetch`-Response or status: 529 with statusText: 'A Timeout Occurred'.
*/
export default function fetchWithTimeout({ url, timeout, options, }: Params): Promise<{
status: number;
statusText: string;
}>;
} | Response>;
export {};

@@ -50,11 +50,23 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function fetchWithTimeout(url, options) {
/**
* Wraps the standard fetch-method and cancels the request after a timeout.
* Default timeout is set to 8000 milliseconds.
*
* @param {string} [required] url the fetch-url
* @param {number} [optional] timeout the timeout in milliseconds
* @param {FetchOptions} [optional = 8000] options the fetch options
* @returns the `fetch`-Response or status: 529 with statusText: 'A Timeout Occurred'.
*/
function fetchWithTimeout(_a) {
var url = _a.url, _b = _a.timeout, timeout = _b === void 0 ? 8000 : _b, options = _a.options;
return __awaiter(this, void 0, void 0, function () {
var timeout, controller, response, id, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
var controller, response, id, err_1;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
timeout = options ? options.timeout : 8000;
controller = new AbortController();
response = { status: 0, statusText: '' };
response = {
status: 500,
statusText: 'Internal Server Error',
};
id = setTimeout(function () {

@@ -67,16 +79,16 @@ controller.abort();

}, timeout);
_a.label = 1;
_c.label = 1;
case 1:
_a.trys.push([1, 3, 4, 5]);
_c.trys.push([1, 3, 4, 5]);
return [4 /*yield*/, fetch(url, __assign(__assign({}, options), { signal: controller.signal }))];
case 2:
response = _a.sent();
response = _c.sent();
return [3 /*break*/, 5];
case 3:
err_1 = _a.sent();
err_1 = _c.sent();
return [3 /*break*/, 5];
case 4:
clearTimeout(id);
return [2 /*return*/, response];
case 5: return [2 /*return*/];
return [7 /*endfinally*/];
case 5: return [2 /*return*/, response];
}

@@ -83,0 +95,0 @@ });

{
"name": "webdev-essentials",
"version": "1.1.0",
"description": "A collection of code-snippets and useful info essential for web development.",
"version": "1.2.0",
"description": "A collection of useful hooks and utils for web development.",
"scripts": {

@@ -20,6 +20,9 @@ "build": "tsc",

"main": "dist/index.js",
"types": "index.d.ts",
"types": "dist/index.d.ts",
"dependencies": {
"react": "^17.0.2"
},
"publishConfig": {
"access": "public"
}
}
# Description
A collection of code-snippets and useful info essential for web development.
A collection of useful hooks and utils for web development.
## Development and testing locally a `npm`-module
- We first need to create a symbolic link in the global `node_modules` folder (the folder where packages are added with `npm install -g <package>`)
- To find out the currently configured globale `node_modules` folder, run: `npm prefix -g`
- Packages are installed at `<prefix>/lib/node_modules`, e.g. `/opt/homebrew/lib/node_modules`
- To create a symlink to your new module under development, run following command from inside the module's root folder: `npm link`
- Check if the symlink has been created: `ll /opt/homebrew/lib/node_modules`
- output should at least contain the new symlink: `webdev-essentials -> ../../../../Users/hans/git/webdev-essentials`
- To use this module in another project, navigate to the other project's root and run: `npm link webdev-essentials`
- this should update dependencies in `package.json` and use the locale version of the module (instead of the npm-hosted package, even if there is)
- import it as usual, e.g.: `import * from 'webdev-essentials'`
- To kill the link, go back to your local version and at root type `npm unlink --no-save webdev-essentials`. Then run `npm install`
### Troubleshooting
If `npm link webdev-essentials` does not work, you can install it by running: `npm install ../../webdev-essentials`.
### Comparison
| Command | Dependency in package.json |
| ----------------------------------- | --------------------------------------------------- |
| npm install ../../webdev-essentials | "webdev-essentials": "file:../../webdev-essentials" |
| npm link webdev-essentials | "webdev-essentials": "^1.0.0" |
[Reference](https://benjaminwfox.com/blog/tech/why-isnt-npm-link-working)
## Publishing a TypeScript package to NPM
- init new `npm`-package: `npm init -y`
- install TypeScript-compiler: `npm i typescript --save-dev`
- init TypeScript: `npx tsc --init`
- add two scripts to `package.json`:
- the `build`-script compiles all the files, whereas the `build:check` command only checks compileability without actually compiling and creating the js-files.
```json
"scripts": {
"build": "tsc",
"build:check": "tsc --noEmit"
},
```
- Add `"declaration": true` to the `compilerOptions` of your `tsconfig.json`. This tells TypeScript to emit an `.d.ts` definitions file along with your compiled JavaScript.
- Add `"types": "index.d.ts"` to your `package.json`. When other people import your library, this tells the TypeScript compiler where to look for your library’s types. The filename of your `.d.ts` file will be the same as your main entry point. So, for example in your `package.json` you’ll want to have something like this in there:
- Add
```json
"main": "dist/index.js",
"types": "index.d.ts"
```
- Set `outDir` in `tsconfig.jsin` to `"outDir": "./dist"`. This specifies an output folder for all emitted files.
- `.gitignore` and `.npmignore`
- We don’t want to track compiled JavaScript files in our git repository, so add `dist` to the `.gitignore` file.
- We do, however, want them sent to NPM when we publish, so create an empty `.npmignore` file (maybe add `/node_modules` there, or simply make it a copy of your `.gitignore` file just without the ignore for the `dist` folder).
- If you don’t have an `.npmignore`, NPM will automatically exclude gitignored files from being published. Having an npmignore file overwrites this behavior.
- Add `"exclude"` object, if you want to exclude folders from the compilation process:
```json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es2017", "es7", "es6", "dom"],
"declaration": true,
"outDir": "dist",
"strict": true,
"esModuleInterop": true
},
"exclude": ["node_modules", "dist", "utils/userLanguage.ts"]
}
```
- To locally generate a tarball of everything that will get sent to and published on NPM to really verify and make sure it matches your expectation: `npm pack`
- To locally test
- in you package root: `npm link`
- in other project: `npm link <yourpackagename>` and in code `import <yourpackagename>`
- to unlink from the other project: `npm unlink --no-save <yourpackagename>`
[Source: The 30-second guide to publishing a TypeScript package to NPM](https://cameronnokes.com/blog/the-30-second-guide-to-publishing-a-typescript-package-to-npm/)
## Rest in TypeScript
- Example-Interface-Definition:
```ts
interface Options {
timeout?: number;
[rest: string]: any;
}
```sh
├── hooks
│ ├── useAPIFetch.tsx
│ ├── useBreakPoint.tsx
│ └── useWindowResize.tsx
└── utils
├── fetchWithTimeout.ts
├── randomFromTo.ts
└── userLanguage.ts
```
- Here, `[rest:string]: any` defines an `index-structure` of `string`-`keys`
- all keys give access to any-type members
- access to members: options.foo, options.bar, ...
- With the `spread`-operator: `fetch(url, ...options);` or const `{ timeout, ...rest} = options;`
- On the contrary, `rest: any[];` defines an `array` named 'rest'
- access to members: `options.rest[0];` or `options.rest[1];`

@@ -15,3 +15,6 @@ {

"target": "es5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
"lib": [
"ES2017",
"dom"
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
"jsx": "preserve" /* Specify what JSX code is generated. */,

@@ -18,0 +21,0 @@ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */

@@ -1,12 +0,32 @@

interface Options {
timeout?: number;
interface FetchOptions {
[rest: string]: any;
}
export default async function fetchWithTimeout(url: string, options?: Options) {
const timeout = options ? options.timeout : 8000;
interface Params {
url: string;
timeout?: number;
options?: FetchOptions;
}
/**
* Wraps the standard fetch-method and cancels the request after a timeout.
* Default timeout is set to 8000 milliseconds.
*
* @param {string} [required] url the fetch-url
* @param {number} [optional] timeout the timeout in milliseconds
* @param {FetchOptions} [optional = 8000] options the fetch options
* @returns the `fetch`-Response or status: 529 with statusText: 'A Timeout Occurred'.
*/
export default async function fetchWithTimeout({
url,
timeout = 8000,
options,
}: Params) {
const controller = new AbortController();
// .abort() cancels the request
let response = { status: 0, statusText: '' };
let response: { status: number; statusText: string } | Response = {
status: 500,
statusText: 'Internal Server Error',
};
const id = setTimeout(() => {

@@ -28,4 +48,4 @@ controller.abort();

clearTimeout(id);
return response;
}
return response;
}

@@ -1,10 +0,14 @@

import { Languages } from '../types';
export enum SupportedLanguages {
de = 'de',
en = 'en',
fr = 'fr',
}
export default function userLanguage(): keyof typeof Languages {
export default function userLanguage<L>(): keyof typeof SupportedLanguages {
const browserLng = navigator.language.substr(0, 2);
if (Object.values(Languages).includes(browserLng as any)) {
return browserLng as keyof typeof Languages;
if (Object.values(SupportedLanguages).includes(browserLng as any)) {
return browserLng as keyof typeof SupportedLanguages;
} else {
return Languages.en;
return SupportedLanguages.en;
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc