Initial check-in

This commit is contained in:
Elf M. Sternberg 2023-11-26 18:22:07 -08:00
commit c892d44853
12 changed files with 12007 additions and 0 deletions

29
.editorconfig Normal file
View File

@ -0,0 +1,29 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# Change these settings to your own preference
indent_style = space
indent_size = 2
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.json]
indent_size = 2
[*.{html,js,md}]
block_comment_start = /**
block_comment = *
block_comment_end = */

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
## editors
/.idea
/.vscode
## system files
.DS_Store
## npm
/node_modules/
/npm-debug.log
## testing
/coverage/
## temp folders
/.tmp/
# build
/_site/
/dist/
/out-tsc/
storybook-static
custom-elements.json

355
LICENSE.md Normal file
View File

@ -0,0 +1,355 @@
Mozilla Public License Version 2.0
==================================
### 1. Definitions
**1.1. “Contributor”**
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
**1.2. “Contributor Version”**
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
**1.3. “Contribution”**
means Covered Software of a particular Contributor.
**1.4. “Covered Software”**
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
**1.5. “Incompatible With Secondary Licenses”**
means
* **(a)** that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
* **(b)** that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
**1.6. “Executable Form”**
means any form of the work other than Source Code Form.
**1.7. “Larger Work”**
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
**1.8. “License”**
means this document.
**1.9. “Licensable”**
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
**1.10. “Modifications”**
means any of the following:
* **(a)** any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
* **(b)** any new file in Source Code Form that contains any Covered
Software.
**1.11. “Patent Claims” of a Contributor**
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
**1.12. “Secondary License”**
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
**1.13. “Source Code Form”**
means the form of the work preferred for making modifications.
**1.14. “You” (or “Your”)**
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, “control” means **(a)** the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or **(b)** ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
### 2. License Grants and Conditions
#### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
* **(a)** under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
* **(b)** under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
#### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
#### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
* **(a)** for any code that a Contributor has removed from Covered Software;
or
* **(b)** for infringements caused by: **(i)** Your and any other third party's
modifications of Covered Software, or **(ii)** the combination of its
Contributions with other software (except as part of its Contributor
Version); or
* **(c)** under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
#### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
#### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
#### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
#### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
### 3. Responsibilities
#### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
#### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
* **(a)** such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
* **(b)** You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
#### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
#### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
#### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
### 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: **(a)** comply with
the terms of this License to the maximum extent possible; and **(b)**
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
### 5. Termination
**5.1.** The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated **(a)** provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and **(b)** on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
**5.2.** If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
**5.3.** In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
### 6. Disclaimer of Warranty
> Covered Software is provided under this License on an “as is”
> basis, without warranty of any kind, either expressed, implied, or
> statutory, including, without limitation, warranties that the
> Covered Software is free of defects, merchantable, fit for a
> particular purpose or non-infringing. The entire risk as to the
> quality and performance of the Covered Software is with You.
> Should any Covered Software prove defective in any respect, You
> (not any Contributor) assume the cost of any necessary servicing,
> repair, or correction. This disclaimer of warranty constitutes an
> essential part of this License. No use of any Covered Software is
> authorized under this License except under this disclaimer.
### 7. Limitation of Liability
> Under no circumstances and under no legal theory, whether tort
> (including negligence), contract, or otherwise, shall any
> Contributor, or anyone who distributes Covered Software as
> permitted above, be liable to You for any direct, indirect,
> special, incidental, or consequential damages of any character
> including, without limitation, damages for lost profits, loss of
> goodwill, work stoppage, computer failure or malfunction, or any
> and all other commercial damages or losses, even if such party
> shall have been informed of the possibility of such damages. This
> limitation of liability shall not apply to liability for death or
> personal injury resulting from such party's negligence to the
> extent applicable law prohibits such limitation. Some
> jurisdictions do not allow the exclusion or limitation of
> incidental or consequential damages, so this exclusion and
> limitation may not apply to You.
### 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
### 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
### 10. Versions of the License
#### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
#### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
#### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
#### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

285
README.md Normal file
View File

@ -0,0 +1,285 @@
# Emerald Counter
I set out to reproduce the effect from "[The CSS Hack You Need To
Know](https://blog.devgenius.io/the-css-hack-you-need-to-know-7a3c2f7a8ce1)", which is all about
using the `attr()` CSS function to extract an attribute's value from the tag being styled so you can
apply it to a `::after` entry that will display the attribute. The idea is that one could then set:
```
<div class="notification-bell-container" current-count=5><svg ...></svg> </div>
```
And get back something that looks like this:
![Image of the Bell Icon](./bell-image.png)
As I was playing with the source code, I realized that it had one major shortcoming: it didn't scale
well. For every different size, if you wanted the notification circle to be even approximately in
the right the right place you would need to hand-code the location of the counter and have
breakpoint-oriented versions for phone, tablet, desktop, extra-wide, and ten-foot displays.
Can we do better than that? With web components we can do anything.
We're going to use a [bell icon from Icon
Finder](https://www.iconfinder.com/icons/211694/bell_icon), and the first thing we're going to do is
encapsulate it into a component that both shows it and scales it:
After running `npm init @open-wc` and creating a new element called "emerald-counter", find the
source file and put this into it:
```
export class EmeraldCounter extends LitElement {
static styles = css`
:host {
display: inline-block;
}
svg {
position: relative;
display: block;
width: 100%;
height: 100%;
}
`;
render() {
return html`
<svg
id="Layer_1"
version="1.1"
viewBox="0 0 512 512"
xml:space="preserve"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<g>
<path
part="bell"
d="M381.7,225.9c0-97.6-52.5-130.8-101.6-138.2c0-0.5,0.1-1,0.1-1.6c0-12.3-10.9-22.1-24.2-22.1c-13.3,0-23.8,9.8-23.8,22.1 c0,0.6,0,1.1,0.1,1.6c-49.2,7.5-102,40.8-102,138.4c0,113.8-28.3,126-66.3,158h384C410.2,352,381.7,339.7,381.7,225.9z"
/>
<path part="bell" d="M256.2,448c26.8,0,48.8-19.9,51.7-43H204.5C207.3,428.1,229.4,448,256.2,448z" />
</g>
</svg>
`;
}
}
```
The `inline-block` is critical here. By default every web component host is just a `<span>`, and
spans are `inline`, so the SVG will inherit that setting and overflow the container to fill the
entire viewport. That wouldn't have been a problem if I hadn't removed the `width` and `height`
attributes from the `svg` declaration itself, but I had to remove them: the whole point of this
exercises is to scale the web component and have it look good at any scale.
The `viewBox` setting is SVG specifies a _relative space_ in which the element will fit, and the
coordinates in the `<path>` elements fit and fill that space. That whole space will scale relative
to its container and the specified size.
So now, in the `demo/index.html` file that comes with any open-wc component development, we can set:
``` HTML
<style>
emerald-counter: {
width: 4rem;
height: 4rem;
}
</style>
<emerald-counter></emerald-counter>
```
... and we'll see the bell component rendered to fill a space `4rem` on a side. For most people,
that will probably be 64 pixels, since the default base font size shipped with most browsers is 16px
and `rem` is a multiplier of the base font size.
Now to introduce our counter. First, we need a *reference* container that both the SVG and the
counter object will use, and the `:host` container isn't good enough; it needs to be free so that
the user can style it any way she chooses. We also want to introduce our element to display our
counter and the number. As a benefit, we can choose not to show any number when the counter is zero.
So now our `render()` function looks like this:
``` JavaScript
return html`
<div id="main">
<svg> ... </svg>
${ !this.counter || this.counter < 1
? nothing
: html `<div id="counter" part="counter"><span part="number">${this.counter}</span></div>`
}
</div>
`;
```
Obviously, this code includes a new state object that we're tracking: the `counter`. Technically,
this is a property; we're going to read it off the element tag and we're not going to reflect it if
it's changed internally:
``` JavaScript
@property({ type: Number, attribute: "current-count" })
counter = 0;
```
And frankly, at this moment, it looks terrible.
### Stylin'
Everything from this point on is about style. Let's set the stage. First, our host needs *at
least* some sort of block-level definition to keep the SVG from overflowing its borders. Remember
that the `:host` is, by default, treated like a `span`; it gets its size and positions from its
content, rather than defining a container. Also, our icon is square, and we want to keep it that
way:
``` CSS
:host {
display: inline-block;
aspect-ratio: 1 / 1;
}
```
We have wrapped our SVG and our counter in a `div`. That needs to not be a static object, and it
needs to fill its container:
``` CSS
div#main {
position: relative;
display: block;
width: 100%;
height: 100%;
}
```
The use of `id` inside a WebComponent is strictly limited to *inside* the WebComponent; this `id` is
not visible to the outside world and will not show up on any scans of the top-level HTML. There are
sophisticated libraries for reaching into WebComponents, mostly for testing purposes, and they can
find objects by ID, but only after you've anchored them on the host object itself.
In a way, all WebComponent `:host` objects represent a border between what the container can know
and do to your component, and what the component should know and see about the surrounding context.
Understanding and honoring that distinction will help keep you from writing "React, but in Lit."
Continuing on, our SVG is likewise going to be sized relative to its container:
```CSS
svg {
position: relative;
display: block;
width: 100%;
height: 100%;
z-index: 0;
}
```
And this is where things get... fiddly.
It's unfortunate, but the placement of the counter can't really be abstracted into a formula. Where
it goes, what size it's going to be, and so forth, are dependent upon the icon itself, and the
aesthetic judgement needed to say "That looks right" can't be taught to a machine, not even an LLM,
at least not yet.
What we can say is that we want it to be a grid, so that we can perfectly center the number within
it, and we want it to be above the SVG. We can handle that by setting the SVG's z-index below that
of the counter. Remember that the z-index is *relative* to its container and is isolated within the
`:host`, so "0" and "1" are perfect for our purposes. We want the counter's number to be about a
quarter the size of the whole icon, and we need to give it both a some space with respect to the
dot, and to give it a border so it's separate from the icon. Most of the following is reusable, but
the `top`, `left`, and `padding-top` were (and for the foreseeable future, will be) positioned by
eyeball and guesswork.
```
div#counter {
display: grid;
justify-content: center;
align-content: center;
position: absolute;
z-index: 1;
font-family: "Helvetica Neue", "Arial Nova", Helvetica, Arial, sans-serif;
font-size: 1em;
top: 8%;
left: 60%;
width: 30%;
height: 30%;
aspect-ratio: 1 / 1;
border-radius: 50%;
border: 0.2em solid white;
font-weight: bold;
background: red;
color: white;
}
div#counter span {
padding-top: 0.28em;
vertical-align: text-bottom;
}
```
Now, in our `index.html`, we're going to include a new style block, and we're going to define an
auto-scaling [CSS Custom
Property](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties). Like so:
```HTML
<style>
:root {
--step-0: clamp(0.75rem, 0.491rem + 1.295vw, 3rem);
}
emerald-counter {
--counter-size: calc(var(--step-0) * 4);
width: var(--counter-size);
font-size: var(--counter-size);
}
</style>
```
It is a shortcoming of CSS that we want our font-size to scale with the width of the object, but we
can't really achieve that. So we have to set both, so that the `em` fields in our code correctly get
the right sizes. Using a CSS Custom Property allows us to do the calculation once; harder to get it
wrong that way, avoids [the last line phenomenon](https://dl.acm.org/doi/10.1007/s10664-016-9489-6).
It may seem odd that we set it to the same multiplier as the width setting, but if you look at the
CSS above you'll see that both the relative size of the counter and its positioning are set in
fractions of an 'em'. This allows all the sub-components of the web component to scale *and
position* together correctly regardless of the font size, creating pixel-perfect positioning within
the component.
But see that `:root` setting? We're creating a new variable, `--step`, and we're setting it to be
somewhere between 12px and 48px, where exactly is a factor of some multiple of the viewport width,
but it's `clamp`ed so that it can't exceed those two settings. You can see, then, that if you change
the viewport width, the notification icon scales correctly and smoothly:
<video controls style="width: 80%">
<source src="./rescaling.webm" type="video/webm" />
</video>
The result is simple enough. You can now just say:
```
<emerald-counter current-count=5></emerald-counter>
```
And you'll see this:
<script type="module" src="./emerald-counter.js"></script>
<style>
:root {
--demo-step-0: clamp(0.75rem, 0.491rem + 1.295vw, 3rem);
}
emerald-counter {
--counter-size: calc(var(--demo-step-0) * 4);
width: var(--counter-size);
font-size: var(--counter-size);
}
.emerald-counter-demo {
width: 100%;
height: 6rem;
display: grid;
justify-content: center;
align-content: center;
}
</style>
<div class="emerald-counter-demo">
<emerald-counter current-count=5></emerald-counter>
</div>
I'm a big fan of dynamic scaling, if you resize the window horizontally you'll see that the fonts,
images, and so forth that I use scale smoothly with the resizing of the viewport. And now there's at
least one notification icon that scales smoothly along with everything else. I count that as a win.

29
assets/open-wc-logo.svg Normal file
View File

@ -0,0 +1,29 @@
<svg
width="244px"
height="244px"
viewBox="0 0 244 244"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<defs>
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-1">
<stop stop-color="#9B00FF" offset="0%"></stop>
<stop stop-color="#0077FF" offset="100%"></stop>
</linearGradient>
</defs>
<g
id="Page-1"
stroke="none"
stroke-width="1"
fill="none"
fill-rule="evenodd"
>
<path
d="M205.639259,176.936244 C207.430887,174.217233 209.093339,171.405629 210.617884,168.510161 M215.112174,158.724316 C216.385153,155.50304 217.495621,152.199852 218.433474,148.824851 M220.655293,138.874185 C221.231935,135.482212 221.637704,132.03207 221.863435,128.532919 M222,118.131039 C221.860539,114.466419 221.523806,110.85231 221.000113,107.299021 M218.885321,96.8583653 C218.001583,93.4468963 216.942225,90.1061026 215.717466,86.8461994 M211.549484,77.3039459 C209.957339,74.1238901 208.200597,71.0404957 206.290425,68.0649233 M200.180513,59.5598295 C181.848457,36.6639805 153.655709,22 122.036748,22 C66.7879774,22 22,66.771525 22,122 C22,177.228475 66.7879774,222 122.036748,222 C152.914668,222 180.52509,208.015313 198.875424,186.036326"
id="Shape"
stroke="url(#linearGradient-1)"
stroke-width="42.0804674"
></path>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

36
index.html Normal file
View File

@ -0,0 +1,36 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="Description" content="Put your description here.">
<base href="/">
<style>
html,
body {
margin: 0;
padding: 0;
font-family: sans-serif;
background-color: #ffffff;
}
:root {
--step-0: clamp(0.75rem, 0.491rem + 1.295vw, 3rem);
}
emerald-counter {
--counter-size: calc(var(--step-0) * 4);
width: var(--counter-size);
font-size: var(--counter-size);
}
</style>
<title>emerald-counter</title>
</head>
<body>
<emerald-counter current-count=6></emerald-counter>
<script type="module" src="./out-tsc/src/emerald-counter.js"></script>
</body>
</html>

10959
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

86
package.json Normal file
View File

@ -0,0 +1,86 @@
{
"name": "emerald-counter",
"description": "Webcomponent emerald-counter following open-wc recommendations",
"license": "MIT",
"author": "emerald-counter",
"version": "0.0.0",
"type": "module",
"scripts": {
"lint": "eslint --ext .ts,.html . --ignore-path .gitignore && prettier \"**/*.ts\" --check --ignore-path .gitignore",
"format": "eslint --ext .ts,.html . --fix --ignore-path .gitignore && prettier \"**/*.ts\" --write --ignore-path .gitignore",
"build": "rimraf dist && tsc && rollup -c rollup.config.js && npm run analyze -- --exclude dist",
"start:build": "web-dev-server --root-dir dist --app-index index.html --open",
"analyze": "cem analyze --litelement",
"start": "tsc && concurrently -k -r \"tsc --watch --preserveWatchOutput\" \"wds\""
},
"dependencies": {
"lit": "^2.0.2"
},
"devDependencies": {
"@babel/preset-env": "^7.16.4",
"@custom-elements-manifest/analyzer": "^0.4.17",
"@open-wc/building-rollup": "^2.0.2",
"@open-wc/eslint-config": "^9.2.1",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-node-resolve": "^13.0.6",
"@typescript-eslint/eslint-plugin": "^5.48.0",
"@typescript-eslint/parser": "^5.48.0",
"@web/dev-server": "^0.1.34",
"@web/rollup-plugin-html": "^1.11.0",
"@web/rollup-plugin-import-meta-assets": "^1.0.7",
"babel-plugin-template-html-minifier": "^4.1.0",
"concurrently": "^5.3.0",
"deepmerge": "^4.2.2",
"eslint": "^8.31.0",
"eslint-config-prettier": "^8.3.0",
"husky": "^4.3.8",
"lint-staged": "^10.5.4",
"prettier": "^2.4.1",
"rimraf": "^3.0.2",
"rollup": "^2.60.0",
"rollup-plugin-esbuild": "^5.0.0",
"rollup-plugin-workbox": "^6.2.0",
"tslib": "^2.3.1",
"typescript": "^4.5.2"
},
"eslintConfig": {
"parser": "@typescript-eslint/parser",
"extends": [
"@open-wc",
"prettier"
],
"plugins": [
"@typescript-eslint"
],
"rules": {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error"
],
"import/no-unresolved": "off",
"import/extensions": [
"error",
"always",
{
"ignorePackages": true
}
]
}
},
"prettier": {
"singleQuote": true,
"arrowParens": "avoid"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.ts": [
"eslint --fix",
"prettier --write"
]
},
"customElements": "custom-elements.json"
}

71
rollup.config.js Normal file
View File

@ -0,0 +1,71 @@
import nodeResolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import html from '@web/rollup-plugin-html';
import { importMetaAssets } from '@web/rollup-plugin-import-meta-assets';
import esbuild from 'rollup-plugin-esbuild';
import { generateSW } from 'rollup-plugin-workbox';
import path from 'path';
export default {
input: 'index.html',
output: {
entryFileNames: '[hash].js',
chunkFileNames: '[hash].js',
assetFileNames: '[hash][extname]',
format: 'es',
dir: 'dist',
},
preserveEntrySignatures: false,
plugins: [
/** Enable using HTML as rollup entrypoint */
html({
minify: true,
injectServiceWorker: true,
serviceWorkerPath: 'dist/sw.js',
}),
/** Resolve bare module imports */
nodeResolve(),
/** Minify JS, compile JS to a lower language target */
esbuild({
minify: true,
target: ['chrome64', 'firefox67', 'safari11.1'],
}),
/** Bundle assets references via import.meta.url */
importMetaAssets(),
/** Minify html and css tagged template literals */
babel({
plugins: [
[
require.resolve('babel-plugin-template-html-minifier'),
{
modules: { lit: ['html', { name: 'css', encapsulation: 'style' }] },
failOnError: false,
strictCSS: true,
htmlMinifier: {
collapseWhitespace: true,
conservativeCollapse: true,
removeComments: true,
caseSensitive: true,
minifyCSS: true,
},
},
],
],
}),
/** Create and inject a service worker */
generateSW({
globIgnores: ['polyfills/*.js', 'nomodule-*.js'],
navigateFallback: '/index.html',
// where to output the generated sw
swDest: path.join('dist', 'sw.js'),
// directory to match patterns against to be precached
globDirectory: path.join('dist'),
// cache any html js and css by default
globPatterns: ['**/*.{html,js,css,webmanifest}'],
skipWaiting: true,
clientsClaim: true,
runtimeCaching: [{ urlPattern: 'polyfills/*.js', handler: 'CacheFirst' }],
}),
],
};

87
src/emerald-counter.ts Normal file
View File

@ -0,0 +1,87 @@
import { LitElement, html, css, nothing } from 'lit';
import { property, customElement } from 'lit/decorators.js';
@customElement('emerald-counter')
export class EmeraldCounter extends LitElement {
static styles = css`
:host {
display: inline-block;
aspect-ratio: 1 / 1;
}
div#main {
position: relative;
display: block;
width: 100%;
height: 100%;
}
svg {
position: relative;
display: block;
width: 100%;
height: 100%;
z-index: 0;
}
div#counter {
display: grid;
justify-content: center;
align-content: center;
position: absolute;
z-index: 1;
font-family: "Helvetica Neue", "Arial Nova", Helvetica, Arial, sans-serif;
font-size: 0.25em;
top: 8%;
left: 60%;
width: 30%;
height: 30%;
aspect-ratio: 1 / 1;
border-radius: 50%;
border: 0.2em solid white;
font-weight: bold;
background: red;
color: white;
}
div#counter span {
padding-top: 0.28em;
vertical-align: text-bottom;
}
`;
@property({ type: Number, attribute: "current-count" })
counter = 0;
@property({ attribute: "icon-color" })
color = "#000000";
render() {
return html`
<div id="main">
<svg
id="Layer_1"
version="1.1"
viewBox="0 0 512 512"
xml:space="preserve"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
part="bell"
>
<g>
<path
style="stroke: ${this.color}; fill: ${this.color}"
d="M381.7,225.9c0-97.6-52.5-130.8-101.6-138.2c0-0.5,0.1-1,0.1-1.6c0-12.3-10.9-22.1-24.2-22.1c-13.3,0-23.8,9.8-23.8,22.1 c0,0.6,0,1.1,0.1,1.6c-49.2,7.5-102,40.8-102,138.4c0,113.8-28.3,126-66.3,158h384C410.2,352,381.7,339.7,381.7,225.9z"
/>
<path
style="stroke: ${this.color}; fill: ${this.color}"
d="M256.2,448c26.8,0,48.8-19.9,51.7-43H204.5C207.3,428.1,229.4,448,256.2,448z"
/>
</g>
</svg>
${!this.counter || this.counter < 1
? nothing
: html`<div id="counter" part="counter"><span part="number">${this.counter}</span></div>`}
</div>
`;
}
}

20
tsconfig.json Normal file
View File

@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"moduleResolution": "node",
"noEmitOnError": true,
"lib": ["es2017", "dom"],
"strict": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"importHelpers": true,
"outDir": "out-tsc",
"sourceMap": true,
"inlineSources": true,
"rootDir": "./",
"incremental": true
},
"include": ["**/*.ts"]
}

26
web-dev-server.config.mjs Normal file
View File

@ -0,0 +1,26 @@
// import { hmrPlugin, presets } from '@open-wc/dev-server-hmr';
/** Use Hot Module replacement by adding --hmr to the start command */
const hmr = process.argv.includes('--hmr');
export default /** @type {import('@web/dev-server').DevServerConfig} */ ({
open: '/',
watch: !hmr,
/** Resolve bare module imports */
nodeResolve: {
exportConditions: ['browser', 'development'],
},
/** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */
// esbuildTarget: 'auto'
/** Set appIndex to enable SPA routing */
appIndex: './index.html',
plugins: [
/** Use Hot Module Replacement by uncommenting. Requires @open-wc/dev-server-hmr plugin */
// hmr && hmrPlugin({ exclude: ['**/*/node_modules/**/*'], presets: [presets.litElement] }),
],
// See documentation for all available options
});