Find a mentor

const PRIMARY_BOOST_MAP = (function () { var el = document.getElementById('primary-boost-map-data'); if (!el) return {}; try { return JSON.parse(el.textContent); } catch (e) { return {}; } })(); const PRIMARY_BOOST_SCORE = 3; const LOCATION_OPTIONAL_FILTERS = optionalFilters; function compactQueryKey(q) { return String(q || '').trim().toLowerCase().replace(/[\s\-_./,&'+]+/g, ''); } function primaryBoostExperimentOn() { // Gated by search-primary-boost PostHog flag (control = off, test = on). // Dataset is pinned sync from mc_ff before InstantSearch runs. try { return document.documentElement.dataset.searchPrimaryBoost === 'test'; } catch (e) { return false; } } function specialtyBoostFilters(query) { if (!primaryBoostExperimentOn()) return []; if (!query) return []; const cleaned = String(query).trim().replace(/\s+/g, ' '); if (!cleaned || cleaned.split(' ').length > 3) return []; const labels = PRIMARY_BOOST_MAP[compactQueryKey(cleaned)] || PRIMARY_BOOST_MAP[cleaned.toLowerCase()]; if (!labels || !labels.length) return []; return labels.map(function (label) { return 'primary_tags:' + label + ''; }); } function mergeBrowseOptionalFilters(query) { const specialty = specialtyBoostFilters(query); const base = LOCATION_OPTIONAL_FILTERS || []; if (!specialty.length) return base.length ? base : undefined; return base.concat(specialty); } const searchClient = { ...algoliaLiteClient, search(requests) { const tagged = requests.map(function (req) { const params = Object.assign({}, req.params || {}); const query = params.query || ''; const specialty = specialtyBoostFilters(query); const merged = mergeBrowseOptionalFilters(query); if (merged && merged.length) { params.optionalFilters = merged; } const tags = Array.isArray(params.analyticsTags) ? params.analyticsTags.slice() : ['web']; if (specialty.length && tags.indexOf('primary-boost') === -1) { tags.push('primary-boost'); } params.analyticsTags = tags; return Object.assign({}, req, { params: params }); }); return algoliaLiteClient.search(tagged); }, }; function googleAnalyticsMiddleware() { const sendEventDebounced = () => { gtag('event', 'page_view', { page_location: window.location.pathname + window.location.search, }); } return { onStateChange() { sendEventDebounced(); }, subscribe() {}, unsubscribe() {}, }; } // Persist session price override across router updates const PRICE_OVERRIDE = new URLSearchParams(window.location.search).get('price_override'); window.PRICE_OVERRIDE = PRICE_OVERRIDE; const search = instantsearch({ indexName: 'MentorProfile_prod', searchClient, routing: { router: instantsearch.routers.history({ windowTitle({ search, tags, company, location }) { // if search is all lowercase, titlecase it (every word capitalized) if (search) { search = search.toLowerCase().split(' ').map((s) => s.charAt(0).toUpperCase() + s.substring(1)).join(' '); } if (search) { return `Find ${search} mentors – MentorCruise` } else if (tags) { tags = tags?.split(',')[0] return `Find a ${tags} mentor – MentorCruise` } else if (company) { company = company?.split(',')[0] return `Find a mentor at ${company} – MentorCruise` } else if (location) { location = location?.split(',')[0] return `Find a mentor in ${location} – MentorCruise` } else return "Find a mentor – MentorCruise" }, }), stateMapping: { stateToRoute(uiState) { const indexUiState = uiState['MentorProfile_prod']; // only set min_price if it's not 0 // only set max_price if it has a value let min_price = indexUiState.range && indexUiState.range.all_prices?.split(':')[0]; if (min_price === '0' || min_price === '') { min_price = undefined; } let max_price = indexUiState.range && indexUiState.range.all_prices?.split(':')[1]; if (max_price === '') { max_price = undefined; } // Helper to return undefined for empty arrays (prevents ?param= in URL) const joinOrUndefined = (arr) => arr?.length ? arr.join(',') : undefined; return { search: indexUiState.query || undefined, tags: joinOrUndefined(indexUiState.refinementList?.tag_list_full_whitespace), language_list: joinOrUndefined(indexUiState.refinementList?.language_list), cleaned_job_title: joinOrUndefined(indexUiState.refinementList?.cleaned_job_title), location: joinOrUndefined(indexUiState.refinementList?.get_location_display), company: joinOrUndefined(indexUiState.refinementList?.company), services: joinOrUndefined(indexUiState.refinementList?.service_list), campaign: joinOrUndefined(indexUiState.refinementList?.marketing_campaigns), top_mentor: indexUiState.toggle && indexUiState.toggle.top_mentor ? 'true' : undefined, min_price: min_price, max_price: max_price, price_override: PRICE_OVERRIDE || undefined, // Route on bucket names, not raw UTC hours, so a shared link // recomputes for the recipient's own timezone. availability: availState.buckets.size ? [...availState.buckets].join(',') : undefined, weekends: availState.weekend ? 'true' : undefined }; }, routeToState(routeState) { return { ['MentorProfile_prod']: { query: routeState.search, refinementList: { tag_list_full_whitespace: routeState.tags ? routeState.tags.split(',') : [], language_list: routeState.language_list ? routeState.language_list.split(',') : [], cleaned_job_title: routeState.cleaned_job_title ? routeState.cleaned_job_title.split(',') : [], get_location_display: routeState.location ? routeState.location.split(',') : [], company: routeState.company ? routeState.company.split(',') : [], service_list: routeState.services ? routeState.services.split(',') : [], marketing_campaigns: routeState.campaign ? routeState.campaign.split(',') : [], }, toggle: { top_mentor: routeState.top_mentor === 'true', }, range: { all_prices: routeState.min_price && routeState.max_price ? `${routeState.min_price}:${routeState.max_price}` : null, }, }, }; }, } }, insights: { insightsInitParams: { useCookie: true, }, }, }); search.use(googleAnalyticsMiddleware); window.search = search; // Re-run InstantSearch when search-primary-boost flips after first paint // (posthog.onFeatureFlags). The search client reads the flag on every request. window.mcRefreshSearchOptionalFilters = function () { try { if (window.search && typeof window.search.refresh === 'function') { window.search.refresh(); } } catch (e) { /* InstantSearch not ready */ } }; // `company` is a free-text bio field, so the facet is dominated by noise: // generic non-companies ("Self-employed"), personal brands ("Coaching by // Darinka"), "ex-/former" duplicates of real employers ("Ex-Amazon"), // multi-company bios ("Agoda | ex Apple", "DocuSign, Oracle") and a long tail // of single-mentor entries. Recognizable employers are short, single names with // more than one mentor, so we filter to those. A currently-refined value is // always kept so a user's selection never disappears. Shared by both company // refinementList widgets. // // Note: this also applies to the searchable ("Search for companies") results, // so single-mentor companies are not findable there – an intentional trade-off // for a clean, trustworthy filter. const COMPANY_JUNK = new Set([ 'self-employed', 'self employed', 'freelance', 'freelancer', 'freelancing', 'various', 'multiple', 'n/a', 'na', 'none', 'other', 'independent', 'consultant', 'consulting', 'remote', 'student', 'unemployed', 'startup', 'stealth', 'stealth startup', 'confidential', 'private', 'self', ]); // Minimum mentors before a company is worth surfacing as a filter. const COMPANY_MIN_COUNT = 2; // Separators that signal a free-text bio rather than one company name. const COMPANY_SEPARATORS = /[|/,;•·]|\s-\s|\s@\s/; function filterCompanyItems(items) { return items.filter(i => { if (i.isRefined) return true; const raw = (i.label || '').trim(); if (!raw) return false; const l = raw.toLowerCase(); if (COMPANY_JUNK.has(l)) return false; // "ex-"/"former" prefixes just duplicate a real company name. if (/^(ex[-.\s]|former(ly)?\b|fmr\b)/.test(l)) return false; // Multi-company / descriptive bios. if (COMPANY_SEPARATORS.test(raw)) return false; // Real employers are short, not wordy descriptions. if (raw.length > 28) return false; if (raw.split(/\s+/).length > 4) return false; // Drop the single-mentor long tail. if ((i.count || 0) < COMPANY_MIN_COUNT) return false; return true; }); } // Read the token from the anon_session cookie at runtime rather than // server-rendering it, so the anonymous browse HTML stays identical for // every visitor and can be safely Redis-cached. The cookie is set by the // response, so it is available here even on a first (cached) visit. (function () { var m = document.cookie.match(/(?:^|;\s*)anon_session=([^;]+)/); var token = m ? decodeURIComponent(m[1]) : 'anon-' + Math.random().toString(36).slice(2); window.aa('setUserToken', token); })(); search.addWidgets([ instantsearch.widgets.configure({ clickAnalytics: true, // Separates browse searches from server-side ones (AI chat, MCP) in // Algolia Analytics; mentor/tag_demand.py reads this tag. analyticsTags: ['web'], optionalFilters: optionalFilters, // No widget mounts these facets, so declare them here for the helper's // addDisjunctiveFacetRefinement calls in applyAvailabilityRefinements. disjunctiveFacets: ['available_utc_hours', 'available_weekends'], }), instantsearch.widgets.searchBox({ container: '#searchbox', placeholder: "Search for any skill, title or company", searchAsYouType: true, showSubmit: false, showReset: false, showLoadingIndicator: false, cssClasses: { input: ['block w-full h-12 rounded border border-solid border-white bg-transparent py-2 pl-12 pr-3 text-white placeholder:text-white/80 focus:ring-2 focus:ring-brand-blue focus:border-brand-blue sm:text-base'] } }), instantsearch.widgets.refinementList({ attribute: 'marketing_campaigns', container: '#campaigns_listbox', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, cssClasses: { list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'], noResults: ['text-brand-light-text text-sm'], }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; }, }, }), instantsearch.widgets.infiniteHits({ container: '#infinite-hits', transformItems(items) { let max_price = search.renderState[Object.keys(search.renderState)[0]].range['all_prices'].start[1] return items.map(item => ({ ...item, price: (isFinite(max_price) && item.price > max_price) ? item.all_prices[0] : item.price, })); }, cssClasses: { disabledLoadMore: ['hidden'], disabledLoadPrevious: ['hidden'], }, templates: { item(hit, { html, components, sendEvent, }) { return html`
Top Mentor
Quick Responder
${hit.avg_rating_float_one_decimal}
(${hit.saved_rating_count} Review${hit.saved_rating_count === 1 ? '' : 's'})
${hit.headline}
${hit.bio_formatted ? hit.bio_formatted.slice(0, 200) + "..." : ""}
${hit?.tag_list?.map( (tag, index) => html`${tag}` )}
Bundle price
$${window.ACTIVE_BUNDLE?.total_price}
${window.ACTIVE_BUNDLE?.quantity ? 'for ' + window.ACTIVE_BUNDLE.quantity + ' sessions' : ''}
Starting from
${(function(){ var usd = (window.PRICE_OVERRIDE) ? window.PRICE_OVERRIDE : (hit.all_prices && hit.all_prices[0] ? hit.all_prices[0] : ''); if (!usd && usd !== 0) return ''; return (window.MC_formatPrice ? window.MC_formatPrice(usd) : ('$' + usd)); })()} ${(window.PRICE_OVERRIDE) ? '' : '/month'}
Save ${(hit.quarterly_discount * 100).toFixed(0)}% with a 3-month plan
Only ${hit.saved_open_spots} spot${hit.saved_open_spots === 1 ? '' : 's'} left
`; }, showMoreText(data, { html }) { return html`Show more`; }, showPreviousText(data, { html }) { return html`Show previous`; }, empty(results, { html }) { // The full no-results experience lives in #no-results-panel // (mentor-list-twocol.html), revealed by toggleNoResultsPanel // below. Render nothing here so the two don't stack. return html``; }, }, }), instantsearch.widgets.hitsPerPage({ container: '#hits-per-page', items: [ { label: HITS_PER_PAGE + ' hits per page', value: HITS_PER_PAGE, default: true }, ], }), instantsearch.widgets.stats({ container: '#hitcount', templates: { text(data, { html }) { let hits = data.nbHits; if (hits > 1000) { hits = "1,000+" } return html`${hits} mentors found`; }, }, }), instantsearch.widgets.stats({ container: '#hitcount-mobile', templates: { text(data, { html }) { let hits = data.nbHits; if (hits > 1000) { hits = "1,000+" } return html`${hits} mentors found`; }, }, }), instantsearch.widgets.stats({ container: '#hitcount-banner', templates: { text(data, { html }) { let hits = data.nbHits; if (hits < 4 && hits > 0) { return html`

Haven’t found what you need?

Submit this search and get notified about new matching mentors

`; } }, }, }), instantsearch.widgets.clearRefinements({ container: '#clear-refinements', includedAttributes: ["tag_list_full_whitespace", "service_list", "get_location_display", "company", "get_skills", "cleaned_job_title", "language_list", "marketing_campaigns"], templates: { resetLabel({ hasRefinements }, { html }) { return html`
Reset all filters
`; }, }, }), // ── Sidebar variant widgets ─────────────────────────────────────────── // The mentor list sidebar ships two mounts side-by-side: // `_max` → maximalist flat (default / control) // `_acc` → maximalist accordion (test variant, gated by the // `sidebar-variant` PostHog flag in mentor-list-twocol.html) // Both DOM trees render so every container exists at mount time; CSS // visibility decides which is shown to the user. Algolia syncs state // across the two via the helper, so toggling between them does not lose // refinements. // Refinement-list defaults (matches existing config in this file) instantsearch.widgets.refinementList({ container: '#skills_listbox_max', attribute: 'tag_list_full_whitespace', operator: 'and', limit: 6, showMoreLimit: 20, showMore: true, searchable: true, searchablePlaceholder: 'Search for skills', cssClasses: { searchableForm: ['py-2'], searchableInput: ['bg-transparent border border-solid border-brand-light-text-alternative text-brand-light-text placeholder-brand-light-text-alternative text-sm py-2 px-2 focus:ring-brand-green focus:border-brand-green block w-full rounded-md mb-0'], searchableSubmit: ['hidden'], searchableReset: ['hidden'], searchableLoadingIndicator: ['hidden'], list: ['pt-2'], showMore: ['pt-1 pb-2 text-sm cursor-pointer font-semibold text-brand-light-text'], disabledShowMore: ['hidden'], noResults: ['text-brand-light-text text-sm'], }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, }), instantsearch.widgets.refinementList({ container: '#job_titles_listbox_max', attribute: 'cleaned_job_title', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, searchable: true, searchablePlaceholder: 'Search for job titles', cssClasses: { searchableForm: ['py-2'], searchableInput: ['bg-transparent border border-solid border-brand-light-text-alternative text-brand-light-text placeholder-brand-light-text-alternative text-sm py-2 px-2 focus:ring-brand-green focus:border-brand-green block w-full rounded-md mb-0'], searchableSubmit: ['hidden'], searchableReset: ['hidden'], searchableLoadingIndicator: ['hidden'], list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'], noResults: ['text-brand-light-text text-sm'], }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, }), instantsearch.widgets.refinementList({ container: '#companies_listbox_max', attribute: 'company', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, searchable: true, searchablePlaceholder: 'Search for companies', cssClasses: { searchableForm: ['py-2'], searchableInput: ['bg-transparent border border-solid border-brand-light-text-alternative text-brand-light-text placeholder-brand-light-text-alternative text-sm py-2 px-2 focus:ring-brand-green focus:border-brand-green block w-full rounded-md mb-0'], searchableSubmit: ['hidden'], searchableReset: ['hidden'], searchableLoadingIndicator: ['hidden'], list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'], noResults: ['text-brand-light-text text-sm'], }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, transformItems: filterCompanyItems, }), instantsearch.widgets.refinementList({ container: '#languages_listbox_max', attribute: 'language_list', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, cssClasses: { list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'] }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, }), instantsearch.widgets.refinementList({ container: '#countries_listbox_max', attribute: 'get_location_display', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, cssClasses: { list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'] }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, transformItems(items) { return items.map(i => { if (i.label === "United States of America") { i.label = "United States"; } return i; }); }, }), instantsearch.widgets.rangeInput({ container: '#price_input_max', attribute: 'all_prices', min: 0, templates: { separatorText: 'to', submitText: 'Apply', }, cssClasses: { submit: ['light-btn', 'small', 'h-10'] }, }), instantsearch.widgets.toggleRefinement({ container: '#topmentor_max', attribute: 'top_mentor', cssClasses: { checkbox: ['form-checkbox border-solid focus:ring-brand-green h-4 w-4 text-brand-green border-brand-light-text-alternative rounded'] }, templates: { labelText({ count }, { html }) { return html`Only top mentors`; } }, }), instantsearch.widgets.toggleRefinement({ container: '#inquiryonly_max', attribute: 'open_to_inquiries', cssClasses: { checkbox: ['form-checkbox border-solid focus:ring-brand-green h-4 w-4 text-brand-green border-brand-light-text-alternative rounded'] }, templates: { labelText({ count }, { html }) { return html`Open to inquiries`; } }, }), instantsearch.widgets.refinementList({ container: '#skills_listbox_acc', attribute: 'tag_list_full_whitespace', operator: 'and', limit: 6, showMoreLimit: 20, showMore: true, searchable: true, searchablePlaceholder: 'Search for skills', cssClasses: { searchableForm: ['py-2'], searchableInput: ['bg-transparent border border-solid border-brand-light-text-alternative text-brand-light-text placeholder-brand-light-text-alternative text-sm py-2 px-2 focus:ring-brand-green focus:border-brand-green block w-full rounded-md mb-0'], searchableSubmit: ['hidden'], searchableReset: ['hidden'], searchableLoadingIndicator: ['hidden'], list: ['pt-2'], showMore: ['pt-1 pb-2 text-sm cursor-pointer font-semibold text-brand-light-text'], disabledShowMore: ['hidden'], noResults: ['text-brand-light-text text-sm'], }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, }), instantsearch.widgets.refinementList({ container: '#job_titles_listbox_acc', attribute: 'cleaned_job_title', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, searchable: true, searchablePlaceholder: 'Search for job titles', cssClasses: { searchableForm: ['py-2'], searchableInput: ['bg-transparent border border-solid border-brand-light-text-alternative text-brand-light-text placeholder-brand-light-text-alternative text-sm py-2 px-2 focus:ring-brand-green focus:border-brand-green block w-full rounded-md mb-0'], searchableSubmit: ['hidden'], searchableReset: ['hidden'], searchableLoadingIndicator: ['hidden'], list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'], noResults: ['text-brand-light-text text-sm'], }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, }), instantsearch.widgets.refinementList({ container: '#companies_listbox_acc', attribute: 'company', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, searchable: true, searchablePlaceholder: 'Search for companies', cssClasses: { searchableForm: ['py-2'], searchableInput: ['bg-transparent border border-solid border-brand-light-text-alternative text-brand-light-text placeholder-brand-light-text-alternative text-sm py-2 px-2 focus:ring-brand-green focus:border-brand-green block w-full rounded-md mb-0'], searchableSubmit: ['hidden'], searchableReset: ['hidden'], searchableLoadingIndicator: ['hidden'], list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'], noResults: ['text-brand-light-text text-sm'], }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, transformItems: filterCompanyItems, }), instantsearch.widgets.refinementList({ container: '#languages_listbox_acc', attribute: 'language_list', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, cssClasses: { list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'] }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, }), instantsearch.widgets.refinementList({ container: '#countries_listbox_acc', attribute: 'get_location_display', operator: 'or', limit: 6, showMoreLimit: 20, showMore: true, cssClasses: { list: ['pt-2'], showMore: ['pt-1 pb-2 cursor-pointer text-sm font-semibold text-brand-light-text'], disabledShowMore: ['hidden'] }, templates: { item(item, { html }) { const { url, label, count, isRefined } = item; return html`
${ label === label.toLowerCase() ? label.charAt(0).toUpperCase() + label.slice(1) : label }
${count} 1k+
`; } }, transformItems(items) { return items.map(i => { if (i.label === "United States of America") { i.label = "United States"; } return i; }); }, }), instantsearch.widgets.rangeInput({ container: '#price_input_acc', attribute: 'all_prices', min: 0, templates: { separatorText: 'to', submitText: 'Apply', }, cssClasses: { submit: ['light-btn', 'small', 'h-10'] }, }), // Active refinements rendered as removable chips at the top of the // accordion sidebar so users always see what's applied (the accordion // sections collapse, so without this the only signal is the `N selected` // header badge). // `all_prices` is filtered out when values still match the rangeInput // bounds (PRICE_DEFAULT_MIN/MAX) – Algolia treats those as active // refinements from page load, but to the user they're just defaults // until they change them. instantsearch.widgets.currentRefinements({ container: '#current_refinements_acc', includedAttributes: [ 'tag_list_full_whitespace', 'cleaned_job_title', 'company', 'language_list', 'get_location_display', 'top_mentor', 'open_to_inquiries', 'all_prices', ], transformItems(items) { const labels = { tag_list_full_whitespace: 'Skill', cleaned_job_title: 'Job', company: 'Company', language_list: 'Language', get_location_display: 'Country', top_mentor: 'Top mentor', open_to_inquiries: 'Open to inquiries', all_prices: 'Price', }; return items .map(item => { if (item.attribute === 'all_prices') { const custom = (item.refinements || []).filter(r => !((r.operator === '>=' && r.value === PRICE_DEFAULT_MIN) || (r.operator === '<=' && r.value === PRICE_DEFAULT_MAX)) ); if (custom.length === 0) return null; return { ...item, refinements: custom, label: labels[item.attribute] }; } return { ...item, label: labels[item.attribute] || item.label }; }) .filter(Boolean); }, }), // ── No-results recovery panel widgets ───────────────────────────────── // These mount into #no-results-panel (mentor-list-twocol.html), which is // hidden until the render hook below detects nbHits === 0. They give the // user a way out of the dead-end: remove an individual filter (chips) or // clear them all. Config mirrors the accordion currentRefinements / // #clear-refinements widgets above. instantsearch.widgets.currentRefinements({ container: '#no-results-current-refinements', includedAttributes: [ 'tag_list_full_whitespace', 'cleaned_job_title', 'company', 'language_list', 'get_location_display', 'top_mentor', 'open_to_inquiries', 'all_prices', ], transformItems(items) { const labels = { tag_list_full_whitespace: 'Skill', cleaned_job_title: 'Job', company: 'Company', language_list: 'Language', get_location_display: 'Country', top_mentor: 'Top mentor', open_to_inquiries: 'Open to inquiries', all_prices: 'Price', }; return items .map(item => { if (item.attribute === 'all_prices') { const custom = (item.refinements || []).filter(r => !((r.operator === '>=' && r.value === PRICE_DEFAULT_MIN) || (r.operator === '<=' && r.value === PRICE_DEFAULT_MAX)) ); if (custom.length === 0) return null; return { ...item, refinements: custom, label: labels[item.attribute] }; } return { ...item, label: labels[item.attribute] || item.label }; }) .filter(Boolean); }, }), instantsearch.widgets.toggleRefinement({ container: '#topmentor_acc', attribute: 'top_mentor', cssClasses: { checkbox: ['form-checkbox border-solid focus:ring-brand-green h-4 w-4 text-brand-green border-brand-light-text-alternative rounded'] }, templates: { labelText({ count }, { html }) { return html`Only top mentors`; } }, }), instantsearch.widgets.toggleRefinement({ container: '#inquiryonly_acc', attribute: 'open_to_inquiries', cssClasses: { checkbox: ['form-checkbox border-solid focus:ring-brand-green h-4 w-4 text-brand-green border-brand-light-text-alternative rounded'] }, templates: { labelText({ count }, { html }) { return html`Open to inquiries`; } }, }), instantsearch.widgets.analytics({ pushFunction(formattedParameters, state, _) { if (state.query) { window.setTimeout(function() { Beacon('show-message', 'fe7e8abc-aac8-44e8-b700-876fad6fc40d') }, 10000); } posthog.capture("mentor searched (frontend)", properties = { 'search': state.query, 'tags': state.facetsRefinements.tag_list_full_whitespace, 'languages': state.facetsRefinements.language_list, 'companies': state.disjunctiveFacetsRefinements.company, 'countries': state.disjunctiveFacetsRefinements.get_location_display, 'services': state.facetsRefinements.service_list, }) } }), ]); search.start(); // ── Availability control wiring ──────────────────────────────────────────── // The checkboxes live outside any InstantSearch widget container (so they are // never wiped on render). Both sidebar variants render simultaneously and CSS // hides one, so we bind to ALL .js-avail inputs and keep them in sync off the // single shared availState. Refinements are applied directly via the helper. function applyAvailabilityRefinements(doSearch = true) { const helper = window.search.helper; helper.clearRefinements('available_utc_hours'); const hours = new Set(); availState.buckets.forEach(k => bucketToUtcHours(k).forEach(h => hours.add(h))); hours.forEach(h => helper.addDisjunctiveFacetRefinement('available_utc_hours', h)); helper.clearRefinements('available_weekends'); if (availState.weekend) helper.addDisjunctiveFacetRefinement('available_weekends', true); if (doSearch) helper.search(); refreshSidebarCounts(); renderAvailabilityChips(); } function syncAvailabilityCheckboxes() { document.querySelectorAll('.js-avail').forEach(cb => { const k = cb.getAttribute('data-avail'); cb.checked = k === 'weekends' ? availState.weekend : availState.buckets.has(k); }); } // Human labels + display order for the active-availability chips. The stock // currentRefinements widget can't represent these (one bucket expands to // several raw UTC-hour refinements that can't be reverse-mapped to a bucket), // so we render our own chips from availState, styled to match. const AVAIL_LABELS = { mornings: 'Mornings', daytime: 'During the day', evenings: 'Evenings', night: 'During the night', weekends: 'Weekends', }; const AVAIL_CHIP_ORDER = ['mornings', 'daytime', 'evenings', 'night', 'weekends']; function renderAvailabilityChips() { const box = document.getElementById('availability_refinements_acc'); if (!box) return; const selected = AVAIL_CHIP_ORDER.filter(k => k === 'weekends' ? availState.weekend : availState.buckets.has(k) ); if (!selected.length) { box.innerHTML = ''; return; } box.innerHTML = ''; } // One delegated listener handles chip removals across re-renders. (function bindAvailabilityChipRemoval() { const box = document.getElementById('availability_refinements_acc'); if (!box) return; box.addEventListener('click', (e) => { const btn = e.target.closest('[data-avail-remove]'); if (!btn) return; const k = btn.getAttribute('data-avail-remove'); if (k === 'weekends') { availState.weekend = false; } else { availState.buckets.delete(k); } syncAvailabilityCheckboxes(); applyAvailabilityRefinements(); }); })(); // Gated behind the `availability-filter` PostHog flag (variant `test`). The // data attribute is set by the synchronous cache read at the top of // mentor-list-twocol.html and reconciled in its posthog.onFeatureFlags handler, // which calls this again once the flag lands for first-time users. Idempotent. let _availInited = false; function initAvailabilityControl() { if (_availInited) return; if (document.documentElement.dataset.availabilityFilter !== 'test') return; _availInited = true; const tzName = (Intl.DateTimeFormat().resolvedOptions().timeZone) || 'UTC'; function renderTz() { // Lowercase 12-hour, no leading zero (e.g. "1:48 pm") to match the // am/pm range labels below. const t = new Date().toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }).toLowerCase(); document.querySelectorAll('.js-avail-tz').forEach(el => { el.textContent = `${tzName} · ${t}`; }); } renderTz(); setInterval(renderTz, 60000); document.querySelectorAll('.js-avail').forEach(cb => { cb.addEventListener('change', () => { const k = cb.getAttribute('data-avail'); if (k === 'weekends') { availState.weekend = cb.checked; } else if (cb.checked) { availState.buckets.add(k); } else { availState.buckets.delete(k); } syncAvailabilityCheckboxes(); applyAvailabilityRefinements(); }); }); // Restore from a shared URL (?availability=evenings,daytime&weekends=true). // Buckets are recomputed to the current viewer's timezone on apply. const params = new URLSearchParams(window.location.search); const availParam = params.get('availability'); if (availParam) availParam.split(',').forEach(k => { if (AVAIL_BUCKETS[k]) availState.buckets.add(k); }); if (params.get('weekends') === 'true') availState.weekend = true; if (availState.buckets.size || availState.weekend) { syncAvailabilityCheckboxes(); applyAvailabilityRefinements(); } } // Expose so the posthog.onFeatureFlags handler can wire it once the flag lands // for first-time users (returning users are handled by the synchronous read). window.initAvailabilityControl = initAvailabilityControl; initAvailabilityControl(); // Alpine store powering the "N selected" badges shown next to each closed // accordion section header in #sidebar-accordion. Populated from Algolia // helper state on every render so it stays in sync with both checkbox // clicks and URL state restoration. document.addEventListener('alpine:init', () => { Alpine.store('sidebar', { counts: { skills: 0, jobs: 0, companies: 0, languages: 0, countries: 0, availability: 0, quick: 0, price: 0 }, hasRefinements: false, }); }); function refreshSidebarCounts() { if (typeof Alpine === 'undefined' || !Alpine.store('sidebar')) return; const state = window.search?.helper?.state; if (!state) return; const fr = state.facetsRefinements || {}; const dfr = state.disjunctiveFacetsRefinements || {}; // Reconcile availability checkboxes when the helper refinements were cleared // externally (e.g. a "clear all" widget) but availState still shows them. const helperHasAvail = (dfr.available_utc_hours || []).length || (dfr.available_weekends || []).length; if (!helperHasAvail && (availState.buckets.size || availState.weekend)) { availState.buckets.clear(); availState.weekend = false; syncAvailabilityCheckboxes(); } const nr = state.numericRefinements || {}; const len = (v) => Array.isArray(v) ? v.length : 0; const priceMins = (nr.all_prices && nr.all_prices['>=']) || []; const priceMaxs = (nr.all_prices && nr.all_prices['<=']) || []; const hasCustomPriceMin = priceMins.some(v => v !== PRICE_DEFAULT_MIN); const hasCustomPriceMax = priceMaxs.some(v => v !== PRICE_DEFAULT_MAX); const store = Alpine.store('sidebar'); const c = store.counts; c.skills = len(fr.tag_list_full_whitespace); c.jobs = len(dfr.cleaned_job_title); c.companies = len(dfr.company); c.languages = len(dfr.language_list) || len(fr.language_list); c.countries = len(dfr.get_location_display); c.quick = len(dfr.top_mentor) + len(dfr.open_to_inquiries) + len(fr.top_mentor) + len(fr.open_to_inquiries); c.price = (hasCustomPriceMin || hasCustomPriceMax) ? 1 : 0; c.availability = availState.buckets.size + (availState.weekend ? 1 : 0); store.hasRefinements = c.skills + c.jobs + c.companies + c.languages + c.countries + c.availability + c.quick + c.price > 0; // Render the availability chips here (after the clear-all reconcile above) // so they reflect the just-reconciled availState, not a stale value. renderAvailabilityChips(); } window.search.on('render', refreshSidebarCounts); // ── Search result tracking ───────────────────────────────────────────────── // Impressions and clicks per search term feed the mentor's per-term CTR. // The term is the first skill refinement, then job title, then the query. function mcSearchTerm() { const state = window.search?.helper?.state; return ( state?.facetsRefinements?.tag_list_full_whitespace?.[0] || state?.disjunctiveFacetsRefinements?.cleaned_job_title?.[0] || state?.query || '' ).toLowerCase().trim(); } (function bindSearchTracking() { // searchAsYouType renders on every keystroke. Waiting for results to // settle keeps partial queries ("reac") out of the term stats. const SETTLE_MS = 700; const sent = new Set(); let settleTimer = null; function fireImpression(card) { const path = card.dataset.mcTrack; const term = card.dataset.mcTerm || ''; const key = path + '|' + term; if (!path || sent.has(key)) return; sent.add(key); const params = new URLSearchParams({ position: card.dataset.mcPosition || '0', term: term }); fetch(path + '?' + params.toString(), { keepalive: true }).catch(() => {}); } const observer = 'IntersectionObserver' in window ? new IntersectionObserver((entries) => { entries.forEach((entry) => { if (!entry.isIntersecting) return; observer.unobserve(entry.target); fireImpression(entry.target); }); }, { rootMargin: '0px 0px 300px 0px' }) : null; function observeCards() { const term = mcSearchTerm(); document.querySelectorAll('#infinite-hits [data-mc-track]').forEach((card) => { const path = card.dataset.mcTrack; if (!path) return; // Preact reuses card nodes across renders, so key on what the // node shows now rather than on the node itself. const seen = path + '|' + term; if (card.dataset.mcSeen === seen) return; card.dataset.mcSeen = seen; card.dataset.mcTerm = term; if (observer) { observer.unobserve(card); observer.observe(card); } else { fireImpression(card); } }); } // One demand beacon per settled search, including searches that found // nobody: the only place unmet browse demand is recorded. const sentSearches = new Set(); function fireSearchDemand() { const term = mcSearchTerm(); const results = window.search?.helper?.lastResults; if (!term || !results || sentSearches.has(term)) return; sentSearches.add(term); const params = new URLSearchParams({ term: term, hits: String(results.nbHits || 0) }); fetch('/mentor/search/demand/?' + params.toString(), { keepalive: true }).catch(() => {}); } window.search.on('render', () => { clearTimeout(settleTimer); settleTimer = setTimeout(() => { observeCards(); fireSearchDemand(); }, SETTLE_MS); }); function fireClick(event) { if (event.type === 'auxclick' && event.button !== 1) return; const link = event.target.closest('a'); const card = link && link.closest('[data-mc-track]'); if (!card || !card.dataset.mcTrack) return; const params = new URLSearchParams({ term: card.dataset.mcTerm || mcSearchTerm(), source: 'search', }); const url = card.dataset.mcTrack + 'click/?' + params.toString(); if (!(navigator.sendBeacon && navigator.sendBeacon(url))) { fetch(url, { method: 'POST', keepalive: true }).catch(() => {}); } } const hitsRoot = document.getElementById('infinite-hits'); if (hitsRoot) { hitsRoot.addEventListener('click', fireClick); hitsRoot.addEventListener('auxclick', fireClick); } })(); // Full reset for the no-results panel: clears the search query AND every // refinement, then re-runs the search. The query is NOT a facet refinement, so // clearRefinements alone can't undo a gibberish query that returns nothing – // setQuery('') is required. The reset-selection event resets the Alpine // sidebar counters; availability checkboxes / price inputs reconcile on the // next render (see refreshSidebarCounts). function clearNoResultsSearch() { if (!window.search || !window.search.helper) return; window.search.helper.setQuery('').clearRefinements().search(); window.dispatchEvent(new CustomEvent('reset-selection')); } // Reveal the no-results recovery panel (#no-results-panel) when a search comes // back empty, hide the regular hits list so the two empty states don't stack, // and render the active query + filters as removable chips so the user always // has a one-tap way back to results. function renderNoResultsPanel() { const panel = document.getElementById('no-results-panel'); if (!panel) return; const helper = window.search && window.search.helper; const results = helper && helper.lastResults; const noResults = !!results && results.nbHits === 0; panel.classList.toggle('hidden', !noResults); const hits = document.getElementById('infinite-hits'); if (hits) hits.classList.toggle('hidden', noResults); if (!noResults) return; // Render the active query as a removable chip (built via DOM nodes so the // user-controlled query string can't inject markup). const query = (helper && helper.state && helper.state.query) || ''; const queryBox = document.getElementById('no-results-query'); if (queryBox) { queryBox.innerHTML = ''; if (query) { const chip = document.createElement('span'); chip.className = 'query-chip'; chip.appendChild(document.createTextNode('Search: “' + query + '”')); const btn = document.createElement('button'); btn.type = 'button'; btn.setAttribute('aria-label', 'Clear search term'); btn.textContent = '×'; btn.onclick = function () { window.search.helper.setQuery('').search(); }; chip.appendChild(btn); queryBox.appendChild(chip); } } const hasChips = panel.querySelectorAll('#no-results-current-refinements .ais-CurrentRefinements-item').length > 0; const hasSomething = hasChips || !!query; const filterBlock = document.getElementById('no-results-has-filters'); if (filterBlock) filterBlock.classList.toggle('hidden', !hasSomething); const resetBtn = document.getElementById('no-results-reset'); if (resetBtn) resetBtn.classList.toggle('hidden', !hasSomething); } window.search.on('render', renderNoResultsPanel); // Set a week-long cookie when the 'lockin' marketing campaign is active (function() { const ONE_WEEK_SECONDS = 7 * 24 * 60 * 60; function setCampaignCookieIfLockinActive() { try { const state = window.search?.helper?.state; const campaigns = state?.disjunctiveFacetsRefinements?.marketing_campaigns || state?.facetsRefinements?.marketing_campaigns || []; if (Array.isArray(campaigns) && campaigns.includes('lockin')) { document.cookie = `mc_campaign=lockin; max-age=${ONE_WEEK_SECONDS}; path=/`; } } catch (e) {} } // initial check (also covers direct URL with ?campaign=lockin) setCampaignCookieIfLockinActive(); // keep it in sync on every render window.search.on('render', setCampaignCookieIfLockinActive); })(); // Proactively refine by campaign URL parameter if present (helps when routing state hasn't applied yet) (function() { try { const params = new URLSearchParams(window.location.search); const urlCampaign = params.get('campaign'); if (urlCampaign) { // set cookie immediately if lockin via URL param if (urlCampaign === 'lockin') { const ONE_WEEK_SECONDS = 7 * 24 * 60 * 60; document.cookie = `mc_campaign=lockin; max-age=${ONE_WEEK_SECONDS}; path=/`; } const hasRefinement = (window.search?.helper?.state?.disjunctiveFacetsRefinements?.marketing_campaigns || []).includes(urlCampaign); if (!hasRefinement) { window.search.helper .addDisjunctiveFacetRefinement('marketing_campaigns', urlCampaign) .search(); } } } catch (e) {} })();