Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@danielhaim/randomutil

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@danielhaim/randomutil

An NPM package for easily populating DOM elements with random data, perfect for testing and prototyping web interfaces. Supports various data types including text, images, avatars, and dates.

  • 1.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4
decreased by-60%
Maintainers
1
Weekly downloads
 
Created
Source

RandomUtil

npm version Downloads GitHub

Overview

The RandomUtil module, accessible as an NPM package in both amd and commonjs configurations, expedites the prototyping of web interfaces. It adeptly fills DOM elements with a variety of random content. The module's versatility extends to numerous data types, encompassing text (encompassing titles, tags, and excerpts), images, tailored dates, and SVG-crafted avatars.

CodePen Demo

API Documentation

To initiate, install RandomUtil using NPM:

npm i @danielhaim/randomutil

Module Example

import RandomUtil from "@danielhaim/randomutil";

const randomContentManager = new RandomUtil.RandomContentManager(1);
const randomUtilController = new RandomUtil.RandomUtilController();

// Content Generation
randomController.randomTag(randomContent.randomTags);
randomController.randomTitle(randomContent.randomTitles);
randomController.randomExcerpt(randomContent.randomExcerpts);

// Date & Time Generation
randomController.randomReadTime();
randomController.randomDate("Y/m/d");

const UNSPLASH_ACCESS_KEY = "YOUR_UNSPLASH_ACCESS_KEY"; 
// Register API: [Unsplash API](https://unsplash.com/documentation#getting-started)
// Alternatively, you can use the `.env` file.

const imageCount = document.querySelectorAll("[data-random='img']").length;

// Image Generation
randomUtilController.randomImages({
  count: imageCount,
  query: "nature",
  orientation: "portrait",
  accessKey: UNSPLASH_ACCESS_KEY
});

// Avatar Generation
randomUtilController.randomAvatar({ 
  options: { 
    variant: "default" // Options: ['pixel', 'abstract', 'smile']
  } 
});

Browser Example

<script src="./path/to/dist/randomutil.amd.js"></script>
<script>
const randomContent = new window.RandomUtil.RandomContentManager(1);
const randomController = new window.RandomUtil.RandomUtilController();
// ...
</script>

RandomContentManager()

  1. The RandomContentManager() manages content distribution from a set of five arrays, while RandomUtil.Controller() handles the distribution of this content. Each array focuses on distinct themes
    1. Array 1: Wildlife preservation and conservation content.
    2. Array 2: Global explorations and adventures.
    3. Array 3: Technology and innovation topics.
    4. Array 4: Fashion and beauty-related content.
    5. Array 5: Creative and advertising materials.
// Initialize a RandomContentManager for Array 3 (Technology and Innovation)
const randomContent = new RandomContentManager(3);

// Initialize RandomUtil.Controller for content distribution
const randomController = new RandomUtil.Controller();

// Generate and populate elements with content:
randomController.generateTag(randomContentManager.tags); // For `[data-random="tag"]` elements
randomController.generateTitle(randomContentManager.titles); // For `[data-random="title"]` elements
randomController.generateExcerpt(randomContentManager.excerpts); // For `[data-random="excerpt"]` elements

RandomUtil.Controller()

The RandomUtil.Controller() is in charge of content distribution and offers several methods to target specific DOM elements:

MethodTarget ElementOutput
randomTitles(titles)[data-random="title"]Randomly selects and populates title elements.
randomTags(tags)[data-random="tag"]Assigns random tags to elements.
randomExcerpts(excerpts)[data-random="excerpt"]Fills elements with random excerpts.
randomReadTime(text = 'min read')[data-random="read-time"]Generates read time content (e.g., "8 min read").
randomDate(format)[data-random="date"]Provides random dates in the specified format (default: M j, Y, e.g., Dec 21, 2019).
randomDate[data-random-date="l, F jS, Y"]Custom date format support (e.g., "Saturday, December 21st, 2019").
randomColors({ options })[data-random="color"]Adds custom CSS variables with hex, rgb.
randomImages({ count, query, orientation, accessKey })[data-random="img"]Fetches random images (requires Unsplash API Key).
randomImages({})[data-random-img="person, face"]Advanced image querying for specific elements.
randomAvatar({ avatarOptions })[data-random="avatar"]Provides random avatars with options like 'pixel', 'smile', or 'abstract'.
randomAvatar({ avatarOptions })[data-random-avatar="pixel"]More advanced avatar customization.
// Initialize a RandomContentManager for Array 1 (Wildlife preservation and conservation content)
const randomContent = new RandomContentManager(1);

// Initialize RandomUtil.Controller for content distribution
const randomController = new RandomUtil.Controller();
randomController.randomTag(randomContent.randomTags); // For `[data-random="tag"]` elements
randomController.randomTitle(randomContent.randomTitles); // For `[data-random="title"]` elements
randomController.randomExcerpt(randomContent.randomExcerpts); // For `[data-random="excerpt"]` elements
randomController.randomReadTime(); // For `[data-random="time"]` elements

randomController.randomDate("Y/m/d"); // For `[data-random="date"]` or `[data-random-date]` elements

// For `[data-random="img"]` and `[data-random-img]` elements
const randomImageCount = document.querySelectorAll("[data-random='img']").length;
randomController.randomImages({ 
    count: randomImageCount, // for caching the API
    query: "nature",
    orientation: "portrait",
    accessKey: UNSPLASH_ACCESS_KEY 
});

// For `[data-random="avatar"]` and `[data-random-avatar]` elements
randomController.randomAvatar({ 
    avatarOptions: { 
      colors: ["#FF5733", "#33FF57", "#5733FF"], // Optional color set
      variant: "default"
    }
});

randomColor({ options });

Dynamically apply a random color to elements specified by the [data-random="color"] attribute. It allows for selecting colors from a predefined palette or a custom set of colors, further offering the ability to customize the CSS variable names used for the RGB and hex color values.

const randomController = new RandomUtil.Controller();

// Default usage with predefined palette
randomController.randomColor();

// Using a custom set of colors
randomController.randomColor({
    customColors: [
        "#405de6",
        "#5851db",
        "#833ab4",
    ]
});

// Customizing the CSS variable names
randomController.randomColor({
    varName: 'primary', // Prefix for the CSS variables (--primary-rgb, --primary-hex)
    customColors: [
        "#405de6",
        "#5851db",
        "#833ab4",
        "#c13584"
    ]
});

randomDate()

The randomDate() method is designed to populate elements with [data-random="date"] and [data-random-date=""] attributes. Utilizing the [data-random-date] attribute, you gain access to more specific date formats, such as l, F jS, Y, which results in a formatted date like "Saturday, December 21st, 2019." This flexibility allows you to tailor the date presentation to your specific needs.

CategoryFormatDescriptionExample
Day of Month
dNumeric, with leading zeros01–3101–31
jNumeric, without leading zeros1–311–31
SThe English suffix for the day of the monthst, nd or th in the 1st, 2nd or 15thst, nd or th in the 1st, 2nd or 15th
Weekday
lFull name (lowercase ‘L’)Sunday – SaturdaySunday – Saturday
DThree letter nameMon – SunMon – Sun
Month
mNumeric, with leading zeros01–1201–12
nNumeric, without leading zeros1–121–12
FTextual fullJanuary – DecemberJanuary – December
MTextual three lettersJan – DecJan – Dec
Year
YNumeric, 4 digitsEg., 1999, 2003Eg., 1999, 2003
yNumeric, 2 digitsEg., 99, 03Eg., 99, 03
Time
aLowercaseam, pmam, pm
AUppercaseAM, PMAM, PM
gHour, 12-hour, without leading zeros1–121–12
hHour, 12-hour, with leading zeros01–1201–12
GHour, 24-hour, without leading zeros0-230-23
HHour, 24-hour, with leading zeros00-2300-23
iMinutes, with leading zeros00-5900-59
sSeconds, with leading zeros00-5900-59
TTimezone abbreviationEg., EST, MDT …Eg., EST, MDT …
Full Date/Time
cISO 86012004-02-12T15:19:21+00:002004-02-12T15:19:21+00:00
rRFC 2822Thu, 21 DecThu, 21 Dec
USeconds since the Unix Epoch (January 1 1970 00:00:00 GMT)15778368001577836800
M jS, YCustomDec 21st, 2019Dec 21st, 2019
l, F jS, YCustomSaturday, December 21st, 2019Saturday, December 21st, 2019
// Initialize RandomUtil.Controller for content distribution
const randomController = new RandomUtil.Controller();
randomController.randomDate("Y/m/d");
<!-- Input -->
<span data-random="date"></span>
<span data-random-date="M jS, Y"></span>

<!-- Output -->
<span>2019/01/21</span>
<span>Dec 21st, 2019</span>

randomImages()

This method allows you to fetch images from the Unsplash API. To get started, you can register an Unsplash Application and grab your access key here.

  1. The randomImages({ count, query, orientation, accessKey }) constructor:
  2. count (Optional): Number of images to fetch. Default is 12.
  3. query (Optional): The category of images. Default is "nature".
  4. orientation (Optional): The orientation of the images. Default is "landscape".
  5. accessKey (Optional): Your Unsplash API key. If not provided, it will default to process.env.UNSPLASH_ACCESS_KEY.
const UNSPLASH_ACCESS_KEY = 'your-api-key';

const randomController = new RandomUtil.Controller();
const randomImageCount = document.querySelectorAll("[data-random='img']").length;

randomController.randomImages({ 
    count: randomImageCount, // for caching the API
    query: "nature",
    orientation: "portrait",
    accessKey: UNSPLASH_ACCESS_KEY 
});
<img data-random="img" />
<img data-random="img" data-random-img="person, face" />
<img data-random="img" data-random-img="school bus" />

randomAvatar({})

The randomAvatar method offers the functionality to create diverse and customizable avatars. This implementation draws inspiration from a modified version of Boring Avatars in vanilla JavaScript.

const randomController = new RandomUtil.Controller();

randomController.randomAvatar({ 
    avatarOptions: { 
      colors: ["#FF5733", "#33FF57", "#5733FF"],
      variant: "default" // ["smile", "pixel", "abstract"]
    }
});

License

This software is released under the MIT License

Report Issues or Request a Feature

If you encounter any issues or have suggestions for improvements, please feel free to report them. Your feedback is invaluable in enhancing this software.

Folder Structure

Here's an overview of the project's folder structure:

.
├── .env
├── .gitattributes
├── .gitignore
├── .nvmrc
├── LICENSE
├── README.md
├── __test__
│   └── randomutil.amd.test.js
├── babel.config.js
├── demo
│   ├── demo.css
│   ├── demo.js
│   └── index.html
├── dist
│   ├── randomutil.amd.js
│   └── randomutil.module.js
├── index.js
├── jest.config.js
├── package-lock.json
├── package.json
├── sets
│   └── palette.json
├── src
│   ├── index.js
│   ├── util.avatar.js
│   ├── util.content.js
│   ├── util.date.js
│   └── util.image.js
└── webpack.config.js

Keywords

FAQs

Package last updated on 19 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

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