@redvars/peacock 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/.editorconfig +29 -0
  2. package/.husky/pre-commit +1 -0
  3. package/LICENSE +21 -0
  4. package/README.md +46 -0
  5. package/custom-elements-manifest.config.mjs +34 -0
  6. package/custom-elements.md +252 -0
  7. package/demo/index.html +24 -0
  8. package/demo/tokens.css +510 -0
  9. package/dist/src/LoaderUtils.d.ts +23 -0
  10. package/dist/src/LoaderUtils.js +81 -0
  11. package/dist/src/LoaderUtils.js.map +1 -0
  12. package/dist/src/avatar/avatar.css.d.ts +1 -0
  13. package/dist/src/avatar/avatar.css.js +41 -0
  14. package/dist/src/avatar/avatar.css.js.map +1 -0
  15. package/dist/src/avatar/avatar.d.ts +14 -0
  16. package/dist/src/avatar/avatar.js +44 -0
  17. package/dist/src/avatar/avatar.js.map +1 -0
  18. package/dist/src/icon/datasource.d.ts +2 -0
  19. package/dist/src/icon/datasource.js +20 -0
  20. package/dist/src/icon/datasource.js.map +1 -0
  21. package/dist/src/icon/icon.css.d.ts +1 -0
  22. package/dist/src/icon/icon.css.js +22 -0
  23. package/dist/src/icon/icon.css.js.map +1 -0
  24. package/dist/src/icon/icon.d.ts +26 -0
  25. package/dist/src/icon/icon.js +119 -0
  26. package/dist/src/icon/icon.js.map +1 -0
  27. package/dist/src/icon/p-icon.d.ts +3 -0
  28. package/dist/src/icon/p-icon.js +10 -0
  29. package/dist/src/icon/p-icon.js.map +1 -0
  30. package/dist/src/index.d.ts +2 -0
  31. package/dist/src/index.js +3 -0
  32. package/dist/src/index.js.map +1 -0
  33. package/dist/src/peacock-loader.d.ts +1 -0
  34. package/dist/src/peacock-loader.js +16 -0
  35. package/dist/src/peacock-loader.js.map +1 -0
  36. package/dist/src/utils.d.ts +3 -0
  37. package/dist/src/utils.js +101 -0
  38. package/dist/src/utils.js.map +1 -0
  39. package/dist/test/icon.test.d.ts +1 -0
  40. package/dist/test/icon.test.js +14 -0
  41. package/dist/test/icon.test.js.map +1 -0
  42. package/dist/tsconfig.tsbuildinfo +1 -0
  43. package/package.json +87 -0
  44. package/readme-gen.mjs +11 -0
  45. package/rollup.config.js +19 -0
  46. package/src/LoaderUtils.ts +121 -0
  47. package/src/avatar/avatar.css.ts +41 -0
  48. package/src/avatar/avatar.ts +39 -0
  49. package/src/avatar/demo/index.html +26 -0
  50. package/src/icon/datasource.ts +28 -0
  51. package/src/icon/demo/index.html +25 -0
  52. package/src/icon/icon.css.ts +22 -0
  53. package/src/icon/icon.ts +117 -0
  54. package/src/icon/p-icon.ts +5 -0
  55. package/src/index.ts +2 -0
  56. package/src/peacock-loader.ts +17 -0
  57. package/src/utils.ts +118 -0
  58. package/test/icon.test.ts +16 -0
  59. package/tsconfig.json +22 -0
  60. package/web-dev-server.config.js +27 -0
  61. package/web-test-runner.config.js +41 -0
@@ -0,0 +1,117 @@
1
+ import { html, LitElement } from 'lit';
2
+ import { property, state } from 'lit/decorators.js';
3
+ import { unsafeSVG } from 'lit/directives/unsafe-svg.js';
4
+ import { fetchIcon, fetchSVG } from './datasource.js';
5
+ import { sanitizeSvg } from '../utils.js';
6
+ import { styles } from './icon.css.js';
7
+
8
+ /**
9
+ * @summary Icons are visual symbols used to represent ideas, objects, or actions.
10
+ *
11
+ * @cssprop --icon-color - Controls the color of the icon.
12
+ * @cssprop [--icon-size=1rem] - Controls the size of the icon. Defaults to "1rem"
13
+ */
14
+ export class Icon extends LitElement {
15
+ static styles = [styles];
16
+
17
+ @property({ type: String, reflect: true }) name?: string = 'home';
18
+
19
+ @property({ type: String, reflect: true }) src?: string;
20
+
21
+ @property({ type: String }) provider?: 'material-symbols' | 'carbon' =
22
+ 'material-symbols';
23
+
24
+ @state()
25
+ private svgContent: string = '';
26
+
27
+ // loading + error states for consumers/tests
28
+ @state()
29
+ private loading: boolean = false;
30
+
31
+ @state()
32
+ private error: Error | null = null;
33
+
34
+ // token to avoid race conditions when multiple fetches overlap
35
+ private _fetchId = 0;
36
+
37
+ // optional debounce for rapid property changes
38
+ private _debounceTimer: number | undefined;
39
+
40
+ firstUpdated() {
41
+ // perform initial fetch once component is connected and rendered
42
+ this.__scheduleUpdate();
43
+ }
44
+
45
+ updated(changedProperties: any) {
46
+ // only refetch when name or src changed
47
+ if (changedProperties.has('name') || changedProperties.has('src')) {
48
+ this.__scheduleUpdate();
49
+ }
50
+ }
51
+
52
+ render() {
53
+ // accessible wrapper; consumers can provide a fallback via <slot name="fallback">.
54
+ return html` <div class="icon">
55
+ ${this.svgContent
56
+ ? unsafeSVG(this.svgContent)
57
+ : html`<slot name="fallback"></slot>`}
58
+ </div>`;
59
+ }
60
+
61
+ // small debounce to coalesce rapid changes (50ms)
62
+ private __scheduleUpdate() {
63
+ if (this._debounceTimer) {
64
+ clearTimeout(this._debounceTimer as any);
65
+ }
66
+ // @ts-ignore - setTimeout in DOM returns number
67
+ this._debounceTimer = window.setTimeout(() => this.__updateSvg(), 50);
68
+ }
69
+
70
+ /**
71
+ * @internal
72
+ */
73
+ private async __updateSvg() {
74
+ this._fetchId += 1;
75
+ const currentId = this._fetchId;
76
+ this.loading = true;
77
+ this.error = null;
78
+
79
+ try {
80
+ let raw: string | undefined;
81
+
82
+ if (this.name) {
83
+ raw = await fetchIcon(this.name, this.provider);
84
+ } else if (this.src) {
85
+ raw = await fetchSVG(this.src);
86
+ } else {
87
+ raw = '';
88
+ }
89
+
90
+ // If another fetch started after this one, ignore this result
91
+ if (currentId !== this._fetchId) return;
92
+
93
+ if (raw) {
94
+ this.svgContent = sanitizeSvg(raw);
95
+ } else {
96
+ this.svgContent = '';
97
+ }
98
+ } catch (err: any) {
99
+ // capture and surface error, but avoid throwing
100
+ this.error = err instanceof Error ? err : new Error(String(err));
101
+ this.svgContent = '';
102
+ // bubble an event so consumers can react
103
+ this.dispatchEvent(
104
+ new CustomEvent('icon-error', {
105
+ detail: { name: this.name, src: this.src, error: this.error },
106
+ bubbles: true,
107
+ composed: true,
108
+ }),
109
+ );
110
+ } finally {
111
+ // ensure loading is cleared unless another fetch started
112
+ if (currentId === this._fetchId) {
113
+ this.loading = false;
114
+ }
115
+ }
116
+ }
117
+ }
@@ -0,0 +1,5 @@
1
+ import { customElement } from 'lit/decorators.js';
2
+ import { Icon } from './icon.js';
3
+
4
+ @customElement('p-icon')
5
+ export class IconComponent extends Icon {}
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { Icon } from './icon/icon.js';
2
+ export { Avatar } from './avatar/avatar.js';
@@ -0,0 +1,17 @@
1
+ // Eager loaded
2
+ import { Icon } from './icon/icon.js';
3
+ import { LoaderConfig, LoaderUtils } from './LoaderUtils.js';
4
+
5
+ const loaderConfig: LoaderConfig = {
6
+ prefix: 'p',
7
+ components: {
8
+ icon: {
9
+ CustomElementClass: Icon,
10
+ },
11
+ avatar: {
12
+ importPath: './avatar/avatar.js',
13
+ },
14
+ },
15
+ };
16
+
17
+ new LoaderUtils(loaderConfig).start();
package/src/utils.ts ADDED
@@ -0,0 +1,118 @@
1
+ export async function createCacheFetch(name: string) {
2
+ let cache: Cache | null = null;
3
+ // This map tracks requests currently being processed
4
+ const inFlightRequests = new Map<string, Promise<string>>();
5
+
6
+ try {
7
+ cache = await window.caches.open(name);
8
+ } catch (e) {
9
+ console.warn('window.caches access not allowed');
10
+ }
11
+
12
+ return async (url: string): Promise<string> => {
13
+ // 1. Check if we are already fetching this URL
14
+ if (inFlightRequests.has(url)) {
15
+ // Return the existing promise instead of starting a new one
16
+ return inFlightRequests.get(url)!;
17
+ }
18
+
19
+ // 2. Create the main logic as a promise
20
+ const fetchPromise = (async () => {
21
+ const request = new Request(url);
22
+
23
+ // Check Cache first
24
+ if (cache) {
25
+ const cachedResponse = await cache.match(request);
26
+ if (cachedResponse) {
27
+ return await cachedResponse.text();
28
+ }
29
+ }
30
+
31
+ // Prepare network request
32
+ const urlObj = new URL(request.url);
33
+ const isSameOrigin = urlObj.origin === window.location.origin;
34
+
35
+ const response = await fetch(request.url, {
36
+ method: 'GET',
37
+ mode: isSameOrigin ? 'no-cors' : 'cors',
38
+ credentials: isSameOrigin ? 'same-origin' : 'omit',
39
+ });
40
+
41
+ // --- Handle 404 ---
42
+ if (response.status === 404) {
43
+ console.error(`[Fetch Error] Resource not found (404): ${url}`);
44
+ return ''; // Return empty string as requested
45
+ }
46
+
47
+ const result = await response.text();
48
+
49
+ // Update Cache if applicable
50
+ if (cache && response.status === 200) {
51
+ // We clone the response logic by creating a new Response with the text body
52
+ await cache.put(
53
+ request,
54
+ new Response(result, {
55
+ status: response.status,
56
+ statusText: response.statusText,
57
+ headers: response.headers,
58
+ }),
59
+ );
60
+ }
61
+
62
+ return result;
63
+ })();
64
+
65
+ // 3. Store the promise in the map
66
+ inFlightRequests.set(url, fetchPromise);
67
+
68
+ try {
69
+ // 4. Wait for the result
70
+ return await fetchPromise;
71
+ } finally {
72
+ // 5. Clean up: Remove the promise from the map when done
73
+ // This ensures subsequent calls (after this one finishes) can start fresh
74
+ inFlightRequests.delete(url);
75
+ }
76
+ };
77
+ }
78
+
79
+ // Basic sanitization: remove <script>, <foreignObject>, event handler attributes (on*), and iframes
80
+ export function sanitizeSvg(rawSvg: string) {
81
+ try {
82
+ const parser = new DOMParser();
83
+ const doc = parser.parseFromString(rawSvg, 'image/svg+xml');
84
+
85
+ // remove script tags
86
+ const scripts = Array.from(doc.querySelectorAll('script'));
87
+ scripts.forEach(n => n.remove());
88
+
89
+ // remove foreignObject and iframe-like elements
90
+ const foreigns = Array.from(doc.querySelectorAll('foreignObject, iframe'));
91
+ foreigns.forEach(n => n.remove());
92
+
93
+ // remove event handler attributes like onload, onclick, etc.
94
+ const all = Array.from(doc.querySelectorAll('*'));
95
+ all.forEach(el => {
96
+ const attrs = Array.from(el.attributes).filter(a => /^on/i.test(a.name));
97
+ attrs.forEach(a => el.removeAttribute(a.name));
98
+ });
99
+
100
+ const el = doc.documentElement;
101
+ if (!el) return '';
102
+
103
+ // serialize back to string
104
+ const serializer = new XMLSerializer();
105
+ return serializer.serializeToString(el);
106
+ } catch (e) {
107
+ // parsing failed; fall back to empty content to avoid injecting unsafe content
108
+ return '';
109
+ }
110
+ }
111
+
112
+ export const getTypography = (name: string) => `
113
+ font-family: var(--typography-${name}-font-family) !important;
114
+ font-size: var(--typography-${name}-font-size) !important;
115
+ font-weight: var(--typography-${name}-font-weight) !important;
116
+ line-height: var(--typography-${name}-line-height) !important;
117
+ letter-spacing: var(--typography-${name}-letter-spacing) !important;
118
+ `;
@@ -0,0 +1,16 @@
1
+ import { html } from 'lit';
2
+ import { fixture, expect } from '@open-wc/testing';
3
+ import { Icon } from '../src/index.js';
4
+ import '../src/p-icon.js';
5
+
6
+ describe('Icon', () => {
7
+ it('has a default name as home', async () => {
8
+ const el = await fixture<Icon>(html`<p-icon></p-icon>`);
9
+ expect(el.name).to.equal('home');
10
+ });
11
+
12
+ it('passes the a11y audit', async () => {
13
+ const el = await fixture<Icon>(html`<p-icon></p-icon>`);
14
+ await expect(el).shadowDom.to.be.accessible();
15
+ });
16
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2021",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "noEmitOnError": true,
7
+ "lib": ["es2021", "dom", "DOM.Iterable"],
8
+ "strict": true,
9
+ "esModuleInterop": false,
10
+ "allowSyntheticDefaultImports": true,
11
+ "experimentalDecorators": true,
12
+ "importHelpers": true,
13
+ "outDir": "dist",
14
+ "sourceMap": true,
15
+ "inlineSources": true,
16
+ "rootDir": "./",
17
+ "declaration": true,
18
+ "incremental": true,
19
+ "skipLibCheck": true
20
+ },
21
+ "include": ["**/*.ts"]
22
+ }
@@ -0,0 +1,27 @@
1
+ // import { hmrPlugin, presets } from '@open-wc/dev-server-hmr';
2
+
3
+ /** Use Hot Module replacement by adding --hmr to the start command */
4
+ const hmr = process.argv.includes('--hmr');
5
+
6
+ export default /** @type {import('@web/dev-server').DevServerConfig} */ ({
7
+ open: '/demo/',
8
+ /** Use regular watch mode if HMR is not enabled. */
9
+ watch: !hmr,
10
+ /** Resolve bare module imports */
11
+ nodeResolve: {
12
+ exportConditions: ['browser', 'development'],
13
+ },
14
+
15
+ /** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */
16
+ // esbuildTarget: 'auto'
17
+
18
+ /** Set appIndex to enable SPA routing */
19
+ // appIndex: 'demo/index.html',
20
+
21
+ plugins: [
22
+ /** Use Hot Module Replacement by uncommenting. Requires @open-wc/dev-server-hmr plugin */
23
+ // hmr && hmrPlugin({ exclude: ['**/*/node_modules/**/*'], presets: [presets.lit] }),
24
+ ],
25
+
26
+ // See documentation for all available options
27
+ });
@@ -0,0 +1,41 @@
1
+ // import { playwrightLauncher } from '@web/test-runner-playwright';
2
+
3
+ const filteredLogs = ['Running in dev mode', 'Lit is in dev mode'];
4
+
5
+ export default /** @type {import("@web/test-runner").TestRunnerConfig} */ ({
6
+ /** Test files to run */
7
+ files: 'dist/test/**/*.test.js',
8
+
9
+ /** Resolve bare module imports */
10
+ nodeResolve: {
11
+ exportConditions: ['browser', 'development'],
12
+ },
13
+
14
+ /** Filter out lit dev mode logs */
15
+ filterBrowserLogs(log) {
16
+ for (const arg of log.args) {
17
+ if (typeof arg === 'string' && filteredLogs.some(l => arg.includes(l))) {
18
+ return false;
19
+ }
20
+ }
21
+ return true;
22
+ },
23
+
24
+ /** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */
25
+ // esbuildTarget: 'auto',
26
+
27
+ /** Amount of browsers to run concurrently */
28
+ // concurrentBrowsers: 2,
29
+
30
+ /** Amount of test files per browser to test concurrently */
31
+ // concurrency: 1,
32
+
33
+ /** Browsers to run tests on */
34
+ // browsers: [
35
+ // playwrightLauncher({ product: 'chromium' }),
36
+ // playwrightLauncher({ product: 'firefox' }),
37
+ // playwrightLauncher({ product: 'webkit' }),
38
+ // ],
39
+
40
+ // See documentation for all available options
41
+ });