Rewild Your Web
web browser dweb
at main 86 lines 2.0 kB view raw
1// SPDX-License-Identifier: AGPL-3.0-or-later 2 3const PREF_NAME = "browserhtml.search_engine"; 4 5// Load the default search engines resource. 6import ENGINES from "//shared.localhost:8888/search/default_engines.json" with { type: "json" }; 7 8export default class SearchEngines extends EventTarget { 9 constructor() { 10 super(); 11 this.currentEngine = null; 12 this.engines = ENGINES; 13 } 14 15 async ensureReady() { 16 if (this.currentEngine) { 17 return; 18 } 19 20 // Check if the preference matches an existing engine. If not, reset to the 21 // first engine. 22 let prefEngine = navigator.servo.getStringPreference(PREF_NAME); 23 console.log(`search engine in prefs: ${prefEngine}`); 24 let engine = this.engines.find((engine) => { 25 return engine.id == prefEngine; 26 }); 27 28 if (!engine) { 29 engine = this.engines[0]; 30 navigator.servo.setStringPreference(PREF_NAME, engine.id); 31 } 32 this.currentEngine = engine; 33 34 console.log(`current engine: ${this.currentEngine.name}`); 35 36 this.dispatchCurrentEngine(); 37 38 navigator.embedder.addEventListener( 39 "preferencechanged", 40 this.onPrefChange.bind(this), 41 ); 42 } 43 44 set(engineId) { 45 if (!this.engines) { 46 return; 47 } 48 49 let engine = this.engines.find((engine) => { 50 return engine.id == engineId; 51 }); 52 if (!engine) { 53 console.error(`Unknown search engine: ${engineId}`); 54 return; 55 } 56 this.currentEngine = engine; 57 this.dispatchCurrentEngine(); 58 } 59 60 onPrefChange(event) { 61 if (event.detail.name !== PREF_NAME) { 62 return; 63 } 64 this.set(event.detail.value); 65 } 66 67 dispatchCurrentEngine() { 68 if (!this.currentEngine) { 69 return; 70 } 71 72 let event = new CustomEvent("engine", { detail: this.currentEngine }); 73 this.dispatchEvent(event); 74 } 75 76 queryUrl(text) { 77 if (!this.currentEngine) { 78 return null; 79 } 80 81 return this.currentEngine["template"].replace( 82 "{searchTerms}", 83 encodeURIComponent(text), 84 ); 85 } 86}