plz-penguin-letters 0.1.0 → 0.2.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.
- package/CHANGELOG.md +26 -0
- package/README.ko.md +154 -28
- package/README.md +155 -29
- package/dist/cjs/install.d.ts +2 -0
- package/dist/cjs/install.js +52 -3
- package/dist/cjs/letters.js +65 -8
- package/dist/cjs/plan.d.ts +3 -2
- package/dist/cjs/plan.js +14 -14
- package/dist/esm/install.d.ts +2 -0
- package/dist/esm/install.js +52 -3
- package/dist/esm/letters.js +65 -8
- package/dist/esm/plan.d.ts +3 -2
- package/dist/esm/plan.js +14 -14
- package/package.json +3 -2
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Changes that affect people using the library. The newest version is at the top.
|
|
4
|
+
|
|
5
|
+
## 0.2.0 - 2026-12-03
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- **React apps could crash.** The library used to take the original text node out of the page. React keeps a reference to that node, so inserting something before it (`{loading && <Spinner />}{label}`) or removing it threw "not a child of this node". The text node now stays where it is and is only emptied.
|
|
10
|
+
- **Endless nesting when `include` contains `span`.** The library's own pieces are `span`s, so it huddled its own output again and again. It no longer looks inside a box it made.
|
|
11
|
+
- **Letters sticking out by about 1px in Firefox** when a line was narrowed a lot. The width is now checked again after the pieces are on the page.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- **One line by default.** `maxRows` now defaults to `1` (it was `3`): a longer translation is narrowed on a single line. Set `maxRows: 2` or `3` to let it stack.
|
|
16
|
+
- **How the number of rows is chosen.** It takes the fewest rows that keep the letters at or above `squeeze`, instead of the row count with the largest letters. A line that would get very thin is stacked sooner.
|
|
17
|
+
- **Short translations stack as plain lines.** When the translation has four letters or fewer per letter of the original, it is no longer cut into cells (`CO N / FI RM`); it is stacked as lines (`CON / FIRM`).
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- **Alignment.** Lines narrower than the original now follow the element's alignment instead of always sitting in the middle. See [How it decides](./README.md#how-it-decides).
|
|
22
|
+
- **`always` option.** Turn it off to huddle only when the longer text would push something or overflow.
|
|
23
|
+
|
|
24
|
+
## 0.1.0 - 2026-12-03
|
|
25
|
+
|
|
26
|
+
- First release: `installPenguinLetters()` and `penguinLetters()`.
|
package/README.ko.md
CHANGED
|
@@ -32,6 +32,25 @@
|
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
|
|
35
|
+
**목차**
|
|
36
|
+
|
|
37
|
+
- [문제](#문제)
|
|
38
|
+
- [펭귄식 해결책](#펭귄식-해결책)
|
|
39
|
+
- [뭉친 모습 더 보기](#뭉친-모습-더-보기)
|
|
40
|
+
- [쓰는 법](#쓰는-법)
|
|
41
|
+
- [어떻게 정하나](#어떻게-정하나)
|
|
42
|
+
- [옵션](#옵션)
|
|
43
|
+
- [몇 줄까지 (`maxRows`)](#몇-줄까지-maxrows)
|
|
44
|
+
- [얼마나 가늘게 (`squeeze`, `fill`)](#얼마나-가늘게-squeeze-fill)
|
|
45
|
+
- [어디를 볼지 (`include`, `exclude`, `always`)](#어디를-볼지-include-exclude-always)
|
|
46
|
+
- [안 뭉쳐도 되는 것들](#안-뭉쳐도-되는-것들)
|
|
47
|
+
- [한 일을 확인하기](#한-일을-확인하기)
|
|
48
|
+
- [진지한 부분](#진지한-부분)
|
|
49
|
+
- [자주 묻는 질문](#자주-묻는-질문)
|
|
50
|
+
- [변경 기록](#변경-기록)
|
|
51
|
+
- [개발](#개발)
|
|
52
|
+
- [라이선스](#라이선스)
|
|
53
|
+
|
|
35
54
|
```bash
|
|
36
55
|
npm install plz-penguin-letters
|
|
37
56
|
```
|
|
@@ -46,6 +65,8 @@ installPenguinLetters({ base: ko, text: fr });
|
|
|
46
65
|
|
|
47
66
|
앱 맨 위에 한 줄. 레이아웃은 다시는 안 깨진다.
|
|
48
67
|
|
|
68
|
+
|
|
69
|
+
|
|
49
70
|
## 문제
|
|
50
71
|
|
|
51
72
|
화면을 한 언어로 디자인한다. 전부 딱 맞는다. 그리고 독일어 번역이 도착한다.
|
|
@@ -54,35 +75,47 @@ installPenguinLetters({ base: ko, text: fr });
|
|
|
54
75
|
|
|
55
76
|
보통은 유연한 레이아웃이나 짧은 문구, 아니면 긴 회의로 이걸 푼다. 우리는 펭귄에게 물어봤다.
|
|
56
77
|
|
|
78
|
+
|
|
79
|
+
|
|
57
80
|
## 펭귄식 해결책
|
|
58
81
|
|
|
59
82
|
황제펭귄은 남극의 겨울을 뭉쳐서 버틴다. 수천 마리가 어깨를 맞대고, 수천 마리가 들어갈 리 없는 자리에 들어간다.
|
|
60
83
|
|
|
61
84
|
글자도 그렇게 할 수 있다.
|
|
62
85
|
|
|
63
|
-
|
|
86
|
+
번역은 원문이 차지하던 바로 그 상자 안에 그려진다. 들어갈 때까지 가로로 좁아지고, 높이는 원문과 똑같이 유지한다. 그래서 글자가 작아지는 대신 길쭉해진다. 허락하면 줄로도 쌓인다. 그때는 원문의 글자 하나가 한 칸이 된다.
|
|
64
87
|
|
|
65
88
|
```
|
|
89
|
+
눈치 → PERCEPTIVENESS 한 줄, 아주 가늘게 (기본)
|
|
90
|
+
|
|
66
91
|
눈치 → PERC EPT
|
|
67
|
-
(두 글자) IVEN ESS
|
|
92
|
+
(두 글자) IVEN ESS maxRows: 2
|
|
68
93
|
```
|
|
69
94
|
|
|
70
95
|
글자는 하나도 안 빠지고, 픽셀은 하나도 안 움직인다.
|
|
71
96
|
|
|
97
|
+
|
|
98
|
+
|
|
72
99
|
## 뭉친 모습 더 보기
|
|
73
100
|
|
|
74
101
|
**탭** — 전에도 다섯 개, 후에도 다섯 개. `Benachrichtigungen` 18글자도 그 안에 다 들어 있다.
|
|
75
102
|
|
|
76
|
-
<img src="./docs/demo-tabs.ko.gif" width="760" alt="탭 바. 전: 긴 번역이 뒤쪽 탭을 화면 밖으로 민다. 후: 탭 다섯 개가 제자리에 있고 글자는
|
|
103
|
+
<img src="./docs/demo-tabs.ko.gif" width="760" alt="탭 바. 전: 긴 번역이 뒤쪽 탭을 화면 밖으로 민다. 후: 탭 다섯 개가 제자리에 있고 글자는 더 가늘다." />
|
|
77
104
|
|
|
78
105
|
**표 머리글** — 열이 움직이지 않는다. 이렇게 평온했던 적이 없다.
|
|
79
106
|
|
|
80
107
|
<img src="./docs/demo-table.ko.gif" width="760" alt="표. 전: 머리글이 길어져 열이 넓어지다 마지막 열이 잘린다. 후: 열이 움직이지 않는다." />
|
|
81
108
|
|
|
82
|
-
**큰 낱말
|
|
109
|
+
**큰 낱말 하나를 쌓은 모습 (`maxRows: 3`, 칸 테두리 표시)** — 뭉친 속을 들여다본 모습.
|
|
83
110
|
|
|
84
111
|
<img src="./docs/demo-word.ko.gif" width="760" alt="120px 의 「설정」. 두 글자가 각각 한 칸이고, Settings · Paramètres · Einstellungen 이 그 안에 쌓인다." />
|
|
85
112
|
|
|
113
|
+
**운 좋게 잘린 낱말들 (`maxRows: 2`)** — 글자를 읽지 않고 세어서 자른다. 그런데 가끔 딱 음절 자리에 떨어진다. `암호`는 `PASS / WORD`, `MOT DE / PASSE`, `PASS / WORT`, `MẬT / KHẨU`가 된다.
|
|
114
|
+
|
|
115
|
+
<img src="./docs/demo-lucky.ko.gif" width="760" alt="120px 의 「암호」를 영어, 프랑스어, 독일어, 베트남어로 바꾼다. 두 줄까지 허락하니 Password 는 PASS 위에 WORD, Mot de passe 는 MOT DE 위에 PASSE, Passwort 는 PASS 위에 WORT, Mật khẩu 는 MẬT 위에 KHẨU 로 쌓인다." />
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
86
119
|
## 쓰는 법
|
|
87
120
|
|
|
88
121
|
원문이 무엇이었는지 알려 주는 방법이 세 가지다.
|
|
@@ -122,7 +155,7 @@ installPenguinLetters();
|
|
|
122
155
|
```js
|
|
123
156
|
import { penguinLetters } from "plz-penguin-letters";
|
|
124
157
|
|
|
125
|
-
const undo = penguinLetters(element, { base: "눈치", text: "perceptiveness" });
|
|
158
|
+
const undo = penguinLetters(element, { base: "눈치", text: "perceptiveness", maxRows: 2 });
|
|
126
159
|
```
|
|
127
160
|
|
|
128
161
|
### React
|
|
@@ -133,54 +166,145 @@ React용 패키지는 없다. 펭귄은 짐을 가볍게 다닌다.
|
|
|
133
166
|
useEffect(() => installPenguinLetters({ base: ko, text: messages }), [messages]);
|
|
134
167
|
```
|
|
135
168
|
|
|
169
|
+
next-intl이라면 `messages`는 `useMessages()`이고, `base`는 서버 컴포넌트에서 원문 언어 파일을 내려 주면 된다.
|
|
170
|
+
|
|
136
171
|
두 함수 모두 원래대로 되돌리는 함수를 돌려준다. 부르면 글자들이 다시 흩어진다.
|
|
137
172
|
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
## 어떻게 정하나
|
|
176
|
+
|
|
177
|
+
맡은 요소마다 이 순서로 정한다.
|
|
178
|
+
|
|
179
|
+
1. **상자.** 원문을 그 요소의 글꼴로, 보이지 않게 놓는다. 그 상자가 자리다. 자리를 차지하는 것은 이것뿐이다.
|
|
180
|
+
2. **높이.** 글자 크기는 번역의 획 높이가 원문의 획 높이와 똑같아지게 잡는다. 가장 높은 획의 위 끝부터 가장 낮은 획의 아래 끝까지다.
|
|
181
|
+
3. **줄 수.** 먼저 한 줄로 해 본다. 글자를 `squeeze`보다 더 좁혀야 하고 `maxRows`가 허락하면 두 줄, 그다음 세 줄을 해 본다. 글자가 `squeeze` 밑으로 안 내려가는 가장 적은 줄 수를 고른다.
|
|
182
|
+
4. **칸이냐 줄이냐.** 번역이 원문 한 글자당 네 글자를 넘으면, 원문 글자 하나가 한 칸이 되고 조각이 그 안에 쌓인다(`PERC EPT / IVEN ESS`). 그보다 적으면 칸마다 한두 글자뿐이라, 칸 없이 줄로만 쌓는다(`ENREG / ISTRER`).
|
|
183
|
+
5. **폭.** 좁히는 비율은 낱말 전체가 하나를 쓴다. 가장 넓은 조각이 들어가는 값이다. 짧은 조각은 늘이지 않고 자간을 조금 벌린다(`spread`).
|
|
184
|
+
6. **어느 쪽에 붙일지.** 칸에 든 조각은 칸 가운데에 둔다. 칸 없이 쌓인 줄이 원문보다 좁으면 요소를 따른다. 제목, 여백 있는 버튼, 문장 속 링크는 글 정렬(`text-align`)을 따르고, 버튼 안의 꾸밈 없는 라벨은 이웃이 있는 쪽을 따른다(아이콘 옆이면 아이콘 쪽, 혼자면 가운데).
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
## 옵션
|
|
189
|
+
|
|
190
|
+
옵션 없이도 돈다. 모든 옵션은 화면 전체에 적용된다.
|
|
191
|
+
|
|
192
|
+
| 옵션 | 값 | 기본값 | 뜻 |
|
|
193
|
+
| --- | --- | --- | --- |
|
|
194
|
+
| `base`, `text` | 객체 | 없음 | 번역 파일: 원문 언어와 지금 보여 주는 언어 |
|
|
195
|
+
| `pairs` | 객체 | 없음 | `{ "보이는 글": "원문" }`. 번역 파일보다 먼저다 |
|
|
196
|
+
| `include` | CSS 선택자 | 버튼, 링크, 라벨, `th`, `legend`, `summary`, 제목, `role` button · tab · menuitem | 사전으로 찾아볼 요소 |
|
|
197
|
+
| `exclude` | CSS 선택자 | 없음 | 이 선택자에 맞는 요소와 그 안쪽은 건드리지 않는다 |
|
|
198
|
+
| `always` | boolean | `true` | 자리가 넉넉해도 뭉친다 |
|
|
199
|
+
| `maxRows` | 숫자 | `1` | 쌓을 수 있는 줄 수 |
|
|
200
|
+
| `rows` | 숫자 | 자동 | 줄 수를 못박는다 |
|
|
201
|
+
| `squeeze` | 0 – 1 | `0.5` | 이보다 좁혀야 하면 줄을 하나 더 쌓아 본다 |
|
|
202
|
+
| `fill` | boolean | `true` | 높이를 꽉 채운다. 글자가 작아지는 대신 가늘어진다 |
|
|
203
|
+
| `uppercase` | boolean | `true` | 대문자로 그린다 |
|
|
204
|
+
| `spread` | 숫자 (em) | `0.08` | 짧은 조각이 칸을 채우려고 벌릴 수 있는 자간 |
|
|
205
|
+
| `lineGap` | 숫자 (em) | `0.08` | 줄 사이 틈 |
|
|
206
|
+
| `cellGap` | 숫자 (em) | `0` | 칸 사이 틈 |
|
|
207
|
+
| `down` | boolean | `false` | 한 칸을 아래로 다 읽고 다음 칸으로 간다 |
|
|
208
|
+
| `debug` | boolean | `false` | 칸 테두리를 그린다 |
|
|
209
|
+
|
|
210
|
+
```js
|
|
211
|
+
installPenguinLetters({ base: ko, text: fr, maxRows: 2, exclude: ".editor, [contenteditable]" });
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`penguinLetters(element, options)`는 `base`와 `text`를 글로 받고, `maxRows`부터 아래의 옵션을 같이 받는다.
|
|
215
|
+
|
|
216
|
+
### 몇 줄까지 (`maxRows`)
|
|
217
|
+
|
|
218
|
+
같은 낱말을 `maxRows`만 바꿔 세 번 그렸다. `약관`은 두 글자고, 독일어로는 `Allgemeine Geschäftsbedingungen` 서른한 글자다.
|
|
219
|
+
|
|
220
|
+
<img src="./docs/demo-rows.ko.gif" width="760" alt="「약관」을 나란히 세 번 그리고 영어, 프랑스어, 독일어, 베트남어로 바꾼다. maxRows 1 은 아주 가는 한 줄, maxRows 2 는 두 줄, maxRows 3 은 독일어에서 세 줄이 되고 글자 폭이 거의 원래대로다." />
|
|
221
|
+
|
|
222
|
+
| | `약관` → `Allgemeine Geschäftsbedingungen` | 좁힌 비율 |
|
|
223
|
+
| --- | --- | --- |
|
|
224
|
+
| `maxRows: 1` (기본) | `ALLGEMEINE GESCHÄFTSBEDINGUNGEN` 한 줄. 바코드처럼 보이지만 한 낱말이 한 줄에 있다 | 0.09 |
|
|
225
|
+
| `maxRows: 2` | `ALLGEMEI NE GESC / HÄFTSBED INGUNGEN` | 0.35 |
|
|
226
|
+
| `maxRows: 3` | `ALLGE MEINE / GESCH ÄFTSB / EDING UNGEN` | 0.76 |
|
|
227
|
+
|
|
228
|
+
줄은 글자가 아직 `squeeze`보다 가늘 때만 하나 더 쌓는다. 프랑스어 `Conditions générales`는 `maxRows: 3`을 줘도 두 줄에서 멈춘다. 두 줄에서 이미 0.59가 되기 때문이다.
|
|
229
|
+
|
|
230
|
+
한 줄이 기본인 까닭은 가장 덜 놀라워서다. 줄로 쌓는 것이 이 라이브러리 이름의 유래다. 보고 싶을 때 켠다.
|
|
231
|
+
|
|
232
|
+
`rows`는 고르지 않고 줄 수를 못박는다.
|
|
233
|
+
|
|
234
|
+
### 얼마나 가늘게 (`squeeze`, `fill`)
|
|
235
|
+
|
|
236
|
+
`squeeze`는 줄을 하나 더 쌓게 만드는 한도다. `0.5`는 "한 줄로 넣으면 원래 폭의 절반보다 가늘어질 때 두 줄을 해 본다"는 뜻이다. `maxRows: 1`이면 해 볼 다른 줄이 없으니, 그 줄이 필요한 만큼 가늘어진다.
|
|
237
|
+
|
|
238
|
+
`fill`은 글자를 원문의 높이 그대로 둔다. 끄면 한도가 진짜 한도가 된다. 글자는 `squeeze`에서 좁아지기를 멈추고 대신 작아진다. 그러면 낱말이 옆의 글보다 낮아 보인다.
|
|
239
|
+
|
|
240
|
+
`uppercase`가 켜져 있는 까닭은 대문자가 높이가 고르고 아래로 내려가는 획이 없어서 상자를 채우기 때문이다. 소문자면 `g`나 `y` 하나가 나머지 글자의 높이를 깎는다.
|
|
241
|
+
|
|
242
|
+
### 어디를 볼지 (`include`, `exclude`, `always`)
|
|
243
|
+
|
|
244
|
+
`include`는 사전으로 찾아볼 요소의 선택자다. 글을 직접 품은 요소만 맡으니, 버튼이 라벨을 한 번 더 감싸고 있으면(`<button><span>저장</span></button>`) 감싼 요소를 넣는다.
|
|
245
|
+
|
|
246
|
+
```js
|
|
247
|
+
installPenguinLetters({ base: ko, text: fr, include: "button, a, h1, h2, h3, span" });
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
선택자가 넓을수록 더 많이 뭉친다. `p`와 `div`를 넣으면 문장까지 잡힌다.
|
|
251
|
+
|
|
252
|
+
`always: false`는 길어진 글이 이웃을 밀거나, 보이는 상자를 키우거나, 넘칠 때만 뭉친다. 오른쪽이 비어 있는 제목은 그대로 둔다.
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
138
256
|
## 안 뭉쳐도 되는 것들
|
|
139
257
|
|
|
140
258
|
- 원문보다 넓지 않은 번역(`확인` → `OK`). 짧은 펭귄은 자유롭게 다닌다.
|
|
141
|
-
- 글 말고 다른 것이 같이 든 요소(라벨 옆의 아이콘, 문장 속 링크). 얘도 뭉치게 하고 싶으면 라벨을 `<span>`으로
|
|
259
|
+
- 글 말고 다른 것이 같이 든 요소(라벨 옆의 아이콘, 문장 속 링크). 얘도 뭉치게 하고 싶으면 라벨을 `<span>`으로 감싸고 `include`에 `span`을 넣는다.
|
|
260
|
+
- 값이 끼어든 글(`{count}개`). 화면의 글이 번역 파일의 글과 달라진다.
|
|
142
261
|
- `include` 밖의 요소와 `exclude` 안의 요소.
|
|
143
262
|
- 서로 다른 원문 두 개에 걸리는 글(`Fermer`가 `닫기`이기도 `종료`이기도 할 때). 찍을 수는 없으니, 이런 것은 속성으로 표시한다.
|
|
144
263
|
|
|
145
|
-
|
|
264
|
+
|
|
146
265
|
|
|
147
|
-
|
|
266
|
+
## 한 일을 확인하기
|
|
148
267
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
| `cellGap` | `0` | 칸 사이 틈(그린 글자 크기 대비). |
|
|
161
|
-
| `lineGap` | `0.08` | 줄 사이 틈(글자 크기 대비). |
|
|
162
|
-
| `spread` | `0.08` | 짧은 조각은 자간을 이만큼까지 벌려 칸을 채운다. |
|
|
163
|
-
| `down` | `false` | 가로로 이어 읽지 않고, 한 칸을 아래로 다 읽은 뒤 다음 칸으로 간다. |
|
|
164
|
-
| `debug` | `false` | 칸 테두리를 그린다. 누가 어디 섰는지 보인다. |
|
|
165
|
-
|
|
166
|
-
`penguinLetters(element, options)`는 `base`와 `text`를 글로 받고, `uppercase`부터 아래의 배치 옵션을 같이 받는다.
|
|
268
|
+
`debug: true`는 칸마다 테두리를 그린다. 누가 어디 섰는지 보인다.
|
|
269
|
+
|
|
270
|
+
맡은 요소에는 개발자 도구에서 읽을 수 있는 표시도 붙는다.
|
|
271
|
+
|
|
272
|
+
```html
|
|
273
|
+
<span data-penguin-plan="2x2 69.5px 0.59">
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
칸 수 × 줄 수, 글자 크기, 좁힌 비율이다.
|
|
277
|
+
|
|
278
|
+
|
|
167
279
|
|
|
168
280
|
## 진지한 부분
|
|
169
281
|
|
|
170
282
|
아이디어는 장난스럽다. 구현은 장난이 아니다.
|
|
171
283
|
|
|
172
|
-
-
|
|
284
|
+
- **프레임워크와 싸우지 않는다.** 원래 글 노드를 화면에서 떼지 않는다. 그래서 React가 그 글을 고치고, 그 옆에 끼우고, 지워도 터지지 않는다. 글이 바뀌면 다시 뭉친다.
|
|
285
|
+
- **변화를 따라간다.** 나중에 생긴 요소도 처리하고, 요소 크기가 바뀌거나 웹 폰트가 다 읽히면 다시 계산한다.
|
|
286
|
+
- **낭독기**는 번역을 평범한 낱말 하나로 읽는다. 조각은 낭독기에 숨긴다.
|
|
173
287
|
- **서버 렌더링**: `document`가 없는 곳에서 부르면 아무것도 하지 않는다.
|
|
174
288
|
- **테스트**: Chromium, Firefox, WebKit에서 돌린다. `Intl.Segmenter`가 필요하다.
|
|
175
289
|
- **글자 수로 자른다.** 음절 자리가 아니다. `PERC / IVEN`은 사전의 하이픈 자리가 아니다. 펭귄은 하이픈을 안 쓴다.
|
|
176
290
|
|
|
291
|
+
|
|
292
|
+
|
|
177
293
|
## 자주 묻는 질문
|
|
178
294
|
|
|
179
295
|
**실서비스에 써도 되나요?**
|
|
180
296
|
제목이나 큰 버튼에서는 의외로 의도한 디자인처럼 보인다. 14px 본문이라면 디자이너에게 먼저 물어보자.
|
|
181
297
|
|
|
182
298
|
**14px에서도 읽히나요?**
|
|
183
|
-
글자가 아주
|
|
299
|
+
글자가 아주 가늘어진다. 한 글자도 빠지지 않았다. 세어 봤다.
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
## 변경 기록
|
|
304
|
+
|
|
305
|
+
버전마다 바뀐 것은 [CHANGELOG.md](./CHANGELOG.md)에 있다(영어). 최신 버전이 맨 위다.
|
|
306
|
+
|
|
307
|
+
|
|
184
308
|
|
|
185
309
|
## 개발
|
|
186
310
|
|
|
@@ -191,6 +315,8 @@ npm run build # dist/esm + dist/cjs, 타입 선언 포함
|
|
|
191
315
|
npm run record # 리드미 움짤(docs/demo*.gif) 다시 만들기 — ffmpeg 필요
|
|
192
316
|
```
|
|
193
317
|
|
|
318
|
+
|
|
319
|
+
|
|
194
320
|
## 라이선스
|
|
195
321
|
|
|
196
322
|
MIT. 펭귄은 한 마리도 눌리지 않았다. 글자들은 자원했다.
|
package/README.md
CHANGED
|
@@ -32,6 +32,25 @@
|
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
|
|
35
|
+
**Contents**
|
|
36
|
+
|
|
37
|
+
- [The problem](#the-problem)
|
|
38
|
+
- [The penguin solution](#the-penguin-solution)
|
|
39
|
+
- [More huddles](#more-huddles)
|
|
40
|
+
- [Usage](#usage)
|
|
41
|
+
- [How it decides](#how-it-decides)
|
|
42
|
+
- [Options](#options)
|
|
43
|
+
- [How many rows (`maxRows`)](#how-many-rows-maxrows)
|
|
44
|
+
- [How thin (`squeeze`, `fill`)](#how-thin-squeeze-fill)
|
|
45
|
+
- [Where to look (`include`, `exclude`, `always`)](#where-to-look-include-exclude-always)
|
|
46
|
+
- [Who gets to roam free](#who-gets-to-roam-free)
|
|
47
|
+
- [Seeing what it did](#seeing-what-it-did)
|
|
48
|
+
- [The serious part](#the-serious-part)
|
|
49
|
+
- [FAQ](#faq)
|
|
50
|
+
- [Changelog](#changelog)
|
|
51
|
+
- [Development](#development)
|
|
52
|
+
- [License](#license)
|
|
53
|
+
|
|
35
54
|
```bash
|
|
36
55
|
npm install plz-penguin-letters
|
|
37
56
|
```
|
|
@@ -46,6 +65,8 @@ installPenguinLetters({ base: en, text: fr });
|
|
|
46
65
|
|
|
47
66
|
One line at the top of your app. Your layout will never break again.
|
|
48
67
|
|
|
68
|
+
|
|
69
|
+
|
|
49
70
|
## The problem
|
|
50
71
|
|
|
51
72
|
You design a screen in one language. Everything fits. Then the German translation arrives.
|
|
@@ -54,35 +75,47 @@ You design a screen in one language. Everything fits. Then the German translatio
|
|
|
54
75
|
|
|
55
76
|
Most people fix this with flexible layouts, shorter copy, or a long meeting. We asked the penguins.
|
|
56
77
|
|
|
78
|
+
|
|
79
|
+
|
|
57
80
|
## The penguin solution
|
|
58
81
|
|
|
59
82
|
Emperor penguins survive the Antarctic winter by huddling: thousands of them, shoulder to shoulder, in a space that should not hold thousands of penguins.
|
|
60
83
|
|
|
61
84
|
Letters can do that too.
|
|
62
85
|
|
|
63
|
-
|
|
86
|
+
The translation is drawn in the exact box the original word took. It is narrowed until it fits, and it keeps the full height of the original, so the letters get tall and thin rather than small. If you let it, it also stacks into rows, with each letter of the original word as one cell.
|
|
64
87
|
|
|
65
88
|
```
|
|
89
|
+
FAQ → FOIRE AUX QUESTIONS one line, very thin (default)
|
|
90
|
+
|
|
66
91
|
FAQ → FOI RE AUX
|
|
67
|
-
(3 letters) QUE STI ONS
|
|
92
|
+
(3 letters) QUE STI ONS maxRows: 2
|
|
68
93
|
```
|
|
69
94
|
|
|
70
95
|
Not one letter is dropped, and not one pixel moves.
|
|
71
96
|
|
|
97
|
+
|
|
98
|
+
|
|
72
99
|
## More huddles
|
|
73
100
|
|
|
74
101
|
**Tabs** — five tabs before, five tabs after. `Benachrichtigungen` is in there too, all 18 letters.
|
|
75
102
|
|
|
76
|
-
<img src="./docs/demo-tabs.gif" width="760" alt="A tab bar. Before: longer translations push the last tabs off the edge. After: all five tabs stay where they were, in
|
|
103
|
+
<img src="./docs/demo-tabs.gif" width="760" alt="A tab bar. Before: longer translations push the last tabs off the edge. After: all five tabs stay where they were, in thinner letters." />
|
|
77
104
|
|
|
78
105
|
**Table headers** — the columns have not moved. They have never been so calm.
|
|
79
106
|
|
|
80
107
|
<img src="./docs/demo-table.gif" width="760" alt="A table. Before: longer headers widen the columns until the last one is cut off. After: the columns do not move." />
|
|
81
108
|
|
|
82
|
-
**One big word,
|
|
109
|
+
**One big word, stacked (`maxRows: 3`, cells outlined)** — a look inside the huddle.
|
|
83
110
|
|
|
84
111
|
<img src="./docs/demo-word.gif" width="760" alt="The word FAQ at 120px. Each of its three letters is a cell, and Foire aux questions, Häufig gestellte Fragen and Câu hỏi thường gặp are stacked inside them." />
|
|
85
112
|
|
|
113
|
+
**Lucky cuts (`maxRows: 2`)** — words are cut by counting letters, not by reading them. Sometimes the count lands exactly on a syllable: `Hi` becomes `BON / JOUR`, `SER / VUS` and `XIN / CHÀO`.
|
|
114
|
+
|
|
115
|
+
<img src="./docs/demo-lucky.gif" width="760" alt="The word Hi at 120px, switched to French, German and Vietnamese. With two rows allowed, Bonjour is stacked as BON over JOUR, Servus as SER over VUS, and Xin chào as XIN over CHÀO." />
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
86
119
|
## Usage
|
|
87
120
|
|
|
88
121
|
There are three ways to tell it what the original word was.
|
|
@@ -122,7 +155,7 @@ An element with the attribute is always handled, wherever it is.
|
|
|
122
155
|
```js
|
|
123
156
|
import { penguinLetters } from "plz-penguin-letters";
|
|
124
157
|
|
|
125
|
-
const undo = penguinLetters(element, { base: "FAQ", text: "Foire aux questions" });
|
|
158
|
+
const undo = penguinLetters(element, { base: "FAQ", text: "Foire aux questions", maxRows: 2 });
|
|
126
159
|
```
|
|
127
160
|
|
|
128
161
|
### React
|
|
@@ -133,54 +166,145 @@ There is no React package. Penguins travel light.
|
|
|
133
166
|
useEffect(() => installPenguinLetters({ base: en, text: messages }), [messages]);
|
|
134
167
|
```
|
|
135
168
|
|
|
169
|
+
With next-intl, `messages` is `useMessages()`, and `base` is the original language's file passed down from a server component.
|
|
170
|
+
|
|
136
171
|
Both functions return a function that puts everything back and lets the letters spread out again.
|
|
137
172
|
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
## How it decides
|
|
176
|
+
|
|
177
|
+
For every element it handles, in this order:
|
|
178
|
+
|
|
179
|
+
1. **The box.** The original word is laid out invisibly, in the element's own font. That box is the footprint, and it is the only thing that takes up space.
|
|
180
|
+
2. **The height.** The font size is chosen so the letters are exactly as tall as the original's ink, from the top of the tallest stroke to the bottom of the lowest.
|
|
181
|
+
3. **The rows.** One row is tried first. If the letters would have to be narrower than `squeeze`, and `maxRows` allows it, a second row is tried, then a third. The fewest rows that keep the letters at or above `squeeze` win.
|
|
182
|
+
4. **Cells or lines.** With more than four letters of translation per letter of the original, each original letter becomes a cell and the pieces are stacked inside it (`FOI RE AUX / QUE STI ONS`). With fewer, cells would hold one or two letters each, so it stacks plain lines instead (`ENREG / ISTRER`).
|
|
183
|
+
5. **The width.** One narrowing ratio is used for the whole word: the one that makes the widest piece fit. Shorter pieces get a little letter-spacing (`spread`) instead of being stretched.
|
|
184
|
+
6. **The side.** Pieces in cells sit in the middle of their cell. Plain lines narrower than the original follow the element: `text-align` for headings, padded buttons and links inside a sentence; for a bare label inside a button, the side its neighbours are on (next to the icon, or centred if it is alone).
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
## Options
|
|
189
|
+
|
|
190
|
+
It works with no options at all. Every option applies to the whole page.
|
|
191
|
+
|
|
192
|
+
| Option | Value | Default | Meaning |
|
|
193
|
+
| --- | --- | --- | --- |
|
|
194
|
+
| `base`, `text` | object | none | Translation files: the original language, and the one on screen |
|
|
195
|
+
| `pairs` | object | none | `{ "shown text": "original" }`. Wins over the files |
|
|
196
|
+
| `include` | CSS selector | buttons, links, labels, `th`, `legend`, `summary`, headings, `role` button · tab · menuitem | Which elements are looked up in the dictionary |
|
|
197
|
+
| `exclude` | CSS selector | none | Elements matching this, and everything inside them, are left alone |
|
|
198
|
+
| `always` | boolean | `true` | Huddle even when there is room to grow |
|
|
199
|
+
| `maxRows` | number | `1` | How many rows it may stack |
|
|
200
|
+
| `rows` | number | auto | Force an exact number of rows |
|
|
201
|
+
| `squeeze` | 0 – 1 | `0.5` | How narrow letters may get before another row is tried |
|
|
202
|
+
| `fill` | boolean | `true` | Keep the full height; letters get thin instead of small |
|
|
203
|
+
| `uppercase` | boolean | `true` | Draw in capitals |
|
|
204
|
+
| `spread` | number (em) | `0.08` | Letter-spacing short pieces may get to fill their cell |
|
|
205
|
+
| `lineGap` | number (em) | `0.08` | Gap between rows |
|
|
206
|
+
| `cellGap` | number (em) | `0` | Gap between cells |
|
|
207
|
+
| `down` | boolean | `false` | Read down each cell, then move to the next |
|
|
208
|
+
| `debug` | boolean | `false` | Outline the cells |
|
|
209
|
+
|
|
210
|
+
```js
|
|
211
|
+
installPenguinLetters({ base: en, text: fr, maxRows: 2, exclude: ".editor, [contenteditable]" });
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`penguinLetters(element, options)` takes `base` and `text` as strings, plus everything from `maxRows` down.
|
|
215
|
+
|
|
216
|
+
### How many rows (`maxRows`)
|
|
217
|
+
|
|
218
|
+
The same word three times, with only `maxRows` changed. `T&C` is three letters; the German for it is `Allgemeine Geschäftsbedingungen`, thirty-one.
|
|
219
|
+
|
|
220
|
+
<img src="./docs/demo-rows.gif" width="760" alt="The label T&C drawn three times side by side, switched between French, German and Vietnamese. With maxRows 1 the translation is one very thin line. With maxRows 2 it is two rows. With maxRows 3 the German one takes three rows and the letters are almost their natural width." />
|
|
221
|
+
|
|
222
|
+
| | `T&C` → `Allgemeine Geschäftsbedingungen` | Narrowed to |
|
|
223
|
+
| --- | --- | --- |
|
|
224
|
+
| `maxRows: 1` (default) | `ALLGEMEINE GESCHÄFTSBEDINGUNGEN` on one line. Reads like a barcode, but it is one word on one line | 0.13 |
|
|
225
|
+
| `maxRows: 2` | `ALLGE MEINE GESC / HÄFTSB EDING UNGEN` | 0.44 |
|
|
226
|
+
| `maxRows: 3` | `ALLG EME INE / GES CHÄF TSB / EDIN GUN GEN` | 0.96 |
|
|
227
|
+
|
|
228
|
+
A row is added only while the letters are still narrower than `squeeze`. The French `Conditions générales` stops at two rows even with `maxRows: 3`, because two rows already bring it to 0.61.
|
|
229
|
+
|
|
230
|
+
One line is the default because it is the least surprising. Stacking is where the library gets its name; turn it on when you want to see it.
|
|
231
|
+
|
|
232
|
+
`rows` skips the choice and forces a number.
|
|
233
|
+
|
|
234
|
+
### How thin (`squeeze`, `fill`)
|
|
235
|
+
|
|
236
|
+
`squeeze` is the limit that triggers another row: `0.5` means "if one line would be narrower than half its natural width, try two". With `maxRows: 1` there is no other row to try, so the line simply gets as thin as it must.
|
|
237
|
+
|
|
238
|
+
`fill` keeps the letters at the full height of the original. Turn it off and the limit becomes a hard one: letters stop narrowing at `squeeze` and get smaller instead, which leaves the word shorter than its neighbours.
|
|
239
|
+
|
|
240
|
+
`uppercase` is on because capitals have even heights and no descenders, so they fill the box. With lowercase, a `g` or `y` takes height away from every other letter.
|
|
241
|
+
|
|
242
|
+
### Where to look (`include`, `exclude`, `always`)
|
|
243
|
+
|
|
244
|
+
`include` is a selector for the elements that are looked up in the dictionary. Only elements that hold plain text directly are handled, so if your buttons wrap their label (`<button><span>Save</span></button>`), add the wrapper:
|
|
245
|
+
|
|
246
|
+
```js
|
|
247
|
+
installPenguinLetters({ base: en, text: fr, include: "button, a, h1, h2, h3, span" });
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The wider the selector, the more gets huddled. `p` and `div` will catch whole sentences.
|
|
251
|
+
|
|
252
|
+
`always: false` huddles only when the longer text would actually push a neighbour, grow a visible box, or overflow. A heading with empty space to its right is then left alone.
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
138
256
|
## Who gets to roam free
|
|
139
257
|
|
|
140
258
|
- A translation that is not wider than the original (`Cancel` → `Hủy`). Short penguins roam free.
|
|
141
|
-
- Elements with anything other than plain text inside (an icon next to the label, a link inside a sentence). Wrap the label in a `<span>` if you want it huddled too.
|
|
259
|
+
- Elements with anything other than plain text inside (an icon next to the label, a link inside a sentence). Wrap the label in a `<span>` and add `span` to `include` if you want it huddled too.
|
|
260
|
+
- Text with values in it (`{count} items`). The text on screen no longer matches the file.
|
|
142
261
|
- Anything outside `include`, and anything inside `exclude`.
|
|
143
262
|
- A text that maps to two different originals (`Fermer` for both `Close` and `Quit`). It can't guess; mark those with the attribute.
|
|
144
263
|
|
|
145
|
-
|
|
264
|
+
|
|
146
265
|
|
|
147
|
-
|
|
266
|
+
## Seeing what it did
|
|
148
267
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
| `cellGap` | `0` | Gap between cells, in em of the drawn size. |
|
|
161
|
-
| `lineGap` | `0.08` | Gap between rows, in em. |
|
|
162
|
-
| `spread` | `0.08` | Short pieces get up to this much letter-spacing to fill their cell. |
|
|
163
|
-
| `down` | `false` | Read down each cell before moving to the next, instead of across. |
|
|
164
|
-
| `debug` | `false` | Outlines the cells, so you can see who stands where. |
|
|
165
|
-
|
|
166
|
-
`penguinLetters(element, options)` takes `base` and `text` as strings, plus the layout options from `uppercase` down.
|
|
268
|
+
`debug: true` outlines every cell, so you can see who stands where.
|
|
269
|
+
|
|
270
|
+
Each handled element also gets a marker you can read in the inspector:
|
|
271
|
+
|
|
272
|
+
```html
|
|
273
|
+
<span data-penguin-plan="3x2 57.1px 0.60">
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
That is cells × rows, the font size, and the narrowing ratio.
|
|
277
|
+
|
|
278
|
+
|
|
167
279
|
|
|
168
280
|
## The serious part
|
|
169
281
|
|
|
170
282
|
The idea is playful. The implementation is not kidding.
|
|
171
283
|
|
|
172
|
-
- **It
|
|
284
|
+
- **It does not fight your framework.** The original text node stays in the page, so React can keep updating it, inserting next to it and removing it. When the text changes, the huddle is redone.
|
|
285
|
+
- **It follows changes.** Elements added later are picked up, and everything is recalculated when the element is resized or a web font finishes loading.
|
|
286
|
+
- **Screen readers** get the translation as one normal word. The pieces are hidden from them.
|
|
173
287
|
- **Server rendering**: calling it where there is no `document` does nothing.
|
|
174
|
-
- **Tested** on Chromium, Firefox and WebKit
|
|
288
|
+
- **Tested** on Chromium, Firefox and WebKit. Needs `Intl.Segmenter`.
|
|
175
289
|
- **Words are cut by letter count**, not by syllable. `FOI / RE` is not where a dictionary would hyphenate. Penguins do not hyphenate.
|
|
176
290
|
|
|
291
|
+
|
|
292
|
+
|
|
177
293
|
## FAQ
|
|
178
294
|
|
|
179
295
|
**Should I use this in production?**
|
|
180
296
|
On a headline or a big button, it looks surprisingly intentional. On 14px body text, ask your designer first.
|
|
181
297
|
|
|
182
298
|
**Is it readable at 14px?**
|
|
183
|
-
The letters get very
|
|
299
|
+
The letters get very thin. They are all there. We counted.
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
## Changelog
|
|
304
|
+
|
|
305
|
+
What changed in each version is in [CHANGELOG.md](./CHANGELOG.md). The newest version is at the top.
|
|
306
|
+
|
|
307
|
+
|
|
184
308
|
|
|
185
309
|
## Development
|
|
186
310
|
|
|
@@ -191,6 +315,8 @@ npm run build # dist/esm + dist/cjs with type declarations
|
|
|
191
315
|
npm run record # re-record the README GIFs (docs/demo*.gif) — needs ffmpeg
|
|
192
316
|
```
|
|
193
317
|
|
|
318
|
+
|
|
319
|
+
|
|
194
320
|
## License
|
|
195
321
|
|
|
196
322
|
MIT. No penguins were squeezed. The letters volunteered.
|
package/dist/cjs/install.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface InstallOptions extends PlanOptions {
|
|
|
26
26
|
include?: string;
|
|
27
27
|
/** 건드리지 않을 요소 선택자 — 그 안쪽까지 뺀다. */
|
|
28
28
|
exclude?: string;
|
|
29
|
+
/** 자리가 넉넉해도 원문 자리에 뭉친다. 끄면 길어진 글이 무언가를 밀거나 넘칠 때만 뭉친다(오른쪽이 빈 제목·라벨은 그대로 둔다). 기본 켬. */
|
|
30
|
+
always?: boolean;
|
|
29
31
|
/** 대문자로 바꿔 그린다. 기본 켬. */
|
|
30
32
|
uppercase?: boolean;
|
|
31
33
|
/** 칸 테두리를 그린다. */
|
package/dist/cjs/install.js
CHANGED
|
@@ -61,6 +61,37 @@ function validSelector(selector) {
|
|
|
61
61
|
return "";
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
+
/** 눈에 보이는 상자(배경·테두리·그림자)가 없는가 — 그냥 글이면 길어져도 「상자가 커졌다」 고 할 것이 없다. */
|
|
65
|
+
function plain(el) {
|
|
66
|
+
const style = getComputedStyle(el);
|
|
67
|
+
const borders = [style.borderTopWidth, style.borderRightWidth, style.borderBottomWidth, style.borderLeftWidth];
|
|
68
|
+
return style.backgroundImage === "none" && /transparent|, 0\)$/.test(style.backgroundColor) && style.boxShadow === "none" && borders.every((width) => parseFloat(width) === 0);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* 번역이 들어가도 둘레가 그대로인가 — 글을 원문으로 잠깐 바꿔 놓고, 부모와 양옆 요소의 자리(상자가 보이는 요소면 자기 크기도)를 견준다.
|
|
72
|
+
* 오른쪽이 비어 있는 제목·라벨처럼 길어져도 아무것도 밀지 않는 글은 뭉칠 까닭이 없다.
|
|
73
|
+
*/
|
|
74
|
+
function roomy(el, base) {
|
|
75
|
+
const node = el.firstChild;
|
|
76
|
+
const parent = el.parentElement;
|
|
77
|
+
// 이미 넘쳐서 잘리고 있으면 자리가 없는 것이다.
|
|
78
|
+
// `body` 는 뺀다 — 브라우저가 `body` 의 스크롤 폭을 화면 폭으로 돌려줘, 여백만 있어도 넘친 것처럼 보인다.
|
|
79
|
+
if (el.scrollWidth > el.clientWidth || (parent && parent !== document.body && parent.scrollWidth > parent.clientWidth))
|
|
80
|
+
return false;
|
|
81
|
+
const around = [parent, el.previousElementSibling, el.nextElementSibling].filter((item) => item !== null);
|
|
82
|
+
const snap = () => [...around, ...(plain(el) ? [] : [el])].map((item) => item.getBoundingClientRect());
|
|
83
|
+
const now = snap();
|
|
84
|
+
const text = node.data;
|
|
85
|
+
node.data = base;
|
|
86
|
+
const designed = snap();
|
|
87
|
+
node.data = text;
|
|
88
|
+
// 세로는 줄 하나가 늘었는지만 본다 — 글꼴이 달라(한글·알파벳) 줄 높이가 1~2px 다른 것은 밀린 것이 아니다.
|
|
89
|
+
const line = parseFloat(getComputedStyle(el).fontSize) / 2;
|
|
90
|
+
return now.every((box, i) => {
|
|
91
|
+
const was = designed[i];
|
|
92
|
+
return Math.abs(box.left - was.left) < 1 && Math.abs(box.width - was.width) < 1 && Math.abs(box.top - was.top) < line && Math.abs(box.height - was.height) < line;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
64
95
|
/** 여러 번 설치해도 장치는 하나만 돈다 — 다시 설치하면 앞의 것을 걷고 새 설정으로 돈다(언어를 바꿀 때). */
|
|
65
96
|
let stop = null;
|
|
66
97
|
/**
|
|
@@ -72,16 +103,22 @@ function installPenguinLetters(options = {}) {
|
|
|
72
103
|
if (typeof document === "undefined" || typeof MutationObserver === "undefined")
|
|
73
104
|
return () => { };
|
|
74
105
|
stop?.();
|
|
75
|
-
const { base: _base, text: _text, pairs: _pairs, include, exclude, ...rest } = options;
|
|
106
|
+
const { base: _base, text: _text, pairs: _pairs, include, exclude, always = true, ...rest } = options;
|
|
76
107
|
const bases = pairsOf(options);
|
|
77
108
|
const wanted = validSelector(include) || INCLUDE;
|
|
78
109
|
const skipped = validSelector(exclude);
|
|
79
110
|
/** 맡은 요소 — 그때 넣은 글과 걷는 함수. */
|
|
111
|
+
/** 자리가 넉넉해 그대로 둔 요소와 그때의 글 — 화면이 바뀔 때마다 다시 재지 않는다. 창 크기가 바뀌면 비운다. */
|
|
112
|
+
let spacious = new WeakMap();
|
|
80
113
|
const handled = new Map();
|
|
81
114
|
const visit = (el) => {
|
|
115
|
+
// 넣어 둔 상자의 속(원문 자리·낭독용 글·조각)은 보지 않는다 — `include` 에 `span` 이 들면 그 속을 또 뭉쳐 끝없이 겹친다.
|
|
116
|
+
if (el.closest(`[${letters_ts_1.PLAN_ATTRIBUTE}]`))
|
|
117
|
+
return;
|
|
82
118
|
const done = handled.get(el);
|
|
83
|
-
// 넣어 둔
|
|
84
|
-
|
|
119
|
+
// 넣어 둔 그대로(비워 둔 글 노드 + 상자)면 볼 것이 없다.
|
|
120
|
+
// 바깥 코드(프레임워크)가 글을 다시 썼거나 옆에 다른 것을 끼웠으면 걷고 처음부터 다시 본다.
|
|
121
|
+
if (done && el.childNodes.length === 2 && el.firstChild?.nodeValue === "" && el.lastElementChild?.hasAttribute(letters_ts_1.PLAN_ATTRIBUTE))
|
|
85
122
|
return;
|
|
86
123
|
done?.undo();
|
|
87
124
|
handled.delete(el);
|
|
@@ -101,6 +138,11 @@ function installPenguinLetters(options = {}) {
|
|
|
101
138
|
const size = parseFloat(getComputedStyle(el).fontSize);
|
|
102
139
|
if (!measure || measure(text, size).width <= measure(base, size).width)
|
|
103
140
|
return;
|
|
141
|
+
// 원문보다 넓어도, 길어진 만큼 아무것도 밀지 않으면 그대로 둔다(`always` 를 껐을 때).
|
|
142
|
+
if (!always && spacious.get(el) === text)
|
|
143
|
+
return;
|
|
144
|
+
if (!always && roomy(el, base))
|
|
145
|
+
return void spacious.set(el, text);
|
|
104
146
|
}
|
|
105
147
|
handled.set(el, { text, undo: (0, letters_ts_1.penguinLetters)(el, { ...rest, base, text }) });
|
|
106
148
|
};
|
|
@@ -121,10 +163,16 @@ function installPenguinLetters(options = {}) {
|
|
|
121
163
|
const observer = new MutationObserver(() => {
|
|
122
164
|
frame ||= requestAnimationFrame(scan);
|
|
123
165
|
});
|
|
166
|
+
// 창이 좁아지면 넉넉하던 자리가 모자랄 수 있다 — 처음부터 다시 본다.
|
|
167
|
+
const resized = () => {
|
|
168
|
+
spacious = new WeakMap();
|
|
169
|
+
frame ||= requestAnimationFrame(scan);
|
|
170
|
+
};
|
|
124
171
|
const boot = () => {
|
|
125
172
|
if (stopped)
|
|
126
173
|
return;
|
|
127
174
|
scan();
|
|
175
|
+
window.addEventListener("resize", resized);
|
|
128
176
|
observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: [ATTRIBUTE] });
|
|
129
177
|
};
|
|
130
178
|
let stopped = false;
|
|
@@ -140,6 +188,7 @@ function installPenguinLetters(options = {}) {
|
|
|
140
188
|
if (stop === mine)
|
|
141
189
|
stop = null;
|
|
142
190
|
observer.disconnect();
|
|
191
|
+
window.removeEventListener("resize", resized);
|
|
143
192
|
cancelAnimationFrame(frame);
|
|
144
193
|
for (const { undo } of handled.values())
|
|
145
194
|
undo();
|
package/dist/cjs/letters.js
CHANGED
|
@@ -20,7 +20,37 @@ const plan_ts_1 = require("./plan.js");
|
|
|
20
20
|
exports.PLAN_ATTRIBUTE = "data-penguin-plan";
|
|
21
21
|
/** 화면에는 안 보이고 낭독기는 읽는다. */
|
|
22
22
|
const SPOKEN = "position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";
|
|
23
|
-
const CELL = "display:flex;flex-direction:column;justify-content:center;
|
|
23
|
+
const CELL = "display:flex;flex-direction:column;justify-content:center;min-width:0";
|
|
24
|
+
/** 글 정렬(왼쪽 · 가운데 · 오른쪽)마다 조각을 놓는 자리와, 좁힐 때 기준이 되는 쪽. */
|
|
25
|
+
const SIDES = { left: ["flex-start", "left"], center: ["center", "center"], right: ["flex-end", "right"] };
|
|
26
|
+
/**
|
|
27
|
+
* 원문보다 좁은 조각을 원문 자리의 어느 쪽에 붙일지.
|
|
28
|
+
* 요소가 글보다 넓거나(제목), 여백이 있는 상자거나(버튼), 문장 속에 끼어 있으면(링크) 글 정렬(`text-align`)을 따른다.
|
|
29
|
+
* 글에 딱 맞는 꾸밈 없는 요소(버튼 안의 `span`)는 글 정렬로 알 수 없다 — 그 요소를 놓는 것은 바깥의 flex 다.
|
|
30
|
+
* 그때는 놓인 자리를 본다: 같은 줄의 이웃이나 부모의 안쪽 끝 가운데 더 가까운 쪽에 붙어 있다고 친다(양쪽이 같으면 가운데).
|
|
31
|
+
*/
|
|
32
|
+
function sideOf(el, box) {
|
|
33
|
+
const style = getComputedStyle(el);
|
|
34
|
+
const padding = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
|
|
35
|
+
const mine = el.getBoundingClientRect();
|
|
36
|
+
const parent = el.parentElement;
|
|
37
|
+
const inText = [...(parent?.childNodes ?? [])].some((node) => node.nodeType === Node.TEXT_NODE && node.nodeValue?.trim());
|
|
38
|
+
if (!parent || inText || padding > 0 || mine.width - box.getBoundingClientRect().width > 1) {
|
|
39
|
+
const rtl = style.direction === "rtl";
|
|
40
|
+
const toRight = style.textAlign === "right" || style.textAlign === (rtl ? "start" : "end") || (rtl && style.textAlign === "justify");
|
|
41
|
+
return style.textAlign === "center" ? "center" : toRight ? "right" : "left";
|
|
42
|
+
}
|
|
43
|
+
const around = parent.getBoundingClientRect();
|
|
44
|
+
const outer = getComputedStyle(parent);
|
|
45
|
+
/** 같은 줄에 놓인 이웃의 자리 — 없거나 다른 줄이면 null. */
|
|
46
|
+
const beside = (item) => {
|
|
47
|
+
const place = item?.getBoundingClientRect();
|
|
48
|
+
return place && place.width > 0 && place.bottom > mine.top && place.top < mine.bottom ? place : null;
|
|
49
|
+
};
|
|
50
|
+
const left = mine.left - (beside(el.previousElementSibling)?.right ?? around.left + parseFloat(outer.borderLeftWidth) + parseFloat(outer.paddingLeft));
|
|
51
|
+
const right = (beside(el.nextElementSibling)?.left ?? around.right - parseFloat(outer.borderRightWidth) - parseFloat(outer.paddingRight)) - mine.right;
|
|
52
|
+
return Math.abs(left - right) <= 2 ? "center" : left < right ? "left" : "right";
|
|
53
|
+
}
|
|
24
54
|
/** 같은 요소에 다시 부르면 앞의 것을 먼저 걷는다. */
|
|
25
55
|
const undos = new WeakMap();
|
|
26
56
|
let ctx = null;
|
|
@@ -56,6 +86,10 @@ function penguinLetters(el, options) {
|
|
|
56
86
|
undos.get(el)?.();
|
|
57
87
|
const { base, text, uppercase = true, debug = false, ...rest } = options;
|
|
58
88
|
const before = [...el.childNodes];
|
|
89
|
+
// 글만 든 요소면 그 글 노드를 떼지 않고 비워만 둔다 — 프레임워크(React)가 그 노드를 쥐고 있어,
|
|
90
|
+
// 떼어 내면 나중에 그 앞에 다른 것을 끼우거나 그 노드를 지울 때 「자식이 아니다」 로 화면이 죽는다.
|
|
91
|
+
const kept = before.length === 1 && before[0].nodeType === Node.TEXT_NODE ? before[0] : null;
|
|
92
|
+
const original = kept?.data ?? "";
|
|
59
93
|
const make = (css, content = "") => {
|
|
60
94
|
const node = document.createElement("span");
|
|
61
95
|
node.style.cssText = css;
|
|
@@ -68,7 +102,12 @@ function penguinLetters(el, options) {
|
|
|
68
102
|
ghost.setAttribute("aria-hidden", "true");
|
|
69
103
|
stage.setAttribute("aria-hidden", "true");
|
|
70
104
|
box.append(ghost, make(SPOKEN, text), stage);
|
|
71
|
-
|
|
105
|
+
if (kept) {
|
|
106
|
+
kept.data = "";
|
|
107
|
+
el.append(box);
|
|
108
|
+
}
|
|
109
|
+
else
|
|
110
|
+
el.replaceChildren(box);
|
|
72
111
|
const draw = () => {
|
|
73
112
|
const fontSize = parseFloat(getComputedStyle(ghost).fontSize);
|
|
74
113
|
const canvas = measurer(ghost);
|
|
@@ -78,15 +117,27 @@ function penguinLetters(el, options) {
|
|
|
78
117
|
const measure = (content, size) => content === base && size === fontSize ? { ...canvas(content, size), width: ghost.getBoundingClientRect().width } : canvas(content, size);
|
|
79
118
|
const shown = uppercase ? upper(text, el.closest("[lang]")?.lang) : text;
|
|
80
119
|
const { cols, rows, size, squeeze, pitch, cells } = (0, plan_ts_1.plan)(base, shown, fontSize, measure, rest);
|
|
120
|
+
// 칸으로 나눴으면 칸 가운데에 둔다(칸이 원문 글자 자리다). 칸이 없으면 요소의 정렬을 따른다 —
|
|
121
|
+
// 왼쪽 정렬된 제목에서 원문보다 좁게 쌓인 줄이 가운데로 가면, 위아래 글과 줄 머리가 어긋난다.
|
|
122
|
+
const [place, origin] = SIDES[cols > 1 ? "center" : sideOf(el, box)];
|
|
81
123
|
// ponytail: 조각 더미를 글자 상자 가운데에 둔다 — 획의 가운데와 조금 어긋날 수 있다. 눈에 띄면 기준선을 재서 획 끝에 맞춘다.
|
|
82
124
|
stage.style.cssText = `position:absolute;inset:0;display:grid;grid-template-columns:repeat(${cols},minmax(0,1fr));font-size:${size}px;line-height:${pitch};letter-spacing:normal`;
|
|
83
125
|
stage.replaceChildren(...cells.map((lines) => {
|
|
84
|
-
const cell = make(
|
|
126
|
+
const cell = make(`${CELL};align-items:${place}${debug ? ";outline:1px dashed" : ""}`);
|
|
85
127
|
// 자간은 마지막 글자 뒤에도 붙는다 — 그만큼 당겨 가운데를 맞춘다.
|
|
86
|
-
cell.append(...lines.map((line) => make(`white-space:nowrap;transform:scaleX(${squeeze});letter-spacing:${line.spacing}px;margin-right:${-line.spacing}px`, line.text)));
|
|
128
|
+
cell.append(...lines.map((line) => make(`white-space:nowrap;transform:scaleX(${squeeze});transform-origin:${origin} center;letter-spacing:${line.spacing}px;margin-right:${-line.spacing}px`, line.text)));
|
|
87
129
|
return cell;
|
|
88
130
|
}));
|
|
89
|
-
|
|
131
|
+
// 캔버스로 잰 폭과 화면에 놓인 폭이 조금 다른 브라우저가 있다 — 아주 가늘게 좁힐 때 그 차이로 1px 가까이 넘친다.
|
|
132
|
+
// 놓인 폭을 재서, 넘치면 그만큼 더 좁힌다.
|
|
133
|
+
const lines = [...stage.querySelectorAll(":scope > * > *")];
|
|
134
|
+
const room = stage.getBoundingClientRect().width / cols;
|
|
135
|
+
const widest = Math.max(0, ...lines.map((line) => line.getBoundingClientRect().width + parseFloat(line.style.marginRight) * squeeze));
|
|
136
|
+
const tight = widest > room ? (squeeze * room) / widest : squeeze;
|
|
137
|
+
if (tight < squeeze)
|
|
138
|
+
for (const line of lines)
|
|
139
|
+
line.style.transform = `scaleX(${tight})`;
|
|
140
|
+
box.setAttribute(exports.PLAN_ATTRIBUTE, `${cols}x${rows} ${Math.round(size * 10) / 10}px ${tight.toFixed(2)}`);
|
|
90
141
|
};
|
|
91
142
|
draw();
|
|
92
143
|
// 글자 크기가 바뀌거나 글꼴이 늦게 실리면 기준 글의 자리가 달라진다 — 조각은 자리 위에 띄워 둬서, 다시 그려도 자리는 안 바뀐다.
|
|
@@ -100,9 +151,15 @@ function penguinLetters(el, options) {
|
|
|
100
151
|
undos.delete(el);
|
|
101
152
|
observer?.disconnect();
|
|
102
153
|
document.fonts?.removeEventListener("loadingdone", draw);
|
|
103
|
-
// 바깥 코드가 그사이 내용을 바꿨으면 그대로 둔다.
|
|
104
|
-
if (box.parentNode
|
|
105
|
-
|
|
154
|
+
// 바깥 코드가 그사이 내용을 통째로 바꿨으면 그대로 둔다.
|
|
155
|
+
if (box.parentNode !== el)
|
|
156
|
+
return;
|
|
157
|
+
if (!kept)
|
|
158
|
+
return el.replaceChildren(...before);
|
|
159
|
+
box.remove();
|
|
160
|
+
// 비워 둔 글 노드에 바깥 코드가 새 글을 써 넣었으면 그 글을 둔다.
|
|
161
|
+
if (kept.data === "")
|
|
162
|
+
kept.data = original;
|
|
106
163
|
};
|
|
107
164
|
undos.set(el, undo);
|
|
108
165
|
return undo;
|
package/dist/cjs/plan.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export type Measure = (text: string, size: number) => {
|
|
|
12
12
|
export interface PlanOptions {
|
|
13
13
|
/** 줄 수. 주지 않으면 글자가 가장 크게 나오는 줄 수를 고른다. */
|
|
14
14
|
rows?: number;
|
|
15
|
-
/**
|
|
15
|
+
/** 쌓을 수 있는 줄 수의 한도. 기본은 1 — 한 줄로만 좁힌다. 2 · 3 을 주면 한 줄로 너무 가늘어질 때 그만큼까지 줄을 쌓는다. */
|
|
16
16
|
maxRows?: number;
|
|
17
17
|
/** 가로로 좁히는 한도 — 줄 수를 고를 때 쓴다(이보다 더 좁혀야 하는 줄 수는 밀린다). `fill` 을 끄면 이보다 더 좁히지 않고 글자 크기를 줄인다. */
|
|
18
18
|
squeeze?: number;
|
|
@@ -46,6 +46,7 @@ export interface Plan {
|
|
|
46
46
|
}
|
|
47
47
|
/**
|
|
48
48
|
* `base`(기준 글)를 `fontSize` 로 그린 자리에 `text`(넣을 글)를 넣는 배치를 돌려준다.
|
|
49
|
-
* 줄 수를 주지 않으면 한 줄부터 한도까지
|
|
49
|
+
* 줄 수를 주지 않으면 한 줄부터 한도까지 해 보고, 장평이 한도 밑으로 내려가지 않는 가장 적은 줄 수를 고른다 — 한 줄로 가늘어지느니 줄을 쌓는다.
|
|
50
|
+
* 높이를 채우지 않을 때(`fill: false`)는 글자가 가장 크게 나오는 줄 수를 고른다.
|
|
50
51
|
*/
|
|
51
52
|
export declare function plan(base: string, text: string, fontSize: number, measure: Measure, options?: PlanOptions): Plan;
|
package/dist/cjs/plan.js
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
8
|
exports.plan = plan;
|
|
9
|
-
const DEFAULTS = { maxRows:
|
|
10
|
-
/** 칸마다 이 글자
|
|
9
|
+
const DEFAULTS = { maxRows: 1, squeeze: 0.5, fill: true, cellGap: 0, lineGap: 0.08, spread: 0.08, down: false };
|
|
10
|
+
/** 칸마다 이 글자 수를 넘어야 칸으로 나눈다 — 그보다 적으면 조각이 한두 글자뿐이라, 칸 없이 줄로만 쌓는다(확인 · CON / FIRM). */
|
|
11
11
|
const ONE_LINE = 4;
|
|
12
12
|
const segmenter = new Intl.Segmenter();
|
|
13
13
|
/** 눈에 보이는 글자 단위로 나눈다 — 부호가 따로 붙은 글자나 이모지를 가운데서 자르지 않는다. */
|
|
@@ -40,10 +40,12 @@ function cut(items, sizes) {
|
|
|
40
40
|
function layout(base, chars, fontSize, wanted, measure, o) {
|
|
41
41
|
const whole = measure(base, fontSize);
|
|
42
42
|
const letters = Math.max(1, graphemes(base).length);
|
|
43
|
-
|
|
44
|
-
const
|
|
43
|
+
const perCell = Math.ceil(chars.length / letters);
|
|
44
|
+
const celled = perCell > ONE_LINE;
|
|
45
|
+
// 줄 수는 모든 칸이 같다 — 한 줄에 놓을 글자가 하나는 있어야 한다.
|
|
46
|
+
const rows = Math.max(1, Math.min(wanted, celled ? perCell : chars.length));
|
|
45
47
|
// 한 줄이면 칸으로 나누지 않는다 — 나누면 낱말 가운데에 띄어쓰기 같은 틈만 생긴다.
|
|
46
|
-
const cols = rows === 1 ? 1 : letters;
|
|
48
|
+
const cols = rows === 1 || !celled ? 1 : letters;
|
|
47
49
|
const gap = cols === 1 ? 0 : o.cellGap;
|
|
48
50
|
const order = [...Array(cols).keys()];
|
|
49
51
|
// ponytail: 글자 수로 자른다(띄어쓰기도 글자 하나) — 낱말 사이·음절 자리에서 자르려면 자를 자리 후보를 받아 고르게 바꾼다.
|
|
@@ -85,7 +87,8 @@ function layout(base, chars, fontSize, wanted, measure, o) {
|
|
|
85
87
|
}
|
|
86
88
|
/**
|
|
87
89
|
* `base`(기준 글)를 `fontSize` 로 그린 자리에 `text`(넣을 글)를 넣는 배치를 돌려준다.
|
|
88
|
-
* 줄 수를 주지 않으면 한 줄부터 한도까지
|
|
90
|
+
* 줄 수를 주지 않으면 한 줄부터 한도까지 해 보고, 장평이 한도 밑으로 내려가지 않는 가장 적은 줄 수를 고른다 — 한 줄로 가늘어지느니 줄을 쌓는다.
|
|
91
|
+
* 높이를 채우지 않을 때(`fill: false`)는 글자가 가장 크게 나오는 줄 수를 고른다.
|
|
89
92
|
*/
|
|
90
93
|
function plan(base, text, fontSize, measure, options = {}) {
|
|
91
94
|
const o = { ...DEFAULTS, ...options };
|
|
@@ -94,12 +97,9 @@ function plan(base, text, fontSize, measure, options = {}) {
|
|
|
94
97
|
return { width: measure(base, fontSize).width, cols: 1, rows: 1, size: fontSize, squeeze: 1, pitch: 1, cells: [] };
|
|
95
98
|
if (options.rows)
|
|
96
99
|
return layout(base, chars, fontSize, options.rows, measure, o);
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
best = next;
|
|
103
|
-
}
|
|
104
|
-
return best;
|
|
100
|
+
// 글자 수보다 많은 줄은 못 쌓는다 — 줄 수가 깎인 것은 앞의 것과 같으니 뺀다.
|
|
101
|
+
const tries = Array.from({ length: Math.max(1, o.maxRows) }, (_, i) => layout(base, chars, fontSize, i + 1, measure, o)).filter((tried, i) => tried.rows === i + 1);
|
|
102
|
+
if (!o.fill)
|
|
103
|
+
return tries.reduce((best, next) => (next.score > best.score + 0.01 ? next : best));
|
|
104
|
+
return tries.find((tried) => tried.squeeze >= o.squeeze - 1e-9) ?? tries.reduce((best, next) => (next.squeeze > best.squeeze ? next : best));
|
|
105
105
|
}
|
package/dist/esm/install.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface InstallOptions extends PlanOptions {
|
|
|
26
26
|
include?: string;
|
|
27
27
|
/** 건드리지 않을 요소 선택자 — 그 안쪽까지 뺀다. */
|
|
28
28
|
exclude?: string;
|
|
29
|
+
/** 자리가 넉넉해도 원문 자리에 뭉친다. 끄면 길어진 글이 무언가를 밀거나 넘칠 때만 뭉친다(오른쪽이 빈 제목·라벨은 그대로 둔다). 기본 켬. */
|
|
30
|
+
always?: boolean;
|
|
29
31
|
/** 대문자로 바꿔 그린다. 기본 켬. */
|
|
30
32
|
uppercase?: boolean;
|
|
31
33
|
/** 칸 테두리를 그린다. */
|
package/dist/esm/install.js
CHANGED
|
@@ -58,6 +58,37 @@ function validSelector(selector) {
|
|
|
58
58
|
return "";
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
|
+
/** 눈에 보이는 상자(배경·테두리·그림자)가 없는가 — 그냥 글이면 길어져도 「상자가 커졌다」 고 할 것이 없다. */
|
|
62
|
+
function plain(el) {
|
|
63
|
+
const style = getComputedStyle(el);
|
|
64
|
+
const borders = [style.borderTopWidth, style.borderRightWidth, style.borderBottomWidth, style.borderLeftWidth];
|
|
65
|
+
return style.backgroundImage === "none" && /transparent|, 0\)$/.test(style.backgroundColor) && style.boxShadow === "none" && borders.every((width) => parseFloat(width) === 0);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* 번역이 들어가도 둘레가 그대로인가 — 글을 원문으로 잠깐 바꿔 놓고, 부모와 양옆 요소의 자리(상자가 보이는 요소면 자기 크기도)를 견준다.
|
|
69
|
+
* 오른쪽이 비어 있는 제목·라벨처럼 길어져도 아무것도 밀지 않는 글은 뭉칠 까닭이 없다.
|
|
70
|
+
*/
|
|
71
|
+
function roomy(el, base) {
|
|
72
|
+
const node = el.firstChild;
|
|
73
|
+
const parent = el.parentElement;
|
|
74
|
+
// 이미 넘쳐서 잘리고 있으면 자리가 없는 것이다.
|
|
75
|
+
// `body` 는 뺀다 — 브라우저가 `body` 의 스크롤 폭을 화면 폭으로 돌려줘, 여백만 있어도 넘친 것처럼 보인다.
|
|
76
|
+
if (el.scrollWidth > el.clientWidth || (parent && parent !== document.body && parent.scrollWidth > parent.clientWidth))
|
|
77
|
+
return false;
|
|
78
|
+
const around = [parent, el.previousElementSibling, el.nextElementSibling].filter((item) => item !== null);
|
|
79
|
+
const snap = () => [...around, ...(plain(el) ? [] : [el])].map((item) => item.getBoundingClientRect());
|
|
80
|
+
const now = snap();
|
|
81
|
+
const text = node.data;
|
|
82
|
+
node.data = base;
|
|
83
|
+
const designed = snap();
|
|
84
|
+
node.data = text;
|
|
85
|
+
// 세로는 줄 하나가 늘었는지만 본다 — 글꼴이 달라(한글·알파벳) 줄 높이가 1~2px 다른 것은 밀린 것이 아니다.
|
|
86
|
+
const line = parseFloat(getComputedStyle(el).fontSize) / 2;
|
|
87
|
+
return now.every((box, i) => {
|
|
88
|
+
const was = designed[i];
|
|
89
|
+
return Math.abs(box.left - was.left) < 1 && Math.abs(box.width - was.width) < 1 && Math.abs(box.top - was.top) < line && Math.abs(box.height - was.height) < line;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
61
92
|
/** 여러 번 설치해도 장치는 하나만 돈다 — 다시 설치하면 앞의 것을 걷고 새 설정으로 돈다(언어를 바꿀 때). */
|
|
62
93
|
let stop = null;
|
|
63
94
|
/**
|
|
@@ -69,16 +100,22 @@ export function installPenguinLetters(options = {}) {
|
|
|
69
100
|
if (typeof document === "undefined" || typeof MutationObserver === "undefined")
|
|
70
101
|
return () => { };
|
|
71
102
|
stop?.();
|
|
72
|
-
const { base: _base, text: _text, pairs: _pairs, include, exclude, ...rest } = options;
|
|
103
|
+
const { base: _base, text: _text, pairs: _pairs, include, exclude, always = true, ...rest } = options;
|
|
73
104
|
const bases = pairsOf(options);
|
|
74
105
|
const wanted = validSelector(include) || INCLUDE;
|
|
75
106
|
const skipped = validSelector(exclude);
|
|
76
107
|
/** 맡은 요소 — 그때 넣은 글과 걷는 함수. */
|
|
108
|
+
/** 자리가 넉넉해 그대로 둔 요소와 그때의 글 — 화면이 바뀔 때마다 다시 재지 않는다. 창 크기가 바뀌면 비운다. */
|
|
109
|
+
let spacious = new WeakMap();
|
|
77
110
|
const handled = new Map();
|
|
78
111
|
const visit = (el) => {
|
|
112
|
+
// 넣어 둔 상자의 속(원문 자리·낭독용 글·조각)은 보지 않는다 — `include` 에 `span` 이 들면 그 속을 또 뭉쳐 끝없이 겹친다.
|
|
113
|
+
if (el.closest(`[${PLAN_ATTRIBUTE}]`))
|
|
114
|
+
return;
|
|
79
115
|
const done = handled.get(el);
|
|
80
|
-
// 넣어 둔
|
|
81
|
-
|
|
116
|
+
// 넣어 둔 그대로(비워 둔 글 노드 + 상자)면 볼 것이 없다.
|
|
117
|
+
// 바깥 코드(프레임워크)가 글을 다시 썼거나 옆에 다른 것을 끼웠으면 걷고 처음부터 다시 본다.
|
|
118
|
+
if (done && el.childNodes.length === 2 && el.firstChild?.nodeValue === "" && el.lastElementChild?.hasAttribute(PLAN_ATTRIBUTE))
|
|
82
119
|
return;
|
|
83
120
|
done?.undo();
|
|
84
121
|
handled.delete(el);
|
|
@@ -98,6 +135,11 @@ export function installPenguinLetters(options = {}) {
|
|
|
98
135
|
const size = parseFloat(getComputedStyle(el).fontSize);
|
|
99
136
|
if (!measure || measure(text, size).width <= measure(base, size).width)
|
|
100
137
|
return;
|
|
138
|
+
// 원문보다 넓어도, 길어진 만큼 아무것도 밀지 않으면 그대로 둔다(`always` 를 껐을 때).
|
|
139
|
+
if (!always && spacious.get(el) === text)
|
|
140
|
+
return;
|
|
141
|
+
if (!always && roomy(el, base))
|
|
142
|
+
return void spacious.set(el, text);
|
|
101
143
|
}
|
|
102
144
|
handled.set(el, { text, undo: penguinLetters(el, { ...rest, base, text }) });
|
|
103
145
|
};
|
|
@@ -118,10 +160,16 @@ export function installPenguinLetters(options = {}) {
|
|
|
118
160
|
const observer = new MutationObserver(() => {
|
|
119
161
|
frame ||= requestAnimationFrame(scan);
|
|
120
162
|
});
|
|
163
|
+
// 창이 좁아지면 넉넉하던 자리가 모자랄 수 있다 — 처음부터 다시 본다.
|
|
164
|
+
const resized = () => {
|
|
165
|
+
spacious = new WeakMap();
|
|
166
|
+
frame ||= requestAnimationFrame(scan);
|
|
167
|
+
};
|
|
121
168
|
const boot = () => {
|
|
122
169
|
if (stopped)
|
|
123
170
|
return;
|
|
124
171
|
scan();
|
|
172
|
+
window.addEventListener("resize", resized);
|
|
125
173
|
observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: [ATTRIBUTE] });
|
|
126
174
|
};
|
|
127
175
|
let stopped = false;
|
|
@@ -137,6 +185,7 @@ export function installPenguinLetters(options = {}) {
|
|
|
137
185
|
if (stop === mine)
|
|
138
186
|
stop = null;
|
|
139
187
|
observer.disconnect();
|
|
188
|
+
window.removeEventListener("resize", resized);
|
|
140
189
|
cancelAnimationFrame(frame);
|
|
141
190
|
for (const { undo } of handled.values())
|
|
142
191
|
undo();
|
package/dist/esm/letters.js
CHANGED
|
@@ -15,7 +15,37 @@ import { plan } from "./plan.js";
|
|
|
15
15
|
export const PLAN_ATTRIBUTE = "data-penguin-plan";
|
|
16
16
|
/** 화면에는 안 보이고 낭독기는 읽는다. */
|
|
17
17
|
const SPOKEN = "position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";
|
|
18
|
-
const CELL = "display:flex;flex-direction:column;justify-content:center;
|
|
18
|
+
const CELL = "display:flex;flex-direction:column;justify-content:center;min-width:0";
|
|
19
|
+
/** 글 정렬(왼쪽 · 가운데 · 오른쪽)마다 조각을 놓는 자리와, 좁힐 때 기준이 되는 쪽. */
|
|
20
|
+
const SIDES = { left: ["flex-start", "left"], center: ["center", "center"], right: ["flex-end", "right"] };
|
|
21
|
+
/**
|
|
22
|
+
* 원문보다 좁은 조각을 원문 자리의 어느 쪽에 붙일지.
|
|
23
|
+
* 요소가 글보다 넓거나(제목), 여백이 있는 상자거나(버튼), 문장 속에 끼어 있으면(링크) 글 정렬(`text-align`)을 따른다.
|
|
24
|
+
* 글에 딱 맞는 꾸밈 없는 요소(버튼 안의 `span`)는 글 정렬로 알 수 없다 — 그 요소를 놓는 것은 바깥의 flex 다.
|
|
25
|
+
* 그때는 놓인 자리를 본다: 같은 줄의 이웃이나 부모의 안쪽 끝 가운데 더 가까운 쪽에 붙어 있다고 친다(양쪽이 같으면 가운데).
|
|
26
|
+
*/
|
|
27
|
+
function sideOf(el, box) {
|
|
28
|
+
const style = getComputedStyle(el);
|
|
29
|
+
const padding = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
|
|
30
|
+
const mine = el.getBoundingClientRect();
|
|
31
|
+
const parent = el.parentElement;
|
|
32
|
+
const inText = [...(parent?.childNodes ?? [])].some((node) => node.nodeType === Node.TEXT_NODE && node.nodeValue?.trim());
|
|
33
|
+
if (!parent || inText || padding > 0 || mine.width - box.getBoundingClientRect().width > 1) {
|
|
34
|
+
const rtl = style.direction === "rtl";
|
|
35
|
+
const toRight = style.textAlign === "right" || style.textAlign === (rtl ? "start" : "end") || (rtl && style.textAlign === "justify");
|
|
36
|
+
return style.textAlign === "center" ? "center" : toRight ? "right" : "left";
|
|
37
|
+
}
|
|
38
|
+
const around = parent.getBoundingClientRect();
|
|
39
|
+
const outer = getComputedStyle(parent);
|
|
40
|
+
/** 같은 줄에 놓인 이웃의 자리 — 없거나 다른 줄이면 null. */
|
|
41
|
+
const beside = (item) => {
|
|
42
|
+
const place = item?.getBoundingClientRect();
|
|
43
|
+
return place && place.width > 0 && place.bottom > mine.top && place.top < mine.bottom ? place : null;
|
|
44
|
+
};
|
|
45
|
+
const left = mine.left - (beside(el.previousElementSibling)?.right ?? around.left + parseFloat(outer.borderLeftWidth) + parseFloat(outer.paddingLeft));
|
|
46
|
+
const right = (beside(el.nextElementSibling)?.left ?? around.right - parseFloat(outer.borderRightWidth) - parseFloat(outer.paddingRight)) - mine.right;
|
|
47
|
+
return Math.abs(left - right) <= 2 ? "center" : left < right ? "left" : "right";
|
|
48
|
+
}
|
|
19
49
|
/** 같은 요소에 다시 부르면 앞의 것을 먼저 걷는다. */
|
|
20
50
|
const undos = new WeakMap();
|
|
21
51
|
let ctx = null;
|
|
@@ -51,6 +81,10 @@ export function penguinLetters(el, options) {
|
|
|
51
81
|
undos.get(el)?.();
|
|
52
82
|
const { base, text, uppercase = true, debug = false, ...rest } = options;
|
|
53
83
|
const before = [...el.childNodes];
|
|
84
|
+
// 글만 든 요소면 그 글 노드를 떼지 않고 비워만 둔다 — 프레임워크(React)가 그 노드를 쥐고 있어,
|
|
85
|
+
// 떼어 내면 나중에 그 앞에 다른 것을 끼우거나 그 노드를 지울 때 「자식이 아니다」 로 화면이 죽는다.
|
|
86
|
+
const kept = before.length === 1 && before[0].nodeType === Node.TEXT_NODE ? before[0] : null;
|
|
87
|
+
const original = kept?.data ?? "";
|
|
54
88
|
const make = (css, content = "") => {
|
|
55
89
|
const node = document.createElement("span");
|
|
56
90
|
node.style.cssText = css;
|
|
@@ -63,7 +97,12 @@ export function penguinLetters(el, options) {
|
|
|
63
97
|
ghost.setAttribute("aria-hidden", "true");
|
|
64
98
|
stage.setAttribute("aria-hidden", "true");
|
|
65
99
|
box.append(ghost, make(SPOKEN, text), stage);
|
|
66
|
-
|
|
100
|
+
if (kept) {
|
|
101
|
+
kept.data = "";
|
|
102
|
+
el.append(box);
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
el.replaceChildren(box);
|
|
67
106
|
const draw = () => {
|
|
68
107
|
const fontSize = parseFloat(getComputedStyle(ghost).fontSize);
|
|
69
108
|
const canvas = measurer(ghost);
|
|
@@ -73,15 +112,27 @@ export function penguinLetters(el, options) {
|
|
|
73
112
|
const measure = (content, size) => content === base && size === fontSize ? { ...canvas(content, size), width: ghost.getBoundingClientRect().width } : canvas(content, size);
|
|
74
113
|
const shown = uppercase ? upper(text, el.closest("[lang]")?.lang) : text;
|
|
75
114
|
const { cols, rows, size, squeeze, pitch, cells } = plan(base, shown, fontSize, measure, rest);
|
|
115
|
+
// 칸으로 나눴으면 칸 가운데에 둔다(칸이 원문 글자 자리다). 칸이 없으면 요소의 정렬을 따른다 —
|
|
116
|
+
// 왼쪽 정렬된 제목에서 원문보다 좁게 쌓인 줄이 가운데로 가면, 위아래 글과 줄 머리가 어긋난다.
|
|
117
|
+
const [place, origin] = SIDES[cols > 1 ? "center" : sideOf(el, box)];
|
|
76
118
|
// ponytail: 조각 더미를 글자 상자 가운데에 둔다 — 획의 가운데와 조금 어긋날 수 있다. 눈에 띄면 기준선을 재서 획 끝에 맞춘다.
|
|
77
119
|
stage.style.cssText = `position:absolute;inset:0;display:grid;grid-template-columns:repeat(${cols},minmax(0,1fr));font-size:${size}px;line-height:${pitch};letter-spacing:normal`;
|
|
78
120
|
stage.replaceChildren(...cells.map((lines) => {
|
|
79
|
-
const cell = make(
|
|
121
|
+
const cell = make(`${CELL};align-items:${place}${debug ? ";outline:1px dashed" : ""}`);
|
|
80
122
|
// 자간은 마지막 글자 뒤에도 붙는다 — 그만큼 당겨 가운데를 맞춘다.
|
|
81
|
-
cell.append(...lines.map((line) => make(`white-space:nowrap;transform:scaleX(${squeeze});letter-spacing:${line.spacing}px;margin-right:${-line.spacing}px`, line.text)));
|
|
123
|
+
cell.append(...lines.map((line) => make(`white-space:nowrap;transform:scaleX(${squeeze});transform-origin:${origin} center;letter-spacing:${line.spacing}px;margin-right:${-line.spacing}px`, line.text)));
|
|
82
124
|
return cell;
|
|
83
125
|
}));
|
|
84
|
-
|
|
126
|
+
// 캔버스로 잰 폭과 화면에 놓인 폭이 조금 다른 브라우저가 있다 — 아주 가늘게 좁힐 때 그 차이로 1px 가까이 넘친다.
|
|
127
|
+
// 놓인 폭을 재서, 넘치면 그만큼 더 좁힌다.
|
|
128
|
+
const lines = [...stage.querySelectorAll(":scope > * > *")];
|
|
129
|
+
const room = stage.getBoundingClientRect().width / cols;
|
|
130
|
+
const widest = Math.max(0, ...lines.map((line) => line.getBoundingClientRect().width + parseFloat(line.style.marginRight) * squeeze));
|
|
131
|
+
const tight = widest > room ? (squeeze * room) / widest : squeeze;
|
|
132
|
+
if (tight < squeeze)
|
|
133
|
+
for (const line of lines)
|
|
134
|
+
line.style.transform = `scaleX(${tight})`;
|
|
135
|
+
box.setAttribute(PLAN_ATTRIBUTE, `${cols}x${rows} ${Math.round(size * 10) / 10}px ${tight.toFixed(2)}`);
|
|
85
136
|
};
|
|
86
137
|
draw();
|
|
87
138
|
// 글자 크기가 바뀌거나 글꼴이 늦게 실리면 기준 글의 자리가 달라진다 — 조각은 자리 위에 띄워 둬서, 다시 그려도 자리는 안 바뀐다.
|
|
@@ -95,9 +146,15 @@ export function penguinLetters(el, options) {
|
|
|
95
146
|
undos.delete(el);
|
|
96
147
|
observer?.disconnect();
|
|
97
148
|
document.fonts?.removeEventListener("loadingdone", draw);
|
|
98
|
-
// 바깥 코드가 그사이 내용을 바꿨으면 그대로 둔다.
|
|
99
|
-
if (box.parentNode
|
|
100
|
-
|
|
149
|
+
// 바깥 코드가 그사이 내용을 통째로 바꿨으면 그대로 둔다.
|
|
150
|
+
if (box.parentNode !== el)
|
|
151
|
+
return;
|
|
152
|
+
if (!kept)
|
|
153
|
+
return el.replaceChildren(...before);
|
|
154
|
+
box.remove();
|
|
155
|
+
// 비워 둔 글 노드에 바깥 코드가 새 글을 써 넣었으면 그 글을 둔다.
|
|
156
|
+
if (kept.data === "")
|
|
157
|
+
kept.data = original;
|
|
101
158
|
};
|
|
102
159
|
undos.set(el, undo);
|
|
103
160
|
return undo;
|
package/dist/esm/plan.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export type Measure = (text: string, size: number) => {
|
|
|
12
12
|
export interface PlanOptions {
|
|
13
13
|
/** 줄 수. 주지 않으면 글자가 가장 크게 나오는 줄 수를 고른다. */
|
|
14
14
|
rows?: number;
|
|
15
|
-
/**
|
|
15
|
+
/** 쌓을 수 있는 줄 수의 한도. 기본은 1 — 한 줄로만 좁힌다. 2 · 3 을 주면 한 줄로 너무 가늘어질 때 그만큼까지 줄을 쌓는다. */
|
|
16
16
|
maxRows?: number;
|
|
17
17
|
/** 가로로 좁히는 한도 — 줄 수를 고를 때 쓴다(이보다 더 좁혀야 하는 줄 수는 밀린다). `fill` 을 끄면 이보다 더 좁히지 않고 글자 크기를 줄인다. */
|
|
18
18
|
squeeze?: number;
|
|
@@ -46,6 +46,7 @@ export interface Plan {
|
|
|
46
46
|
}
|
|
47
47
|
/**
|
|
48
48
|
* `base`(기준 글)를 `fontSize` 로 그린 자리에 `text`(넣을 글)를 넣는 배치를 돌려준다.
|
|
49
|
-
* 줄 수를 주지 않으면 한 줄부터 한도까지
|
|
49
|
+
* 줄 수를 주지 않으면 한 줄부터 한도까지 해 보고, 장평이 한도 밑으로 내려가지 않는 가장 적은 줄 수를 고른다 — 한 줄로 가늘어지느니 줄을 쌓는다.
|
|
50
|
+
* 높이를 채우지 않을 때(`fill: false`)는 글자가 가장 크게 나오는 줄 수를 고른다.
|
|
50
51
|
*/
|
|
51
52
|
export declare function plan(base: string, text: string, fontSize: number, measure: Measure, options?: PlanOptions): Plan;
|
package/dist/esm/plan.js
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* 기준 글의 한 글자가 한 칸이다. 넣을 글을 줄과 칸으로 나누고, 글자 크기와 장평(가로로 좁히는 비율)을 낱말 전체에 하나씩 정한다.
|
|
4
4
|
* 글자 폭과 획 높이는 받은 `measure` 로 잰다 — 브라우저에서는 캔버스로, 테스트에서는 가짜로.
|
|
5
5
|
*/
|
|
6
|
-
const DEFAULTS = { maxRows:
|
|
7
|
-
/** 칸마다 이 글자
|
|
6
|
+
const DEFAULTS = { maxRows: 1, squeeze: 0.5, fill: true, cellGap: 0, lineGap: 0.08, spread: 0.08, down: false };
|
|
7
|
+
/** 칸마다 이 글자 수를 넘어야 칸으로 나눈다 — 그보다 적으면 조각이 한두 글자뿐이라, 칸 없이 줄로만 쌓는다(확인 · CON / FIRM). */
|
|
8
8
|
const ONE_LINE = 4;
|
|
9
9
|
const segmenter = new Intl.Segmenter();
|
|
10
10
|
/** 눈에 보이는 글자 단위로 나눈다 — 부호가 따로 붙은 글자나 이모지를 가운데서 자르지 않는다. */
|
|
@@ -37,10 +37,12 @@ function cut(items, sizes) {
|
|
|
37
37
|
function layout(base, chars, fontSize, wanted, measure, o) {
|
|
38
38
|
const whole = measure(base, fontSize);
|
|
39
39
|
const letters = Math.max(1, graphemes(base).length);
|
|
40
|
-
|
|
41
|
-
const
|
|
40
|
+
const perCell = Math.ceil(chars.length / letters);
|
|
41
|
+
const celled = perCell > ONE_LINE;
|
|
42
|
+
// 줄 수는 모든 칸이 같다 — 한 줄에 놓을 글자가 하나는 있어야 한다.
|
|
43
|
+
const rows = Math.max(1, Math.min(wanted, celled ? perCell : chars.length));
|
|
42
44
|
// 한 줄이면 칸으로 나누지 않는다 — 나누면 낱말 가운데에 띄어쓰기 같은 틈만 생긴다.
|
|
43
|
-
const cols = rows === 1 ? 1 : letters;
|
|
45
|
+
const cols = rows === 1 || !celled ? 1 : letters;
|
|
44
46
|
const gap = cols === 1 ? 0 : o.cellGap;
|
|
45
47
|
const order = [...Array(cols).keys()];
|
|
46
48
|
// ponytail: 글자 수로 자른다(띄어쓰기도 글자 하나) — 낱말 사이·음절 자리에서 자르려면 자를 자리 후보를 받아 고르게 바꾼다.
|
|
@@ -82,7 +84,8 @@ function layout(base, chars, fontSize, wanted, measure, o) {
|
|
|
82
84
|
}
|
|
83
85
|
/**
|
|
84
86
|
* `base`(기준 글)를 `fontSize` 로 그린 자리에 `text`(넣을 글)를 넣는 배치를 돌려준다.
|
|
85
|
-
* 줄 수를 주지 않으면 한 줄부터 한도까지
|
|
87
|
+
* 줄 수를 주지 않으면 한 줄부터 한도까지 해 보고, 장평이 한도 밑으로 내려가지 않는 가장 적은 줄 수를 고른다 — 한 줄로 가늘어지느니 줄을 쌓는다.
|
|
88
|
+
* 높이를 채우지 않을 때(`fill: false`)는 글자가 가장 크게 나오는 줄 수를 고른다.
|
|
86
89
|
*/
|
|
87
90
|
export function plan(base, text, fontSize, measure, options = {}) {
|
|
88
91
|
const o = { ...DEFAULTS, ...options };
|
|
@@ -91,12 +94,9 @@ export function plan(base, text, fontSize, measure, options = {}) {
|
|
|
91
94
|
return { width: measure(base, fontSize).width, cols: 1, rows: 1, size: fontSize, squeeze: 1, pitch: 1, cells: [] };
|
|
92
95
|
if (options.rows)
|
|
93
96
|
return layout(base, chars, fontSize, options.rows, measure, o);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
best = next;
|
|
100
|
-
}
|
|
101
|
-
return best;
|
|
97
|
+
// 글자 수보다 많은 줄은 못 쌓는다 — 줄 수가 깎인 것은 앞의 것과 같으니 뺀다.
|
|
98
|
+
const tries = Array.from({ length: Math.max(1, o.maxRows) }, (_, i) => layout(base, chars, fontSize, i + 1, measure, o)).filter((tried, i) => tried.rows === i + 1);
|
|
99
|
+
if (!o.fill)
|
|
100
|
+
return tries.reduce((best, next) => (next.score > best.score + 0.01 ? next : best));
|
|
101
|
+
return tries.find((tried) => tried.squeeze >= o.squeeze - 1e-9) ?? tries.reduce((best, next) => (next.squeeze > best.squeeze ? next : best));
|
|
102
102
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "plz-penguin-letters",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Huddle up plz, penguin letters. Keeps your layout intact, however long the translation gets.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"i18n",
|
|
@@ -46,7 +46,8 @@
|
|
|
46
46
|
"./package.json": "./package.json"
|
|
47
47
|
},
|
|
48
48
|
"files": [
|
|
49
|
-
"dist"
|
|
49
|
+
"dist",
|
|
50
|
+
"CHANGELOG.md"
|
|
50
51
|
],
|
|
51
52
|
"main": "./dist/cjs/index.js",
|
|
52
53
|
"module": "./dist/esm/index.js",
|