line-flex-message-preview 0.0.0-stage → 0.1.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.
@@ -0,0 +1,132 @@
1
+ var pe={none:0,xs:2,sm:4,md:8,lg:12,xl:16,xxl:20};function w(t,e=t,n=t,i=e){return[t,e,n,i]}function T(t,e,n,i,r,s=0){return{maxWidth:t,cornerRadius:e,inset:s,headerPadding:n,bodyPadding:i,bodyPaddingBottomWithFooter:r,footerPadding:w(10)}}var Y=Object.freeze({name:"simulator",spacing:pe,textSize:{xxs:11,xs:13,sm:14,md:16,lg:19,xl:22,xxl:29,"3xl":35,"4xl":48,"5xl":74},imageSize:{xxs:40,xs:60,sm:80,md:100,lg:120,xl:140,xxl:160,"3xl":180,"4xl":200,"5xl":220},cornerRadius:pe,borderWidth:{none:0,light:.5,normal:1,medium:2,"semi-bold":3,bold:4},bubble:{nano:T(120,10,w(10),w(10),10),micro:T(160,10,w(10),w(10),10),deca:T(220,10,w(11,14,13),w(11,14,13),17),hecto:T(241,10,w(11,14,13),w(11,14,13),17),kilo:T(260,10,w(13),w(13),17),mega:T(300,17,w(20),w(19,20,20),10),giga:T(500,5,w(20),w(19,20,20),10,7)},button:{height:{md:52,sm:40},paddingInline:16,cornerRadius:8,fontSize:16,primary:{background:"#17c950",color:"#ffffff"},secondary:{background:"#dcdfe5",color:"#111111"},link:{color:"#42659a"}},carousel:{itemWidthPercent:80,leadingGap:7,gap:9,trailingGap:7},textColor:"#444444",bubbleBackground:"#ffffff",separatorColor:"#d4d6da",lineHeight:"1.4",maxLines:!1,lineSpacing:!1}),ye=Object.freeze({...Y,name:"ios",bubble:{...Y.bubble,giga:{...Y.bubble.giga,inset:8}},lineHeight:"max(1.2em, 16px)",maxLines:!0,lineSpacing:!0}),ge=Object.freeze({ios:ye,simulator:Y}),be=ye;function X(t){return t==null?be:typeof t!="string"?t:Object.hasOwn(ge,t)?ge[t]:be}var Me=/^(-?\d+(?:\.\d+)?)(px|%)$/,Ie=/^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i,Ve=/^(-?\d+(?:\.\d+)?)deg$/,Fe=/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/;function k(t,e={}){if(typeof t!="string")return;let n=Me.exec(t);if(!n)return;let i=n[2];if(i==="%"&&!e.percent)return;let r=Number(n[1]);return Number.isFinite(r)?{n:r,unit:i}:void 0}function C(t){return`${t.n}${t.unit}`}function x(t){return typeof t=="string"&&Ie.test(t)?t.toLowerCase():void 0}function Z(t){if(typeof t!="string")return;let e=Ve.exec(t);if(!e)return;let n=Number(e[1]);return Number.isFinite(n)?n:void 0}function G(t){if(typeof t!="string")return;let e=Fe.exec(t);if(!e)return;let n=Number(e[1]),i=Number(e[2]);return n>0&&i>0&&Number.isFinite(n)&&Number.isFinite(i)?[n,i]:void 0}function W(t){if(typeof t!="string"||t.length>2e3)return;let e;try{e=new URL(t)}catch{return}if(!(e.protocol!=="https:"||e.username!==""||e.password!==""))return e.href}function H(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function P(t,e){return typeof e=="string"&&Object.hasOwn(t,e)?t[e]:void 0}function d(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Je="\u200B";function f(t,e,n=[]){return{tag:t,classes:e,style:new Map,attrs:{},children:n}}function v(t){return`${t}px`}function Q(t,e,n=!1){let i=P(e.spacing,t);if(i!==void 0)return v(i);let r=k(t,{percent:n});return r&&C(r)}function he(t,e){let n=P(e.textSize,t);if(n!==void 0)return v(n);let i=k(t);return i&&i.n>=0?C(i):void 0}function ne(t){return t.position==="absolute"}function I(t,e,n){d(e.action)&&typeof e.action.type=="string"&&(t.action={action:e.action,path:n},t.classes.push("act"))}function $(t,e,n,i,r={}){let{profile:s}=i,o=ne(e),a=n.layout==="vertical";if(!o){let b=e.margin===void 0?void 0:Q(e.margin,s),g=e.type==="filler"||e.type==="spacer"||n.previous==="spacer",h=n.index===0||g&&n.spacingKeyword===!0?void 0:n.spacing,R=b??(e.margin===void 0?h:void 0);R!==void 0&&t.style.set(a?"margin-block-start":"margin-inline-start",R)}n.block?t.style.set("flex","1 0 auto"):r.flex==="none"?t.style.set("flex","none"):H(e.flex)&&(e.flex===0?t.style.set("flex","none"):t.style.set("flex",a?`${e.flex} 0 auto`:`${e.flex} 0 0px`)),o&&t.classes.push("abs");let l=[["offsetTop","top"],["offsetBottom","bottom"],["offsetStart","inset-inline-start"],["offsetEnd","inset-inline-end"]];for(let[b,g]of l){let c=Q(e[b],s,!0);c!==void 0&&t.style.set(g,c)}e.gravity==="center"&&t.style.set("justify-content","center"),e.gravity==="bottom"&&t.style.set("justify-content","flex-end")}function me(t,e,n){let i=he(e.size,n);i!==void 0&&t.style.set("font-size",i),e.weight==="bold"&&t.style.set("font-weight","700"),e.weight==="regular"&&t.style.set("font-weight","400"),e.style==="italic"&&t.style.set("font-style","italic"),e.style==="normal"&&t.style.set("font-style","normal"),e.decoration==="underline"&&t.style.set("text-decoration","underline"),e.decoration==="line-through"&&t.style.set("text-decoration","line-through"),e.decoration==="none"&&t.style.set("text-decoration","none");let r=x(e.color);r&&t.style.set("color",r)}var Ge=new Set(["flex-start","center","flex-end","space-between","space-around","space-evenly"]),We=new Set(["flex-start","center","flex-end"]);function He(t,e,n,i){let{profile:r}=i,s=t.layout==="horizontal"||t.layout==="baseline"?t.layout:"vertical",o=f("div",["c","box",s==="vertical"?"v":"h"]);s==="baseline"&&o.classes.push("bl");let a=k(t.width,{percent:!0}),l=k(t.height,{percent:!0}),b=!e.block&&(e.layout==="vertical"?l!==void 0:a!==void 0);$(o,t,e,i,b?{flex:"none"}:{}),I(o,t,n);let g=ne(t);s!=="vertical"&&e.layout==="vertical"&&!g&&!i.inAbsolute&&!a&&o.classes.push("fill");let c=e.padding?e.padding.map(v):[void 0,void 0,void 0,void 0],h=Q(t.paddingAll,r,!0);h!==void 0&&c.fill(h);let R=["paddingTop","paddingEnd","paddingBottom","paddingStart"],z=["padding-block-start","padding-inline-end","padding-block-end","padding-inline-start"];R.forEach((M,E)=>{let q=Q(t[M],r,!0);q!==void 0&&(c[E]=q)}),c.forEach((M,E)=>{M!==void 0&&o.style.set(z[E],M)});let A=x(t.backgroundColor);A&&o.style.set("background-color",A);let J=Ke(t.background);J&&o.style.set("background-image",J);let L=x(t.borderColor);L&&o.style.set("border-color",L);let O=P(r.borderWidth,t.borderWidth),U=O!==void 0?v(O):te(t.borderWidth);U!==void 0&&o.style.set("border-width",U);let D=P(r.cornerRadius,t.cornerRadius),ce=D!==void 0?v(D):te(t.cornerRadius);ce!==void 0&&o.style.set("border-radius",ce),a&&o.style.set("width",C(a)),l&&o.style.set("height",C(l));let de=k(t.maxWidth,{percent:!0});de&&o.style.set("max-width",C(de));let ue=k(t.maxHeight,{percent:!0});ue&&o.style.set("max-height",C(ue)),typeof t.justifyContent=="string"&&Ge.has(t.justifyContent)&&o.style.set("justify-content",t.justifyContent),typeof t.alignItems=="string"&&We.has(t.alignItems)&&o.style.set("align-items",t.alignItems);let _=P(r.spacing,t.spacing),je=_!==void 0?_>0?v(_):void 0:te(t.spacing),Be=g&&!i.inAbsolute?{...i,inAbsolute:!0}:i,ee=Array.isArray(t.contents)?t.contents:[];return ee.forEach((M,E)=>{let q=E>0&&d(ee[E-1])?ee[E-1].type:void 0,fe=ie(M,{layout:s,block:!1,spacing:je,spacingKeyword:_!==void 0,index:E,previous:q},`${n}/contents/${E}`,Be);fe&&o.children.push(fe)}),o}function te(t){let e=k(t);return e&&e.n>=0?C(e):void 0}function Ke(t){if(!d(t)||t.type!=="linearGradient")return;let e=Z(t.angle),n=x(t.startColor),i=x(t.endColor);if(e===void 0||!n||!i)return;let r=[`${n} 0%`];if(t.centerColor!==void 0){let s=x(t.centerColor),o=k(t.centerPosition??"50%",{percent:!0});if(!s||!o||o.unit!=="%")return;r.push(`${s} ${C(o)}`)}return r.push(`${i} 100%`),`linear-gradient(${e}deg, ${r.join(", ")})`}function Ue(t,e){if(!d(t)||t.type!=="span")return;let n=f("span",["span"],[typeof t.text=="string"?t.text:""]);return me(n,t,e),n}function De(t,e,n,i){let{profile:r}=i,s=t.wrap===!0,o=f("div",["c","text"]);s&&o.classes.push("wrap"),$(o,t,e,i),me(o,t,r),I(o,t,n),t.align==="center"&&o.style.set("text-align","center"),t.align==="end"&&o.style.set("text-align","end");let a=c=>{if(!s)return c;if(r.maxLines&&H(t.maxLines)&&t.maxLines>0&&(c.classes.push("clamp"),c.style.set("-webkit-line-clamp",String(t.maxLines))),r.lineSpacing){let h=k(t.lineSpacing);h&&h.n>0&&(c.style.set("--ls",C(h)),c.style.set("margin-block",`${h.n/-2}px`))}return c},l=Array.isArray(t.contents)?t.contents.map(c=>Ue(c,r)).filter(c=>c!==void 0):[];if(l.length>0)return o.children.push(a(f("p",[],l))),o;let b=(typeof t.text=="string"?t.text:"").split(`
2
+ `);if(!s){for(let c of b)o.children.push(f("p",[],c===""?[]:[c]));return o}let g=[];return b.forEach((c,h)=>{h>0&&g.push(f("br",[])),c!==""?g.push(c):h===b.length-1&&h>0&&g.push(Je)}),o.children.push(a(f("p",[],g))),o}function _e(t,e,n,i){let{profile:r}=i,s=f("div",["c","image"]);$(s,t,e,i),I(s,t,n),t.align==="start"&&s.style.set("align-items","flex-start"),t.align==="end"&&s.style.set("align-items","flex-end");let o=f("div",["frame"]),a=t.size??"md",l=a==="full",b=P(r.imageSize,a),g=k(a,{percent:!0});l?o.style.set("width","100%"):b!==void 0?o.style.set("width",v(b)):g&&g.n>=0?o.style.set("width",C(g)):o.style.set("width",v(r.imageSize.md)),l&&(ne(t)||e.layout!=="vertical"&&t.flex===0)&&s.style.set("width","100%");let[c,h]=G(t.aspectRatio)??[1,1];o.style.set("aspect-ratio",`${c} / ${h}`);let R=x(t.backgroundColor);R&&o.style.set("background-color",R);let z=W(t.url);if(z){let A=f("img",[t.aspectMode==="cover"?"cover":"fit"]);A.attrs={src:z,alt:"",loading:"lazy",decoding:"async",referrerpolicy:"no-referrer",draggable:"false"},o.children.push(A)}return s.children.push(o),s}function qe(t,e,n,i){let r=f("div",["c","button"]);$(r,t,e,i),I(r,t,n);let s=t.style==="primary"||t.style==="secondary"?t.style:"link",o=f("div",["btn",s]);t.height==="sm"&&o.classes.push("sm");let a=x(t.color);a&&o.style.set(s==="link"?"color":"background-color",a);let l=d(t.action)&&typeof t.action.label=="string"?t.action.label:"";return o.children.push(f("div",["label"],l===""?[]:[l])),r.children.push(o),r}function Ye(t,e,n){let i=f("div",["c","icon"]);$(i,t,e,n,{flex:"none"});let r=he(t.size,n.profile);r!==void 0&&i.style.set("font-size",r);let[s,o]=G(t.aspectRatio)??[1,1],a=W(t.url),l=f(a?"img":"span",["ico"]);return a&&(l.attrs={src:a,alt:"",decoding:"async",referrerpolicy:"no-referrer",draggable:"false"}),l.style.set("width",`${s/o}em`),i.children.push(f("div",[],[l])),i}function Xe(t,e,n){let i=f("div",["c","sep"]);$(i,{type:"separator",margin:t.margin},e,n,{flex:"none"});let r=x(t.color);return r&&i.style.set("color",r),i}function Ze(t,e,n){let i=f("div",["c","filler"]);return $(i,{type:"filler",flex:t.flex},e,n),i}function Qe(t,e,n){let i=f("div",["c","spacer"]);$(i,{type:"spacer"},e,n,{flex:"none"});let r=v(P(n.profile.spacing,t.size)??n.profile.spacing.md),s=e.layout==="vertical";return i.style.set("width",s?"1px":r),i.style.set("height",s?r:"1px"),i}function ie(t,e,n,i){if(!d(t))return;let r;switch(t.type){case"box":r=He(t,e,n,i);break;case"text":r=De(t,e,n,i);break;case"image":r=_e(t,e,n,i);break;case"button":r=qe(t,e,n,i);break;case"icon":r=Ye(t,e,i);break;case"separator":r=Xe(t,e,i);break;case"filler":r=Ze(t,e,i);break;case"spacer":r=Qe(t,e,i);break;case"video":if(r=ie(t.altContent,e,n,i),!r)return;I(r,t,n);break;default:return}return i.annotate&&(r.attrs["data-path"]=n),r}var et=["header","hero","body","footer"];function xe(t,e,n){let{profile:i}=n,r=P(i.bubble,t.size)??i.bubble.mega,s=t.direction==="rtl",o=d(t.styles)?t.styles:{},a=f("div",["card"]);a.attrs.dir=s?"rtl":"ltr",a.style.set("border-radius",v(r.cornerRadius)),r.inset>0&&a.style.set("margin-inline",v(r.inset)),I(a,t,e);let l=d(t.footer);for(let g of et){let c=t[g];if(!d(c))continue;let h=d(o[g])?o[g]:{};if(h.separator===!0&&a.children.length>0){let L=f("div",["sep"]),O=x(h.separatorColor);O&&L.style.set("color",O),a.children.push(L)}let R=f("div",["block",g]),z=x(h.backgroundColor);z&&R.style.set("background-color",z);let A;if(g==="header"&&(A=r.headerPadding),g==="footer"&&(A=r.footerPadding),g==="body"){let[L,O,U,D]=r.bodyPadding;A=[L,O,l?r.bodyPaddingBottomWithFooter:U,D]}let J=ie(c,{layout:"vertical",block:!0,index:0,padding:A},`${e}/${g}`,n);J&&R.children.push(J),a.children.push(R)}let b=f("div",["bubble"],[a]);return b.style.set("max-width",v(r.maxWidth)),n.annotate&&(b.attrs["data-path"]=e),b}function tt(t,e){let{carousel:n}=e.profile,i=f("div",["track"]);(Array.isArray(t.contents)?t.contents:[]).forEach((o,a)=>{if(!d(o)||o.type!=="bubble")return;let l=xe(o,`/contents/${a}`,e);l.style.set("width",`${n.itemWidthPercent}%`),l.style.set("margin-inline-start",v(i.children.length===0?n.leadingGap:n.gap)),i.children.push(l)});let s=f("div",["tail"]);return s.style.set("width",v(n.trailingGap)),i.children.push(s),f("div",["carousel"],[i])}function re(t){if(d(t))return t.type==="flex"?d(t.contents)?t.contents:void 0:t}function we(t,e){let n={profile:e.profile,annotate:e.annotate===!0,inAbsolute:!1},i=f("div",["root"]),r=re(t);return r?.type==="bubble"?i.children.push(xe(r,"",n)):r?.type==="carousel"&&i.children.push(tt(r,n)),i}var ke=new WeakMap;function ve(t,e){for(let n=t;n&&n!==e;n=n.parentElement){let i=ke.get(n);if(i)return i}}function Se(t,e){let n=e.createElement(t.tag);t.classes.length>0&&(n.className=t.classes.join(" "));for(let[i,r]of t.style)n.style.setProperty(i,r);for(let[i,r]of Object.entries(t.attrs))n.setAttribute(i,r);for(let i of t.children)n.appendChild(typeof i=="string"?e.createTextNode(i):Se(i,e));return t.action&&ke.set(n,t.action),n}function Re(t,e={},n=document){let i=X(e.profile);return Se(we(t,{profile:i,annotate:e.annotate}),n)}var nt='-apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Roboto, "Segoe UI", "Noto Sans", sans-serif',Ce=new WeakMap;function Ae(t){let e=Ce.get(t);return e===void 0&&(e=it(t),Ce.set(t,e)),e}function it(t){let{button:e}=t,n=t.lineSpacing?`calc(${t.lineHeight} + var(--ls, 0px))`:t.lineHeight;return`
3
+ :host { display: block; }
4
+ :host([hidden]) { display: none; }
5
+
6
+ /* Nothing inherited from the page gets past this element; the only way in is
7
+ the custom properties named here. */
8
+ .root {
9
+ all: initial;
10
+ /* \`all\` leaves these two alone. */
11
+ direction: ltr;
12
+ unicode-bidi: isolate;
13
+ /* Its own formatting and stacking context: a float on the page cannot push
14
+ into the bubble, and nothing inside can stack against the page. */
15
+ display: flow-root;
16
+ isolation: isolate;
17
+ font-family: var(--flex-message-font-family, ${nt});
18
+ font-size: 16px;
19
+ line-height: 1.4;
20
+ color: ${t.textColor};
21
+ -webkit-text-size-adjust: none;
22
+ text-size-adjust: none;
23
+ -webkit-user-select: none;
24
+ user-select: none;
25
+ cursor: default;
26
+ }
27
+ .root *, .root *::before, .root *::after {
28
+ box-sizing: border-box;
29
+ margin: 0;
30
+ padding: 0;
31
+ border: 0 solid transparent;
32
+ }
33
+
34
+ .bubble { width: 100%; min-width: 0; }
35
+ .card {
36
+ display: flex;
37
+ flex-direction: column;
38
+ overflow: hidden;
39
+ background-color: var(--flex-message-bubble-background, ${t.bubbleBackground});
40
+ }
41
+ .block { display: flex; flex-direction: column; }
42
+
43
+ /* Every component is a column flex container that shares its parent's space. */
44
+ .c {
45
+ display: flex;
46
+ flex-direction: column;
47
+ flex: 1 0 0px;
48
+ min-width: 0;
49
+ max-width: 100%;
50
+ position: relative;
51
+ }
52
+ .abs { position: absolute; width: auto; }
53
+ .act { cursor: pointer; }
54
+
55
+ .box { overflow: hidden; }
56
+ .box.h { flex-direction: row; }
57
+ .box.fill { width: 100%; }
58
+ .box.bl { align-items: baseline; }
59
+ .box.v > .c { flex: none; }
60
+ .box.h > .c { overflow: hidden; }
61
+ .box.v > .filler { flex: 1 0 0px; }
62
+ .filler, .spacer { position: static; }
63
+
64
+ /* A hairline that takes no space of its own. */
65
+ .sep { flex: none; position: relative; width: 100%; color: ${t.separatorColor}; }
66
+ .sep::before {
67
+ content: "";
68
+ display: block;
69
+ position: absolute;
70
+ z-index: 1;
71
+ inset-inline-start: 0;
72
+ width: 100%;
73
+ height: 1px;
74
+ background-color: currentColor;
75
+ transform: scaleY(0.5);
76
+ transform-origin: 0 0;
77
+ }
78
+ .sep:last-child::before { margin-top: -1px; transform-origin: 0 100%; }
79
+ .box.h > .sep { width: auto; align-self: stretch; overflow: visible; }
80
+ .box.h > .sep::before { width: 1px; height: 100%; transform: scaleX(0.5); transform-origin: 0 0; }
81
+ .box.h > .sep:last-child::before { margin-top: 0; margin-inline-start: -1px; transform-origin: 100% 0; }
82
+ [dir="rtl"] .box.h > .sep::before { transform-origin: 100% 0; }
83
+ [dir="rtl"] .box.h > .sep:last-child::before { transform-origin: 0 0; }
84
+
85
+ .text p, .span { line-height: ${n}; }
86
+ .text p { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
87
+ .text p:empty::before { content: "\\200b"; }
88
+ .text.wrap p { white-space: normal; overflow-wrap: break-word; word-wrap: break-word; text-overflow: clip; }
89
+ .text p.clamp { display: -webkit-box; -webkit-box-orient: vertical; }
90
+ .span { font-style: inherit; font-weight: inherit; text-decoration: inherit; }
91
+
92
+ .btn {
93
+ display: flex;
94
+ align-items: center;
95
+ justify-content: center;
96
+ width: 100%;
97
+ height: ${e.height.md}px;
98
+ padding: 0 ${e.paddingInline}px;
99
+ border-radius: ${e.cornerRadius}px;
100
+ font-size: ${e.fontSize}px;
101
+ }
102
+ .btn.sm { height: ${e.height.sm}px; }
103
+ .btn.primary { background-color: ${e.primary.background}; color: ${e.primary.color}; }
104
+ .btn.secondary { background-color: ${e.secondary.background}; color: ${e.secondary.color}; }
105
+ .btn.link { color: ${e.link.color}; }
106
+ .label { max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
107
+
108
+ .image { align-items: center; overflow: hidden; }
109
+ .frame { flex: none; position: relative; max-width: 100%; overflow: hidden; }
110
+ .frame > img { display: block; position: absolute; inset: 0; width: 100%; height: 100%; }
111
+ .frame > .fit { object-fit: contain; }
112
+ .frame > .cover { object-fit: cover; }
113
+
114
+ .ico { display: inline-block; height: 1em; vertical-align: baseline; object-fit: contain; }
115
+
116
+ .carousel { overflow-x: auto; scrollbar-width: none; }
117
+ .carousel::-webkit-scrollbar { display: none; }
118
+ .track { display: flex; width: 100%; }
119
+ .track > .bubble { display: flex; flex: none; }
120
+ .track > .tail { flex: none; height: 1px; }
121
+ .track .card { flex: 1 0 0px; min-width: 0; }
122
+ .track .block { flex: none; }
123
+ .track .block.body { flex: 1 0 auto; }
124
+
125
+ .error {
126
+ padding: 8px 12px;
127
+ border-radius: 8px;
128
+ background-color: #fdecea;
129
+ color: #8a1c13;
130
+ font-size: 13px;
131
+ }
132
+ `.trim()}var m=["none","xs","sm","md","lg","xl","xxl"],se=["xxs","xs","sm","md","lg","xl","xxl","3xl","4xl","5xl"],y=(...t)=>({kind:"enum",values:t}),p=(t,e=!1)=>({kind:"length",keywords:t,percent:e}),B={kind:"color"},V={kind:"integer"},F={kind:"boolean"},S={kind:"string"},N={kind:"structure"},K={position:y("relative","absolute"),offsetTop:p(m,!0),offsetBottom:p(m,!0),offsetStart:p(m,!0),offsetEnd:p(m,!0)},Ee={size:p(se),color:B,weight:y("regular","bold"),style:y("normal","italic"),decoration:y("none","underline","line-through")},Pe={box:{type:S,layout:y("horizontal","vertical","baseline"),contents:N,backgroundColor:B,borderColor:B,borderWidth:p(["none","light","normal","medium","semi-bold","bold"]),cornerRadius:p(m),width:p(void 0,!0),maxWidth:p(void 0,!0),height:p(void 0,!0),maxHeight:p(void 0,!0),flex:V,spacing:p(m),margin:p(m),paddingAll:p(m,!0),paddingTop:p(m,!0),paddingBottom:p(m,!0),paddingStart:p(m,!0),paddingEnd:p(m,!0),action:N,justifyContent:y("flex-start","center","flex-end","space-between","space-around","space-evenly"),alignItems:y("flex-start","center","flex-end"),background:N,...K},button:{type:S,action:N,flex:V,margin:p(m),height:y("sm","md"),style:y("primary","secondary","link"),color:B,gravity:y("top","bottom","center"),adjustMode:y("shrink-to-fit"),scaling:F,...K},image:{type:S,url:{kind:"url"},flex:V,margin:p(m),align:y("start","end","center"),gravity:y("top","bottom","center"),size:p([...se,"full"],!0),aspectRatio:{kind:"ratio"},aspectMode:y("fit","cover"),backgroundColor:B,action:N,animated:F,...K},video:{type:S,url:{kind:"url"},previewUrl:{kind:"url"},altContent:N,aspectRatio:{kind:"ratio"},action:N},icon:{type:S,url:{kind:"url"},margin:p(m),size:p(se),aspectRatio:{kind:"ratio"},scaling:F,...K},text:{type:S,text:S,contents:N,adjustMode:y("shrink-to-fit"),flex:V,margin:p(m),align:y("start","end","center"),gravity:y("top","bottom","center"),wrap:F,lineSpacing:p(),action:N,maxLines:V,scaling:F,...Ee,...K},span:{type:S,text:S,...Ee},separator:{type:S,margin:p(m),color:B},filler:{type:S,flex:V},spacer:{type:S,size:y("xs","sm","md","lg","xl","xxl")}};var Ne=["icon","text","filler","spacer"],$e=12,rt=["type","size","direction","header","hero","body","footer","styles","action"];var ot=["nano","micro","deca","hecto","kilo","mega","giga"],oe=["header","hero","body","footer"],st={text:["adjustMode","scaling"],button:["adjustMode","scaling"],icon:["scaling"],image:["animated"]},ze=20;function u(t,e){return`${t}/${String(e).replace(/~/g,"~0").replace(/\//g,"~1")}`}function j(t){let e=typeof t=="string"?JSON.stringify(t):String(JSON.stringify(t));return e.length>60?`${e.slice(0,57)}...`:e}var ae=class{issues=[];add(e,n,i,r){this.issues.push({path:i,severity:e,code:n,message:r})}value(e,n,i,r){let s=o=>this.add("error","invalid-value",i,`${r} must be ${o}; got ${j(n)}.`);switch(e.kind){case"enum":(typeof n!="string"||!e.values.includes(n))&&s(`one of ${e.values.join(", ")}`);return;case"length":{if(typeof n=="string"&&e.keywords?.includes(n))return;let o=k(n,{percent:e.percent}),a=r.startsWith("offset");if(!o||o.n<0&&!a){let l=e.percent?"a px or % value":"a px value";s(e.keywords?`${l} or one of ${e.keywords.join(", ")}`:l)}return}case"color":x(n)||s("a #RRGGBB or #RRGGBBAA colour");return;case"url":W(n)||s("an https URL of at most 2000 characters");return;case"ratio":{let o=G(n);o?o[1]>o[0]*3&&s("a ratio whose height is at most three times its width"):s('a "{width}:{height}" ratio');return}case"integer":H(n)||s("a non-negative integer");return;case"boolean":typeof n!="boolean"&&s("true or false");return;case"string":typeof n!="string"&&s("a string");return;case"structure":return}}action(e,n){(!d(e)||typeof e.type!="string")&&this.add("error","invalid-value",n,"action must be an action object with a type.")}gradient(e,n){if(!d(e)||e.type!=="linearGradient"){this.add("error","invalid-value",n,"background must be an object of type linearGradient.");return}let i=Z(e.angle);(i===void 0||i<0||i>=360)&&this.add("error","invalid-value",u(n,"angle"),'angle must be from "0deg" up to, but not including, "360deg".');for(let r of["startColor","endColor"])x(e[r])||this.add("error","invalid-value",u(n,r),`${r} must be a #RRGGBB or #RRGGBBAA colour.`);e.centerColor!==void 0&&!x(e.centerColor)&&this.add("error","invalid-value",u(n,"centerColor"),"centerColor must be a #RRGGBB or #RRGGBBAA colour."),e.centerPosition!==void 0&&k(e.centerPosition,{percent:!0})?.unit!=="%"&&this.add("error","invalid-value",u(n,"centerPosition"),"centerPosition must be a percentage.")}component(e,n,i){if(!d(e)){this.add("error","invalid-type",n,"A component must be an object.");return}let r=e.type,s=typeof r=="string"&&Object.hasOwn(Pe,r)?Pe[r]:void 0;if(!s||typeof r!="string"){this.add("error","unknown-component",n,`Unknown component type ${j(r)}.`);return}r==="span"&&!i.inText&&this.add("error","misplaced-component",n,"A span can only be used in the contents of a text."),r!=="span"&&i.inText&&this.add("error","misplaced-component",n,`The contents of a text can only hold spans; got ${r}.`),r==="icon"&&i.parentLayout!=="baseline"&&this.add("error","misplaced-component",n,"An icon can only be used in a baseline box."),r==="video"&&!i.hero&&this.add("error","misplaced-component",n,"A video can only be the hero of a bubble."),i.parentLayout==="baseline"&&!Ne.includes(r)&&this.add("error","misplaced-component",n,`A baseline box can only hold ${Ne.slice(0,3).join(", ")}; got ${r}.`),(r==="filler"||r==="spacer")&&this.add("warning","deprecated",n,`${r} is deprecated; use padding, margin or justifyContent instead.`);for(let[a,l]of Object.entries(e)){let b=Object.hasOwn(s,a)?s[a]:void 0;if(!b){this.add("error","unknown-property",u(n,a),`${r} has no property ${j(a)}.`);continue}l!==void 0&&(this.value(b,l,u(n,a),a),a==="action"&&this.action(l,u(n,a)),a==="background"&&this.gradient(l,u(n,a)))}for(let a of st[r]??[])e[a]!==void 0&&e[a]!==!1&&this.add("warning","not-rendered",u(n,a),`${a} is accepted by LINE but not drawn by this preview.`);let o=a=>{e[a]===void 0&&this.add("error","missing-property",n,`${r} requires ${a}.`)};switch(r){case"box":{o("layout");let a=i.depth+1;if(a===ze+1&&this.add("error","too-deep",n,`Boxes can be nested at most ${ze} levels deep.`),!Array.isArray(e.contents)){this.add("error",e.contents===void 0?"missing-property":"invalid-type",n,"box requires contents, an array of components.");return}e.contents.forEach((l,b)=>{this.component(l,u(u(n,"contents"),b),{parentLayout:String(e.layout),depth:a})});return}case"text":{let a=Array.isArray(e.contents)&&e.contents.length>0;e.contents!==void 0&&!Array.isArray(e.contents)&&this.add("error","invalid-type",u(n,"contents"),"contents must be an array of spans."),Array.isArray(e.contents)&&e.contents.forEach((l,b)=>this.component(l,u(u(n,"contents"),b),{inText:!0,depth:i.depth})),!a&&e.text===void 0&&this.add("error","missing-property",n,"text requires text or contents."),!a&&e.text===""&&this.add("error","invalid-value",u(n,"text"),"text must not be empty.");return}case"button":o("action"),d(e.action)&&(typeof e.action.label!="string"||e.action.label==="")&&this.add("error","missing-property",u(n,"action"),"The action of a button requires a label.");return;case"span":e.text===void 0?this.add("error","missing-property",n,"span requires text."):e.text===""&&this.add("error","invalid-value",u(n,"text"),"text must not be empty.");return;case"image":case"icon":o("url");return;case"video":o("url"),o("previewUrl"),!d(e.altContent)||e.altContent.type!=="box"&&e.altContent.type!=="image"?this.add("error",e.altContent===void 0?"missing-property":"invalid-value",n,"video requires altContent, a box or an image."):this.component(e.altContent,u(n,"altContent"),{depth:i.depth}),this.add("warning","not-rendered",n,"Video is not played in this preview; its altContent is shown instead.");return}}bubble(e,n,i=!1){if(!d(e)||e.type!=="bubble"){this.add("error","invalid-type",n,"Expected an object of type bubble.");return}for(let r of Object.keys(e))rt.includes(r)||this.add("error","unknown-property",u(n,r),`bubble has no property ${j(r)}.`);e.size!==void 0&&this.value(y(...ot),e.size,u(n,"size"),"size"),e.direction!==void 0&&this.value(y("ltr","rtl"),e.direction,u(n,"direction"),"direction"),e.action!==void 0&&this.action(e.action,u(n,"action")),oe.every(r=>e[r]===void 0)&&this.add("error","missing-property",n,"A bubble requires at least one of header, hero, body and footer.");for(let r of oe){let s=e[r];if(s===void 0)continue;let o=u(n,r);if(r!=="hero"&&(!d(s)||s.type!=="box")){this.add("error","invalid-type",o,`${r} must be a box.`);continue}if(r==="hero"&&(!d(s)||!["box","image","video"].includes(String(s.type)))){this.add("error","invalid-type",o,"hero must be a box, an image or a video.");continue}r==="hero"&&d(s)&&s.type==="video"&&(i&&this.add("error","misplaced-component",o,"A video cannot be used in a carousel."),["kilo","mega","giga"].includes(String(e.size??"mega"))||this.add("error","misplaced-component",o,"A video needs a bubble of size kilo, mega or giga.")),this.component(s,o,{hero:r==="hero",depth:0})}if(e.styles!==void 0){let r=u(n,"styles");if(!d(e.styles)){this.add("error","invalid-type",r,"styles must be an object.");return}for(let[s,o]of Object.entries(e.styles)){let a=u(r,s);if(!oe.includes(s)){this.add("error","unknown-property",a,`styles has no block ${j(s)}.`);continue}if(!d(o)){this.add("error","invalid-type",a,"A block style must be an object.");continue}this.blockStyle(o,a)}}}blockStyle(e,n){for(let[i,r]of Object.entries(e)){let s=u(n,i);i==="backgroundColor"||i==="separatorColor"?this.value(B,r,s,i):i==="separator"?this.value(F,r,s,i):this.add("error","unknown-property",s,`A block style has no property ${j(i)}.`)}}container(e,n){if(!d(e)){this.add("error","invalid-type",n,"Expected a bubble or a carousel.");return}if(e.type==="bubble")this.bubble(e,n);else if(e.type==="carousel"){if(!Array.isArray(e.contents)||e.contents.length===0){this.add("error","missing-property",n,"carousel requires contents, a non-empty array of bubbles.");return}let i=u(n,"contents");e.contents.length>$e&&this.add("error","invalid-value",i,`A carousel can hold at most ${$e} bubbles; got ${e.contents.length}.`),new Set(e.contents.map(s=>d(s)?s.size??"mega":void 0)).size>1&&this.add("error","invalid-value",i,"The bubbles of a carousel must all have the same size."),e.contents.forEach((s,o)=>this.bubble(s,u(i,o),!0))}else this.add("error","invalid-type",n,`Expected type bubble or carousel; got ${j(e.type)}.`)}};function Le(t){let e=new ae,n=t;if(typeof n=="string")try{n=JSON.parse(n)}catch(i){return e.add("error","invalid-json","",`Not valid JSON: ${i instanceof Error?i.message:String(i)}`),e.issues}return d(n)&&n.type==="flex"?((typeof n.altText!="string"||n.altText==="")&&e.add("error","missing-property","","A flex message requires altText, a non-empty string."),e.container(n.contents,"/contents")):e.container(n,""),e.issues}var at=globalThis.HTMLElement??class{},Oe=new WeakMap;function lt(t,e){let n=Ae(e);if("adoptedStyleSheets"in t&&typeof CSSStyleSheet=="function"&&"replaceSync"in CSSStyleSheet.prototype){let r=Oe.get(e);r||(r=new CSSStyleSheet,r.replaceSync(n),Oe.set(e,r)),t.adoptedStyleSheets=[r];return}let i=document.createElement("style");i.textContent=n,t.append(i)}var le=class extends at{static observedAttributes=["profile","annotate"];#i=void 0;#r=!1;#o=[];#e;#s;#n=!1;#a;get message(){return this.#i}set message(e){this.#i=e??void 0,this.#r=e!=null,this.#t()}get profile(){return this.#a}set profile(e){this.#a=e??void 0,this.#t()}get issues(){return this.#o}connectedCallback(){for(let e of["message","profile"])if(Object.hasOwn(this,e)){let n=this[e];delete this[e],this[e]=n}this.#e||(this.#e=this.shadowRoot??this.attachShadow({mode:"open"}),this.#e.addEventListener("click",this.#c),this.#e.addEventListener("error",this.#l,!0)),this.#s??=new MutationObserver(()=>{this.#r||this.#t()}),this.#s.observe(this,{childList:!0,characterData:!0,subtree:!0}),this.#t()}disconnectedCallback(){this.#s?.disconnect()}attributeChangedCallback(e,n,i){n!==i&&this.#t()}render(){this.#n=!1;let e=this.#e;if(!e)return;let n=this.#i;if(!this.#r&&(n=this.querySelector(':scope > script[type="application/json"]')?.textContent?.trim()||void 0,n===void 0&&e.childElementCount>0&&!e.querySelector(".root[data-rendered]")))return;let i=n,r=[];if(typeof n=="string")try{i=JSON.parse(n)}catch{i=void 0}n!==void 0&&(r=Le(n));let s=this.#a??X(this.getAttribute("profile")),o=Re(i,{profile:s,annotate:this.hasAttribute("annotate")},this.ownerDocument);if(o.setAttribute("data-rendered",""),n!==void 0&&!re(i)?.type){let a=this.ownerDocument.createElement("div");a.className="error",a.setAttribute("part","error"),a.textContent=r[0]?.message??"Not a Flex message.",o.append(a)}e.replaceChildren(),lt(e,s),e.append(o),this.#o=Object.freeze(r),this.dispatchEvent(new CustomEvent("flex-message-render",{detail:{issues:this.#o}}))}#t(){this.#n||!this.#e||(this.#n=!0,queueMicrotask(()=>{this.#n&&this.render()}))}#l=e=>{e.target instanceof HTMLImageElement&&(e.target.style.visibility="hidden")};#c=e=>{let n=this.#e;if(!n||!(e.target instanceof Element))return;let i=ve(e.target,n);i&&this.dispatchEvent(new CustomEvent("flex-message-action",{detail:i,bubbles:!0,composed:!0}))}};function Te(t="flex-message"){typeof customElements>"u"||customElements.get(t)||customElements.define(t,le)}Te();export{le as FlexMessageElement,Te as defineFlexMessageElement};
package/dist/html.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { type Profile } from './profile.js';
2
+ export interface RenderOptions {
3
+ /** `"ios"` (default), `"simulator"`, or a custom profile. */
4
+ profile?: Profile | string;
5
+ /** Adds `data-path` (a JSON Pointer into the container) to every component. */
6
+ annotate?: boolean;
7
+ }
8
+ export interface RenderToStringOptions extends RenderOptions {
9
+ /** Custom element name to wrap the output in. Default `flex-message`. */
10
+ tagName?: string;
11
+ /** CSP nonce for the `<style>` element inside the shadow root. */
12
+ nonce?: string;
13
+ }
14
+ export declare function escapeText(value: string): string;
15
+ export declare function escapeAttribute(value: string): string;
16
+ /**
17
+ * Renders a Flex message (or a bare bubble / carousel) to static HTML: a
18
+ * custom element holding a declarative shadow root. It needs no JavaScript to
19
+ * display, and the page's CSS cannot reach inside it.
20
+ */
21
+ export declare function renderToString(input: unknown, options?: RenderToStringOptions): string;
22
+ export interface RenderDocumentOptions extends RenderToStringOptions {
23
+ /** Page background. Default is a LINE-like chat blue-grey. */
24
+ background?: string;
25
+ /** Space around the message, in px. Default 0. */
26
+ padding?: number;
27
+ lang?: string;
28
+ }
29
+ /** A complete HTML page showing one message; meant for screenshots and tests. */
30
+ export declare function renderDocument(input: unknown, options?: RenderDocumentOptions): string;
package/dist/html.js ADDED
@@ -0,0 +1,86 @@
1
+ // Element tree → HTML string, wrapped in a declarative shadow root.
2
+ import { resolveProfile } from './profile.js';
3
+ import { stylesheetFor } from './styles.js';
4
+ import { buildTree } from './tree.js';
5
+ const VOID = new Set(['br', 'img']);
6
+ export function escapeText(value) {
7
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
8
+ }
9
+ export function escapeAttribute(value) {
10
+ return escapeText(value).replace(/"/g, '&quot;').replace(/'/g, '&#39;');
11
+ }
12
+ /**
13
+ * Collects per-element declarations into shared classes. The string output has
14
+ * no `style` attributes, so it works under a Content-Security-Policy that
15
+ * allows styles by nonce only.
16
+ */
17
+ class StyleSink {
18
+ classes = new Map();
19
+ classFor(style) {
20
+ if (style.size === 0)
21
+ return undefined;
22
+ let declarations = '';
23
+ for (const [property, value] of style)
24
+ declarations += `${property}:${value}!important;`;
25
+ let name = this.classes.get(declarations);
26
+ if (name === undefined) {
27
+ name = `s${this.classes.size}`;
28
+ this.classes.set(declarations, name);
29
+ }
30
+ return name;
31
+ }
32
+ css() {
33
+ let css = '';
34
+ for (const [declarations, name] of this.classes)
35
+ css += `.${name}{${declarations}}`;
36
+ return css;
37
+ }
38
+ }
39
+ function serialize(node, sink) {
40
+ if (typeof node === 'string')
41
+ return escapeText(node);
42
+ const styleClass = sink.classFor(node.style);
43
+ const classes = styleClass ? [...node.classes, styleClass] : node.classes;
44
+ let html = `<${node.tag}`;
45
+ if (classes.length > 0)
46
+ html += ` class="${escapeAttribute(classes.join(' '))}"`;
47
+ for (const [name, value] of Object.entries(node.attrs))
48
+ html += ` ${name}="${escapeAttribute(value)}"`;
49
+ html += '>';
50
+ if (VOID.has(node.tag))
51
+ return html;
52
+ for (const child of node.children)
53
+ html += serialize(child, sink);
54
+ return `${html}</${node.tag}>`;
55
+ }
56
+ const TAG_NAME = /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/;
57
+ /**
58
+ * Renders a Flex message (or a bare bubble / carousel) to static HTML: a
59
+ * custom element holding a declarative shadow root. It needs no JavaScript to
60
+ * display, and the page's CSS cannot reach inside it.
61
+ */
62
+ export function renderToString(input, options = {}) {
63
+ const profile = resolveProfile(options.profile);
64
+ const tagName = options.tagName !== undefined && TAG_NAME.test(options.tagName) ? options.tagName : 'flex-message';
65
+ const sink = new StyleSink();
66
+ const body = serialize(buildTree(input, { profile, annotate: options.annotate }), sink);
67
+ const nonce = options.nonce === undefined ? '' : ` nonce="${escapeAttribute(options.nonce)}"`;
68
+ // A stylesheet never contains "</style", but this keeps that true by construction.
69
+ const css = `${stylesheetFor(profile)}\n${sink.css()}`.replace(/<\//g, '<\\/');
70
+ return (`<${tagName} profile="${escapeAttribute(profile.name)}">` +
71
+ `<template shadowrootmode="open"><style${nonce}>${css}</style>${body}</template>` +
72
+ `</${tagName}>`);
73
+ }
74
+ const SAFE_BACKGROUND = /^#[0-9a-fA-F]{3,8}$|^transparent$/;
75
+ const SAFE_LANG = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
76
+ /** A complete HTML page showing one message; meant for screenshots and tests. */
77
+ export function renderDocument(input, options = {}) {
78
+ const background = options.background !== undefined && SAFE_BACKGROUND.test(options.background) ? options.background : '#8cabd9';
79
+ const padding = typeof options.padding === 'number' && options.padding >= 0 ? options.padding : 0;
80
+ const lang = options.lang !== undefined && SAFE_LANG.test(options.lang) ? options.lang : 'en';
81
+ const nonce = options.nonce === undefined ? '' : ` nonce="${escapeAttribute(options.nonce)}"`;
82
+ return (`<!doctype html><html lang="${lang}"><head><meta charset="utf-8">` +
83
+ `<meta name="viewport" content="width=device-width, initial-scale=1">` +
84
+ `<style${nonce}>html,body{margin:0}body{background:${background};padding:${padding}px}</style></head>` +
85
+ `<body>${renderToString(input, options)}</body></html>`);
86
+ }
@@ -0,0 +1,10 @@
1
+ export { renderToString, renderDocument } from './html.js';
2
+ export type { RenderOptions, RenderToStringOptions, RenderDocumentOptions } from './html.js';
3
+ export { renderToElement, actionAt } from './dom.js';
4
+ export type { ActionTarget } from './dom.js';
5
+ export { stylesheetFor, DEFAULT_FONT_FAMILY } from './styles.js';
6
+ export { validate } from './validate.js';
7
+ export type { Issue, IssueSeverity } from './validate.js';
8
+ export { iosProfile, simulatorProfile, profiles, defaultProfile, resolveProfile } from './profile.js';
9
+ export type { Profile, ProfileName, BubbleMetrics, Sides } from './profile.js';
10
+ export type * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // Side-effect-free entry: rendering to strings and elements, validation, types.
2
+ // The custom element is in './element' (class) and './define' (registers it).
3
+ export { renderToString, renderDocument } from './html.js';
4
+ export { renderToElement, actionAt } from './dom.js';
5
+ export { stylesheetFor, DEFAULT_FONT_FAMILY } from './styles.js';
6
+ export { validate } from './validate.js';
7
+ export { iosProfile, simulatorProfile, profiles, defaultProfile, resolveProfile } from './profile.js';
@@ -0,0 +1,75 @@
1
+ import type { BorderWidthKeyword, BubbleSize, Keyword, SizeKeyword } from './types.js';
2
+ /** top, end, bottom, start — in px. */
3
+ export type Sides = readonly [top: number, end: number, bottom: number, start: number];
4
+ export interface BubbleMetrics {
5
+ /** The bubble is as wide as its container, up to this many px. */
6
+ maxWidth: number;
7
+ cornerRadius: number;
8
+ /** Space kept on each side of a single (non-carousel) bubble, in px. */
9
+ inset: number;
10
+ headerPadding: Sides;
11
+ bodyPadding: Sides;
12
+ /** Bottom padding of the body when the bubble also has a footer. */
13
+ bodyPaddingBottomWithFooter: number;
14
+ footerPadding: Sides;
15
+ }
16
+ export interface Profile {
17
+ readonly name: string;
18
+ /** Shared by spacing, margin, padding and offset keywords. */
19
+ readonly spacing: Readonly<Record<Keyword, number>>;
20
+ /** Font size of text, span and icon keywords. */
21
+ readonly textSize: Readonly<Record<SizeKeyword, number>>;
22
+ /** Width of image size keywords. `full` is 100% and is not listed. */
23
+ readonly imageSize: Readonly<Record<SizeKeyword, number>>;
24
+ readonly cornerRadius: Readonly<Record<Keyword, number>>;
25
+ readonly borderWidth: Readonly<Record<BorderWidthKeyword, number>>;
26
+ readonly bubble: Readonly<Record<BubbleSize, BubbleMetrics>>;
27
+ readonly button: {
28
+ readonly height: Readonly<Record<'md' | 'sm', number>>;
29
+ readonly paddingInline: number;
30
+ readonly cornerRadius: number;
31
+ readonly fontSize: number;
32
+ readonly primary: {
33
+ readonly background: string;
34
+ readonly color: string;
35
+ };
36
+ readonly secondary: {
37
+ readonly background: string;
38
+ readonly color: string;
39
+ };
40
+ readonly link: {
41
+ readonly color: string;
42
+ };
43
+ };
44
+ readonly carousel: {
45
+ /** Each bubble is this share of the container width, capped by its maxWidth. */
46
+ readonly itemWidthPercent: number;
47
+ readonly leadingGap: number;
48
+ readonly gap: number;
49
+ readonly trailingGap: number;
50
+ };
51
+ readonly textColor: string;
52
+ readonly bubbleBackground: string;
53
+ readonly separatorColor: string;
54
+ /** CSS `line-height` of a line of text, relative to its own font size. */
55
+ readonly lineHeight: string;
56
+ /** Whether `maxLines` clamps wrapped text. */
57
+ readonly maxLines: boolean;
58
+ /** Whether `lineSpacing` adds space between lines. */
59
+ readonly lineSpacing: boolean;
60
+ }
61
+ /**
62
+ * What LINE's Flex Message Simulator draws. It ignores `maxLines`,
63
+ * `lineSpacing`, `adjustMode` and `scaling`, and its lines are taller than a
64
+ * phone's. Kept for regression testing against the Simulator, not as a target.
65
+ */
66
+ export declare const simulatorProfile: Profile;
67
+ /**
68
+ * LINE for iOS. Starts from the Simulator's values and replaces what a phone
69
+ * was measured to do differently.
70
+ */
71
+ export declare const iosProfile: Profile;
72
+ export declare const profiles: Readonly<Record<string, Profile>>;
73
+ export type ProfileName = 'ios' | 'simulator';
74
+ export declare const defaultProfile: Profile;
75
+ export declare function resolveProfile(profile: Profile | string | null | undefined): Profile;
@@ -0,0 +1,86 @@
1
+ // Rendering metrics.
2
+ //
3
+ // LINE publishes the structure of Flex Messages but none of the pixel values
4
+ // behind its keywords, so every number here is a measurement. Where each one
5
+ // comes from, on which device and when, is recorded in docs/measurements.md;
6
+ // update that file whenever a value here changes.
7
+ const spacing = { none: 0, xs: 2, sm: 4, md: 8, lg: 12, xl: 16, xxl: 20 };
8
+ function sides(top, end = top, bottom = top, start = end) {
9
+ return [top, end, bottom, start];
10
+ }
11
+ function bubbleMetrics(maxWidth, cornerRadius, padding, bodyPadding, bodyPaddingBottomWithFooter, inset = 0) {
12
+ return {
13
+ maxWidth,
14
+ cornerRadius,
15
+ inset,
16
+ headerPadding: padding,
17
+ bodyPadding,
18
+ bodyPaddingBottomWithFooter,
19
+ footerPadding: sides(10),
20
+ };
21
+ }
22
+ /**
23
+ * What LINE's Flex Message Simulator draws. It ignores `maxLines`,
24
+ * `lineSpacing`, `adjustMode` and `scaling`, and its lines are taller than a
25
+ * phone's. Kept for regression testing against the Simulator, not as a target.
26
+ */
27
+ export const simulatorProfile = Object.freeze({
28
+ name: 'simulator',
29
+ spacing,
30
+ textSize: { xxs: 11, xs: 13, sm: 14, md: 16, lg: 19, xl: 22, xxl: 29, '3xl': 35, '4xl': 48, '5xl': 74 },
31
+ imageSize: { xxs: 40, xs: 60, sm: 80, md: 100, lg: 120, xl: 140, xxl: 160, '3xl': 180, '4xl': 200, '5xl': 220 },
32
+ cornerRadius: spacing,
33
+ borderWidth: { none: 0, light: 0.5, normal: 1, medium: 2, 'semi-bold': 3, bold: 4 },
34
+ bubble: {
35
+ nano: bubbleMetrics(120, 10, sides(10), sides(10), 10),
36
+ micro: bubbleMetrics(160, 10, sides(10), sides(10), 10),
37
+ deca: bubbleMetrics(220, 10, sides(11, 14, 13), sides(11, 14, 13), 17),
38
+ hecto: bubbleMetrics(241, 10, sides(11, 14, 13), sides(11, 14, 13), 17),
39
+ kilo: bubbleMetrics(260, 10, sides(13), sides(13), 17),
40
+ mega: bubbleMetrics(300, 17, sides(20), sides(19, 20, 20), 10),
41
+ giga: bubbleMetrics(500, 5, sides(20), sides(19, 20, 20), 10, 7),
42
+ },
43
+ button: {
44
+ height: { md: 52, sm: 40 },
45
+ paddingInline: 16,
46
+ cornerRadius: 8,
47
+ fontSize: 16,
48
+ primary: { background: '#17c950', color: '#ffffff' },
49
+ secondary: { background: '#dcdfe5', color: '#111111' },
50
+ link: { color: '#42659a' },
51
+ },
52
+ carousel: { itemWidthPercent: 80, leadingGap: 7, gap: 9, trailingGap: 7 },
53
+ textColor: '#444444',
54
+ bubbleBackground: '#ffffff',
55
+ separatorColor: '#d4d6da',
56
+ lineHeight: '1.4',
57
+ maxLines: false,
58
+ lineSpacing: false,
59
+ });
60
+ /**
61
+ * LINE for iOS. Starts from the Simulator's values and replaces what a phone
62
+ * was measured to do differently.
63
+ */
64
+ export const iosProfile = Object.freeze({
65
+ ...simulatorProfile,
66
+ name: 'ios',
67
+ bubble: {
68
+ ...simulatorProfile.bubble,
69
+ giga: { ...simulatorProfile.bubble.giga, inset: 8 },
70
+ },
71
+ lineHeight: 'max(1.2em, 16px)',
72
+ maxLines: true,
73
+ lineSpacing: true,
74
+ });
75
+ export const profiles = Object.freeze({
76
+ ios: iosProfile,
77
+ simulator: simulatorProfile,
78
+ });
79
+ export const defaultProfile = iosProfile;
80
+ export function resolveProfile(profile) {
81
+ if (profile === null || profile === undefined)
82
+ return defaultProfile;
83
+ if (typeof profile !== 'string')
84
+ return profile;
85
+ return Object.hasOwn(profiles, profile) ? profiles[profile] : defaultProfile;
86
+ }
@@ -0,0 +1,4 @@
1
+ import type { Profile } from './profile.js';
2
+ /** Font stack used unless the host sets `--flex-message-font-family`. */
3
+ export declare const DEFAULT_FONT_FAMILY = "-apple-system, BlinkMacSystemFont, \"Helvetica Neue\", Helvetica, Roboto, \"Segoe UI\", \"Noto Sans\", sans-serif";
4
+ export declare function stylesheetFor(profile: Profile): string;
package/dist/styles.js ADDED
@@ -0,0 +1,152 @@
1
+ // The stylesheet that lives inside the shadow root.
2
+ //
3
+ // It holds layout rules only. Everything that depends on the message (sizes,
4
+ // colours, spacing) is computed in tree.ts and set per element, so the rules
5
+ // here stay few and the metrics stay in one place (profile.ts).
6
+ /** Font stack used unless the host sets `--flex-message-font-family`. */
7
+ export const DEFAULT_FONT_FAMILY = '-apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Roboto, "Segoe UI", "Noto Sans", sans-serif';
8
+ const cache = new WeakMap();
9
+ export function stylesheetFor(profile) {
10
+ let css = cache.get(profile);
11
+ if (css === undefined) {
12
+ css = build(profile);
13
+ cache.set(profile, css);
14
+ }
15
+ return css;
16
+ }
17
+ function build(profile) {
18
+ const { button } = profile;
19
+ // With lineSpacing on, each line box grows by --ls (set per paragraph).
20
+ const lineHeight = profile.lineSpacing ? `calc(${profile.lineHeight} + var(--ls, 0px))` : profile.lineHeight;
21
+ return `
22
+ :host { display: block; }
23
+ :host([hidden]) { display: none; }
24
+
25
+ /* Nothing inherited from the page gets past this element; the only way in is
26
+ the custom properties named here. */
27
+ .root {
28
+ all: initial;
29
+ /* \`all\` leaves these two alone. */
30
+ direction: ltr;
31
+ unicode-bidi: isolate;
32
+ /* Its own formatting and stacking context: a float on the page cannot push
33
+ into the bubble, and nothing inside can stack against the page. */
34
+ display: flow-root;
35
+ isolation: isolate;
36
+ font-family: var(--flex-message-font-family, ${DEFAULT_FONT_FAMILY});
37
+ font-size: 16px;
38
+ line-height: 1.4;
39
+ color: ${profile.textColor};
40
+ -webkit-text-size-adjust: none;
41
+ text-size-adjust: none;
42
+ -webkit-user-select: none;
43
+ user-select: none;
44
+ cursor: default;
45
+ }
46
+ .root *, .root *::before, .root *::after {
47
+ box-sizing: border-box;
48
+ margin: 0;
49
+ padding: 0;
50
+ border: 0 solid transparent;
51
+ }
52
+
53
+ .bubble { width: 100%; min-width: 0; }
54
+ .card {
55
+ display: flex;
56
+ flex-direction: column;
57
+ overflow: hidden;
58
+ background-color: var(--flex-message-bubble-background, ${profile.bubbleBackground});
59
+ }
60
+ .block { display: flex; flex-direction: column; }
61
+
62
+ /* Every component is a column flex container that shares its parent's space. */
63
+ .c {
64
+ display: flex;
65
+ flex-direction: column;
66
+ flex: 1 0 0px;
67
+ min-width: 0;
68
+ max-width: 100%;
69
+ position: relative;
70
+ }
71
+ .abs { position: absolute; width: auto; }
72
+ .act { cursor: pointer; }
73
+
74
+ .box { overflow: hidden; }
75
+ .box.h { flex-direction: row; }
76
+ .box.fill { width: 100%; }
77
+ .box.bl { align-items: baseline; }
78
+ .box.v > .c { flex: none; }
79
+ .box.h > .c { overflow: hidden; }
80
+ .box.v > .filler { flex: 1 0 0px; }
81
+ .filler, .spacer { position: static; }
82
+
83
+ /* A hairline that takes no space of its own. */
84
+ .sep { flex: none; position: relative; width: 100%; color: ${profile.separatorColor}; }
85
+ .sep::before {
86
+ content: "";
87
+ display: block;
88
+ position: absolute;
89
+ z-index: 1;
90
+ inset-inline-start: 0;
91
+ width: 100%;
92
+ height: 1px;
93
+ background-color: currentColor;
94
+ transform: scaleY(0.5);
95
+ transform-origin: 0 0;
96
+ }
97
+ .sep:last-child::before { margin-top: -1px; transform-origin: 0 100%; }
98
+ .box.h > .sep { width: auto; align-self: stretch; overflow: visible; }
99
+ .box.h > .sep::before { width: 1px; height: 100%; transform: scaleX(0.5); transform-origin: 0 0; }
100
+ .box.h > .sep:last-child::before { margin-top: 0; margin-inline-start: -1px; transform-origin: 100% 0; }
101
+ [dir="rtl"] .box.h > .sep::before { transform-origin: 100% 0; }
102
+ [dir="rtl"] .box.h > .sep:last-child::before { transform-origin: 0 0; }
103
+
104
+ .text p, .span { line-height: ${lineHeight}; }
105
+ .text p { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
106
+ .text p:empty::before { content: "\\200b"; }
107
+ .text.wrap p { white-space: normal; overflow-wrap: break-word; word-wrap: break-word; text-overflow: clip; }
108
+ .text p.clamp { display: -webkit-box; -webkit-box-orient: vertical; }
109
+ .span { font-style: inherit; font-weight: inherit; text-decoration: inherit; }
110
+
111
+ .btn {
112
+ display: flex;
113
+ align-items: center;
114
+ justify-content: center;
115
+ width: 100%;
116
+ height: ${button.height.md}px;
117
+ padding: 0 ${button.paddingInline}px;
118
+ border-radius: ${button.cornerRadius}px;
119
+ font-size: ${button.fontSize}px;
120
+ }
121
+ .btn.sm { height: ${button.height.sm}px; }
122
+ .btn.primary { background-color: ${button.primary.background}; color: ${button.primary.color}; }
123
+ .btn.secondary { background-color: ${button.secondary.background}; color: ${button.secondary.color}; }
124
+ .btn.link { color: ${button.link.color}; }
125
+ .label { max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
126
+
127
+ .image { align-items: center; overflow: hidden; }
128
+ .frame { flex: none; position: relative; max-width: 100%; overflow: hidden; }
129
+ .frame > img { display: block; position: absolute; inset: 0; width: 100%; height: 100%; }
130
+ .frame > .fit { object-fit: contain; }
131
+ .frame > .cover { object-fit: cover; }
132
+
133
+ .ico { display: inline-block; height: 1em; vertical-align: baseline; object-fit: contain; }
134
+
135
+ .carousel { overflow-x: auto; scrollbar-width: none; }
136
+ .carousel::-webkit-scrollbar { display: none; }
137
+ .track { display: flex; width: 100%; }
138
+ .track > .bubble { display: flex; flex: none; }
139
+ .track > .tail { flex: none; height: 1px; }
140
+ .track .card { flex: 1 0 0px; min-width: 0; }
141
+ .track .block { flex: none; }
142
+ .track .block.body { flex: 1 0 auto; }
143
+
144
+ .error {
145
+ padding: 8px 12px;
146
+ border-radius: 8px;
147
+ background-color: #fdecea;
148
+ color: #8a1c13;
149
+ font-size: 13px;
150
+ }
151
+ `.trim();
152
+ }