@codecademy/brand 1.0.0-alpha.4bc8aac7b1.0 → 1.0.0-alpha.67f9320ff7.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 (120) hide show
  1. package/dist/AppBar/AppBarSection.js +1 -1
  2. package/dist/AppHeader/AppHeaderElements/AppHeaderCatalogDropdown/index.d.ts +0 -1
  3. package/dist/AppHeader/AppHeaderElements/AppHeaderCatalogDropdown/index.js +2 -4
  4. package/dist/AppHeader/AppHeaderElements/AppHeaderCatalogSection/elements.d.ts +14 -14
  5. package/dist/AppHeader/AppHeaderElements/AppHeaderCatalogSection/elements.js +6 -6
  6. package/dist/AppHeader/AppHeaderElements/AppHeaderCatalogSection/index.d.ts +0 -1
  7. package/dist/AppHeader/AppHeaderElements/AppHeaderCatalogSection/index.js +15 -12
  8. package/dist/AppHeader/AppHeaderElements/AppHeaderLink/index.d.ts +5 -5
  9. package/dist/AppHeader/AppHeaderElements/AppHeaderListItem/index.d.ts +1 -1
  10. package/dist/AppHeader/AppHeaderElements/AppHeaderResourcesDropdown/index.d.ts +1 -1
  11. package/dist/AppHeader/AppHeaderElements/AppHeaderResourcesSection/index.js +2 -2
  12. package/dist/AppHeader/Search/QuizAndHelpCenterLinks.d.ts +0 -1
  13. package/dist/AppHeader/Search/QuizAndHelpCenterLinks.js +11 -8
  14. package/dist/AppHeader/Search/SearchButton.js +1 -3
  15. package/dist/AppHeader/Search/SearchPane.d.ts +1 -3
  16. package/dist/AppHeader/Search/SearchPane.js +72 -66
  17. package/dist/AppHeader/Search/SearchWorker/PromiseLookup.d.ts +18 -0
  18. package/dist/AppHeader/Search/SearchWorker/PromiseLookup.js +35 -0
  19. package/dist/AppHeader/Search/SearchWorker/index.d.ts +4 -34
  20. package/dist/AppHeader/Search/SearchWorker/index.js +22 -73
  21. package/dist/AppHeader/Search/SearchWorker/src.d.ts +1 -2
  22. package/dist/AppHeader/Search/SearchWorker/src.js +253 -199
  23. package/dist/AppHeader/Search/SearchWorker/types.d.ts +32 -0
  24. package/dist/AppHeader/Search/SearchWorker/types.js +5 -0
  25. package/dist/AppHeader/Search/SearchWorker/worker.d.ts +2 -0
  26. package/dist/AppHeader/Search/SearchWorker/worker.js +32 -0
  27. package/dist/AppHeader/Search/useHeaderSearch.d.ts +1 -3
  28. package/dist/AppHeader/Search/useHeaderSearch.js +2 -4
  29. package/dist/AppHeader/index.d.ts +1 -2
  30. package/dist/AppHeader/index.js +11 -16
  31. package/dist/AppHeader/shared/elements.d.ts +10 -272
  32. package/dist/AppHeader/shared/elements.js +9 -7
  33. package/dist/AppHeaderMobile/AppHeaderMainMenuMobile/index.js +1 -1
  34. package/dist/AppHeaderMobile/index.d.ts +0 -1
  35. package/dist/AppHeaderMobile/index.js +6 -8
  36. package/dist/Avatar/index.js +1 -1
  37. package/dist/Carousel/elements.d.ts +4 -4
  38. package/dist/Carousel/index.js +7 -4
  39. package/dist/CertificationPathCard/__tests__/__fixtures__/index.d.ts +2 -0
  40. package/dist/CertificationPathCard/index.d.ts +18 -0
  41. package/dist/CertificationPathCard/index.js +39 -0
  42. package/dist/ContentGroupBaseCard/index.d.ts +5 -0
  43. package/dist/ContentGroupBaseCard/index.js +14 -5
  44. package/dist/DropdownButton/DropdownList.js +1 -1
  45. package/dist/DropdownButton/index.d.ts +312 -1
  46. package/dist/DropdownButton/index.js +9 -6
  47. package/dist/EmptySection/index.d.ts +1 -1
  48. package/dist/EmptySection/index.js +31 -10
  49. package/dist/GlobalFooter/FooterHeading.d.ts +4 -4
  50. package/dist/GlobalFooter/FooterHeading.js +12 -25
  51. package/dist/GlobalFooter/FooterLinks.d.ts +1 -1
  52. package/dist/GlobalFooter/FooterLinks.js +10 -19
  53. package/dist/GlobalFooter/FooterNavLinks/CatalogLinks.js +28 -46
  54. package/dist/GlobalFooter/FooterSubHeading.d.ts +2 -2
  55. package/dist/GlobalFooter/FooterSubHeading.js +9 -18
  56. package/dist/GlobalHeader/GlobalHeaderItems.d.ts +0 -1
  57. package/dist/GlobalHeader/GlobalHeaderItems.js +0 -8
  58. package/dist/GlobalHeader/GlobalHeaderVariants.d.ts +4 -4
  59. package/dist/GlobalHeader/GlobalHeaderVariants.js +11 -11
  60. package/dist/GlobalHeader/index.d.ts +4 -2
  61. package/dist/GlobalHeader/index.js +45 -48
  62. package/dist/GlobalHeader/types.d.ts +0 -4
  63. package/dist/Grid/GridCollapse.js +16 -23
  64. package/dist/LayoutMenuVariant/AccordionMenu.d.ts +2 -0
  65. package/dist/LayoutMenuVariant/AccordionMenu.js +3 -3
  66. package/dist/LayoutMenuVariant/LayoutMenuSection.js +2 -1
  67. package/dist/LayoutMenuVariant/SectionItemLink.d.ts +2 -1
  68. package/dist/LayoutMenuVariant/SectionItemLink.js +2 -1
  69. package/dist/LoadingCurriculumCard/index.js +1 -1
  70. package/dist/Logo/index.d.ts +4 -1
  71. package/dist/Logo/index.js +6 -2
  72. package/dist/LogoFromSkillsoft/index.js +1 -1
  73. package/dist/NotificationList/NotificationItem.js +3 -3
  74. package/dist/Notifications/elements.d.ts +2 -2
  75. package/dist/PlanCard/PricingAmount.d.ts +1 -1
  76. package/dist/PlanCard/PricingAmount.js +4 -4
  77. package/dist/PlanCard/consts.js +1 -1
  78. package/dist/PlanCard/index.d.ts +1 -2
  79. package/dist/PlanCard/index.js +14 -22
  80. package/dist/ProLabel/index.d.ts +1 -1
  81. package/dist/ProLabel/index.js +1 -1
  82. package/dist/ResourceCard/index.d.ts +4 -3
  83. package/dist/ResourceCard/index.js +6 -3
  84. package/dist/SocialMediaSharing/SocialShareIconLink.js +2 -2
  85. package/dist/SocialMediaSharingDropdown/index.d.ts +4 -1
  86. package/dist/SocialMediaSharingDropdown/index.js +11 -2
  87. package/dist/Testimonial/index.d.ts +1 -1
  88. package/dist/index.d.ts +1 -1
  89. package/dist/index.js +1 -1
  90. package/dist/lib/catalogList/index.js +2 -9
  91. package/dist/stories/Atoms/Subgrid.stories.js +1 -1
  92. package/dist/stories/Molecules/CurriculumCards/CertificationPathCard.stories.d.ts +9 -0
  93. package/dist/stories/Molecules/CurriculumCards/CertificationPathCard.stories.js +65 -0
  94. package/dist/stories/Organisms/GlobalHeader/About.stories.js +8 -8
  95. package/dist/stories/Organisms/GlobalPage.stories.js +4 -4
  96. package/dist/stories/Organisms/PlanCard.stories.js +2 -3
  97. package/package.json +4 -5
  98. package/dist/StudyPlan/ContentItemDetail.d.ts +0 -10
  99. package/dist/StudyPlan/ContentItemDetail.js +0 -114
  100. package/dist/StudyPlan/CreateStudyPlanSectionContent.d.ts +0 -14
  101. package/dist/StudyPlan/CreateStudyPlanSectionContent.js +0 -90
  102. package/dist/StudyPlan/ShowMoreContentItemsButton.d.ts +0 -9
  103. package/dist/StudyPlan/ShowMoreContentItemsButton.js +0 -44
  104. package/dist/StudyPlan/StudyPlanDeleteDialog.d.ts +0 -6
  105. package/dist/StudyPlan/StudyPlanDeleteDialog.js +0 -26
  106. package/dist/StudyPlan/StudyPlanDescription.d.ts +0 -10
  107. package/dist/StudyPlan/StudyPlanDescription.js +0 -50
  108. package/dist/StudyPlan/StudyPlanModal/StudyPlanForm.d.ts +0 -10
  109. package/dist/StudyPlan/StudyPlanModal/StudyPlanForm.js +0 -138
  110. package/dist/StudyPlan/StudyPlanModal/StudyPlanModalFooter.d.ts +0 -14
  111. package/dist/StudyPlan/StudyPlanModal/StudyPlanModalFooter.js +0 -64
  112. package/dist/StudyPlan/StudyPlanModal/index.d.ts +0 -18
  113. package/dist/StudyPlan/StudyPlanModal/index.js +0 -120
  114. package/dist/StudyPlan/SuggestedContentItemsSectionHeader.d.ts +0 -8
  115. package/dist/StudyPlan/SuggestedContentItemsSectionHeader.js +0 -58
  116. package/dist/StudyPlan/assets/studyPlanBanner.svg +0 -9
  117. package/dist/StudyPlan/helpers.d.ts +0 -75
  118. package/dist/StudyPlan/helpers.js +0 -165
  119. package/dist/StudyPlan/index.d.ts +0 -8
  120. package/dist/StudyPlan/index.js +0 -8
@@ -10,246 +10,300 @@
10
10
  * "c", "d", and "e" each get a score of 3, because each is part of the match "cde"
11
11
  *
12
12
  * For autocomplete, a large list of titles is preloaded, and this
13
- * scoring algorythm is used both to find the top 5 matches, and to
13
+ * scoring algorithm is used both to find the top 5 matches, and to
14
14
  * determine which characters should be highlighted.
15
15
  * (These titles have certain phrases like "Intro to" removed so that they
16
16
  * better resemble something that a user would type.)
17
17
  *
18
18
  * For search-as-you-type, we rely on typesense to find matches,
19
- * but we still use this algorythm for character highlighting.
19
+ * but we still use this algorithm for character highlighting.
20
20
  */
21
21
 
22
- export function getPortalOrigin() {
22
+ function getPortalOrigin() {
23
23
  const {
24
24
  origin
25
25
  } = window.location;
26
+ const envs = ['tengu', 'tayra', 'staging', 'www'];
27
+
26
28
  // for standard envs, use portal app in the same env
27
- if (['tengu', 'tayra', 'staging', 'www'].map(s => `https://${s}.codecademy.com`).includes(origin)) {
28
- return origin;
29
- }
29
+ if (envs.some(s => `https://${s}.codecademy.com` === origin)) return origin;
30
30
 
31
- // for local, use local portal-app
32
- if (origin.includes('localhost')) {
33
- return origin.replace(/:\d{4}/, ':3100'); // replace if origin port is monolith or le
34
- }
31
+ // for local, use local portal-app, replace if origin port is monolith or le
32
+ if (origin.includes('localhost')) return origin.replace(/:\d{4}/, ':3100');
35
33
 
36
34
  // otherwise (e.g. in monolith pr env) use staging portal-app
37
35
  return 'https://staging.codecademy.com';
38
36
  }
39
- export function getSearchWorkerSrc() {
40
- const {
41
- search
42
- } = window.location;
37
+ export function serializeSearchWorkerSrc() {
43
38
  const BASE_URL = `${getPortalOrigin()}/api/portal/search`;
44
- return `
45
- const splitWords = /[ :-]/g;
39
+ const fnAsStr = worker.toString().trim();
46
40
 
47
- function getWordSet(str) {
48
- const words = str.split(splitWords);
49
- const filtered = words.map((w) => w.trim()).filter(Boolean);
50
- return new Set(filtered);
51
- }
41
+ // in a prod build, webpack will handle removing comments
52
42
 
53
- function preparseTitle({ value: title, popularity }) {
54
- const titleLower = title.toLowerCase();
55
- const titleWordSet = getWordSet(titleLower);
56
- return { title, titleLower, titleWordSet, popularity };
57
- }
43
+ return fnAsStr.slice(fnAsStr.indexOf('{') + 1, -1) // remove wrapping function, which may have been renamed by minification
44
+ .replaceAll(' ', '') // remove indentation
45
+ .replaceAll('{BASE_URL}', BASE_URL) // interpolate base url
46
+ .replaceAll('{SEARCH}', window.location.search); // interpolate search query
47
+ }
58
48
 
59
- async function preloadAutocompleteTitles() {
60
- const f = await fetch('${BASE_URL}/autocomplete-preload/${search}');
61
- const titles = await f.json();
62
- return titles.map(preparseTitle);
49
+ /*
50
+ * This function contains the code that is serialized to run in the worker. It
51
+ * can't reference anything outside of itself (except types). Data is passed to
52
+ * the worker via onmessage and passed back to the main thread via postMessage.
53
+ */
54
+ function worker() {
55
+ const preloadTitlesPromise = (async () => {
56
+ const f = await fetch('{BASE_URL}/autocomplete-preload{SEARCH}');
57
+ const rawTitles = await f.json();
58
+ return rawTitles.map(preparseTitle);
59
+ })();
60
+ function preparseTitle(_ref) {
61
+ let {
62
+ value,
63
+ popularity
64
+ } = _ref;
65
+ const lower = value.toLowerCase();
66
+ const words = getWordSet(lower);
67
+ return {
68
+ title: value,
69
+ lower,
70
+ words,
71
+ popularity
72
+ };
73
+ }
74
+ function preparseQuery(query) {
75
+ const words = getWordSet(query);
76
+ return {
77
+ query,
78
+ words
79
+ };
80
+ }
81
+ const wordSplitters = /[ :-]/g;
82
+ function getWordSet(str) {
83
+ const words = str.split(wordSplitters).map(w => w.trim()).filter(Boolean);
84
+ return new Set(words);
85
+ }
86
+ const handlers = {
87
+ autocomplete: autocompleteHandler,
88
+ 'search-as-you-type': searchAsYouTypeHandler
89
+ };
90
+ onmessage = _ref2 => {
91
+ let {
92
+ data
93
+ } = _ref2;
94
+ const {
95
+ query,
96
+ action
97
+ } = data;
98
+ const handler = handlers[action];
99
+ if (handler) {
100
+ handler(preparseQuery(query));
63
101
  }
102
+ };
103
+ function getScoredTitle(q, t) {
104
+ const charScores = getCharScores(q, t);
105
+ const score = getTotalScore(q, t, charScores);
106
+ return {
107
+ title: t.title,
108
+ charScores,
109
+ score
110
+ };
111
+ }
112
+ const maxResults = 5;
113
+ async function autocompleteHandler(q) {
114
+ const titles = await preloadTitlesPromise;
115
+ const scoredTitles = titles.map(t => getScoredTitle(q, t));
116
+ const topAutocompleteTitles = scoredTitles.filter(x => x.score > 0).sort((a, b) => a.score > b.score ? -1 : 1).slice(0, maxResults).map(t => ({
117
+ title: t.title,
118
+ segments: getHighlightSegments(t.title, t.charScores)
119
+ }));
120
+ postMessage({
121
+ query: q.query,
122
+ result: topAutocompleteTitles,
123
+ action: 'autocomplete'
124
+ });
125
+ }
126
+ async function searchAsYouTypeHandler(q) {
127
+ const f = await fetch('{BASE_URL}/search-as-you-type{SEARCH}', {
128
+ body: JSON.stringify({
129
+ query: q.query,
130
+ max: maxResults
131
+ }),
132
+ method: 'POST'
133
+ });
134
+ const searchAsYouTypeResults = await f.json();
135
+ for (const entry of searchAsYouTypeResults.top) {
136
+ const t = preparseTitle({
137
+ value: entry.title,
138
+ popularity: 0
139
+ });
140
+ const charScores = getCharScores(q, t);
141
+ entry.segments = getHighlightSegments(entry.title, charScores);
142
+ entry.key = q.query + ':' + entry.title;
143
+ }
144
+ postMessage({
145
+ query: q.query,
146
+ result: searchAsYouTypeResults,
147
+ action: 'search-as-you-type'
148
+ });
149
+ }
64
150
 
65
- // Used by autocomplete, both for finding top 5, and for highlighting
66
- // Used by search-as-you-type, only for highlighting
67
- // Returns number[], where each number is the match score for a char in the title
68
- function getTitleCharScores(query, queryWordSet, titleLower) {
69
- // prefill with an empty array for each character in title
70
- const overlap = Array(titleLower.length)
71
- .fill(0)
72
- .map(() => []);
73
-
74
- for (
75
- let queryShift = 1 - query.length;
76
- queryShift < titleLower.length;
77
- queryShift++
78
- ) {
79
- let cmc = null; // consecutive matching characters
80
- const startOverlap = Math.max(queryShift, 0);
81
- const endOverlap = Math.min(query.length + queryShift, titleLower.length);
82
- for (let i = startOverlap; i < endOverlap; i++) {
83
- if (query[i - queryShift] === titleLower[i] && titleLower[i] !== ' ') {
84
- if (!cmc) {
85
- // start a new cmc
86
- cmc = { str: '' };
87
- }
88
- // append this char to the current cmc
89
- cmc.str += query[i - queryShift];
90
- overlap[i].push(cmc);
91
- } else if (cmc) {
92
- cmc = null; // set to null so that the next match starts a new cmc
93
- }
94
- }
95
- }
151
+ /*
152
+ * For the search "alge", .04 is just low enough so that "Linear algebra"
153
+ * (which matches on 4 letters) comes in above "Data structures and algorithms"
154
+ * (which only matches on 3 letters, but has a high popularity score).
155
+ */
156
+ const popularityStrength = 0.04;
96
157
 
97
- const avgQueryWordLength = query.length / queryWordSet.size;
98
-
99
- // If avgQueryWordLength is 1-3, we want to the min match to be about that same size.
100
- // If avgQueryWordLength is longer, we want min match to be longer...but not too long.
101
- // e.g. For avgQueryWordLength of 9, min should be 5
102
- // The misspelling "regresion" should still match "regression", but not "encryption",
103
- // "authentication" or other words ending in "ion"
104
- const minMatchLength = Math.ceil(avgQueryWordLength ** 0.65);
105
-
106
- const titleCharScores = [];
107
- for (const cmcs of overlap) {
108
- let score = 0;
109
- for (const cmc of cmcs) {
110
- // if the string of consecutive matching chars meets the minMatchLength
111
- // or if it's a standalone word in the query (e.g "C")
112
- if (cmc.str.length >= minMatchLength || queryWordSet.has(cmc.str)) {
113
- score += cmc.str.length;
114
- }
115
- }
116
- titleCharScores.push(score);
158
+ // Total used in sorting to find autocomplet top 5
159
+ // Bonus scores are includes in certain cases
160
+ function getTotalScore(q, t, charScores) {
161
+ let fromChars = 0;
162
+ for (const s of charScores) {
163
+ fromChars += s;
164
+ }
165
+ const fromPopularity = (t.popularity || 0) * popularityStrength;
166
+ let bonus = 0;
167
+ // for each complete word present in both the title and query
168
+ for (const qw of q.words) {
169
+ if (t.words.has(qw)) {
170
+ bonus += 100;
117
171
  }
118
- return titleCharScores;
119
172
  }
120
173
 
121
- // Total used in sorting to find autocomplet top 5
122
- // Bonus scores are includes in certain cases
123
- function getTotalScore(
124
- query,
125
- queryWordSet,
126
- titleLower,
127
- titleWordSet,
128
- titleCharScores
129
- ) {
130
- let fromChars = 0;
131
- for (const s of titleCharScores) {
132
- fromChars += s;
133
- }
174
+ // if the title starts with the query
175
+ if (t.lower.startsWith(q.query)) {
176
+ bonus += 200;
177
+ } else if (t.lower.startsWith(q.query.slice(0, 3))) {
178
+ // or at least the first 3 chars
179
+ bonus += 100;
180
+ }
134
181
 
135
- let bonus = 0;
136
- // for each complete word present in both the title and query
137
- for (const qw of queryWordSet) {
138
- if (titleWordSet.has(qw)) {
139
- bonus += 100;
140
- }
141
- }
182
+ // if the title is an exact match with the query
183
+ if (t.lower === q.query) {
184
+ bonus += 100;
185
+ }
142
186
 
143
- // if the title starts with the query
144
- if (titleLower.startsWith(query)) {
145
- bonus += 100;
146
- }
187
+ // if there are some matching chars and the title is within 3 chars length of the query
188
+ if (fromChars > 1 && Math.abs(t.lower.length - q.query.length) <= 3) {
189
+ bonus += 100;
190
+ }
191
+ return fromChars + (fromChars > 1 ? fromPopularity : 0) + bonus;
192
+ }
147
193
 
148
- // if the title is an exact match with the query
149
- if (titleLower === query) {
150
- bonus += 100;
194
+ // returns { value: string, highlight: boolean }[]
195
+ function getHighlightSegments(title, charScores) {
196
+ let currentSegment = null;
197
+ const segments = [];
198
+ const shouldHighlight = i => charScores[i] > 0;
199
+ const isDifferentFromPrev = i => shouldHighlight(i - 1) !== shouldHighlight(i);
200
+ for (let i = 0; i < title.length; i++) {
201
+ if (i === 0 || isDifferentFromPrev(i)) {
202
+ // If this char should be highlighted, but the prev one should not
203
+ // or vice versa, start a new segment.
204
+ currentSegment = {
205
+ value: '',
206
+ highlight: shouldHighlight(i)
207
+ };
208
+ segments.push(currentSegment);
151
209
  }
152
-
153
- return fromChars + bonus;
210
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
211
+ currentSegment.value += title[i];
154
212
  }
213
+ return segments;
214
+ }
155
215
 
156
- // returns { value: string, highlight: boolean }[]
157
- function getHighlightSegments(title, titleCharScores) {
158
- let currentSegment = null;
159
- const segments = [];
216
+ // Used by autocomplete, both for finding top 5, and for highlighting
217
+ // Used by search-as-you-type, only for highlighting
218
+ // Returns number[], where each number is the match score for a char in the title
219
+ function getCharScores(q, t) {
220
+ /*
221
+ * Prefill the array for each char in the title.
222
+ * For each char, we keep an array of the consecutive matches the char is a part of.
223
+ */
224
+ const cmcsForTitleChars = Array(t.lower.length).fill(0).map(() => []);
160
225
 
161
- const shouldHighlight = (i) => titleCharScores[i] > 0;
226
+ /*
227
+ * Overlay the query onto the title to see which chars match.
228
+ * Shift to align at different positions.
229
+ * e.g.
230
+ * shift: 0
231
+ * query: python3 learn
232
+ * title: learn python 3
233
+ * (no matches)
234
+ *
235
+ * shift: 6
236
+ * query: python3 learn
237
+ * title: learn python 3
238
+ * (the word "python" matches)
239
+ *
240
+ * shift: 7
241
+ * query: python3 learn
242
+ * title: learn python 3
243
+ * ("3" matches)
244
+ *
245
+ * shift: -8
246
+ * query: python3 learn
247
+ * title: learn python 3
248
+ * ("learn" matches)
249
+ */
250
+ for (let shift = 1 - q.query.length; shift < t.lower.length; shift++) {
251
+ // for each shift position
162
252
 
163
- const isDifferentFromPrev = (i) =>
164
- shouldHighlight(i - 1) !== shouldHighlight(i);
253
+ let cmc = null;
254
+ const startOverlap = Math.max(shift, 0);
255
+ const endOverlap = Math.min(q.query.length + shift, t.lower.length);
165
256
 
166
- for (let i = 0; i < title.length; i++) {
167
- if (i === 0 || isDifferentFromPrev(i)) {
168
- // If this char should be highlighted, but the prev one should not
169
- // or vice versa, start a new segment.
170
- currentSegment = { value: '', highlight: shouldHighlight(i) };
171
- segments.push(currentSegment);
172
- }
173
- currentSegment.value += title[i];
174
- }
175
- return segments;
176
- }
257
+ // i is the index of a char in the title
258
+ for (let i = startOverlap; i < endOverlap; i++) {
259
+ // for each char position in the potentially overlapping area
177
260
 
178
- const preloadPromise = preloadAutocompleteTitles();
261
+ // if char at this position matches (and isn't a space)
262
+ if (q.query[i - shift] === t.lower[i] && t.lower[i] !== ' ') {
263
+ if (!cmc) {
264
+ // start a new cmc if needed
265
+ cmc = {
266
+ value: ''
267
+ };
268
+ }
179
269
 
180
- onmessage = ({ data }) => {
181
- const { action, query, max } = data;
182
- const queryWordSet = getWordSet(query);
183
- if (action === 'autocomplete') {
184
- processAutcomplete(query, queryWordSet, max);
185
- }
186
- if (action === 'search-as-you-type') {
187
- processSearchAsYouType(query, queryWordSet, max);
188
- }
189
- };
270
+ /*
271
+ * Append this char to the current cmc.
272
+ * We use an object with {value} so that we can modify by reference,
273
+ * since we want to modify the cmc, not only for this char, but also
274
+ * for any previous chars that this cmc was pushed to, since those
275
+ * chars are part of this same consecutive match.
276
+ */
277
+ cmc.value += q.query[i - shift];
190
278
 
191
- async function processAutcomplete(query, queryWordSet, max) {
192
- const autocompleteTitles = await preloadPromise;
193
-
194
- const scoredAutocompleteTitles = autocompleteTitles.map(
195
- ({ title, titleLower, titleWordSet, popularity }) => {
196
- const titleCharScores = getTitleCharScores(
197
- query,
198
- queryWordSet,
199
- titleLower
200
- );
201
- const titleScore = getTotalScore(
202
- query,
203
- queryWordSet,
204
- titleLower,
205
- titleWordSet,
206
- titleCharScores
207
- );
208
- return { title, titleCharScores, titleScore, popularity };
279
+ // include this cmc for this char
280
+ cmcsForTitleChars[i].push(cmc);
281
+ } else if (cmc) {
282
+ // set to null so that the next match starts a new cmc
283
+ cmc = null;
209
284
  }
210
- );
211
-
212
- /*
213
- * For the search "alge", .04 is just low enough so that "Linear algebra"
214
- * (which matches on 4 letters) comes in above "Data structures and algorithms"
215
- * (which only matches on 3 letters, but has a high popularity score).
216
- */
217
- const popularityStrength = 0.04;
218
-
219
- const topAutocompleteTitles = scoredAutocompleteTitles
220
- .filter((x) => x.titleScore > 0)
221
- .sort((a, b) =>
222
- a.titleScore + (a.popularity || 0) * popularityStrength >
223
- b.titleScore + (b.popularity || 0) * popularityStrength
224
- ? -1
225
- : 1
226
- )
227
- .slice(0, max)
228
- .map(({ title, titleCharScores }) => ({
229
- title,
230
- segments: getHighlightSegments(title, titleCharScores),
231
- key: query + ':' + title,
232
- }));
233
-
234
- postMessage({ query, topAutocompleteTitles });
285
+ }
235
286
  }
287
+ const avgQueryWordLength = q.query.length / q.words.size;
236
288
 
237
- async function processSearchAsYouType(query, queryWordSet, max) {
238
- const f = await fetch('${BASE_URL}/search-as-you-type/${search}', {
239
- body: JSON.stringify({ query, max }),
240
- method: 'POST',
241
- });
242
- const searchAsYouTypeResults = await f.json();
243
- for (const entry of searchAsYouTypeResults.top) {
244
- const charScores = getTitleCharScores(
245
- query,
246
- queryWordSet,
247
- entry.title.toLowerCase()
248
- );
249
- entry.segments = getHighlightSegments(entry.title, charScores);
250
- entry.key = query + ':' + entry.title;
289
+ // If avgQueryWordLength is 1-3, we want to the min match to be about that same size.
290
+ // If avgQueryWordLength is longer, we want min match to be longer...but not too long.
291
+ // e.g. For avgQueryWordLength of 9, min should be 5
292
+ // The misspelling "regresion" should still match "regression", but not "encryption",
293
+ // "authentication" or other words ending in "ion"
294
+ const minMatchLength = Math.ceil(avgQueryWordLength ** 0.65);
295
+ const charScores = [];
296
+ for (const cmcs of cmcsForTitleChars) {
297
+ let score = 0;
298
+ for (const cmc of cmcs) {
299
+ // if the string of consecutive matching chars meets the minMatchLength
300
+ // or if it's a standalone word in the query (e.g "C")
301
+ if (cmc.value.length >= minMatchLength || q.words.has(cmc.value)) {
302
+ score += cmc.value.length;
303
+ }
251
304
  }
252
- postMessage({ query, searchAsYouTypeResults });
305
+ charScores.push(score);
253
306
  }
254
- `;
307
+ return charScores;
308
+ }
255
309
  }
@@ -0,0 +1,32 @@
1
+ export type HighlightSegment = {
2
+ value: string;
3
+ highlight: boolean;
4
+ };
5
+ export type AutocompleteSuggestion = {
6
+ title: string;
7
+ segments: HighlightSegment[];
8
+ };
9
+ export type SearchAsYouTypeResults = {
10
+ query: string;
11
+ top: {
12
+ type: string;
13
+ title: string;
14
+ slug: string;
15
+ contentId?: string;
16
+ urlPath: string;
17
+ key: string;
18
+ segments: HighlightSegment[];
19
+ }[];
20
+ queryLoadTime: number;
21
+ searchId: string;
22
+ resultsCount: number;
23
+ };
24
+ export declare enum SearchAction {
25
+ Autocomplete = "autocomplete",
26
+ SearchAsYouType = "search-as-you-type"
27
+ }
28
+ export type SearchResultTypes = {
29
+ [SearchAction.Autocomplete]: AutocompleteSuggestion[];
30
+ [SearchAction.SearchAsYouType]: SearchAsYouTypeResults;
31
+ };
32
+ export type SearchWorker = <A extends SearchAction>(action: A, query: string) => Promise<SearchResultTypes[A]>;
@@ -0,0 +1,5 @@
1
+ export let SearchAction = /*#__PURE__*/function (SearchAction) {
2
+ SearchAction["Autocomplete"] = "autocomplete";
3
+ SearchAction["SearchAsYouType"] = "search-as-you-type";
4
+ return SearchAction;
5
+ }({});
@@ -0,0 +1,2 @@
1
+ import type { SearchWorker } from './types';
2
+ export declare function createSearchWorker(): SearchWorker;
@@ -0,0 +1,32 @@
1
+ import { PromiseLookup } from './PromiseLookup';
2
+ import { serializeSearchWorkerSrc } from './src';
3
+ const mockWorker = () => ({
4
+ onmessage: () => null,
5
+ postMessage: () => null
6
+ });
7
+ export function createSearchWorker() {
8
+ const src = serializeSearchWorkerSrc();
9
+ const blob = new Blob([src], {
10
+ type: 'text/javascript'
11
+ });
12
+ const dataUrl = URL.createObjectURL?.(blob);
13
+ const w = typeof Worker === 'undefined' ? mockWorker() : new Worker(dataUrl);
14
+ const results = new PromiseLookup({
15
+ onKeyInit: (action, query) => w.postMessage({
16
+ action,
17
+ query
18
+ })
19
+ });
20
+ w.onmessage = _ref => {
21
+ let {
22
+ data
23
+ } = _ref;
24
+ const {
25
+ query,
26
+ result,
27
+ action
28
+ } = data;
29
+ results.resolve(action, query, result);
30
+ };
31
+ return (action, query) => results.get(action, query);
32
+ }
@@ -1,7 +1,5 @@
1
1
  import { AppHeaderSearch } from './types';
2
- export declare const useHeaderSearch: ({ onEnable, onSearch, onTrackingClick, onSearchAsYouType, showQuiz, }: AppHeaderSearch & {
3
- showQuiz?: boolean;
4
- }) => readonly [{
2
+ export declare const useHeaderSearch: ({ onEnable, onSearch, onTrackingClick, onSearchAsYouType, }: AppHeaderSearch) => readonly [{
5
3
  readonly id: "search";
6
4
  readonly type: "render-element";
7
5
  readonly renderElement: () => import("react/jsx-runtime").JSX.Element;
@@ -8,8 +8,7 @@ export const useHeaderSearch = _ref => {
8
8
  onEnable,
9
9
  onSearch,
10
10
  onTrackingClick,
11
- onSearchAsYouType,
12
- showQuiz
11
+ onSearchAsYouType
13
12
  } = _ref;
14
13
  const [isSearchVisible, setIsSearchVisible] = useState(false);
15
14
  const searchButtonRef = useRef(null);
@@ -35,8 +34,7 @@ export const useHeaderSearch = _ref => {
35
34
  onTrackingClick: onTrackingClick,
36
35
  toggleSearch: toggleSearch,
37
36
  searchButtonRef: searchButtonRef,
38
- onSearchAsYouType: onSearchAsYouType,
39
- showQuiz: showQuiz
37
+ onSearchAsYouType: onSearchAsYouType
40
38
  })
41
39
  }, "search-content")];
42
40
  };
@@ -14,7 +14,6 @@ export type AppHeaderProps = AppHeaderAction & {
14
14
  */
15
15
  hideRightButtonDefaults?: boolean;
16
16
  isTeams?: boolean;
17
- showQuiz?: boolean;
18
17
  };
19
18
  export declare const StyledAppBar: import("@emotion/styled").StyledComponent<import("..").AppBarProps & {
20
19
  theme?: import("@emotion/react").Theme;
@@ -25,5 +24,5 @@ export declare const StyledNavBar: import("@emotion/styled").StyledComponent<{
25
24
  } & {
26
25
  theme?: import("@emotion/react").Theme;
27
26
  }, React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement>, {}>;
28
- export declare const mapItemToElement: (action: AppHeaderClickHandler, item: AppHeaderItem, isAnon: boolean, isTeams?: boolean, showQuiz?: boolean, redirectParam?: string, onKeyDown?: (event: React.KeyboardEvent) => void, mobile?: boolean) => ReactNode;
27
+ export declare const mapItemToElement: (action: AppHeaderClickHandler, item: AppHeaderItem, isAnon: boolean, isTeams?: boolean, redirectParam?: string, onKeyDown?: (event: React.KeyboardEvent) => void, mobile?: boolean) => ReactNode;
29
28
  export declare const AppHeader: React.FC<AppHeaderProps>;