# UDTruncateText Powershell Universal Component Module 🦐

By
,
Powershell
,
Modules
Published 2022-09-14

Link To Download UDTruncateText Module
https://www.powershellgallery.com/packages/UDTruncateText/1.0.0

GitHub Link to this UDTruncateText Repository
https://github.com/psDevUK/UDTruncateText

Without using UDTruncateText
Using UDTruncateText

Maybe you have a lot of text and not enough space
Maybe you have a lot of text and not enough space

Truncating the text to give the less is more approach
Truncating the text to give the less is more approach

# Demo Dashboard 🤪

A real quick and easy dashboard to demonstrate the power behind this component.

New-UDDashboard -Title 'UDTruncateText' -Content {
New-UDRow -Columns {
  New-UDColumn -Content {
New-UDTruncateText -HyperLink "https://adam-bacon.netlify.app/recent-modules/udtextfit/" -Lines 2 -ReadOn "Read More Here" -Text "So this is a super important bit of text you need to read, but do not want to ramble on too long so have a link to encourage the user to read the main article"
  } -LargeSize 4 -MediumSize 4 -SmallSize 4
}
}

# The Project 🏗️

Okay so I know if you are a web-designer or know your HTML and JavaScript well enough you could probably just hard-code the solution. However I am just a guy who loves to use Powershell to make things work, and try to provide an easier solution to the given problem.

What was the problem? Me, yes that is right the problem was me. I was looking for another component to build, one that did not exist already in the eco-system. It is getting tough to find a useful component that I have not already built or is not included in the product by default. However I saw this component and thought 💡 this would be a great idea to build this as a custom React component for Powershell Universal.

Orginal React Component Here
https://www.npmjs.com/package/react-text-truncate

Demo of the original component
http://shinychang.github.io/React-Text-Truncate/

# Using New Site To Find Components 📰

IF YOU READ THE LAST ARTICLE YOU CAN SKIP THIS PARAGRAPH

Yep so even though I am providing the link to the official react component above which is pointing to npmjs.com it seems for some reason when I am searching on npmjs.com I get limited to 20 results no matter what. Like I used to get back thousands of results, and scroll through pages and pages of components till I found the one I was looking for. I even signed up to npmjs thinking maybe you now need to be a member to get back all the results, but I was still only getting 20 results back.

Thankfully the internet has more than just one webpage to find react components, and I then landed on:-

I am now using yarnpkg to find React components
https://yarnpkg.com/

Which was bringing back the number of results I used to get on npmjs and it even gave me the link to the npmjs package page.

So I know this is not the most super-fancy react component but as mentioned I could really see this being useful if you have a super busy dashboard with so much information to display to the user, so instead of giving the end-user a brain-overload. Why not present just enough information to the end-user then let them decide if they wish to read the full article associated with the truncated text.

# Component JSX File 🗃️

So there are a fair few good files you need to edit in some shape or form to build a component, I think it would be a good idea for me to document this process to show how simple it really is. Before I could edit this JSX file within the components folder I needed to make sure I had installed the npm pacakge for this react component as I saw this needed more than one dependency I used the following website to detect all the dependencies to save me clicking

Find Dependencies Easily
https://npm.anvaka.com/

I then copied this list into notepad then ran this one line to install all these dependencies

gc C:\Builds\dependencies.txt | % {npm i $_ --legacy-peer-deps}

So once these were installed, and I had renamed the .PSD1 and .PSM1 file to the module name I wanted. I then edited the .PSD1 file to include the RootModule as the newly named .PSM1 file, I edited the component.build.ps1 file to copy the newly named modules

	Copy-Item $PSScriptRoot\UDTruncateText.psd1 $OutputPath
	Copy-Item $PSScriptRoot\UDTruncateText.psm1 $OutputPath

also edited line 20 in the webpack.config.js file to be

library: 'udtruncatetext'

Within the components folder there is an index.js file my edited file looked like

import UDTruncateText from './component';
UniversalDashboard.register("udtruncatetext", UDTruncateText);

Please keep case-sensitive lower-case for the webpack.config.js file which then reflects what is typed as first arguement within the parenthesis as shown above. Once you have made all these edits to the existing template files, and installed the npm package and all dependencies (in this case I only had two packages to install as only one dependency) it is time to construct the actual component that will be displayed on the dashboard. This is done by editing the component.jsx file witin the components folder within the github template you downloaded. This is my final edited component.jsx file:-

import React from 'react';
import { withComponentFeatures } from 'universal-dashboard';
import TextTruncate from 'react-text-truncate';

const UDTruncateText = props => {
  return (
    <TextTruncate
    key={props.id}
    line={props.line}
    element="span"
    truncateText={props.truncateText}
    text={props.text}
    textTruncateChild={<a href={props.href}>{props.readon}</a>}
/>
  );
  }

export default withComponentFeatures(UDTruncateText)

So VSCode was not complaining about any of the code above, so now I needed to edit the .PSM1 and .PSD1 file to finish this component off before running invoke-build so this is my final PSD1 file below

#
# Module manifest for module 'UDTruncateText'
#
# Generated by: psdevuk
#
# Generated on: 12/09/2022
#

@{

# Script module or binary module file associated with this manifest.
RootModule = 'UDTruncateText.psm1'

# Version number of this module.
ModuleVersion = '1.0.0'

# Supported PSEditions
# CompatiblePSEditions = @()

# ID used to uniquely identify this module
GUID = '76de2c49-86a9-4b58-9247-edbe35fed09a'

# Author of this module
Author = 'psdevuk'

# Company or vendor of this module
CompanyName = 'Home'

# Copyright statement for this module
Copyright = '(c) Adam. All rights reserved.'

# Description of the functionality provided by this module
 Description = 'Gives the ability to truncate the amount of text shown, and provide a hyperlink to read the rest of the information'

# Minimum version of the PowerShell engine required by this module
# PowerShellVersion = ''

# Name of the PowerShell host required by this module
# PowerShellHostName = ''

# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()

# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'New-UDTruncateText'

# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'

# Variables to export from this module
VariablesToExport = '*'

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '*'

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

    PSData = @{

        # Tags applied to this module. These help with module discovery in online galleries.
         Tags = @('ud-component','text','formatting')

        # A URL to the license for this module.
        # LicenseUri = ''

        # A URL to the main website for this project.
         ProjectUri = 'https://github.com/psDevUK/UDTruncateText'

        # A URL to an icon representing this module.
         IconUri = 'https://c.tenor.com/WMFB1K1DFA4AAAAd/information-overload-mind-blown.gif'

        # ReleaseNotes of this module
        # ReleaseNotes = ''

        # Prerelease string of this module
        # Prerelease = ''

        # Flag to indicate whether the module requires explicit user acceptance for install/update/save
        # RequireLicenseAcceptance = $false

        # External dependent modules of this module
        # ExternalModuleDependencies = @()

    } # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}

To make the actual cmdlet behind this component you need to edit the pre-defined function in the .PSM1 file so this is my finished .PSM1 before running the invoke-build

$IndexJs = Get-ChildItem "$PSScriptRoot\index.*.bundle.js"
$AssetId = [UniversalDashboard.Services.AssetService]::Instance.RegisterAsset($IndexJs.FullName)

function New-UDTruncateText {
    <#
    .SYNOPSIS
    Gives the ability to decide how much text to display
    
    .DESCRIPTION
    Allows you to decide how many lines of text you wish to display then provide a hyperlink for the end-user to carry on reading the article
    
    .PARAMETER Id
    The ID of this editor

    .PARAMETER Hyperlink
    Set the hyperlink to point to the main article

    .PARAMETER Lines 
    Set the number of lines you want to return to the end user before the text is truncated

    .PARAMETER TruncateText
    Displays the truncation text which is defaulted to ...

    .PARAMETER ReadOn
    Text for the hyperlink at the end of the truncation defaulted to Read On

    .PARAMETER Text
    Text for the component

    .EXAMPLE
    New-UDTruncateText -HyperLink "https://adam-bacon.netlify.app/recent-modules/udtextfit/" -Lines 2 -ReadOn "Read More Here" -Text "So this is a super important bit of text you need to read, but do not want to ramble on too long so have a link to encourage the user to read the main article"
    #>
    
    param(
        [Parameter()]
        [string]$Id = (New-Guid).ToString(),
        [Parameter()]
        [int]$Lines,
        [Parameter()]
        [string]$Text,
        [Parameter()]
        [string]$TruncateText = "...",
        [Parameter()]
        [string]$HyperLink,
        [Parameter()]
        [string]$ReadOn = "Read On"
    )

    End {
        @{
            assetId = $AssetId 
            isPlugin = $true 
            type = "udtruncatetext"
            id = $Id

            line = $Lines
            truncateText = $TruncateText
            text = $Text
            href = $HyperLink
            readon = $ReadOn
        }
    }
}

# Ready, Steady, Go! 🚦

So once you have followed the above, you are now ready to run:-

invoke-build

As long as you read the official documentation on building a custom component you would have already downloaded all the prerequisite modules and software required to build custom components. I did find I needed to also install the psake module as well. This process literally took 10 seconds or less. As long as you do not get any errors, and the process completes then within the output directory you will have you brand-new custom component you built.

I restarted the PowershellUniversal service then logged into the main portal. Verified the module was being picked up by the software, by searching the available modules within the program. Once I verified my new module was included, I then did a test on the dashboard.

I now had a fully working react custom component loaded into the Powershell Universal dashboard I had created. I then verified all the parameters worked, which they did then it was time to publish this module to the Powershell Gallery. Please note to include ud-component within the module tags to enable your custom component to be found on the market place exclusive to this product.

Link to this module on marketplace
https://marketplace.universaldashboard.io/Dashboard/UDTruncateText

# 💥 That is how this Powershell module was done. Till next time, take care