plz-penguin-letters 0.2.0 → 0.3.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 CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  Changes that affect people using the library. The newest version is at the top.
4
4
 
5
+ ## 0.3.0 - 2026-12-04
6
+
7
+ ### Added
8
+
9
+ - **Messages with values in them.** A message like `{count} items` never matched, because the screen says `3 items`. The library now reads the value off the screen and puts it into the original (`{count}개` → `3개`). Only plain `{name}` slots are handled: plural and select messages (`{count, plural, …}`) and rich-text tags (`<b>`) are still skipped, and can be marked with the `data-penguin-letters` attribute instead.
10
+
11
+ ### Changed
12
+
13
+ - **It only looks at what changed.** Every change anywhere on the page used to trigger a search of the whole document on the next frame, so a page with text streaming in (a chat answer, a log) searched everything up to 60 times a second. It now checks only the elements that changed and what is inside them, and does nothing at all for changes inside an `exclude`d area.
14
+
5
15
  ## 0.2.0 - 2026-12-03
6
16
 
7
17
  ### Fixed
package/README.ko.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  <div align="center">
4
4
 
5
- <img src="./docs/penguin-letters.png" width="340" alt="거친 낙서 두 장. 위: SAVE 때문에 늘어난 버튼이 옆 버튼을 화면 밖으로 밀어 테두리가 찢어졌다. 아래: 같은 화면이 멀쩡하고, SAVE 가 두 줄로 쌓여 다른 버튼과 같은 크기의 버튼 안에 들어가 있다." />
5
+ <img src="./docs/penguin-pair.png" width="560" alt="거친 낙서 네 장이 두 줄로 놓였다. 왼쪽은 글자: SAVE 때문에 늘어난 버튼이 옆 버튼을 화면 밖으로 밀어 테두리가 찢어졌고, 아래는 같은 화면이 멀쩡하며 SAVE 가 두 줄로 쌓여 원래 크기의 버튼 안에 들어가 있다. 오른쪽은 같은 두 장면인데 글자 대신 펭귄 네 마리다: 한 줄로 서면 화면이 찢어지고, 머리를 맞대고 뭉치면 들어간다." />
6
6
 
7
7
  </div>
8
8
 
9
- <p align="center"><sub>뭉치기 전, 그리고 후.</sub></p>
9
+ <p align="center"><sub>뭉치기 전, 그리고 후. 왼쪽은 글자들, 오른쪽은 글자들의 속마음.</sub></p>
10
10
 
11
11
  <h1 align="center">Huddle up plz, penguin letters.</h1>
12
12
 
@@ -130,6 +130,8 @@ installPenguinLetters({ base: ko, text: fr });
130
130
 
131
131
  언어가 바뀌면 새 파일로 다시 부른다. 앞의 설치는 제 손으로 치우고 나간다.
132
132
 
133
+ 값이 끼어드는 문구도 된다. 화면에 `12 éléments sélectionnés`가 보이고 번역 파일에 `{count} éléments sélectionnés`와 `{count}개 선택`이 있으면, 화면에서 `12`를 읽어 `12개 선택`을 자리로 쓴다.
134
+
133
135
  ### 2. 짝 직접 주기
134
136
 
135
137
  번역 파일이 없으면 짝을 직접 넘긴다. 왼쪽이 화면에 보이는 글, 오른쪽이 원문이다.
@@ -257,7 +259,7 @@ installPenguinLetters({ base: ko, text: fr, include: "button, a, h1, h2, h3, spa
257
259
 
258
260
  - 원문보다 넓지 않은 번역(`확인` → `OK`). 짧은 펭귄은 자유롭게 다닌다.
259
261
  - 글 말고 다른 것이 같이 든 요소(라벨 옆의 아이콘, 문장 속 링크). 얘도 뭉치게 하고 싶으면 라벨을 `<span>`으로 감싸고 `include`에 `span`을 넣는다.
260
- - 값이 끼어든 글(`{count}개`). 화면의 글이 번역 파일의 글과 달라진다.
262
+ - 복수형·선택·서식이 든 문구(`{count, plural, …}`, `<b>{name}</b>`). 어느 갈래가 화면에 나왔는지 알 수 없으니, 이런 것은 속성으로 표시한다.
261
263
  - `include` 밖의 요소와 `exclude` 안의 요소.
262
264
  - 서로 다른 원문 두 개에 걸리는 글(`Fermer`가 `닫기`이기도 `종료`이기도 할 때). 찍을 수는 없으니, 이런 것은 속성으로 표시한다.
263
265
 
@@ -282,7 +284,7 @@ installPenguinLetters({ base: ko, text: fr, include: "button, a, h1, h2, h3, spa
282
284
  아이디어는 장난스럽다. 구현은 장난이 아니다.
283
285
 
284
286
  - **프레임워크와 싸우지 않는다.** 원래 글 노드를 화면에서 떼지 않는다. 그래서 React가 그 글을 고치고, 그 옆에 끼우고, 지워도 터지지 않는다. 글이 바뀌면 다시 뭉친다.
285
- - **변화를 따라간다.** 나중에 생긴 요소도 처리하고, 요소 크기가 바뀌거나 웹 폰트가 다 읽히면 다시 계산한다.
287
+ - **변화를 따라가되, 바뀐 자리만 본다.** 나중에 생긴 요소도 처리하고, 요소 크기가 바뀌거나 웹 폰트가 다 읽히면 다시 계산한다. 무언가 바뀌면 그 자리만 다시 보니, 채팅에 글이 흘러나와도 문서 전체를 훑지 않는다. 그런 영역을 `exclude`에 넣으면 거기서는 아예 일하지 않는다.
286
288
  - **낭독기**는 번역을 평범한 낱말 하나로 읽는다. 조각은 낭독기에 숨긴다.
287
289
  - **서버 렌더링**: `document`가 없는 곳에서 부르면 아무것도 하지 않는다.
288
290
  - **테스트**: Chromium, Firefox, WebKit에서 돌린다. `Intl.Segmenter`가 필요하다.
package/README.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  <div align="center">
4
4
 
5
- <img src="./docs/penguin-letters.png" width="340" alt="Two rough sketches. Top: a button stretched by the word SAVE shoves its neighbour through the edge of the screen, tearing it. Bottom: the same screen intact, with SAVE stacked in two rows inside a button the same size as the others." />
5
+ <img src="./docs/penguin-pair.png" width="560" alt="Four rough sketches in two columns. Left, with letters: a button stretched by the word SAVE shoves its neighbour through the edge of the screen, tearing it; below, the same screen intact with SAVE stacked in two rows inside a button of the original size. Right, the same two scenes with four penguins instead of letters: standing in a row they tear the screen, huddled head to head they fit." />
6
6
 
7
7
  </div>
8
8
 
9
- <p align="center"><sub>Before the huddle, and after.</sub></p>
9
+ <p align="center"><sub>Before the huddle, and after. Left: the letters. Right: what they are thinking.</sub></p>
10
10
 
11
11
  <h1 align="center">Huddle up plz, penguin letters.</h1>
12
12
 
@@ -130,6 +130,8 @@ The two files are matched by key (nested keys are fine). When a button shows `En
130
130
 
131
131
  When the language changes, call it again with the new file. The previous install cleans up after itself.
132
132
 
133
+ Messages with values in them work too. If the screen says `12 éléments sélectionnés`, the files say `{count} éléments sélectionnés` and `{count} selected`, it reads the `12` off the screen and uses `12 selected` as the footprint.
134
+
133
135
  ### 2. Pairs
134
136
 
135
137
  No translation files? Hand over the pairs yourself — shown text on the left, original on the right.
@@ -257,7 +259,7 @@ The wider the selector, the more gets huddled. `p` and `div` will catch whole se
257
259
 
258
260
  - A translation that is not wider than the original (`Cancel` → `Hủy`). Short penguins roam free.
259
261
  - 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.
262
+ - Plural, select and rich-text messages (`{count, plural, …}`, `<b>{name}</b>`). It can't work out which branch is on screen; mark those with the attribute.
261
263
  - Anything outside `include`, and anything inside `exclude`.
262
264
  - A text that maps to two different originals (`Fermer` for both `Close` and `Quit`). It can't guess; mark those with the attribute.
263
265
 
@@ -282,7 +284,7 @@ That is cells × rows, the font size, and the narrowing ratio.
282
284
  The idea is playful. The implementation is not kidding.
283
285
 
284
286
  - **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.
287
+ - **It follows changes, and only the changes.** Elements added later are picked up, and a huddle is recalculated when its element is resized or a web font finishes loading. When something changes it looks at that spot only, so text streaming into a chat does not make it search the whole page. Put such areas in `exclude` and it does nothing for them at all.
286
288
  - **Screen readers** get the translation as one normal word. The pieces are hidden from them.
287
289
  - **Server rendering**: calling it where there is no `document` does nothing.
288
290
  - **Tested** on Chromium, Firefox and WebKit. Needs `Intl.Segmenter`.
@@ -28,13 +28,28 @@ function flatten(dictionary, prefix = "", out = new Map()) {
28
28
  }
29
29
  return out;
30
30
  }
31
- /** 「넣을 글 → 원문」 사전. 같은 글이 서로 다른 원문에 걸리면 어느 쪽인지 알 수 없다 — null 로 두고 건너뛴다. */
31
+ /** 값이 끼어드는 자리 — `{count}` 처럼 이름만 든 것. */
32
+ const SLOT = /\{(\w+)\}/g;
33
+ /** 이름만 든 자리 말고는 중괄호·태그가 없는가 — 복수형·선택(`{count, plural, …}`)이나 서식 태그(`<b>`)가 든 문구는 풀지 못한다. */
34
+ const simple = (message) => !/[{}<]/.test(message.replace(SLOT, ""));
35
+ /**
36
+ * 「넣을 글 → 원문」 을 찾는 함수. 같은 글이 서로 다른 원문에 걸리면 어느 쪽인지 알 수 없다 — null 을 돌려주고 건너뛴다.
37
+ * 값이 끼어드는 문구(`{count} items`)는 화면의 글(`3 items`)에서 값을 읽어, 원문의 같은 이름 자리에 넣는다(`{count}개` → `3개`).
38
+ */
32
39
  function pairsOf({ base, text, pairs }) {
33
40
  const bases = new Map();
34
- const add = (shown, origin) => {
41
+ const shapes = [];
42
+ const add = (shown, origin, wins = false) => {
35
43
  if (shown === origin)
36
44
  return;
37
- bases.set(shown, bases.has(shown) && bases.get(shown) !== origin ? null : origin);
45
+ if (!shown.includes("{"))
46
+ return void bases.set(shown, !wins && bases.has(shown) && bases.get(shown) !== origin ? null : origin);
47
+ const names = [...shown.matchAll(SLOT)].map((slot) => slot[1]);
48
+ // 글자가 하나도 없는 문구(`{name}`)는 무엇에나 맞아 버린다 — 뺀다.
49
+ if (names.length === 0 || !simple(shown) || !simple(origin) || !shown.replace(SLOT, "").trim())
50
+ return;
51
+ const parts = shown.split(SLOT).map((part, i) => (i % 2 ? "(.+?)" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
52
+ shapes.push({ shape: new RegExp(`^${parts.join("")}$`), names, origin });
38
53
  };
39
54
  if (base && text) {
40
55
  const origins = flatten(base);
@@ -46,8 +61,32 @@ function pairsOf({ base, text, pairs }) {
46
61
  }
47
62
  // 직접 준 짝이 번역 파일을 이긴다.
48
63
  for (const [shown, origin] of Object.entries(pairs ?? {}))
49
- bases.set(shown.trim(), origin.trim());
50
- return bases;
64
+ add(shown.trim(), origin.trim(), true);
65
+ /** 값이 든 문구로 푼 결과 — 화면이 바뀔 때마다 같은 글을 다시 맞춰 보지 않는다. */
66
+ const solved = new Map();
67
+ return (shown) => {
68
+ if (bases.has(shown))
69
+ return bases.get(shown);
70
+ if (shapes.length === 0)
71
+ return undefined;
72
+ if (!solved.has(shown)) {
73
+ // ponytail: 값이 든 문구를 차례로 다 맞춰 본다 — 그런 문구가 수천이면 앞머리 글자로 묶어 줄인다.
74
+ const found = new Set();
75
+ for (const { shape, names, origin } of shapes) {
76
+ const match = shape.exec(shown);
77
+ if (!match)
78
+ continue;
79
+ const values = new Map(names.map((name, i) => [name, match[i + 1]]));
80
+ // 원문에만 있는 자리는 채울 값이 없다.
81
+ if ([...origin.matchAll(SLOT)].every((slot) => values.has(slot[1])))
82
+ found.add(origin.replace(SLOT, (_, name) => values.get(name) ?? ""));
83
+ }
84
+ if (solved.size > 2000)
85
+ solved.clear();
86
+ solved.set(shown, found.size === 1 ? [...found][0] : found.size > 1 ? null : undefined);
87
+ }
88
+ return solved.get(shown);
89
+ };
51
90
  }
52
91
  /** 틀린 선택자는 없는 것으로 친다 — 선택자 오타 하나로 화면 전체가 죽지 않게. */
53
92
  function validSelector(selector) {
@@ -104,7 +143,7 @@ function installPenguinLetters(options = {}) {
104
143
  return () => { };
105
144
  stop?.();
106
145
  const { base: _base, text: _text, pairs: _pairs, include, exclude, always = true, ...rest } = options;
107
- const bases = pairsOf(options);
146
+ const baseOf = pairsOf(options);
108
147
  const wanted = validSelector(include) || INCLUDE;
109
148
  const skipped = validSelector(exclude);
110
149
  /** 맡은 요소 — 그때 넣은 글과 걷는 함수. */
@@ -129,7 +168,7 @@ function installPenguinLetters(options = {}) {
129
168
  return;
130
169
  const text = (el.textContent ?? "").trim();
131
170
  const marked = el.getAttribute(ATTRIBUTE)?.trim();
132
- const base = marked || (el.matches(wanted) ? bases.get(text) : undefined);
171
+ const base = marked || (el.matches(wanted) ? baseOf(text) : undefined);
133
172
  if (!base || !text || base === text)
134
173
  return;
135
174
  if (!marked) {
@@ -146,7 +185,12 @@ function installPenguinLetters(options = {}) {
146
185
  }
147
186
  handled.set(el, { text, undo: (0, letters_ts_1.penguinLetters)(el, { ...rest, base, text }) });
148
187
  };
149
- // ponytail: 화면이 바뀔 때마다 문서 전체에서 선택자로 다시 찾는다(한 프레임에 한 번) — 느려지면 바뀐 자리만 본다.
188
+ const candidates = `[${ATTRIBUTE}], ${wanted}`;
189
+ /** 바뀐 자리들 — 다음 프레임에 그 요소와 안쪽만 다시 본다. `everything` 이면 문서 전체를 본다(처음 · 창 크기가 바뀐 뒤). */
190
+ const dirty = new Set();
191
+ let everything = true;
192
+ /** 바뀐 자리가 이보다 많으면 하나씩 보느니 문서 전체를 한 번 훑는다. */
193
+ const MANY = 50;
150
194
  const scan = () => {
151
195
  frame = 0;
152
196
  for (const el of handled.keys()) {
@@ -155,17 +199,35 @@ function installPenguinLetters(options = {}) {
155
199
  handled.get(el)?.undo();
156
200
  handled.delete(el);
157
201
  }
158
- for (const el of document.querySelectorAll(`[${ATTRIBUTE}], ${wanted}`))
159
- visit(el);
202
+ const roots = everything || dirty.size > MANY ? [document.body] : [...dirty];
203
+ everything = false;
204
+ dirty.clear();
205
+ for (const root of roots) {
206
+ // 화면에서 빠졌거나 제외한 영역 안이면 볼 것이 없다 — 채팅처럼 글이 계속 흘러나오는 영역을 `exclude` 로 빼면 거기서는 일하지 않는다.
207
+ if (!root.isConnected || (skipped && root.closest(skipped)))
208
+ continue;
209
+ if (root instanceof HTMLElement && root.matches(candidates))
210
+ visit(root);
211
+ for (const el of root.querySelectorAll(candidates))
212
+ visit(el);
213
+ }
160
214
  };
161
215
  let frame = 0;
162
- // 넣으면서 바꾼 것도 변화로 잡히지만, 다시 찾아도 이미 맡은 요소는 건너뛰어 되풀이되지 않는다.
163
- const observer = new MutationObserver(() => {
164
- frame ||= requestAnimationFrame(scan);
216
+ // 넣으면서 바꾼 것도 변화로 잡히지만, 다시 봐도 이미 맡은 요소는 건너뛰어 되풀이되지 않는다.
217
+ const observer = new MutationObserver((records) => {
218
+ for (const record of records) {
219
+ const target = record.target instanceof Element ? record.target : record.target.parentElement;
220
+ // 넣어 둔 상자 속에서 생긴 변화는 우리가 그린 것이다.
221
+ if (target && !target.closest(`[${letters_ts_1.PLAN_ATTRIBUTE}]`))
222
+ dirty.add(target);
223
+ }
224
+ if (dirty.size > 0)
225
+ frame ||= requestAnimationFrame(scan);
165
226
  });
166
227
  // 창이 좁아지면 넉넉하던 자리가 모자랄 수 있다 — 처음부터 다시 본다.
167
228
  const resized = () => {
168
229
  spacious = new WeakMap();
230
+ everything = true;
169
231
  frame ||= requestAnimationFrame(scan);
170
232
  };
171
233
  const boot = () => {
@@ -25,13 +25,28 @@ function flatten(dictionary, prefix = "", out = new Map()) {
25
25
  }
26
26
  return out;
27
27
  }
28
- /** 「넣을 글 → 원문」 사전. 같은 글이 서로 다른 원문에 걸리면 어느 쪽인지 알 수 없다 — null 로 두고 건너뛴다. */
28
+ /** 값이 끼어드는 자리 — `{count}` 처럼 이름만 든 것. */
29
+ const SLOT = /\{(\w+)\}/g;
30
+ /** 이름만 든 자리 말고는 중괄호·태그가 없는가 — 복수형·선택(`{count, plural, …}`)이나 서식 태그(`<b>`)가 든 문구는 풀지 못한다. */
31
+ const simple = (message) => !/[{}<]/.test(message.replace(SLOT, ""));
32
+ /**
33
+ * 「넣을 글 → 원문」 을 찾는 함수. 같은 글이 서로 다른 원문에 걸리면 어느 쪽인지 알 수 없다 — null 을 돌려주고 건너뛴다.
34
+ * 값이 끼어드는 문구(`{count} items`)는 화면의 글(`3 items`)에서 값을 읽어, 원문의 같은 이름 자리에 넣는다(`{count}개` → `3개`).
35
+ */
29
36
  function pairsOf({ base, text, pairs }) {
30
37
  const bases = new Map();
31
- const add = (shown, origin) => {
38
+ const shapes = [];
39
+ const add = (shown, origin, wins = false) => {
32
40
  if (shown === origin)
33
41
  return;
34
- bases.set(shown, bases.has(shown) && bases.get(shown) !== origin ? null : origin);
42
+ if (!shown.includes("{"))
43
+ return void bases.set(shown, !wins && bases.has(shown) && bases.get(shown) !== origin ? null : origin);
44
+ const names = [...shown.matchAll(SLOT)].map((slot) => slot[1]);
45
+ // 글자가 하나도 없는 문구(`{name}`)는 무엇에나 맞아 버린다 — 뺀다.
46
+ if (names.length === 0 || !simple(shown) || !simple(origin) || !shown.replace(SLOT, "").trim())
47
+ return;
48
+ const parts = shown.split(SLOT).map((part, i) => (i % 2 ? "(.+?)" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
49
+ shapes.push({ shape: new RegExp(`^${parts.join("")}$`), names, origin });
35
50
  };
36
51
  if (base && text) {
37
52
  const origins = flatten(base);
@@ -43,8 +58,32 @@ function pairsOf({ base, text, pairs }) {
43
58
  }
44
59
  // 직접 준 짝이 번역 파일을 이긴다.
45
60
  for (const [shown, origin] of Object.entries(pairs ?? {}))
46
- bases.set(shown.trim(), origin.trim());
47
- return bases;
61
+ add(shown.trim(), origin.trim(), true);
62
+ /** 값이 든 문구로 푼 결과 — 화면이 바뀔 때마다 같은 글을 다시 맞춰 보지 않는다. */
63
+ const solved = new Map();
64
+ return (shown) => {
65
+ if (bases.has(shown))
66
+ return bases.get(shown);
67
+ if (shapes.length === 0)
68
+ return undefined;
69
+ if (!solved.has(shown)) {
70
+ // ponytail: 값이 든 문구를 차례로 다 맞춰 본다 — 그런 문구가 수천이면 앞머리 글자로 묶어 줄인다.
71
+ const found = new Set();
72
+ for (const { shape, names, origin } of shapes) {
73
+ const match = shape.exec(shown);
74
+ if (!match)
75
+ continue;
76
+ const values = new Map(names.map((name, i) => [name, match[i + 1]]));
77
+ // 원문에만 있는 자리는 채울 값이 없다.
78
+ if ([...origin.matchAll(SLOT)].every((slot) => values.has(slot[1])))
79
+ found.add(origin.replace(SLOT, (_, name) => values.get(name) ?? ""));
80
+ }
81
+ if (solved.size > 2000)
82
+ solved.clear();
83
+ solved.set(shown, found.size === 1 ? [...found][0] : found.size > 1 ? null : undefined);
84
+ }
85
+ return solved.get(shown);
86
+ };
48
87
  }
49
88
  /** 틀린 선택자는 없는 것으로 친다 — 선택자 오타 하나로 화면 전체가 죽지 않게. */
50
89
  function validSelector(selector) {
@@ -101,7 +140,7 @@ export function installPenguinLetters(options = {}) {
101
140
  return () => { };
102
141
  stop?.();
103
142
  const { base: _base, text: _text, pairs: _pairs, include, exclude, always = true, ...rest } = options;
104
- const bases = pairsOf(options);
143
+ const baseOf = pairsOf(options);
105
144
  const wanted = validSelector(include) || INCLUDE;
106
145
  const skipped = validSelector(exclude);
107
146
  /** 맡은 요소 — 그때 넣은 글과 걷는 함수. */
@@ -126,7 +165,7 @@ export function installPenguinLetters(options = {}) {
126
165
  return;
127
166
  const text = (el.textContent ?? "").trim();
128
167
  const marked = el.getAttribute(ATTRIBUTE)?.trim();
129
- const base = marked || (el.matches(wanted) ? bases.get(text) : undefined);
168
+ const base = marked || (el.matches(wanted) ? baseOf(text) : undefined);
130
169
  if (!base || !text || base === text)
131
170
  return;
132
171
  if (!marked) {
@@ -143,7 +182,12 @@ export function installPenguinLetters(options = {}) {
143
182
  }
144
183
  handled.set(el, { text, undo: penguinLetters(el, { ...rest, base, text }) });
145
184
  };
146
- // ponytail: 화면이 바뀔 때마다 문서 전체에서 선택자로 다시 찾는다(한 프레임에 한 번) — 느려지면 바뀐 자리만 본다.
185
+ const candidates = `[${ATTRIBUTE}], ${wanted}`;
186
+ /** 바뀐 자리들 — 다음 프레임에 그 요소와 안쪽만 다시 본다. `everything` 이면 문서 전체를 본다(처음 · 창 크기가 바뀐 뒤). */
187
+ const dirty = new Set();
188
+ let everything = true;
189
+ /** 바뀐 자리가 이보다 많으면 하나씩 보느니 문서 전체를 한 번 훑는다. */
190
+ const MANY = 50;
147
191
  const scan = () => {
148
192
  frame = 0;
149
193
  for (const el of handled.keys()) {
@@ -152,17 +196,35 @@ export function installPenguinLetters(options = {}) {
152
196
  handled.get(el)?.undo();
153
197
  handled.delete(el);
154
198
  }
155
- for (const el of document.querySelectorAll(`[${ATTRIBUTE}], ${wanted}`))
156
- visit(el);
199
+ const roots = everything || dirty.size > MANY ? [document.body] : [...dirty];
200
+ everything = false;
201
+ dirty.clear();
202
+ for (const root of roots) {
203
+ // 화면에서 빠졌거나 제외한 영역 안이면 볼 것이 없다 — 채팅처럼 글이 계속 흘러나오는 영역을 `exclude` 로 빼면 거기서는 일하지 않는다.
204
+ if (!root.isConnected || (skipped && root.closest(skipped)))
205
+ continue;
206
+ if (root instanceof HTMLElement && root.matches(candidates))
207
+ visit(root);
208
+ for (const el of root.querySelectorAll(candidates))
209
+ visit(el);
210
+ }
157
211
  };
158
212
  let frame = 0;
159
- // 넣으면서 바꾼 것도 변화로 잡히지만, 다시 찾아도 이미 맡은 요소는 건너뛰어 되풀이되지 않는다.
160
- const observer = new MutationObserver(() => {
161
- frame ||= requestAnimationFrame(scan);
213
+ // 넣으면서 바꾼 것도 변화로 잡히지만, 다시 봐도 이미 맡은 요소는 건너뛰어 되풀이되지 않는다.
214
+ const observer = new MutationObserver((records) => {
215
+ for (const record of records) {
216
+ const target = record.target instanceof Element ? record.target : record.target.parentElement;
217
+ // 넣어 둔 상자 속에서 생긴 변화는 우리가 그린 것이다.
218
+ if (target && !target.closest(`[${PLAN_ATTRIBUTE}]`))
219
+ dirty.add(target);
220
+ }
221
+ if (dirty.size > 0)
222
+ frame ||= requestAnimationFrame(scan);
162
223
  });
163
224
  // 창이 좁아지면 넉넉하던 자리가 모자랄 수 있다 — 처음부터 다시 본다.
164
225
  const resized = () => {
165
226
  spacious = new WeakMap();
227
+ everything = true;
166
228
  frame ||= requestAnimationFrame(scan);
167
229
  };
168
230
  const boot = () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plz-penguin-letters",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Huddle up plz, penguin letters. Keeps your layout intact, however long the translation gets.",
5
5
  "keywords": [
6
6
  "i18n",