@link-foundation/ui-devmode 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.
Files changed (46) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +353 -2
  3. package/package.json +78 -4
  4. package/src/activation.js +235 -0
  5. package/src/adapter.js +92 -0
  6. package/src/agent-instruction.d.ts +6 -0
  7. package/src/agent-instruction.js +17 -0
  8. package/src/agent-instruction.txt +8 -0
  9. package/src/apply-shared.js +135 -0
  10. package/src/comments/commands.js +77 -0
  11. package/src/comments/geometry.js +65 -0
  12. package/src/comments/index.d.ts +93 -0
  13. package/src/comments/index.js +205 -0
  14. package/src/comments/model.js +359 -0
  15. package/src/comments/picking.js +154 -0
  16. package/src/comments/style.js +36 -0
  17. package/src/comments/view.js +250 -0
  18. package/src/comments/voice.js +64 -0
  19. package/src/defaults-dialog.js +120 -0
  20. package/src/details.js +159 -0
  21. package/src/editors.js +194 -0
  22. package/src/export.js +50 -0
  23. package/src/foreign/adapter.js +166 -0
  24. package/src/foreign/apply.js +89 -0
  25. package/src/foreign/entry.js +173 -0
  26. package/src/foreign/index.d.ts +32 -0
  27. package/src/foreign/injected.js +6 -0
  28. package/src/foreign/persist.js +54 -0
  29. package/src/foreign/properties.js +126 -0
  30. package/src/foreign/runtime.js +67 -0
  31. package/src/index.d.ts +204 -0
  32. package/src/index.js +201 -0
  33. package/src/inspector-css.js +106 -0
  34. package/src/inspector.js +342 -0
  35. package/src/inspector.lino +50 -0
  36. package/src/messages.js +113 -0
  37. package/src/model.d.ts +101 -0
  38. package/src/model.js +473 -0
  39. package/src/overlay.js +91 -0
  40. package/src/policy.js +222 -0
  41. package/src/read-asset.browser.js +8 -0
  42. package/src/read-asset.js +10 -0
  43. package/src/session.js +555 -0
  44. package/src/share.js +23 -0
  45. package/src/validate.js +170 -0
  46. package/src/views.js +328 -0
@@ -0,0 +1,235 @@
1
+ /**
2
+ * The three ways into dev mode: a keyboard shortcut (`Alt+Shift+D` by
3
+ * default), the `?ui-dev` URL parameter and a `<ui-dev-mode>` element in
4
+ * the page. This module is small on purpose: it is the only part of dev mode
5
+ * a page loads before dev mode is opened.
6
+ */
7
+
8
+ /** The URL parameter that opens dev mode on load. */
9
+ export const URL_PARAMETER = 'ui-dev';
10
+
11
+ /** The custom element that opens dev mode when it is connected. */
12
+ export const ELEMENT_NAME = 'ui-dev-mode';
13
+
14
+ /** The event a connected `<ui-dev-mode>` element dispatches. */
15
+ export const REQUEST_EVENT = 'ui-dev-mode-request';
16
+
17
+ /** `?ui-dev=false` (or `0`, `off`, `no`) keeps dev mode closed. */
18
+ const OFF_VALUES = new Set(['false', '0', 'off', 'no']);
19
+
20
+ /** Modifier names of a shortcut and the `KeyboardEvent` flag of each. */
21
+ const MODIFIERS = {
22
+ alt: 'altKey',
23
+ option: 'altKey',
24
+ shift: 'shiftKey',
25
+ ctrl: 'ctrlKey',
26
+ control: 'ctrlKey',
27
+ meta: 'metaKey',
28
+ cmd: 'metaKey',
29
+ command: 'metaKey',
30
+ };
31
+
32
+ /**
33
+ * @typedef {object} Shortcut
34
+ * @property {boolean} altKey
35
+ * @property {boolean} shiftKey
36
+ * @property {boolean} ctrlKey
37
+ * @property {boolean} metaKey
38
+ * @property {string} code a `KeyboardEvent.code` such as `KeyD`
39
+ */
40
+
41
+ /**
42
+ * The `KeyboardEvent.code` of a key name: `D` is `KeyD`, `7` is `Digit7`;
43
+ * any other name (`F12`, `Backquote`) is a code already.
44
+ */
45
+ function keyCode(name) {
46
+ if (name.length === 1) {
47
+ const upper = name.toUpperCase();
48
+ if (upper >= 'A' && upper <= 'Z') {
49
+ return `Key${upper}`;
50
+ }
51
+ if (upper >= '0' && upper <= '9') {
52
+ return `Digit${upper}`;
53
+ }
54
+ }
55
+ return name;
56
+ }
57
+
58
+ /**
59
+ * Read a shortcut such as `Alt+Shift+D`. The key is matched by
60
+ * `KeyboardEvent.code` (the physical key), so the shortcut works on every
61
+ * keyboard layout, also where `Alt` changes `event.key` (macOS).
62
+ * @param {string} text
63
+ * @returns {Shortcut}
64
+ */
65
+ export function parseShortcut(text) {
66
+ const parts = String(text)
67
+ .split('+')
68
+ .map((part) => part.trim())
69
+ .filter((part) => part !== '');
70
+ const shortcut = {
71
+ altKey: false,
72
+ shiftKey: false,
73
+ ctrlKey: false,
74
+ metaKey: false,
75
+ code: '',
76
+ };
77
+ for (const part of parts) {
78
+ const flag = MODIFIERS[part.toLowerCase()];
79
+ if (flag === undefined) {
80
+ shortcut.code = keyCode(part);
81
+ } else {
82
+ shortcut[flag] = true;
83
+ }
84
+ }
85
+ if (shortcut.code === '') {
86
+ throw new TypeError(`The shortcut "${text}" names no key`);
87
+ }
88
+ return Object.freeze(shortcut);
89
+ }
90
+
91
+ /**
92
+ * Whether a key event is the shortcut (every modifier must match).
93
+ * @param {Pick<KeyboardEvent, 'code'|'altKey'|'shiftKey'|'ctrlKey'|'metaKey'>} event
94
+ * @param {Shortcut} shortcut
95
+ */
96
+ export const matchesShortcut = (event, shortcut) =>
97
+ event.code === shortcut.code &&
98
+ Boolean(event.altKey) === shortcut.altKey &&
99
+ Boolean(event.shiftKey) === shortcut.shiftKey &&
100
+ Boolean(event.ctrlKey) === shortcut.ctrlKey &&
101
+ Boolean(event.metaKey) === shortcut.metaKey;
102
+
103
+ const EDITABLE_TAGS = new Set(['INPUT', 'TEXTAREA', 'SELECT']);
104
+
105
+ /**
106
+ * Whether a node is a place where the user types: `input`, `textarea`,
107
+ * `select` or inside `[contenteditable]`.
108
+ * @param {unknown} node
109
+ */
110
+ export function isEditableTarget(node) {
111
+ const element = /** @type {any} */ (node);
112
+ if (!element || typeof element.tagName !== 'string') {
113
+ return false;
114
+ }
115
+ if (EDITABLE_TAGS.has(element.tagName.toUpperCase())) {
116
+ return true;
117
+ }
118
+ return Boolean(
119
+ element.isContentEditable ||
120
+ element.closest?.('[contenteditable]:not([contenteditable="false"])')
121
+ );
122
+ }
123
+
124
+ /** The innermost target of an event, also inside a shadow root. */
125
+ export const eventTarget = (event) =>
126
+ (typeof event.composedPath === 'function' ? event.composedPath()[0] : null) ??
127
+ event.target;
128
+
129
+ /**
130
+ * Whether dev mode opens on page load. Pure: the shortcut is a later user
131
+ * action, so only the URL parameter and the element count here.
132
+ * @param {{ url: string|URL, policy: import('./policy.js').DevModePolicy,
133
+ * hasElement?: boolean }} input
134
+ * @returns {boolean}
135
+ */
136
+ export function shouldActivate({ url, policy, hasElement = false }) {
137
+ if (!policy.enabled) {
138
+ return false;
139
+ }
140
+ if (hasElement && policy.entry.has('element')) {
141
+ return true;
142
+ }
143
+ if (!policy.entry.has('url-parameter')) {
144
+ return false;
145
+ }
146
+ const params = new globalThis.URL(String(url), 'http://localhost/')
147
+ .searchParams;
148
+ return (
149
+ params.has(URL_PARAMETER) &&
150
+ !OFF_VALUES.has(params.get(URL_PARAMETER).toLowerCase())
151
+ );
152
+ }
153
+
154
+ /**
155
+ * Define `<ui-dev-mode>` in a window. Returns `false` when the window
156
+ * has the definition (an element in the page is then not upgraded again).
157
+ */
158
+ function defineElement(window) {
159
+ const registry = window.customElements;
160
+ if (!registry || registry.get(ELEMENT_NAME)) {
161
+ return false;
162
+ }
163
+ const Event = window.CustomEvent;
164
+ registry.define(
165
+ ELEMENT_NAME,
166
+ class UiDevMode extends window.HTMLElement {
167
+ connectedCallback() {
168
+ this.dispatchEvent(
169
+ new Event(REQUEST_EVENT, { bubbles: true, composed: true })
170
+ );
171
+ }
172
+ }
173
+ );
174
+ return true;
175
+ }
176
+
177
+ /**
178
+ * Install the entry points the policy allows: the key listener, the URL
179
+ * parameter (read once, now) and the `<ui-dev-mode>` element. A disabled
180
+ * policy installs nothing.
181
+ *
182
+ * `onActivate(entry)` is called with `'url-parameter'` or `'element'`;
183
+ * the shortcut calls `onToggle('shortcut')` when given, else `onActivate`.
184
+ * The shortcut is ignored while the focus is in an editable field.
185
+ * @param {{ window: Window & typeof globalThis,
186
+ * policy: import('./policy.js').DevModePolicy,
187
+ * onActivate: (entry: string) => void,
188
+ * onToggle?: (entry: string) => void }} options
189
+ * @returns {() => void} removes the listeners
190
+ */
191
+ export function installActivation({ window, policy, onActivate, onToggle }) {
192
+ if (!policy.enabled) {
193
+ return () => {};
194
+ }
195
+ const cleanups = [];
196
+ const listen = (target, type, listener, capture) => {
197
+ target.addEventListener(type, listener, capture);
198
+ cleanups.push(() => target.removeEventListener(type, listener, capture));
199
+ };
200
+ if (policy.entry.has('shortcut')) {
201
+ const shortcut = parseShortcut(policy.shortcut);
202
+ listen(
203
+ window,
204
+ 'keydown',
205
+ (event) => {
206
+ if (
207
+ event.defaultPrevented ||
208
+ event.repeat ||
209
+ !matchesShortcut(event, shortcut) ||
210
+ isEditableTarget(eventTarget(event))
211
+ ) {
212
+ return;
213
+ }
214
+ event.preventDefault();
215
+ (onToggle ?? onActivate)('shortcut');
216
+ },
217
+ true
218
+ );
219
+ }
220
+ if (policy.entry.has('element')) {
221
+ listen(window, REQUEST_EVENT, () => onActivate('element'), false);
222
+ // Defining the element upgrades the ones in the page, which request
223
+ // dev mode; an element of an earlier definition has to be looked up.
224
+ if (
225
+ !defineElement(window) &&
226
+ window.document.querySelector(ELEMENT_NAME) !== null
227
+ ) {
228
+ onActivate('element');
229
+ }
230
+ }
231
+ if (shouldActivate({ url: window.location.href, policy })) {
232
+ onActivate('url-parameter');
233
+ }
234
+ return () => cleanups.splice(0).forEach((cleanup) => cleanup());
235
+ }
package/src/adapter.js ADDED
@@ -0,0 +1,92 @@
1
+ /** The shared inspector contract for ui-dom and foreign pages. */
2
+ import { defaultVocabulary } from '@link-foundation/ui-core';
3
+ import { applyEdit, propertyRows, topWritableLayer } from './model.js';
4
+
5
+ /**
6
+ * @typedef {object} PageAdapter
7
+ * @property {() => object} tree A store-shaped view of the imported document.
8
+ * @property {(id: string) => Node|null} nodeFor
9
+ * @property {(node: Node) => string|null} idFor
10
+ * @property {(id: string, name: string|object, value: unknown) => object} applyProperty
11
+ * @property {(callback: () => void) => () => void} observe
12
+ * @property {(id: string) => object[]} rows Property grid presentation.
13
+ */
14
+
15
+ /**
16
+ * The tree of the document read from the effective configuration, for a
17
+ * page that passes no ui-store store. Same shape as a store.
18
+ */
19
+ export function documentTree(config) {
20
+ let doc = null;
21
+ const parents = new Map();
22
+ const load = () => {
23
+ if (doc === null) {
24
+ doc = config.effective();
25
+ parents.clear();
26
+ const walk = (node, parent) => {
27
+ parents.set(node.id, parent);
28
+ (node.children ?? []).forEach((child) => walk(child, node.id));
29
+ };
30
+ doc.roots.forEach((node) => walk(node, null));
31
+ }
32
+ return doc;
33
+ };
34
+ return {
35
+ get: (id) => load().byId.get(id),
36
+ roots: () => load().roots.map((node) => node.id),
37
+ children: (id) =>
38
+ (load().byId.get(id)?.children ?? []).map((node) => node.id),
39
+ parentOf: (id) => (load(), parents.get(id) ?? null),
40
+ toDocument: load,
41
+ subscribe: (listener) =>
42
+ config.subscribe((...args) => {
43
+ doc = null;
44
+ listener(...args);
45
+ }),
46
+ };
47
+ }
48
+
49
+ /** Adapt an existing ui-dom page without changing its edit or pick behavior. */
50
+ export function createUiDomAdapter(options) {
51
+ const { config, policy, root } = options;
52
+ const tree = options.store ?? documentTree(config);
53
+ const modelOptions = {
54
+ policy,
55
+ vocabulary: options.vocabulary ?? defaultVocabulary(),
56
+ parentOf: (id) => tree.parentOf(id),
57
+ getElement: (id) => tree.get(id),
58
+ };
59
+ const layer = policy.writeLayers.includes('session')
60
+ ? 'session'
61
+ : topWritableLayer(policy);
62
+ return {
63
+ tree: () => tree,
64
+ nodeFor: (id) =>
65
+ options.handle?.nodeFor?.(id) ??
66
+ [...root.querySelectorAll('[data-link-id]')].find(
67
+ (node) => node.getAttribute('data-link-id') === id
68
+ ) ??
69
+ null,
70
+ idFor(node) {
71
+ for (let at = node; at && root.contains(at); at = at.parentNode) {
72
+ if (at.nodeType === 1 && at.hasAttribute('data-link-id')) {
73
+ return at.getAttribute('data-link-id');
74
+ }
75
+ }
76
+ return null;
77
+ },
78
+ rows: (id) =>
79
+ tree.get(id) ? propertyRows(tree.get(id), config, modelOptions) : [],
80
+ applyProperty(id, row, value) {
81
+ if (typeof row === 'string') {
82
+ row = { name: row, key: null };
83
+ }
84
+ return applyEdit(
85
+ config,
86
+ { id, name: row.name, key: row.key ?? null, value, layer },
87
+ modelOptions
88
+ );
89
+ },
90
+ observe: (callback) => config.subscribe(callback),
91
+ };
92
+ }
@@ -0,0 +1,6 @@
1
+ export function loadAgentTemplate(): Promise<string>;
2
+ export function renderAgentInstruction(values?: {
3
+ repository?: string;
4
+ siteConfig?: string;
5
+ overrides?: string;
6
+ }): string;
@@ -0,0 +1,17 @@
1
+ /* global URL */
2
+ import { readAsset } from './read-asset.js';
3
+
4
+ /** Read the shipped template in Node or a browser, without bundler-specific imports. */
5
+ export async function loadAgentTemplate() {
6
+ return await readAsset(new URL('./agent-instruction.txt', import.meta.url));
7
+ }
8
+
9
+ const template = await loadAgentTemplate();
10
+
11
+ /** Fill named placeholders with supplied values or explicit unknown markers. */
12
+ export function renderAgentInstruction(values = {}) {
13
+ return template.replace(
14
+ /\{(\w+)\}/g,
15
+ (_, key) => values[key] || `<unknown ${key}>`
16
+ );
17
+ }
@@ -0,0 +1,8 @@
1
+ Make these UI overrides the defaults of {repository}.
2
+ 1. Open {siteConfig}. Apply every `set` link below to the matching element
3
+ or token. Keep comments and layout (do not reformat the file).
4
+ 2. Do not change anything else. Run: npm test
5
+ 3. Open a pull request titled "Make UI overrides the defaults"
6
+ and paste the overrides block into its description.
7
+
8
+ {overrides}
@@ -0,0 +1,135 @@
1
+ import { formatLinks } from '@link-foundation/ui-core';
2
+ import { translator } from './messages.js';
3
+ import { defaultPolicy } from './policy.js';
4
+ import { decodeShareHash, SHARE_PREFIX } from './share.js';
5
+ import { validateOverrides } from './validate.js';
6
+
7
+ export const BACKUP_KEY = 'ui-overrides:before-the-link';
8
+
9
+ /** Validate external text, back up both writable layers, then preview in session only. */
10
+ export function applySharedOverrides({
11
+ config,
12
+ location,
13
+ history,
14
+ storage,
15
+ schema = config.effective(),
16
+ policy = defaultPolicy(),
17
+ text,
18
+ document,
19
+ t = translator(),
20
+ }) {
21
+ const fromHash = text === undefined;
22
+ if (fromHash && !location.hash.startsWith(SHARE_PREFIX)) {
23
+ return null;
24
+ }
25
+ const input = fromHash ? decodeShareHash(location.hash) : text;
26
+ const report = validateOverrides(input, { schema, policy });
27
+ report.applied = false;
28
+ if (!policy.enabled || !policy.writeLayers.includes('session')) {
29
+ report.links = [];
30
+ report.rejected.push({
31
+ link: null,
32
+ reason: 'Site policy forbids session previews',
33
+ });
34
+ }
35
+ const before = {
36
+ name: 'Before the link',
37
+ user: config.overrides('user'),
38
+ session: config.overrides('session'),
39
+ };
40
+ preview(config, storage, before, report);
41
+ if (fromHash) {
42
+ history.replaceState(
43
+ history.state,
44
+ '',
45
+ location.pathname + location.search
46
+ );
47
+ }
48
+ let banner;
49
+ const finish = () => banner?.remove();
50
+ report.keep = finish;
51
+ report.discard = () => {
52
+ if (report.applied) {
53
+ config.clear('session');
54
+ for (const o of before.session) {
55
+ config.set('session', o.id, o.name, o.values, o.key ?? undefined);
56
+ }
57
+ }
58
+ finish();
59
+ };
60
+ if (document) {
61
+ banner = showBanner(document, report, t);
62
+ }
63
+ return report;
64
+ }
65
+
66
+ function preview(config, storage, before, report) {
67
+ const sets =
68
+ report.links[0]?.values.filter(
69
+ (link) => Array.isArray(link) && link[0] === 'set'
70
+ ) ?? [];
71
+ if (sets.length) {
72
+ try {
73
+ storage.setItem(
74
+ BACKUP_KEY,
75
+ formatLinks([
76
+ {
77
+ id: 'before-the-link',
78
+ values: [
79
+ 'backup',
80
+ ['name', before.name],
81
+ ...['user', 'session'].map((layer) => [
82
+ layer,
83
+ ...before[layer].map((o) => [
84
+ 'set',
85
+ o.id,
86
+ o.name,
87
+ ...(o.key === null || o.key === undefined ? [] : [o.key]),
88
+ ...o.values,
89
+ ]),
90
+ ]),
91
+ ],
92
+ },
93
+ ])
94
+ );
95
+ const result = config.importLook(formatLinks(report.links), 'session');
96
+ if (!result.ok) {
97
+ throw new Error(result.diagnostics.map((d) => d.message).join('; '));
98
+ }
99
+ report.applied = true;
100
+ } catch (error) {
101
+ report.rejected.push({ link: null, reason: error.message });
102
+ }
103
+ }
104
+ }
105
+
106
+ function showBanner(document, report, t) {
107
+ const banner = document.createElement('aside');
108
+ banner.dataset.uiDevmode = 'shared';
109
+ banner.setAttribute('aria-label', t('shared.title'));
110
+ const status = document.createElement('p');
111
+ status.setAttribute('role', 'status');
112
+ status.textContent = t('shared.title');
113
+ banner.append(status);
114
+ for (const { link, reason } of report.rejected) {
115
+ const rejection = document.createElement('p');
116
+ rejection.textContent =
117
+ link === null
118
+ ? reason
119
+ : `${formatLinks([link], { style: 'inline' }).trim()}: ${reason}`;
120
+ banner.append(rejection);
121
+ }
122
+ for (const [key, action] of [
123
+ ['shared.keep', report.keep],
124
+ ['shared.discard', report.discard],
125
+ ]) {
126
+ const button = document.createElement('button');
127
+ button.type = 'button';
128
+ button.textContent = t(key);
129
+ button.onclick = action;
130
+ banner.append(button);
131
+ }
132
+ document.body.prepend(banner);
133
+
134
+ return banner;
135
+ }
@@ -0,0 +1,77 @@
1
+ import { createDictation } from './voice.js';
2
+
3
+ /** Form commands share the same validated model as programmatic callers. */
4
+ export function commentCommands({
5
+ window,
6
+ view,
7
+ model,
8
+ picking,
9
+ selection,
10
+ select,
11
+ destroy,
12
+ announce,
13
+ isClosed,
14
+ }) {
15
+ let inputMethod = 'text';
16
+ let active = false;
17
+ const t = view.t;
18
+ const dictation = createDictation({
19
+ window,
20
+ onText: (text) => {
21
+ view.instruction.value = `${view.instruction.value} ${text}`
22
+ .trim()
23
+ .slice(0, 4000);
24
+ inputMethod = 'voice';
25
+ },
26
+ onStatus: announce,
27
+ onActive: (value) => {
28
+ active = value;
29
+ view.voice.setAttribute('aria-pressed', String(value));
30
+ view.voice.textContent = t(
31
+ value ? 'Stop voice input' : 'Start voice input'
32
+ );
33
+ },
34
+ });
35
+ view.voice.disabled = !dictation.supported;
36
+ if (!dictation.supported) {
37
+ view.voice.title = t(
38
+ 'Voice input is unavailable. Type your instruction instead.'
39
+ );
40
+ }
41
+ const commands = {
42
+ pick: () => picking.setMode('pick'),
43
+ lasso: () => picking.setMode('lasso'),
44
+ clear: () => select([]),
45
+ close: destroy,
46
+ voice: () => (active ? dictation.stop() : dictation.start()),
47
+ add() {
48
+ model.add(selection(), view.instruction.value, inputMethod);
49
+ dictation.stop();
50
+ view.instruction.value = '';
51
+ inputMethod = 'text';
52
+ },
53
+ export() {
54
+ view.exchange.value = model.export();
55
+ },
56
+ import() {
57
+ model.import(view.exchange.value);
58
+ },
59
+ async copy() {
60
+ view.exchange.value = model.export();
61
+ try {
62
+ await window.navigator.clipboard.writeText(view.exchange.value);
63
+ if (!isClosed()) {
64
+ announce(t('Copied.'));
65
+ }
66
+ } catch {
67
+ if (isClosed()) {
68
+ return;
69
+ }
70
+ view.exchange.focus();
71
+ view.exchange.select();
72
+ announce(t('Text selected. Copy it with your keyboard.'));
73
+ }
74
+ },
75
+ };
76
+ return { commands, destroy: () => dictation.destroy() };
77
+ }
@@ -0,0 +1,65 @@
1
+ /** Freehand lasso in viewport CSS pixels. Enclosing containers are excluded. */
2
+ const cross = (a, b, p) =>
3
+ (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
4
+ const onSegment = (a, b, p) =>
5
+ Math.abs(cross(a, b, p)) < 1e-8 &&
6
+ p.x >= Math.min(a.x, b.x) &&
7
+ p.x <= Math.max(a.x, b.x) &&
8
+ p.y >= Math.min(a.y, b.y) &&
9
+ p.y <= Math.max(a.y, b.y);
10
+ const intersects = (a, b, c, d) =>
11
+ onSegment(a, b, c) ||
12
+ onSegment(a, b, d) ||
13
+ onSegment(c, d, a) ||
14
+ onSegment(c, d, b) ||
15
+ (cross(a, b, c) * cross(a, b, d) < 0 && cross(c, d, a) * cross(c, d, b) < 0);
16
+
17
+ function inside(p, polygon) {
18
+ let yes = false;
19
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
20
+ const a = polygon[i];
21
+ const b = polygon[j];
22
+ if (onSegment(a, b, p)) {
23
+ return true;
24
+ }
25
+ if (
26
+ a.y > p.y !== b.y > p.y &&
27
+ p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x
28
+ ) {
29
+ yes = !yes;
30
+ }
31
+ }
32
+ return yes;
33
+ }
34
+
35
+ export function lasso(rects, polygon) {
36
+ if (polygon.length < 3) {
37
+ return [];
38
+ }
39
+ return rects
40
+ .filter((r) => {
41
+ if (r.width <= 0 || r.height <= 0) {
42
+ return false;
43
+ }
44
+ const corners = [
45
+ { x: r.x, y: r.y },
46
+ { x: r.x + r.width, y: r.y },
47
+ { x: r.x + r.width, y: r.y + r.height },
48
+ { x: r.x, y: r.y + r.height },
49
+ ];
50
+ if (corners.some((p) => inside(p, polygon))) {
51
+ return true;
52
+ }
53
+ return corners.some((a, i) =>
54
+ polygon.some((c, j) =>
55
+ intersects(
56
+ a,
57
+ corners[(i + 1) % 4],
58
+ c,
59
+ polygon[(j + 1) % polygon.length]
60
+ )
61
+ )
62
+ );
63
+ })
64
+ .map((r) => r.id);
65
+ }