• This repository has been archived on 30/May/2023
  • Stars
    star
    496
  • Rank 85,360 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A collection of base component recipes for Lightning Web Components on Salesforce Platform

‼️ This repo is archived as of April 2023. Developers looking for source code should reference the public npm package lightning-base-components. Source code is provided as-is with no support contract. ‼️

ARCHIVED: Base Components Recipes

View examples for base components in small bites. Each recipe demonstrates a working example of the base components to build pages and apps quickly. Use and customize the base components and the recipes in your apps.

Base component recipes open up the source code for the base components shown in the Component Library. We transpiled the base components into the c namespace so that you can use the components in your projects. Explore the inner workings of the components and use the source code to build new components with your own requirements. The possibilities are endless with the source in your hands!

Only a subset of the components in the Component Library are available. For more information, see the Documentation section.

Base components implement Salesforce Lightning Design System (SLDS) and are developed using Lightning Web Components. A c namespace component can contain components in the lightning namespace.

Before You Start

Consider using base component recipes only if the base components in the lightning namespace don't work for your requirements. For example, use base component recipes if you need to customize the styles of the base components beyond supported styling mechanisms. For a list of available base components in the lightning namespace, see the Component Library.

To customize the styles on lightning namespace components, we recommend using SLDS styling hooks. For more information, see Style Components with SLDS.

Getting Started

We recommend using a scratch org to work with base component recipes on the Salesforce platform.

  1. Set up your environment by following the steps in the Lightning Web Components Dev Guide, which includes:

    • Install the Salesforce CLI.
    • Install Visual Studio Code and the Salesforce Extension Pack, or your own favorite code editor.
    • Set up a Dev Hub org so you can work with Lightning web components in scratch orgs.
  2. Authenticate with your Dev Hub org and provide it with an alias, as shown by mybaseorg in the following command.

sfdx force:auth:web:login -d -a mybaseorg
  1. Clone the base-component-recipes repository.
git clone [email protected]:salesforce/base-components-recipes.git
cd base-components-recipes
  1. Create a scratch org and provide it with an alias, as shown by base-recipes in the following command.
sfdx force:org:create -s -f config/project-scratch-def.json -a base-recipes

If you get an error "You do not have access to the [ScratchOrgInfo] object", make sure you have enabled your org as a Dev Hub org. See Enable Dev Hub in Your Org. Alternatively, sign up for a Dev Hub org at https://developer.salesforce.com/promotions/orgs/dx-signup.

  1. Push the base-components-recipes code to your scratch org.
sfdx force:source:push
  1. Open the scratch org.
sfdx force:org:open
  1. In App Launcher, select the Base Components app. This app shows the base component recipes at base-components-recipes/example/lwc.

Use Base Components on Salesforce Platform

Create a helloWorld Lightning web component that uses a base component, c-button. We'll use Visual Studio Code in this example.

  1. In Visual Studio Code, open your base-components-recipes directory.
  2. Open the Command Palette by pressing Ctrl+Shift+P on Windows or Cmd+Shift+P on macOS.
  3. Type SFDX.
  4. Select SFDX: Create Lightning Web Component.
  5. Type helloWorld for the name of the new component and press Enter.
  6. Press Enter to accept the default force-app/main/default/lwc directory.
  7. A helloWorld bundle is created in force-app/main/default/lwc and the helloWorld.js JavaScript file opens in the editor.
  8. In helloWorld.js, replace the content with the following code. Save the file.
//helloWorld.js

import { LightningElement, api } from 'lwc';
export default class HelloWorld extends LightningElement {
    @api greeting = 'Hello World';
}
  1. Open the HTML file, helloWorld.html, and replace its content with the following code. Save the file.
<!--helloWorld.html-->

<template>
    <c-button label={greeting} title="greeting"> </c-button>
</template>
  1. In the XML file, helloWorld.js-meta.xml, replace the content with the following code. Save the file.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>
  1. Push your changes.
sfdx force:source:push

Your helloWorld component is now ready for action. You can add this component to your apps and pages via the Lightning App Builder. For more information, see the Quick Start: Lightning Web Components Trailhead project.

[Experimental] Use Base Components Outside of Salesforce Platform

Base Components in the c namespace are intended for use on the Salesforce platform. However, we realize the desire to use them in non-Salesforce scenarios. Currently, many components will work, but others will not, due to dependencies on the Salesforce platform. Our goal is to provide Base Components for non-Salesforce use cases, and we’ve created the LWC Storybook PoC to show what this might look like in the future. Please click the Watch button on the repo for updates as we move forward.

Documentation

Base components in the c namespace map to components in the lightning namespace. We transpiled the base components into the c namespace so that you can use the components in your projects. Find the base components in the c namespace in base-components-recipes/force-app/main/default/lwc/.

The components below link to documentation for components in the lightning namespace, but the usage is similar unless otherwise noted.

Component Description Comment
c-accordion A collection of vertically stacked sections with multiple content areas. This component contains slots and isn't supported as an Aura component.
c-accordion-section A single section of content. Use this component within c-accordion. This component contains slots and isn't supported as an Aura component.
c-avatar A visual representation of an object, such as an account or user
c-badge A label which holds a small amount of information, such as the number of unread notifications
c-button A button element that invokes an action
c-button-group A group of buttons that invokes similar actions
c-button-icon An icon-only button element that invokes an action The tooltip attribute isn't supported.
c-button-icon-stateful An icon-only button that retains state
c-button-menu A dropdown menu with a list of actions or functions. Use this component with c-menu-divider and c-menu-subheader to create menu dividers and sub-headings. The tooltip attribute isn't supported. For the menu-alignment attribute, the auto alignment isn't supported. This component references labels on Salesforce platform.
c-button-stateful A button that toggles between states
c-card A stylized container around a group of information This component contains slots and isn't supported as an Aura component.
c-carousel A collection of images and captions that are displayed one at a time. Use this component with c-carousel-image This component contains slots and isn't supported as an Aura component. This component references labels on Salesforce platform.
c-checkbox-group A group of checkboxes that enables selection of single or multiple options
c-combobox A read-only input field with a dropdown list for single selection This component references labels on Salesforce platform.
c-dual-listbox A pair of lists that enables multiple options to be selected and reordered This component references labels on Salesforce platform.
c-dynamic-icon A set of animated icons
c-formatted-date-time A pair of date and time that's displayed based on the user locale
c-formatted-location A pair of latitude and longitude for a location
c-formatted-name A name that's displayed based on the user locale, which determines the format and order of the constituents (suffix, salutation, etc.)
c-formatted-number A decimal, currency, or percentage that's displayed base on the user locale
c-formatted-phone A phone number that opens the default VOIP call app when clicked
c-formatted-text A group of text with an option to display URLs and email addresses as links
c-formatted-time A time value that's displayed based on the user locale
c-formatted-url A URL that's displayed as a link
c-icon A visual element that provides context and enhances usability For use on Salesforce platform only.
c-input-location A pair of latitude and longitude fields This component references labels on Salesforce platform.
c-layout A responsive grid system This component contains slots and isn't supported as an Aura component.
c-layout-item A container in a grid system This component contains slots and isn't supported as an Aura component.
c-menu-item A list item in a menu. Use this component within c-button-menu
c-output-field A read-only display of a label, help text, and value for a field on a Salesforce object. Use this component within c-record-view-form. For use on Salesforce platform only.
c-pill A label that can contain a link and can be removed from view This component contains slots and isn't supported as an Aura component. This component references labels on Salesforce platform.
c-pill-container A list of pills grouped in a container This component references labels on Salesforce platform.
c-radio-group A group of radio buttons that can have a single option selected This component references labels on Salesforce platform.
c-record-edit-form A form for creating or editing a record with one or more fields For use on Salesforce platform only. Use c-record-edit-form with lightning-input-field. Use c-messages in the form to display server-side error messages. This component references labels on Salesforce platform.
c-record-form A form for creating, displaying, or editing a record with automatic switching between edit and view modes For use on Salesforce platform only. This component references labels on Salesforce platform.
c-record-view-form A form for displaying record data. Use c-output-field within c-record-view-form. For use on Salesforce platform only. This component contains slots and isn't supported as an Aura component. This component references labels on Salesforce platform.
c-relative-date-time A group of text depicting how a specified time relates to the current time, such as "a few seconds ago" or "in 5 years"
c-slider An input range slider that enables selection of a value between two specified numbers
c-spinner An animated spinner
c-tab A single tab within a c-tabset component.
c-tabset A list of tabs. Use this component with c-tab. This component references labels on Salesforce platform.
c-textarea A textarea field for multi-line text input This component references labels on Salesforce platform.
c-tile A group of related information associated with a record This component contains slots and isn't supported as an Aura component. This component references labels on Salesforce platform.
c-tree A visualization of a structural hierarchy with nested items that can be collapsed or expanded. Use this component with c-tree-item. This component references labels on Salesforce platform.
c-vertical-navigation A vertical list of links that can be grouped into sections using c-vertical-navigation-section This component contains slots and isn't supported as an Aura component. This component references labels on Salesforce platform.
c-vertical-navigation-item A text-only link within c-vertical-navigation-section or c-vertical-navigation-overflow
c-vertical-navigation-item-badge A link and badge within c-vertical-navigation-section or c-vertical-navigation-overflow
c-vertical-navigation-item-icon A link and icon within c-vertical-navigation-section or c-vertical-navigation-overflow

Localization

You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length. Create custom labels that you can use in your Lightning web components.

Update Labels

To update the Custom Labels metadata, go to the force-app/main/default/labels directory. The labels are available in the lightning.labels-meta.xml file. For syntax and an example of a CustomLabels definition, see the Metadata API Dev Guide.

Add labels for your custom components in the lightning.labels-meta.xml file.

<labels>
    <categories>lightning</categories>
    <fullName>MyCard_cardTitle</fullName>
    <language>en_US</language>
    <protected>false</protected>
    <shortDescription>cardTitleLabel</shortDescription>
    <value>This is my card</value>
  </labels>

Customize Labels

To customize your labels, from Setup, type Custom Labels in the Quick Find box, then select Custom Labels. Our labels are shipped in English and can be translated to other languages. For more information, see the Translate Labels section below and Custom Labels in Salesforce Help.

Use Labels

Import the labels from the @salesforce/label scoped module. Reference your label name using the c namespace.

// myComponent.js

import cardTitleLabel from '@salesforce/label/c.MyCard_cardTitle';
import loadingLabel from '@salesforce/label/c.lightning_LightningControl_loading';
import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
    label = {
        cardTitleLabel,
        loadingLabel
    };
}

Use your labels in a Lightning web component.

<!-- myComponent.html -->

<template>
    <c-card title={label.cardTitleLabel}>
        {label.loadingLabel}
    </c-card>
</template>

Translate Labels

Enable the Translation Workbench to support translations in your org. See Enable and Disable the Translation Workbench in Salesforce Help. Next, modify sfdx-project.json to include the path for the translation files, which are available in the optional folder.

{
    "packageDirectories": [
        {
            "path": "force-app",
            "default": true
        },
        {
            "path": "examples",
            "default": false
        },
        {
            "path": "optional"
        }
    ],
    "namespace": "",
    "sfdcLoginUrl": "https://login.salesforce.com",
    "sourceApiVersion": "46.0"
}

After updating sfdx-project.json, push the files to your scratch org.

sfdx force:source:push

Testing

We use the Jest JavaScript Testing Framework to author and run component tests. If you modify any base component recipes or add your own components, run tests to verify your changes.

For your own components, add tests to a __tests__ sub-folder of your componentName folder and name the test componentName.spec.js.

To illustrate how to test components we'll add a test to the helloWorld component created earlier.

  1. Create a __tests__ subfolder in the helloWorld folder.

  2. Create a file named helloWorld.spec.js in __tests__.

  3. Insert this code and save the file.

//__tests__/helloWorld.spec.js

import { createElement } from 'lwc';
import Element from 'c/helloWorld';

const createComponent = (params = {}) => {
    const element = createElement('c-hello-world', { is: Element });
    Object.assign(element, params);
    document.body.appendChild(element);
    return element;
};

describe('c-hello-world', () => {
    it('button has the expected message', () => {
        const element = createComponent();
        const button = element.shadowRoot.querySelector('c-button');
        return Promise.resolve().then(() => {
            expect(button.label).toEqual('Hello World');
        });
    });
});
  1. Run the helloWorld test suite from the base-components-recipe folder.
npm run test helloWorld
  1. Run all base components recipes test suites.
npm run test

This runs lint and unit tests. See the package.json file for all the available tests.

Contributing

We are not accepting contributions at this time. If you have any questions about base components recipes, please use the following channels.

FAQ

More Repositories

1

LAVIS

LAVIS - A One-stop Library for Language-Vision Intelligence
Jupyter Notebook
8,226
star
2

CodeGen

CodeGen is a family of open-source model for program synthesis. Trained on TPU-v4. Competitive with OpenAI Codex.
Python
4,594
star
3

BLIP

PyTorch code for BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation
Jupyter Notebook
3,879
star
4

akita

🚀 State Management Tailored-Made for JS Applications
TypeScript
3,442
star
5

Merlion

Merlion: A Machine Learning Framework for Time Series Intelligence
Python
3,232
star
6

ja3

JA3 is a standard for creating SSL client fingerprints in an easy to produce and shareable way.
Python
2,502
star
7

CodeT5

Home of CodeT5: Open Code LLMs for Code Understanding and Generation
Python
2,437
star
8

decaNLP

The Natural Language Decathlon: A Multitask Challenge for NLP
Python
2,301
star
9

TransmogrifAI

TransmogrifAI (pronounced trăns-mŏgˈrə-fī) is an AutoML library for building modular, reusable, strongly typed machine learning workflows on Apache Spark with minimal hand-tuning
Scala
2,227
star
10

policy_sentry

IAM Least Privilege Policy Generator
Python
1,938
star
11

awd-lstm-lm

LSTM and QRNN Language Model Toolkit for PyTorch
Python
1,900
star
12

cloudsplaining

Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report.
JavaScript
1,865
star
13

ctrl

Conditional Transformer Language Model for Controllable Generation
Python
1,766
star
14

lwc

⚡️ LWC - A Blazing Fast, Enterprise-Grade Web Components Foundation
JavaScript
1,537
star
15

WikiSQL

A large annotated semantic parsing corpus for developing natural language interfaces.
HTML
1,520
star
16

sloop

Kubernetes History Visualization
Go
1,396
star
17

CodeTF

CodeTF: One-stop Transformer Library for State-of-the-art Code LLM
Python
1,375
star
18

ALBEF

Code for ALBEF: a new vision-language pre-training method
Python
1,276
star
19

pytorch-qrnn

PyTorch implementation of the Quasi-Recurrent Neural Network - up to 16 times faster than NVIDIA's cuDNN LSTM
Python
1,255
star
20

ai-economist

Foundation is a flexible, modular, and composable framework to model socio-economic behaviors and dynamics with both agents and governments. This framework can be used in conjunction with reinforcement learning to learn optimal economic policies, as done by the AI Economist (https://www.einstein.ai/the-ai-economist).
Python
964
star
21

jarm

Python
914
star
22

design-system-react

Salesforce Lightning Design System for React
JavaScript
896
star
23

tough-cookie

RFC6265 Cookies and CookieJar for Node.js
TypeScript
858
star
24

reactive-grpc

Reactive stubs for gRPC
Java
814
star
25

OmniXAI

OmniXAI: A Library for eXplainable AI
Jupyter Notebook
782
star
26

xgen

Salesforce open-source LLMs with 8k sequence length.
Python
704
star
27

vulnreport

Open-source pentesting management and automation platform by Salesforce Product Security
HTML
593
star
28

UniControl

Unified Controllable Visual Generation Model
Python
577
star
29

hassh

HASSH is a network fingerprinting standard which can be used to identify specific Client and Server SSH implementations. The fingerprints can be easily stored, searched and shared in the form of a small MD5 fingerprint.
Python
525
star
30

progen

Official release of the ProGen models
Python
518
star
31

Argus

Time series monitoring and alerting platform.
Java
501
star
32

matchbox

Write PyTorch code at the level of individual examples, then run it efficiently on minibatches.
Python
488
star
33

PCL

PyTorch code for "Prototypical Contrastive Learning of Unsupervised Representations"
Python
483
star
34

cove

Python
470
star
35

CodeRL

This is the official code for the paper CodeRL: Mastering Code Generation through Pretrained Models and Deep Reinforcement Learning (NeurIPS22).
Python
465
star
36

DialogStudio

DialogStudio: Towards Richest and Most Diverse Unified Dataset Collection and Instruction-Aware Models for Conversational AI
Python
431
star
37

warp-drive

Extremely Fast End-to-End Deep Multi-Agent Reinforcement Learning Framework on a GPU (JMLR 2022)
Python
429
star
38

observable-membrane

A Javascript Membrane implementation using Proxies to observe mutation on an object graph
TypeScript
368
star
39

PyRCA

PyRCA: A Python Machine Learning Library for Root Cause Analysis
Python
367
star
40

DeepTime

PyTorch code for Learning Deep Time-index Models for Time Series Forecasting (ICML 2023)
Python
322
star
41

ULIP

Python
316
star
42

logai

LogAI - An open-source library for log analytics and intelligence
Python
298
star
43

MultiHopKG

Multi-hop knowledge graph reasoning learned via policy gradient with reward shaping and action dropout
Jupyter Notebook
290
star
44

CodeGen2

CodeGen2 models for program synthesis
Python
269
star
45

provis

Official code repository of "BERTology Meets Biology: Interpreting Attention in Protein Language Models."
Python
269
star
46

jaxformer

Minimal library to train LLMs on TPU in JAX with pjit().
Python
255
star
47

EDICT

Jupyter Notebook
247
star
48

causalai

Salesforce CausalAI Library: A Fast and Scalable framework for Causal Analysis of Time Series and Tabular Data
Jupyter Notebook
223
star
49

ETSformer

PyTorch code for ETSformer: Exponential Smoothing Transformers for Time-series Forecasting
Python
221
star
50

themify

👨‍🎨 CSS Themes Made Easy. A robust, opinionated solution to manage themes in your web application
TypeScript
216
star
51

rules_spring

Bazel rule for building Spring Boot apps as a deployable jar
Starlark
215
star
52

simpletod

Official repository for "SimpleTOD: A Simple Language Model for Task-Oriented Dialogue"
Python
212
star
53

TabularSemanticParsing

Translating natural language questions to a structured query language
Jupyter Notebook
210
star
54

grpc-java-contrib

Useful extensions for the grpc-java library
Java
208
star
55

GeDi

GeDi: Generative Discriminator Guided Sequence Generation
Python
207
star
56

aws-allowlister

Automatically compile an AWS Service Control Policy that ONLY allows AWS services that are compliant with your preferred compliance frameworks.
Python
207
star
57

mirus

Mirus is a cross data-center data replication tool for Apache Kafka
Java
200
star
58

generic-sidecar-injector

A generic framework for injecting sidecars and related configuration in Kubernetes using Mutating Webhook Admission Controllers
Go
200
star
59

CoST

PyTorch code for CoST: Contrastive Learning of Disentangled Seasonal-Trend Representations for Time Series Forecasting (ICLR 2022)
Python
196
star
60

factCC

Resources for the "Evaluating the Factual Consistency of Abstractive Text Summarization" paper
Python
192
star
61

runway-browser

Interactive visualization framework for Runway models of distributed systems
JavaScript
188
star
62

glad

Global-Locally Self-Attentive Dialogue State Tracker
Python
186
star
63

ALPRO

Align and Prompt: Video-and-Language Pre-training with Entity Prompts
Python
177
star
64

densecap

Jupyter Notebook
176
star
65

cloud-guardrails

Rapidly apply hundreds of security controls in Azure
HCL
174
star
66

booksum

Python
167
star
67

kafka-junit

This library wraps Kafka's embedded test cluster, allowing you to more easily create and run integration tests using JUnit against a "real" kafka server running within the context of your tests. No need to stand up an external kafka cluster!
Java
166
star
68

sfdx-lwc-jest

Run Jest against LWC components in SFDX workspace environment
JavaScript
156
star
69

ctrl-sum

Resources for the "CTRLsum: Towards Generic Controllable Text Summarization" paper
Python
144
star
70

cos-e

Commonsense Explanations Dataset and Code
Python
143
star
71

hierarchicalContrastiveLearning

Python
140
star
72

secure-filters

Anti-XSS Security Filters for EJS and More
JavaScript
138
star
73

metabadger

Prevent SSRF attacks on AWS EC2 via automated upgrades to the more secure Instance Metadata Service v2 (IMDSv2).
Python
129
star
74

dockerfile-image-update

A tool that helps you get security patches for Docker images into production as quickly as possible without breaking things
Java
127
star
75

Converse

Python
125
star
76

refocus

The Go-To Platform for Visualizing Service Health
JavaScript
125
star
77

CoMatch

Code for CoMatch: Semi-supervised Learning with Contrastive Graph Regularization
Python
117
star
78

BOLAA

Python
114
star
79

bazel-eclipse

This repo holds two IDE projects. One is the Eclipse Feature for developing Bazel projects in Eclipse. The Bazel Eclipse Feature supports importing, building, and testing Java projects that are built using the Bazel build system. The other is the Bazel Java Language Server, which is a build integration for IDEs such as VS Code.
Java
108
star
80

botsim

BotSIM - a data-efficient end-to-end Bot SIMulation toolkit for evaluation, diagnosis, and improvement of commercial chatbots
Jupyter Notebook
108
star
81

near-membrane

JavaScript Near Membrane Library that powers Lightning Locker Service
TypeScript
107
star
82

rng-kbqa

Python
105
star
83

MUST

PyTorch code for MUST
Python
103
star
84

fsnet

Python
101
star
85

bro-sysmon

How to Zeek Sysmon Logs!
Zeek
101
star
86

Timbermill

A better logging service
Java
99
star
87

best

🏆 Delightful Benchmarking & Performance Testing
TypeScript
95
star
88

eslint-config-lwc

Opinionated ESLint configurations for LWC projects
JavaScript
93
star
89

craft

CRAFT removes the language barrier to create Kubernetes Operators.
Go
91
star
90

AuditNLG

AuditNLG: Auditing Generative AI Language Modeling for Trustworthiness
Python
90
star
91

online_conformal

Methods for online conformal prediction.
Jupyter Notebook
90
star
92

lobster-pot

Scans every git push to your Github organisations to find unwanted secrets.
Go
88
star
93

violet-conversations

Sophisticated Conversational Applications/Bots
JavaScript
84
star
94

ml4ir

Machine Learning for Information Retrieval
Jupyter Notebook
84
star
95

apex-mockery

Lightweight mocking library in Apex
Apex
83
star
96

fast-influence-functions

Python
80
star
97

MoPro

MoPro: Webly Supervised Learning
Python
79
star
98

TaiChi

Open source library for few shot NLP
Python
79
star
99

helm-starter-istio

An Istio starter template for Helm
Shell
78
star
100

QAConv

This repository maintains the QAConv dataset, a question-answering dataset on informative conversations including business emails, panel discussions, and work channels.
Python
77
star