* updating sidebar's version info
* removing beta badge
* updating tooltip + version number decorator for official launch
* removing beta notice from docs landing view
* removing beta from Installation docs
* Document code completion setup for Web Awesome
Added instructions for enabling code completion in VS Code and JetBrains IDEs for Web Awesome components.
This mirror what already exist for Shoelace: https://shoelace.style/getting-started/usage#code-completion
+ a new line to explain how to setup VS Code completion from the CDN
* Update packages/webawesome/docs/docs/usage.md
* Update packages/webawesome/docs/docs/usage.md
* Update packages/webawesome/docs/docs/usage.md
* Update packages/webawesome/docs/docs/usage.md
* Update packages/webawesome/docs/docs/usage.md
* Update packages/webawesome/docs/docs/usage.md
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* adding .appearance-plain for lists to utils.css
* adding gitLastModifiedISO filter to .eleventy.js
* adding link to Pro License in sidebar.njk
* adding link to Free License in sidebar.njk
* adding link to Terms of Service in sidebar.njk
* adding "last updated" date to changelog.md
* Make the README better
• Replace straight quotes with smart quotes
• Revise Node.js minimum requirement wording (to prevent line breaks)
• Replace old links to LitElement (Polymer) to Lit
• Replace mentions of “NPM” with “npm”, as per https://github.com/npm/cli?tab=readme-ov-file#is-it-npm-or-npm-or-npm
• Fix some grammar and abbreviations
• Made “dependencies” and “devDependencies” mentions unquoted to be consistent
• Correct “MIT license” with “MIT License”, as per https://opensource.org/license/mit
* Make some specific changes to make wording more clear
* add missing dot
* remove smart quotes
* updating Pro Badge's appearance
* abstracting Pro Badge into include
* adding nanoid-based uniqueId filter to eleventyConfig
* ensuring Pro Badge instances have unique ids
* using added uniqueId filter + nanoid
* converting Pro Badge to be macro-based
* customizing Pro Badge's associated wa-tooltip size
* syncing up `<body>` classes on blank.njk
* using `wa_page_attributes` block instead of `pageType`
* using `head` block instead of `pageType`
* removing `pageType` from `<body>` classes
* removing `pageType` from eleventyConfig
* updating color-scheme-selector's icons
* allowing `wa-page` attributes to override those set in base.njk
* allowing pageClass to be used on base.njk's `<body>`
* import relevant utilities into native styles
* import color variant classes into free palettes
* import the default palette into kitchen sink, not the default theme
* fix palette path
* import each theme's intended palette
* started horizontal card logic
* a little more work
* remove SSR attributes
These are no longer used since we're not serving up an SSR version of the website anymore.
* more work
* looking for old code
* added actions slot to horizontal card
* troubleshooting linter issue
* fixed liniting error
* responded to feedback
* added jsDoc and updated example
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* adding conditional header + footer includes to `base.njk`
- support for custom headers via `header` front matter variable
- support for custom footers via `footer` front matter variable
- backward compatibility with default header
* revising `base.njk`'s body classes
* adding fileSlug-based class to body
* adding pageType-based class (default `docs`) to body
* adding conditional CSS asset logic to `base.njk`
* to load marketing-based CSS based on pageType
* to load docs-based CSS by default
* disabling wa-page's sticky header for marketing pageType
* using layout utilities for sidebar heading link styling
* syncing up sidebar heading + general link styles
* updating sidebar heading text + icon alignment
* updating layout of experimental + pro badge decoratives
* increasing visual padding of `#search-trigger`'s `<kbd>`
* fixing `<li>` indentations
* Add FA 7 support
* Add FA 7 support
* Add FA 7 support
* Update the system library to use FA 7 icons
* fix: fix type issues
* Update the SVGs in the system library to be minified/compressed
* add suggestions and more features
* feat: add `swap-opacity` attribute
* fix: remove unrelated stuff in `swap-opacity` attribute styling
* Only scale paths for fixed width icons
* fix: fix Prettier lint issues
* fix: fix more syntax errors
* lint: Fix CSS linting, batch 1 of 3
* lint: fix TS linting issues, batch 2 of 3
* lint: Fix JS linting issues, batch 3 of 3
* lint: fix hopefully last linting issue, batch 3.5 of 3
* lint: fix final linting issues, 3.75 of 3
* lint: the actual last lint fix, batch 3.875 of 3
* chore: centre SVG paths within the SVG for fixed‐width icons
* fix iconoir example
* add comment to clarify
* use a constant for fa version
* remove unsupported features
* update for FA7; improve duotone support
* update changelog
* remove redundant fixed-width attributes
* update kit code
* notdog!
* add support for pro+ icons
* clean up example layouts, use consistent icon sizes
---------
Co-authored-by: randomguy-2650 <150704902+randomguy-2650@users.noreply.github.com>
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* Adjust label styles for button and checkbox components to not crush space of nested tags
* Adjust label styles for button and checkbox components to not crush space of nested tags
* Update packages/webawesome/src/components/checkbox/checkbox.css
---------
Co-authored-by: Tobias Bannwart <tobias.bannwart@bison-group.com>
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* add before / after watch events so pro can properly incrementally build
* add events for pro / app
* add extra hooks for non-wa dev
* add old new line
* use package-lock.json from next
* npm install
* prettier
* change to webawesome
* change to webawesome
* update index.md
* whitespace
* add thanks for being a webawesome pro subscriber
* add stub for currentUser
* add source code link
* add source code link
* prettier
* fix raw call
* add pro badge to themer
* add isPro flag to palettes
* show based on currentUser.hasPro
* fix logged out user stuff
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* progress, components A – C
* left behind tweaks for A – C
* all the rest
* tweaks
* remove 'accent + outlined' appearances and other tweaks
* fix overlooked docs + scouts rule
* re-add `--checked-icon-color` to radio and checkbox
* revert to `--thumb-size`
* fix theme overrides
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* consolidate theme files
* move dimension to its own layer
* touch up
* fix `.wa-invert`
* fix selectors and missing fonts
* fix selectors (for real this time)
* add button for drawer example
* scaffolding
* building initial page
* loading blank
* committing to pull down changes
* committing to merge
* trying to sync with next
* drawer issue
* added content to drawer
* added checkout page
* added checkout page
* committing to merge
* committing to merge
* made changes to sidebar
* syncing with repo
* syncing with repo
* update sidebar again
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* use wa-popup in color picker
* remove test
* remove old dropdown, menu, menu item, menu label
* remove old dropdown
* rework dropdown + dropdown item
* update examples
* add hide duration
* update jsdoc
* add event
* add size
* add size
* fix docs
* remove old test; fix types
* add submenu to example
* adapt for <wa-popup>
* remove state
* fix dropdown stuff (#1044)
* fix dropdown stuff
* prettier
* get typescript to give a real error
* remove unnecessary checks
* prettier
* remove old tag
* convert old dropdowns to new syntax
* update example
* update styles
---------
Co-authored-by: Konnor Rogers <konnor5456@gmail.com>
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* tidy and touch up content styles
* finish touching up inline text styles
* move styles for docs code blocks from `native.css` to appropriate files
* tidy and touch up list and table styles
* tidy and touch up details styles
* tidy up dialog styles
* fix bloated spacing in dialog and drawer
* add fieldset, refactor radio and checkbox styles
* refactor input, textarea, and select styles
* refactor range styles to match new `<wa-slider>`
* readability improvements
* touch up theme overrides
* fix Matter checkbox and radio hover styles
* visual test setup
* fix improper class placement in visual tests
* add `wa-form-control-*-font-size` and `-wa-form-control-hint-*` custom properties
* use new custom properties
* dump of component sizing improvements
* fix native color picker styles
* update menu with relative sizes
* tidy up menu, select, and tag sizing
* use relative sizing across components
* touch up custom properties
* update docs and comments
* update changelog
* revert changes to visual tests to simplify PR
* revert leftover change to visual tests
* tidy up space doc markdown
* fix default card spacing
* fix card docs
* wrap up new `--tag-max-size` for `<wa-select>`
* change default `--tag-max-size`
* prettier
* touch up
* clean up leftovers
* fix native form control margins
* set default toggle size relative to font size
* correct toggle size in docs
* Konnorrogers/lm form control sizing (#1025)
* try a second updateComplete??
* try a second updateComplete??
* more timeouts?
* try logging
* more logging
gp
* maybe now
* radio group test
* add todo note'
* add workflow dispatch for client tests
---------
Co-authored-by: Konnor Rogers <konnor5456@gmail.com>
* remove redundant styles from template
* rotate arrow based on placement so borders show correctly when applied
* use actual placement, not preferred
* add popover
* update changelog
* update changelog
* use <dialog> for popover
* fix arrow border in FF/Safari
* update content
* add sidebar to plop
* add popover
* remove test value
* remove animation to prevent page-to-page blips
* static sidebar
* manage open sections on page load and with turbo
* cleanup unused scripts
* Remove overlap between Style Utilities and Layout
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* vertical => orientation="vertical"; fixes#674
* add issue
* Update divider styles and docs to use `orientation='vertical'`
* Update split panel styles and docs to use `orientation='vertical'`
* Update remaining docs and patterns examples to `orientation='vertical'`
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* Exclude Create link from sidebar, for reals this time
* Fix bug
* Very rough prototype of look & feel
* a11y
* Clean up data files
* Automatically generate theme metadata
* Read look & feel params straight from theme
* First stab at dimensionality icons
* Fix rounding 0 bug
* Add border width slider
* [Image-comparer] Expose wrapper as part
* [Comparer] `pointer-events: none` while dragging
* Dark mode slider
* Adjust increments and ranges for look + feel sliders
* Fix preview
* Fix bug where dark mode was not inverted
* Ability to select panel from URL
* Create mixin for Vue form controls and use it in `<swatch-select>`
* Prototype of slider min/max icon buttons
* Nx tooltip
* Icons
* Prevent failed request
* info-tip: Support passing text as prop
* Clearable
* [Brutalist] Match `--wa-shadow-offset-x-scale` to `--wa-shadow-offset-y-scale`
* Add 'Blocky' dimension (derived from Awesome theme)
* Only show Reset button when `clearable` is set
* Remove `clearable` from Look & Feel sliders
* Add tooltips to min/max buttons
* Remove superfluous `aria-label`
* Do not assume that all hyphens in URLs mean nesting, make it explicit
* Formatting
* Fix bug where styles were not applied on page load
* Update Subtle dimension to maximize compatibility
* `<wa-scoped>`: Do not allow non-template children
* Workaround for card not updating
* Update Glossy dimension to maximize compatibility
* Sync scrolling between regular and inverted preview
* Fix bug
* Make changing the base theme reset customizations
* Fix palette page
* Remove cancel button from editable text
* Don't error in theme pages
* Update Playful dimension to maximize compatibility
* Rename 'Look and Feel' to 'Elements' for better parallel structure
* Hide dimensionality controls
* Make back icon motion more subtle
* Expand spacing slider bounds
* Add `tabindex="-1"` where missing in theme showcase
* Remove extraneous gap from theme headers
* fix edit button bug
* rename comparer => comparison; fix aria-controls
* Always save theme name on blur
* Add changelog for themer and new patterns category
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* initial commit to this pr
* updated patterns
* category lists
* post headers
* WIP
* made some content updates
* deleted rogue file
* updated descriptions
* ran prettier
* updated padding
* updated prettierignore
* updated element
* swtiched to token
* updated with category list feedback
* updated with category list feedback
* updated with feedback for featurd post
* updated with feedback for footer
* updated with newsletter feedback'
* updated with feedback to the paywall
* updated with updates for post footer
* more footer updates
* updated with feedback for the post header
* updated with feedback for post list
* updated social share
* updated sign up and login
* added logic to elements to prevent them from closing on escape
* Fix typo (incomplete `<h2>` tag)
* Add missing input labels, fix capitalization and punctuation
* Add description to Blog & News index
* ran prettier on markdown files
* ignored the post list file
* changed hierarchy
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* [Menu-item] Drop `base` wrapper (rel #207)
Also add two states: `has-submenu` and `submenu-expanded`
* Add `checked-icon` and `submenu-icon` slots
* [Menu-label] Drop `base` part
* update changelog
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* Basic scaffolding
* Generate theme & palette data.js that other JS can import
* Make it possible to include page-card without links
* WIP
* Add `appearance` to details, closes#569
Except `accent` as that's a) far less useful and b) trickier due to the icon color
* Fix broken link
* WIP
* WIP
* Icons icon
* Unify styles for interactive cards
* Prevent focusing inside theme icons
* Fixes
* Action page cards
* Panel scrollables
* scrollable
* Scroll shadows
* Add renaming UI
* UI
* Move styling of heading icons to `ui.css`
* Support permalinks & CRUD
* Make clickable cards more accessible
* Style cards a little better
* Default to styles panel if theme is selected
* Update theme-icons.css
* Custom themes should be saved under Custom
* Get theme code
* Bigger title
* Fixes
* Use theme Vue app for remixing too
* Fix preview jank and make preview script more flexible
* Make radio groups scrollable
* Add affordance to button cards
* Sticky
* `<color-select>`
* Fix theme remixing
* Improve previewing logic
* Fix preview
* Move `domChange()` to separate module
`theme-picker.js` includes side-effects, which may not always be desirable everywhere we may want to import `domChange()`
* Update preview.js
* Panel animation
* Hide Save button if no changes and not saved
* Do not show blank code when no selection has been made
* Use theme slug in filename
* Remove unused component
* Better UI for editing title (and any other text)
* Tweak UI of renaming
* Better indicate default selection
* Fix preview reverting bug
* Fill out app preview with more examples
* Remove `zoom` from theme showcase (yields unexpected/painful results Safari), improve display in wider viewports
* Pending delete
* Make styles panel cards scrollable
* Fix some of the Safari issues
* Update search.css
* Update panel.css
* Select preview UI
* Fix typo
* Frame colors setting as color contrast
* Show dark mode in color mappings
* Brand color
* Swatch styling
* Fix caret icon
* Move Starting theme to the same level as other controls
* Rename typography to Fonts
* Fix bug: Swatch select should show swatches from the selected palette
* Move capitalize to shared utils
* Add utils for handling nested objects
* Icons panel
* Update code.js
* Move utils around
* Add fit and finish to sidebar panels
* Theme card: Move icons to separate data structure
* Move data to dedicated folder since we now have a lot more of it
* Add default icon families and variants to themes
* Data
* Add `deepEntries()`
* Add Duotone
* Spruce up icons preview
* Use theme's icon family in showcase
* Font cards
* Font cards
* Add `max-inline-size` to preview container
* Remove alternate preview options
* Remove theme subtitle
* Support FA kit codes
* Remove Pro badges from theme cards
* Use panagram preview for Fonts
* Consistent heading and label capitalization
* Classes for different icons-card types
* Update data.js.njk
* Variable style on icon family cards
* Fix Sharp Duotone
* Clean up FA kit code hint
* Hide non-functional Icon Library field
* Fix theme icon heights
* icon variant -> style in theme metadata
* Fix bug with icons defaults not being shown
* More convenient theme defaults
* Fix bug with non updating URL
* Fix bug
* Fix multiplying badges
* Custom docs pages
* Add Duotone icons to Mellow theme
* Fix 404
* Remove "Create" from sidebar
* Fix bug
* Move vue components to `/assets/`, move their CSS with them
* Safari/FF compatibility
* Make panels scrollable again
* Fix extra spacing
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* Reduce build process noise
- Only run 11ty when something has changed within `docs/`
- Only run esbuild if a JS file has changed within
* Update scripts/build.js
Co-authored-by: Konnor Rogers <konnor5456@gmail.com>
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
Co-authored-by: Konnor Rogers <konnor5456@gmail.com>
- Add `:where([class^='wa-theme-'], [class*=' wa-theme-'])` to default `typography.css` since we declare mappings that need to be inherited by other themes.
- Remove declarations that redeclare defaults
- Ensure consistent order
- [Awesome] Switch code font to ui-monospace
Fixes several issues for components using the `display: contents` technique:
- Introduce `--display` CSS property to make it possible to override internal display value of base part.
- Ensure `display: contents` is always applied with `!important` to avoid rendering glitches like the one here
- Ensure non-inherited custom properties are also inherited
- Ensure the `hidden` attribute still works.
* dividing up e-commerce patterns
* started invoice table
* building out the filter
* Initial Commit
* switching machines
* switching machines
* started split image pattern:
* commiting to merge in next
* commiting to switch machines
* upated the product detail patterns
* updated product list patterns
* updated some patterns
* filter work
* added utilities to order history
* added utilities to order-summary
* updated width of container
* switching machines
* switching machines
* fixing conflicts
* editing descriptions
* updated descriptions
* adding some polish
* more filter work
* updated prouct preview
* Revisions to "Product Features"
* "Category Filters" revisions + `wa-placeholder` utility
* cleaned up product list
* tweaked product overview
* tweaked order history
* tweak category preview
* "Checkout Form" revisions
* Re-add `navigation` to "Product Features" carousel
* cleaned up shopping cart
* tweaked order summary
* Add missing file extension
* Fix typo in file name
* Revert checkout form changes in attempt to improve diff
* Reimplement checkout form revisions
* cleaned up checkout form
* Add "What's a Pattern?" and "Using Patterns" to index
* Update category descriptions and headings
* Add docs layout for patterns with stylesheet
* tweaked customer review
* Add checkout form example
* a little more polish
* more tweaks
* switching branches to merge
* created e-commerce index
* unlisted links
* updtated content
* updated content for category preview
* updated order history
* committing to bring branches up to next
* inital commit
* Reorganize app patterns into separate pages
* switching machines
* Add link style utilities
* Refactor product list patterns
* more polish
* Refactor product overview patterns
* switching machines
* Refactor shopping cart patterns
* committing to pull down changes
* updated product preview
* updated image
* updated incentives
* Clean up utility usage and code formatting for category previews
* started updating with style utilities
* Clean up utilities and formatting, replace placeholder text in order history
* updated incentive images
* updated reviews
* added review variant
* more polish
* some heavy duty updates
* removed store navigation
* switching machines
:
* Clean up utility usage and code formatting for order summaries
* Clean up utility usage and code formatting for product previews
* big switchover
* removed old file
* working on sidebar
* updated sidebar
* created info category
* splitting up the old blog page
* a little cleanup and adding detail
* got three done
* updated social share
* Quick formatting adjustment
* initial paywalls
* Use overviews in pattern subcategories (#826)
* Do not error if no pages
* Automatically set parents and tags for patterns
* Update overview.njk
* [WIP] Use overview pages for pattern listings
* Remove explicit parents
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* some newsletter signups
* added login patterns
* reworked feeds'
* a few more
* added a few more
* add more app patterns
* App pattern tweaks (#827)
* Fix `patterns.css` reference
* Tweaks to action panel patterns
* Tweaks to comments patterns
* Progress on data display patterns
* Progress on empty state patterns
* Use email-related data from recent update in `pattern-main` (altered slightly)
* Tweaks to data display patterns
* Tweaks to empty state patterns
* Tweaks to FAQ patterns
* Tweaks to feed patterns
* Tweaks to grid patterns
* Tweaks to pagination patterns
* Tweaks to pricing patterns
* Tweaks to description list patterns
* Tweaks to leaderboard patterns
* Add and update names and descriptions
* Ensure comments fields have labels
* Tweak recent additions
* switching machines
* catching up with next
* added permissions pattern
* switching machines
* added post articles
* having local browset issues
* a few more app patterns
* took out info patterns
* spiffed up the action panels
* gave the action panels a once over
* added content to data display
* updated a few patterns
* clean up a few e-commerce patterns
* added time componen to reviews
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
Co-authored-by: Lea Verou <lea@verou.me>
Co-authored-by: Lindsay M <126139086+lindsaym-fa@users.noreply.github.com>
* First stab at using the Popover API for PE
* fix popup
* First stab at using the Popover API for PE
* fix popup
* Prettier
* Fix TS error
* Remove workaround
* Default to `strategy = fixed` if Popover API is not supported
* Clear out default UA styles for popovers
* Kill `hoist` with fire 🔥
* Refactor
* Update `@floating-ui/dom`
* Fix flipping and shofting
* Fix autosize
* Use `defaultBoundary` for `flip` too
That way we get the previous behavior for it.
* Remove `strategy`, just use `SUPPORTS_POPOVER` check where relevant
* Remove uses of `strategy`
* Use viewport as the default boundary for shifting and autosizing and add `boundary=scroll` to override
---------
Co-authored-by: konnorrogers <konnor5456@gmail.com>
* Generalize CRUD logic to more easily support themes (and other types of entities)
* Decouple data structures managing saved entities (palettes, themes), sidebar update logic, and palette app (and soon themer) by using events
* Simplify logic (a lot of it carried complexity back from the time we did not use uids and/or was overly general)
* `PersistedArray` class to encapsulate arrays persisted in localStorage
* Remove unused `palette.equals()` function
- Moved fixes to bug fixes section
- Linked `allDefined()` and `.wa-cloak` to their docs
- Grouped related bugfixes together
- Moved docs bugfixes to the end (since they are of least interest to users)
* Fix: Parent URL should be undefined if parent is falsy
* Document `docs.11tydata.js` better
* Move `docs/installation.md` to `docs/`, fixes#585
* Just in case
* Make sure components that only appear within page icons are still detected
* Palette icons
* Update theme-icons.css
* Reduce whitespace between swatches
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
* revert structure and styles to fix WA-A #123
* fix WA-A #201
* update changelog
* fix search dialog position so it doesn't jump around
* remove close watcher; fix dialog/drawer backdrop animations
Instead of raw DSD, use a component that pulls in a child template and then goes over the CSS and extracts font-related rules into the document, just once per rule.
This also fixes theme icons in Vue.
* Fix outline for headings that have links
Previously produced blank items because it assumed any link in a heading is an anchor
* Filter unlisted items from overviews
Previously they were filtered only when the card was rendered, so their heading was still shown
* [Overview] Add id to group headings
* Hide headings from empty groups
Should never happen but you never know
* [Overview] Ensure "Other" is always last even when no sorting
- Sidebar, overview listings, breadcrumbs now based on actual parent-child relationships, rather than increasingly outdated heuristics
- parent properties are now generated automatically from the URL structure, and need only be specified to override that default
- Ability to group by page hierarchy in overview pages, where pages that have >= 2 children become categories
Smaller improvements:
- More flexible syntax for specifying the params of overview pages
- [Overviews] Hide group heading if only one group is present
- parentItem and parentUrl properties that can be used on any page
- Alias a collection as the children of a page (useful for "virtual" parents like Layout)
- Do not error if a page card icon is missing
* Initial comment, based on #768
* Add `neutral` color variables
* Add `success`, `warning`, and `danger` variables
* Theme touch-ups
* Remove unused clamped tokens
* Re-add clamped tokens test page, refactor to be based on hue instead of `brand`
- Add ids, use ids to link copy button. No need for client-side script or updating the copy button manually for dynamic code snippets.
- Add button to link to code block
- Slight refactor on copy plugin to use the 11ty API properly
- General infrastructure to support palette tweaking
- Hue shifts per color scale (UI, permalinks, dynamic code snippets)
- Scale overall chroma up/down (UI, permalinks, dynamic code snippets)
- Update contrast ratio tables (styling for contrast up/down/fail could use improvement, but it's a starting point)
- Make sure it works with Turbo (i.e. things don't break when we navigate to another page)
- Drop `base` part (rel #207)
- Add `hint` slot and attribute (it was the only form control that did not support that)
- Refactor `@watch` calls to `updated()` per @claviska's plan for them
* Add `label` attribute and `defaultLabel` getter to option and menu-item, drop `getTextLabel()`
- Add `label` attribute to option and menu-item, closes#698
- [Option] Add `defaultLabel` cached property to both
- [Option] Remove `getTextLabel()` method from both (people can just set `el.label`)
- Refactor: Merge utils to get text content into one more powerful utility function
- Fixed typo in `slot.ts`
.
Add `label` attribute to menu, remove `getTextLabel`
* Update filename
* Initial progress on visual test suite
* Additional tests and descriptions
* Add native callout, add dividers between tables
* Indicate test failures, improve alignment tests
* Split tests into separate files
* Add table scrolling
* Remove irrelevant icon test cases
* Add test failures
* Shorten "Inline Code" > "Code" to prevent wrapping
* Add horizontal orientation to radio button tests
* add orientation to radio group; fixes#613
* fix timing issue that prevents value from being set sometimes
* gimme a break
* make radio button examples horizontal
---------
Co-authored-by: lindsaym-fa <dev@lindsaym.design>
- Add `default` descriptor
- Do not reflect attributes when equal to their default value
- Patch getter return value to return default value when empty
- Use it in button `appearance`
- Added `part="control", fixes#529
- Removed wrapper div which is no longer needed
- Removed `form-control--has-hint` class which is no longer used anywhere
* Initial glassy theme progress
* Add fallback to slider thumb box shadow
* Remove redundant `wa-dark` styles and refactor shadows
* Rename to 'Glossy' since it fits the vibe better
- Minimize needless swaps
- Centralize logic
- Use an actual `<wa-select>` rather than hacking it with `<wa-dropdown>`
- Move shared includes to shared template
- Rewrite critical theme JS
- Refactor of theme picker code
- Utilize view transitions better and use them for color scheme too
- Do not store default value in localStorage
- Removed unused `*-wide` templates
- Fixed#482
* Presentation improvements
* Change `-webkit-text-size-adjust` to supported value (`none` isn't a supported keyword on iOS)
* Try using `text-size-adjust`
* Throwing caution to the wind
* Give up on `text-size-adjust` and add 1-column view
* tweaked the tag component
* updated based on feedback
* updated to remove span
* changed display to initial
* prettier
---------
Co-authored-by: Konnor Rogers <konnor5456@gmail.com>
* skip broken test
* add middleware to follow new stylesheet imports
* fix avatar tests
* update badge tests
* fix button tests
* skip carousel test
* fix checkbox tests
* fix details test
* update radio button tests
* fix input tests
* fix progress bar tests
* update
* fix range tests
* fix select tests
* restore wrapper div to pass a11y tests
* fix switch tests
* fix tag tests
* fix textarea tests
* fix tooltip tests
* skips
* fix tree item tests
* [DRAFT]: test fixes (#421)
* working on some stuff..
* add a small delay for menu-item
* prettier
* add a small delay for menu-item
* prettier
* add a small delay for menu-item
* add a small delay for menu-item
* add a small delay for menu-item
* prettier
* Empty commit
* add a small delay for menu-item
* always build with alpha
* always build with alpha
* move to alpha builds
---------
Co-authored-by: Konnor Rogers <konnor5456@gmail.com>
- Use hueless color tokens so it can be used with variants (and add example)
- Fix hover effect on zebra rows
- Reduce padding a bit
- Shorten utility class
- CSS nesting
- Simplify styles and DOM
- Add `.wa-text-field` utility class
- Eliminate `--border-color` (except when set by appearance utils), `--border-style`, `--border-radius`
Revert "Replace font-size variable with `1em`"
This reverts commit 1ac70f31abe2bab310bbfbdbb3aa5d4498c5648d.
Replace font-size vars with 1em when calculating form control height
As discussed with @lindsaym-fa last week. Hopefully this will eventually help reduce duplication across themes.
Co-Authored-By: Lindsay M <126139086+lindsaym-fa@users.noreply.github.com>
As discussed with @lindsaym-fa
Still unsure about some of these (especially about whether blockquote & details should be separate) but I figured better go ahead and split and we can fine tune later
Co-Authored-By: Lindsay M <126139086+lindsaym-fa@users.noreply.github.com>
- Removed BEM-style naming (the shadow DOM gives you scoping already!)
- Use new size helper
- Organize styles to keep an element’s styles together, using nesting for modifiers
- Removed unused classes
Turns out `prettier-plugin-organize-imports` sorts imports differently than the old one so this will prevent spreading the change across multiple commits whenever we touch a file (and potentially introducing conflicts)
- Reduce class names by using `:has()`, native pseudo-classes, or `[part~=foo]` selectors
- Remove `hasFocus` property since it’s no longer needed
- Move the icon hiding logic to CSS
Shared styles are now added in the base class, rather than having to be repeated in every component.
In the odd case a component does not want the shared styles, it can define a custom `styles` property of its own.
Rn this means we don't get expand animations at all but that’s fine. I think it's fine to have an animation on close and not on open (different user goals — you open to get to the info, you close to get it out of the way, the opening is more urgent)
* initial progress
* spruce up docs sample page
* clean up and organization
* revert extraneous addition to applied.css
* accidentally reverted the wrong change 😅
* take 2 - revert extraneous addition in applied.css
* more cleanup
* Simplify how list of components is exposed to 11ty
No need for functions or computing multiple times, that's what data is for!
* Add attributes to component data
* Cleanup
* Add slug (tagName without wa-)
* Add component reference / cheatsheet
* initial progress
* testing progress
* play with naming, utility classes
* more tweaking and testing
* progress on 12 column grid
* add layout index, start documenting
* documentation progress
* cleanup and doc progress
* more doc progress
* more progress
* final progress hurdle and cleanup
* refining and editing
* remove sandbox
* refactor extra utility classes
* layout index improvements
* change gap modifiers to utility classes
* change align modifiers to utility classes
* move layout examples above fold
* reduce demo markup
* use standard aspect ratio property for wa-frame
* change border-radius modifier to utility class
* rename wa-grid's 'min-inline-size' to 'min-column-size'
* clean up comments
* rename wa-align-* to wa-align-items-*
* break out style utilities from layout
* clean up
* continued ssr work
* continued ssr work
* prettier
* all components now rendering
* everything finally works
* fix type issues
* working on breadcrumb
* working on breadcrumb
* radio group
* convert all tests to ssr
* prettier
* test suite finally passing
* add layout stuff
* add changelog
* fix TS issue
* fix tests
* fixing deploy stuff
* get QR code displaying
* fix tests
* fix tests
* prettier
* condense hydration stuff
* prettier
* comment out range test
* fixing issues
* use base fixtures
* fixing examples
* dont vendor
* fix import of hydration support
* adding notes
* add notesg
* add ssr loader
* fix build
* prettier
* add notes
* add notes
* prettier
* fixing bundled stuff
* remove cdn
* remove cdn
* prettier
* fiixng tests
* prettier
* split jobs??
* prettier
* fix build stuff
* add reset mouse and await aTimeout
* prettier
* fix improper tests
* prettier
* bail on first
* fix linting
* only test form with client
* redundancy on ssr-loader??
* maybe this will work
* prettier
* try callout now
* fix form.test.ts
* fix form.test.ts
* prettier
* fix forms
* fix forms
* try again
* prettier
* add some awaits
* prettier
* comment out broken SSR tests
* prettier
* comment out broken SSR tests
* prettier
* dont skip in CI
* upgrade playwright to beta
* prettier
* try some trickery
* try some trickery
* await updateComplete
* try to fix form.test.ts
* import hydrateable elements 1 time
* prettier
* fix input defaultValue issues
* fix form controls to behave like their native counterpartS
* add changelog entry
* prettier
* fix unexpected behavior with range / button
* add test for min / maxlength
* prettier
* fix accessibility issue in tab group
* add changelog entry
gp
* fix swatches for things that dont have background colors
* first pass at starlight
* converting to starlight
* working on converting to starlight
* working on data
* watch custom-elements.json
* turn on pagefind
* add component meta data
* fix renderings / overrides.
* fix mdx logo
* continue starlight work
* building site
* get global styles + reloads working
* themer fixes
* adding additional headings
* working on dynamic content
* have TableOfContents.astro push to TOC
* working on code stuff
* remove code preview
* deploy
* add patch package
* patch in build
* patch in build
* remove {% raw %} calls
* convert to starlight...complete
* prettier
* update lockfile
* merge main
* fix index.mdx
* prettier'
* fix small things
* docs updates
* add dark mode shortcut
* prettier
* prettier
* prettier
* remove pagefind from public
* add twitteR
* prettier
* fix tests
* prettier
* remove square, stretch, and squish spacing tokens
* remove units from base tokens
* rename corner tokens with t-shirt size scale
* rename 'font-size' tokens to 'size'
* rename 'neutral' primitives to 'base'
* remove black and white tokens
* improve 'form-controls' tokens
* reintroduce granular focus ring tokens
* fix themer styles
* tweak shadow styles
* improve naming and scope of foundational colors
* overhaul color naming and add new themes
* more classic sl component styles
* make 'chic' theme dark by default
* adjust table row colors
* remove deprecated properties from 'classic' theme
* remove mistakenly committed stylesheets
* revert adjustment to space properties
* delete web-types.json
* revert "rename 'font-size' tokens to 'size'"
* Move custom properties related to shadows and borders to separate stylesheets
* Change base values and themer calculations related to shadows and borders to be unitless
* Add low-level custom properties for alert, button, card, input, select, switch, and textarea
* Add generic guidance for authoring custom properties to the Contributing docs
* [RFC] Proof-of-concept commit for submenu support
This is a Request For Comments to seek directional guidance towards
implementing the submenu slot of menu-item.
Includes:
- SubmenuController to manage event listeners on menu-item.
- Example usage in menu-item documentation.
- Trivial tests to check rendering.
Outstanding questions include:
- Accessibility concerns. E.g. where to handle 'ArrowRight',
'ArrowLeft'?
- Should selection of menu-item denoting submenu be possible or
customizable?
- How to parameterize contained popup?
- Implementation concerns:
- Use of ref / id
- delegation of some rendering to the controller
- What to test
Related to [#620](https://github.com/shoelace-style/shoelace/issues/620).
* Update submenu-controller.ts
Removed extraneous `console.log()`.
* PoC working of ArrowRight to focus on submenu.
* Revert "PoC working of ArrowRight to focus on submenu."
(Didn't mean to publish this.)
This reverts commit be04e9a221.
* [WIP] Submenu WIP continues.
- Submenus now close on change-of-focus, not a timeout.
- Keyboard navigation support added.
- Skidding fix for better alignment.
- Submenu documentation moved to Menu page.
- Tests for accessibility, right and left arrow keys.
* Cleanup: Removed dead code and dead code comments.
* style: Eslint warnings and errors fixed. npm run verify now passes.
* fix: 2 changes to menu / submenu on-click behavior:
1. Close submenu on click explicitly, so this occurs even if the menu is
not inside of an sl-dropdown.
2. In menu, ignore clicks that do not explicitly target a menu-item.
Clicks that were on (e.g. a menu-border) were emitting select events.
* fix: Prevent menu's extraneous Enter / space key propagation.
Menu's handleKeyDown calls item.click (to emit the selection).
Propagating the keyboard event on Enter / space would the cause re-entry
into a submenu, so prevent the needless propagation.
* Submenu tweaks ...
- 100 ms delay when opening submenus on mouseover
- Shadows added
- Distance added to popup to have submenus overlap menu slightly.
* polish up submenu stuff
* stay highlighted when submenu is open
* update changelog
* resolve feedback
---------
Co-authored-by: Bryce Moore <bryce.moore@gmail.com>
* Never select tree items when clicking the chevron
This changes the behaviour of sl-tree so that clicking on the expand/collapse icon will not select/deselect the item, only toggle it's expanded state.
* Refactor: inline SlTree.syncTreeItems
This was only called from 2 places, and they each had different
behaviour anyways.
* SlTree: separate expand/collapse from selection
This makes 'multi' and 'single' mode consistent with each other, and
with native file managers.
* feat(clipboard): add new component sl-clipboard
* using slots
* using a single copyStatus
* feat(clipboard): support inputs/textarea/links and shadow dom
* fix(clipboard): add area-live to announce copied
* feat(clipboard): support any component with a value property
* initial attempt at not auto defining
* add files with -
* continued work on removing auto-define
* fix component definitions
* update with new tag stuff
* fix lots of things
* fix improper scoped elements
* working through side effects
* continued react wrapper work
* update changelog
* formatting
* fixes
* update changelog
* lint / formatting
* fix version injection
* fix version injection, work on test
* fix version injection, work on test
* fix merge conflicts
* fix jsdoc null issue
* fix templates
* use exports
* working on tests
* working on registration mocking
* fix customElements test
* linting
* fix some test stuff
* clean up test
* clean up comment
* rename scopedElements to dependencies
* linting / formatting
* linting / formatting
* mark all packages external and still bundle
* set bundle false
* set bundle true
* dont minify
* fix merge conflicts
* use built shoelace-element
* fix lint errors
* prettier
* appease eslint
* appease eslint gods
* appease eslint gods
* appease eslint gods
* appease eslint gods
* add shoelace-autoloader
* move it all into 1 function
* add exportmaps note
* prettier
* add jsdelivr entrypoint
* read as utf8
* update docs with .component.js importS
* prettier
* Move keydown handler for sl-drawer back to base div
This restores the stacking behaviour of drawers
See: #1457
* Autofocus panel of sl-drawer when it is open on firstUpdate
* Rename SlSlideChange for consistency with other events
* Setup React event types for events used by Shoelace components
Means that consumers of Shoelace via the React wrapper will be able to
use callback methods with the correct event type, instead of having to
rely on casting and friends when using Typescript.
* Add docs demonstrating importing event types for React callbacks
* add modal tab tracking
* prettier
* sort by tabindex
* sort by tabindex
* add a dialog test case for shadow roots
* add a changelog note
* add a changelog note
* prettier + test fixes
* prettier + test fixes
* Add tests for qr-code
* Fix a small bug in qr-code
The background color was not passed to the
qr code
---------
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
The current statement is incorrect and will result in
`Module not found: Package path ./dist/shoelace is not exported from package /your/path/to/node_modules/@shoelace-style/shoelace (see exports field in /your/path/to/node_modules/@shoelace-style/shoelace/package.json)`
* Added tests for sl-split-panel
test for horizontal arrangement
* Added tests for sl-split-panel
tests for vertical arrangement
---------
Co-authored-by: stefanie.hellgartner <stefanie.hellgartner@in-tech.com>
* add regression test for checkbox focusing
* change number of checkboxes / switches
* change max-height to 400px so it fails
* re-add positon: relative;
* Improve performance of sl-icon by caching later
* Fixed error handling
* Don't use requestInclude in sl-icon
* Separate sl-icon errors into cacheable and retryable errors
* Fix acessability issue
* Additionally adapted the test
* Added more accessability tests
* Updated the testing documentation
to take the fact that accessability checks cover only
rendered content into account
---------
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
Did not manage to check
that the properties are correctly passed
to the animation api at this point so this
stays a blackbox test
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
The reason for the problems is that the error event does
not escape from the shadow dom.
Thus it cannot be awaited for in the test
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
* fix(carousel): don't resume autoplay if interacting
* fix(carousel): wrap pagination items
* chore(carousel): add unit tests
* feat(carousel): more reactive pagination dots
* fix(carousel): trigger scrollend when user scroll exactly over a snap point
* Resize observer sometimes throws errors which
are nothing to worry about, see also the corresponding
comment on tab-group.test.ts
* Unfortunately, the web testing library installs an
error event handler which takes precedence before the
event handlers installed in the tests
(see node_modules/@web/browser-logs/dist/logUncaughtErrors.js)
* the only possibility to avoid these null logs is to install
an error event handler at an even earlier place
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
* Improved tests for SlAlert
* added more test for coverage
* Grouped tests in multiple subgroups
* remove executing only one tests
* Fix the now executing tests
---------
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
* #1163 - added read-only properties 'validity' and 'validationMessage' to all nine form controls
* #1163 - added base support for showing form validation messages below the form controls
* #1163 - animated validation errors in demo
* #1181 - Removed all previous changes that have been validation error specific
* Started with 'Inline validation' demo / fixed merge issues / etc.
* #1181 - continued work on missing form validation features
* #1181 - enhanced validation support for SlColorPicker / some cleanup
* #1181 - fixed CSS issues
* #1181 - fixed again CSS issues
* '1181 - added form validation features finally working
* #1181 - bug fixes
* #1181 - fixed open issues / added API doc comments
* #1181 - updated inline validation demos / removed some legacy code
* #1181 - finished invalid form validation example
* #1181 - added tests / several bugfixes
* #1181 - fixed typos etc.
* #1181 - tests
* #1181 - tests
* #1181 - tests
* dropdown filtered menu items
* updated filter, added test
- updated filter to match menu getAllItems private method
- added test
---------
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* remove duplicate test
* Add tests for sl-tab-group -- initial round of tests
* use individual fixtures for each test
* extract mocks + utility functions in external files
* remove unnecessary internals of intersection observer from the mock
* added first test on scroll buttons
* add scrolling tests
* remove resize observer mock
Resize observer is triggered but waiting for element
to be updated is not enough. You need to free the main thread
with the test for some time
* Also removed intersection observer mock
By waiting long enough for the things to happen automatically
* Fix problems with resize observer
These problems appeared after npm ci but (according
to the sources linked in the comments) unproblematic
* Handle merge request comments
* replace custom wait function with corresponding function
from openwc/testing
* Extracted waitForScrollingToEnd and isElementVisibleFromScrolling into
dedicated files to be reused
* Improve queryByTestId --> make it usable for more complex values
* Add js docs
* run lint fix
* Added tests for selecting a tab by click
* added further tests for tab group selection
* use Promise<void> instead of Promise<any>
to avoid eslint errors
---------
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
* Initial example of a JSON schema and converter for design tokens
* Clean up script and relocate file
* Update token JSON format and finish build process
* removed checked and indeterminate parts from doc
* Revert "removed checked and indeterminate parts from doc"
This reverts commit 5e702387e1ace4e5d6b424f861df8e6a3a1a4fdd.
* control--checked & control--indeterminate parts
* sl-color-picker use lib '@ctrl/tinycolor' instead of 'color'
typescript, esm and smaller
* parseColor adjustments
removed normalizeColorString and other tweaks
* added hsv format
* fixed const
* Fix mapping in exports
Fixes#1019
- Add correct mapping for public entrypoints.
* Remove shoelace.js from from exports list
Should still works fine while importing this way: import { thing } from '@shoelace-style/shoelace';
* added stepUp and stepDown to sl-range
* step function & default props tests for sl-range
* stepUp, stepDown & showPicker functions for input
* step functions & default props tests for sl-input
* made name and placeholder default to empty string
* updated changelog
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
add check to input component if japanese character is chosen by pressing enter key and prevent form submitting
Co-authored-by: VitaliyMaznyi <vitalii.maznyi@fasterthanlight.me>
* Added tests for sl-relative-time
* Solves a blinker which appears only when I run
the full test suite: Chromium and webkit are fine
but sometimes there is this one error on firefox
for the disabled test of the menu item (saying there
was a timeout waiting). Did not happen again after
doing the change.
Co-authored-by: Dominikus Hellgartner <dominikus.hellgartner@gmail.com>
* move component description from docs to component
* use component description in docs
* add style for lead sentence, keep bc for not updated components
* run `npm prettier`
* render summary as part of the header
* add `title` as another custom tag for JSDoc
* render components title in header
* provide possibility to render components "description" into docs with `[component-description:COMPONENT_NAME]`
* the meta summary should be rendered into header too
* Avoid bubbling events for sl-include
I ran into an issue where icons inside of an HTML include were dispatching `sl-load` events, which was causing my `sl-include` event handler to run multiple times. By adding these guards, we ensure only events immediately dispatched by the element itself will be handled.
* Use the correct event variable
The description for the checkbox's value attribute is currently "the checkbox's value attribute." I think we can do better than that, especially considering anyone who hasn't worked with old-school HTML forms that POST to the URL in the `action` attribute is unlikely to know why a checkbox has a value and that value is not boolean.
While I was here I improved a couple of other descriptions. If there's an interest, I can expand this PR to update all of the properties in all controls where the description is tautological.
* Tooltip: Recalculate target after slotchange
The tooltip's positioning breaks after a slotchange, unless the tooltips target is recalculated.
* Update src/components/tooltip/tooltip.test.ts
Co-authored-by: Cory LaViska <cory@abeautifulsite.net>
* initial button tests and setup helpers
* fix as many linting errors as I could
* switch back to regular fixtures
* test(button|button-group|divider|format-bytes) add tests for more components
* add tests for format util components
* finish format-number tests
* remove unnecessary ignore
@@ -35,7 +35,7 @@ This Code of Conduct applies within all project spaces, and it also applies when
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at cory@abeautifulsite.net. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@fontawesome.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
# # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name:Client Tests
on:
workflow_dispatch:
push:
branches:[next]
pull_request:
branches:[next]
jobs:
client_test:
runs-on:ubuntu-latest
strategy:
matrix:
node-version:[20.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name:Node.js CI
on:
push:
branches:[next]
pull_request:
branches:[next]
jobs:
build:
runs-on:ubuntu-latest
strategy:
matrix:
node-version:[14.x, 16.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name:SSR Tests
on:
# push:
# branches: [next]
workflow_dispatch:
jobs:
ssr_test:
runs-on:ubuntu-latest
strategy:
matrix:
node-version:[20.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Shoemakers, or "Shoelace developers," can use this documentation to learn how to build Shoelace from source. You will need Node >= 14.15 to build and run the project locally.
Developers can use this documentation to learn how to build Web Awesome from source. You will need Node.js 14.17 or later to build and run the project locally.
**You don't need to do any of this to use Shoelace!** This page is for people who want to contribute to the project, tinker with the source, or create a custom build of Shoelace.
**You don't need to do any of this to use Web Awesome!** This page is for people who want to contribute to the project, tinker with the source, or create a custom build of Web Awesome.
If that's not what you're trying to do, the [documentation website](https://shoelace.style) is where you want to be.
If that's not what you're trying to do, the [documentation website](https://webawesome.com) is where you want to be.
### What are you using to build Shoelace?
### What are you using to build Web Awesome?
Components are built with [LitElement](https://lit-element.polymer-project.org/), a custom elements base class that provides an intuitive API and reactive data binding. The build is a custom script with bundling powered by [esbuild](https://esbuild.github.io/).
Components are built with [Lit](https://lit.dev/), a custom elements base class that provides an intuitive API and reactive data binding. The build is a custom script with bundling powered by [esbuild](https://esbuild.github.io/).
### Understanding the Web Awesome monorepo
Web Awesome uses [npm workspaces](https://docs.npmjs.com/cli/v11/using-npm/workspaces) for its monorepo structure and is fairly minimal in what it provides.
By using npm workspaces and a monorepo structure, we can get consistent builds, shared configurations, and reduced duplication across repositories which reduces regressions and forces consistency across `webawesome`, `webawesome-pro`, and `webawesome-app`.
Generally, if you plan to only work with the free version of `webawesome` it is easiest to go to `packages/webawesome` and run all commands from there.
### Where do npm dependencies go?
Any dependencies intended to be used across all packages (i.e., `prettier`, `eslint`) that are **not** used at runtime should be in the root `devDependencies` of `package.json`.
```bash
npm install -D -w prettier
```
Any dependencies that will be used at runtime by a package should be part of the specific package's `dependencies` such as `lit`. This is required because if that dependency is not in the `packages/*/package.json`, it will not be installed when used via npm.
Individual packages are also free to install `devDependencies` as needed as long as they are specific to that package only.
To install a package specific to a Web Awesome package, change your working directory to that package's root (i.e., `cd packages/webawesome && npm install <package-name>`).
### Forking the Repo
Start by [forking the repo](https://github.com/shoelace-style/shoelace/fork) on GitHub, then clone it locally and install dependencies.
Start by [forking the repo](https://github.com/shoelace-style/webawesome/fork) on GitHub, then clone it locally and install dependencies.
Once you've cloned the repo, run the following command.
Once you've cloned the repo, run the following command from the respective directory within `packages/*`.
```bash
cd packages/webawesome
npm start
```
This will spin up the Shoelace dev server. After the initial build, a browser will open automatically. There is currently no hot module reloading (HMR), as browser's don't provide a way to reregister custom elements, but most changes to the source will reload the browser automatically.
The documentation is powered by Docsify, which uses raw markdown files to generate pages. As such, no static files are built for the docs.
This will spin up the dev server. After the initial build, a browser will open automatically. There is currently no hot module reloading (HMR), as browsers don't provide a way to reregister custom elements, but most changes to the source will reload the browser automatically.
### Building
To generate a production build, run the following command.
```bash
cd packages/webawesome
npm run build
```
You can also run `npm run build:serve` to start an [`http-server`](https://www.npmjs.com/package/http-server) instance on `http://localhost:4000` after the build completes, so you can preview the production build.
### Creating New Components
To scaffold a new component, run the following command, replacing `sl-tag-name` with the desired tag name.
To scaffold a new component, run the following command, replacing `wa-tag-name` with the desired tag name.
```bash
npm run create sl-tag-name
cd packages/webawesome
npm run create wa-tag-name
```
This will generate a source file, a stylesheet, and a docs page for you. When you start the dev server, you'll find the new component in the "Components" section of the sidebar.
### Adding additional packages
Right now the only additional packages are in private repositories.
To add additional packages from other repositories, run `git clone <url> packages/<package-name>` to clone your repo into `packages/`.
Make sure to run `npm install` at the root of the monorepo after adding your package!
### Contributing
Shoelace is an open source project and contributions are encouraged! If you're interesting in contributing, please review the [contribution guidelines](CONTRIBUTING.md) first.
Web Awesome is an open source project and contributions are encouraged! If you're interesting in contributing, please review the [contribution guidelines](CONTRIBUTING.md) first.
## License
Shoelace is designed in New Hampshire by [Cory LaViska](https://twitter.com/claviska). It’s available under the terms of the MIT license.
Designing, developing, and supporting this library requires a lot of time, effort, and skill. I’d like to keep it open source so everyone can use it, but that doesn’t provide me with any income.
**Therefore, if you’re using my software to make a profit,** I respectfully ask that you help [fund its development](https://github.com/sponsors/claviska) by becoming a sponsor. There are multiple tiers to choose from with benefits at every level, including prioritized support, bug fixes, feature requests, and advertising.
👇 Your support is very much appreciated! 👇
- [Become a sponsor](https://github.com/sponsors/claviska)
- [Star on GitHub](https://github.com/shoelace-style/shoelace/stargazers)
- [Follow on Twitter](https://twitter.com/shoelace_style)
Whether you're building Shoelace or building something _with_ Shoelace — have fun creating! 🥾
Web Awesome is available under the terms of the [MIT License](LICENSE.md).
This alert will automatically hide itself after three seconds, unless you interact with it.
</SlAlert>
</div>
<style>{css}</style>
</>
);
};
```
### Toast Notifications
To display an alert as a toast notification, or "toast", create the alert and call its `toast()` method. This will move the alert out of its position in the DOM and into [the toast stack](#the-toast-stack) where it will be shown. Once dismissed, it will be removed from the DOM completely. To reuse a toast, store a reference to it and call `toast()` again later on.
You should always use the `closable` attribute so users can dismiss the notification. It's also common to set a reasonable `duration` when the notification doesn't require acknowledgement.
<strong>Your account has been deleted</strong><br />
We're very sorry to see you go!
</SlAlert>
</>
);
};
```
### Creating Toasts Imperatively
For convenience, you can create a utility that emits toast notifications with a function call rather than composing them in your HTML. To do this, generate the alert with JavaScript, append it to the body, and call the `toast()` method as shown in the example below.
The toast stack is a fixed position singleton element created and managed internally by the alert component. It will be added and removed from the DOM as needed when toasts are shown. When more than one toast is visible, they will stack vertically in the toast stack.
By default, the toast stack is positioned at the top-right of the viewport. You can change its position by targeting `.sl-toast-stack` in your stylesheet. To make toasts appear at the top-left of the viewport, for example, use the following styles.
```css
.sl-toast-stack {
left: 0;
right: auto;
}
```
?> By design, it is not possible to show toasts in more than one stack simultaneously. Such behavior is confusing and makes for a poor user experience.
alt="Animation of untied shoes walking on pavement"
/>
);
```
?> This component uses `<canvas>` to draw freeze frames, so images are subject to [cross-origin restrictions](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image).
Animate elements declaratively with nearly 100 baked-in presets, or roll your own with custom keyframes. Powered by the [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API).
To animate an element, wrap it in `<sl-animation>` and set an animation `name`. The animation will not start until you add the `play` attribute. Refer to the [properties table](#properties) for a list of all animation options.
?> The animation will only be applied to the first child element found in `<sl-animation>`.
## Examples
### Animations & Easings
This example demonstrates all of the baked-in animations and easings. Animations are based on those found in the popular [Animate.css](https://animate.style/) library.
Use an [Intersection Observer](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) to control the animation when an element enters or exits the viewport. For example, scroll the box below in and out of your screen. The animation stops when the box exits the viewport and restarts each time it enters the viewport.
Animations won't play until you apply the `play` attribute. You can omit it initially, then apply it on demand such as after a user interaction. In this example, the button will animate once every time the button is clicked.
Like [images](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img), you should always provide `alt` text for avatars as alternate text for assistive devices.
```html preview
<sl-avatar label="User avatar"></sl-avatar>
```
```jsx react
import { SlAvatar } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlAvatar label="User avatar" />
);
```
## Examples
### Images
To use an image for the avatar, set the `image` and `alt` attributes. This will take priority and be shown over initials and icons.
label="Avatar of a gray tabby kitten looking down"
/>
);
```
### Initials
When you don't have an image to use, you can set the `initials` attribute to show something more personalized than an icon.
```html preview
<sl-avatar initials="SL" label="Avatar with initials: SL"></sl-avatar>
```
```jsx react
import { SlAvatar } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlAvatar initials="SL" label="Avatar with initials: SL" />
);
```
### Custom Icons
When no image or initials are set, an icon will be shown. The default avatar shows a generic "user" icon, but you can customize this with the `icon` slot.
```html preview
<sl-avatar label="Avatar with an image icon">
<sl-icon slot="icon" name="image"></sl-icon>
</sl-avatar>
<sl-avatar label="Avatar with an archive icon">
<sl-icon slot="icon" name="archive"></sl-icon>
</sl-avatar>
<sl-avatar label="Avatar with a briefcase icon">
<sl-icon slot="icon" name="briefcase"></sl-icon>
</sl-avatar>
```
```jsx react
import { SlAvatar, SlIcon } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<>
<SlAvatar label="Avatar with an image icon">
<SlIcon slot="icon" name="image" />
</SlAvatar>
<SlAvatar label="Avatar with an archive icon">
<SlIcon slot="icon" name="archive" />
</SlAvatar>
<SlAvatar label="Avatar with a briefcase icon">
<SlIcon slot="icon" name="briefcase" />
</SlAvatar>
</>
);
```
### Shapes
Avatars can be shaped using the `shape` attribute.
import { SlBadge } from '@shoelace-style/shoelace/dist/react';
const css = `
.badge-pulse sl-badge:not(:last-of-type) {
margin-right: 1rem;
}
`;
const App = () => (
<>
<div className="badge-pulse">
<SlBadge variant="primary" pill pulse>1</SlBadge>
<SlBadge variant="success" pill pulse>1</SlBadge>
<SlBadge variant="neutral" pill pulse>1</SlBadge>
<SlBadge variant="warning" pill pulse>1</SlBadge>
<SlBadge variant="danger" pill pulse>1</SlBadge>
</div>
<style>{css}</style>
</>
);
```
### With Buttons
One of the most common use cases for badges is attaching them to buttons. To make this easier, badges will be automatically positioned at the top-right when they're a child of a button.
```html preview
<sl-button>
Requests
<sl-badge pill>30</sl-badge>
</sl-button>
<sl-button style="margin-left: 1rem;">
Warnings
<sl-badge variant="warning" pill>8</sl-badge>
</sl-button>
<sl-button style="margin-left: 1rem;">
Errors
<sl-badge variant="danger" pill>6</sl-badge>
</sl-button>
```
```jsx react
import { SlBadge, SlButton } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<>
<SlButton>
Requests
<SlBadge pill>30</SlBadge>
</SlButton>
<SlButton style={{ marginLeft: '1rem' }}>
Warnings
<SlBadge variant="warning" pill>8</SlBadge>
</SlButton>
<SlButton style={{ marginLeft: '1rem' }}>
Errors
<SlBadge variant="danger" pill>6</SlBadge>
</SlButton>
</>
);
```
### With Menu Items
When including badges in menu items, use the `suffix` slot to make sure they're aligned correctly.
Breadcrumbs provide a group of links so users can easily navigate a website's hierarchy.
Breadcrumbs are usually placed before a page's main content with the current page shown last to indicate the user's position in the navigation.
```html preview
<sl-breadcrumb>
<sl-breadcrumb-item>Catalog</sl-breadcrumb-item>
<sl-breadcrumb-item>Clothing</sl-breadcrumb-item>
<sl-breadcrumb-item>Women's</sl-breadcrumb-item>
<sl-breadcrumb-item>Shirts & Tops</sl-breadcrumb-item>
</sl-breadcrumb>
```
```jsx react
import { SlBreadcrumb, SlBreadcrumbItem } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlBreadcrumb>
<SlBreadcrumbItem>Catalog</SlBreadcrumbItem>
<SlBreadcrumbItem>Clothing</SlBreadcrumbItem>
<SlBreadcrumbItem>Women's</SlBreadcrumbItem>
<SlBreadcrumbItem>Shirts & Tops</SlBreadcrumbItem>
</SlBreadcrumb>
);
```
## Examples
### Breadcrumb Links
By default, breadcrumb items are rendered as buttons so you can use them to navigate single-page applications. In this case, you'll need to add event listeners to handle clicks.
For websites, you'll probably want to use links instead. You can make any breadcrumb item a link by applying an `href` attribute to it. Now, when the user activates it, they'll be taken to the corresponding page — no event listeners required.
It's often helpful to have a button that works like a link. This is possible by setting the `href` attribute, which will make the component render an `<a>` under the hood. This gives you all the default link behavior the browser provides (e.g. <kbd>CMD/CTRL/SHIFT + CLICK</kbd>) and exposes the `target` and `download` attributes.
?> When a `target` is set, the link will receive `rel="noreferrer noopener"` for [security reasons](https://mathiasbynens.github.io/rel-noopener/).
### Setting a Custom Width
As expected, buttons can be given a custom width by setting the `width` attribute. This is useful for making buttons span the full width of their container on smaller screens.
Use the `caret` attribute to add a dropdown indicator when a button will trigger a dropdown, menu, or popover.
```html preview
<sl-button size="small" caret>Small</sl-button>
<sl-button size="medium" caret>Medium</sl-button>
<sl-button size="large" caret>Large</sl-button>
```
```jsx react
import { SlButton } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<>
<SlButton size="small" caret>Small</SlButton>
<SlButton size="medium" caret>Medium</SlButton>
<SlButton size="large" caret>Large</SlButton>
</>
);
```
### Loading
Use the `loading` attribute to make a button busy. The width will remain the same as before, preventing adjacent elements from moving around. Clicks will be suppressed until the loading state is removed.
This example demonstrates how to style buttons using a custom class. This is the recommended approach if you need to add additional variations. To customize an existing variation, modify the selector to target the button's `variant` attribute instead of a class (e.g. `sl-button[variant="primary"]`).
```html preview
<sl-button class="pink">Pink Button</sl-button>
<style>
sl-button.pink::part(base) {
/* Set design tokens for height and border width */
Checkboxes allow the user to toggle an option on or off.
```html preview
<sl-checkbox>Checkbox</sl-checkbox>
```
```jsx react
import { SlCheckbox } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlCheckbox>Checkbox</SlCheckbox>
);
```
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Checked
Use the `checked` attribute to activate the checkbox.
```html preview
<sl-checkbox checked>Checked</sl-checkbox>
```
```jsx react
import { SlCheckbox } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlCheckbox checked>Checked</SlCheckbox>
);
```
### Indeterminate
Use the `indeterminate` attribute to make the checkbox indeterminate.
import { SlColorPicker } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlColorPicker />
);
```
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Opacity
Use the `opacity` attribute to enable the opacity slider. When this is enabled, the value will be displayed as HEXA, RGBA, or HSLA based on `format`.
```html preview
<sl-color-picker opacity></sl-color-picker>
```
```jsx react
import { SlColorPicker } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlColorPicker opacity />
);
```
### Formats
Set the color picker's format with the `format` attribute. Valid options include `hex`, `rgb`, and `hsl`. Note that the color picker's input will accept any parsable format (including CSS color names) regardless of this option.
To prevent users from toggling the format themselves, add the `no-format-toggle` attribute.
Details show a brief summary and expand to show additional content.
```html preview
<sl-details summary="Toggle Me">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</sl-details>
```
```jsx react
import { SlDetails } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlDetails summary="Toggle Me">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</SlDetails>
);
```
## Examples
### Disabled
Use the `disable` attribute to prevent the details from expanding.
```html preview
<sl-details summary="Disabled" disabled>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</sl-details>
```
```jsx react
import { SlDetails } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlDetails summary="Disabled" disabled>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</SlDetails>
);
```
### Grouping Details
Details are designed to function independently, but you can simulate a group or "accordion" where only one is shown at a time by listening for the `sl-show` event.
```html preview
<div class="details-group-example">
<sl-details summary="First" open>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</sl-details>
<sl-details summary="Second">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</sl-details>
<sl-details summary="Third">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
By design, a dialog's height will never exceed that of the viewport. As such, dialogs will not scroll with the page ensuring the header and footer are always accessible to the user.
By default, dialogs will close when the user clicks the close button, clicks the overlay, or presses the <kbd>Escape</kbd> key. In most cases, the default behavior is the best behavior in terms of UX. However, there are situations where this may be undesirable, such as when data loss will occur.
To keep the dialog open in such cases, you can cancel the `sl-request-close` event. When canceled, the dialog will remain open and pulse briefly to draw the user's attention to it.
By default, the dialog's panel will gain focus when opened. This allows a subsequent tab press to focus on the first tabbable element within the dialog. To set focus on a different element, listen for and cancel the `sl-initial-focus` event.
```html preview
<sl-dialog label="Dialog" class="dialog-focus">
<sl-input placeholder="I will have focus when the dialog is opened"></sl-input>
import { SlDivider } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<>
Above
<SlDivider style={{ '--spacing': '2rem' }} />
Below
</>
);
```
### Vertical
Add the `vertical` attribute to draw the divider in a vertical orientation. The divider will span the full height of its container. Vertical dividers work especially well inside of a flex container.
By default, the drawer slides out of its [containing block](https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#Identifying_the_containing_block), which is usually the viewport. To make the drawer slide out of its parent element, add the `contained` attribute and `position: relative` to the parent.
By design, a drawer's height will never exceed 100% of its container. As such, drawers will not scroll with the page to ensure the header and footer are always accessible to the user.
By default, drawers will close when the user clicks the close button, clicks the overlay, or presses the <kbd>Escape</kbd> key. In most cases, the default behavior is the best behavior in terms of UX. However, there are situations where this may be undesirable, such as when data loss will occur.
To keep the drawer open in such cases, you can cancel the `sl-request-close` event. When canceled, the drawer will remain open and pulse briefly to draw the user's attention to it.
By default, the drawer's panel will gain focus when opened. This allows the first tab press to focus on the first tabbable element within the drawer. To set focus on a different element, listen for and cancel the `sl-initial-focus` event.
```html preview
<sl-drawer label="Drawer" class="drawer-focus">
<sl-input placeholder="I will have focus when the drawer is opened"></sl-input>
Dropdowns expose additional content that "drops down" in a panel.
Dropdowns consist of a trigger and a panel. By default, activating the trigger will expose the panel and interacting outside of the panel will close it.
Dropdowns are designed to work well with [menus](/components/menu) to provide a list of options the user can select from. However, dropdowns can also be used in lower-level applications (e.g. [color picker](/components/color-picker) and [select](/components/select)). The API gives you complete control over showing, hiding, and positioning the panel.
When dropdowns are used with [menus](/components/menu), you can listen for the `sl-select` event to determine which menu item was selected. The menu item element will be exposed in `event.detail.item`. You can set `value` props to make it easier to identify commands.
Alternatively, you can listen for the `click` event on individual menu items. Note that, using this approach, disabled menu items will still emit a `click` event.
The preferred placement of the dropdown can be set with the `placement` attribute. Note that the actual position may vary to ensure the panel remains in the viewport.
```html preview
<sl-dropdown placement="top-start">
<sl-button slot="trigger" caret>Edit</sl-button>
<sl-menu>
<sl-menu-item>Cut</sl-menu-item>
<sl-menu-item>Copy</sl-menu-item>
<sl-menu-item>Paste</sl-menu-item>
<sl-divider></sl-divider>
<sl-menu-item>Find</sl-menu-item>
<sl-menu-item>Replace</sl-menu-item>
</sl-menu>
</sl-dropdown>
```
```jsx react
import {
SlButton,
SlDivider,
SlDropdown,
SlMenu,
SlMenuItem
} from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlDropdown placement="top-start">
<SlButton slot="trigger" caret>Edit</SlButton>
<SlMenu>
<SlMenuItem>Cut</SlMenuItem>
<SlMenuItem>Copy</SlMenuItem>
<SlMenuItem>Paste</SlMenuItem>
<SlDivider />
<SlMenuItem>Find</SlMenuItem>
<SlMenuItem>Replace</SlMenuItem>
</SlMenu>
</SlDropdown>
);
```
### Distance
The distance from the panel to the trigger can be customized using the `distance` attribute. This value is specified in pixels.
```html preview
<sl-dropdown distance="30">
<sl-button slot="trigger" caret>Edit</sl-button>
<sl-menu>
<sl-menu-item>Cut</sl-menu-item>
<sl-menu-item>Copy</sl-menu-item>
<sl-menu-item>Paste</sl-menu-item>
<sl-divider></sl-divider>
<sl-menu-item>Find</sl-menu-item>
<sl-menu-item>Replace</sl-menu-item>
</sl-menu>
</sl-dropdown>
```
```jsx react
import {
SlButton,
SlDivider,
SlDropdown,
SlMenu,
SlMenuItem
} from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlDropdown distance={30}>
<SlButton slot="trigger" caret>Edit</SlButton>
<SlMenu>
<SlMenuItem>Cut</SlMenuItem>
<SlMenuItem>Copy</SlMenuItem>
<SlMenuItem>Paste</SlMenuItem>
<SlDivider />
<SlMenuItem>Find</SlMenuItem>
<SlMenuItem>Replace</SlMenuItem>
</SlMenu>
</SlDropdown>
);
```
### Skidding
The offset of the panel along the trigger can be customized using the `skidding` attribute. This value is specified in pixels.
```html preview
<sl-dropdown skidding="30">
<sl-button slot="trigger" caret>Edit</sl-button>
<sl-menu>
<sl-menu-item>Cut</sl-menu-item>
<sl-menu-item>Copy</sl-menu-item>
<sl-menu-item>Paste</sl-menu-item>
<sl-divider></sl-divider>
<sl-menu-item>Find</sl-menu-item>
<sl-menu-item>Replace</sl-menu-item>
</sl-menu>
</sl-dropdown>
```
```jsx react
import {
SlButton,
SlDivider,
SlDropdown,
SlMenu,
SlMenuItem
} from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlDropdown skidding={30}>
<SlButton slot="trigger" caret>Edit</SlButton>
<SlMenu>
<SlMenuItem>Cut</SlMenuItem>
<SlMenuItem>Copy</SlMenuItem>
<SlMenuItem>Paste</SlMenuItem>
<SlDivider />
<SlMenuItem>Find</SlMenuItem>
<SlMenuItem>Replace</SlMenuItem>
</SlMenu>
</SlDropdown>
);
```
### Hoisting
Dropdown panels will be clipped if they're inside a container that has `overflow: auto|hidden`. The `hoist` attribute forces the panel to use a fixed positioning strategy, allowing it to break out of the container. In this case, the panel will be positioned relative to its containing block, which is usually the viewport unless an ancestor uses a `transform`, `perspective`, or `filter`. [Refer to this page](https://developer.mozilla.org/en-US/docs/Web/CSS/position#fixed) for more details.
Formats a date/time using the specified locale and options.
Localization is handled by the browser's [`Intl.DateTimeFormat` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat). No language packs are required.
import { SlFormatDate } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlFormatDate date="2020-07-15T09:17:00-04:00" />
);
```
The `date` attribute determines the date/time to use when formatting. It must be a string that [`Date.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) can interpret or a [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object set via JavaScript. If omitted, the current date/time will be assumed.
?> When using strings, avoid ambiguous dates such as `03/04/2020` which can be interpreted as March 4 or April 3 depending on the user's browser and locale. Instead, always use a valid [ISO 8601 date time string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Date_Time_String_Format) to ensure the date will be parsed properly by all clients.
## Examples
### Date & Time Formatting
Formatting options are based on those found in the [`Intl.DateTimeFormat` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat). When formatting options are provided, the date/time will be formatted according to those values. When no formatting options are provided, a localized, numeric date will be displayed instead.
By default, the browser will determine whether to use 12-hour or 24-hour time. To force one or the other, set the `hour-format` attribute to `12` or `24`.
Formats a number using the specified locale and options.
Localization is handled by the browser's [`Intl.NumberFormat` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat). No language packs are required.
To format a number as a monetary value, set the `type` attribute to `currency` and set the `currency` attribute to the desired ISO 4217 currency code. You should also specify `lang` to ensure the the number is formatted correctly for the target locale.
Icon buttons are designed to have a uniform appearance, so their color is not inherited. However, you can still customize them by styling the `base` part.
Icons are symbols that can be used to represent various options within an application.
Shoelace comes bundled with over 1,500 icons courtesy of the [Bootstrap Icons](https://icons.getbootstrap.com/) project. These icons are part of the `default` icon library. If you prefer, you can register [custom icon libraries](#icon-libraries) as well.
Click or tap on an icon below to copy its name and use it like this.
Icons are sized relative to the current font size. To change their size, set the `font-size` property on the icon itself or on a parent element as shown below.
```html preview
<div style="font-size: 32px;">
<sl-icon name="exclamation-triangle"></sl-icon>
<sl-icon name="archive"></sl-icon>
<sl-icon name="battery-charging"></sl-icon>
<sl-icon name="bell"></sl-icon>
<sl-icon name="clock"></sl-icon>
<sl-icon name="cloud"></sl-icon>
<sl-icon name="download"></sl-icon>
<sl-icon name="file-earmark"></sl-icon>
<sl-icon name="flag"></sl-icon>
<sl-icon name="heart"></sl-icon>
<sl-icon name="image"></sl-icon>
<sl-icon name="lightning"></sl-icon>
<sl-icon name="mic"></sl-icon>
<sl-icon name="search"></sl-icon>
<sl-icon name="star"></sl-icon>
<sl-icon name="trash"></sl-icon>
</div>
```
```jsx react
import { SlIcon } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<div style={{ fontSize: '32px' }}>
<SlIcon name="exclamation-triangle" />
<SlIcon name="archive" />
<SlIcon name="battery-charging" />
<SlIcon name="bell" />
<SlIcon name="clock" />
<SlIcon name="cloud" />
<SlIcon name="download" />
<SlIcon name="file-earmark" />
<SlIcon name="flag" />
<SlIcon name="heart" />
<SlIcon name="image" />
<SlIcon name="lightning" />
<SlIcon name="mic" />
<SlIcon name="search" />
<SlIcon name="star" />
<SlIcon name="trash" />
</div>
);
```
### Labels
For non-decorative icons, use the `label` attribute to announce it to assistive devices.
```html preview
<sl-icon name="star-fill" label="Add to favorites"></sl-icon>
```
```jsx react
import { SlIcon } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlIcon name="star-fill" label="Add to favorites" />
);
```
### Custom Icons
Custom icons can be loaded individually with the `src` attribute. Only SVGs on a local or CORS-enabled endpoint are supported. If you're using more than one custom icon, it might make sense to register a [custom icon library](#icon-libraries).
You can register additional icons to use with the `<sl-icon>` component through icon libraries. Icon files can exist locally or on a CORS-enabled endpoint (e.g. a CDN). There is no limit to how many icon libraries you can register and there is no cost associated with registering them, as individual icons are only requested when they're used.
Shoelace ships with two built-in icon libraries, `default` and `system`. The [default icon library](#customizing-the-default-library) contains all of the icons in the Bootstrap Icons project. The [system icon library](#customizing-the-system-library) contains only a small subset of icons that are used internally by Shoelace components.
To register an additional icon library, use the `registerIconLibrary()` function that's exported from `utilities/icon-library.js`. At a minimum, you must provide a name and a resolver function. The resolver function translates an icon name to a URL where the corresponding SVG file exists. Refer to the examples below to better understand how it works.
If necessary, a mutator function can be used to mutate the SVG element before rendering. This is necessary for some libraries due to the many possible ways SVGs are crafted. For example, icons should ideally inherit the current text color via `currentColor`, so you may need to apply `fill="currentColor` or `stroke="currentColor"` to the SVG element using this function.
Here's an example that registers an icon library located in the `/assets/icons` directory.
```html
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
If an icon is used before registration occurs, it will be empty initially but shown when registered.
The following examples demonstrate how to register a number of popular, open source icon libraries via CDN. Feel free to adapt the code as you see fit to use your own origin or naming conventions.
### Boxicons
This will register the [Boxicons](https://boxicons.com/) library using the jsDelivr CDN. This library has three variations: regular (`bx-*`), solid (`bxs-*`), and logos (`bxl-*`). A mutator function is required to set the SVG's `fill` to `currentColor`.
Icons in this library are licensed under the [Creative Commons 4.0 License](https://github.com/atisawd/boxicons#license).
```html preview
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('boxicons', {
resolver: name => {
let folder = 'regular';
if (name.substring(0, 4) === 'bxs-') folder = 'solid';
if (name.substring(0, 4) === 'bxl-') folder = 'logos';
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('feather', {
resolver: name => `https://cdn.jsdelivr.net/npm/feather-icons@4.28.0/dist/icons/${name}.svg`
});
</script>
```
### Font Awesome
This will register the [Font Awesome Free](https://fontawesome.com/) library using the jsDelivr CDN. This library has three variations: regular (`far-*`), solid (`fas-*`), and brands (`fab-*`). A mutator function is required to set the SVG's `fill` to `currentColor`.
Icons in this library are licensed under the [Font Awesome Free License](https://github.com/FortAwesome/Font-Awesome/blob/master/LICENSE.txt). Some of the icons that appear on the Font Awesome website require a license and are therefore not available in the CDN.
```html preview
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('fa', {
resolver: name => {
const filename = name.replace(/^fa[rbs]-/, '');
let folder = 'regular';
if (name.substring(0, 4) === 'fas-') folder = 'solid';
if (name.substring(0, 4) === 'fab-') folder = 'brands';
This will register the [Ionicons](https://ionicons.com/) library using the jsDelivr CDN. This library has three variations: outline (default), filled (`*-filled`), and sharp (`*-sharp`). A mutator function is required to polyfill a handful of styles we're not including.
Icons in this library are licensed under the [MIT License](https://github.com/ionic-team/ionicons/blob/master/LICENSE).
```html preview
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('ionicons', {
resolver: name => `https://cdn.jsdelivr.net/npm/ionicons@5.1.2/dist/ionicons/svg/${name}.svg`,
This will register the [Jam Icons](https://jam-icons.com/) library using the jsDelivr CDN. This library has two variations: regular (default) and filled (`*-f`). A mutator function is required to set the SVG's `fill` to `currentColor`.
Icons in this library are licensed under the [MIT License](https://github.com/michaelampr/jam/blob/master/LICENSE).
```html preview
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('jam', {
resolver: name => `https://cdn.jsdelivr.net/npm/jam-icons@2.0.0/svg/${name}.svg`,
This will register the [Material Icons](https://material.io/resources/icons/?style=baseline) library using the jsDelivr CDN. This library has three variations: outline (default), round (`*_round`), and sharp (`*_sharp`). A mutator function is required to set the SVG's `fill` to `currentColor`.
Icons in this library are licensed under the [Apache 2.0 License](https://github.com/google/material-design-icons/blob/master/LICENSE).
```html preview
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('material', {
resolver: name => {
const match = name.match(/^(.*?)(_(round|sharp))?$/);
This will register the [Remix Icon](https://remixicon.com/) library using the jsDelivr CDN. This library groups icons by categories, so the name must include the category and icon separated by a slash, as well as the `-line` or `-fill` suffix as needed. A mutator function is required to set the SVG's `fill` to `currentColor`.
Icons in this library are licensed under the [Apache 2.0 License](https://github.com/Remix-Design/RemixIcon/blob/master/License).
```html preview
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
This will register the [Unicons](https://iconscout.com/unicons) library using the jsDelivr CDN. This library has two variations: line (default) and solid (`*-s`). A mutator function is required to set the SVG's `fill` to `currentColor`.
Icons in this library are licensed under the [Apache 2.0 License](https://github.com/Iconscout/unicons/blob/master/LICENSE). Some of the icons that appear on the Unicons website, particularly many of the solid variations, require a license and are therefore not available in the CDN.
```html preview
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
The default icon library contains over 1,300 icons courtesy of the [Bootstrap Icons](https://icons.getbootstrap.com/) project. These are the icons that display when you use `<sl-icon>` without the `library` attribute. If you prefer to have these icons resolve elsewhere or to a different icon library, register an icon library using the `default` name and a custom resolver.
This example will load the same set of icons from the jsDelivr CDN instead of your local assets folder.
```html
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('default', {
resolver: name => `https://cdn.jsdelivr.net/npm/bootstrap-icons@1.0.0/icons/${name}.svg`
});
</script>
```
### Customizing the System Library
The system library contains only the icons used internally by Shoelace components. Unlike the default icon library, the system library does not rely on physical assets. Instead, its icons are hard-coded as data URIs into the resolver to ensure their availability.
If you want to change the icons Shoelace uses internally, you can register an icon library using the `system` name and a custom resolver. If you choose to do this, it's your responsibility to provide all of the icons that are required by components. You can reference `src/components/library.system.ts` for a complete list of system icons used by Shoelace.
```html
<script type="module">
import { registerIconLibrary } from '/dist/utilities/icon-library.js';
registerIconLibrary('system', {
resolver: name => `/path/to/custom/icons/${name}.svg`
});
</script>
```
<!-- Supporting scripts and styles for the search utility -->
Compare visual differences between similar photos with a sliding panel.
For best results, use images that share the same dimensions. The slider can be controlled by dragging or pressing the left and right arrow keys. (Tip: press shift + arrows to move the slider in larger intervals, or home + end to jump to the beginning or end.)
```html preview
<sl-image-comparer>
<img slot="before" src="https://images.unsplash.com/photo-1517331156700-3c241d2b4d83?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80&sat=-100&bri=-5" alt="Grayscale version of kittens in a basket looking around.">
<img slot="after" src="https://images.unsplash.com/photo-1517331156700-3c241d2b4d83?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80" alt="Color version of kittens in a basket looking around.">
</sl-image-comparer>
```
```jsx react
import { SlImageComparer } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlImageComparer>
<img slot="before" src="https://images.unsplash.com/photo-1517331156700-3c241d2b4d83?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80&sat=-100&bri=-5" alt="Grayscale version of kittens in a basket looking around." />
<img slot="after" src="https://images.unsplash.com/photo-1517331156700-3c241d2b4d83?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80" alt="Color version of kittens in a basket looking around." />
</SlImageComparer>
);
```
## Examples
### Initial Position
Use the `position` attribute to set the initial position of the slider. This is a percentage from `0` to `100`.
```html preview
<sl-image-comparer position="25">
<img slot="before" src="https://images.unsplash.com/photo-1520903074185-8eca362b3dce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1200&q=80" alt="A person sitting on bricks wearing untied boots.">
<img slot="after" src="https://images.unsplash.com/photo-1520640023173-50a135e35804?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2250&q=80" alt="A person sitting on a yellow curb tying shoelaces on a boot.">
</sl-image-comparer>
```
```jsx react
import { SlImageComparer } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlImageComparer position={25}>
<img slot="before" src="https://images.unsplash.com/photo-1520903074185-8eca362b3dce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1200&q=80" alt="A person sitting on bricks wearing untied boots." />
<img slot="after" src="https://images.unsplash.com/photo-1520640023173-50a135e35804?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2250&q=80" alt="A person sitting on a yellow curb tying shoelaces on a boot." />
Includes give you the power to embed external HTML files into the page.
Included files are asynchronously requested using `window.fetch()`. Requests are cached, so the same file can be included multiple times, but only one request will be made.
The included content will be inserted into the `<sl-include>` element's default slot so it can be easily accessed and styled through the light DOM.
When an include file loads successfully, the `sl-load` event will be emitted. You can listen for this event to add custom loading logic to your includes.
If the request fails, the `sl-error` event will be emitted. In this case, `event.detail.status` will contain the resulting HTTP status code of the request, e.g. 404 (not found).
import { SlInput } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlInput />
);
```
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Placeholders
Use the `placeholder` attribute to add a placeholder.
The `value` attribute can be used to assign a hidden value, such as a unique identifier, to a menu item. When an item is selected, the `sl-select` event will be emitted and a reference to the item will be available at `event.detail.item`. You can use this reference to access the selected item's value, its checked state, and more.
Menus provide a list of options for the user to choose from.
You can use [menu items](/components/menu-item), [menu labels](/components/menu-label), and [dividers](/components/divider) to compose a menu. Menus support keyboard interactions, including type-to-select an option.
?> Menus are intended for system menus (dropdown menus, select menus, context menus, etc.). They should not be mistaken for navigation menus which serve a different purpose and have a different semantic meaning. If you're building navigation, use `<nav>` and `<a>` elements instead.
The Mutation Observer component offers a thin, declarative interface to the [`MutationObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver).
The mutation observer will report changes to the content it wraps through the `sl-mutation` event. When emitted, a collection of [MutationRecord](https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord) objects will be attached to `event.detail` that contains information about how it changed.
```html preview
<div class="mutation-overview">
<sl-mutation-observer attr="variant">
<sl-button variant="primary">Click to mutate</sl-button>
<SlButton variant={variant} onClick={handleClick}>Click to mutate</SlButton>
</SlMutationObserver>
<style>{css}</style>
</>
);
};
```
?> When you create a mutation observer, you must indicate what changes it should respond to by including at least one of `attr`, `child-list`, or `char-data`. If you don't specify at least one of these attributes, no mutation events will be emitted.
## Examples
### Child List
Use the `child-list` attribute to watch for new child elements that are added or removed.
const value = Math.min(100, progressBar.value + 10);
progressBar.value = value;
progressBar.textContent = `${value}%`;
});
subtractButton.addEventListener('click', () => {
const value = Math.max(0, progressBar.value - 10)
progressBar.value = value;
progressBar.textContent = `${value}%`;
});
</script>
```
```jsx react
import { useState } from 'react';
import {
SlButton,
SlIcon,
SlProgressBar
} from '@shoelace-style/shoelace/dist/react';
const App = () => {
const [value, setValue] = useState(50);
function adjustValue(amount) {
let newValue = value + amount;
if (newValue < 0) newValue = 0;
if (newValue > 100) newValue = 100;
setValue(newValue);
}
return (
<>
<SlProgressBar value={value}>
{value}%
</SlProgressBar>
<br />
<SlButton circle onClick={() => adjustValue(-10)}>
<SlIcon name="dash" />
</SlButton>
<SlButton circle onClick={() => adjustValue(10)}>
<SlIcon name="plus" />
</SlButton>
</>
);
};
```
### Indeterminate
The `indeterminate` attribute can be used to inform the user that the operation is pending, but its status cannot currently be determined. In this state, `value` is ignored and the label, if present, will not be shown.
```html preview
<sl-progress-bar indeterminate></sl-progress-bar>
```
```jsx react
import { SlProgressBar } from '@shoelace-style/shoelace/dist/react';
Generates a [QR code](https://www.qrcode.com/) and renders it using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API).
QR codes are useful for providing small pieces of information to users who can quickly scan them with a smartphone. Most smartphones have built-in QR code scanners, so simply pointing the camera at a QR code will decode it and allow the user to visit a website, dial a phone number, read a message, etc.
```html preview
<div class="qr-overview">
<sl-qr-code value="https://shoelace.style/" label="Scan this code to visit Shoelace on the web!"></sl-qr-code>
Use the `fill` and `background` attributes to modify the QR code's colors. You should always ensure good contrast for optimal compatibility with QR code scanners.
QR codes can be rendered with various levels of [error correction](https://www.qrcode.com/en/about/error_correction.html) that can be set using the `error-correction` attribute. This example generates four codes with the same value using different error correction levels.
Radios allow the user to select one option from a group of many.
Radios are designed to be used with [radio groups](/components/radio-group). As such, all of the examples on this page utilize them to demonstrate their correct usage.
```html preview
<sl-radio-group label="Select an option">
<sl-radio value="1" checked>Option 1</sl-radio>
<sl-radio value="2">Option 2</sl-radio>
<sl-radio value="3">Option 3</sl-radio>
</sl-radio-group>
```
```jsx react
import { SlRadio, SlRadioGroup } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlRadioGroup label="Select an option">
<SlRadio value="1" checked>Option 1</SlRadio>
<SlRadio value="2">Option 2</SlRadio>
<SlRadio value="3">Option 3</SlRadio>
</SlRadioGroup>
);
```
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Disabled
Use the `disabled` attribute to disable a radio.
```html preview
<sl-radio-group label="Select an option">
<sl-radio value="1" checked>Option 1</sl-radio>
<sl-radio value="2">Option 2</sl-radio>
<sl-radio value="3">Option 3</sl-radio>
<sl-radio value="4" disabled>Disabled</sl-radio>
</sl-radio-group>
```
```jsx react
import { SlRadio, SlRadioGroup } from '@shoelace-style/shoelace/dist/react';
Ranges allow the user to select a single value within a given range using a slider.
```html preview
<sl-range></sl-range>
```
```jsx react
import { SlRange } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlRange />
);
```
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Min, Max, and Step
Use the `min` and `max` attributes to set the range's minimum and maximum values, respectively. The `step` attribute determines the value's interval when increasing and decreasing.
```html preview
<sl-range min="0" max="10" step="1"></sl-range>
```
```jsx react
import { SlRange } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlRange min={0} max={10} step={1} />
);
```
### Disabled
Use the `disabled` attribute to disable a slider.
```html preview
<sl-range disabled></sl-range>
```
```jsx react
import { SlRange } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlRange disabled />
);
```
### Tooltip Placement
By default, the tooltip is shown on top. Set `tooltip` to `bottom` to show it below the slider.
```html preview
<sl-range tooltip="bottom"></sl-range>
```
```jsx react
import { SlRange } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlRange tooltip="bottom" />
);
```
### Disable the Tooltip
To disable the tooltip, set `tooltip` to `none`.
```html preview
<sl-range tooltip="none"></sl-range>
```
```jsx react
import { SlRange } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlRange tooltip="none" />
);
```
### Custom Track Colors
You can customize the active and inactive portions of the track using the `--track-color-active` and `--track-color-inactive` custom properties.
Outputs a localized time phrase relative to the current date and time.
Localization is handled by the browser's [`Intl.RelativeTimeFormat` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat). No language packs are required.
The `date` attribute determines when the date/time is calculated from. It must be a string that [`Date.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) can interpret or a [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object set via JavaScript.
?> When using strings, avoid ambiguous dates such as `03/04/2020` which can be interpreted as March 4 or April 3 depending on the user's browser and locale. Instead, always use a valid [ISO 8601 date time string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Date_Time_String_Format) to ensure the date will be parsed properly by all clients.
!> The `Intl.RelativeTimeFormat` API is available [in all major browsers](https://caniuse.com/mdn-javascript_builtins_intl_relativetimeformat), but it only became available to Safari in version 14. If you need to support Safari 13, you'll need to [use a polyfill](https://github.com/catamphetamine/relative-time-format).
## Examples
### Keeping Time in Sync
Use the `sync` attribute to update the displayed value automatically as time passes.
relativeTime.date = new Date(new Date().getTime() - 60000);
</script>
```
```jsx react
import { SlRelativeTime } from '@shoelace-style/shoelace/dist/react';
const date = new Date(new Date().getTime() - 60000);
const App = () => (
<SlRelativeTime date={date} sync />
);
```
### Formatting Styles
You can change how the time is displayed using the `format` attribute. Note that some locales may display the same values for `narrow` and `short` formats.
The Resize Observer component offers a thin, declarative interface to the [`ResizeObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver).
The resize observer will report changes to the dimensions of the elements it wraps through the `sl-resize` event. When emitted, a collection of [`ResizeObserverEntry`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry) objects will be attached to `event.detail` that contains the target element and information about its dimensions.
You can slot in any [replaced element](https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element), including `<iframe>`, `<img>`, and `<video>`. As the element's width changes, its height will resize proportionally. Only one element should be slotted into the container. The default aspect ratio is `16:9`.
```html preview
<sl-responsive-media>
<img src="https://images.unsplash.com/photo-1541427468627-a89a96e5ca1d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1800&q=80" alt="A train riding through autumn foliage with mountains in the distance.">
</sl-responsive-media>
```
```jsx react
import { SlResponsiveMedia } from '@shoelace-style/shoelace/dist/react';
alt="A train riding through autumn foliage with mountains in the distance."
/>
</SlResponsiveMedia>
);
```
## Examples
### Responsive Images
The following image maintains a `4:3` aspect ratio as its container is resized.
```html preview
<sl-responsive-media aspect-ratio="4:3">
<img src="https://images.unsplash.com/photo-1473186578172-c141e6798cf4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1800&q=80" alt="Two blue chairs on a sandy beach.">
</sl-responsive-media>
```
```jsx react
import { SlResponsiveMedia } from '@shoelace-style/shoelace/dist/react';
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Placeholders
Use the `placeholder` attribute to add a placeholder.
To allow multiple options to be selected, use the `multiple` attribute. It's a good practice to use `clearable` when this option is enabled. When using this option, `value` will be an array instead of a string.
```html preview
<sl-select placeholder="Select a few" multiple clearable>
The `value` property is bound to the current selection. As the selection changes, so will the value. To programmatically manage the selection, update the `value` property.
Skeletons are used to show where content will eventually be drawn.
These are simple containers for scaffolding layouts that mimic what users will see when content has finished loading. This prevents large areas of empty space during asynchronous operations.
Skeletons try not to be opinionated, as there are endless possibilities for designing layouts. Therefore, you'll likely use more than one skeleton to create the effect you want. If you find yourself using them frequently, consider creating a template that renders them with the desired arrangement and styles.
There are two built-in effects, `sheen` and `pulse`. Effects are intentionally subtle, as they can be distracting when used extensively. The default is `none`, which displays a static, non-animated skeleton.
```html preview
<div class="skeleton-effects">
<sl-skeleton effect="none"></sl-skeleton>
None
<sl-skeleton effect="sheen"></sl-skeleton>
Sheen
<sl-skeleton effect="pulse"></sl-skeleton>
Pulse
</div>
<style>
.skeleton-effects {
font-size: var(--sl-font-size-small);
}
.skeleton-effects sl-skeleton:not(:first-child) {
margin-top: 1rem;
}
</style>
```
```jsx react
import { SlSkeleton } from '@shoelace-style/shoelace/dist/react';
const css = `
.skeleton-effects {
font-size: var(--sl-font-size-small);
}
.skeleton-effects sl-skeleton:not(:first-child) {
margin-top: 1rem;
}
`;
const App = () => (
<>
<div className="skeleton-effects">
<SlSkeleton effect="none" />
None
<SlSkeleton effect="sheen" />
Sheen
<SlSkeleton effect="pulse" />
Pulse
</div>
<style>{css}</style>
</>
);
```
### Paragraphs
Use multiple skeletons and some clever styles to simulate paragraphs.
```html preview
<div class="skeleton-paragraphs">
<sl-skeleton></sl-skeleton>
<sl-skeleton></sl-skeleton>
<sl-skeleton></sl-skeleton>
<sl-skeleton></sl-skeleton>
<sl-skeleton></sl-skeleton>
</div>
<style>
.skeleton-paragraphs sl-skeleton {
margin-bottom: 1rem;
}
.skeleton-paragraphs sl-skeleton:nth-child(2) {
width: 95%;
}
.skeleton-paragraphs sl-skeleton:nth-child(4) {
width: 90%;
}
.skeleton-paragraphs sl-skeleton:last-child {
width: 50%;
}
</style>
```
```jsx react
import { SlSkeleton } from '@shoelace-style/shoelace/dist/react';
const css = `
.skeleton-paragraphs sl-skeleton {
margin-bottom: 1rem;
}
.skeleton-paragraphs sl-skeleton:nth-child(2) {
width: 95%;
}
.skeleton-paragraphs sl-skeleton:nth-child(4) {
width: 90%;
}
.skeleton-paragraphs sl-skeleton:last-child {
width: 50%;
}
`;
const App = () => (
<>
<div className="skeleton-paragraphs">
<SlSkeleton />
<SlSkeleton />
<SlSkeleton />
<SlSkeleton />
<SlSkeleton />
</div>
<style>{css}</style>
</>
);
```
### Avatars
Set a matching width and height to make a circle, square, or rounded avatar skeleton.
```html preview
<div class="skeleton-avatars">
<sl-skeleton></sl-skeleton>
<sl-skeleton></sl-skeleton>
<sl-skeleton></sl-skeleton>
</div>
<style>
.skeleton-avatars sl-skeleton {
display: inline-block;
width: 3rem;
height: 3rem;
margin-right: .5rem;
}
.skeleton-avatars sl-skeleton:nth-child(1) {
--border-radius: 0;
}
.skeleton-avatars sl-skeleton:nth-child(2) {
--border-radius: var(--sl-border-radius-medium);
}
</style>
```
```jsx react
import { SlSkeleton } from '@shoelace-style/shoelace/dist/react';
const css = `
.skeleton-avatars sl-skeleton {
display: inline-block;
width: 3rem;
height: 3rem;
margin-right: .5rem;
}
.skeleton-avatars sl-skeleton:nth-child(1) {
--border-radius: 0;
}
.skeleton-avatars sl-skeleton:nth-child(2) {
--border-radius: var(--sl-border-radius-medium);
}
`;
const App = () => (
<>
<div className="skeleton-avatars">
<SlSkeleton />
<SlSkeleton />
<SlSkeleton />
</div>
<style>{css}</style>
</>
);
```
### Custom Shapes
Use the `--border-radius` custom property to make circles, squares, and rectangles. For more complex shapes, you can apply `clip-path` to the `indicator` part. [Try Clippy](https://bennettfeely.com/clippy/) if you need help generating custom shapes.
Spinners are used to show the progress of an indeterminate operation.
```html preview
<sl-spinner></sl-spinner>
```
```jsx react
import { SlSpinner } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlSpinner />
);
```
## Examples
### Size
Spinners are sized based on the current font size. To change their size, set the `font-size` property on the spinner itself or on a parent element as shown below.
import { SlSplitPanel } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlSplitPanel position="200">
<div
slot="start"
style={{
height: '200px',
background: 'var(--sl-color-neutral-50)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
>
Start
</div>
<div
slot="end"
style={{
height: '200px',
background: 'var(--sl-color-neutral-50)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
>
End
</div>
</SlSplitPanel>
);
```
### Vertical
Add the `vertical` attribute to render the split panel in a vertical orientation where the start and end panels are stacked. You also need to set a height when using the vertical orientation.
To snap panels at specific positions while dragging, add the `snap` attribute with one or more space-separated values. Values must be in pixels or percentages. For example, to snap the panel at `100px` and `50%`, use `snap="100px 50%"`. You can also customize how close the divider must be before snapping with the `snap-threshold` attribute.
import { SlSplitPanel } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlSplitPanel disabled>
<div
slot="start"
style={{
height: '200px',
background: 'var(--sl-color-neutral-50)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
>
Start
</div>
<div
slot="end"
style={{
height: '200px',
background: 'var(--sl-color-neutral-50)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
>
End
</div>
</SlSplitPanel>
);
```
### Setting the Primary Panel
By default, both panels will grow or shrink proportionally when the host element is resized. If a primary panel is designated, it will maintain its size and the secondary panel will grow or shrink to fit the remaining space. You can set the primary panel to `start` or `end` using the `primary` attribute.
Try resizing the example below with each option and notice how the panels respond.
To set a minimum or maximum size of the primary panel, use the `--min` and `--max` custom properties. Since the secondary panel is flexible, size constraints can only be applied to the primary panel. If no primary panel is designated, these constraints will be applied to the `start` panel.
This examples demonstrates how you can ensure both panels are at least 150px using `--min`, `--max`, and the `calc()` function.
You can target the `divider` part to apply CSS properties to the divider. To add a handle, slot an icon or another element into the `handle` slot. When customizing the divider, make sure to think about focus styles for keyboard users.
Switches allow the user to toggle an option on or off.
```html preview
<sl-switch>Switch</sl-switch>
```
```jsx react
import { SlSwitch } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlSwitch>Switch</SlSwitch>
);
```
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Checked
Use the `checked` attribute to activate the switch.
```html preview
<sl-switch checked>Checked</sl-switch>
```
```jsx react
import { SlSwitch } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlSwitch checked>Checked</SlSwitch>
);
```
### Disabled
Use the `disabled` attribute to disable the switch.
```html preview
<sl-switch disabled>Disabled</sl-switch>
```
```jsx react
import { SlSwitch } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlSwitch disabled>Disabled</SlSwitch>
);
```
### Custom Size
Use the available custom properties to make the switch a different size.
Tab groups organize content into a container that shows one section at a time.
Tab groups make use of [tabs](/components/tab) and [tab panels](/components/tab-panel). Each tab must be slotted into the `nav` slot and its `panel` must refer to a tab panel of the same name.
<SlTabPanel name="general">This is the general tab panel.</SlTabPanel>
<SlTabPanel name="custom">This is the custom tab panel.</SlTabPanel>
<SlTabPanel name="advanced">This is the advanced tab panel.</SlTabPanel>
<SlTabPanel name="disabled">This is a disabled tab panel.</SlTabPanel>
</SlTabGroup>
);
```
### Closable Tabs
Add the `closable` attribute to a tab to show a close button. This example shows how you can dynamically remove tabs from the DOM when the close button is activated.
When focused, keyboard users can press <kbd>Left</kbd> or <kbd>Right</kbd> to select the desired tab. By default, the corresponding tab panel will be shown immediately (automatic activation). You can change this behavior by setting `activation="manual"` which will require the user to press <kbd>Space</kbd> or <kbd>Enter</kbd> before showing the tab panel (manual activation).
Textareas collect data from the user and allow multiple lines of text.
```html preview
<sl-textarea></sl-textarea>
```
```jsx react
import { SlTextarea } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlTextarea />
);
```
?> This component works with standard `<form>` elements. Please refer to the section on [form controls](/getting-started/form-controls) to learn more about form submission and client-side validation.
## Examples
### Rows
Use the `rows` attribute to change the number of text rows that get shown.
```html preview
<sl-textarea rows="2"></sl-textarea>
```
```jsx react
import { SlTextarea } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlTextarea rows={2} />
);
```
### Placeholders
Use the `placeholder` attribute to add a placeholder.
Tooltips display additional information based on a specific action.
A tooltip's target is its _first child element_, so you should only wrap one element inside of the tooltip. If you need the tooltip to show up for multiple elements, nest them inside a container first.
Tooltips use `display: contents` so they won't interfere with how elements are positioned in a flex or grid layout.
```html preview
<sl-tooltip content="This is a tooltip">
<sl-button>Hover Me</sl-button>
</sl-tooltip>
```
```jsx react
import { SlButton, SlTooltip } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlTooltip content="This is a tooltip">
<SlButton>Hover Me</SlButton>
</SlTooltip>
);
```
## Examples
### Placement
Use the `placement` attribute to set the preferred placement of the tooltip.
Set the `trigger` attribute to `click` to toggle the tooltip on click instead of hover.
```html preview
<sl-tooltip content="Click again to dismiss" trigger="click">
<sl-button>Click to Toggle</sl-button>
</sl-tooltip>
```
```jsx react
import { SlButton, SlTooltip } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlTooltip content="Click again to dismiss" trigger="click">
<SlButton>Click to Toggle</SlButton>
</SlTooltip>
);
```
### Manual Trigger
Tooltips can be controller programmatically by setting the `trigger` attribute to `manual`. Use the `open` attribute to control when the tooltip is shown.
import { SlAvatar, SlButton, SlTooltip } from '@shoelace-style/shoelace/dist/react';
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<SlButton
style={{ marginRight: '4rem' }}
onClick={() => setOpen(!open)}
>
Toggle Manually
</SlButton>
<SlTooltip open={open} content="This is an avatar" trigger="manual">
<SlAvatar />
</SlTooltip>
</>
);
};
```
### Remove Arrows
You can control the size of tooltip arrows by overriding the `--sl-tooltip-arrow-size` design token.
```html preview
<div style="--sl-tooltip-arrow-size: 0;">
<sl-tooltip content="This is a tooltip">
<sl-button>Above</sl-button>
</sl-tooltip>
<sl-tooltip content="This is a tooltip" placement="bottom">
<sl-button>Below</sl-button>
</sl-tooltip>
</div>
```
```jsx react
import { SlButton, SlTooltip } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<div style={{ '--sl-tooltip-arrow-size': '0' }}>
<SlTooltip content="This is a tooltip">
<SlButton>Above</SlButton>
</SlTooltip>
<SlTooltip content="This is a tooltip" placement="bottom">
<SlButton>Below</SlButton>
</SlTooltip>
</div>
);
```
To override it globally, set it in a root block in your stylesheet after the Shoelace stylesheet is loaded.
```css
:root {
--sl-tooltip-arrow-size: 0;
}
```
### HTML in Tooltips
Use the `content` slot to create tooltips with HTML content. Tooltips are designed only for text and presentational elements. Avoid placing interactive content, such as buttons, links, and form controls, in a tooltip.
```html preview
<sl-tooltip>
<div slot="content">
I'm not <strong>just</strong> a tooltip, I'm a <em>tooltip</em> with HTML!
</div>
<sl-button>Hover me</sl-button>
</sl-tooltip>
```
```jsx react
import { SlButton, SlTooltip } from '@shoelace-style/shoelace/dist/react';
const App = () => (
<SlTooltip content="This is a tooltip">
<div slot="content">
I'm not <strong>just</strong> a tooltip, I'm a <em>tooltip</em> with HTML!
</div>
<SlButton>Hover Me</SlButton>
</SlTooltip>
);
```
### Hoisting
Tooltips will be clipped if they're inside a container that has `overflow: auto|hidden|scroll`. The `hoist` attribute forces the tooltip to use a fixed positioning strategy, allowing it to break out of the container. In this case, the tooltip will be positioned relative to its containing block, which is usually the viewport unless an ancestor uses a `transform`, `perspective`, or `filter`. [Refer to this page](https://developer.mozilla.org/en-US/docs/Web/CSS/position#fixed) for more details.
```html preview
<div class="tooltip-hoist">
<sl-tooltip content="This is a tooltip">
<sl-button>No Hoist</sl-button>
</sl-tooltip>
<sl-tooltip content="This is a tooltip" hoist>
<sl-button>Hoist</sl-button>
</sl-tooltip>
</div>
<style>
.tooltip-hoist {
border: solid 2px var(--sl-panel-border-color);
overflow: hidden;
padding: var(--sl-spacing-medium);
position: relative;
}
</style>
```
```jsx react
import { SlButton, SlTooltip } from '@shoelace-style/shoelace/dist/react';
The visually hidden utility makes content accessible to assistive devices without displaying it on the screen.
According to [The A11Y Project](https://www.a11yproject.com/posts/2013-01-11-how-to-hide-content/), "there are real world situations where visually hiding content may be appropriate, while the content should remain available to assistive technologies, such as screen readers. For instance, hiding a search field's label as a common magnifying glass icon is used in its stead."
Since visually hidden content can receive focus when tabbing, the element will become visible when something inside receives focus. This behavior is intentional, as sighted keyboards user won't be able to determine where the focus indicator is without it.
```html preview
<div style="min-height: 100px;">
<sl-visually-hidden>
<a href="#">Skip to main content</a>
</sl-visually-hidden>
</div>
```
## Examples
### Links That Open in New Windows
In this example, the link will open a new window. Screen readers will announce "opens in a new window" even though the text content isn't visible to sighted users.
```html preview
<a href="https://example.com/" target="_blank">
Visit External Page
<sl-icon name="box-arrow-up-right"></sl-icon>
<sl-visually-hidden>opens in a new window</sl-visually-hidden>
</a>
```
### Content Conveyed By Context
Adding a title or label may seem redundant at times, but they're very helpful for unsighted users. Rather than omit them, you can provide context to unsighted users with visually hidden content.
Angular [plays nice](https://custom-elements-everywhere.com/#angular) with custom elements, so you can use Shoelace in your Angular apps with ease.
## Installation
To add Shoelace to your Angular app, install the package from npm.
```bash
npm install @shoelace-style/shoelace
```
Next, [include a theme](/getting-started/themes) and set the [base path](/getting-started/installation#setting-the-base-path) for icons and other assets. In this example, we'll import the light theme and use the CDN as a base path.
?> If you'd rather not use the CDN for assets, you can create a build task that copies `node_modules/@shoelace-style/shoelace/dist/assets` into a public folder in your app. Then you can point the base path to that folder instead.
## Configuration
Then make sure to apply the custom elements schema as shown below.
Shoelace offers a React version of every component to provide an idiomatic experience for React users. You can easily toggle between HTML and React examples throughout the documentation.
## Installation
To add Shoelace to your React app, install the package from npm.
```bash
npm install @shoelace-style/shoelace
```
Next, [include a theme](/getting-started/themes) and set the [base path](/getting-started/installation#setting-the-base-path) for icons and other assets. In this example, we'll import the light theme and use the CDN as a base path.
?> If you'd rather not use the CDN for assets, you can create a [build task](https://webpack.js.org/plugins/copy-webpack-plugin/) that copies `node_modules/@shoelace-style/shoelace/dist/assets` into your app's `public` directory. Then you can point the base path to that folder instead.
Now you can start using components!
## Usage
### Importing Components
Every Shoelace component is available to import as a React component. Note that we're importing the `<SlButton>`_React component_ instead of the `<sl-button>`_custom element_ in the example below.
You can find a copy + paste import for each component in the "importing" section of its documentation.
### Event Handling
Many Shoelace components emit [custom events](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). For example, the [input component](/components/input) emits the `sl-input` event when it receives input. In React, you can listen for the event using `onSlInput`.
Here's how you can bind the input's value to a state variable.
If you're using TypeScript, it's important to note that `event.target` will be a reference to the underlying custom element. You can use `(event.target as any).value` as a quick fix, or you can strongly type the event target as shown below.
Testing with web components can be challenging if your test environment runs in a Node environment (i.e. it doesn't run in a real browser). Fortunately, [Jest](https://jestjs.io/) has made a number of strides to support web components and provide additional browser APIs. However, it's still not a complete replication of a browser environment.
Here are some tips that will help smooth things over if you're having trouble with Jest + Shoelace.
?> If you're looking for a fast, modern testing alternative, consider [Web Test Runner](https://modern-web.dev/docs/test-runner/overview/).
### Upgrade Jest
Jest underwent a major revamp and received support for web components in [version 26.5.0](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2650) when it introduced [JSDOM 16.2.0](https://github.com/jsdom/jsdom/blob/master/Changelog.md#1620). This release also included a number of mocks for built-in browser functions such as `MutationObserver`, `document.createRange`, and others.
If you're using [Create React App](https://reactjs.org/docs/create-a-new-react-app.html#create-react-app), you can update `react-scripts` which will also update Jest.
```
npm install react-scripts@latest
```
### Mock Missing APIs
Some components use `window.matchMedia`, but this function isn't supported by JSDOM so you'll need to mock it yourself.
In `src/setupTests.js`, add the following.
```js
Object.defineProperty(window,'matchMedia',{
writable:true,
value:jest.fn().mockImplementation(query=>({
matches:false,
media:query,
onchange:null,
addListener:jest.fn(),// deprecated
removeListener:jest.fn(),// deprecated
addEventListener:jest.fn(),
removeEventListener:jest.fn(),
dispatchEvent:jest.fn(),
})),
});
```
For more details, refer to Jest's [manual mocking](https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom) documentation.
### Transform ES Modules
ES Modules are a [well-supported browser standard](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/). This is how Shoelace is distributed, but most React apps expect CommonJS. As a result, you'll probably run into the following error.
```
Error: Unable to import outside of a module
```
To fix this, add the following to your `package.json` which tells the transpiler to process Shoelace modules.
These instructions are for apps created via Create React App. If you're using Jest directly, you can add `transformIgnorePatterns` directly into `jest.config.js`.
For more details, refer to Jest's [`transformIgnorePatterns` customization](https://jestjs.io/docs/tutorial-react-native#transformignorepatterns-customization) documentation.
?> Are you using Shoelace with React? [Help us improve this page!](https://github.com/shoelace-style/shoelace/blob/next/docs/frameworks/react.md)
Vue [plays nice](https://custom-elements-everywhere.com/#vue) with custom elements, so you can use Shoelace in your Vue apps with ease.
?> These instructions are for Vue 2. If you're using Vue 3, [please help us update this page](https://github.com/shoelace-style/shoelace/blob/next/docs/frameworks/vue.md).
## Installation
To add Shoelace to your Vue app, install the package from npm.
```bash
npm install @shoelace-style/shoelace
```
Next, [include a theme](/getting-started/themes) and set the [base path](/getting-started/installation#setting-the-base-path) for icons and other assets. In this example, we'll import the light theme and use the CDN as a base path.
?> If you'd rather not use the CDN for assets, you can create a build task that copies `node_modules/@shoelace-style/shoelace/dist/assets` into a public folder in your app. Then you can point the base path to that folder instead.
## Configuration
You'll need to tell Vue to ignore Shoelace components. This is pretty easy because they all start with `sl-`.
Now you can start using Shoelace components in your app!
## Usage
### Binding Complex Data
When binding complex data such as objects and arrays, use the `.prop` modifier to make Vue bind them as a property instead of an attribute.
```html
<sl-color-picker:swatches.prop="mySwatches"/>
```
### Two-way Binding
One caveat is there's currently [no support for v-model on custom elements](https://github.com/vuejs/vue/issues/7830), but you can still achieve two-way binding manually.
If that's too verbose for your liking, you can use a custom directive instead. [This utility](https://www.npmjs.com/package/@shoelace-style/vue-sl-model) adds a custom directive that will work just like `v-model` but for Shoelace components. To install it, use this command.
```bash
npm install @shoelace-style/vue-sl-model
```
Next, import the directive and enable it like this.
Shoelace components can be customized at a high level through design tokens. This gives you control over theme colors and general styling. For more advanced customizations, you can make use of component parts and custom properties to target individual components.
## Design Tokens
Shoelace makes use of several design tokens to provide a consistent appearance across components. You can customize them and use them in your own application with pure CSS — no preprocessor required.
Design tokens offer a high-level way to customize the library with minimal effort. There are no component-specific variables, however, as design tokens are intended to be generic and highly reusable. To customize an individual component, refer to the section entitled [Component Parts](#component-parts).
Design tokens are accessed through CSS custom properties that are defined in your theme. Because design tokens live at the page level, they're prefixed with `--sl-` to avoid collisions with other libraries.
To customize a design token, simply override it in your stylesheet using a `:root` block. Here's an example that changes the primary theme to purple based on existing [color primitives](/tokens/color#primitives).
```css
:root{
/* Changes the primary theme color to purple using primitives */
Many design tokens are described further along in this documentation. For a complete list, refer to `src/themes/light.styles.ts` in the project's [source code](https://github.com/shoelace-style/shoelace/blob/current/src/themes/light.styles.ts).
## Component Parts
Whereas design tokens offer a high-level way to customize the library, component parts offer a low-level way to customize individual components. Again, this is done with pure CSS — no preprocessor required.
Shoelace components use a [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) to encapsulate their styles and behaviors. As a result, you can't simply target their internals with the usual CSS selectors. Instead, components expose "parts" that can be targeted with the [CSS part selector](https://developer.mozilla.org/en-US/docs/Web/CSS/::part), or `::part()`.
Here's an example that modifies buttons with the `tomato-button` class.
At first glance, this approach might seem a bit verbose or even limiting, but it comes with a few important advantages:
- Customizations can be made to components with explicit selectors, such as `::part(icon)`, rather than implicit selectors, such as `.button > div > span + .icon`, that are much more fragile.
- The internal structure of a component will likely change as it evolves. By exposing component parts through an API, the internals can be reworked without fear of breaking customizations as long as its parts remain intact.
- It encourages us to think more about how components are designed and how customizations should be allowed before users can take advantage of them. Once we opt a part into the component's API, it's guaranteed to be supported and can't be removed until a major version of the library is released.
Most (but not all) components expose parts. You can find them in each component's API documentation under the "CSS Parts" section.
## Custom Properties
For convenience, some components expose CSS custom properties you can override. These are not design tokens, nor do they have the same `--sl-` prefix since they're scoped to a component.
You can set custom properties on a component in your stylesheet.
```css
sl-avatar {
--size: 6rem;
}
```
This will also work if you need to target a subset of components with a specific class.
```css
sl-avatar.your-class {
--size: 6rem;
}
```
Alternatively, you can set them inline directly on the element.
```html
<sl-avatar style="--size: 6rem;"></sl-avatar>
```
Not all components expose CSS custom properties. For those that do, they can be found in the component's API documentation.
## Animations
Some components use animation, such as when a dialog is shown or hidden. Animations are performed using the [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) rather than CSS. However, you can still customize them through Shoelace's animation registry. If a component has customizable animations, they'll be listed in the "Animation" section of its documentation.
To customize a default animation, use the `setDefaultAnimation()` method. The function accepts an animation name (found in the component's docs) and an object with `keyframes` and `options` or `null` to disable the animation.
This example will make all dialogs use a custom show animation.
```js
import { setDefaultAnimation } from '@shoelace-style/shoelace/dist/utilities/animation-registry.js';
If you only want to target a single component, use the `setAnimation()` method instead. This function accepts an element, an animation name, and an object comprised of animation `keyframes` and `options`.
In this example, only the target dialog will use a custom show animation.
```js
import { setAnimation } from '@shoelace-style/shoelace/dist/utilities/animation-registry.js';
To learn more about creating Web Animations, refer to the documentation for [`Element.animate()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/animate).
?> Animations respect the users `prefers-reduced-motion` setting. When this setting is enabled, animations will not be played. To disable animations for all users, pass in `null` instead of a keyframes/options object.
Every Shoelace component makes use of a [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) to encapsulate markup, styles, and behavior. One caveat of this approach is that native `<form>` elements do not recognize form controls located inside a shadow root.
Shoelace solves this problem by using the [`formdata`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/formdata_event) event, which is [available in all modern browsers](https://caniuse.com/mdn-api_htmlformelement_formdata_event). This means, when a form is submitted, Shoelace form controls will automatically append their values to the `FormData` object that's used to submit the form. In most cases, things will "just work." However, if you're using a form serialization library, it might need to be adapted to recognize Shoelace form controls.
?> If you're using an older browser that doesn't support the `formdata` event, a lightweight polyfill will be automatically applied to ensure forms submit as expected.
## Form Serialization
Serialization is just a fancy word for collecting form data. If you're relying on standard form submissions, e.g. `<form action="...">`, you can probably skip this section. However, most modern apps use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) or a library such as [axios](https://github.com/axios/axios) to submit forms using JavaScript.
The [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) interface offers a standard way to serialize forms in the browser. You can create a `FormData` object from any `<form>` element like this.
```js
constform=document.querySelector('form');
constdata=newFormData(form);
// All form control data is available in a FormData object
```
However, some folks find `FormData` tricky to work with or they need to pass a JSON payload to their server. To accommodate this, Shoelace offers a serialization utility that gathers form data and returns a simple JavaScript object instead.
// All form control data is available in a plain object
```
This results in an object with name/value pairs that map to each form control. If more than one form control shares the same name, the values will be passed as an array, e.g. `{ name: ['value1', 'value2'] }`.
## Form Control Validation
Client-side validation can be enabled through the browser's [Constraint Validation API](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation) for Shoelace form controls. You can activate it using attributes such as `required`, `pattern`, `minlength`, and `maxlength`. Shoelace implements many of the same attributes as native form controls, but check each form control's documentation for a list of all supported properties.
As the user interacts with a form control, its `invalid` attribute will reflect its validity based on its current value and the constraints that have been defined. When a form control is invalid, the containing form will not be submitted. Instead, the browser will show the user a relevant error message. If you don't want to use client-side validation, you can suppress this behavior by adding `novalidate` to the surrounding `<form>` element.
All form controls support validation, but not all validation props are available for every component. Refer to a component's documentation to see which validation props it supports.
!> Client-side validation can be used to improve the UX of forms, but it is not a replacement for server-side validation. **You should always validate and sanitize user input on the server!**
### Required Fields
To make a field required, use the `required` prop. The form will not be submitted if a required form control is empty.
To restrict a value to a specific [pattern](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern), use the `pattern` attribute. This example only allows the letters A-Z, so the form will not submit if a number or symbol is entered. This only works with `<sl-input>` elements.
To create a custom validation error, use the `setCustomValidity` method. The form will not be submitted when this method is called with anything other than an empty string, and its message will be shown by the browser as the validation error. To make the input valid again, call the method a second time with an empty string as the argument.
The `invalid` attribute reflects the form control's validity, so you can style invalid fields using the `[invalid]` selector. The example below demonstrates how you can give erroneous fields a different appearance. Type something other than "shoelace" to demonstrate this.
<small slot="help-text">Please enter "shoelace" to continue</small>
</SlInput>
<style>{css}</style>
</>
);
```
### Third-party Validation
To opt out of the browser's built-in validation and use your own, add the `novalidate` attribute to the form. This will ignore all constraints and prevent the browser from showing its own warnings when form controls are invalid.
Remember that the `invalid` attribute on form controls reflects validity as defined by the [Constraint Validation API](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation). You can set it initially, but the `invalid` attribute will update as the user interacts with the form control. As such, you should not rely on it to set invalid styles using a custom validation library.
Instead, toggle a class and target it in your stylesheet as shown below.
You can use Shoelace via CDN or by installing it locally. You can also [cherry pick](#cherry-picking) individual components for faster load times.
If you're using a framework, make sure to check out the pages for [React](/frameworks/react), [Vue](/frameworks/vue), and [Angular](/frameworks/angular).
## CDN Installation (Easiest)
The easiest way to install Shoelace is with the CDN. Just add the following tags to your page to get all components and the default light theme.
If you want to load the light or dark theme based on the user's `prefers-color-scheme` setting, use this. The `media` attributes ensure that only the user's preferred theme stylesheet loads and the `onload` attribute sets the appropriate [theme class](/getting-started/themes) on the `<html>` element.
Now you can [start using Shoelace!](/getting-started/usage)
## Local Installation
If you don't want to use the CDN, you can install Shoelace locally with the following command.
```bash
npm install @shoelace-style/shoelace
```
It's up to you to make the source files available to your app. One way to do this is to create a route in your app called `/shoelace` that serves static files from `node_modules/@shoelace-style/shoelace`.
Once you've done that, add the following tags to your page. Make sure to update `href` and `src` so they point to the route you created.
Alternatively, [you can use a bundler](#bundling).
?> For clarity, the docs will usually show imports from `@shoelace-style/shoelace`. If you're not using a module resolver or bundler, you'll need to adjust these paths to point to the folder Shoelace is in.
## Setting the Base Path
Some components rely on assets (icons, images, etc.) and Shoelace needs to know where they're located. For convenience, Shoelace will try to auto-detect the correct location based on the script you've loaded it from. This assumes assets are colocated with `shoelace.js` and will "just work" for most users.
However, if you're [cherry picking](#cherry-picking) or [bundling](#bundling) Shoelace, you'll need to set the base path. You can do this one of two ways.
?> The library also exports a `getBasePath()` method you can use to reference assets.
## Cherry Picking
The previous approach is the _easiest_ way to load Shoelace, but easy isn't always efficient. You'll incur the full size of the library even if you only use a handful of components. This is convenient for prototyping or if you're using most of the components, but it may result in longer load times in production. To improve this, you can cherry pick the components you need.
Cherry picking can be done from your local install or [directly from the CDN](https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@%VERSION%/). This will limit the number of files the browser has to download and reduce the amount of bytes being transferred. The disadvantage is that you need to load component manually.
Here's an example that loads only the button component. Again, if you're not using a module resolver, you'll need to adjust the path to point to the folder Shoelace is in.
You can copy and paste the code to import a component from the "Importing" section of the component's documentation. Note that some components have dependencies that are automatically imported when you cherry pick. If a component has dependencies, they will be listed in the "Dependencies" section of its docs.
!> Never cherry pick components or utilities from `shoelace.js` as this will cause the browser to load the entire library. Instead, cherry pick from specific modules as shown above.
!> You will see files named `chunk.[hash].js` in the `chunks` directory. Never import these files directly, as they are generated and change from version to version.
## Bundling
Shoelace is distributed as a collection of standard ES modules that [all modern browsers can understand](https://caniuse.com/es6-module). However, importing a lot of modules can result in a lot of HTTP requests and potentially longer load times. Using a CDN can alleviate this, but some users may wish to further optimize their imports with a bundler.
To use Shoelace with a bundler, first install Shoelace along with your bundler of choice.
```bash
npm install @shoelace-style/shoelace
```
Now it's time to configure your bundler. Configurations vary for each tool, but here are some examples to help you get started.
// Set the base path to the folder you copied Shoelace's assets to
setBasePath('/path/to/shoelace/dist');
// <sl-button>, <sl-icon>, <sl-input>, and <sl-rating> are ready to use!
```
!> Component modules include side effects for registration purposes. Because of this, importing directly from `@shoelace-style/shoelace` may result in a larger bundle size than necessary. For optimal tree shaking, always cherry pick, i.e. import components and utilities from their respective files, as shown above.
Designed in New Hampshire by [Cory LaViska](https://twitter.com/claviska).
</div>
<div class="splash-end">
<img class="splash-image" src="/assets/images/undraw-content-team.svg" alt="Cartoon of people assembling components while standing on a giant laptop.">
Now you have access to all of Shoelace's components! Try adding a button:
```html preview expanded
<sl-button>Click me</sl-button>
```
?> This will load all of Shoelace's components, but you should probably only load the ones you're actually using. To learn how, or for other ways to install Shoelace, refer to the [installation instructions](getting-started/installation).
## New to Web Components?
**TL;DR**–we finally have a way to create [our own HTML elements](https://html.spec.whatwg.org/multipage/custom-elements.html) and use them in any framework we want!
Thanks to the popularity of frameworks such as Angular, Vue, and React, component-driven development has become a part of our every day lives. Components help us encapsulate styles and behaviors into reusable building blocks. They make a lot of sense in terms of design, development, and testing.
Unfortunately, _framework-specific_ components fail us in a number of ways:
- You can only use them in the framework they're designed for 🔒
- Their lifespan is limited to that of the framework's ⏳
- New frameworks/versions can lead to breaking changes, requiring substantial effort to update components 😭
Web components solve these problems. They're [supported by all modern browsers](https://caniuse.com/#feat=custom-elementsv1), they're framework-agnostic, and they're [part of the standard](https://developer.mozilla.org/en-US/docs/Web/Web_Components), so we know they'll be supported for many years to come.
This is the technology that Shoelace is built on.
## What Problem Does This Solve?
Shoelace provides a collection of professionally designed, highly customizable UI components built on a framework agnostic technology. Why spend hundreds of hours (or more) building a design system from scratch? Why make a component library that only works with one framework?
With Shoelace, you can:
- Start building things faster (no need to roll your own buttons)
- Build multiple apps with different frameworks that all share the same UI components
- Fully customize components to match your existing designs
- Incrementally adopt components as needed (no need to ditch your framework)
- Upgrade or switch frameworks without rebuilding foundational components
If your organization is looking to build a design system, [Shoelace will save you thousands of dollars](https://medium.com/eightshapes-llc/and-you-thought-buttons-were-easy-26eb5b5c1871).* All the foundational components you need are right here, ready to be customized for your brand. And since it's built on web standards, browsers will continue to support it for many years to come.
Whether you use Shoelace as a starting point for your organization's design system or for a fun personal project, there's no limit to what you can do with it.
<small>*Please consider giving back some of what you save by [supporting this project with a sponsorship](https://github.com/sponsors/claviska).</small>
## Browser Support
Shoelace is tested in the latest two versions of the following browsers.
Critical bug fixes in earlier versions will be addressed based on their severity and impact.
If you need to support IE11 or pre-Chromium Edge, this library isn't for you. Although web components can (to some degree) be polyfilled for legacy browsers, supporting them is outside the scope of this project. If you're using Shoelace in such a browser, you're gonna have a bad time. ⛷
## License
Shoelace is designed in New Hampshire by [Cory LaViska](https://twitter.com/claviska). It's available under the terms of the MIT license.
Designing, developing, and supporting this library requires a lot of time, effort, and skill. If you're using this software to make a profit, I respectfully ask that you help [fund its development](https://github.com/sponsors/claviska) by becoming a sponsor.
Shoelace is designed to be highly customizable through pure CSS. Out of the box, you can choose from a light or dark theme. Alternatively, you can design your own theme.
A theme is nothing more than a stylesheet that uses the Shoelace API to define design tokens and apply custom styles to components. To create a theme, you will need a decent understanding of CSS, including [CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) and the [`::part` selector](https://developer.mozilla.org/en-US/docs/Web/CSS/::part).
?> For component developers, built-in themes are also available as JavaScript modules that export [Lit CSSResult](https://lit.dev/docs/api/styles/#CSSResult) objects. You can find them in `dist/themes/*.styles.js`.
## Theme Basics
All themes are scoped to classes using the `sl-theme-{name}` convention, where `{name}` is a lowercase, hyphen-delimited value representing the name of the theme. The included light and dark themes use `sl-theme-light` and `sl-theme-dark`, respectively. A custom theme called "Purple Power", for example, would use a class called `sl-theme-purple-power`
All selectors must be scoped to the theme's class to ensure interoperability with other themes. You should also scope them to `:host` so they can be imported and applied to custom element shadow roots.
```css
:host,
.sl-theme-purple-power{
/* ... */
}
```
### Activating Themes
To activate a theme, import it and apply the theme's class to the `<html>` element. This example imports and activates the built-in dark theme.
?> There is one exception to this rule — the light theme _does not_ need to be activated. For convenience, the light theme is scoped to `:root` and will be activated by default when imported.
### Using Multiple Themes
You can activate themes on various containers throughout the page. This example uses the light theme with a dark-themed sidebar.
It's for this reason that themes must be scoped to specific classes.
## Creating Themes
There are two ways to create themes. The easiest way is to customize a built-in theme. The advanced way is to create a new theme from scratch. Which method you choose depends on your project's requirements and the amount of effort you're willing to commit to.
### Customizing a Built-in Theme
The easiest way to customize Shoelace is to override one of the built-in themes. You can do this by importing the light or dark theme as-is, then creating a separate stylesheet that overrides [design tokens](/getting-started/customizing#design-tokens) and adds [component styles](/getting-started/customizing#component-parts) to your liking. You must import your theme _after_ the built-in theme.
If you're customizing the light theme, you should scope your styles to the following selectors.
```css
:root,
:host,
.sl-theme-light{
/* your custom styles here */
}
```
If you're customizing the dark theme, you should scope your styles to the following selectors.
```css
:host,
.sl-theme-dark{
/* your custom styles here */
}
```
By customizing a built-in theme, you'll maintain a smaller stylesheet containing only the changes you've made. Contrast this to [creating a new theme](#creating-a-new-theme), where you need to explicitly define every design token required by the library. This approach is more "future-proof," as new design tokens that emerge in subsequent versions of Shoelace will be accounted for by the built-in theme.
While this approach is easier to maintain, the drawback is that your theme can't be activated independently — it's tied to the built-in theme you're extending.
### Creating a New Theme
Creating a new theme is more of an undertaking than [customizing an existing one](#customizing-a-built-in-theme). At a minimum, you must implement all of the required design tokens. The easiest way to do this is by "forking" one of the built-in themes and modifying it from there.
Start by changing the selector to match your theme's name. Assuming your new theme is called "Purple Power", your theme should be scoped like this.
```css
:host,
.sl-theme-purple-power{
/* your custom styles here */
}
```
By creating a new theme, you won't be relying on a built-in theme as a foundation. Because the theme is decoupled from the built-ins, you can activate it independently as an alternative to the built-ins. This is the recommended approach if you're looking to open source your theme for others to use.
You will, however, need to maintain your theme more carefully, as new versions of Shoelace may introduce new design tokens that your theme won't have accounted for. Because of this, it's recommended that you clearly specify which version(s) of Shoelace your theme is designed to work with and keep it up to date as new versions of Shoelace are released.
## Dark Theme
The built-in dark theme uses an inverted color scale so, if you're using design tokens as intended, you'll get dark mode for free. While this isn't the same as a professionally curated dark theme, it provides an excellent baseline for one and you're encouraged to customize it depending on your needs.
The dark theme works by taking the light theme's [color tokens](/tokens/color) and "flipping" the scale so 100 becomes 900, 200 becomes 800, 300 becomes 700, etc. Next, the luminance of each primitive was fine-tuned to avoid true black, which is often undesirable in dark themes, and provide a richer experience. The result is a custom dark palette that complements the light theme and makes it easy to offer light and dark modes with minimal effort.
To install the dark theme, add the following to the `<head>` section of your page.
To activate the theme, apply the `sl-theme-dark` class to the `<html>` element.
```html
<htmlclass="sl-theme-dark">
...
</html>
```
### Detecting the User's Color Scheme Preference
Shoelace doesn't try to auto-detect the user's light/dark mode preference. This should be done at the application level. As a best practice, to provide a dark theme in your app, you should:
- Check for [`prefers-color-scheme`](https://stackoverflow.com/a/57795495/567486) and use its value by default
- Allow the user to override the setting in your app
- Remember the user's preference and restore it on subsequent logins
Shoelace avoids using the `prefers-color-scheme` media query because not all apps support dark mode, and it would break things for the ones that don't.
Shoelace components are just regular HTML elements, or [custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) to be precise. You can use them like any other element. Each component has detailed documentation that describes its full API, including properties, events, methods, and more.
If you're new to custom elements, often referred to as "web components," this section will familiarize you with how to use them.
## Properties
Many components have properties that can be set using attributes. For example, buttons accept a `size` attribute that maps to the `size` property which dictates the button's size.
```html
<sl-buttonsize="small">Click me</sl-button>
```
Some properties are boolean, so they only have true/false values. To activate a boolean property, add the corresponding attribute without a value.
```html
<sl-buttondisabled>Click me</sl-button>
```
In rare cases, a property may require an array, an object, or a function. For example, to customize the color picker's list of preset swatches, you set the `swatches` property to an array of colors. This can be done with JavaScript.
Refer to a component's documentation for a complete list of its properties.
## Events
You can listen for standard events such as `click`, `mouseover`, etc. as you normally would. In addition, some components emit custom events. These work the same way as standard events, but are prefixed with `sl-` to prevent collisions with standard events and other libraries.
Refer to a component's documentation for a complete list of its custom events.
## Methods
Some components have methods you can call to trigger various behaviors. For example, you can set focus on a Shoelace input using the `focus()` method.
```html
<sl-input></sl-input>
<script>
constinput=document.querySelector('sl-input');
input.focus();
</script>
```
Refer to a component's documentation for a complete list of its methods and their arguments.
## Slots
Many components use slots to accept content inside of them. The most common slot is the _default_ slot, which includes any content inside the component that doesn't have a `slot` attribute.
For example, a button's default slot is used to populate its label.
```html
<sl-button>Click me</sl-button>
```
Some components also have _named_ slots. A named slot can be populated by adding a child element with the appropriate `slot` attribute. Notice how the icon below has the `slot="prefix"` attribute? This tells the component to place the icon into its `prefix` slot.
```html
<sl-button>
<sl-iconslot="prefix"name="gear"></sl-icon>
Settings
</sl-button>
```
The location of a named slot doesn't matter. You can put it anywhere inside the component and the browser will move it to the right place automatically!
Refer to a component's documentation for a complete list of available slots.
## Don't Use Self-closing Tags
Custom elements cannot have self-closing tags. Similar to `<script>` and `<textarea>`, you must always include the full closing tag.
```html
<!-- Don't do this -->
<sl-input/>
<!-- Always do this -->
<sl-input></sl-input>
```
## Differences from Native Elements
You might expect similarly named elements to share the same API as native HTML elements. This is not always the case. Shoelace components **are not** designed to be one-to-one replacements for their HTML counterparts.
For example, `<button>` and `<sl-button>` both have a `type` attribute, but it does different things. The former controls whether the button submits a form and the latter controls the button's appearance.
?> **Don't make assumptions about a component's API!** To prevent unexpected behaviors, please take the time to review the documentation and make sure you understand what each attribute, property, method, and event is intended to do.
## Waiting for Components to Load
Web components are registered with JavaScript, so depending on how and when you load Shoelace, you may notice a [Flash of Undefined Custom Elements (FOUCE)](https://www.abeautifulsite.net/posts/flash-of-undefined-custom-elements/) when the page loads. There are a couple ways to prevent this, both of which are described in the linked article.
One option is to use the [`:defined`](https://developer.mozilla.org/en-US/docs/Web/CSS/:defined) CSS pseudo-class to "hide" custom elements that haven't been registered yet. You can scope it to specific tags or you can hide all undefined custom elements as shown below.
```css
:not(:defined){
visibility:hidden;
}
```
As soon as a custom element is registered, it will immediately appear with all of its styles, effectively eliminating FOUCE. Note the use of `visibility: hidden` instead of `display: none` to reduce shifting as elements are registered. The drawback to this approach is that custom elements can potentially appear one by one instead of all at the same time.
Another option is to use [`customElements.whenDefined()`](https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/whenDefined), which returns a promise that resolves when the specified element gets registered. You'll probably want to use it with [`Promise.allSettled()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) in case an element fails to load for some reason.
A clever way to use this method is to hide the `<body>` with `opacity: 0` and add a class that fades it in as soon as all your custom elements are defined.
```html
<style>
body{
opacity:0;
}
body.ready{
opacity:1;
transition:.25sopacity;
}
</style>
<scripttype="module">
awaitPromise.allSettled([
customElements.whenDefined('sl-button'),
customElements.whenDefined('sl-card'),
customElements.whenDefined('sl-rating')
]);
// Button, card, and rating are registered now! Add
// the `ready` class so the UI fades in.
document.body.classList.add('ready');
</script>
```
## Code Completion
### VS Code
Shoelace ships with a file called `vscode.html-custom-data.json` that can be used to describe its components to Visual Studio Code. This enables code completion for Shoelace components (also known as "code hinting" or "IntelliSense"). To enable it, you need to tell VS Code where the file is.
If `settings.json` already exists, simply add the above line to the root of the object. Note that you may need to restart VS Code for the changes to take affect.
### Other Editors
Most popular editors support custom code completion with a bit of configuration. Please [submit a feature request](https://github.com/shoelace-style/shoelace/issues/new/choose) for your editor of choice. PRs are also welcome!
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.