file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
lib/portable_text/parser.rb
Ruby
module PortableText class UnknownTypeError < StandardError end class Parser def parse(json) elements = ensure_array(json) create_chunks(elements).map do |chunk| if List.list_item?(chunk.first) create_list(chunk) else Block.from_json(chunk.first) end end end private attr_reader :serializer_registry def ensure_array(input) input.is_a?(Array) ? input : [input] end # Adjacent list items need to be "chunked" into a single list, while blocks are standalone def create_chunks(elements) last_started_list_type = nil elements.chunk_while do |e1, e2| if List.list_item?(e1) && List.list_item?(e2) last_started_list_type = e1["listItem"] if last_started_list_type.nil? e2_level = e2["level"] || List.default_level if e2_level > 1 || (e2_level == 1 && e2["listItem"] == last_started_list_type) true else last_started_list_type = e2["listItem"] false end else last_started_list_type = nil false end end end def list_items?(e1, e2) List.list_item?(e1) && List.list_item?(e2) end def create_list(elements) blocks = elements.map { |e| Block.from_json(e) } List.new(blocks) end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/renderable.rb
Ruby
module PortableText module Renderable def to_html(wrapping_html = nil) raise NotImplementedError, "#{self.class} must implement #to_html" end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/renderer.rb
Ruby
module PortableText class Renderer def render(input) blocks = parser.parse(input) html = blocks.map(&:to_html).join return html if blocks.length <= 1 serializer.call(html) end private def parser Parser.new end def serializer Serializer::HTMLElement.new("div") end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/base.rb
Ruby
module PortableText module Serializer class Base def call(inner_html, data = nil) raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/html_element.rb
Ruby
require_relative "base" module PortableText module Serializer class HTMLElement < Base def initialize(tag) @tag = tag end def call(inner_html, _data = nil) "<#{@tag}>#{inner_html}</#{@tag}>" end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/image.rb
Ruby
require_relative "base" module PortableText module Serializer class Image < Base def initialize(base_url) @base_url = base_url end def call(_inner_html, data) src = image_url(data) if data.dig("_internal", "inline") image_html(src) else figure_html(image_html(src)) end end private def image_html(src) "<img src=\"#{src}\"/>" end def image_url(data) return data["asset"]["url"] if data["asset"]["url"] parts = image_parts(data["asset"]["_ref"]) id = parts[0] dimensions = parts[1] ext = parts[2] "#{@base_url}/#{id}-#{dimensions}.#{ext}" end def image_parts(image_ref) image_ref.split("-").drop(1) end def figure_html(inner_html) "<figure>#{inner_html}</figure>" end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/link.rb
Ruby
require_relative "base" module PortableText module Serializer class Link < Base def call(inner_html, data = nil) "<a href=\"#{data["href"]}\">#{inner_html}</a>" end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/list_item.rb
Ruby
require_relative "base" module PortableText module Serializer class ListItem < Base def call(inner_html, data) list_tag(with_styles(inner_html, data["style"])) end private def with_styles(inner_html, style) if style && style != "normal" apply_styles(inner_html, style) else inner_html end end def apply_styles(text, style) "<#{style}>#{text}</#{style}>" end def list_tag(inner_html) "<li>#{inner_html}</li>" end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/registry.rb
Ruby
module PortableText module Serializer class Registry def initialize(base_image_url:, on_missing_serializer: -> {}) @base_image_url = base_image_url @on_missing_serializer = on_missing_serializer @serializers = default_serializers end def get(key, fallback:, ctx: nil) serializer = @serializers[key&.to_sym] unless serializer @on_missing_serializer&.call(key, ctx) end serializer || @serializers[fallback&.to_sym] end def register(key, serializer) @serializers[key.to_sym] = serializer end def reset @serializers = default_serializers end private def default_serializers { ul: Serializer::HTMLElement.new("ul"), ol: Serializer::HTMLElement.new("ol"), li: Serializer::ListItem.new, normal: Serializer::HTMLElement.new("p"), h1: Serializer::HTMLElement.new("h1"), h2: Serializer::HTMLElement.new("h2"), h3: Serializer::HTMLElement.new("h3"), h4: Serializer::HTMLElement.new("h4"), h5: Serializer::HTMLElement.new("h5"), h6: Serializer::HTMLElement.new("h6"), blockquote: Serializer::HTMLElement.new("blockquote"), strong: Serializer::HTMLElement.new("strong"), em: Serializer::HTMLElement.new("em"), code: Serializer::HTMLElement.new("code"), "strike-through": Serializer::HTMLElement.new("del"), underline: Serializer::Underline.new, link: Serializer::Link.new, image: Serializer::Image.new(@base_image_url), span: Serializer::Span.new, missing_mark: Serializer::HTMLElement.new("span") } end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/span.rb
Ruby
require_relative "base" module PortableText module Serializer class Span < Base def call(inner_html, _data = nil) escape_html_string(inner_html) end private def escape_html_string(html_string) map = { "'" => "&#x27;", "\n" => "<br/>", "\"" => "&quot;" } pattern = Regexp.union(map.keys) html_string.gsub(pattern) do |match| map[match] end end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/serializer/underline.rb
Ruby
require_relative "base" module PortableText module Serializer class Underline < Base def call(inner_html, _data = nil) "<span style=\"text-decoration:underline;\">#{inner_html}</span>" end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/span.rb
Ruby
require_relative "renderable" module PortableText class Span include Renderable class << self def from_json(json, mark_defs) type = json["_type"] text = json["text"] marks = (json["marks"] || []).map { |mark_key| Mark.from_key(mark_key, mark_defs) } serializer = PortableText.configuration.serializer_registry.get(type, fallback: "span", ctx: json) new \ serializer: serializer, attributes: { type: type, text: text, marks: marks, }, raw_json: json.merge("_internal" => { "inline" => true }) end end attr_reader :text attr_accessor :marks def initialize(attributes: {}, raw_json: {}, serializer:) @type = attributes[:type] @text = attributes[:text] @marks = attributes[:marks] @raw_json = raw_json @serializer = serializer end def to_html @serializer.call(text, @raw_json) end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
lib/portable_text/version.rb
Ruby
module RubyPortabletext VERSION = "0.1.0" end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/block_test.rb
Ruby
require_relative "test_helper" require_relative "./renderable_interface_test" class PortableText::BlockTest < Minitest::Test include RenderableInterfaceTest def setup @object = PortableText::Block.new \ attributes: { key: "test", type: "test", style: "test", children: [] }, serializer: PortableText::Serializer::HTMLElement.new("p"), raw_json: {} end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/children_test.rb
Ruby
require_relative "test_helper" class PortableText::ChildrenTest < Minitest::Test class MockHtmlSerializer < PortableText::Serializer::Base def initialize(key) @key = key end def call(inner_html, data = nil) "<#{@key}>#{inner_html}</#{@key}>" end end class MockCustomSerializer < PortableText::Serializer::Base def call(inner_html, data) href = data["href"] "<a href=\"#{href}\">#{inner_html}</a>" end end def setup custom_mark_def = PortableText::MarkDef.new(key: "custom_mark", type: "custom_mark", raw_json: { "href" => "#test" }) @custom_mark = PortableText::Mark.new(key: "custom_mark", definition: custom_mark_def, serializer: MockCustomSerializer.new) @strong_mark = PortableText::Mark.new(key: "strong", serializer: MockHtmlSerializer.new("strong")) @em_mark = PortableText::Mark.new(key: "em", serializer: MockHtmlSerializer.new("em")) end test "renders list of spans" do child1 = create_child(attributes: { marks: [], text: "one" }) child2 = create_child(attributes: { marks: [], text: "two" }) children = PortableText::Children.new([child1, child2]) assert_equal "onetwo", children.to_html end test "renders with decorator marks" do child1 = create_child(attributes: { marks: [@strong_mark], text: "one" }) child2 = create_child(attributes: { marks: [], text: "two" }) children = PortableText::Children.new([child1, child2]) assert_equal "<strong>one</strong>two", children.to_html end test "consecutive but different marks" do child1 = create_child(attributes: { marks: [@strong_mark], text: "one" }) child2 = create_child(attributes: { marks: [@em_mark], text: "two" }) children = PortableText::Children.new([child1, child2]) assert_equal "<strong>one</strong><em>two</em>", children.to_html end test "renders with overlapping decorator marks" do child1 = create_child(attributes: { marks: [@strong_mark], text: "A word of " }) child2 = create_child(attributes: { marks: [@em_mark, @strong_mark], text: "warning;" }) child3 = create_child(attributes: { marks: [@strong_mark], text: " Sanity is addictive." }) child4 = create_child(attributes: { marks: [], text: " have " }) child5 = create_child(attributes: { marks: [@em_mark], text: "fun!" }) children = PortableText::Children.new([child1, child2, child3, child4, child5]) assert_equal "<strong>A word of <em>warning;</em> Sanity is addictive.</strong> have <em>fun!</em>", children.to_html end test "renders with annotations" do child1 = create_child(attributes: { marks: [@custom_mark], text: "one" }) child2 = create_child(attributes: { marks: [], text: "two" }) children = PortableText::Children.new([child1, child2]) assert_equal "<a href=\"#test\">one</a>two", children.to_html end test "renders with overlapping decorators and annotations" do child1 = create_child(attributes: { marks: [@strong_mark], text: "A word of " }) child2 = create_child(attributes: { marks: [@em_mark, @strong_mark], text: "warning;" }) child3 = create_child(attributes: { marks: [@strong_mark, @custom_mark], text: " Sanity is addictive." }) child4 = create_child(attributes: { marks: [], text: " have " }) child5 = create_child(attributes: { marks: [@em_mark], text: "fun!" }) children = PortableText::Children.new([child1, child2, child3, child4, child5]) assert_equal "<strong>A word of <em>warning;</em><a href=\"#test\"> Sanity is addictive.</a></strong> have <em>fun!</em>", children.to_html end test "renders inline blocks" do class MockImageSerializer < PortableText::Serializer::Base def call(inner_html, data) ref = data["asset"]["_ref"] "<mock-image>#{ref}</mock-image>" end end child1 = create_child(attributes: { marks: [@strong_mark], text: "one" }) child2 = create_child(type: "image", serializer: MockImageSerializer.new, attributes: { type: "image", }, raw_json: { "asset" => { "_type" => "reference", "_ref" => "image-YiOKD0O6AdjKPaK24WtbOEv0-3456x2304-jpg" } }) children = PortableText::Children.new([child1, child2]) assert_equal "<strong>one</strong><mock-image>image-YiOKD0O6AdjKPaK24WtbOEv0-3456x2304-jpg</mock-image>", children.to_html end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/list_test.rb
Ruby
require_relative "test_helper" require_relative "renderable_interface_test" class PortableText::ListTest < Minitest::Test include RenderableInterfaceTest class MockListSerializer < PortableText::Serializer::Base def initialize(tag) @tag = tag end def call(inner_html, data = nil) "<#{@tag}>#{inner_html}</#{@tag}>" end end def setup @object = PortableText::List.new([]) end test "renders basic list" do items = [ create_list_item("bullet", 1, "first"), create_list_item("bullet", 1, "second"), create_list_item("bullet", 1, "third"), ] list = PortableText::List.new(items) assert_equal "<ul><li>first</li><li>second</li><li>third</li></ul>", list.to_html end test "renders nested list" do # - 1a # - 2a # - 2b # - 3a # - 3b # - 1b # - 1c items = [ create_list_item("bullet", 1, "1a"), create_list_item("bullet", 2, "2a"), create_list_item("bullet", 2, "2b"), create_list_item("bullet", 3, "3a"), create_list_item("bullet", 3, "3b"), create_list_item("bullet", 1, "1b"), create_list_item("bullet", 1, "1c"), ] list = PortableText::List.new(items) assert_equal "<ul><li>1a<ul><li>2a</li><li>2b<ul><li>3a</li><li>3b</li></ul></li></ul></li><li>1b</li><li>1c</li></ul>", list.to_html end private def create_list_span(text) PortableText::Span.new(attributes: { text: text, marks: [] }, serializer: PortableText::Serializer::Span.new) end def create_list_item(type, level, text) PortableText::Block.new \ attributes: { list_level: level, list_type: type, children: PortableText::Children.new([create_list_span(text)]) }, raw_json: {}, serializer: PortableText::Serializer::HTMLElement.new("li") end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/parser_test.rb
Ruby
require "test_helper" class ParserTest < Minitest::Test test "can parse single block" do json_data = read_json_file("001-empty-block.json")["input"] parser = PortableText::Parser.new assert_equal 1, parser.parse(json_data).length end test "can parse array of blocks" do json_data = read_json_file("017-all-default-block-styles.json")["input"] parser = PortableText::Parser.new assert_equal 9, parser.parse(json_data).length end test "can parse lists" do json_data = read_json_file("014-nested-lists.json")["input"] assert_equal 13, json_data.length parser = PortableText::Parser.new # 2 blocks, 2 lists assert_equal 4, parser.parse(json_data).length end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/renderable_interface_test.rb
Ruby
module RenderableInterfaceTest def test_implements_interface assert_respond_to(@object, :to_html) end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/renderer_test.rb
Ruby
require "test_helper" class RendererTest < Minitest::Test def setup @renderer = PortableText::Renderer.new end test "001-empty-block" do json_data = read_json_file("001-empty-block.json") assert_rendered_result(json_data) end test "002-single-span" do json_data = read_json_file("002-single-span.json") assert_rendered_result(json_data) end test "003-multiple-spans" do json_data = read_json_file("003-multiple-spans.json") assert_rendered_result(json_data) end test "004-basic-mark-single-span" do json_data = read_json_file("004-basic-mark-single-span.json") assert_rendered_result(json_data) end test "005-basic-mark-multiple-adjacent-spans" do json_data = read_json_file("005-basic-mark-multiple-adjacent-spans.json") assert_rendered_result(json_data) end test "006-basic-mark-nested-marks" do json_data = read_json_file("006-basic-mark-nested-marks.json") assert_rendered_result(json_data) end test "007-link-mark-def" do json_data = read_json_file("007-link-mark-def.json") assert_rendered_result(json_data) end test "008-plain-header-block" do json_data = read_json_file("008-plain-header-block.json") assert_rendered_result(json_data) end test "009-messy-link-text" do json_data = read_json_file("009-messy-link-text.json") assert_rendered_result(json_data) end test "010-basic-bullet-list" do json_data = read_json_file("010-basic-bullet-list.json") assert_rendered_result(json_data) end test "011-basic-numbered-list" do json_data = read_json_file("011-basic-numbered-list.json") assert_rendered_result(json_data) end test "012-image-support" do json_data = read_json_file("012-image-support.json") assert_rendered_result(json_data) end test "013-materialized-image-support" do json_data = read_json_file("013-materialized-image-support.json") assert_rendered_result(json_data) end test "014-nested-lists" do json_data = read_json_file("014-nested-lists.json") assert_rendered_result(json_data) end test "015-all-basic-marks" do json_data = read_json_file("015-all-basic-marks.json") assert_rendered_result(json_data) end test "016-deep-weird-lists" do json_data = read_json_file("016-deep-weird-lists.json") assert_rendered_result(json_data) end test "017-all-default-block-styles" do json_data = read_json_file("017-all-default-block-styles.json") assert_rendered_result(json_data) end test "018-marks-all-the-way-down" do skip json_data = read_json_file("018-marks-all-the-way-down.json") assert_rendered_result(json_data) end test "019-keyless" do json_data = read_json_file("019-keyless.json") assert_rendered_result(json_data) end test "020-empty-array" do json_data = read_json_file("020-empty-array.json") assert_rendered_result(json_data) end test "021-list-without-level" do json_data = read_json_file("021-list-without-level.json") assert_rendered_result(json_data) end test "022-inline-nodes" do json_data = read_json_file("022-inline-nodes.json") assert_rendered_result(json_data) end test "023-hard-breaks" do json_data = read_json_file("023-hard-breaks.json") assert_rendered_result(json_data) end test "024-inline-images" do json_data = read_json_file("024-inline-images.json") assert_rendered_result(json_data) end test "025-image-with-hotspot" do skip json_data = read_json_file("025-image-with-hotspot.json") assert_rendered_result(json_data) end test "026-inline-block-with-text" do PortableText.configuration.serializer_registry.register( "button", Proc.new { |inner_html| "<button>#{inner_html}</button>" } ) json_data = read_json_file("026-inline-block-with-text.json") assert_rendered_result(json_data) PortableText.configuration.serializer_registry.reset end test "027-styled-list-items" do json_data = read_json_file("027-styled-list-items.json") assert_rendered_result(json_data) end test "050-custom-block-type" do class CodeSerializer < PortableText::Serializer::Base def call(_inner_html, data = nil) "<pre data-language=\"#{data["language"]}\"><code>#{escape_html(data["code"])}</code></pre>" end private def escape_html(html_string) map = { "'" => "&#x27;", ">" => "&gt;" } pattern = Regexp.union(map.keys) html_string.gsub(pattern) do |match| map[match] end end end PortableText.configuration.serializer_registry.register("code", CodeSerializer.new) json_data = read_json_file("050-custom-block-type.json") assert_rendered_result(json_data) PortableText.configuration.serializer_registry.reset end test "051-override-defaults" do PortableText.configuration.serializer_registry.register( "image", Proc.new { |data| "<img alt=\"Such image\" src=\"https://cdn.sanity.io/images/3do82whm/production/YiOKD0O6AdjKPaK24WtbOEv0-3456x2304.jpg\"/>" } ) json_data = read_json_file("051-override-defaults.json") assert_rendered_result(json_data) PortableText.configuration.serializer_registry.reset end test "052-custom-marks" do highlighter = Proc.new do |inner_html, data| "<span style=\"border:#{data["thickness"]}px solid;\">#{inner_html}</span>" end PortableText.configuration.serializer_registry.register("highlight", highlighter) json_data = read_json_file("052-custom-marks.json") assert_rendered_result(json_data) PortableText.configuration.serializer_registry.reset end test "053-override-default-marks" do custom_link = Proc.new do |inner_html, data| "<a class=\"mahlink\" href=\"#{data["href"]}\">#{inner_html}</a>" end PortableText.configuration.serializer_registry.register("link", custom_link) json_data = read_json_file("053-override-default-marks.json") assert_rendered_result(json_data) PortableText.configuration.serializer_registry.reset end test "061-missing-mark-serializer" do json_data = read_json_file("061-missing-mark-serializer.json") assert_rendered_result(json_data) end private def assert_rendered_result(json_data) input = json_data["input"] expected = json_data["output"] rendered = @renderer.render(input) assert_equal expected, rendered end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/serializer/html_element_test.rb
Ruby
require_relative "../test_helper" require_relative "./interface_test" class PortableText::Serializer::HTMLElementTest < Minitest::Test include SerializerInterfaceTest def setup @object = PortableText::Serializer::HTMLElement.new("p") end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/serializer/interface_test.rb
Ruby
module SerializerInterfaceTest def test_implements_interface assert_respond_to(@object, :call) end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
test/test_helper.rb
Ruby
require "minitest/autorun" require "minitest/spec" require "json" require "portable_text" PortableText.configure do |config| config.project_id = "3do82whm" config.dataset = "production" config.cdn_base_url = "https://cdn.sanity.io/images" end module Minitest class Test def self.test(name, &block) define_method("test_#{name.gsub(/\s+/, '_')}", &block) end def read_json_file(filename) JSON.parse(File.read(File.join(__dir__, "upstream", filename))) end def create_block(attributes = {}, serializer = nil) serializer = serializer || PortableText::Serializer::HTMLElement.new("p") PortableText::Block.new(serializer: serializer, attributes: attributes) end def create_child(type: "span", attributes: {}, serializer: nil, raw_json: {}) serializer = serializer || PortableText::Serializer::Span.new if type == "span" defaults = { type: "span" } PortableText::Span.new(attributes: defaults.merge(attributes), serializer: serializer) else PortableText::Block.new(serializer: serializer, attributes: attributes, raw_json: raw_json) end end end end
zachgoll/ruby-portabletext
0
A Portable Text Renderer in Ruby
Ruby
zachgoll
Zach Gollwitzer
main.go
Go
package main import ( "crypto/sha256" "encoding/hex" "fmt" "io" "log" "net/http" "net/url" "os" "path/filepath" _ "embed" "github.com/h2non/filetype" ) var port, destDir, baseURLRaw, allowedSubnet string var baseURL *url.URL func main() { port = os.Getenv("PORT") destDir = os.Getenv("FS_DEST_DIR") baseURLRaw = os.Getenv("BASE_URL") allowedSubnet = os.Getenv("ALLOWED_SUBNET") if destDir == "" || baseURLRaw == "" { fmt.Fprintln(os.Stderr, "FS_DEST_DIR and BASE_URL must both be set") os.Exit(1) } var err error baseURL, err = url.Parse(baseURLRaw) if err != nil { fmt.Fprintln(os.Stderr, "BASE_URL is not a valid URL") os.Exit(1) } if port == "" { defaultPort := "7777" log.Println("PORT not set, using default", defaultPort) port = defaultPort } if allowedSubnet == "" { defaultSubnet := "100.64.0.0/10" log.Println("ALLOWED_SUBNET not set, using default", defaultSubnet) allowedSubnet = defaultSubnet } http.HandleFunc("/", root) http.HandleFunc("/upload", upload) log.Fatal(http.ListenAndServe(":"+port, nil)) } //go:embed README.md var readme string func root(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, readme) } func upload(w http.ResponseWriter, r *http.Request) { tempFile, err := os.CreateTemp(destDir, "tmp-upload-*") if err != nil { handleErr(err, r, w, "error writing temporary file to disk", http.StatusInternalServerError) return } defer os.Remove(tempFile.Name()) if _, err := io.Copy(tempFile, r.Body); err != nil { handleErr(err, r, w, "error writing uploaded file to disk", http.StatusInternalServerError) return } // reset file pointer to beginning of file so we can reuse it tempFile.Seek(0, io.SeekStart) hasher := sha256.New() if _, err := io.Copy(hasher, tempFile); err != nil { handleErr(err, r, w, "error hashing file", http.StatusInternalServerError) return } fileExt, err := inferFileExtension(tempFile.Name()) if err != nil || fileExt == "unknown" { handleErr(err, r, w, "failed to infer file type", http.StatusBadRequest) return } fileHash := hex.EncodeToString(hasher.Sum(nil)) fileName, err := shortestAvailableTruncatedFilename(2, destDir, fileHash, fileExt) if err != nil { handleErr(err, r, w, "error generating filename for uploaded file", http.StatusInternalServerError) return } destPath := filepath.Join(destDir, fileName) if err := os.Rename(tempFile.Name(), destPath); err != nil { handleErr(err, r, w, "error moving temporary file to FS_DEST_DIR", http.StatusInternalServerError) return } fileURLRelative, err := url.Parse("./" + fileName) if err != nil { handleErr(err, r, w, "internal error constructing file URL", http.StatusInternalServerError) return } fileURL := baseURL.ResolveReference(fileURLRelative) fmt.Fprintln(w, fileURL.String()) } func handleErr(err error, r *http.Request, w http.ResponseWriter, userMsg string, statusCode int) { http.Error(w, userMsg, statusCode) log.Println("IP:", r.RemoteAddr, "Path:", r.URL.Path, "Error: '", userMsg, "-", err) } // find the shortest available truncation of nameToTruncate that doesn't // yet exist in destDir. returned truncations will have a basename no shorter // than startingLength. func shortestAvailableTruncatedFilename(startingLength int, destDir, nameToTruncate, ext string) (string, error) { truncated := firstN(nameToTruncate, startingLength) + "." + ext path := filepath.Join(destDir, truncated) exists, err := fileExists(path) if err != nil { return "", err } if exists { return shortestAvailableTruncatedFilename(startingLength+1, destDir, nameToTruncate, ext) } return truncated, nil } // from https://stackoverflow.com/a/41604514 func firstN(s string, n int) string { i := 0 for j := range s { if i == n { return s[:j] } i++ } return s } // from https://stackoverflow.com/a/10510783 func fileExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } func inferFileExtension(path string) (string, error) { t, err := filetype.MatchFile(path) if err != nil { return "", err } return t.Extension, nil }
zachlatta/cdn
4
CDN microservice to upload files to zachlatta.com that only accepts traffic from Tailscale IPs
Go
zachlatta
Zach Latta
hackclub
Sources/App.swift
Swift
import SwiftUI @main struct FreeFlowApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { MenuBarExtra { MenuBarView() .environmentObject(appDelegate.appState) } label: { MenuBarLabel() .environmentObject(appDelegate.appState) } } } struct MenuBarLabel: View { @EnvironmentObject var appState: AppState var body: some View { let icon: String = if appState.isRecording { "record.circle" } else if appState.isTranscribing { "ellipsis.circle" } else { "mic.fill" } Image(systemName: icon) } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/AppContextService.swift
Swift
import Foundation import ApplicationServices import AppKit struct AppContext { let appName: String? let bundleIdentifier: String? let windowTitle: String? let selectedText: String? let currentActivity: String let contextPrompt: String? let screenshotDataURL: String? let screenshotMimeType: String? let screenshotError: String? var contextSummary: String { currentActivity } } final class AppContextService { private let apiKey: String private let baseURL = "https://api.groq.com/openai/v1" private let fallbackTextModel = "meta-llama/llama-4-scout-17b-16e-instruct" private let visionModel = "meta-llama/llama-4-scout-17b-16e-instruct" private let maxScreenshotDataURILength = 500_000 private let screenshotCompressionPrimary = 0.5 private let screenshotMaxDimension: CGFloat = 1024 init(apiKey: String) { self.apiKey = apiKey } func collectContext() async -> AppContext { guard let frontmostApp = NSWorkspace.shared.frontmostApplication else { return AppContext( appName: nil, bundleIdentifier: nil, windowTitle: nil, selectedText: nil, currentActivity: "You are dictating in an unrecognized context.", contextPrompt: nil, screenshotDataURL: nil, screenshotMimeType: nil, screenshotError: "No frontmost application" ) } let appName = frontmostApp.localizedName let bundleIdentifier = frontmostApp.bundleIdentifier let appElement = AXUIElementCreateApplication(frontmostApp.processIdentifier) let windowTitle = focusedWindowTitle(from: appElement) ?? appName let selectedText = selectedText(from: appElement) let screenshot = captureActiveWindowScreenshot( processIdentifier: frontmostApp.processIdentifier, appElement: appElement, focusedWindowTitle: windowTitle ) let currentActivity: String let contextPrompt: String? if !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { if let result = await inferActivityWithLLM( appName: appName, bundleIdentifier: bundleIdentifier, windowTitle: windowTitle, selectedText: selectedText, screenshotDataURL: screenshot.dataURL ) { currentActivity = result.activity contextPrompt = result.prompt } else { currentActivity = fallbackCurrentActivity( appName: appName, bundleIdentifier: bundleIdentifier, selectedText: selectedText, windowTitle: windowTitle, screenshotAvailable: screenshot.dataURL != nil ) contextPrompt = nil } } else { currentActivity = fallbackCurrentActivity( appName: appName, bundleIdentifier: bundleIdentifier, selectedText: selectedText, windowTitle: windowTitle, screenshotAvailable: screenshot.dataURL != nil ) contextPrompt = nil } return AppContext( appName: appName, bundleIdentifier: bundleIdentifier, windowTitle: windowTitle, selectedText: selectedText, currentActivity: currentActivity, contextPrompt: contextPrompt, screenshotDataURL: screenshot.dataURL, screenshotMimeType: screenshot.mimeType, screenshotError: screenshot.error ) } private func inferActivityWithLLM( appName: String?, bundleIdentifier: String?, windowTitle: String?, selectedText: String?, screenshotDataURL: String? ) async -> (activity: String, prompt: String)? { let modelsToTry = [ screenshotDataURL != nil ? visionModel : fallbackTextModel, fallbackTextModel ] for model in modelsToTry { let screenshotPayload = model == visionModel ? screenshotDataURL : nil if let inferred = await inferActivityWithLLM( appName: appName, bundleIdentifier: bundleIdentifier, windowTitle: windowTitle, selectedText: selectedText, screenshotDataURL: screenshotPayload, model: model ) { return inferred } } return nil } private func inferActivityWithLLM( appName: String?, bundleIdentifier: String?, windowTitle: String?, selectedText: String?, screenshotDataURL: String?, model: String ) async -> (activity: String, prompt: String)? { do { var request = URLRequest(url: URL(string: "\(baseURL)/chat/completions")!) request.httpMethod = "POST" request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "Content-Type") let metadata = """ App: \(appName ?? "Unknown") Bundle ID: \(bundleIdentifier ?? "Unknown") Window: \(windowTitle ?? "Unknown") Selected text: \(selectedText ?? "None") """ let systemPrompt = """ You are a context synthesis assistant for a speech-to-text pipeline. Given app/window metadata and an optional screenshot, output exactly two sentences that describe what the user is doing right now and the likely writing intent in the current window. Prioritize concrete details only from the context: for email, identify recipients, subject or thread cues, and whether the user is replying or composing; for terminal/code/text work, identify the active command, file, document title, or topic. If details are missing, state uncertainty instead of inventing facts. Return only two sentences, no labels, no markdown, no extra commentary. """ let textOnlyPrompt = "Analyze the context and infer the user's current activity in exactly two sentences.\n\n\(metadata)" var userMessageDescription: String var userMessage: Any = textOnlyPrompt if let screenshotDataURL { userMessageDescription = "[screenshot attached]\nAnalyze the screenshot plus metadata to infer current activity.\n\(metadata)" userMessage = [ [ "type": "text", "text": "Analyze the screenshot plus metadata to infer current activity." ], [ "type": "text", "text": metadata ], [ "type": "image_url", "image_url": ["url": screenshotDataURL] ] ] } else { userMessageDescription = textOnlyPrompt } let fullPrompt = "Model: \(model)\n\n[System]\n\(systemPrompt)\n[User]\n\(userMessageDescription)" let payload: [String: Any] = [ "model": model, "temperature": 0.2, "messages": [ ["role": "system", "content": systemPrompt], ["role": "user", "content": userMessage] ] ] request.httpBody = try JSONSerialization.data(withJSONObject: payload, options: []) let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { return nil } guard httpResponse.statusCode == 200 else { return nil } guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let choices = json["choices"] as? [[String: Any]], let firstChoice = choices.first, let message = firstChoice["message"] as? [String: Any], let content = message["content"] as? String else { return nil } let cleaned = content.trimmingCharacters(in: .whitespacesAndNewlines) guard !cleaned.isEmpty else { return nil } return (activity: normalizedActivitySummary(cleaned), prompt: fullPrompt) } catch { return nil } } private func normalizedActivitySummary(_ value: String) -> String { let sentences = value .split(whereSeparator: { $0 == "." || $0 == "。" || $0 == "!" || $0 == "?" }) .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } if sentences.count <= 2 { return value } let firstTwo = sentences.prefix(2) return firstTwo.joined(separator: ". ") + "." } private func fallbackCurrentActivity( appName: String?, bundleIdentifier: String?, selectedText: String?, windowTitle: String?, screenshotAvailable: Bool ) -> String { let activeApp = appName ?? "the active application" if screenshotAvailable { return "Could not reliably infer a two-sentence summary for \(activeApp) from the screenshot and metadata." } return "Could not reliably infer a two-sentence summary for \(activeApp) from the visible metadata." } private func focusedWindowTitle(from appElement: AXUIElement) -> String? { guard let focusedWindow = accessibilityElement(from: appElement, attribute: kAXFocusedWindowAttribute as CFString) else { return nil } if let windowTitle = accessibilityString(from: focusedWindow, attribute: kAXTitleAttribute as CFString) { return trimmedText(windowTitle) } return nil } private func selectedText(from appElement: AXUIElement) -> String? { if let focusedElement = accessibilityElement(from: appElement, attribute: kAXFocusedUIElementAttribute as CFString), let selectedText = accessibilityString(from: focusedElement, attribute: kAXSelectedTextAttribute as CFString) { return trimmedText(selectedText) } if let selectedText = accessibilityString(from: appElement, attribute: kAXSelectedTextAttribute as CFString) { return trimmedText(selectedText) } return nil } private func accessibilityElement(from element: AXUIElement, attribute: CFString) -> AXUIElement? { var value: CFTypeRef? let result = AXUIElementCopyAttributeValue(element, attribute, &value) guard result == .success, let rawValue = value, CFGetTypeID(rawValue) == AXUIElementGetTypeID() else { return nil } return unsafeBitCast(rawValue, to: AXUIElement.self) } private func accessibilityString(from element: AXUIElement, attribute: CFString) -> String? { var value: CFTypeRef? let result = AXUIElementCopyAttributeValue(element, attribute, &value) guard result == .success, let stringValue = value as? String else { return nil } return trimmedText(stringValue) } private func accessibilityPoint(from element: AXUIElement, attribute: CFString) -> CGPoint? { var value: CFTypeRef? let result = AXUIElementCopyAttributeValue(element, attribute, &value) guard result == .success, let rawValue = value, CFGetTypeID(rawValue) == AXValueGetTypeID() else { return nil } let axValue = unsafeBitCast(rawValue, to: AXValue.self) var point = CGPoint.zero guard AXValueGetValue(axValue, .cgPoint, &point) else { return nil } return point } private func accessibilitySize(from element: AXUIElement, attribute: CFString) -> CGSize? { var value: CFTypeRef? let result = AXUIElementCopyAttributeValue(element, attribute, &value) guard result == .success, let rawValue = value, CFGetTypeID(rawValue) == AXValueGetTypeID() else { return nil } let axValue = unsafeBitCast(rawValue, to: AXValue.self) var size = CGSize.zero guard AXValueGetValue(axValue, .cgSize, &size) else { return nil } return size } private func captureActiveWindowScreenshot( processIdentifier: pid_t, appElement: AXUIElement, focusedWindowTitle: String? ) -> (dataURL: String?, mimeType: String?, error: String?) { if !CGPreflightScreenCaptureAccess() { return ( nil, nil, "Screen recording permission not granted. Enable in System Settings > Privacy & Security > Screen Recording." ) } let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] guard let windows else { return (nil, nil, "Unable to read window list") } let ownerPIDKey = kCGWindowOwnerPID as String let layerKey = kCGWindowLayer as String let onScreenKey = kCGWindowIsOnscreen as String let windowIDKey = kCGWindowNumber as String let boundsKey = kCGWindowBounds as String let nameKey = kCGWindowName as String struct CandidateWindow { let id: CGWindowID let layer: Int let area: Int let bounds: CGRect? let name: String? } let candidateWindows = windows.compactMap { windowInfo -> CandidateWindow? in guard let ownerPID = windowInfo[ownerPIDKey] as? Int, ownerPID == processIdentifier else { return nil } guard let isOnScreen = windowInfo[onScreenKey] as? Bool, isOnScreen else { return nil } guard let windowIDValue = windowInfo[windowIDKey] as? Int else { return nil } let layer = (windowInfo[layerKey] as? Int) ?? 0 let bounds = boundsRect(windowInfo[boundsKey]) let width = bounds?.width ?? 1 let height = bounds?.height ?? 1 let area = Int(width * height) let name = trimmedText(windowInfo[nameKey] as? String) return CandidateWindow( id: CGWindowID(windowIDValue), layer: layer, area: area, bounds: bounds, name: name ) } if let focusedWindowBounds = focusedWindowBounds(from: appElement), !focusedWindowBounds.isNull { if let activeWindow = candidateWindows .compactMap({ candidate -> (CandidateWindow, CGFloat)? in guard let candidateBounds = candidate.bounds else { return nil } let intersection = candidateBounds.intersection(focusedWindowBounds) guard !intersection.isNull else { return nil } let overlap = intersection.width * intersection.height return (candidate, overlap) }) .sorted(by: { lhs, rhs in if lhs.0.layer == rhs.0.layer { return lhs.1 > rhs.1 } return lhs.0.layer < rhs.0.layer }) .first?.0 { if let dataURL = captureWindowImage( windowID: activeWindow.id, fileType: .jpeg, mimeType: "image/jpeg", compression: screenshotCompressionPrimary, maxDimension: screenshotMaxDimension ) { return (dataURL, "image/jpeg", nil) } } if let focusedWindowTitle, let activeWindow = candidateWindows .filter({ candidate in let normalizedName = candidate.name? .lowercased() .trimmingCharacters(in: .whitespacesAndNewlines) let normalizedTarget = focusedWindowTitle .lowercased() .trimmingCharacters(in: .whitespacesAndNewlines) guard let normalizedName, !normalizedName.isEmpty, !normalizedTarget.isEmpty else { return false } return normalizedName == normalizedTarget || normalizedName.contains(normalizedTarget) }) .sorted(by: { lhs, rhs in if lhs.layer == rhs.layer { return lhs.area > rhs.area } return lhs.layer < rhs.layer }) .first { if let dataURL = captureWindowImage( windowID: activeWindow.id, fileType: .jpeg, mimeType: "image/jpeg", compression: screenshotCompressionPrimary, maxDimension: screenshotMaxDimension ) { return (dataURL, "image/jpeg", nil) } } } guard let fullScreenImage = CGWindowListCreateImage( CGRect.infinite, .optionOnScreenOnly, kCGNullWindowID, [.bestResolution] ) else { return (nil, nil, "Could not capture screenshot (screen recording permission or window access issue)") } if let croppedImage = croppedWhitespaceImage(from: fullScreenImage), let dataURL = convertImageToDataURL( croppedImage, mimeType: "image/jpeg", fileType: .jpeg, compression: screenshotCompressionPrimary, maxDimension: screenshotMaxDimension ) { return (dataURL, "image/jpeg", nil) } return (nil, nil, "Could not capture screenshot within size limits") } private func captureWindowImage( windowID: CGWindowID, fileType: NSBitmapImageRep.FileType, mimeType: String, compression: Double? = nil, maxDimension: CGFloat? = nil ) -> String? { guard let image = CGWindowListCreateImage( .null, .optionIncludingWindow, windowID, [.bestResolution] ) else { return nil } guard let croppedImage = croppedWhitespaceImage(from: image) else { return nil } if let dataURL = convertImageToDataURL( croppedImage, mimeType: mimeType, fileType: fileType, compression: compression, maxDimension: maxDimension ) { return dataURL } return nil } private func boundsValue(_ value: Any?) -> CGSize? { guard let bounds = value as? [String: Any], let width = bounds["Width"] as? CGFloat, let height = bounds["Height"] as? CGFloat else { return nil } return CGSize(width: width, height: height) } private func boundsRect(_ value: Any?) -> CGRect? { guard let bounds = value as? [String: Any], let x = bounds["X"] as? CGFloat, let y = bounds["Y"] as? CGFloat, let width = bounds["Width"] as? CGFloat, let height = bounds["Height"] as? CGFloat else { return nil } return CGRect(x: x, y: y, width: width, height: height) } private func focusedWindowBounds(from appElement: AXUIElement) -> CGRect? { guard let focusedWindow = accessibilityElement( from: appElement, attribute: kAXFocusedWindowAttribute as CFString ), let point = accessibilityPoint(from: focusedWindow, attribute: kAXPositionAttribute as CFString), let size = accessibilitySize(from: focusedWindow, attribute: kAXSizeAttribute as CFString) else { return nil } return CGRect(origin: point, size: size) } private func convertImageToDataURL( _ image: CGImage, mimeType: String, fileType: NSBitmapImageRep.FileType, compression: Double?, maxDimension: CGFloat? ) -> String? { let compressionSteps: [Double] = if let compression { [compression, compression * 0.5, compression * 0.25] } else { [1.0] } let dimensionSteps: [CGFloat?] = if let maxDimension { [maxDimension, maxDimension * 0.75, maxDimension * 0.5] } else { [nil] } for dim in dimensionSteps { let imageToEncode = dim.flatMap { resizedImage(for: image, maxDimension: $0) } ?? image let rep = NSBitmapImageRep(cgImage: imageToEncode) for comp in compressionSteps { guard let imageData = rep.representation( using: fileType, properties: [.compressionFactor: comp] ) else { continue } let base64 = imageData.base64EncodedString() if base64.count <= maxScreenshotDataURILength { return "data:\(mimeType);base64,\(base64)" } } } return nil } private func croppedWhitespaceImage(from image: CGImage) -> CGImage? { let width = image.width let height = image.height guard width > 0, height > 0 else { return nil } let bytesPerPixel = 4 let bytesPerRow = width * bytesPerPixel let byteCount = bytesPerRow * height var pixelData = Array(repeating: UInt8(0), count: byteCount) guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), let context = CGContext( data: &pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return image } let drawRect = CGRect(origin: .zero, size: CGSize(width: width, height: height)) context.draw(image, in: drawRect) let whiteThreshold: UInt8 = 245 let alphaThreshold: UInt8 = 5 var minX = width var minY = height var maxX: Int = -1 var maxY: Int = -1 var hasContent = false for y in 0..<height { let rowOffset = y * bytesPerRow for x in 0..<width { let offset = rowOffset + x * bytesPerPixel let r = pixelData[offset] let g = pixelData[offset + 1] let b = pixelData[offset + 2] let a = pixelData[offset + 3] if a <= alphaThreshold { continue } if r >= whiteThreshold && g >= whiteThreshold && b >= whiteThreshold { continue } hasContent = true minX = min(minX, x) minY = min(minY, y) maxX = max(maxX, x) maxY = max(maxY, y) } } guard hasContent else { return image } let cropRect = CGRect( x: CGFloat(minX), y: CGFloat(minY), width: CGFloat(maxX - minX + 1), height: CGFloat(maxY - minY + 1) ) return image.cropping(to: cropRect) ?? image } private func resizedImage(for image: CGImage, maxDimension: CGFloat) -> CGImage? { let width = CGFloat(image.width) let height = CGFloat(image.height) guard width > maxDimension || height > maxDimension else { return image } let scale = min(maxDimension / width, maxDimension / height, 1.0) let targetSize = CGSize(width: width * scale, height: height * scale) let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = CGContext( data: nil, width: Int(targetSize.width), height: Int(targetSize.height), bitsPerComponent: image.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: image.bitmapInfo.rawValue ) else { return nil } context.interpolationQuality = .high context.draw(image, in: CGRect(origin: .zero, size: targetSize)) return context.makeImage() } private func trimmedText(_ value: String?) -> String? { guard let value else { return nil } let trimmed = value .trimmingCharacters(in: .whitespacesAndNewlines) .replacingOccurrences(of: "\n", with: " ") return trimmed.isEmpty ? nil : trimmed } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/AppDelegate.swift
Swift
import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate { let appState = AppState() var setupWindow: NSWindow? private var settingsWindow: NSWindow? func applicationDidFinishLaunching(_ notification: Notification) { NotificationCenter.default.addObserver( self, selector: #selector(handleShowSetup), name: .showSetup, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(handleShowSettings), name: .showSettings, object: nil ) if !appState.hasCompletedSetup { showSetupWindow() } else { appState.startHotkeyMonitoring() appState.startAccessibilityPolling() Task { @MainActor in UpdateManager.shared.startPeriodicChecks() } if !AXIsProcessTrusted() { appState.showAccessibilityAlert() } } } @objc func handleShowSetup() { appState.hasCompletedSetup = false appState.stopAccessibilityPolling() showSetupWindow() } @objc private func handleShowSettings() { showSettingsWindow() } private func showSettingsWindow() { if let settingsWindow, settingsWindow.isVisible { settingsWindow.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) return } if settingsWindow == nil { presentSettingsWindow() } else { settingsWindow?.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } } private func presentSettingsWindow() { let settingsView = SettingsView() .environmentObject(appState) let hostingView = NSHostingView(rootView: settingsView) let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 780, height: 540), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false ) window.title = "FreeFlow" window.contentView = hostingView window.isReleasedWhenClosed = false window.center() window.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) settingsWindow = window NotificationCenter.default.addObserver( forName: NSWindow.willCloseNotification, object: window, queue: .main ) { [weak self] _ in self?.settingsWindow = nil } } func showSetupWindow() { NSApp.setActivationPolicy(.regular) let setupView = SetupView(onComplete: { [weak self] in self?.completeSetup() }) .environmentObject(appState) let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 520, height: 480), styleMask: [.titled, .closable, .fullSizeContentView], backing: .buffered, defer: false ) window.title = "FreeFlow" window.titlebarAppearsTransparent = true window.isMovableByWindowBackground = true window.contentView = NSHostingView(rootView: setupView) window.minSize = NSSize(width: 520, height: 480) window.center() window.makeKeyAndOrderFront(nil) window.isReleasedWhenClosed = false self.setupWindow = window NSApp.activate(ignoringOtherApps: true) } func completeSetup() { appState.hasCompletedSetup = true setupWindow?.close() setupWindow = nil NSApp.setActivationPolicy(.accessory) appState.startHotkeyMonitoring() appState.startAccessibilityPolling() Task { @MainActor in UpdateManager.shared.startPeriodicChecks() } if !AXIsProcessTrusted() { appState.showAccessibilityAlert() } } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/AppState.swift
Swift
import Foundation import Combine import AppKit import AVFoundation import CoreAudio import ServiceManagement import ApplicationServices import ScreenCaptureKit import os.log private let recordingLog = OSLog(subsystem: "com.zachlatta.freeflow", category: "Recording") enum SettingsTab: String, CaseIterable, Identifiable { case general case runLog var id: String { rawValue } var title: String { switch self { case .general: return "General" case .runLog: return "Run Log" } } var icon: String { switch self { case .general: return "gearshape" case .runLog: return "clock.arrow.circlepath" } } } final class AppState: ObservableObject, @unchecked Sendable { private let apiKeyStorageKey = "groq_api_key" private let customVocabularyStorageKey = "custom_vocabulary" private let selectedMicrophoneStorageKey = "selected_microphone_id" private let transcribingIndicatorDelay: TimeInterval = 1.0 private let maxPipelineHistoryCount = 20 @Published var hasCompletedSetup: Bool { didSet { UserDefaults.standard.set(hasCompletedSetup, forKey: "hasCompletedSetup") } } @Published var apiKey: String { didSet { persistAPIKey(apiKey) contextService = AppContextService(apiKey: apiKey) } } @Published var selectedHotkey: HotkeyOption { didSet { UserDefaults.standard.set(selectedHotkey.rawValue, forKey: "hotkey_option") restartHotkeyMonitoring() } } @Published var customVocabulary: String { didSet { UserDefaults.standard.set(customVocabulary, forKey: customVocabularyStorageKey) } } @Published var isRecording = false @Published var isTranscribing = false @Published var lastTranscript: String = "" @Published var errorMessage: String? @Published var statusText: String = "Ready" @Published var hasAccessibility = false @Published var isDebugOverlayActive = false @Published var selectedSettingsTab: SettingsTab? = .general @Published var pipelineHistory: [PipelineHistoryItem] = [] @Published var debugStatusMessage = "Idle" @Published var lastRawTranscript = "" @Published var lastPostProcessedTranscript = "" @Published var lastPostProcessingPrompt = "" @Published var lastContextSummary = "" @Published var lastPostProcessingStatus = "" @Published var lastContextScreenshotDataURL: String? = nil @Published var lastContextScreenshotStatus = "No screenshot" @Published var hasScreenRecordingPermission = false @Published var launchAtLogin: Bool { didSet { setLaunchAtLogin(launchAtLogin) } } @Published var selectedMicrophoneID: String { didSet { UserDefaults.standard.set(selectedMicrophoneID, forKey: selectedMicrophoneStorageKey) } } @Published var availableMicrophones: [AudioDevice] = [] let audioRecorder = AudioRecorder() let hotkeyManager = HotkeyManager() let overlayManager = RecordingOverlayManager() private var accessibilityTimer: Timer? private var audioLevelCancellable: AnyCancellable? private var debugOverlayTimer: Timer? private var transcribingIndicatorTask: Task<Void, Never>? private var contextService: AppContextService private var contextCaptureTask: Task<AppContext?, Never>? private var capturedContext: AppContext? private var hasShownScreenshotPermissionAlert = false private var audioDeviceListenerBlock: AudioObjectPropertyListenerBlock? private let pipelineHistoryStore = PipelineHistoryStore() init() { let hasCompletedSetup = UserDefaults.standard.bool(forKey: "hasCompletedSetup") let apiKey = Self.loadStoredAPIKey(account: apiKeyStorageKey) let selectedHotkey = HotkeyOption(rawValue: UserDefaults.standard.string(forKey: "hotkey_option") ?? "fn") ?? .fnKey let customVocabulary = UserDefaults.standard.string(forKey: customVocabularyStorageKey) ?? "" let initialAccessibility = AXIsProcessTrusted() let initialScreenCapturePermission = CGPreflightScreenCaptureAccess() var removedAudioFileNames: [String] = [] do { removedAudioFileNames = try pipelineHistoryStore.trim(to: maxPipelineHistoryCount) } catch { print("Failed to trim pipeline history during init: \(error)") } for audioFileName in removedAudioFileNames { Self.deleteAudioFile(audioFileName) } let savedHistory = pipelineHistoryStore.loadAllHistory() let selectedMicrophoneID = UserDefaults.standard.string(forKey: selectedMicrophoneStorageKey) ?? "default" self.contextService = AppContextService(apiKey: apiKey) self.hasCompletedSetup = hasCompletedSetup self.apiKey = apiKey self.selectedHotkey = selectedHotkey self.customVocabulary = customVocabulary self.pipelineHistory = savedHistory self.hasAccessibility = initialAccessibility self.hasScreenRecordingPermission = initialScreenCapturePermission self.launchAtLogin = SMAppService.mainApp.status == .enabled self.selectedMicrophoneID = selectedMicrophoneID refreshAvailableMicrophones() installAudioDeviceListener() } private static func loadStoredAPIKey(account: String) -> String { if let storedKey = AppSettingsStorage.load(account: account), !storedKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return storedKey } return "" } private func persistAPIKey(_ value: String) { let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) if trimmed.isEmpty { AppSettingsStorage.delete(account: apiKeyStorageKey) } else { AppSettingsStorage.save(trimmed, account: apiKeyStorageKey) } } static func audioStorageDirectory() -> URL { let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "FreeFlow" let audioDir = appSupport.appendingPathComponent("\(appName)/audio", isDirectory: true) if !FileManager.default.fileExists(atPath: audioDir.path) { try? FileManager.default.createDirectory(at: audioDir, withIntermediateDirectories: true) } return audioDir } static func saveAudioFile(from tempURL: URL) -> String? { let fileName = UUID().uuidString + "." + tempURL.pathExtension let destURL = audioStorageDirectory().appendingPathComponent(fileName) do { try FileManager.default.copyItem(at: tempURL, to: destURL) return fileName } catch { return nil } } private static func deleteAudioFile(_ fileName: String) { let fileURL = audioStorageDirectory().appendingPathComponent(fileName) try? FileManager.default.removeItem(at: fileURL) } func clearPipelineHistory() { do { let removedAudioFileNames = try pipelineHistoryStore.clearAll() for audioFileName in removedAudioFileNames { Self.deleteAudioFile(audioFileName) } pipelineHistory = [] } catch { errorMessage = "Unable to clear run history: \(error.localizedDescription)" } } func deleteHistoryEntry(id: UUID) { guard let index = pipelineHistory.firstIndex(where: { $0.id == id }) else { return } do { if let audioFileName = try pipelineHistoryStore.delete(id: id) { Self.deleteAudioFile(audioFileName) } pipelineHistory.remove(at: index) } catch { errorMessage = "Unable to delete run history entry: \(error.localizedDescription)" } } func startAccessibilityPolling() { accessibilityTimer?.invalidate() hasAccessibility = AXIsProcessTrusted() hasScreenRecordingPermission = hasScreenCapturePermission() accessibilityTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in DispatchQueue.main.async { self?.hasAccessibility = AXIsProcessTrusted() self?.hasScreenRecordingPermission = self?.hasScreenCapturePermission() ?? false } } } func stopAccessibilityPolling() { accessibilityTimer?.invalidate() accessibilityTimer = nil } func openAccessibilitySettings() { let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue(): true] as CFDictionary AXIsProcessTrustedWithOptions(options) } func hasScreenCapturePermission() -> Bool { CGPreflightScreenCaptureAccess() } func requestScreenCapturePermission() { // ScreenCaptureKit triggers the "Screen & System Audio Recording" // permission dialog on macOS Sequoia+, correctly identifying the // running app (unlike the legacy CGWindowListCreateImage path). SCShareableContent.getExcludingDesktopWindows(false, onScreenWindowsOnly: false) { [weak self] _, _ in DispatchQueue.main.async { self?.hasScreenRecordingPermission = CGPreflightScreenCaptureAccess() } } hasScreenRecordingPermission = CGPreflightScreenCaptureAccess() } func openScreenCaptureSettings() { let settingsURL = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") if let url = settingsURL { NSWorkspace.shared.open(url) } } private func setLaunchAtLogin(_ enabled: Bool) { do { if enabled { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() } } catch { // Revert the toggle on failure without re-triggering didSet let current = SMAppService.mainApp.status == .enabled if current != launchAtLogin { launchAtLogin = current } } } func refreshLaunchAtLoginStatus() { let current = SMAppService.mainApp.status == .enabled if current != launchAtLogin { launchAtLogin = current } } func refreshAvailableMicrophones() { availableMicrophones = AudioDevice.availableInputDevices() } private func installAudioDeviceListener() { var propertyAddress = AudioObjectPropertyAddress( mSelector: kAudioHardwarePropertyDevices, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain ) let block: AudioObjectPropertyListenerBlock = { [weak self] _, _ in DispatchQueue.main.async { self?.refreshAvailableMicrophones() } } audioDeviceListenerBlock = block AudioObjectAddPropertyListenerBlock( AudioObjectID(kAudioObjectSystemObject), &propertyAddress, DispatchQueue.main, block ) } func startHotkeyMonitoring() { hotkeyManager.onKeyDown = { [weak self] in DispatchQueue.main.async { self?.handleHotkeyDown() } } hotkeyManager.onKeyUp = { [weak self] in DispatchQueue.main.async { self?.handleHotkeyUp() } } hotkeyManager.start(option: selectedHotkey) } private func restartHotkeyMonitoring() { hotkeyManager.start(option: selectedHotkey) } private func handleHotkeyDown() { os_log(.info, log: recordingLog, "handleHotkeyDown() fired, isRecording=%{public}d, isTranscribing=%{public}d", isRecording, isTranscribing) guard !isRecording && !isTranscribing else { return } startRecording() } private func handleHotkeyUp() { guard isRecording else { return } stopAndTranscribe() } func toggleRecording() { os_log(.info, log: recordingLog, "toggleRecording() called, isRecording=%{public}d", isRecording) if isRecording { stopAndTranscribe() } else { startRecording() } } private func startRecording() { let t0 = CFAbsoluteTimeGetCurrent() os_log(.info, log: recordingLog, "startRecording() entered") guard hasAccessibility else { errorMessage = "Accessibility permission required. Grant access in System Settings > Privacy & Security > Accessibility." statusText = "No Accessibility" showAccessibilityAlert() return } os_log(.info, log: recordingLog, "accessibility check passed: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) guard ensureMicrophoneAccess() else { return } os_log(.info, log: recordingLog, "mic access check passed: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) beginRecording() os_log(.info, log: recordingLog, "startRecording() finished: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) } private func ensureMicrophoneAccess() -> Bool { let status = AVCaptureDevice.authorizationStatus(for: .audio) switch status { case .authorized: return true case .notDetermined: AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in DispatchQueue.main.async { if granted { self?.beginRecording() } else { self?.errorMessage = "Microphone permission denied. Grant access in System Settings > Privacy & Security > Microphone." self?.statusText = "No Microphone" self?.showMicrophonePermissionAlert() } } } return false default: errorMessage = "Microphone permission denied. Grant access in System Settings > Privacy & Security > Microphone." statusText = "No Microphone" showMicrophonePermissionAlert() return false } } private func beginRecording() { os_log(.info, log: recordingLog, "beginRecording() entered") errorMessage = nil isRecording = true statusText = "Starting..." hasShownScreenshotPermissionAlert = false // Show initializing dots only if engine takes longer than 0.5s to start var overlayShown = false let initTimer = DispatchSource.makeTimerSource(queue: .main) initTimer.schedule(deadline: .now() + 0.5) initTimer.setEventHandler { [weak self] in guard let self, !overlayShown else { return } overlayShown = true os_log(.info, log: recordingLog, "engine slow — showing initializing overlay") self.overlayManager.showInitializing() } initTimer.resume() // Transition to waveform when first real audio arrives (any non-zero RMS) let deviceUID = selectedMicrophoneID audioRecorder.onRecordingReady = { [weak self] in DispatchQueue.main.async { guard let self else { return } initTimer.cancel() os_log(.info, log: recordingLog, "first real audio — transitioning to waveform") self.statusText = "Recording..." if overlayShown { self.overlayManager.transitionToRecording() } else { self.overlayManager.showRecording() } overlayShown = true NSSound(named: "Tink")?.play() } } // Start engine on background thread so UI isn't blocked DispatchQueue.global(qos: .userInitiated).async { [weak self] in guard let self else { return } let t0 = CFAbsoluteTimeGetCurrent() do { try self.audioRecorder.startRecording(deviceUID: deviceUID) os_log(.info, log: recordingLog, "audioRecorder.startRecording() done: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) DispatchQueue.main.async { self.startContextCapture() self.audioLevelCancellable = self.audioRecorder.$audioLevel .receive(on: DispatchQueue.main) .sink { [weak self] level in self?.overlayManager.updateAudioLevel(level) } } } catch { DispatchQueue.main.async { initTimer.cancel() self.isRecording = false self.errorMessage = self.formattedRecordingStartError(error) self.statusText = "Error" self.overlayManager.dismiss() } } } } private func formattedRecordingStartError(_ error: Error) -> String { if let recorderError = error as? AudioRecorderError { return "Failed to start recording: \(recorderError.localizedDescription)" } let lower = error.localizedDescription.lowercased() if lower.contains("operation couldn't be completed") || lower.contains("operation could not be completed") { return "Failed to start recording: Audio input error. Verify microphone access is granted and a working mic is selected in System Settings > Sound > Input." } let nsError = error as NSError if nsError.domain == NSOSStatusErrorDomain { return "Failed to start recording (audio subsystem error \(nsError.code)). Check microphone permissions and selected input device." } return "Failed to start recording: \(error.localizedDescription)" } func showMicrophonePermissionAlert() { let alert = NSAlert() alert.messageText = "Microphone Permission Required" alert.informativeText = "FreeFlow cannot record audio without Microphone access.\n\nGo to System Settings > Privacy & Security > Microphone and enable FreeFlow." alert.alertStyle = .critical alert.addButton(withTitle: "Open System Settings") alert.addButton(withTitle: "Dismiss") alert.icon = NSImage(systemSymbolName: "mic.fill", accessibilityDescription: nil) let response = alert.runModal() if response == .alertFirstButtonReturn { let settingsURL = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone") if let url = settingsURL { NSWorkspace.shared.open(url) } } } func showAccessibilityAlert() { let alert = NSAlert() alert.messageText = "Accessibility Permission Required" alert.informativeText = "FreeFlow cannot type transcriptions without Accessibility access.\n\nGo to System Settings > Privacy & Security > Accessibility and enable FreeFlow." alert.alertStyle = .critical alert.addButton(withTitle: "Open System Settings") alert.addButton(withTitle: "Dismiss") alert.icon = NSImage(systemSymbolName: "exclamationmark.triangle.fill", accessibilityDescription: nil) let response = alert.runModal() if response == .alertFirstButtonReturn { openAccessibilitySettings() } } private func stopAndTranscribe() { audioLevelCancellable?.cancel() audioLevelCancellable = nil debugStatusMessage = "Preparing audio" let sessionContext = capturedContext let inFlightContextTask = contextCaptureTask capturedContext = nil contextCaptureTask = nil lastRawTranscript = "" lastPostProcessedTranscript = "" lastContextSummary = "" lastPostProcessingStatus = "" lastPostProcessingPrompt = "" lastContextScreenshotDataURL = nil lastContextScreenshotStatus = "No screenshot" guard let fileURL = audioRecorder.stopRecording() else { errorMessage = "No audio recorded" isRecording = false statusText = "Error" return } let savedAudioFileName = Self.saveAudioFile(from: fileURL) isRecording = false isTranscribing = true statusText = "Transcribing..." debugStatusMessage = "Transcribing audio" errorMessage = nil NSSound(named: "Pop")?.play() overlayManager.slideUpToNotch { } transcribingIndicatorTask?.cancel() let indicatorDelay = transcribingIndicatorDelay transcribingIndicatorTask = Task { [weak self] in do { try await Task.sleep(nanoseconds: UInt64(indicatorDelay * 1_000_000_000)) let shouldShowTranscribing = self?.isTranscribing ?? false guard shouldShowTranscribing else { return } await MainActor.run { [weak self] in self?.overlayManager.showTranscribing() } } catch {} } let transcriptionService = TranscriptionService(apiKey: apiKey) let postProcessingService = PostProcessingService(apiKey: apiKey) Task { do { async let transcript = transcriptionService.transcribe(fileURL: fileURL) let rawTranscript = try await transcript let appContext: AppContext if let sessionContext { appContext = sessionContext } else if let inFlightContext = await inFlightContextTask?.value { appContext = inFlightContext } else { appContext = fallbackContextAtStop() } await MainActor.run { [weak self] in self?.debugStatusMessage = "Running post-processing" } let finalTranscript: String let processingStatus: String let postProcessingPrompt: String do { let postProcessingResult = try await postProcessingService.postProcess( transcript: rawTranscript, context: appContext, customVocabulary: customVocabulary ) finalTranscript = postProcessingResult.transcript processingStatus = "Post-processing succeeded" postProcessingPrompt = postProcessingResult.prompt } catch { finalTranscript = rawTranscript processingStatus = "Post-processing failed, using raw transcript" postProcessingPrompt = "" } await MainActor.run { self.lastContextSummary = appContext.contextSummary self.lastContextScreenshotDataURL = appContext.screenshotDataURL self.lastContextScreenshotStatus = appContext.screenshotError ?? "available (\(appContext.screenshotMimeType ?? "image"))" let trimmedRawTranscript = rawTranscript.trimmingCharacters(in: .whitespacesAndNewlines) let trimmedFinalTranscript = finalTranscript.trimmingCharacters(in: .whitespacesAndNewlines) self.lastPostProcessingPrompt = postProcessingPrompt self.lastRawTranscript = trimmedRawTranscript self.lastPostProcessedTranscript = trimmedFinalTranscript self.lastPostProcessingStatus = processingStatus self.recordPipelineHistoryEntry( rawTranscript: trimmedRawTranscript, postProcessedTranscript: trimmedFinalTranscript, postProcessingPrompt: postProcessingPrompt, context: appContext, processingStatus: processingStatus, audioFileName: savedAudioFileName ) self.transcribingIndicatorTask?.cancel() self.transcribingIndicatorTask = nil self.lastTranscript = trimmedFinalTranscript self.isTranscribing = false self.debugStatusMessage = "Done" if trimmedFinalTranscript.isEmpty { self.statusText = "Nothing to transcribe" self.overlayManager.dismiss() } else { self.statusText = "Copied to clipboard!" self.overlayManager.showDone() DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { self.overlayManager.dismiss() } NSPasteboard.general.clearContents() NSPasteboard.general.setString(trimmedFinalTranscript, forType: .string) DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.pasteAtCursor() } } self.audioRecorder.cleanup() DispatchQueue.main.asyncAfter(deadline: .now() + 3) { if self.statusText == "Copied to clipboard!" || self.statusText == "Nothing to transcribe" { self.statusText = "Ready" } } } } catch { let resolvedContext: AppContext if let sessionContext { resolvedContext = sessionContext } else if let inFlightContext = await inFlightContextTask?.value { resolvedContext = inFlightContext } else { resolvedContext = fallbackContextAtStop() } await MainActor.run { self.transcribingIndicatorTask?.cancel() self.transcribingIndicatorTask = nil self.errorMessage = error.localizedDescription self.isTranscribing = false self.statusText = "Error" self.audioRecorder.cleanup() self.overlayManager.dismiss() self.lastPostProcessedTranscript = "" self.lastRawTranscript = "" self.lastContextSummary = "" self.lastPostProcessingStatus = "Error: \(error.localizedDescription)" self.lastPostProcessingPrompt = "" self.lastContextScreenshotDataURL = resolvedContext.screenshotDataURL self.lastContextScreenshotStatus = resolvedContext.screenshotError ?? "available (\(resolvedContext.screenshotMimeType ?? "image"))" self.recordPipelineHistoryEntry( rawTranscript: "", postProcessedTranscript: "", postProcessingPrompt: "", context: resolvedContext, processingStatus: "Error: \(error.localizedDescription)", audioFileName: savedAudioFileName ) } } } } private func recordPipelineHistoryEntry( rawTranscript: String, postProcessedTranscript: String, postProcessingPrompt: String, context: AppContext, processingStatus: String, audioFileName: String? = nil ) { let newEntry = PipelineHistoryItem( timestamp: Date(), rawTranscript: rawTranscript, postProcessedTranscript: postProcessedTranscript, postProcessingPrompt: postProcessingPrompt, contextSummary: context.contextSummary, contextPrompt: context.contextPrompt, contextScreenshotDataURL: context.screenshotDataURL, contextScreenshotStatus: context.screenshotError ?? "available (\(context.screenshotMimeType ?? "image"))", postProcessingStatus: processingStatus, debugStatus: debugStatusMessage, customVocabulary: customVocabulary, audioFileName: audioFileName ) do { let removedAudioFileNames = try pipelineHistoryStore.append(newEntry, maxCount: maxPipelineHistoryCount) for audioFileName in removedAudioFileNames { Self.deleteAudioFile(audioFileName) } pipelineHistory = pipelineHistoryStore.loadAllHistory() } catch { errorMessage = "Unable to save run history entry: \(error.localizedDescription)" } } private func startContextCapture() { contextCaptureTask?.cancel() capturedContext = nil lastContextSummary = "Collecting app context..." lastPostProcessingStatus = "" lastContextScreenshotDataURL = nil lastContextScreenshotStatus = "Collecting screenshot..." contextCaptureTask = Task { [weak self] in guard let self else { return nil } let context = await self.contextService.collectContext() await MainActor.run { self.capturedContext = context self.lastContextSummary = context.contextSummary self.lastContextScreenshotDataURL = context.screenshotDataURL self.lastContextScreenshotStatus = context.screenshotError ?? "available (\(context.screenshotMimeType ?? "image"))" self.lastPostProcessingStatus = "App context captured" self.handleScreenshotCaptureIssue(context.screenshotError) } return context } } private func fallbackContextAtStop() -> AppContext { let frontmostApp = NSWorkspace.shared.frontmostApplication let windowTitle = focusedWindowTitle(for: frontmostApp) return AppContext( appName: frontmostApp?.localizedName, bundleIdentifier: frontmostApp?.bundleIdentifier, windowTitle: windowTitle, selectedText: nil, currentActivity: "Could not refresh app context at stop time; using text-only post-processing.", contextPrompt: nil, screenshotDataURL: nil, screenshotMimeType: nil, screenshotError: "No app context captured before stop" ) } private func focusedWindowTitle(for app: NSRunningApplication?) -> String? { guard let app else { return nil } let appElement = AXUIElementCreateApplication(app.processIdentifier) return focusedWindowTitle(from: appElement) } private func focusedWindowTitle(from appElement: AXUIElement) -> String? { guard let focusedWindow = accessibilityElement(from: appElement, attribute: kAXFocusedWindowAttribute as CFString) else { return nil } guard let windowTitle = accessibilityString(from: focusedWindow, attribute: kAXTitleAttribute as CFString) else { return nil } return trimmedText(windowTitle) } private func accessibilityElement(from element: AXUIElement, attribute: CFString) -> AXUIElement? { var value: CFTypeRef? let result = AXUIElementCopyAttributeValue(element, attribute, &value) guard result == .success, let rawValue = value, CFGetTypeID(rawValue) == AXUIElementGetTypeID() else { return nil } return unsafeBitCast(rawValue, to: AXUIElement.self) } private func accessibilityString(from element: AXUIElement, attribute: CFString) -> String? { var value: CFTypeRef? let result = AXUIElementCopyAttributeValue(element, attribute, &value) guard result == .success, let stringValue = value as? String else { return nil } return stringValue } private func trimmedText(_ value: String) -> String? { let trimmed = value .trimmingCharacters(in: .whitespacesAndNewlines) .replacingOccurrences(of: "\n", with: " ") return trimmed.isEmpty ? nil : trimmed } private func handleScreenshotCaptureIssue(_ message: String?) { guard let message, !message.isEmpty else { hasShownScreenshotPermissionAlert = false return } errorMessage = "Screenshot capture issue: \(message)" NSSound(named: "Basso")?.play() if isScreenCapturePermissionError(message) && !hasShownScreenshotPermissionAlert { hasShownScreenshotPermissionAlert = true showScreenshotPermissionAlert(message: message) } else { showScreenshotCaptureErrorAlert(message: message) } // Stop the recording — a screenshot is required _ = audioRecorder.stopRecording() audioRecorder.cleanup() audioLevelCancellable?.cancel() audioLevelCancellable = nil contextCaptureTask?.cancel() contextCaptureTask = nil capturedContext = nil isRecording = false statusText = "Screenshot Required" overlayManager.dismiss() } private func isScreenCapturePermissionError(_ message: String) -> Bool { let lowered = message.lowercased() return lowered.contains("permission") || lowered.contains("screen recording") } private func showScreenshotPermissionAlert(message: String) { let alert = NSAlert() alert.messageText = "Screen Recording Permission Required" alert.informativeText = "\(message)\n\nFreeFlow requires Screen Recording permission to capture screenshots for context-aware transcription.\n\nGo to System Settings > Privacy & Security > Screen Recording and enable FreeFlow." alert.alertStyle = .critical alert.addButton(withTitle: "Open System Settings") alert.addButton(withTitle: "Dismiss") alert.icon = NSImage(systemSymbolName: "camera.viewfinder", accessibilityDescription: nil) let response = alert.runModal() if response == .alertFirstButtonReturn { openScreenCaptureSettings() } } private func showScreenshotCaptureErrorAlert(message: String) { let alert = NSAlert() alert.messageText = "Screenshot Capture Failed" alert.informativeText = "\(message)\n\nA screenshot is required for context-aware transcription. Recording has been stopped." alert.alertStyle = .critical alert.addButton(withTitle: "Dismiss") alert.icon = NSImage(systemSymbolName: "camera.viewfinder", accessibilityDescription: nil) _ = alert.runModal() } func toggleDebugOverlay() { if isDebugOverlayActive { stopDebugOverlay() } else { startDebugOverlay() } } private func startDebugOverlay() { isDebugOverlayActive = true overlayManager.showRecording() // Simulate audio levels with a timer var phase: Double = 0.0 debugOverlayTimer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in guard let self = self else { return } phase += 0.15 // Generate a fake audio level that oscillates like speech let base = 0.3 + 0.2 * sin(phase) let noise = Float.random(in: -0.15...0.15) let level = min(max(Float(base) + noise, 0.0), 1.0) self.overlayManager.updateAudioLevel(level) } } private func stopDebugOverlay() { debugOverlayTimer?.invalidate() debugOverlayTimer = nil isDebugOverlayActive = false overlayManager.dismiss() } func toggleDebugPanel() { selectedSettingsTab = .runLog NotificationCenter.default.post(name: .showSettings, object: nil) } private func pasteAtCursor() { let source = CGEventSource(stateID: .hidSystemState) let keyDown = CGEvent(keyboardEventSource: source, virtualKey: 9, keyDown: true) keyDown?.flags = .maskCommand keyDown?.post(tap: .cgSessionEventTap) let keyUp = CGEvent(keyboardEventSource: source, virtualKey: 9, keyDown: false) keyUp?.flags = .maskCommand keyUp?.post(tap: .cgSessionEventTap) } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/AudioRecorder.swift
Swift
import AVFoundation import CoreAudio import Foundation import os.log private let recordingLog = OSLog(subsystem: "com.zachlatta.freeflow", category: "Recording") struct AudioDevice: Identifiable { let id: AudioDeviceID let uid: String let name: String static func availableInputDevices() -> [AudioDevice] { var propertyAddress = AudioObjectPropertyAddress( mSelector: kAudioHardwarePropertyDevices, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain ) var dataSize: UInt32 = 0 var status = AudioObjectGetPropertyDataSize( AudioObjectID(kAudioObjectSystemObject), &propertyAddress, 0, nil, &dataSize ) guard status == noErr, dataSize > 0 else { return [] } let deviceCount = Int(dataSize) / MemoryLayout<AudioDeviceID>.size var deviceIDs = [AudioDeviceID](repeating: 0, count: deviceCount) status = AudioObjectGetPropertyData( AudioObjectID(kAudioObjectSystemObject), &propertyAddress, 0, nil, &dataSize, &deviceIDs ) guard status == noErr else { return [] } var devices: [AudioDevice] = [] for deviceID in deviceIDs { // Check if device has input streams var inputStreamAddress = AudioObjectPropertyAddress( mSelector: kAudioDevicePropertyStreamConfiguration, mScope: kAudioDevicePropertyScopeInput, mElement: kAudioObjectPropertyElementMain ) var streamSize: UInt32 = 0 guard AudioObjectGetPropertyDataSize(deviceID, &inputStreamAddress, 0, nil, &streamSize) == noErr, streamSize > 0 else { continue } let bufferListPointer = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: 1) defer { bufferListPointer.deallocate() } guard AudioObjectGetPropertyData(deviceID, &inputStreamAddress, 0, nil, &streamSize, bufferListPointer) == noErr else { continue } let bufferList = UnsafeMutableAudioBufferListPointer(bufferListPointer) let inputChannels = bufferList.reduce(0) { $0 + Int($1.mNumberChannels) } guard inputChannels > 0 else { continue } // Get device UID var uidAddress = AudioObjectPropertyAddress( mSelector: kAudioDevicePropertyDeviceUID, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain ) var uidRef: Unmanaged<CFString>? var uidSize = UInt32(MemoryLayout<Unmanaged<CFString>?>.size) guard AudioObjectGetPropertyData(deviceID, &uidAddress, 0, nil, &uidSize, &uidRef) == noErr, let uid = uidRef?.takeUnretainedValue() as String? else { continue } // Get device name var nameAddress = AudioObjectPropertyAddress( mSelector: kAudioObjectPropertyName, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain ) var nameRef: Unmanaged<CFString>? var nameSize = UInt32(MemoryLayout<Unmanaged<CFString>?>.size) guard AudioObjectGetPropertyData(deviceID, &nameAddress, 0, nil, &nameSize, &nameRef) == noErr, let name = nameRef?.takeUnretainedValue() as String? else { continue } devices.append(AudioDevice(id: deviceID, uid: uid, name: name)) } return devices } static func deviceID(forUID uid: String) -> AudioDeviceID? { // Look up through the enumerated devices to avoid CFString pointer issues return availableInputDevices().first(where: { $0.uid == uid })?.id } } enum AudioRecorderError: LocalizedError { case invalidInputFormat(String) case missingInputDevice var errorDescription: String? { switch self { case .invalidInputFormat(let details): return "Invalid input format: \(details)" case .missingInputDevice: return "No audio input device available." } } } class AudioRecorder: NSObject, ObservableObject { private var audioEngine: AVAudioEngine? private var audioFile: AVAudioFile? private var tempFileURL: URL? private let audioFileQueue = DispatchQueue(label: "com.zachlatta.freeflow.audiofile") private var recordingStartTime: CFAbsoluteTime = 0 private var firstBufferLogged = false private var bufferCount: Int = 0 private var currentDeviceUID: String? private var storedInputFormat: AVAudioFormat? @Published var isRecording = false @Published var audioLevel: Float = 0.0 private var smoothedLevel: Float = 0.0 /// Called on the audio thread when the first non-silent buffer arrives. var onRecordingReady: (() -> Void)? private var readyFired = false func startRecording(deviceUID: String? = nil) throws { let t0 = CFAbsoluteTimeGetCurrent() recordingStartTime = t0 firstBufferLogged = false bufferCount = 0 readyFired = false os_log(.info, log: recordingLog, "startRecording() entered") guard AVCaptureDevice.default(for: .audio) != nil else { throw AudioRecorderError.missingInputDevice } os_log(.info, log: recordingLog, "AVCaptureDevice check: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) // Reuse existing engine if same device, otherwise build new one if let _ = audioEngine, currentDeviceUID == deviceUID { os_log(.info, log: recordingLog, "reusing existing engine: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) } else { // Tear down old engine if device changed if audioEngine != nil { audioEngine?.inputNode.removeTap(onBus: 0) audioEngine?.stop() audioEngine = nil } let engine = AVAudioEngine() os_log(.info, log: recordingLog, "AVAudioEngine created: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) // Set specific input device if requested if let uid = deviceUID, !uid.isEmpty, uid != "default", let deviceID = AudioDevice.deviceID(forUID: uid) { os_log(.info, log: recordingLog, "device lookup resolved to %d: %.3fms", deviceID, (CFAbsoluteTimeGetCurrent() - t0) * 1000) let inputUnit = engine.inputNode.audioUnit! var id = deviceID AudioUnitSetProperty( inputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &id, UInt32(MemoryLayout<AudioDeviceID>.size) ) } let inputNode = engine.inputNode os_log(.info, log: recordingLog, "inputNode accessed: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) let inputFormat = inputNode.outputFormat(forBus: 0) os_log(.info, log: recordingLog, "inputFormat retrieved (rate=%.0f, ch=%d): %.3fms", inputFormat.sampleRate, inputFormat.channelCount, (CFAbsoluteTimeGetCurrent() - t0) * 1000) guard inputFormat.sampleRate > 0 else { throw AudioRecorderError.invalidInputFormat("Invalid sample rate: \(inputFormat.sampleRate)") } guard inputFormat.channelCount > 0 else { throw AudioRecorderError.invalidInputFormat("No input channels available") } storedInputFormat = inputFormat // Install tap — checks isRecording and audioFile dynamically inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { [weak self] buffer, _ in guard let self, self.isRecording else { return } self.bufferCount += 1 // Check if this buffer has real audio var rms: Float = 0 let frames = Int(buffer.frameLength) if frames > 0, let channelData = buffer.floatChannelData { let samples = channelData[0] var sum: Float = 0 for i in 0..<frames { sum += samples[i] * samples[i] } rms = sqrtf(sum / Float(frames)) } if self.bufferCount <= 40 { let elapsed = (CFAbsoluteTimeGetCurrent() - self.recordingStartTime) * 1000 os_log(.info, log: recordingLog, "buffer #%d at %.3fms, frames=%d, rms=%.6f", self.bufferCount, elapsed, buffer.frameLength, rms) } // Fire ready callback on first non-silent buffer if !self.readyFired && rms > 0 { self.readyFired = true let elapsed = (CFAbsoluteTimeGetCurrent() - self.recordingStartTime) * 1000 os_log(.info, log: recordingLog, "FIRST non-silent buffer at %.3fms — recording ready", elapsed) self.onRecordingReady?() } self.audioFileQueue.sync { if let file = self.audioFile { do { try file.write(from: buffer) } catch { self.audioFile = nil } } } self.computeAudioLevel(from: buffer) } os_log(.info, log: recordingLog, "tap installed: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) engine.prepare() os_log(.info, log: recordingLog, "engine prepared: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) self.audioEngine = engine self.currentDeviceUID = deviceUID } // Start engine if not already running if let engine = audioEngine, !engine.isRunning { try engine.start() os_log(.info, log: recordingLog, "engine started: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) } guard let inputFormat = storedInputFormat else { throw AudioRecorderError.invalidInputFormat("No stored input format") } // Create a temp file to write audio to let tempDir = FileManager.default.temporaryDirectory let fileURL = tempDir.appendingPathComponent(UUID().uuidString + ".wav") self.tempFileURL = fileURL // Try the input format first to avoid conversion issues, then fall back to 16-bit PCM. let newAudioFile: AVAudioFile do { newAudioFile = try AVAudioFile(forWriting: fileURL, settings: inputFormat.settings) } catch { let fallbackSettings: [String: Any] = [ AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: inputFormat.sampleRate, AVNumberOfChannelsKey: inputFormat.channelCount, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsNonInterleaved: inputFormat.isInterleaved ? 0 : 1, ] newAudioFile = try AVAudioFile( forWriting: fileURL, settings: fallbackSettings, commonFormat: .pcmFormatInt16, interleaved: inputFormat.isInterleaved ) } os_log(.info, log: recordingLog, "audio file created: %.3fms", (CFAbsoluteTimeGetCurrent() - t0) * 1000) audioFileQueue.sync { self.audioFile = newAudioFile } self.isRecording = true os_log(.info, log: recordingLog, "startRecording() complete: %.3fms total", (CFAbsoluteTimeGetCurrent() - t0) * 1000) } func stopRecording() -> URL? { let elapsed = (CFAbsoluteTimeGetCurrent() - recordingStartTime) * 1000 os_log(.info, log: recordingLog, "stopRecording() called: %.3fms after start, %d buffers received", elapsed, bufferCount) audioFileQueue.sync { audioFile = nil } isRecording = false smoothedLevel = 0.0 DispatchQueue.main.async { self.audioLevel = 0.0 } // Stop engine so mic indicator goes away — keep engine object for fast restart audioEngine?.stop() os_log(.info, log: recordingLog, "engine stopped (mic indicator off)") return tempFileURL } private func computeAudioLevel(from buffer: AVAudioPCMBuffer) { let frames = Int(buffer.frameLength) guard frames > 0 else { return } var sumOfSquares: Float = 0.0 if let channelData = buffer.floatChannelData { let samples = channelData[0] for i in 0..<frames { let sample = samples[i] sumOfSquares += sample * sample } } else if let channelData = buffer.int16ChannelData { let samples = channelData[0] for i in 0..<frames { let sample = Float(samples[i]) / Float(Int16.max) sumOfSquares += sample * sample } } else { return } let rms = sqrtf(sumOfSquares / Float(frames)) // Scale RMS (~0.01-0.1 for speech) to 0-1 range let scaled = min(rms * 10.0, 1.0) // Fast attack, slower release — follows speech dynamics closely if scaled > smoothedLevel { smoothedLevel = smoothedLevel * 0.3 + scaled * 0.7 } else { smoothedLevel = smoothedLevel * 0.6 + scaled * 0.4 } DispatchQueue.main.async { self.audioLevel = self.smoothedLevel } } func cleanup() { if let url = tempFileURL { try? FileManager.default.removeItem(at: url) tempFileURL = nil } } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/HotkeyManager.swift
Swift
import Cocoa import Carbon enum HotkeyOption: String, CaseIterable, Identifiable { case fnKey = "fn" case rightOption = "rightOption" case f5 = "f5" var id: String { rawValue } var displayName: String { switch self { case .fnKey: return "Fn (Globe) Key" case .rightOption: return "Right Option Key" case .f5: return "F5 Key" } } var keyCode: UInt16 { switch self { case .fnKey: return 63 // Fn/Globe key case .rightOption: return 61 // Right Option case .f5: return 96 // F5 } } var isModifier: Bool { switch self { case .fnKey, .rightOption: return true case .f5: return false } } } class HotkeyManager { private var globalFlagsMonitor: Any? private var localFlagsMonitor: Any? private var globalKeyDownMonitor: Any? private var globalKeyUpMonitor: Any? private var localKeyDownMonitor: Any? private var localKeyUpMonitor: Any? private var isKeyDown = false private var currentOption: HotkeyOption = .fnKey var onKeyDown: (() -> Void)? var onKeyUp: (() -> Void)? func start(option: HotkeyOption) { stop() currentOption = option isKeyDown = false if option.isModifier { globalFlagsMonitor = NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) { [weak self] event in self?.handleFlagsChanged(event: event) } localFlagsMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] event in self?.handleFlagsChanged(event: event) return event } } else { // For regular keys like F5, monitor keyDown/keyUp globalKeyDownMonitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in self?.handleKeyDown(event: event) } globalKeyUpMonitor = NSEvent.addGlobalMonitorForEvents(matching: .keyUp) { [weak self] event in self?.handleKeyUp(event: event) } localKeyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in self?.handleKeyDown(event: event) return event } localKeyUpMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyUp) { [weak self] event in self?.handleKeyUp(event: event) return event } } } private func handleFlagsChanged(event: NSEvent) { guard event.keyCode == currentOption.keyCode else { return } let flagIsSet: Bool switch currentOption { case .fnKey: flagIsSet = event.modifierFlags.contains(.function) case .rightOption: flagIsSet = event.modifierFlags.contains(.option) default: return } if flagIsSet && !isKeyDown { isKeyDown = true onKeyDown?() } else if !flagIsSet && isKeyDown { isKeyDown = false onKeyUp?() } } private func handleKeyDown(event: NSEvent) { guard event.keyCode == currentOption.keyCode else { return } guard !event.isARepeat else { return } // Ignore key repeat if !isKeyDown { isKeyDown = true onKeyDown?() } } private func handleKeyUp(event: NSEvent) { guard event.keyCode == currentOption.keyCode else { return } if isKeyDown { isKeyDown = false onKeyUp?() } } func stop() { if let m = globalFlagsMonitor { NSEvent.removeMonitor(m) } if let m = localFlagsMonitor { NSEvent.removeMonitor(m) } if let m = globalKeyDownMonitor { NSEvent.removeMonitor(m) } if let m = globalKeyUpMonitor { NSEvent.removeMonitor(m) } if let m = localKeyDownMonitor { NSEvent.removeMonitor(m) } if let m = localKeyUpMonitor { NSEvent.removeMonitor(m) } globalFlagsMonitor = nil localFlagsMonitor = nil globalKeyDownMonitor = nil globalKeyUpMonitor = nil localKeyDownMonitor = nil localKeyUpMonitor = nil isKeyDown = false } deinit { stop() } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/KeychainStorage.swift
Swift
import Foundation import Security enum AppSettingsStorage { private static let bundleID = Bundle.main.bundleIdentifier ?? "com.zachlatta.freeflow" private static var storageDirectory: URL { let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "FreeFlow" let dir = appSupport.appendingPathComponent(appName, isDirectory: true) if !FileManager.default.fileExists(atPath: dir.path) { try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) } return dir } private static var settingsFileURL: URL { storageDirectory.appendingPathComponent(".settings") } // MARK: - Public API static func load(account: String) -> String? { migrateFromKeychainIfNeeded(account: account) let dict = loadSettings() return dict[account] } static func save(_ value: String, account: String) { var dict = loadSettings() dict[account] = value writeSettings(dict) } static func delete(account: String) { var dict = loadSettings() dict.removeValue(forKey: account) writeSettings(dict) } // MARK: - File I/O private static func loadSettings() -> [String: String] { let url = settingsFileURL guard FileManager.default.fileExists(atPath: url.path), let data = try? Data(contentsOf: url), let dict = try? JSONDecoder().decode([String: String].self, from: data) else { return [:] } return dict } private static func writeSettings(_ dict: [String: String]) { guard let data = try? JSONEncoder().encode(dict) else { return } let url = settingsFileURL try? data.write(to: url, options: [.atomic]) // Restrict to owner-only read/write (0600) try? FileManager.default.setAttributes( [.posixPermissions: 0o600], ofItemAtPath: url.path ) } // MARK: - One-time migration from Keychain private static let migrationDoneKey = "keychain_migration_done" private static func migrateFromKeychainIfNeeded(account: String) { let dict = loadSettings() if dict[migrationDoneKey] != nil { return } // Try to load from Keychain if let keychainValue = loadFromKeychain(account: account), !keychainValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { var updated = dict updated[account] = keychainValue updated[migrationDoneKey] = "true" writeSettings(updated) // Clean up old keychain entry deleteFromKeychain(account: account) } else { // Mark migration as done even if nothing was in Keychain var updated = dict updated[migrationDoneKey] = "true" writeSettings(updated) } } // MARK: - Legacy Keychain helpers (for migration only) private static func loadFromKeychain(account: String) -> String? { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: bundleID, kSecAttrAccount as String: account, kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne ] var result: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &result) guard status == errSecSuccess, let data = result as? Data, let value = String(data: data, encoding: .utf8) else { return nil } return value } private static func deleteFromKeychain(account: String) { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: bundleID, kSecAttrAccount as String: account ] SecItemDelete(query as CFDictionary) } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/MenuBarView.swift
Swift
import SwiftUI struct MenuBarView: View { @EnvironmentObject var appState: AppState @ObservedObject private var updateManager = UpdateManager.shared private var appVersion: String { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0" } var body: some View { VStack(spacing: 4) { Text("FreeFlow v\(appVersion)") .font(.caption) .foregroundStyle(.secondary) .padding(.horizontal, 16) .padding(.vertical, 4) Divider() if !appState.hasScreenRecordingPermission { Button { appState.requestScreenCapturePermission() } label: { Label("Screen Recording Permission Needed", systemImage: "camera.viewfinder") } .buttonStyle(.plain) .foregroundStyle(.white) .font(.caption.weight(.semibold)) .padding(.horizontal, 16) .padding(.vertical, 8) .frame(maxWidth: .infinity) .background(Color.orange) Divider() } // Accessibility warning if !appState.hasAccessibility { Button { appState.showAccessibilityAlert() } label: { Label("Accessibility Required", systemImage: "exclamationmark.triangle.fill") } .buttonStyle(.plain) .foregroundStyle(.white) .font(.caption.weight(.semibold)) .padding(.horizontal, 16) .padding(.vertical, 8) .frame(maxWidth: .infinity) .background(Color.red) Divider() } // Status if appState.isRecording { Label("Recording...", systemImage: "record.circle") .foregroundStyle(.red) .padding(.horizontal, 16) .padding(.vertical, 6) } else if appState.isTranscribing { Label(appState.debugStatusMessage, systemImage: "ellipsis.circle") .foregroundStyle(.secondary) .padding(.horizontal, 16) .padding(.vertical, 6) } else { Text("Hold \(appState.selectedHotkey.displayName) to dictate") .foregroundStyle(.secondary) .font(.caption) .padding(.horizontal, 16) .padding(.vertical, 6) } Divider() // Manual toggle Button(appState.isRecording ? "Stop Recording" : "Start Dictating") { appState.toggleRecording() } .disabled(appState.isTranscribing) if let error = appState.errorMessage { Divider() Text(error) .foregroundStyle(.red) .font(.caption) .padding(.horizontal, 16) .lineLimit(3) } if !appState.lastTranscript.isEmpty && !appState.isRecording && !appState.isTranscribing { Divider() Text(appState.lastTranscript) .font(.caption) .foregroundStyle(.secondary) .padding(.horizontal, 16) .lineLimit(4) .frame(maxWidth: 280, alignment: .leading) Button("Copy Again") { NSPasteboard.general.clearContents() NSPasteboard.general.setString(appState.lastTranscript, forType: .string) } } Divider() // Hotkey picker Menu("Push-to-Talk Key") { ForEach(HotkeyOption.allCases) { option in Button { appState.selectedHotkey = option } label: { if appState.selectedHotkey == option { Text("✓ \(option.displayName)") } else { Text(" \(option.displayName)") } } } } Menu("Microphone") { Button { appState.selectedMicrophoneID = "default" } label: { if appState.selectedMicrophoneID == "default" || appState.selectedMicrophoneID.isEmpty { Text("✓ System Default") } else { Text(" System Default") } } ForEach(appState.availableMicrophones) { device in Button { appState.selectedMicrophoneID = device.uid } label: { if appState.selectedMicrophoneID == device.uid { Text("✓ \(device.name)") } else { Text(" \(device.name)") } } } } Button("Re-run Setup...") { NotificationCenter.default.post(name: .showSetup, object: nil) } Button("Settings") { NotificationCenter.default.post(name: .showSettings, object: nil) } Divider() Button(appState.isDebugOverlayActive ? "Stop Debug Overlay" : "Debug Overlay") { appState.toggleDebugOverlay() } if updateManager.updateAvailable { Divider() switch updateManager.updateStatus { case .downloading: VStack(spacing: 4) { Text("Downloading update... \(Int((updateManager.downloadProgress ?? 0) * 100))%") .font(.caption.weight(.semibold)) .foregroundStyle(.white) ProgressView(value: updateManager.downloadProgress ?? 0) .progressViewStyle(.linear) .tint(.white) } .padding(.horizontal, 16) .padding(.vertical, 8) .frame(maxWidth: .infinity) .background(Color.blue) case .installing, .readyToRelaunch: HStack(spacing: 6) { ProgressView() .controlSize(.small) Text("Installing update...") .font(.caption.weight(.semibold)) } .foregroundStyle(.white) .padding(.horizontal, 16) .padding(.vertical, 8) .frame(maxWidth: .infinity) .background(Color.blue) default: Button { updateManager.showUpdateAlert() } label: { Label("Update Available", systemImage: "arrow.down.circle.fill") } .buttonStyle(.plain) .foregroundStyle(.white) .font(.caption.weight(.semibold)) .padding(.horizontal, 16) .padding(.vertical, 8) .frame(maxWidth: .infinity) .background(Color.blue) } } Divider() Button("Quit FreeFlow") { NSApplication.shared.terminate(nil) } .keyboardShortcut("q") } .padding(4) } } extension Notification.Name { static let showSetup = Notification.Name("showSetup") static let showSettings = Notification.Name("showSettings") }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/Notification+VoiceToText.swift
Swift
import Foundation // Notification names defined in MenuBarView.swift: // .showSetup, .showSettings
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/PipelineDebugContentView.swift
Swift
import SwiftUI import AppKit func imageFromDataURL(_ dataURL: String) -> NSImage? { guard let commaIndex = dataURL.lastIndex(of: ",") else { return nil } let base64 = String(dataURL[dataURL.index(after: commaIndex)...]) guard let data = Data(base64Encoded: base64, options: .ignoreUnknownCharacters) else { return nil } return NSImage(data: data) } struct PipelineDebugContentView: View { let statusMessage: String let postProcessingStatus: String let contextSummary: String let contextScreenshotStatus: String let contextScreenshotDataURL: String? let rawTranscript: String let postProcessedTranscript: String let postProcessingPrompt: String var body: some View { VStack(alignment: .leading, spacing: 16) { if !statusMessage.isEmpty { debugRow(title: "Status", value: statusMessage) } if !postProcessingStatus.isEmpty { debugRow(title: "Post-Processing", value: postProcessingStatus) } if !postProcessingPrompt.isEmpty { debugRow(title: "Post-Processing Prompt", value: postProcessingPrompt, copyText: postProcessingPrompt) } if !contextSummary.isEmpty { debugRow(title: "Context", value: contextSummary) } if !contextScreenshotStatus.isEmpty || contextScreenshotDataURL != nil { screenshotSection( status: contextScreenshotStatus, dataURL: contextScreenshotDataURL ) } if !rawTranscript.isEmpty { debugRow(title: "Raw Transcript", value: rawTranscript, copyText: rawTranscript) } if !postProcessedTranscript.isEmpty { debugRow(title: "Post-Processed Transcript", value: postProcessedTranscript, copyText: postProcessedTranscript) } if contextSummary.isEmpty && rawTranscript.isEmpty && postProcessedTranscript.isEmpty && postProcessingPrompt.isEmpty { Text("No debug data for this entry.") .font(.caption) .foregroundStyle(.secondary) } } .padding(.vertical, 4) } private func debugRow(title: String, value: String, copyText: String? = nil) -> some View { VStack(alignment: .leading, spacing: 6) { Text(title) .font(.body.bold()) ScrollView { Text(value) .textSelection(.enabled) .font(.system(size: 15, weight: .regular, design: .monospaced)) .frame(maxWidth: .infinity, alignment: .leading) } .frame(maxHeight: 160) .padding(10) .background(Color(nsColor: .textBackgroundColor)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.2))) if let copyText { Button("Copy \(title)") { NSPasteboard.general.clearContents() NSPasteboard.general.setString(copyText, forType: .string) } .font(.body) } } } private func screenshotSection(status: String, dataURL: String?) -> some View { VStack(alignment: .leading, spacing: 6) { Text("Context Screenshot") .font(.body.bold()) Text("Status: \(status)") .font(.caption) .foregroundStyle(isScreenshotUnavailable(status) ? .red : .secondary) if let dataURL, let image = imageFromDataURL(dataURL) { ScrollView([.horizontal, .vertical]) { Image(nsImage: image) .resizable() .aspectRatio(contentMode: .fit) .frame(maxWidth: .infinity, minHeight: 180, maxHeight: 320, alignment: .center) .padding(10) } .frame(maxHeight: 320) .background(Color(nsColor: .textBackgroundColor)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.2))) if let payloadBytes = screenshotPayloadBytes(dataURL: dataURL) { Text("Screenshot payload: \(payloadBytes / 1024) KB (Base64)") .font(.caption2) .foregroundStyle(.secondary) } HStack(spacing: 8) { Button("Open in Preview") { openImageInPreview(image) } .font(.body) Button("Copy Screenshot") { copyImageToPasteboard(image) } .font(.body) } } else { VStack(alignment: .leading, spacing: 8) { Text("No screenshot image available.") .font(.callout) .foregroundStyle(.secondary) .padding(10) } .frame(maxWidth: .infinity, alignment: .leading) .background(Color(nsColor: .textBackgroundColor)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.2))) } } } private func screenshotPayloadBytes(dataURL: String) -> Int? { guard let commaIndex = dataURL.lastIndex(of: ",") else { return nil } let base64 = String(dataURL[dataURL.index(after: commaIndex)...]) return Data(base64Encoded: base64, options: .ignoreUnknownCharacters)?.count } private func isScreenshotUnavailable(_ status: String) -> Bool { let lowered = status.lowercased() return lowered.contains("could not") || lowered.contains("no screenshot") || lowered.contains("not available") } private func openImageInPreview(_ image: NSImage) { guard let imageData = image.tiffRepresentation, let rep = NSBitmapImageRep(data: imageData), let pngData = rep.representation(using: .png, properties: [:]) else { return } let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("voice-to-text-context-screenshot.png", isDirectory: false) do { try pngData.write(to: tempURL) NSWorkspace.shared.open(tempURL) } catch { return } } private func copyImageToPasteboard(_ image: NSImage) { let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.writeObjects([image]) } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/PipelineDebugPanelView.swift
Swift
import SwiftUI struct PipelineDebugPanelView: View { @EnvironmentObject var appState: AppState var body: some View { VStack(alignment: .leading, spacing: 16) { header Divider() PipelineDebugContentView( statusMessage: appState.debugStatusMessage, postProcessingStatus: appState.lastPostProcessingStatus, contextSummary: appState.lastContextSummary, contextScreenshotStatus: appState.lastContextScreenshotStatus, contextScreenshotDataURL: appState.lastContextScreenshotDataURL, rawTranscript: appState.lastRawTranscript, postProcessedTranscript: appState.lastPostProcessedTranscript, postProcessingPrompt: appState.lastPostProcessingPrompt ) if appState.lastContextSummary.isEmpty && appState.lastRawTranscript.isEmpty { Text("Run a dictation pass to populate debug output.") .font(.caption) .foregroundStyle(.secondary) } Spacer() } .padding(16) .frame(width: 620, height: 640, alignment: .topLeading) } private var header: some View { VStack(alignment: .leading, spacing: 6) { Text("Pipeline Debug") .font(.title3) Text("Live data for the transcription + post-processing pipeline.") .font(.body) .foregroundStyle(.secondary) } } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/PipelineHistoryItem.swift
Swift
import Foundation struct PipelineHistoryItem: Identifiable, Codable { let id: UUID let timestamp: Date let rawTranscript: String let postProcessedTranscript: String let postProcessingPrompt: String? let contextSummary: String let contextPrompt: String? let contextScreenshotDataURL: String? let contextScreenshotStatus: String let postProcessingStatus: String let debugStatus: String let customVocabulary: String let audioFileName: String? init( id: UUID = UUID(), timestamp: Date, rawTranscript: String, postProcessedTranscript: String, postProcessingPrompt: String?, contextSummary: String, contextPrompt: String?, contextScreenshotDataURL: String?, contextScreenshotStatus: String, postProcessingStatus: String, debugStatus: String, customVocabulary: String, audioFileName: String? = nil ) { self.id = id self.timestamp = timestamp self.rawTranscript = rawTranscript self.postProcessedTranscript = postProcessedTranscript self.postProcessingPrompt = postProcessingPrompt self.contextSummary = contextSummary self.contextPrompt = contextPrompt self.contextScreenshotDataURL = contextScreenshotDataURL self.contextScreenshotStatus = contextScreenshotStatus self.postProcessingStatus = postProcessingStatus self.debugStatus = debugStatus self.customVocabulary = customVocabulary self.audioFileName = audioFileName } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/PipelineHistoryStore.swift
Swift
import Foundation import CoreData final class PipelineHistoryStore { private let container: NSPersistentContainer init() { let model = Self.makeModel() container = NSPersistentContainer(name: "PipelineHistory", managedObjectModel: model) if let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first { let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "FreeFlow" let baseURL = appSupport.appendingPathComponent(appName, isDirectory: true) try? FileManager.default.createDirectory(at: baseURL, withIntermediateDirectories: true) let storeURL = baseURL.appendingPathComponent("PipelineHistory.sqlite") let description = NSPersistentStoreDescription(url: storeURL) description.shouldMigrateStoreAutomatically = true description.shouldInferMappingModelAutomatically = true container.persistentStoreDescriptions = [description] } container.loadPersistentStores { description, error in if let error = error { print("[PipelineHistoryStore] Failed to load persistent store at \(description.url?.path ?? "unknown"): \(error)") // Attempt to recover by destroying and recreating the store if let storeURL = description.url { try? FileManager.default.removeItem(at: storeURL) self.container.loadPersistentStores { _, retryError in if let retryError = retryError { print("[PipelineHistoryStore] Failed to recreate store: \(retryError)") } } } } } } func loadAllHistory() -> [PipelineHistoryItem] { let request = pipelineHistoryRequest() request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)] guard let entities = try? container.viewContext.fetch(request) else { return [] } return entities.compactMap(Self.makeHistoryItem(from:)) } func append(_ item: PipelineHistoryItem, maxCount: Int) throws -> [String] { try insert(item) return try trim(to: maxCount) } func delete(id: UUID) throws -> String? { let request = pipelineHistoryRequest() request.predicate = NSPredicate(format: "id == %@", id as CVarArg) guard let entity = try? container.viewContext.fetch(request).first else { return nil } let audioFileName = entity.audioFileName container.viewContext.delete(entity) try saveContext() return audioFileName } func clearAll() throws -> [String] { let request = pipelineHistoryRequest() request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)] guard let entities = try? container.viewContext.fetch(request) else { return [] } let audioFileNames = entities.compactMap(\.audioFileName) for entity in entities { container.viewContext.delete(entity) } try saveContext() return audioFileNames } func trim(to maxCount: Int) throws -> [String] { guard maxCount > 0 else { let audioFileNames = try clearAll() return audioFileNames } let request = pipelineHistoryRequest() request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)] guard let entities = try? container.viewContext.fetch(request), entities.count > maxCount else { return [] } let dropped = entities[maxCount...] let audioFileNames = dropped.compactMap(\.audioFileName) for entity in dropped { container.viewContext.delete(entity) } try saveContext() return audioFileNames } private func insert(_ item: PipelineHistoryItem) throws { let context = container.viewContext let entity = PipelineHistoryEntry(context: context) entity.id = item.id entity.timestamp = item.timestamp entity.rawTranscript = item.rawTranscript entity.postProcessedTranscript = item.postProcessedTranscript entity.postProcessingPrompt = item.postProcessingPrompt entity.contextSummary = item.contextSummary entity.contextPrompt = item.contextPrompt entity.contextScreenshotDataURL = item.contextScreenshotDataURL entity.contextScreenshotStatus = item.contextScreenshotStatus entity.postProcessingStatus = item.postProcessingStatus entity.debugStatus = item.debugStatus entity.customVocabulary = item.customVocabulary entity.audioFileName = item.audioFileName try saveContext() } private func saveContext() throws { guard container.viewContext.hasChanges else { return } do { try container.viewContext.save() } catch { container.viewContext.rollback() throw error } } private func pipelineHistoryRequest() -> NSFetchRequest<PipelineHistoryEntry> { NSFetchRequest<PipelineHistoryEntry>(entityName: "PipelineHistoryEntry") } private static func makeHistoryItem(from entity: PipelineHistoryEntry) -> PipelineHistoryItem { PipelineHistoryItem( id: entity.id, timestamp: entity.timestamp ?? Date(), rawTranscript: entity.rawTranscript ?? "", postProcessedTranscript: entity.postProcessedTranscript ?? "", postProcessingPrompt: entity.postProcessingPrompt, contextSummary: entity.contextSummary ?? "", contextPrompt: entity.contextPrompt, contextScreenshotDataURL: entity.contextScreenshotDataURL, contextScreenshotStatus: entity.contextScreenshotStatus ?? "available (image)", postProcessingStatus: entity.postProcessingStatus ?? "", debugStatus: entity.debugStatus ?? "", customVocabulary: entity.customVocabulary ?? "", audioFileName: entity.audioFileName ) } private static func makeModel() -> NSManagedObjectModel { let model = NSManagedObjectModel() let entity = NSEntityDescription() entity.name = "PipelineHistoryEntry" entity.managedObjectClassName = NSStringFromClass(PipelineHistoryEntry.self) entity.properties = [ makeAttribute(name: "id", type: .UUIDAttributeType, isOptional: false), makeAttribute(name: "timestamp", type: .dateAttributeType, isOptional: false), makeAttribute(name: "rawTranscript", type: .stringAttributeType, isOptional: false), makeAttribute(name: "postProcessedTranscript", type: .stringAttributeType, isOptional: false), makeAttribute(name: "postProcessingPrompt", type: .stringAttributeType, isOptional: true), makeAttribute(name: "contextSummary", type: .stringAttributeType, isOptional: false), makeAttribute(name: "contextPrompt", type: .stringAttributeType, isOptional: true), makeAttribute(name: "contextScreenshotDataURL", type: .stringAttributeType, isOptional: true), makeAttribute(name: "contextScreenshotStatus", type: .stringAttributeType, isOptional: false), makeAttribute(name: "postProcessingStatus", type: .stringAttributeType, isOptional: false), makeAttribute(name: "debugStatus", type: .stringAttributeType, isOptional: false), makeAttribute(name: "customVocabulary", type: .stringAttributeType, isOptional: false), makeAttribute(name: "audioFileName", type: .stringAttributeType, isOptional: true) ] model.entities = [entity] return model } private static func makeAttribute(name: String, type: NSAttributeType, isOptional: Bool) -> NSAttributeDescription { let attribute = NSAttributeDescription() attribute.name = name attribute.attributeType = type attribute.isOptional = isOptional return attribute } } @objc(PipelineHistoryEntry) final class PipelineHistoryEntry: NSManagedObject { @NSManaged var id: UUID @NSManaged var timestamp: Date? @NSManaged var rawTranscript: String? @NSManaged var postProcessedTranscript: String? @NSManaged var postProcessingPrompt: String? @NSManaged var contextSummary: String? @NSManaged var contextPrompt: String? @NSManaged var contextScreenshotDataURL: String? @NSManaged var contextScreenshotStatus: String? @NSManaged var postProcessingStatus: String? @NSManaged var debugStatus: String? @NSManaged var customVocabulary: String? @NSManaged var audioFileName: String? }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/PostProcessingService.swift
Swift
import Foundation enum PostProcessingError: LocalizedError { case requestFailed(Int, String) case invalidResponse(String) case requestTimedOut(TimeInterval) var errorDescription: String? { switch self { case .requestFailed(let statusCode, let details): "Post-processing failed with status \(statusCode): \(details)" case .invalidResponse(let details): "Invalid post-processing response: \(details)" case .requestTimedOut(let seconds): "Post-processing timed out after \(Int(seconds))s" } } } struct PostProcessingResult { let transcript: String let prompt: String } final class PostProcessingService { private let apiKey: String private let baseURL = "https://api.groq.com/openai/v1" private let defaultModel = "meta-llama/llama-4-scout-17b-16e-instruct" private let postProcessingTimeoutSeconds: TimeInterval = 20 init(apiKey: String) { self.apiKey = apiKey } func postProcess( transcript: String, context: AppContext, customVocabulary: String ) async throws -> PostProcessingResult { let vocabularyTerms = mergedVocabularyTerms(rawVocabulary: customVocabulary) let timeoutSeconds = postProcessingTimeoutSeconds return try await withThrowingTaskGroup(of: PostProcessingResult.self) { group in group.addTask { [weak self] in guard let self else { throw PostProcessingError.invalidResponse("Post-processing service deallocated") } return try await self.process( transcript: transcript, contextSummary: context.contextSummary, model: defaultModel, customVocabulary: vocabularyTerms ) } group.addTask { try await Task.sleep(nanoseconds: UInt64(timeoutSeconds * 1_000_000_000)) throw PostProcessingError.requestTimedOut(timeoutSeconds) } do { guard let result = try await group.next() else { throw PostProcessingError.invalidResponse("No post-processing result") } group.cancelAll() return result } catch { group.cancelAll() throw error } } } private func process( transcript: String, contextSummary: String, model: String, customVocabulary: [String] ) async throws -> PostProcessingResult { var request = URLRequest(url: URL(string: "\(baseURL)/chat/completions")!) request.httpMethod = "POST" request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.timeoutInterval = postProcessingTimeoutSeconds let normalizedVocabulary = normalizedVocabularyText(customVocabulary) let vocabularyPrompt = if !normalizedVocabulary.isEmpty { """ The following vocabulary must be treated as high-priority terms while rewriting. Use these spellings exactly in the output when relevant: \(normalizedVocabulary) """ } else { "" } var systemPrompt = """ You are a dictation post-processor. You receive raw speech-to-text output and return clean text ready to be typed into an application. Your job: - Remove filler words (um, uh, you know, like) unless they carry meaning. - Fix spelling, grammar, and punctuation errors. - When the transcript already contains a word that is a close misspelling of a name or term from the context or custom vocabulary, correct the spelling. Never insert names or terms from context that the speaker did not say. - Preserve the speaker's intent, tone, and meaning exactly. Output rules: - Return ONLY the cleaned transcript text, nothing else. - If the transcription is empty, return exactly: EMPTY - Do not add words, names, or content that are not in the transcription. The context is only for correcting spelling of words already spoken. - Do not change the meaning of what was said. """ if !vocabularyPrompt.isEmpty { systemPrompt += "\n\n" + vocabularyPrompt } let userMessage = """ Instructions: Clean up this RAW_TRANSCRIPTION. Return EMPTY if there should be no result. CONTEXT: "\(contextSummary)" RAW_TRANSCRIPTION: "\(transcript)" """ let promptForDisplay = """ Model: \(model) [System] \(systemPrompt) [User] \(userMessage) """ let payload: [String: Any] = [ "model": model, "temperature": 0.0, "messages": [ [ "role": "system", "content": systemPrompt ], [ "role": "user", "content": userMessage ] ] ] request.httpBody = try JSONSerialization.data(withJSONObject: payload, options: []) let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { throw PostProcessingError.invalidResponse("No HTTP response") } guard httpResponse.statusCode == 200 else { let message = String(data: data, encoding: .utf8) ?? "" throw PostProcessingError.requestFailed(httpResponse.statusCode, message) } guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let choices = json["choices"] as? [[String: Any]], let firstChoice = choices.first, let message = firstChoice["message"] as? [String: Any], let content = message["content"] as? String else { throw PostProcessingError.invalidResponse("Missing choices[0].message.content") } return PostProcessingResult( transcript: sanitizePostProcessedTranscript(content), prompt: promptForDisplay ) } private func sanitizePostProcessedTranscript(_ value: String) -> String { var result = value.trimmingCharacters(in: .whitespacesAndNewlines) guard !result.isEmpty else { return "" } // Strip outer quotes if the LLM wrapped the entire response if result.hasPrefix("\"") && result.hasSuffix("\"") && result.count > 1 { result.removeFirst() result.removeLast() result = result.trimmingCharacters(in: .whitespacesAndNewlines) } // Treat the sentinel value as empty if result == "EMPTY" { return "" } return result } private func mergedVocabularyTerms(rawVocabulary: String) -> [String] { let terms = rawVocabulary .split(whereSeparator: { $0 == "\n" || $0 == "," || $0 == ";" }) .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } var seen = Set<String>() return terms.filter { seen.insert($0.lowercased()).inserted } } private func normalizedVocabularyText(_ vocabularyTerms: [String]) -> String { let terms = vocabularyTerms .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } guard !terms.isEmpty else { return "" } return terms.joined(separator: ", ") } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/RecordingOverlay.swift
Swift
import SwiftUI import AppKit // MARK: - State class RecordingOverlayState: ObservableObject { @Published var phase: OverlayPhase = .recording @Published var audioLevel: Float = 0.0 } enum OverlayPhase { case initializing case recording case transcribing case done } // MARK: - Panel Helpers private func makeOverlayPanel(width: CGFloat, height: CGFloat) -> NSPanel { let panel = NSPanel( contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false ) panel.backgroundColor = .clear panel.isOpaque = false panel.hasShadow = true panel.level = .screenSaver panel.ignoresMouseEvents = true panel.collectionBehavior = [.canJoinAllSpaces] panel.isReleasedWhenClosed = false panel.hidesOnDeactivate = false return panel } /// Creates a container with a vibrancy blur layer and a SwiftUI overlay for the liquid glass effect. private func makeGlassContent<V: View>( width: CGFloat, height: CGFloat, cornerRadius: CGFloat, maskedCorners: CACornerMask = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner], rootView: V ) -> NSView { let scaleFactor = NSScreen.main?.backingScaleFactor ?? 2.0 let container = NSView(frame: NSRect(x: 0, y: 0, width: width, height: height)) container.wantsLayer = true container.layer?.contentsScale = scaleFactor let blur = NSVisualEffectView(frame: container.bounds) blur.appearance = NSAppearance(named: .darkAqua) blur.material = .hudWindow blur.blendingMode = .behindWindow blur.state = .active blur.wantsLayer = true blur.layer?.contentsScale = scaleFactor blur.layer?.cornerRadius = cornerRadius blur.layer?.maskedCorners = maskedCorners blur.layer?.masksToBounds = true blur.autoresizingMask = [.width, .height] container.addSubview(blur) let hosting = NSHostingView(rootView: rootView) hosting.frame = container.bounds hosting.autoresizingMask = [.width, .height] hosting.layer?.contentsScale = scaleFactor container.addSubview(hosting) return container } // MARK: - Manager class RecordingOverlayManager { private var overlayWindow: NSPanel? private var transcribingPanel: NSPanel? private var overlayState = RecordingOverlayState() /// Whether the main screen has a camera housing (notch). private var screenHasNotch: Bool { guard let screen = NSScreen.main else { return false } return screen.safeAreaInsets.top > 0 } func showInitializing() { DispatchQueue.main.async { self.overlayState.phase = .initializing self.overlayState.audioLevel = 0.0 self._showOverlayPanel() } } func showRecording() { DispatchQueue.main.async { self.overlayState.phase = .recording self.overlayState.audioLevel = 0.0 self._showOverlayPanel() } } func transitionToRecording() { DispatchQueue.main.async { self.overlayState.phase = .recording } } func updateAudioLevel(_ level: Float) { DispatchQueue.main.async { self.overlayState.audioLevel = level } } func showTranscribing() { DispatchQueue.main.async { self._showTranscribing() } } func slideUpToNotch(completion: @escaping () -> Void) { DispatchQueue.main.async { self._slideUpToNotch(completion: completion) } } func showDone() { DispatchQueue.main.async { self._showDone() } } func dismiss() { DispatchQueue.main.async { self._dismiss() } } private func _showOverlayPanel() { let panelWidth: CGFloat = 120 let panelHeight: CGFloat = 32 let hasNotch = screenHasNotch let notchInset: CGFloat = 4 // tuck flat top behind menu bar (notch screens only) if let panel = overlayWindow { guard let screen = NSScreen.main else { return } let x = panelX(screen, width: panelWidth) let y: CGFloat if hasNotch { y = screen.visibleFrame.maxY - panelHeight + notchInset } else { y = screen.frame.maxY - panelHeight } panel.setFrame(NSRect(x: x, y: y, width: panelWidth, height: panelHeight), display: true) panel.alphaValue = 1 panel.orderFrontRegardless() return } let panel = makeOverlayPanel(width: panelWidth, height: panelHeight) let view = RecordingOverlayView(state: overlayState) panel.contentView = makeGlassContent( width: panelWidth, height: panelHeight, cornerRadius: 12, maskedCorners: [.layerMinXMinYCorner, .layerMaxXMinYCorner], rootView: view ) if let screen = NSScreen.main { let x = panelX(screen, width: panelWidth) let hiddenY: CGFloat let visibleY: CGFloat if hasNotch { // Start hidden behind menu bar, pop out from notch hiddenY = screen.visibleFrame.maxY visibleY = screen.visibleFrame.maxY - panelHeight + notchInset } else { // Start hidden above screen top, pop in from very top hiddenY = screen.frame.maxY visibleY = screen.frame.maxY - panelHeight } panel.setFrame(NSRect(x: x, y: hiddenY, width: panelWidth, height: panelHeight), display: true) panel.alphaValue = 1 panel.orderFrontRegardless() // Spring-like drop: overshoots slightly then settles NSAnimationContext.runAnimationGroup { ctx in ctx.duration = 0.18 ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.34, 1.56, 0.64, 1.0) panel.animator().setFrame(NSRect(x: x, y: visibleY, width: panelWidth, height: panelHeight), display: true) } } self.overlayWindow = panel } private func _slideUpToNotch(completion: @escaping () -> Void) { guard let panel = overlayWindow, let screen = NSScreen.main else { completion() return } let hiddenY = screenHasNotch ? screen.visibleFrame.maxY : screen.frame.maxY let frame = panel.frame NSAnimationContext.runAnimationGroup({ context in context.duration = 0.09 context.timingFunction = CAMediaTimingFunction(controlPoints: 0.4, 0.0, 1.0, 1.0) panel.animator().setFrame(NSRect(x: frame.origin.x, y: hiddenY, width: frame.width, height: frame.height), display: true) }, completionHandler: { panel.orderOut(nil) self.overlayWindow = nil completion() }) } private func _showTranscribing() { overlayState.phase = .transcribing if let panel = overlayWindow { panel.orderOut(nil) overlayWindow = nil } if transcribingPanel != nil { return } let panelWidth: CGFloat = 44 let panelHeight: CGFloat = 22 let panel = makeOverlayPanel(width: panelWidth, height: panelHeight) let view = TranscribingIndicatorView() panel.contentView = makeGlassContent( width: panelWidth, height: panelHeight, cornerRadius: 11, maskedCorners: [.layerMinXMinYCorner, .layerMaxXMinYCorner], rootView: view ) if let screen = NSScreen.main { let x = panelX(screen, width: panelWidth) let y: CGFloat if screenHasNotch { y = screen.visibleFrame.maxY - panelHeight } else { y = screen.frame.maxY - panelHeight } panel.setFrame(NSRect(x: x, y: y, width: panelWidth, height: panelHeight), display: true) } panel.alphaValue = 0 panel.orderFrontRegardless() NSAnimationContext.runAnimationGroup { context in context.duration = 0.25 panel.animator().alphaValue = 1 } self.transcribingPanel = panel } private func _showDone() { overlayState.phase = .done if let panel = transcribingPanel { NSAnimationContext.runAnimationGroup({ context in context.duration = 0.2 panel.animator().alphaValue = 0 }, completionHandler: { panel.orderOut(nil) self.transcribingPanel = nil }) } } private func _dismiss() { if let panel = overlayWindow { panel.orderOut(nil) overlayWindow = nil } if let panel = transcribingPanel { panel.orderOut(nil) transcribingPanel = nil } } private func panelX(_ screen: NSScreen, width: CGFloat) -> CGFloat { screen.frame.midX - width / 2 } } // MARK: - Liquid Glass Overlay /// Decorative layers on top of the NSVisualEffectView blur to create a liquid glass appearance: /// a specular highlight gradient and a gradient border that's brighter where light hits. private struct LiquidGlassOverlay<S: InsettableShape>: View { let shape: S var body: some View { ZStack { // Dark tint over the blur for a deeper glass look shape .fill(.black.opacity(0.45)) // Specular highlight — subtle light refraction at the top shape .fill( LinearGradient( stops: [ .init(color: .white.opacity(0.12), location: 0), .init(color: .white.opacity(0.03), location: 0.35), .init(color: .clear, location: 0.55) ], startPoint: .top, endPoint: .bottom ) ) // Glass edge — gradient border, brighter at top shape .strokeBorder( LinearGradient( stops: [ .init(color: .white.opacity(0.35), location: 0), .init(color: .white.opacity(0.1), location: 0.5), .init(color: .white.opacity(0.04), location: 1.0) ], startPoint: .top, endPoint: .bottom ), lineWidth: 0.75 ) } } } // MARK: - Waveform Views struct WaveformBar: View { let amplitude: CGFloat private let minHeight: CGFloat = 2 private let maxHeight: CGFloat = 20 var body: some View { Capsule() .fill( LinearGradient( colors: [.white, .white.opacity(0.85)], startPoint: .top, endPoint: .bottom ) ) .frame(width: 3, height: minHeight + (maxHeight - minHeight) * amplitude) } } struct WaveformView: View { let audioLevel: Float private static let barCount = 9 private static let multipliers: [CGFloat] = [0.35, 0.55, 0.75, 0.9, 1.0, 0.9, 0.75, 0.55, 0.35] var body: some View { HStack(spacing: 2.5) { ForEach(0..<Self.barCount, id: \.self) { index in WaveformBar(amplitude: barAmplitude(for: index)) .animation( .interpolatingSpring(stiffness: 600, damping: 28), value: audioLevel ) } } .frame(height: 20) } private func barAmplitude(for index: Int) -> CGFloat { let level = CGFloat(audioLevel) return min(level * Self.multipliers[index], 1.0) } } // MARK: - Recording Overlay View struct InitializingDotsView: View { @State private var activeDot = 0 @State private var timer: Timer? var body: some View { HStack(spacing: 4) { ForEach(0..<3, id: \.self) { index in Circle() .fill(.white.opacity(activeDot == index ? 0.9 : 0.25)) .frame(width: 4.5, height: 4.5) .animation(.easeInOut(duration: 0.4), value: activeDot) } } .onAppear { timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in DispatchQueue.main.async { activeDot = (activeDot + 1) % 3 } } } .onDisappear { timer?.invalidate() timer = nil } } } struct RecordingOverlayView: View { @ObservedObject var state: RecordingOverlayState var body: some View { Group { if state.phase == .initializing { InitializingDotsView() .frame(width: 100, height: 20) .transition(.opacity) } else { WaveformView(audioLevel: state.audioLevel) .frame(width: 100, height: 20) .transition(.opacity) } } .animation(.easeInOut(duration: 0.2), value: state.phase == .initializing) .frame(width: 120, height: 32) .background(LiquidGlassOverlay(shape: UnevenRoundedRectangle(bottomLeadingRadius: 12, bottomTrailingRadius: 12))) } } // MARK: - Transcribing Indicator struct TranscribingIndicatorView: View { @State private var animatingDot = 0 @State private var dotAnimationTimer: Timer? var body: some View { HStack(spacing: 4) { ForEach(0..<3, id: \.self) { index in Circle() .fill(.white.opacity(animatingDot == index ? 0.9 : 0.25)) .frame(width: 4.5, height: 4.5) .animation(.easeInOut(duration: 0.4), value: animatingDot) } } .frame(width: 44, height: 22) .background( LiquidGlassOverlay(shape: UnevenRoundedRectangle(bottomLeadingRadius: 11, bottomTrailingRadius: 11)) ) .onAppear { startDotAnimation() } .onDisappear { stopDotAnimation() } } private func startDotAnimation() { dotAnimationTimer?.invalidate() dotAnimationTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in DispatchQueue.main.async { animatingDot = (animatingDot + 1) % 3 } } } private func stopDotAnimation() { dotAnimationTimer?.invalidate() dotAnimationTimer = nil } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/SettingsView.swift
Swift
import SwiftUI import AVFoundation import ServiceManagement struct SettingsView: View { @EnvironmentObject var appState: AppState var body: some View { HStack(spacing: 0) { VStack(alignment: .leading, spacing: 2) { ForEach(SettingsTab.allCases) { tab in Button { appState.selectedSettingsTab = tab } label: { Label(tab.title, systemImage: tab.icon) .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 8) .padding(.horizontal, 10) .background( RoundedRectangle(cornerRadius: 6) .fill(appState.selectedSettingsTab == tab ? Color.accentColor.opacity(0.15) : Color.clear) ) } .buttonStyle(.plain) } Spacer() } .padding(10) .frame(width: 180) .background(Color(nsColor: .windowBackgroundColor)) Divider() Group { switch appState.selectedSettingsTab { case .general, .none: GeneralSettingsView() case .runLog: RunLogView() } } .frame(maxWidth: .infinity, maxHeight: .infinity) } } } // MARK: - General Settings struct GeneralSettingsView: View { @EnvironmentObject var appState: AppState @Environment(\.openURL) private var openURL @State private var apiKeyInput: String = "" @State private var isValidatingKey = false @State private var keyValidationError: String? @State private var keyValidationSuccess = false @State private var customVocabularyInput: String = "" @State private var micPermissionGranted = false @StateObject private var githubCache = GitHubMetadataCache.shared @ObservedObject private var updateManager = UpdateManager.shared private let freeflowRepoURL = URL(string: "https://github.com/zachlatta/freeflow")! var body: some View { ScrollView { VStack(spacing: 20) { // App branding header VStack(spacing: 12) { Image(nsImage: NSApp.applicationIconImage) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 64, height: 64) Text("FreeFlow") .font(.system(size: 20, weight: .bold, design: .rounded)) Text("v\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0")") .font(.caption) .foregroundStyle(.secondary) // GitHub card VStack(spacing: 10) { HStack(spacing: 8) { AsyncImage(url: URL(string: "https://avatars.githubusercontent.com/u/992248")) { phase in switch phase { case .success(let image): image.resizable().aspectRatio(contentMode: .fill) default: Color.gray.opacity(0.2) } } .frame(width: 22, height: 22) .clipShape(Circle()) Button { openURL(freeflowRepoURL) } label: { Text("zachlatta/freeflow") .font(.system(.caption, design: .monospaced).weight(.medium)) } .buttonStyle(.plain) .foregroundStyle(.blue) Spacer() HStack(spacing: 4) { Image(systemName: "star.fill") .foregroundStyle(.yellow) .font(.caption2) if githubCache.isLoading { ProgressView().scaleEffect(0.5) } else if let count = githubCache.starCount { Text("\(count.formatted()) \(count == 1 ? "star" : "stars")") .font(.caption2.weight(.semibold)) .foregroundStyle(.secondary) } } .padding(.horizontal, 8) .padding(.vertical, 4) .background(Capsule().fill(Color.yellow.opacity(0.14))) Button { openURL(freeflowRepoURL) } label: { HStack(spacing: 4) { Image(systemName: "star") Text("Star") } .font(.caption.weight(.semibold)) .padding(.horizontal, 10) .padding(.vertical, 5) .background(Capsule().fill(Color.yellow.opacity(0.18))) } .buttonStyle(.plain) } if !githubCache.recentStargazers.isEmpty { Divider() HStack(spacing: 8) { HStack(spacing: -6) { ForEach(githubCache.recentStargazers) { star in Button { openURL(star.user.htmlUrl) } label: { AsyncImage(url: star.user.avatarThumbnailUrl) { phase in switch phase { case .success(let image): image.resizable().aspectRatio(contentMode: .fill) default: Color.gray.opacity(0.2) } } .frame(width: 22, height: 22) .clipShape(Circle()) .overlay(Circle().stroke(Color(nsColor: .windowBackgroundColor), lineWidth: 1.5)) } .buttonStyle(.plain) } } .clipped() Text("recently starred") .font(.caption2) .foregroundStyle(.tertiary) .fixedSize() Spacer() } .clipped() } } .padding(12) .background( RoundedRectangle(cornerRadius: 12) .fill(.ultraThinMaterial) .overlay( RoundedRectangle(cornerRadius: 12) .stroke(Color.primary.opacity(0.08), lineWidth: 1) ) ) } .frame(maxWidth: .infinity) .padding(.top, 4) .padding(.bottom, 4) settingsCard("Startup", icon: "power") { startupSection } settingsCard("Updates", icon: "arrow.triangle.2.circlepath") { updatesSection } settingsCard("API Key", icon: "key.fill") { apiKeySection } settingsCard("Push-to-Talk Key", icon: "keyboard.fill") { hotkeySection } settingsCard("Microphone", icon: "mic.fill") { microphoneSection } settingsCard("Custom Vocabulary", icon: "text.book.closed.fill") { vocabularySection } settingsCard("Permissions", icon: "lock.shield.fill") { permissionsSection } } .padding(24) } .onAppear { apiKeyInput = appState.apiKey customVocabularyInput = appState.customVocabulary checkMicPermission() appState.refreshLaunchAtLoginStatus() Task { await githubCache.fetchIfNeeded() } } } private func settingsCard<Content: View>(_ title: String, icon: String, @ViewBuilder content: () -> Content) -> some View { VStack(alignment: .leading, spacing: 12) { Label(title, systemImage: icon) .font(.headline) content() } .padding(16) .frame(maxWidth: .infinity, alignment: .leading) .background(Color(nsColor: .controlBackgroundColor).opacity(0.5)) .cornerRadius(10) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(Color.primary.opacity(0.06), lineWidth: 1) ) } // MARK: Startup private var startupSection: some View { VStack(alignment: .leading, spacing: 10) { Toggle("Launch FreeFlow at login", isOn: $appState.launchAtLogin) if SMAppService.mainApp.status == .requiresApproval { HStack(spacing: 6) { Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.orange) .font(.caption) Text("Login item requires approval in System Settings.") .font(.caption) .foregroundStyle(.secondary) Button("Open Login Items Settings") { NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.LoginItems-Settings.extension")!) } .font(.caption) } } } } // MARK: Updates private var updatesSection: some View { VStack(alignment: .leading, spacing: 10) { Toggle("Automatically check for updates", isOn: Binding( get: { updateManager.autoCheckEnabled }, set: { updateManager.autoCheckEnabled = $0 } )) HStack(spacing: 10) { Button { Task { await updateManager.checkForUpdates(userInitiated: true) } } label: { if updateManager.isChecking { HStack(spacing: 6) { ProgressView() .controlSize(.small) Text("Checking...") } } else { Text("Check for Updates Now") } } .disabled(updateManager.isChecking || updateManager.updateStatus != .idle) if let lastCheck = updateManager.lastCheckDate { Text("Last checked: \(lastCheck.formatted(date: .abbreviated, time: .shortened))") .font(.caption) .foregroundStyle(.secondary) } } if updateManager.updateAvailable { VStack(alignment: .leading, spacing: 8) { switch updateManager.updateStatus { case .downloading: HStack(spacing: 8) { Image(systemName: "arrow.down.circle.fill") .foregroundStyle(.blue) VStack(alignment: .leading, spacing: 4) { Text("Downloading update...") .font(.caption.weight(.semibold)) ProgressView(value: updateManager.downloadProgress ?? 0) .progressViewStyle(.linear) if let progress = updateManager.downloadProgress { Text("\(Int(progress * 100))%") .font(.caption2) .foregroundStyle(.secondary) } } Spacer() Button("Cancel") { updateManager.cancelDownload() } .font(.caption) } case .installing: HStack(spacing: 8) { ProgressView() .controlSize(.small) Text("Installing update...") .font(.caption.weight(.semibold)) } case .readyToRelaunch: HStack(spacing: 8) { ProgressView() .controlSize(.small) Text("Relaunching...") .font(.caption.weight(.semibold)) } case .error(let message): HStack(spacing: 8) { Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.red) Text(message) .font(.caption) .foregroundStyle(.red) Spacer() Button("Retry") { updateManager.updateStatus = .idle if let release = updateManager.latestRelease { updateManager.downloadAndInstall(release: release) } } .font(.caption) } case .idle: HStack(spacing: 8) { Image(systemName: "arrow.down.circle.fill") .foregroundStyle(.blue) Text("A new version of FreeFlow is available!") .font(.caption.weight(.semibold)) Spacer() Button("Update Now") { if let release = updateManager.latestRelease { updateManager.downloadAndInstall(release: release) } } .font(.caption) } } } .padding(10) .background(Color.blue.opacity(0.1)) .cornerRadius(6) } } } // MARK: API Key private var apiKeySection: some View { VStack(alignment: .leading, spacing: 10) { Text("FreeFlow uses Groq's whisper-large-v3 model for transcription.") .font(.caption) .foregroundStyle(.secondary) HStack(spacing: 8) { SecureField("Enter your Groq API key", text: $apiKeyInput) .textFieldStyle(.roundedBorder) .font(.system(.body, design: .monospaced)) .disabled(isValidatingKey) .onChange(of: apiKeyInput) { _ in keyValidationError = nil keyValidationSuccess = false } Button(isValidatingKey ? "Validating..." : "Save") { validateAndSaveKey() } .disabled(apiKeyInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isValidatingKey) } if let error = keyValidationError { Label(error, systemImage: "xmark.circle.fill") .foregroundStyle(.red) .font(.caption) } else if keyValidationSuccess { Label("API key saved", systemImage: "checkmark.circle.fill") .foregroundStyle(.green) .font(.caption) } } } private func validateAndSaveKey() { let key = apiKeyInput.trimmingCharacters(in: .whitespacesAndNewlines) isValidatingKey = true keyValidationError = nil keyValidationSuccess = false Task { let valid = await TranscriptionService.validateAPIKey(key) await MainActor.run { isValidatingKey = false if valid { appState.apiKey = key keyValidationSuccess = true } else { keyValidationError = "Invalid API key. Please check and try again." } } } } // MARK: Push-to-Talk Key private var hotkeySection: some View { VStack(alignment: .leading, spacing: 10) { Text("Hold this key to record, release to transcribe.") .font(.caption) .foregroundStyle(.secondary) VStack(spacing: 6) { ForEach(HotkeyOption.allCases) { option in HotkeyOptionRow( option: option, isSelected: appState.selectedHotkey == option, action: { appState.selectedHotkey = option } ) } } if appState.selectedHotkey == .fnKey { Text("Tip: If Fn opens Emoji picker, go to System Settings > Keyboard and change \"Press fn key to\" to \"Do Nothing\".") .font(.caption) .foregroundStyle(.orange) } } } // MARK: Microphone private var microphoneSection: some View { VStack(alignment: .leading, spacing: 10) { Text("Select which microphone to use for recording.") .font(.caption) .foregroundStyle(.secondary) VStack(spacing: 6) { MicrophoneOptionRow( name: "System Default", isSelected: appState.selectedMicrophoneID == "default" || appState.selectedMicrophoneID.isEmpty, action: { appState.selectedMicrophoneID = "default" } ) ForEach(appState.availableMicrophones) { device in MicrophoneOptionRow( name: device.name, isSelected: appState.selectedMicrophoneID == device.uid, action: { appState.selectedMicrophoneID = device.uid } ) } } } .onAppear { appState.refreshAvailableMicrophones() } } // MARK: Custom Vocabulary private var vocabularySection: some View { VStack(alignment: .leading, spacing: 10) { Text("Words and phrases to preserve during post-processing.") .font(.caption) .foregroundStyle(.secondary) TextEditor(text: $customVocabularyInput) .font(.system(.body, design: .monospaced)) .frame(minHeight: 80, maxHeight: 140) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.3), lineWidth: 1) ) .onChange(of: customVocabularyInput) { newValue in appState.customVocabulary = newValue.trimmingCharacters(in: .whitespacesAndNewlines) } Text("Separate entries with commas, new lines, or semicolons.") .font(.caption) .foregroundStyle(.secondary) } } // MARK: Permissions private var permissionsSection: some View { VStack(alignment: .leading, spacing: 10) { permissionRow( title: "Microphone", icon: "mic.fill", granted: micPermissionGranted, action: { AVCaptureDevice.requestAccess(for: .audio) { granted in DispatchQueue.main.async { micPermissionGranted = granted } } } ) permissionRow( title: "Accessibility", icon: "hand.raised.fill", granted: appState.hasAccessibility, action: { appState.openAccessibilitySettings() } ) permissionRow( title: "Screen Recording", icon: "camera.viewfinder", granted: appState.hasScreenRecordingPermission, action: { appState.requestScreenCapturePermission() } ) } } private func permissionRow(title: String, icon: String, granted: Bool, action: @escaping () -> Void) -> some View { HStack { Image(systemName: icon) .frame(width: 20) .foregroundStyle(.blue) Text(title) Spacer() if granted { Image(systemName: "checkmark.circle.fill") .foregroundStyle(.green) Text("Granted") .font(.caption) .foregroundStyle(.green) } else { Button("Grant Access") { action() } .font(.caption) } } .padding(10) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(6) } private func checkMicPermission() { micPermissionGranted = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized } } // MARK: - Microphone Option Row struct MicrophoneOptionRow: View { let name: String let isSelected: Bool let action: () -> Void var body: some View { Button(action: action) { HStack { Image(systemName: isSelected ? "checkmark.circle.fill" : "circle") .foregroundStyle(isSelected ? .blue : .secondary) Text(name) .foregroundStyle(.primary) Spacer() } .padding(12) .background(isSelected ? Color.blue.opacity(0.1) : Color(nsColor: .controlBackgroundColor)) .cornerRadius(8) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(isSelected ? Color.blue : Color.clear, lineWidth: 1.5) ) } .buttonStyle(.plain) } } // MARK: - Run Log struct RunLogView: View { @EnvironmentObject var appState: AppState var body: some View { VStack(spacing: 0) { HStack { Text("Run Log") .font(.headline) Spacer() Button("Clear History") { appState.clearPipelineHistory() } .disabled(appState.pipelineHistory.isEmpty) } .padding(.horizontal, 24) .padding(.top, 20) .padding(.bottom, 12) Divider() if appState.pipelineHistory.isEmpty { VStack { Spacer() Text("No runs yet. Use dictation to populate history.") .foregroundStyle(.secondary) Spacer() } .frame(maxWidth: .infinity) } else { ScrollView { VStack(spacing: 12) { ForEach(appState.pipelineHistory) { item in RunLogEntryView(item: item) } } .padding(20) } } } } } // MARK: - Run Log Entry struct RunLogEntryView: View { let item: PipelineHistoryItem @EnvironmentObject var appState: AppState @State private var isExpanded = false @State private var showContextPrompt = false @State private var showPostProcessingPrompt = false private var isError: Bool { item.postProcessingStatus.hasPrefix("Error:") } var body: some View { VStack(alignment: .leading, spacing: 0) { // Collapsed header HStack(spacing: 0) { Button { withAnimation(.easeInOut(duration: 0.2)) { isExpanded.toggle() } } label: { HStack { if isError { Image(systemName: "exclamationmark.triangle.fill") .font(.caption) .foregroundStyle(.red) } VStack(alignment: .leading, spacing: 3) { Text(item.timestamp.formatted(date: .numeric, time: .standard)) .font(.subheadline.weight(.semibold)) Text(item.postProcessedTranscript.isEmpty ? "(no transcript)" : item.postProcessedTranscript) .font(.caption) .foregroundStyle(.secondary) .lineLimit(1) .truncationMode(.tail) } Spacer() Image(systemName: "chevron.right") .font(.caption.weight(.semibold)) .foregroundStyle(.secondary) .rotationEffect(.degrees(isExpanded ? 90 : 0)) } .contentShape(Rectangle()) } .buttonStyle(.plain) Button { withAnimation(.easeInOut(duration: 0.2)) { appState.deleteHistoryEntry(id: item.id) } } label: { Image(systemName: "trash") .font(.caption) .foregroundStyle(.secondary) .frame(width: 28, height: 28) .contentShape(Rectangle()) } .buttonStyle(.plain) .help("Delete this run") } .padding(12) if isExpanded { Divider() .padding(.horizontal, 12) VStack(alignment: .leading, spacing: 16) { // Audio player if let audioFileName = item.audioFileName { let audioURL = AppState.audioStorageDirectory().appendingPathComponent(audioFileName) AudioPlayerView(audioURL: audioURL) } else { HStack(spacing: 6) { Image(systemName: "waveform.slash") .font(.caption) .foregroundStyle(.secondary) Text("No audio recorded") .font(.caption) .foregroundStyle(.secondary) } } // Custom vocabulary if !item.customVocabulary.isEmpty { VStack(alignment: .leading, spacing: 6) { Text("Custom Vocabulary") .font(.caption.weight(.semibold)) FlowLayout(spacing: 4) { ForEach(parseVocabulary(item.customVocabulary), id: \.self) { word in Text(word) .font(.caption2) .padding(.horizontal, 8) .padding(.vertical, 3) .background(Color.accentColor.opacity(0.12)) .cornerRadius(4) } } } } // Pipeline steps VStack(alignment: .leading, spacing: 10) { Text("Pipeline") .font(.caption.weight(.semibold)) // Step 1: Context Capture PipelineStepView( number: 1, title: "Capture Context", content: { VStack(alignment: .leading, spacing: 6) { if let dataURL = item.contextScreenshotDataURL, let image = imageFromDataURL(dataURL) { Image(nsImage: image) .resizable() .aspectRatio(contentMode: .fit) .frame(maxHeight: 120) .cornerRadius(4) } if let prompt = item.contextPrompt, !prompt.isEmpty { Button { showContextPrompt.toggle() } label: { HStack(spacing: 4) { Text(showContextPrompt ? "Hide Prompt" : "Show Prompt") .font(.caption) Image(systemName: showContextPrompt ? "chevron.up" : "chevron.down") .font(.caption2) } } .buttonStyle(.plain) .foregroundStyle(Color.accentColor) if showContextPrompt { Text(prompt) .font(.system(.caption2, design: .monospaced)) .textSelection(.enabled) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(4) } } if !item.contextSummary.isEmpty { Text(item.contextSummary) .font(.caption) .foregroundStyle(.secondary) .textSelection(.enabled) } else { Text("No context captured") .font(.caption) .foregroundStyle(.secondary) } } } ) // Step 2: Transcribe Audio PipelineStepView( number: 2, title: "Transcribe Audio", content: { VStack(alignment: .leading, spacing: 4) { Text("Sent audio to Groq whisper-large-v3") .font(.caption) .foregroundStyle(.secondary) .textSelection(.enabled) if !item.rawTranscript.isEmpty { Text(item.rawTranscript) .font(.system(.caption, design: .monospaced)) .textSelection(.enabled) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(4) } else { Text("(empty transcript)") .font(.caption) .foregroundStyle(.secondary) } } } ) // Step 3: Post-Process PipelineStepView( number: 3, title: "Post-Process", content: { VStack(alignment: .leading, spacing: 6) { Text(item.postProcessingStatus) .font(.caption) .foregroundStyle(.secondary) .textSelection(.enabled) if let prompt = item.postProcessingPrompt, !prompt.isEmpty { Button { showPostProcessingPrompt.toggle() } label: { HStack(spacing: 4) { Text(showPostProcessingPrompt ? "Hide Prompt" : "Show Prompt") .font(.caption) Image(systemName: showPostProcessingPrompt ? "chevron.up" : "chevron.down") .font(.caption2) } } .buttonStyle(.plain) .foregroundStyle(Color.accentColor) if showPostProcessingPrompt { Text(prompt) .font(.system(.caption2, design: .monospaced)) .textSelection(.enabled) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(4) } } if !item.postProcessedTranscript.isEmpty { Text(item.postProcessedTranscript) .font(.system(.caption, design: .monospaced)) .textSelection(.enabled) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(4) } } } ) } } .padding(12) } } .background(Color(nsColor: .textBackgroundColor)) .cornerRadius(10) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(isError ? Color.red.opacity(0.4) : Color.secondary.opacity(0.2), lineWidth: 1) ) } private func parseVocabulary(_ text: String) -> [String] { text.components(separatedBy: CharacterSet(charactersIn: ",;\n")) .map { $0.trimmingCharacters(in: .whitespaces) } .filter { !$0.isEmpty } } } // MARK: - Pipeline Step View struct PipelineStepView<Content: View>: View { let number: Int let title: String @ViewBuilder let content: () -> Content var body: some View { HStack(alignment: .top, spacing: 10) { Text("\(number)") .font(.caption2.weight(.bold)) .foregroundStyle(.white) .frame(width: 20, height: 20) .background(Circle().fill(Color.accentColor)) VStack(alignment: .leading, spacing: 6) { Text(title) .font(.caption.weight(.semibold)) content() } .frame(maxWidth: .infinity, alignment: .leading) } .padding(10) .background(Color(nsColor: .controlBackgroundColor).opacity(0.5)) .cornerRadius(8) } } // MARK: - Audio Player class AudioPlayerDelegate: NSObject, AVAudioPlayerDelegate { var onFinish: (() -> Void)? func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { DispatchQueue.main.async { self.onFinish?() } } } struct AudioPlayerView: View { let audioURL: URL @State private var player: AVAudioPlayer? @State private var delegate = AudioPlayerDelegate() @State private var isPlaying = false @State private var duration: TimeInterval = 0 @State private var elapsed: TimeInterval = 0 @State private var progressTimer: Timer? private var progress: Double { guard duration > 0 else { return 0 } return min(elapsed / duration, 1.0) } var body: some View { HStack(spacing: 10) { Button { togglePlayback() } label: { Image(systemName: isPlaying ? "stop.fill" : "play.fill") .font(.body) .frame(width: 28, height: 28) .background(Circle().fill(Color.accentColor.opacity(0.15))) } .buttonStyle(.plain) GeometryReader { geo in ZStack(alignment: .leading) { Capsule() .fill(Color.secondary.opacity(0.15)) .frame(height: 4) Capsule() .fill(Color.accentColor) .frame(width: max(0, geo.size.width * progress), height: 4) } .frame(maxHeight: .infinity, alignment: .center) } .frame(height: 28) Text("\(formatDuration(elapsed)) / \(formatDuration(duration))") .font(.system(.caption2, design: .monospaced)) .foregroundStyle(.secondary) .fixedSize() } .onAppear { loadDuration() } .onDisappear { stopPlayback() } } private func loadDuration() { guard FileManager.default.fileExists(atPath: audioURL.path) else { return } if let p = try? AVAudioPlayer(contentsOf: audioURL) { duration = p.duration } } private func togglePlayback() { if isPlaying { stopPlayback() } else { guard FileManager.default.fileExists(atPath: audioURL.path) else { return } do { let p = try AVAudioPlayer(contentsOf: audioURL) delegate.onFinish = { self.stopPlayback() } p.delegate = delegate p.play() player = p isPlaying = true elapsed = 0 startProgressTimer() } catch {} } } private func stopPlayback() { progressTimer?.invalidate() progressTimer = nil player?.stop() player = nil isPlaying = false elapsed = 0 } private func startProgressTimer() { progressTimer?.invalidate() progressTimer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in if let p = player, p.isPlaying { elapsed = p.currentTime } } } private func formatDuration(_ seconds: TimeInterval) -> String { let mins = Int(seconds) / 60 let secs = Int(seconds) % 60 return String(format: "%d:%02d", mins, secs) } } // MARK: - Flow Layout struct FlowLayout: Layout { var spacing: CGFloat = 4 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { let result = layoutSubviews(proposal: proposal, subviews: subviews) return result.size } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { let result = layoutSubviews(proposal: proposal, subviews: subviews) for (index, subview) in subviews.enumerated() { guard index < result.positions.count else { break } let pos = result.positions[index] subview.place(at: CGPoint(x: bounds.minX + pos.x, y: bounds.minY + pos.y), proposal: .unspecified) } } private func layoutSubviews(proposal: ProposedViewSize, subviews: Subviews) -> (size: CGSize, positions: [CGPoint]) { let maxWidth = proposal.width ?? .infinity var positions: [CGPoint] = [] var x: CGFloat = 0 var y: CGFloat = 0 var rowHeight: CGFloat = 0 var totalHeight: CGFloat = 0 for subview in subviews { let size = subview.sizeThatFits(.unspecified) if x + size.width > maxWidth && x > 0 { x = 0 y += rowHeight + spacing rowHeight = 0 } positions.append(CGPoint(x: x, y: y)) rowHeight = max(rowHeight, size.height) x += size.width + spacing totalHeight = y + rowHeight } return (CGSize(width: maxWidth, height: totalHeight), positions) } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/SetupView.swift
Swift
import SwiftUI import AVFoundation import Combine import Foundation import ServiceManagement struct SetupView: View { var onComplete: () -> Void @EnvironmentObject var appState: AppState @Environment(\.openURL) private var openURL private let freeflowRepoURL = URL(string: "https://github.com/zachlatta/freeflow")! private enum SetupStep: Int, CaseIterable { case welcome = 0 case apiKey case micPermission case accessibility case screenRecording case hotkey case vocabulary case launchAtLogin case testTranscription case ready } @State private var currentStep = SetupStep.welcome @State private var micPermissionGranted = false @State private var accessibilityGranted = false @State private var apiKeyInput: String = "" @State private var isValidatingKey = false @State private var keyValidationError: String? @State private var accessibilityTimer: Timer? @State private var screenRecordingTimer: Timer? @State private var customVocabularyInput: String = "" @StateObject private var githubCache = GitHubMetadataCache.shared // Test transcription state private enum TestPhase: Equatable { case idle, recording, transcribing, done } @State private var testPhase: TestPhase = .idle @State private var testAudioRecorder: AudioRecorder? = nil @State private var testAudioLevel: Float = 0.0 @State private var testTranscript: String = "" @State private var testError: String? = nil @State private var testAudioLevelCancellable: AnyCancellable? = nil @State private var testMicPulsing = false private let totalSteps: [SetupStep] = SetupStep.allCases var body: some View { VStack(spacing: 0) { Group { switch currentStep { case .welcome: welcomeStep case .apiKey: apiKeyStep case .micPermission: micPermissionStep case .accessibility: accessibilityStep case .screenRecording: screenRecordingStep case .hotkey: hotkeyStep case .vocabulary: vocabularyStep case .launchAtLogin: launchAtLoginStep case .testTranscription: testTranscriptionStep case .ready: readyStep } } .frame(maxWidth: .infinity, maxHeight: .infinity) .padding(40) Divider() HStack { if currentStep != .welcome { Button("Back") { keyValidationError = nil withAnimation { currentStep = previousStep(currentStep) } } .disabled(isValidatingKey) } Spacer() if currentStep != .ready { if currentStep == .apiKey { // API key step: validate before continuing Button(isValidatingKey ? "Validating..." : "Continue") { validateAndContinue() } .keyboardShortcut(.defaultAction) .disabled(apiKeyInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isValidatingKey) } else if currentStep == .vocabulary { Button("Continue") { saveCustomVocabularyAndContinue() } .keyboardShortcut(.defaultAction) } else if currentStep == .testTranscription { Button("Skip") { stopTestHotkeyMonitoring() withAnimation { currentStep = nextStep(currentStep) } } .buttonStyle(.plain) .foregroundStyle(.secondary) Button("Continue") { stopTestHotkeyMonitoring() withAnimation { currentStep = nextStep(currentStep) } } .keyboardShortcut(.defaultAction) .disabled(testPhase != .done || testTranscript.isEmpty || testError != nil) } else { Button("Continue") { withAnimation { currentStep = nextStep(currentStep) } } .keyboardShortcut(.defaultAction) .disabled(!canContinueFromCurrentStep) } } else { Button("Get Started") { onComplete() } .keyboardShortcut(.defaultAction) } } .padding(20) } .frame(width: 520, height: 520) .onAppear { apiKeyInput = appState.apiKey customVocabularyInput = appState.customVocabulary checkMicPermission() checkAccessibility() Task { await githubCache.fetchIfNeeded() } } .onDisappear { accessibilityTimer?.invalidate() screenRecordingTimer?.invalidate() } } // MARK: - Steps var welcomeStep: some View { VStack(spacing: 16) { Image(nsImage: NSApp.applicationIconImage) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 128, height: 128) VStack(spacing: 6) { Text("Welcome to FreeFlow") .font(.system(size: 30, weight: .bold, design: .rounded)) Text("Dictate text anywhere on your Mac.\nHold a key to record, release to transcribe.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } VStack(spacing: 10) { HStack(spacing: 8) { AsyncImage(url: URL(string: "https://avatars.githubusercontent.com/u/992248")) { phase in switch phase { case .success(let image): image.resizable().aspectRatio(contentMode: .fill) default: Color.gray.opacity(0.2) } } .frame(width: 26, height: 26) .clipShape(Circle()) Button { openURL(freeflowRepoURL) } label: { Text("zachlatta/freeflow") .font(.system(.caption, design: .monospaced).weight(.medium)) } .buttonStyle(.plain) .foregroundStyle(.blue) Spacer() HStack(spacing: 4) { Image(systemName: "star.fill") .foregroundStyle(.yellow) .font(.caption2) if githubCache.isLoading { ProgressView().scaleEffect(0.5) } else if let count = githubCache.starCount { Text("\(count.formatted()) \(count == 1 ? "star" : "stars")") .font(.caption2.weight(.semibold)) .foregroundStyle(.secondary) } } .padding(.horizontal, 8) .padding(.vertical, 4) .background(Capsule().fill(Color.yellow.opacity(0.14))) Button { openURL(freeflowRepoURL) } label: { HStack(spacing: 4) { Image(systemName: "star") Text("Star") } .font(.caption.weight(.semibold)) .padding(.horizontal, 10) .padding(.vertical, 5) .background(Capsule().fill(Color.yellow.opacity(0.18))) } .buttonStyle(.plain) } if !githubCache.recentStargazers.isEmpty { Divider() HStack(spacing: 8) { HStack(spacing: -6) { ForEach(githubCache.recentStargazers) { star in Button { openURL(star.user.htmlUrl) } label: { AsyncImage(url: star.user.avatarThumbnailUrl) { phase in switch phase { case .success(let image): image.resizable().aspectRatio(contentMode: .fill) default: Color.gray.opacity(0.2) } } .frame(width: 22, height: 22) .clipShape(Circle()) .overlay(Circle().stroke(Color(nsColor: .windowBackgroundColor), lineWidth: 1.5)) } .buttonStyle(.plain) } } .clipped() Text("recently starred") .font(.caption2) .foregroundStyle(.tertiary) .fixedSize() Spacer() } .clipped() } } .padding(12) .background( RoundedRectangle(cornerRadius: 12) .fill(.ultraThinMaterial) .overlay( RoundedRectangle(cornerRadius: 12) .stroke(Color.primary.opacity(0.08), lineWidth: 1) ) ) stepIndicator } } var apiKeyStep: some View { VStack(spacing: 20) { Image(systemName: "key.fill") .font(.system(size: 60)) .foregroundStyle(.blue) Text("Groq API Key") .font(.title) .fontWeight(.bold) Text("FreeFlow uses Groq for fast, high-accuracy transcription.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 4) { Text("How to get a free API key:") .font(.subheadline.weight(.semibold)) VStack(alignment: .leading, spacing: 2) { instructionRow(number: "1", text: "Go to [console.groq.com/keys](https://console.groq.com/keys)") instructionRow(number: "2", text: "Create a free account (if you don't have one)") instructionRow(number: "3", text: "Click **Create API Key** and copy it") } } .padding(10) .frame(maxWidth: .infinity, alignment: .leading) .background( RoundedRectangle(cornerRadius: 8) .fill(Color.blue.opacity(0.06)) ) VStack(alignment: .leading, spacing: 6) { Text("API Key") .font(.headline) SecureField("Paste your Groq API key", text: $apiKeyInput) .textFieldStyle(.roundedBorder) .font(.system(.body, design: .monospaced)) .disabled(isValidatingKey) .onChange(of: apiKeyInput) { _ in keyValidationError = nil } if let error = keyValidationError { Label(error, systemImage: "xmark.circle.fill") .foregroundStyle(.red) .font(.caption) } } } stepIndicator } } var micPermissionStep: some View { VStack(spacing: 20) { Image(systemName: "mic.fill") .font(.system(size: 60)) .foregroundStyle(.blue) Text("Microphone Access") .font(.title) .fontWeight(.bold) Text("FreeFlow needs access to your microphone to record audio for transcription.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) HStack { Image(systemName: "mic.fill") .frame(width: 24) .foregroundStyle(.blue) Text("Microphone") Spacer() if micPermissionGranted { Image(systemName: "checkmark.circle.fill") .foregroundStyle(.green) Text("Granted") .foregroundStyle(.green) } else { Button("Grant Access") { requestMicPermission() } } } .padding(12) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(8) stepIndicator } } var accessibilityStep: some View { VStack(spacing: 20) { Image(systemName: "hand.raised.fill") .font(.system(size: 60)) .foregroundStyle(.blue) Text("Accessibility Access") .font(.title) .fontWeight(.bold) Text("FreeFlow needs Accessibility access to paste transcribed text into your apps.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) HStack { Image(systemName: "hand.raised.fill") .frame(width: 24) .foregroundStyle(.blue) Text("Accessibility") Spacer() if accessibilityGranted { Image(systemName: "checkmark.circle.fill") .foregroundStyle(.green) Text("Granted") .foregroundStyle(.green) } else { Button("Open Settings") { requestAccessibility() } } } .padding(12) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(8) if !accessibilityGranted { Text("Note: If you rebuilt the app, you may need to\nremove and re-add it in Accessibility settings.") .font(.caption) .foregroundStyle(.secondary) .multilineTextAlignment(.center) } stepIndicator } .onAppear { startAccessibilityPolling() } .onDisappear { accessibilityTimer?.invalidate() } } var screenRecordingStep: some View { VStack(spacing: 20) { Image(systemName: "camera.viewfinder") .font(.system(size: 60)) .foregroundStyle(.blue) Text("Screen Recording") .font(.title) .fontWeight(.bold) Text("FreeFlow intelligently adapts the transcription to the current app you're working in (ex. spelling names in an email correctly).") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) Text("It needs this permission to see which app you're working in and any in-progress work. Nothing is stored on FreeFlow's servers (FreeFlow doesn't have servers).") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .font(.callout) .fixedSize(horizontal: false, vertical: true) HStack { Image(systemName: "camera.viewfinder") .frame(width: 24) .foregroundStyle(.blue) Text("Screen Recording") Spacer() if appState.hasScreenRecordingPermission { Image(systemName: "checkmark.circle.fill") .foregroundStyle(.green) Text("Granted") .foregroundStyle(.green) } else { Button("Grant Access") { appState.requestScreenCapturePermission() } } } .padding(12) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(8) stepIndicator } .onAppear { startScreenRecordingPolling() } .onDisappear { screenRecordingTimer?.invalidate() } } var hotkeyStep: some View { VStack(spacing: 20) { Image(systemName: "keyboard.fill") .font(.system(size: 60)) .foregroundStyle(.blue) Text("Push-to-Talk Key") .font(.title) .fontWeight(.bold) Text("Choose which key to hold while speaking.\nPress and hold to record, release to transcribe.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) VStack(spacing: 8) { ForEach(HotkeyOption.allCases) { option in HotkeyOptionRow( option: option, isSelected: appState.selectedHotkey == option, action: { appState.selectedHotkey = option } ) } } .padding(.top, 10) if appState.selectedHotkey == .fnKey { Text("Tip: If Fn opens Emoji picker, go to\nSystem Settings > Keyboard and change\n\"Press fn key to\" to \"Do Nothing\".") .font(.caption) .foregroundStyle(.orange) .multilineTextAlignment(.center) } stepIndicator } } var vocabularyStep: some View { VStack(spacing: 20) { Image(systemName: "text.book.closed.fill") .font(.system(size: 60)) .foregroundStyle(.blue) Text("Custom Vocabulary") .font(.title) .fontWeight(.bold) Text("Add words and phrases that should be preserved in post-processing.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) VStack(alignment: .leading, spacing: 8) { Text("Vocabulary") .font(.headline) TextEditor(text: $customVocabularyInput) .font(.system(.body, design: .monospaced)) .frame(minHeight: 130) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(Color.secondary.opacity(0.3), lineWidth: 1) ) Text("Separate entries with commas, new lines, or semicolons.") .font(.caption) .foregroundStyle(.secondary) } stepIndicator } } var launchAtLoginStep: some View { VStack(spacing: 20) { Image(systemName: "sunrise.fill") .font(.system(size: 60)) .foregroundStyle(.blue) Text("Launch at Login") .font(.title) .fontWeight(.bold) Text("Start FreeFlow automatically when you log in so it's always ready.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) HStack { Image(systemName: "sunrise.fill") .frame(width: 24) .foregroundStyle(.blue) Toggle("Launch FreeFlow at login", isOn: $appState.launchAtLogin) } .padding(12) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(8) stepIndicator } } var testTranscriptionStep: some View { VStack(spacing: 20) { // Microphone picker VStack(spacing: 4) { Picker("Microphone:", selection: $appState.selectedMicrophoneID) { Text("System Default").tag("default") ForEach(appState.availableMicrophones) { device in Text(device.name).tag(device.uid) } } .frame(maxWidth: 340) Text("You can change this later in the menu bar or settings.") .font(.caption2) .foregroundStyle(.tertiary) } Spacer() Group { switch testPhase { case .idle: VStack(spacing: 20) { Image(systemName: "mic.fill") .font(.system(size: 60)) .foregroundStyle(.blue) .scaleEffect(testMicPulsing ? 1.15 : 1.0) .animation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true), value: testMicPulsing) Text("Let's Try It Out!") .font(.title) .fontWeight(.bold) Text("Hold **\(appState.selectedHotkey.displayName)**") .font(.headline) .padding(.horizontal, 16) .padding(.vertical, 10) .background(Color.blue.opacity(0.1)) .cornerRadius(10) Text("Say anything — a sentence or two is perfect.") .foregroundStyle(.secondary) .multilineTextAlignment(.center) } case .recording: VStack(spacing: 20) { ZStack { Circle() .fill(Color.blue.opacity(0.65)) .frame(width: 100, height: 100) Circle() .stroke(Color.blue.opacity(0.8), lineWidth: 3) .frame(width: 100, height: 100) .shadow(color: .blue.opacity(0.5), radius: 10) WaveformView(audioLevel: testAudioLevel) } Text("Listening...") .font(.title2) .fontWeight(.semibold) .foregroundStyle(.blue) } case .transcribing: VStack(spacing: 20) { InlineTranscribingDots() Text("Transcribing...") .font(.title2) .fontWeight(.semibold) .foregroundStyle(.secondary) } case .done: VStack(spacing: 16) { Image(systemName: "checkmark.circle.fill") .font(.system(size: 60)) .foregroundStyle(.green) if let error = testError { Text("Something went wrong") .font(.title2) .fontWeight(.semibold) Text(error) .font(.callout) .foregroundStyle(.secondary) .multilineTextAlignment(.center) Text("Hold **\(appState.selectedHotkey.displayName)** to try again") .font(.callout) .foregroundStyle(.secondary) } else if testTranscript.isEmpty { Text("No speech detected") .font(.title2) .fontWeight(.semibold) .foregroundStyle(.secondary) Text("Hold **\(appState.selectedHotkey.displayName)** to try again") .font(.callout) .foregroundStyle(.secondary) } else { Text("Perfect — FreeFlow is ready to go.") .font(.title2) .fontWeight(.semibold) Text(testTranscript) .font(.body) .padding(12) .frame(maxWidth: .infinity, alignment: .leading) .background(Color(nsColor: .controlBackgroundColor)) .cornerRadius(10) .transition(.move(edge: .bottom).combined(with: .opacity)) Text("Hold **\(appState.selectedHotkey.displayName)** to try again") .font(.callout) .foregroundStyle(.secondary) } } } } .transition(.opacity) .id(testPhase) Spacer() stepIndicator } .onAppear { appState.refreshAvailableMicrophones() testMicPulsing = true startTestHotkeyMonitoring() } .onDisappear { stopTestHotkeyMonitoring() } } var readyStep: some View { VStack(spacing: 20) { Image(systemName: "checkmark.circle.fill") .font(.system(size: 60)) .foregroundStyle(.green) Text("You're All Set!") .font(.title) .fontWeight(.bold) Text("FreeFlow lives in your menu bar.") .multilineTextAlignment(.center) .foregroundStyle(.secondary) VStack(alignment: .leading, spacing: 12) { HowToRow(icon: "keyboard", text: "Hold \(appState.selectedHotkey.displayName) to record") HowToRow(icon: "hand.raised", text: "Release to stop and transcribe") HowToRow(icon: "doc.on.clipboard", text: "Text is typed at your cursor & copied") } .padding(.top, 10) stepIndicator } } var stepIndicator: some View { HStack(spacing: 8) { ForEach(totalSteps, id: \.rawValue) { step in Circle() .fill(step == currentStep ? Color.blue : Color.gray.opacity(0.3)) .frame(width: 8, height: 8) } } .padding(.top, 20) } private var canContinueFromCurrentStep: Bool { switch currentStep { case .micPermission: return micPermissionGranted case .accessibility: return accessibilityGranted case .screenRecording: return appState.hasScreenRecordingPermission case .testTranscription: return testPhase == .done && !testTranscript.isEmpty && testError == nil default: return true } } // MARK: - Helpers private func instructionRow(number: String, text: LocalizedStringKey) -> some View { HStack(alignment: .top, spacing: 6) { Text(number + ".") .font(.subheadline.monospacedDigit()) .foregroundStyle(.secondary) .frame(width: 16, alignment: .trailing) Text(text) .font(.subheadline) .tint(.blue) } } // MARK: - Actions func validateAndContinue() { let key = apiKeyInput.trimmingCharacters(in: .whitespacesAndNewlines) isValidatingKey = true keyValidationError = nil Task { let valid = await TranscriptionService.validateAPIKey(key) await MainActor.run { isValidatingKey = false if valid { appState.apiKey = key withAnimation { currentStep = nextStep(currentStep) } } else { keyValidationError = "Invalid API key. Please check and try again." } } } } func saveCustomVocabularyAndContinue() { appState.customVocabulary = customVocabularyInput.trimmingCharacters(in: .whitespacesAndNewlines) withAnimation { currentStep = nextStep(currentStep) } } private func previousStep(_ step: SetupStep) -> SetupStep { let previous = SetupStep(rawValue: step.rawValue - 1) return previous ?? .welcome } private func nextStep(_ step: SetupStep) -> SetupStep { let next = SetupStep(rawValue: step.rawValue + 1) return next ?? .ready } func checkMicPermission() { switch AVCaptureDevice.authorizationStatus(for: .audio) { case .authorized: micPermissionGranted = true default: break } } func requestMicPermission() { AVCaptureDevice.requestAccess(for: .audio) { granted in DispatchQueue.main.async { micPermissionGranted = granted } } } func checkAccessibility() { accessibilityGranted = AXIsProcessTrusted() } func startAccessibilityPolling() { accessibilityTimer?.invalidate() accessibilityTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in DispatchQueue.main.async { checkAccessibility() } } } func requestAccessibility() { let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue(): true] as CFDictionary AXIsProcessTrustedWithOptions(options) } func startScreenRecordingPolling() { screenRecordingTimer?.invalidate() screenRecordingTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in DispatchQueue.main.async { appState.hasScreenRecordingPermission = CGPreflightScreenCaptureAccess() } } } // MARK: - Test Transcription private func startTestHotkeyMonitoring() { appState.hotkeyManager.onKeyDown = { [self] in DispatchQueue.main.async { guard testPhase == .idle || testPhase == .done else { return } if testPhase == .done { resetTest() } do { let recorder = AudioRecorder() try recorder.startRecording(deviceUID: appState.selectedMicrophoneID) testAudioRecorder = recorder testAudioLevelCancellable = recorder.$audioLevel .receive(on: DispatchQueue.main) .sink { level in testAudioLevel = level } withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) { testPhase = .recording } } catch { testError = error.localizedDescription withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) { testPhase = .done } } } } appState.hotkeyManager.onKeyUp = { [self] in DispatchQueue.main.async { guard testPhase == .recording, let recorder = testAudioRecorder else { return } let fileURL = recorder.stopRecording() testAudioLevelCancellable?.cancel() testAudioLevelCancellable = nil testAudioLevel = 0.0 withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) { testPhase = .transcribing } guard let url = fileURL else { testError = "No audio file was created." withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) { testPhase = .done } return } Task { do { let service = TranscriptionService(apiKey: appState.apiKey) let transcript = try await service.transcribe(fileURL: url) await MainActor.run { testTranscript = transcript withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) { testPhase = .done } } } catch { await MainActor.run { testError = error.localizedDescription withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) { testPhase = .done } } } // Clean up temp file recorder.cleanup() } } } appState.hotkeyManager.start(option: appState.selectedHotkey) } private func stopTestHotkeyMonitoring() { appState.hotkeyManager.stop() appState.hotkeyManager.onKeyDown = nil appState.hotkeyManager.onKeyUp = nil testAudioLevelCancellable?.cancel() testAudioLevelCancellable = nil if let recorder = testAudioRecorder, recorder.isRecording { _ = recorder.stopRecording() recorder.cleanup() } testAudioRecorder = nil } private func resetTest() { testPhase = .idle testTranscript = "" testError = nil testAudioLevel = 0.0 testMicPulsing = true if let recorder = testAudioRecorder { if recorder.isRecording { _ = recorder.stopRecording() } recorder.cleanup() testAudioRecorder = nil } } } struct GitHubRepoInfo: Decodable { let stargazersCount: Int private enum CodingKeys: String, CodingKey { case stargazersCount = "stargazers_count" } } struct GitHubStarRecord: Decodable, Identifiable { let user: GitHubStarUser var id: Int { user.id } } struct GitHubStarUser: Decodable { let id: Int let login: String let avatarUrl: URL let htmlUrl: URL /// Avatar URL resized to 44px (2x for 22pt display) for efficient loading var avatarThumbnailUrl: URL { // GitHub avatar URLs already have query params, so append with & let separator = avatarUrl.absoluteString.contains("?") ? "&" : "?" return URL(string: avatarUrl.absoluteString + "\(separator)s=44")! } private enum CodingKeys: String, CodingKey { case id case login case avatarUrl = "avatar_url" case htmlUrl = "html_url" } } @MainActor class GitHubMetadataCache: ObservableObject { static let shared = GitHubMetadataCache() @Published var starCount: Int? @Published var recentStargazers: [GitHubStarRecord] = [] @Published var isLoading = true private var lastFetchDate: Date? private let cacheDuration: TimeInterval = 5 * 60 // 5 minutes private let repoAPIURL = URL(string: "https://api.github.com/repos/zachlatta/freeflow")! private init() {} func fetchIfNeeded() async { if let lastFetch = lastFetchDate, Date().timeIntervalSince(lastFetch) < cacheDuration { return } isLoading = true do { let repoResult = try await URLSession.shared.data(from: repoAPIURL) guard let repoHTTP = repoResult.1 as? HTTPURLResponse, (200..<300).contains(repoHTTP.statusCode) else { throw URLError(.badServerResponse) } let count = try JSONDecoder().decode(GitHubRepoInfo.self, from: repoResult.0).stargazersCount var recent: [GitHubStarRecord] = [] if count > 0 { let perPage = 100 let lastPage = max(1, Int(ceil(Double(count) / Double(perPage)))) let stargazersURL = URL(string: "https://api.github.com/repos/zachlatta/freeflow/stargazers?per_page=\(perPage)&page=\(lastPage)")! var request = URLRequest(url: stargazersURL) request.setValue("application/vnd.github.v3.star+json", forHTTPHeaderField: "Accept") let starredResult = try await URLSession.shared.data(for: request) if let starredHTTP = starredResult.1 as? HTTPURLResponse, (200..<300).contains(starredHTTP.statusCode) { let all = try JSONDecoder().decode([GitHubStarRecord].self, from: starredResult.0) recent = Array(all.suffix(15).reversed()) } } starCount = count recentStargazers = recent isLoading = false lastFetchDate = Date() } catch { isLoading = false } } } private struct InlineTranscribingDots: View { @State private var activeDot = 0 let timer = Timer.publish(every: 0.4, on: .main, in: .common).autoconnect() var body: some View { HStack(spacing: 8) { ForEach(0..<3, id: \.self) { index in Circle() .fill(Color.blue.opacity(activeDot == index ? 1.0 : 0.3)) .frame(width: 12, height: 12) .scaleEffect(activeDot == index ? 1.3 : 1.0) .animation(.easeInOut(duration: 0.3), value: activeDot) } } .onReceive(timer) { _ in activeDot = (activeDot + 1) % 3 } } } struct HotkeyOptionRow: View { let option: HotkeyOption let isSelected: Bool let action: () -> Void var body: some View { Button(action: action) { HStack { Image(systemName: isSelected ? "checkmark.circle.fill" : "circle") .foregroundStyle(isSelected ? .blue : .secondary) Text(option.displayName) .foregroundStyle(.primary) Spacer() } .padding(12) .background(isSelected ? Color.blue.opacity(0.1) : Color(nsColor: .controlBackgroundColor)) .cornerRadius(8) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(isSelected ? Color.blue : Color.clear, lineWidth: 1.5) ) } .buttonStyle(.plain) } } struct HowToRow: View { let icon: String let text: String var body: some View { HStack(spacing: 12) { Image(systemName: icon) .frame(width: 24) .foregroundStyle(.blue) Text(text) .foregroundStyle(.secondary) } } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/TranscriptionService.swift
Swift
import Foundation class TranscriptionService { private let apiKey: String private let baseURL = "https://api.groq.com/openai/v1" private let transcriptionModel = "whisper-large-v3" private let transcriptionTimeoutSeconds: TimeInterval = 20 init(apiKey: String) { self.apiKey = apiKey } // Validate API key by hitting a lightweight endpoint static func validateAPIKey(_ key: String) async -> Bool { let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return false } var request = URLRequest(url: URL(string: "https://api.groq.com/openai/v1/models")!) request.setValue("Bearer \(trimmed)", forHTTPHeaderField: "Authorization") do { let (_, response) = try await URLSession.shared.data(for: request) let status = (response as? HTTPURLResponse)?.statusCode ?? 0 return status == 200 } catch { return false } } // Upload audio file, submit for transcription, poll until done, return text func transcribe(fileURL: URL) async throws -> String { try await withThrowingTaskGroup(of: String.self) { group in group.addTask { [weak self] in guard let self else { throw TranscriptionError.submissionFailed("Service deallocated") } return try await self.transcribeAudio(fileURL: fileURL) } group.addTask { try await Task.sleep(nanoseconds: UInt64(self.transcriptionTimeoutSeconds * 1_000_000_000)) throw TranscriptionError.transcriptionTimedOut(self.transcriptionTimeoutSeconds) } guard let result = try await group.next() else { throw TranscriptionError.submissionFailed("No transcription result") } group.cancelAll() return result } } // Send audio file for transcription and return text private func transcribeAudio(fileURL: URL) async throws -> String { let url = URL(string: "\(baseURL)/audio/transcriptions")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "Content-Type") let boundary = UUID().uuidString let contentType = "multipart/form-data; boundary=\(boundary)" request.setValue(contentType, forHTTPHeaderField: "Content-Type") let audioData = try Data(contentsOf: fileURL) let body = makeMultipartBody( audioData: audioData, fileName: fileURL.lastPathComponent, model: transcriptionModel, boundary: boundary ) request.httpBody = body let (data, response) = try await URLSession.shared.upload(for: request, from: body) guard let httpResponse = response as? HTTPURLResponse else { throw TranscriptionError.submissionFailed("No response from server") } guard httpResponse.statusCode == 200 else { let responseBody = String(data: data, encoding: .utf8) ?? "" throw TranscriptionError.submissionFailed("Status \(httpResponse.statusCode): \(responseBody)") } return try parseTranscript(from: data) } private func makeMultipartBody(audioData: Data, fileName: String, model: String, boundary: String) -> Data { var body = Data() func append(_ value: String) { body.append(Data(value.utf8)) } append("--\(boundary)\r\n") append("Content-Disposition: form-data; name=\"model\"\r\n\r\n") append("\(model)\r\n") append("--\(boundary)\r\n") append("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileName)\"\r\n") append("Content-Type: \(audioContentType(for: fileName))\r\n\r\n") body.append(audioData) append("\r\n") append("--\(boundary)--\r\n") return body } private func audioContentType(for fileName: String) -> String { if fileName.lowercased().hasSuffix(".wav") { return "audio/wav" } if fileName.lowercased().hasSuffix(".mp3") { return "audio/mpeg" } if fileName.lowercased().hasSuffix(".m4a") { return "audio/mp4" } return "audio/mp4" } private func parseTranscript(from data: Data) throws -> String { if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let text = json["text"] as? String { return text } let plainText = String(data: data, encoding: .utf8) ?? "" let text = plainText .components(separatedBy: .newlines) .joined(separator: " ") .trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty else { throw TranscriptionError.pollFailed("Invalid response") } return text } } enum TranscriptionError: LocalizedError { case uploadFailed(String) case submissionFailed(String) case transcriptionFailed(String) case transcriptionTimedOut(TimeInterval) case pollFailed(String) var errorDescription: String? { switch self { case .uploadFailed(let msg): return "Upload failed: \(msg)" case .submissionFailed(let msg): return "Submission failed: \(msg)" case .transcriptionTimedOut(let seconds): return "Transcription timed out after \(Int(seconds))s" case .transcriptionFailed(let msg): return "Transcription failed: \(msg)" case .pollFailed(let msg): return "Polling failed: \(msg)" } } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
Sources/UpdateManager.swift
Swift
import Foundation import AppKit // MARK: - Data Models struct GitHubRelease: Decodable { let tagName: String let name: String? let htmlUrl: String let publishedAt: String let assets: [GitHubReleaseAsset] enum CodingKeys: String, CodingKey { case tagName = "tag_name" case name case htmlUrl = "html_url" case publishedAt = "published_at" case assets } } struct GitHubReleaseAsset: Decodable { let name: String let browserDownloadUrl: String let size: Int enum CodingKeys: String, CodingKey { case name case browserDownloadUrl = "browser_download_url" case size } } // MARK: - Update Status enum UpdateStatus: Equatable { case idle case downloading case installing case readyToRelaunch case error(String) } // MARK: - Update Manager @MainActor final class UpdateManager: ObservableObject { static let shared = UpdateManager() @Published var updateAvailable = false @Published var latestRelease: GitHubRelease? @Published var latestReleaseDate: String = "" @Published var isChecking = false @Published var downloadProgress: Double? @Published var updateStatus: UpdateStatus = .idle @Published var lastCheckDate: Date? { didSet { if let date = lastCheckDate { UserDefaults.standard.set(date, forKey: "updateLastCheckDate") } } } var autoCheckEnabled: Bool { get { UserDefaults.standard.object(forKey: "updateAutoCheckEnabled") as? Bool ?? true } set { UserDefaults.standard.set(newValue, forKey: "updateAutoCheckEnabled") } } private var skippedVersion: String? { get { UserDefaults.standard.string(forKey: "updateSkippedVersion") } set { UserDefaults.standard.set(newValue, forKey: "updateSkippedVersion") } } private let releasesURL = URL(string: "https://api.github.com/repos/zachlatta/freeflow/releases/latest")! private let stabilityBufferDays: TimeInterval = 3 private let checkIntervalSeconds: TimeInterval = 7 * 24 * 60 * 60 // 7 days private var periodicTimer: Timer? private var activeDownloadTask: URLSessionDataTask? private init() { lastCheckDate = UserDefaults.standard.object(forKey: "updateLastCheckDate") as? Date } // MARK: - Periodic Checks func startPeriodicChecks() { // Initial check after 5 second delay DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in guard let self else { return } Task { @MainActor in if self.shouldAutoCheck() { await self.checkForUpdates(userInitiated: false) } } } // Re-evaluate hourly (handles sleep/wake) periodicTimer?.invalidate() periodicTimer = Timer.scheduledTimer(withTimeInterval: 3600, repeats: true) { [weak self] _ in guard let self else { return } Task { @MainActor in if self.shouldAutoCheck() { await self.checkForUpdates(userInitiated: false) } } } } private func shouldAutoCheck() -> Bool { guard autoCheckEnabled else { return false } guard let lastCheck = lastCheckDate else { return true } return Date().timeIntervalSince(lastCheck) > checkIntervalSeconds } // MARK: - Check for Updates func checkForUpdates(userInitiated: Bool) async { let currentBuildTag = Bundle.main.infoDictionary?["FreeFlowBuildTag"] as? String // Dev builds (no embedded tag): skip auto-checks, but allow manual checks if !userInitiated && currentBuildTag == nil { return } isChecking = true defer { isChecking = false } do { var request = URLRequest(url: releasesURL) request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") request.cachePolicy = .reloadIgnoringLocalCacheData let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { if userInitiated { showErrorAlert("Could not reach GitHub.") } return } // 404 means no releases exist yet if httpResponse.statusCode == 404 { lastCheckDate = Date() updateAvailable = false latestRelease = nil if userInitiated { showUpToDateAlert() } return } guard (200..<300).contains(httpResponse.statusCode) else { if userInitiated { showErrorAlert("GitHub returned status \(httpResponse.statusCode).") } return } let decoder = JSONDecoder() let release = try decoder.decode(GitHubRelease.self, from: data) lastCheckDate = Date() // Parse the published date let iso8601 = ISO8601DateFormatter() iso8601.formatOptions = [.withInternetDateTime, .withFractionalSeconds] let iso8601Basic = ISO8601DateFormatter() iso8601Basic.formatOptions = [.withInternetDateTime] guard let publishedDate = iso8601.date(from: release.publishedAt) ?? iso8601Basic.date(from: release.publishedAt) else { if userInitiated { showErrorAlert("Could not parse release date.") } return } // Format the release date for display let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none let releaseDateString = dateFormatter.string(from: publishedDate) // If this is the same build we're running, no update available if let currentTag = currentBuildTag, release.tagName == currentTag { updateAvailable = false latestRelease = nil if userInitiated { showUpToDateAlert() } return } // Check stability buffer (3 days since published) let daysSincePublished = Date().timeIntervalSince(publishedDate) / (24 * 60 * 60) if daysSincePublished < stabilityBufferDays { if !userInitiated { // Auto-check: silently skip, too new updateAvailable = false return } // Manual check: let user know and offer the update anyway latestRelease = release latestReleaseDate = releaseDateString updateAvailable = true showRecentReleaseAlert(daysSincePublished: daysSincePublished) return } // Check if user skipped this version (only for auto checks) if !userInitiated && skippedVersion == release.tagName { updateAvailable = false return } latestRelease = release latestReleaseDate = releaseDateString updateAvailable = true if userInitiated { showUpdateAlert() } } catch { if userInitiated { showErrorAlert("Failed to check for updates: \(error.localizedDescription)") } } } // MARK: - Alerts func showUpdateAlert() { guard let release = latestRelease else { return } let alert = NSAlert() alert.messageText = "A New Version is Available" alert.informativeText = "A new version of FreeFlow (released \(latestReleaseDate)) is available.\n\nWould you like to download the update?" alert.alertStyle = .informational alert.icon = NSApp.applicationIconImage alert.addButton(withTitle: "Download Update") alert.addButton(withTitle: "Remind Me Later") alert.addButton(withTitle: "Skip This Version") let response = alert.runModal() switch response { case .alertFirstButtonReturn: downloadAndInstall(release: release) case .alertThirdButtonReturn: skippedVersion = release.tagName updateAvailable = false latestRelease = nil default: break // Remind me later — do nothing } } private func showRecentReleaseAlert(daysSincePublished: Double) { guard let release = latestRelease else { return } let hoursAgo = Int(daysSincePublished * 24) let ageText = hoursAgo < 1 ? "less than an hour ago" : hoursAgo < 24 ? "\(hoursAgo) hour\(hoursAgo == 1 ? "" : "s") ago" : "\(Int(daysSincePublished)) day\(Int(daysSincePublished) == 1 ? "" : "s") ago" let alert = NSAlert() alert.messageText = "New Release Available" alert.informativeText = "A new version of FreeFlow was released \(ageText). It's very recent — you can download it now or wait a few days for stability.\n\nWould you like to download it?" alert.alertStyle = .informational alert.icon = NSApp.applicationIconImage alert.addButton(withTitle: "Download Now") alert.addButton(withTitle: "Wait") let response = alert.runModal() if response == .alertFirstButtonReturn { downloadAndInstall(release: release) } } func showUpToDateAlert() { let alert = NSAlert() alert.messageText = "You're Up to Date" alert.informativeText = "You're running the latest version of FreeFlow." alert.alertStyle = .informational alert.icon = NSApp.applicationIconImage alert.addButton(withTitle: "OK") alert.runModal() } private func showErrorAlert(_ message: String) { let alert = NSAlert() alert.messageText = "Update Check Failed" alert.informativeText = message alert.alertStyle = .warning alert.icon = NSApp.applicationIconImage alert.addButton(withTitle: "OK") alert.runModal() } // MARK: - Download and Install func cancelDownload() { activeDownloadTask?.cancel() activeDownloadTask = nil downloadProgress = nil updateStatus = .idle } func downloadAndInstall(release: GitHubRelease) { guard let dmgAsset = release.assets.first(where: { $0.name.hasSuffix(".dmg") }) else { if let url = URL(string: release.htmlUrl) { NSWorkspace.shared.open(url) } return } guard let downloadURL = URL(string: dmgAsset.browserDownloadUrl) else { return } Task { await performUpdate(downloadURL: downloadURL, expectedSize: dmgAsset.size) } } private func performUpdate(downloadURL: URL, expectedSize: Int) async { let fm = FileManager.default let tempDir = fm.temporaryDirectory.appendingPathComponent("freeflow-update-\(UUID().uuidString)") do { try fm.createDirectory(at: tempDir, withIntermediateDirectories: true) } catch { updateStatus = .error("Failed to create temp directory: \(error.localizedDescription)") return } let dmgPath = tempDir.appendingPathComponent("FreeFlow.dmg") // MARK: Download phase updateStatus = .downloading downloadProgress = 0 do { var request = URLRequest(url: downloadURL) request.cachePolicy = .reloadIgnoringLocalCacheData let (asyncBytes, response) = try await URLSession.shared.bytes(for: request) let totalSize = (response as? HTTPURLResponse) .flatMap { Int($0.value(forHTTPHeaderField: "Content-Length") ?? "") } ?? expectedSize let outputHandle = try FileHandle(forWritingTo: { fm.createFile(atPath: dmgPath.path, contents: nil) return dmgPath }()) var receivedBytes = 0 let bufferSize = 65_536 var buffer = Data() buffer.reserveCapacity(bufferSize) for try await byte in asyncBytes { buffer.append(byte) if buffer.count >= bufferSize { outputHandle.write(buffer) receivedBytes += buffer.count buffer.removeAll(keepingCapacity: true) if totalSize > 0 { downloadProgress = Double(receivedBytes) / Double(totalSize) } } } // Write remaining bytes if !buffer.isEmpty { outputHandle.write(buffer) receivedBytes += buffer.count } try outputHandle.close() downloadProgress = 1.0 } catch is CancellationError { try? fm.removeItem(at: tempDir) return } catch let error as URLError where error.code == .cancelled { try? fm.removeItem(at: tempDir) return } catch { updateStatus = .error("Download failed: \(error.localizedDescription)") downloadProgress = nil try? fm.removeItem(at: tempDir) return } // MARK: Install phase - mount DMG, extract app updateStatus = .installing downloadProgress = nil do { let mountPoint = try await mountDMG(at: dmgPath) defer { // Always try to detach let detach = Process() detach.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil") detach.arguments = ["detach", mountPoint, "-quiet"] try? detach.run() detach.waitUntilExit() } // Find the .app inside the mounted volume let volumeURL = URL(fileURLWithPath: mountPoint) let contents = try fm.contentsOfDirectory(at: volumeURL, includingPropertiesForKeys: nil) guard let appBundle = contents.first(where: { $0.pathExtension == "app" }) else { updateStatus = .error("No .app found in DMG.") try? fm.removeItem(at: tempDir) return } // Copy app to staging directory let stagingDir = fm.temporaryDirectory.appendingPathComponent("freeflow-staged-\(UUID().uuidString)") try fm.createDirectory(at: stagingDir, withIntermediateDirectories: true) let stagedApp = stagingDir.appendingPathComponent(appBundle.lastPathComponent) try fm.copyItem(at: appBundle, to: stagedApp) // Clean up DMG (detach happens in defer above, delete temp dir) try? fm.removeItem(at: tempDir) // MARK: Replace & relaunch updateStatus = .readyToRelaunch replaceAndRelaunch(stagedApp: stagedApp, stagingDir: stagingDir) } catch { updateStatus = .error("Install failed: \(error.localizedDescription)") try? fm.removeItem(at: tempDir) } } private func mountDMG(at path: URL) async throws -> String { let process = Process() process.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil") process.arguments = ["attach", path.path, "-nobrowse", "-noverify", "-noautoopen", "-plist"] let pipe = Pipe() process.standardOutput = pipe process.standardError = Pipe() try process.run() process.waitUntilExit() guard process.terminationStatus == 0 else { throw NSError(domain: "UpdateManager", code: 1, userInfo: [ NSLocalizedDescriptionKey: "hdiutil attach failed with exit code \(process.terminationStatus)" ]) } let data = pipe.fileHandleForReading.readDataToEndOfFile() // Parse the plist output to find mount point guard let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], let entities = plist["system-entities"] as? [[String: Any]] else { throw NSError(domain: "UpdateManager", code: 2, userInfo: [ NSLocalizedDescriptionKey: "Could not parse hdiutil output" ]) } // Find the mount point from the entities for entity in entities { if let mountPoint = entity["mount-point"] as? String { return mountPoint } } throw NSError(domain: "UpdateManager", code: 3, userInfo: [ NSLocalizedDescriptionKey: "No mount point found in hdiutil output" ]) } private func replaceAndRelaunch(stagedApp: URL, stagingDir: URL) { let currentAppPath = Bundle.main.bundlePath let pid = ProcessInfo.processInfo.processIdentifier let script = """ while kill -0 \(pid) 2>/dev/null; do sleep 0.2; done rm -rf "\(currentAppPath)" mv "\(stagedApp.path)" "\(currentAppPath)" open "\(currentAppPath)" rm -rf "\(stagingDir.path)" """ let process = Process() process.executableURL = URL(fileURLWithPath: "/bin/bash") process.arguments = ["-c", script] try? process.run() // Quit the current app NSApp.terminate(nil) } }
zachlatta/freeflow
247
Free and open source alternative to Wispr Flow / Superwhisper / Monologue / etc
Swift
zachlatta
Zach Latta
hackclub
frontend/app.ts
TypeScript
import { Howl } from 'howler' //// UTILITIES import { v4 as uuidLib } from 'uuid' const uuid = uuidLib const elementFromHTML = (html: string): HTMLElement => { let div = document.createElement('div') div.innerHTML = html.trim() return div.firstChild as HTMLElement } //// APP LOGIC const welcome = document.getElementById('welcome') const welcomeButton = document.getElementById('welcomeButton') const app = document.getElementById('app') const soundSourcesDiv = document.getElementById('soundSources') const addSoundSourceForm = document.getElementById('addSoundSource') as HTMLFormElement enum SoundSourceState { Load, LoadError, Play, PlayError } class SoundSource { id: string url: string state: SoundSourceState el: HTMLElement sound: Howl destroyCallback: (SoundSource) => void dragXOffset: number dragYOffset: number private destroyId() { return `${this.id}-destroy` } constructor(url: string, destroyCallback: (SoundSource) => void) { this.id = uuid() this.url = url this.state = SoundSourceState.Load this.el = elementFromHTML(this.outerHTML()) this.sound = new Howl({ src: [url], onloaderror: () => { this.state = SoundSourceState.LoadError; this.rerender() }, onplay: () => { this.state = SoundSourceState.Play; this.rerender() }, onplayerror: () => { this.state = SoundSourceState.PlayError; this.rerender() } }) // html5 enables streaming audio this.destroyCallback = destroyCallback this.dragXOffset = 0 this.dragYOffset = 0 } outerHTML() { return ` <div class="soundSource" id="${this.id}"> ${this.innerHTML()} </div> ` } innerHTML() { const stateText = [ `Loading ${this.url}...`, `Error loading ${this.url}.`, `Playing ${this.url}!`, `Error playing ${this.url}` ][this.state] return ` <p>${stateText} <button id="${this.destroyId()}">x</button></p> ` } rerender() { this.el.innerHTML = this.innerHTML() // teardown, when destroy button is clicked document.getElementById(this.destroyId()).addEventListener('click', e => { this.sound.stop() this.destroyCallback(this) }) } appendTo(parentInDocument: HTMLElement) { parentInDocument.appendChild(this.el) this.rerender() this.sound.play() } } let soundSources: SoundSource[] = [] addSoundSourceForm.addEventListener('submit', e => { e.preventDefault() const data = new FormData(addSoundSourceForm) const url = data.get('url') as string if (url == '') { return } const soundSource = new SoundSource(url, (toDestroy: SoundSource) => { toDestroy.el.remove() soundSources.splice(soundSources.indexOf(toDestroy), 1) // remove }) soundSources.push(soundSource) soundSource.appendTo(soundSourcesDiv) addSoundSourceForm.reset() }) // set up drag and drop logic, from https://www.kirupa.com/html5/drag.htm let active let currentX let currentY let initialX let initialY let xOffset = 0 let yOffset = 0 const dragStart = (e) => { active = soundSources.find(s => { if (s.el === e.target) { return true } // TODO: Right now it only checks direct children, should be changed to // recurse through all children. let match = false s.el.childNodes.forEach(child => { if (child === e.target) { match = true } }) return match }) if (active == null) { return } if (e.type === "touchstart") { initialX = e.touches[0].clientX - active.dragXOffset initialY = e.touches[0].clientY - active.dragYOffset } else { initialX = e.clientX - active.dragXOffset initialY = e.clientY - active.dragYOffset } } const dragEnd = (e) => { initialX = currentX initialY = currentY active = null } const drag = (e) => { if (active) { e.preventDefault() if (e.type === "touchmove") { currentX = e.touches[0].clientX - initialX currentY = e.touches[0].clientY - initialY } else { currentX = e.clientX - initialX currentY = e.clientY - initialY } active.dragXOffset = currentX active.dragYOffset = currentY active.sound.pos(currentX / 80, currentY / 80) active.el.style.transform = `translate3d(${currentX}px, ${currentY}px, 0)` } } soundSourcesDiv.addEventListener('touchstart', dragStart, false) soundSourcesDiv.addEventListener('touchend', dragEnd, false) soundSourcesDiv.addEventListener('touchmove', drag, false) soundSourcesDiv.addEventListener('mousedown', dragStart, false) soundSourcesDiv.addEventListener('mouseup', dragEnd, false) soundSourcesDiv.addEventListener('mousemove', drag, false) // start the app when they click the welcome button! const startApp = () => { welcome.style.display = 'none' app.style.display = 'block' } welcomeButton.addEventListener('click', startApp)
zachlatta/soundscape
9
Attempt to make a soundscape designer in the web
TypeScript
zachlatta
Zach Latta
hackclub
frontend/index.html
HTML
<!DOCTYPE html> <html> <head> <title>Soundscape</title> <style> html, body { width: 100%; height: 100%; padding: 0; margin: 0; } #app { width: 100%; height: 100%; } #soundSources { background-color: rgb(203, 229, 247); display: flex; align-items: center; justify-content: center; overflow: hidden; border-radius: 7px; touch-action: none; min-height: 500px; } .soundSource { width: 250px; background-color: white; border: 10px solid rgba(184, 211, 33, 0.5); border-radius: 25px; touch-action: none; user-select: none; } .soundSource#hover { cursor: pointer; border-width: 200px; } </style> </head> <body> <div id="welcome"> <p>Hello, hello! And welcome to Soundscape.</p> <p>To get started, please click this button:</p> <button id="welcomeButton">Click me!</button> </div> <div id="app" style="display: none;"> <div id="soundSources"> </div> <div> <form id="addSoundSource"> Enter sound source URL: <input type="text" name="url"> <input type="submit" value="Add"> </form> </div> </div> <script src="app.js"></script> </body> </html>
zachlatta/soundscape
9
Attempt to make a soundscape designer in the web
TypeScript
zachlatta
Zach Latta
hackclub
demo.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <title>Fundraising Status</title> <style> :root { color-scheme: light dark; } body { color: light-dark(#222, #ddd); background-color: light-dark(#fff, #222); } a[href]:has(fundraising-status) { display: block; cursor: pointer; text-decoration: none; color: inherit; } a[href]:has(fundraising-status):hover { background-color: rgba(0,0,0,.06); } @media (prefers-color-scheme: dark) { a[href]:has(fundraising-status):hover { background-color: rgba(255,255,255,.03); } } </style> <script type="module" src="fundraising-status.js"></script> </head> <body> <header> <h1>Fundraising Status</h1> </header> <main> <p>Back to the <a href="https://github.com/zachleat/fundraising-status">GitHub source code</a>.</p> <p> Empty slot: <fundraising-status min="0" max="200" value="100"></fundraising-status> </p> <p> Slot for favicon or other arbitrary html: <fundraising-status min="0" max="200" value="100"> <img src="https://v1.indieweb-avatar.11ty.dev/https%3A%2F%2Fwww.11ty.dev%2F/" width="30" height="30" alt="11ty Logo" loading="lazy" decoding="async"> </fundraising-status> </p> <p> max width <fundraising-status min="0" max="200" value="100" style="max-width: 14em"> <img src="https://v1.indieweb-avatar.11ty.dev/https%3A%2F%2Fwww.11ty.dev%2F/" width="30" height="30" alt="11ty Logo" loading="lazy" decoding="async"> </fundraising-status> </p> <p> Link Wrapper <a href="https://opencollective.com/11ty"> <fundraising-status min="0" max="200" value="100"> <img src="https://v1.indieweb-avatar.11ty.dev/https%3A%2F%2Fwww.11ty.dev%2F/" width="30" height="30" alt="11ty Logo" loading="lazy" decoding="async"> </fundraising-status> </a> </p> <p> Hide Currency <fundraising-status min="0" max="200" value="100" hide-currency> <span style="margin-right: .75em; display: flex; align-items: center; gap: .5em"> <img src="https://v1.indieweb-avatar.11ty.dev/https%3A%2F%2Fwww.11ty.dev%2F/" width="30" height="30" alt="11ty Logo" loading="lazy" decoding="async"> Sustainability Fundraising </span> </fundraising-status> </p> <p> Intl.NumberFormat currency: <fundraising-status min="0" max="200" value="100" currency="USD"></fundraising-status> </p> <p> Change accent color: <fundraising-status style="--fs-color: #e23c2f" min="0" max="2" value="1"></fundraising-status> </p> <p> Scale with font size: <fundraising-status style="font-size: 2em"> <img src="https://v1.indieweb-avatar.11ty.dev/https%3A%2F%2Fwww.11ty.dev%2F/" width="30" height="30" alt="11ty Logo" loading="lazy" decoding="async"> </fundraising-status> </p> </main> </body> </html>
zachleat/fundraising-status
5
Web component to show the current status of a fundraiser.
HTML
zachleat
Zach Leatherman
11ty, fortawesome
fundraising-status.js
JavaScript
class FundraisingStatus extends HTMLElement { static tagName = "fundraising-status"; static css = ` :host { --fs-color: #333; --fs-background: #eee; display: flex; flex-wrap: nowrap; white-space: nowrap; align-items: center; gap: .25em; } @media (prefers-color-scheme: dark) { :host { --fs-color: rgba(255,255,255,.9); --fs-background: rgba(0,0,0,.2); } } progress { flex-grow: 1; accent-color: var(--fs-color); width: 100%; } .max, .currency { font-size: .8125em; } @supports (appearance: none) { progress { height: 1em; border-radius: .125em; overflow: hidden; appearance: none; } ::-webkit-progress-value { background: var(--fs-color); } ::-moz-progress-bar { background: var(--fs-color); } ::-webkit-progress-bar { background-color: var(--fs-background); box-shadow: 0 .125em .3125em rgba(0, 0, 0, 0.25) inset; } } `; static register(tagName) { if(!("customElements" in globalThis)) { return; } customElements.define(tagName || this.tagName, this); } get currency() { return this.getAttribute("currency") || "USD"; } formatPrice(num, locale) { if(!("NumberFormat" in Intl)) { return num; } let localized = new Intl.NumberFormat(locale || navigator.language, { style: "currency", currency: this.currency, currencyDisplay: "symbol", minimumFractionDigits: 0, maximumFractionDigits: 0, }); return localized.format(num); } connectedCallback() { if (!("replaceSync" in CSSStyleSheet.prototype) || this.shadowRoot) { return; } let min = this.getAttribute("min") || 0; let max = this.getAttribute("max") || 1; let value = this.getAttribute("value") || 0; this.attachShadow({ mode: "open" }); let sheet = new CSSStyleSheet(); sheet.replaceSync(FundraisingStatus.css); this.shadowRoot.adoptedStyleSheets = [sheet]; this.render({ min, max, value, }); } async render({min, max, value}) { this.shadowRoot.innerHTML = `<slot></slot> <progress min="${min}" max="${max}" value="${value}"></progress> <code>${this.formatPrice(value)}</code> <code class="max">/${this.formatPrice(max)}</code> ${!this.hasAttribute("hide-currency") ? `<code class="currency">${this.currency}</code>` : ""}`; } } FundraisingStatus.register();
zachleat/fundraising-status
5
Web component to show the current status of a fundraiser.
HTML
zachleat
Zach Leatherman
11ty, fortawesome
demo.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <title>&lt;hyper-card&gt; Web Component</title> <style> /* Demo styles */ body { font-family: system-ui, sans-serif; background-color: #222; color: #fff; } a[href] { color: inherit; } .demo-card { margin: 4em; display: flex; align-items: center; justify-content: center; padding: 1em; width: 300px; height: 400px; box-shadow: 0 1px 5px #00000099; border-radius: 10px; background-color: #222; background-size: cover; } </style> <script type="module" src="hypercard.js"></script> </head> <body> <header> <h1>&lt;hyper-card&gt; Web Component</h1> </header> <main> <p><a href="https://github.com/zachleat/hypercard">Back to the Source Code</a></p> <p>Full credit to the <a href="https://codepen.io/markmiro/pen/wbqMPa">3D card hover effect CodePen from Mark Miro</a>.</p> <hyper-card class="demo-card">Hello</hyper-card> </main> </body> </html>
zachleat/hypercard
58
Web component to add a three-dimensional hover effect to a card.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
hypercard.js
JavaScript
class HyperCard extends HTMLElement { static tagName = "hyper-card"; static register(tagName, registry) { if(!registry && ("customElements" in globalThis)) { registry = globalThis.customElements; } registry?.define(tagName || this.tagName, this); } static classes = { active: "active" }; static css = ` @media (prefers-reduced-motion: no-preference) { :host { --_hypercard-scale: var(--hypercard-scale, 1.07); --_hypercard-perspective: var(--hypercard-perspective, min(2000px, 100vw)); --_hypercard-glow-opacity: var(--hypercard-glow-opacity, 0.3); /* Useful if you want a different parent to create the stacking context */ position: var(--hypercard-position, relative); transition-duration: 300ms; transition-property: transform, box-shadow; transition-timing-function: ease-out; transform: rotate3d(0); overflow: clip; } :host(.${HyperCard.classes.active}) { transition-duration: 150ms; box-shadow: 0 5px 20px 5px #00000044; } :host .glow { position: absolute; z-index: var(--hypercard-glow-zindex, 0); left: 0; top: 0; right: 0; bottom: 0; background-image: radial-gradient(circle at 50% -20%, rgb(255 255 255 / var(--_hypercard-glow-opacity)), #0000000f); pointer-events: none; } :host(:not(.${HyperCard.classes.active})) .glow { display: none; } } `; useAnimation() { return "matchMedia" in window && !window.matchMedia('(prefers-reduced-motion: reduce)').matches; } connectedCallback() { // https://caniuse.com/mdn-api_cssstylesheet_replacesync if(this.shadowRoot || !("replaceSync" in CSSStyleSheet.prototype)) { return; } let shadowroot = this.attachShadow({ mode: "open" }); let sheet = new CSSStyleSheet(); sheet.replaceSync(HyperCard.css); shadowroot.adoptedStyleSheets = [sheet]; let slot = document.createElement("slot"); shadowroot.appendChild(slot); this.glow = document.createElement("div"); this.glow.classList.add("glow"); shadowroot.appendChild(this.glow); this.bindEvents(); } // Full credit to this: https://codepen.io/markmiro/pen/wbqMPa rotateToMouse(e, bounds) { const mouseX = e.clientX; const mouseY = e.clientY; const leftX = mouseX - bounds.x; const topY = mouseY - bounds.y; const center = { x: leftX - bounds.width / 2, y: topY - bounds.height / 2 } const distance = Math.sqrt(center.x**2 + center.y**2); this.style.transform = ` perspective(var(--_hypercard-perspective)) scale3d(var(--_hypercard-scale), var(--_hypercard-scale), var(--_hypercard-scale)) rotate3d( ${center.y / 100}, ${-center.x / 100}, 0, ${Math.log(distance)* 2}deg ) `; this.glow.style.backgroundImage = ` radial-gradient( circle at ${center.x * 2 + bounds.width/2}px ${center.y * 2 + bounds.height/2}px, rgb(255 255 255 / var(--_hypercard-glow-opacity)), #0000000f ) `; } bindEvents() { let bounds; let handler = (e) => { this.rotateToMouse(e, bounds); }; this.addEventListener("mouseenter", () => { if(!this.useAnimation()) { return; } bounds = this.getBoundingClientRect(); this.classList.add(HyperCard.classes.active); document.addEventListener("mousemove", handler); }); this.addEventListener("mouseleave", () => { if(!this.useAnimation()) { return; } this.classList.remove(HyperCard.classes.active); document.removeEventListener("mousemove", handler); this.style.transform = ""; this.style.background = ""; }); } } HyperCard.register(); export { HyperCard }
zachleat/hypercard
58
Web component to add a three-dimensional hover effect to a card.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
demo.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>&lt;line-numbers&gt; Web Component</title> <style> * { box-sizing: border-box; } :root { --uln-font: Roboto Mono, monospace; --uln-padding-h: .75em; --uln-color: #777; } body { font-family: system-ui, sans-serif; max-width: 40em; margin: 0 auto; padding: 0 0 10em; line-height: 1.5; border: 1px solid #eee; } textarea, pre { margin: 0; } line-numbers { background-color: #fafafa; } /* for demo background color pre-JS */ line-numbers:not(:defined) { display: flex; } @media (max-width: 46.1875em) { /* 739px */ line-numbers:not([obtrusive]) { margin-inline-start: 2em; } } pre { width: 100%; font-size: 1rem; overflow: auto; } textarea { border: none; background-color: transparent; font: inherit; } </style> <script type="module" src="./line-numbers.js"></script> </head> <body> <h1>Unencumbered &lt;line-numbers&gt; Web Component</h1> <p>Back to the <a href="https://github.com/zachleat/line-numbers">source code on GitHub</a>.</p> <p>Demo styles (border on &lt;body&gt; and a background-color on &lt;line-numbers&gt;) have been added here to demonstrate obtrusive behavior (the numbers intrude on and shrink the width of the original content).</p> <h2>&lt;pre&gt;</h2> <line-numbers> <pre># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> </line-numbers> <h3>&lt;pre&gt; (obtrusive, start with 999)</h3> <line-numbers obtrusive start="999"> <pre># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> </line-numbers> <h3><code>&lt;pre&gt;</code> with vertical overflow</h3> <line-numbers> <pre style="max-height: 6em; overflow: auto;"># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> </line-numbers> <h3><code>&lt;pre&gt;</code> with vertical overflow (obtrusive)</h3> <line-numbers obtrusive> <pre style="max-height: 6em; overflow: auto;"># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> </line-numbers> <h3><code>&lt;pre&gt;</code> with horizontal overflow</h3> <line-numbers> <pre style="overflow: auto;"># Hello {{ subject }} line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line another line this is getting longer this is getting longer</pre> </line-numbers> <h3><code>&lt;pre&gt;</code> with horizontal overflow (obtrusive)</h3> <line-numbers obtrusive> <pre style="overflow: auto;"># Hello {{ subject }} line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line another line this is getting longer this is getting longer</pre> </line-numbers> <h3><code>&lt;pre&gt;</code> with both overflow</h3> <line-numbers> <pre style="max-height: 6em; overflow: auto;"># Hello {{ subject }} line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line another line this is getting longer this is getting longer</pre> </line-numbers> <h3><code>&lt;pre&gt;</code> with both overflow (obtrusive)</h3> <line-numbers obtrusive> <pre style="max-height: 6em; overflow: auto;"># Hello {{ subject }} line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line another line this is getting longer this is getting longer</pre> </line-numbers> <h3>Change the counter type</h3> <h4>Leading zero</h4> <line-numbers obtrusive style="--uln-number-type: decimal-leading-zero"> <pre style=""># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> </line-numbers> <h4>Upper roman</h4> <line-numbers obtrusive style="--uln-number-type: upper-roman"> <pre style=""># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> </line-numbers> <!-- <h3><code>&lt;pre&gt;</code> with vertical overflow and <code>overscroll-behavior</code></h3> <line-numbers obtrusive> <pre style="max-height: 6em; overflow: auto; overscroll-behavior: contain;"># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> </line-numbers> --> <h2>&lt;textarea&gt;</h2> <h3>&lt;textarea&gt; with vertical overflow</h3> <p>If you type additional lines into the textarea, we add more numbers.</p> <line-numbers> <textarea style="width: 100%; height: 6em;"># Hello {{ subject }} line another line this is getting longer this is getting longer</textarea> </line-numbers> <h3>&lt;textarea&gt; with both overflow</h3> <line-numbers> <textarea style="width: 100%; height: 6em;"># Hello {{ subject }} line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line another line this is getting longer this is getting longer</textarea> </line-numbers> <h3>&lt;textarea&gt; with both overflow (obtrusive)</h3> <line-numbers obtrusive> <textarea style="width: 100%; height: 6em;"># Hello {{ subject }} line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line super long line another line this is getting longer this is getting longer</textarea> </line-numbers> <h2>Upgrade unwrapped elements</h2> <script type="module"> let btn = document.getElementById("upgrade-content"); btn.addEventListener("click", () => { const LineNumbers = customElements.get("line-numbers"); for(let el of document.body.querySelectorAll("pre, textarea")) { // ignores elements inside <line-numbers> already LineNumbers.upgrade(el); } }); </script> <form> <button type="button" id="upgrade-content">Upgrade</button> </form> <pre style="height: 6em;"># Hello {{ subject }} line another line this is getting longer this is getting longer</pre> <br> <textarea style="width: 100%; height: 6em;"># Hello {{ subject }} line another line this is getting longer this is getting longer</textarea> </body> </html>
zachleat/line-numbers
161
A web component to add line numbers next to various HTML elements
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
line-numbers.js
JavaScript
//! <line-numbers> const css = String.raw; function getObtrusiveScrollbarSize() { let [w, h] = [40, 40]; let d = document; let parent = d.createElement("div"); parent.setAttribute("style", `width:${w}px;height:${h}px;overflow:auto;`); let child = d.createElement("div"); child.setAttribute("style", `width:${w+10}px;height:${h+10}px;`); parent.appendChild(child); d.body.appendChild(parent); let dims = [w - parent.clientWidth, h - parent.clientHeight]; parent.remove(); return dims; } class Numbers extends HTMLElement { #positionPause = false; #target; #scrollTarget; static attrs = { targetSelector: "target", scrollTargetSelector: "scroll-target", startIndex: "start", obtrusive: "obtrusive", manualRender: "manual-render", } static classes = { target: "uln-target", } static tagName = "line-numbers"; static define(registry = window.customElements) { if(!registry.get(this.tagName)) { registry.define(this.tagName, this); } } static upgrade(node) { if(!node || node.closest(this.tagName)) { return; } let h = document.createElement("div"); node.parentNode.insertBefore(h, node); let c = document.createElement(this.tagName); c.appendChild(node); h.replaceWith(c); } static getStyle() { return css` ${this.tagName} > :first-child { display: block; max-width: 100%; } ${this.tagName} .${this.classes.target} { margin: 0; /* Warning: does not handle wrapping long lines */ white-space: nowrap; white-space-collapse: preserve; } ${this.tagName} pre.${this.classes.target} { /* Warning: does not handle wrapping long lines */ white-space: pre; } `; } static globalStyleAdded = false; static getShadowStyle() { return css` * { box-sizing: border-box; } :host { display: flex; position: relative; } .lines { position: absolute; left: 0; top: calc(-1 * var(--uln-top, 0px)); height: 100%; translate: -100% 0; clip-path: inset(var(--uln-top) 0 calc(-1 * var(--uln-top, 0px) + var(--uln-scrollbar-height, 0px)) 0); pointer-events: none; border-radius: var(--uln-border-radius); font: var(--uln-font, inherit); color: var(--uln-color); padding-block: var(--uln-padding-v, 0px); padding-inline: var(--uln-padding-h, .75em); margin: 0; line-height: var(--uln-lh, 1lh); list-style: none; list-style-position: inside; counter-reset: decimal-without-dot var(--uln-number-start, 0); font-variant-numeric: tabular-nums; } :host([obtrusive]) .lines { position: relative; height: var(--uln-height, auto); translate: 0; } .lines li { text-align: right; counter-increment: decimal-without-dot; } .lines li:before { content: counter(decimal-without-dot, var(--uln-number-type, decimal)); } `; } get targetEl() { if(!this.#target) { let targetSelector = this.getAttribute(Numbers.attrs.targetSelector); let target = this.querySelector(targetSelector || ":scope > :first-child"); target.classList.add(Numbers.classes.target); this.#target = target; } return this.#target; } get scrollTargetEl() { if(!this.#scrollTarget) { let scrollTargetSelector = this.getAttribute(Numbers.attrs.scrollTargetSelector); if(scrollTargetSelector) { this.#scrollTarget = this.querySelector(scrollTargetSelector); } } return this.#scrollTarget || this.targetEl; } get linesEl() { return this.shadowRoot.querySelector(".lines") } static isTextarea(el) { return el.tagName === "TEXTAREA"; } static shouldWatchInput(el) { return this.isTextarea(el); // || el.isContentEditable; } getSourceContent() { if(Numbers.isTextarea(this.targetEl)) { return this.targetEl.value; } return this.targetEl.innerText; } setupLines() { let lines = this.getSourceContent().split("\n"); if(this.linesEl.childElementCount !== lines.length) { this.linesEl.innerHTML = lines.map(noop => "<li></li>").join(""); } } positionLines(opts = {}) { let { force, updateScrollbarHeight, overflowType } = Object.assign({ force: false, updateScrollbarHeight: false, }, opts); if(this.#positionPause && !force) { return; } let top = Math.max(this.scrollTargetEl.scrollTop, 0); this.linesEl.style.setProperty("--uln-top", top + "px"); // only required for obtrusive let height = this.scrollTargetEl.offsetHeight; if(height || updateScrollbarHeight) { if(!overflowType) { overflowType = this.getOverflowType(); } } if(height) { if(overflowType) { // TODO start here, disallow vertical overflow type here this.linesEl.style.setProperty("--uln-height", height + "px"); } else { this.linesEl.style.removeProperty("--uln-height"); } } if(updateScrollbarHeight) { if(overflowType === "horizontal" || overflowType === "both") { this.style.setProperty("--uln-scrollbar-height", Numbers.scrollbarDimensions[1] + "px"); } else { this.style.removeProperty("--uln-scrollbar-height"); } } } isObtrusive() { return this.hasAttribute(Numbers.attrs.obtrusive); } getOverflowType() { let target = this.scrollTargetEl; let isObtrusive = this.isObtrusive(); if(isObtrusive) { this.linesEl.style.display = "none"; } let isHorizontal = target?.scrollWidth > this.offsetWidth; let isVertical = target?.scrollHeight > this.offsetHeight; if(isObtrusive) { this.linesEl.style.display = ""; } if(isHorizontal && isVertical) { return "both"; } if(isHorizontal) { return "horizontal"; } if(isVertical) { return "vertical"; } } async connectedCallback() { if (!("replaceSync" in CSSStyleSheet.prototype) || this.shadowRoot) { return; } if(!Numbers.scrollbarDimensions) { Numbers.scrollbarDimensions = getObtrusiveScrollbarSize(); } if(!Numbers.globalStyleAdded) { Numbers.globalStyleAdded = true; let sheet = new CSSStyleSheet(); sheet.replaceSync(Numbers.getStyle()); document.adoptedStyleSheets.push(sheet); } let shadowroot = this.attachShadow({ mode: "open" }); let shadowSheet = new CSSStyleSheet(); shadowSheet.replaceSync(Numbers.getShadowStyle()); shadowroot.adoptedStyleSheets = [shadowSheet]; let template = document.createElement("template"); template.innerHTML = `<ol class="lines" aria-hidden="true"></ol><slot></slot>`; shadowroot.appendChild(template.content.cloneNode(true)); let startIndex = parseInt(this.getAttribute(Numbers.attrs.startIndex), 10); if(!isNaN(startIndex)) { this.linesEl.style.setProperty("--uln-number-start", startIndex - 1); } this.setupLines(); let overflowType = this.getOverflowType(); // Obtrusive type pretends not to have overflow due to height of numbers during init if(this.isObtrusive() || overflowType) { this.positionLines({ updateScrollbarHeight: true, overflowType, }); } if(Numbers.shouldWatchInput(this.targetEl) && !this.hasAttribute(Numbers.attrs.manualRender)) { this.targetEl.addEventListener("input", async () => { this.#positionPause = true; this.setupLines(); this.positionLines({ force: true, updateScrollbarHeight: true }); this.#positionPause = false; }) } this.scrollTargetEl.addEventListener("scroll", () => { this.positionLines(); }, { passive: true }); } render() { this.setupLines(); this.positionLines({ force: true, updateScrollbarHeight: true }); } } if(!(new URL(import.meta.url)).searchParams.has("nodefine")) { Numbers.define(); }
zachleat/line-numbers
161
A web component to add line numbers next to various HTML elements
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
index.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <title>pagefind-search Web Component</title> <link rel="stylesheet" href="./pagefind/pagefind-ui.css"> <script type="module" src="pagefind-search.js"></script> </head> <body> <header> <h1>pagefind-search Web Component</h1> </header> <main> <p><a href="https://github.com/zachleat/pagefind-search">Source code on GitHub</a>.</p> <p>Before content.</p> <pagefind-search _bundle_path="./pagefind/" _page_size="10" pagefind-autofocus> <form action="https://duckduckgo.com/" method="get" style="min-height: 3.2em;"> <label> Search for: <input type="search" name="q" autocomplete="off" autofocus> </label> <input type="hidden" name="sites" value="www.zachleat.com"> <button type="submit">Search</button> </form> </pagefind-search> <p>Inbetween content.</p> <style> /* Reduce CLS */ pagefind-search:not(:defined) { display: block; min-height: 3.2em; } </style> <!-- Set constructor options as attributes --> <pagefind-search _show_images="false" _bundle_path="./pagefind/"></pagefind-search> <p>Inbetween content.</p> <!-- Manual initialization (full JS control) --> <pagefind-search manual id="my-search" _bundle_path="./pagefind/"></pagefind-search> <script type="module"> // import "./pagefind-search.js"; let el = document.querySelector("#my-search"); await el.pagefind({ showImages: false, debounceTimeoutMs: 100, }); console.log( el.pagefindUI ); </script> <p>After content.</p> </main> </body> </html>
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
pagefind-search.js
JavaScript
class PagefindSearch extends HTMLElement { static register(tagName = "pagefind-search", registry) { if ("customElements" in window) { (registry || customElements).define(tagName, this); } } static attrs = { bundlePath: "_bundle_path", manualInit: "manual", autofocus: "pagefind-autofocus", }; static count = 0; get bundlePath() { let dir = this.getAttribute(PagefindSearch.attrs.bundlePath); return dir || "/pagefind/"; } get id() { // prefer existing id attribute if(this.hasAttribute("id")) { return this.getAttribute("id"); } return "_pagefind_search_" + this.count; } static underscoreToCamelCase(str) { return str.replace(/_([a-z])/g, (m) => { return m[1].toUpperCase(); }); } get options() { let o = { element: `#${this.id}`, }; let prefix = "_"; for(let {name, value} of this.attributes) { if(name.startsWith(prefix)) { if(name === PagefindSearch.attrs.bundlePath) { // if bundle path is relative, we need to make it absolute to pass in to Pagefind (GitHub pages fix) let u = new URL(value, location); value = u.pathname; } if(value === "false" || value === "true" || Number(value).toString() === value) { value = JSON.parse(value); } o[PagefindSearch.underscoreToCamelCase(name.slice(prefix.length))] = value; } } return o; } async pagefind(customOptions) { if(typeof PagefindUI == "undefined") { if(!this.scriptPromise) { throw new Error(`<${this.tagName.toLowerCase()}> is not yet attached to a document.`); } await this.scriptPromise; } let options = Object.assign({}, this.options, customOptions); this.pagefindUI = new PagefindUI(options); let input = this.querySelector(`input:is([type="text"], [type="search"])`); if(this.hasAttribute(PagefindSearch.attrs.autofocus)) { input?.focus(); } } async connectedCallback() { if(this.hasAttached) { return; } this.hasAttached = true; this.count = PagefindSearch.count++; this.setAttribute("id", this.id); // clear out fallback content this.replaceChildren(); // we load these in every instance but the browser de-dupes requests for us let stylesheetUrl = `${this.bundlePath}pagefind-ui.css`; let link = document.createElement("link"); link.rel = "stylesheet"; link.href = stylesheetUrl; this.appendChild(link); let scriptUrl = `${this.bundlePath}pagefind-ui.js`; this.scriptPromise = import(scriptUrl); if(!this.hasAttribute(PagefindSearch.attrs.manualInit)) { await this.scriptPromise; await this.pagefind(); } } } PagefindSearch.register();
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
pagefind/pagefind-highlight.js
JavaScript
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // node_modules/mark.js/dist/mark.js var require_mark = __commonJS({ "node_modules/mark.js/dist/mark.js"(exports, module) { (function(global, factory) { typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global.Mark = factory(); })(exports, function() { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) { return typeof obj; } : function(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var DOMIterator = function() { function DOMIterator2(ctx) { var iframes = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true; var exclude = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : []; var iframesTimeout = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 5e3; classCallCheck(this, DOMIterator2); this.ctx = ctx; this.iframes = iframes; this.exclude = exclude; this.iframesTimeout = iframesTimeout; } createClass(DOMIterator2, [{ key: "getContexts", value: function getContexts() { var ctx = void 0, filteredCtx = []; if (typeof this.ctx === "undefined" || !this.ctx) { ctx = []; } else if (NodeList.prototype.isPrototypeOf(this.ctx)) { ctx = Array.prototype.slice.call(this.ctx); } else if (Array.isArray(this.ctx)) { ctx = this.ctx; } else if (typeof this.ctx === "string") { ctx = Array.prototype.slice.call(document.querySelectorAll(this.ctx)); } else { ctx = [this.ctx]; } ctx.forEach(function(ctx2) { var isDescendant = filteredCtx.filter(function(contexts) { return contexts.contains(ctx2); }).length > 0; if (filteredCtx.indexOf(ctx2) === -1 && !isDescendant) { filteredCtx.push(ctx2); } }); return filteredCtx; } }, { key: "getIframeContents", value: function getIframeContents(ifr, successFn) { var errorFn = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : function() { }; var doc = void 0; try { var ifrWin = ifr.contentWindow; doc = ifrWin.document; if (!ifrWin || !doc) { throw new Error("iframe inaccessible"); } } catch (e) { errorFn(); } if (doc) { successFn(doc); } } }, { key: "isIframeBlank", value: function isIframeBlank(ifr) { var bl = "about:blank", src = ifr.getAttribute("src").trim(), href = ifr.contentWindow.location.href; return href === bl && src !== bl && src; } }, { key: "observeIframeLoad", value: function observeIframeLoad(ifr, successFn, errorFn) { var _this = this; var called = false, tout = null; var listener = function listener2() { if (called) { return; } called = true; clearTimeout(tout); try { if (!_this.isIframeBlank(ifr)) { ifr.removeEventListener("load", listener2); _this.getIframeContents(ifr, successFn, errorFn); } } catch (e) { errorFn(); } }; ifr.addEventListener("load", listener); tout = setTimeout(listener, this.iframesTimeout); } }, { key: "onIframeReady", value: function onIframeReady(ifr, successFn, errorFn) { try { if (ifr.contentWindow.document.readyState === "complete") { if (this.isIframeBlank(ifr)) { this.observeIframeLoad(ifr, successFn, errorFn); } else { this.getIframeContents(ifr, successFn, errorFn); } } else { this.observeIframeLoad(ifr, successFn, errorFn); } } catch (e) { errorFn(); } } }, { key: "waitForIframes", value: function waitForIframes(ctx, done) { var _this2 = this; var eachCalled = 0; this.forEachIframe(ctx, function() { return true; }, function(ifr) { eachCalled++; _this2.waitForIframes(ifr.querySelector("html"), function() { if (!--eachCalled) { done(); } }); }, function(handled) { if (!handled) { done(); } }); } }, { key: "forEachIframe", value: function forEachIframe(ctx, filter, each) { var _this3 = this; var end = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : function() { }; var ifr = ctx.querySelectorAll("iframe"), open = ifr.length, handled = 0; ifr = Array.prototype.slice.call(ifr); var checkEnd = function checkEnd2() { if (--open <= 0) { end(handled); } }; if (!open) { checkEnd(); } ifr.forEach(function(ifr2) { if (DOMIterator2.matches(ifr2, _this3.exclude)) { checkEnd(); } else { _this3.onIframeReady(ifr2, function(con) { if (filter(ifr2)) { handled++; each(con); } checkEnd(); }, checkEnd); } }); } }, { key: "createIterator", value: function createIterator(ctx, whatToShow, filter) { return document.createNodeIterator(ctx, whatToShow, filter, false); } }, { key: "createInstanceOnIframe", value: function createInstanceOnIframe(contents) { return new DOMIterator2(contents.querySelector("html"), this.iframes); } }, { key: "compareNodeIframe", value: function compareNodeIframe(node, prevNode, ifr) { var compCurr = node.compareDocumentPosition(ifr), prev = Node.DOCUMENT_POSITION_PRECEDING; if (compCurr & prev) { if (prevNode !== null) { var compPrev = prevNode.compareDocumentPosition(ifr), after = Node.DOCUMENT_POSITION_FOLLOWING; if (compPrev & after) { return true; } } else { return true; } } return false; } }, { key: "getIteratorNode", value: function getIteratorNode(itr) { var prevNode = itr.previousNode(); var node = void 0; if (prevNode === null) { node = itr.nextNode(); } else { node = itr.nextNode() && itr.nextNode(); } return { prevNode, node }; } }, { key: "checkIframeFilter", value: function checkIframeFilter(node, prevNode, currIfr, ifr) { var key = false, handled = false; ifr.forEach(function(ifrDict, i) { if (ifrDict.val === currIfr) { key = i; handled = ifrDict.handled; } }); if (this.compareNodeIframe(node, prevNode, currIfr)) { if (key === false && !handled) { ifr.push({ val: currIfr, handled: true }); } else if (key !== false && !handled) { ifr[key].handled = true; } return true; } if (key === false) { ifr.push({ val: currIfr, handled: false }); } return false; } }, { key: "handleOpenIframes", value: function handleOpenIframes(ifr, whatToShow, eCb, fCb) { var _this4 = this; ifr.forEach(function(ifrDict) { if (!ifrDict.handled) { _this4.getIframeContents(ifrDict.val, function(con) { _this4.createInstanceOnIframe(con).forEachNode(whatToShow, eCb, fCb); }); } }); } }, { key: "iterateThroughNodes", value: function iterateThroughNodes(whatToShow, ctx, eachCb, filterCb, doneCb) { var _this5 = this; var itr = this.createIterator(ctx, whatToShow, filterCb); var ifr = [], elements = [], node = void 0, prevNode = void 0, retrieveNodes = function retrieveNodes2() { var _getIteratorNode = _this5.getIteratorNode(itr); prevNode = _getIteratorNode.prevNode; node = _getIteratorNode.node; return node; }; while (retrieveNodes()) { if (this.iframes) { this.forEachIframe(ctx, function(currIfr) { return _this5.checkIframeFilter(node, prevNode, currIfr, ifr); }, function(con) { _this5.createInstanceOnIframe(con).forEachNode(whatToShow, function(ifrNode) { return elements.push(ifrNode); }, filterCb); }); } elements.push(node); } elements.forEach(function(node2) { eachCb(node2); }); if (this.iframes) { this.handleOpenIframes(ifr, whatToShow, eachCb, filterCb); } doneCb(); } }, { key: "forEachNode", value: function forEachNode(whatToShow, each, filter) { var _this6 = this; var done = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : function() { }; var contexts = this.getContexts(); var open = contexts.length; if (!open) { done(); } contexts.forEach(function(ctx) { var ready = function ready2() { _this6.iterateThroughNodes(whatToShow, ctx, each, filter, function() { if (--open <= 0) { done(); } }); }; if (_this6.iframes) { _this6.waitForIframes(ctx, ready); } else { ready(); } }); } }], [{ key: "matches", value: function matches(element, selector) { var selectors = typeof selector === "string" ? [selector] : selector, fn = element.matches || element.matchesSelector || element.msMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.webkitMatchesSelector; if (fn) { var match = false; selectors.every(function(sel) { if (fn.call(element, sel)) { match = true; return false; } return true; }); return match; } else { return false; } } }]); return DOMIterator2; }(); var Mark$1 = function() { function Mark3(ctx) { classCallCheck(this, Mark3); this.ctx = ctx; this.ie = false; var ua = window.navigator.userAgent; if (ua.indexOf("MSIE") > -1 || ua.indexOf("Trident") > -1) { this.ie = true; } } createClass(Mark3, [{ key: "log", value: function log(msg) { var level = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "debug"; var log2 = this.opt.log; if (!this.opt.debug) { return; } if ((typeof log2 === "undefined" ? "undefined" : _typeof(log2)) === "object" && typeof log2[level] === "function") { log2[level]("mark.js: " + msg); } } }, { key: "escapeStr", value: function escapeStr(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } }, { key: "createRegExp", value: function createRegExp(str) { if (this.opt.wildcards !== "disabled") { str = this.setupWildcardsRegExp(str); } str = this.escapeStr(str); if (Object.keys(this.opt.synonyms).length) { str = this.createSynonymsRegExp(str); } if (this.opt.ignoreJoiners || this.opt.ignorePunctuation.length) { str = this.setupIgnoreJoinersRegExp(str); } if (this.opt.diacritics) { str = this.createDiacriticsRegExp(str); } str = this.createMergedBlanksRegExp(str); if (this.opt.ignoreJoiners || this.opt.ignorePunctuation.length) { str = this.createJoinersRegExp(str); } if (this.opt.wildcards !== "disabled") { str = this.createWildcardsRegExp(str); } str = this.createAccuracyRegExp(str); return str; } }, { key: "createSynonymsRegExp", value: function createSynonymsRegExp(str) { var syn = this.opt.synonyms, sens = this.opt.caseSensitive ? "" : "i", joinerPlaceholder = this.opt.ignoreJoiners || this.opt.ignorePunctuation.length ? "\0" : ""; for (var index in syn) { if (syn.hasOwnProperty(index)) { var value = syn[index], k1 = this.opt.wildcards !== "disabled" ? this.setupWildcardsRegExp(index) : this.escapeStr(index), k2 = this.opt.wildcards !== "disabled" ? this.setupWildcardsRegExp(value) : this.escapeStr(value); if (k1 !== "" && k2 !== "") { str = str.replace(new RegExp("(" + this.escapeStr(k1) + "|" + this.escapeStr(k2) + ")", "gm" + sens), joinerPlaceholder + ("(" + this.processSynomyms(k1) + "|") + (this.processSynomyms(k2) + ")") + joinerPlaceholder); } } } return str; } }, { key: "processSynomyms", value: function processSynomyms(str) { if (this.opt.ignoreJoiners || this.opt.ignorePunctuation.length) { str = this.setupIgnoreJoinersRegExp(str); } return str; } }, { key: "setupWildcardsRegExp", value: function setupWildcardsRegExp(str) { str = str.replace(/(?:\\)*\?/g, function(val) { return val.charAt(0) === "\\" ? "?" : ""; }); return str.replace(/(?:\\)*\*/g, function(val) { return val.charAt(0) === "\\" ? "*" : ""; }); } }, { key: "createWildcardsRegExp", value: function createWildcardsRegExp(str) { var spaces = this.opt.wildcards === "withSpaces"; return str.replace(/\u0001/g, spaces ? "[\\S\\s]?" : "\\S?").replace(/\u0002/g, spaces ? "[\\S\\s]*?" : "\\S*"); } }, { key: "setupIgnoreJoinersRegExp", value: function setupIgnoreJoinersRegExp(str) { return str.replace(/[^(|)\\]/g, function(val, indx, original) { var nextChar = original.charAt(indx + 1); if (/[(|)\\]/.test(nextChar) || nextChar === "") { return val; } else { return val + "\0"; } }); } }, { key: "createJoinersRegExp", value: function createJoinersRegExp(str) { var joiner = []; var ignorePunctuation = this.opt.ignorePunctuation; if (Array.isArray(ignorePunctuation) && ignorePunctuation.length) { joiner.push(this.escapeStr(ignorePunctuation.join(""))); } if (this.opt.ignoreJoiners) { joiner.push("\\u00ad\\u200b\\u200c\\u200d"); } return joiner.length ? str.split(/\u0000+/).join("[" + joiner.join("") + "]*") : str; } }, { key: "createDiacriticsRegExp", value: function createDiacriticsRegExp(str) { var sens = this.opt.caseSensitive ? "" : "i", dct = this.opt.caseSensitive ? ["a\xE0\xE1\u1EA3\xE3\u1EA1\u0103\u1EB1\u1EAF\u1EB3\u1EB5\u1EB7\xE2\u1EA7\u1EA5\u1EA9\u1EAB\u1EAD\xE4\xE5\u0101\u0105", "A\xC0\xC1\u1EA2\xC3\u1EA0\u0102\u1EB0\u1EAE\u1EB2\u1EB4\u1EB6\xC2\u1EA6\u1EA4\u1EA8\u1EAA\u1EAC\xC4\xC5\u0100\u0104", "c\xE7\u0107\u010D", "C\xC7\u0106\u010C", "d\u0111\u010F", "D\u0110\u010E", "e\xE8\xE9\u1EBB\u1EBD\u1EB9\xEA\u1EC1\u1EBF\u1EC3\u1EC5\u1EC7\xEB\u011B\u0113\u0119", "E\xC8\xC9\u1EBA\u1EBC\u1EB8\xCA\u1EC0\u1EBE\u1EC2\u1EC4\u1EC6\xCB\u011A\u0112\u0118", "i\xEC\xED\u1EC9\u0129\u1ECB\xEE\xEF\u012B", "I\xCC\xCD\u1EC8\u0128\u1ECA\xCE\xCF\u012A", "l\u0142", "L\u0141", "n\xF1\u0148\u0144", "N\xD1\u0147\u0143", "o\xF2\xF3\u1ECF\xF5\u1ECD\xF4\u1ED3\u1ED1\u1ED5\u1ED7\u1ED9\u01A1\u1EDF\u1EE1\u1EDB\u1EDD\u1EE3\xF6\xF8\u014D", "O\xD2\xD3\u1ECE\xD5\u1ECC\xD4\u1ED2\u1ED0\u1ED4\u1ED6\u1ED8\u01A0\u1EDE\u1EE0\u1EDA\u1EDC\u1EE2\xD6\xD8\u014C", "r\u0159", "R\u0158", "s\u0161\u015B\u0219\u015F", "S\u0160\u015A\u0218\u015E", "t\u0165\u021B\u0163", "T\u0164\u021A\u0162", "u\xF9\xFA\u1EE7\u0169\u1EE5\u01B0\u1EEB\u1EE9\u1EED\u1EEF\u1EF1\xFB\xFC\u016F\u016B", "U\xD9\xDA\u1EE6\u0168\u1EE4\u01AF\u1EEA\u1EE8\u1EEC\u1EEE\u1EF0\xDB\xDC\u016E\u016A", "y\xFD\u1EF3\u1EF7\u1EF9\u1EF5\xFF", "Y\xDD\u1EF2\u1EF6\u1EF8\u1EF4\u0178", "z\u017E\u017C\u017A", "Z\u017D\u017B\u0179"] : ["a\xE0\xE1\u1EA3\xE3\u1EA1\u0103\u1EB1\u1EAF\u1EB3\u1EB5\u1EB7\xE2\u1EA7\u1EA5\u1EA9\u1EAB\u1EAD\xE4\xE5\u0101\u0105A\xC0\xC1\u1EA2\xC3\u1EA0\u0102\u1EB0\u1EAE\u1EB2\u1EB4\u1EB6\xC2\u1EA6\u1EA4\u1EA8\u1EAA\u1EAC\xC4\xC5\u0100\u0104", "c\xE7\u0107\u010DC\xC7\u0106\u010C", "d\u0111\u010FD\u0110\u010E", "e\xE8\xE9\u1EBB\u1EBD\u1EB9\xEA\u1EC1\u1EBF\u1EC3\u1EC5\u1EC7\xEB\u011B\u0113\u0119E\xC8\xC9\u1EBA\u1EBC\u1EB8\xCA\u1EC0\u1EBE\u1EC2\u1EC4\u1EC6\xCB\u011A\u0112\u0118", "i\xEC\xED\u1EC9\u0129\u1ECB\xEE\xEF\u012BI\xCC\xCD\u1EC8\u0128\u1ECA\xCE\xCF\u012A", "l\u0142L\u0141", "n\xF1\u0148\u0144N\xD1\u0147\u0143", "o\xF2\xF3\u1ECF\xF5\u1ECD\xF4\u1ED3\u1ED1\u1ED5\u1ED7\u1ED9\u01A1\u1EDF\u1EE1\u1EDB\u1EDD\u1EE3\xF6\xF8\u014DO\xD2\xD3\u1ECE\xD5\u1ECC\xD4\u1ED2\u1ED0\u1ED4\u1ED6\u1ED8\u01A0\u1EDE\u1EE0\u1EDA\u1EDC\u1EE2\xD6\xD8\u014C", "r\u0159R\u0158", "s\u0161\u015B\u0219\u015FS\u0160\u015A\u0218\u015E", "t\u0165\u021B\u0163T\u0164\u021A\u0162", "u\xF9\xFA\u1EE7\u0169\u1EE5\u01B0\u1EEB\u1EE9\u1EED\u1EEF\u1EF1\xFB\xFC\u016F\u016BU\xD9\xDA\u1EE6\u0168\u1EE4\u01AF\u1EEA\u1EE8\u1EEC\u1EEE\u1EF0\xDB\xDC\u016E\u016A", "y\xFD\u1EF3\u1EF7\u1EF9\u1EF5\xFFY\xDD\u1EF2\u1EF6\u1EF8\u1EF4\u0178", "z\u017E\u017C\u017AZ\u017D\u017B\u0179"]; var handled = []; str.split("").forEach(function(ch) { dct.every(function(dct2) { if (dct2.indexOf(ch) !== -1) { if (handled.indexOf(dct2) > -1) { return false; } str = str.replace(new RegExp("[" + dct2 + "]", "gm" + sens), "[" + dct2 + "]"); handled.push(dct2); } return true; }); }); return str; } }, { key: "createMergedBlanksRegExp", value: function createMergedBlanksRegExp(str) { return str.replace(/[\s]+/gmi, "[\\s]+"); } }, { key: "createAccuracyRegExp", value: function createAccuracyRegExp(str) { var _this = this; var chars = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\xA1\xBF"; var acc = this.opt.accuracy, val = typeof acc === "string" ? acc : acc.value, ls = typeof acc === "string" ? [] : acc.limiters, lsJoin = ""; ls.forEach(function(limiter) { lsJoin += "|" + _this.escapeStr(limiter); }); switch (val) { case "partially": default: return "()(" + str + ")"; case "complementary": lsJoin = "\\s" + (lsJoin ? lsJoin : this.escapeStr(chars)); return "()([^" + lsJoin + "]*" + str + "[^" + lsJoin + "]*)"; case "exactly": return "(^|\\s" + lsJoin + ")(" + str + ")(?=$|\\s" + lsJoin + ")"; } } }, { key: "getSeparatedKeywords", value: function getSeparatedKeywords(sv) { var _this2 = this; var stack = []; sv.forEach(function(kw) { if (!_this2.opt.separateWordSearch) { if (kw.trim() && stack.indexOf(kw) === -1) { stack.push(kw); } } else { kw.split(" ").forEach(function(kwSplitted) { if (kwSplitted.trim() && stack.indexOf(kwSplitted) === -1) { stack.push(kwSplitted); } }); } }); return { "keywords": stack.sort(function(a, b) { return b.length - a.length; }), "length": stack.length }; } }, { key: "isNumeric", value: function isNumeric(value) { return Number(parseFloat(value)) == value; } }, { key: "checkRanges", value: function checkRanges(array) { var _this3 = this; if (!Array.isArray(array) || Object.prototype.toString.call(array[0]) !== "[object Object]") { this.log("markRanges() will only accept an array of objects"); this.opt.noMatch(array); return []; } var stack = []; var last = 0; array.sort(function(a, b) { return a.start - b.start; }).forEach(function(item) { var _callNoMatchOnInvalid = _this3.callNoMatchOnInvalidRanges(item, last), start = _callNoMatchOnInvalid.start, end = _callNoMatchOnInvalid.end, valid = _callNoMatchOnInvalid.valid; if (valid) { item.start = start; item.length = end - start; stack.push(item); last = end; } }); return stack; } }, { key: "callNoMatchOnInvalidRanges", value: function callNoMatchOnInvalidRanges(range, last) { var start = void 0, end = void 0, valid = false; if (range && typeof range.start !== "undefined") { start = parseInt(range.start, 10); end = start + parseInt(range.length, 10); if (this.isNumeric(range.start) && this.isNumeric(range.length) && end - last > 0 && end - start > 0) { valid = true; } else { this.log("Ignoring invalid or overlapping range: " + ("" + JSON.stringify(range))); this.opt.noMatch(range); } } else { this.log("Ignoring invalid range: " + JSON.stringify(range)); this.opt.noMatch(range); } return { start, end, valid }; } }, { key: "checkWhitespaceRanges", value: function checkWhitespaceRanges(range, originalLength, string) { var end = void 0, valid = true, max = string.length, offset = originalLength - max, start = parseInt(range.start, 10) - offset; start = start > max ? max : start; end = start + parseInt(range.length, 10); if (end > max) { end = max; this.log("End range automatically set to the max value of " + max); } if (start < 0 || end - start < 0 || start > max || end > max) { valid = false; this.log("Invalid range: " + JSON.stringify(range)); this.opt.noMatch(range); } else if (string.substring(start, end).replace(/\s+/g, "") === "") { valid = false; this.log("Skipping whitespace only range: " + JSON.stringify(range)); this.opt.noMatch(range); } return { start, end, valid }; } }, { key: "getTextNodes", value: function getTextNodes(cb) { var _this4 = this; var val = "", nodes = []; this.iterator.forEachNode(NodeFilter.SHOW_TEXT, function(node) { nodes.push({ start: val.length, end: (val += node.textContent).length, node }); }, function(node) { if (_this4.matchesExclude(node.parentNode)) { return NodeFilter.FILTER_REJECT; } else { return NodeFilter.FILTER_ACCEPT; } }, function() { cb({ value: val, nodes }); }); } }, { key: "matchesExclude", value: function matchesExclude(el) { return DOMIterator.matches(el, this.opt.exclude.concat(["script", "style", "title", "head", "html"])); } }, { key: "wrapRangeInTextNode", value: function wrapRangeInTextNode(node, start, end) { var hEl = !this.opt.element ? "mark" : this.opt.element, startNode = node.splitText(start), ret = startNode.splitText(end - start); var repl = document.createElement(hEl); repl.setAttribute("data-markjs", "true"); if (this.opt.className) { repl.setAttribute("class", this.opt.className); } repl.textContent = startNode.textContent; startNode.parentNode.replaceChild(repl, startNode); return ret; } }, { key: "wrapRangeInMappedTextNode", value: function wrapRangeInMappedTextNode(dict, start, end, filterCb, eachCb) { var _this5 = this; dict.nodes.every(function(n, i) { var sibl = dict.nodes[i + 1]; if (typeof sibl === "undefined" || sibl.start > start) { if (!filterCb(n.node)) { return false; } var s = start - n.start, e = (end > n.end ? n.end : end) - n.start, startStr = dict.value.substr(0, n.start), endStr = dict.value.substr(e + n.start); n.node = _this5.wrapRangeInTextNode(n.node, s, e); dict.value = startStr + endStr; dict.nodes.forEach(function(k, j) { if (j >= i) { if (dict.nodes[j].start > 0 && j !== i) { dict.nodes[j].start -= e; } dict.nodes[j].end -= e; } }); end -= e; eachCb(n.node.previousSibling, n.start); if (end > n.end) { start = n.end; } else { return false; } } return true; }); } }, { key: "wrapMatches", value: function wrapMatches(regex, ignoreGroups, filterCb, eachCb, endCb) { var _this6 = this; var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1; this.getTextNodes(function(dict) { dict.nodes.forEach(function(node) { node = node.node; var match = void 0; while ((match = regex.exec(node.textContent)) !== null && match[matchIdx] !== "") { if (!filterCb(match[matchIdx], node)) { continue; } var pos = match.index; if (matchIdx !== 0) { for (var i = 1; i < matchIdx; i++) { pos += match[i].length; } } node = _this6.wrapRangeInTextNode(node, pos, pos + match[matchIdx].length); eachCb(node.previousSibling); regex.lastIndex = 0; } }); endCb(); }); } }, { key: "wrapMatchesAcrossElements", value: function wrapMatchesAcrossElements(regex, ignoreGroups, filterCb, eachCb, endCb) { var _this7 = this; var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1; this.getTextNodes(function(dict) { var match = void 0; while ((match = regex.exec(dict.value)) !== null && match[matchIdx] !== "") { var start = match.index; if (matchIdx !== 0) { for (var i = 1; i < matchIdx; i++) { start += match[i].length; } } var end = start + match[matchIdx].length; _this7.wrapRangeInMappedTextNode(dict, start, end, function(node) { return filterCb(match[matchIdx], node); }, function(node, lastIndex) { regex.lastIndex = lastIndex; eachCb(node); }); } endCb(); }); } }, { key: "wrapRangeFromIndex", value: function wrapRangeFromIndex(ranges, filterCb, eachCb, endCb) { var _this8 = this; this.getTextNodes(function(dict) { var originalLength = dict.value.length; ranges.forEach(function(range, counter) { var _checkWhitespaceRange = _this8.checkWhitespaceRanges(range, originalLength, dict.value), start = _checkWhitespaceRange.start, end = _checkWhitespaceRange.end, valid = _checkWhitespaceRange.valid; if (valid) { _this8.wrapRangeInMappedTextNode(dict, start, end, function(node) { return filterCb(node, range, dict.value.substring(start, end), counter); }, function(node) { eachCb(node, range); }); } }); endCb(); }); } }, { key: "unwrapMatches", value: function unwrapMatches(node) { var parent = node.parentNode; var docFrag = document.createDocumentFragment(); while (node.firstChild) { docFrag.appendChild(node.removeChild(node.firstChild)); } parent.replaceChild(docFrag, node); if (!this.ie) { parent.normalize(); } else { this.normalizeTextNode(parent); } } }, { key: "normalizeTextNode", value: function normalizeTextNode(node) { if (!node) { return; } if (node.nodeType === 3) { while (node.nextSibling && node.nextSibling.nodeType === 3) { node.nodeValue += node.nextSibling.nodeValue; node.parentNode.removeChild(node.nextSibling); } } else { this.normalizeTextNode(node.firstChild); } this.normalizeTextNode(node.nextSibling); } }, { key: "markRegExp", value: function markRegExp(regexp, opt) { var _this9 = this; this.opt = opt; this.log('Searching with expression "' + regexp + '"'); var totalMatches = 0, fn = "wrapMatches"; var eachCb = function eachCb2(element) { totalMatches++; _this9.opt.each(element); }; if (this.opt.acrossElements) { fn = "wrapMatchesAcrossElements"; } this[fn](regexp, this.opt.ignoreGroups, function(match, node) { return _this9.opt.filter(node, match, totalMatches); }, eachCb, function() { if (totalMatches === 0) { _this9.opt.noMatch(regexp); } _this9.opt.done(totalMatches); }); } }, { key: "mark", value: function mark(sv, opt) { var _this10 = this; this.opt = opt; var totalMatches = 0, fn = "wrapMatches"; var _getSeparatedKeywords = this.getSeparatedKeywords(typeof sv === "string" ? [sv] : sv), kwArr = _getSeparatedKeywords.keywords, kwArrLen = _getSeparatedKeywords.length, sens = this.opt.caseSensitive ? "" : "i", handler = function handler2(kw) { var regex = new RegExp(_this10.createRegExp(kw), "gm" + sens), matches = 0; _this10.log('Searching with expression "' + regex + '"'); _this10[fn](regex, 1, function(term, node) { return _this10.opt.filter(node, kw, totalMatches, matches); }, function(element) { matches++; totalMatches++; _this10.opt.each(element); }, function() { if (matches === 0) { _this10.opt.noMatch(kw); } if (kwArr[kwArrLen - 1] === kw) { _this10.opt.done(totalMatches); } else { handler2(kwArr[kwArr.indexOf(kw) + 1]); } }); }; if (this.opt.acrossElements) { fn = "wrapMatchesAcrossElements"; } if (kwArrLen === 0) { this.opt.done(totalMatches); } else { handler(kwArr[0]); } } }, { key: "markRanges", value: function markRanges(rawRanges, opt) { var _this11 = this; this.opt = opt; var totalMatches = 0, ranges = this.checkRanges(rawRanges); if (ranges && ranges.length) { this.log("Starting to mark with the following ranges: " + JSON.stringify(ranges)); this.wrapRangeFromIndex(ranges, function(node, range, match, counter) { return _this11.opt.filter(node, range, match, counter); }, function(element, range) { totalMatches++; _this11.opt.each(element, range); }, function() { _this11.opt.done(totalMatches); }); } else { this.opt.done(totalMatches); } } }, { key: "unmark", value: function unmark(opt) { var _this12 = this; this.opt = opt; var sel = this.opt.element ? this.opt.element : "*"; sel += "[data-markjs]"; if (this.opt.className) { sel += "." + this.opt.className; } this.log('Removal selector "' + sel + '"'); this.iterator.forEachNode(NodeFilter.SHOW_ELEMENT, function(node) { _this12.unwrapMatches(node); }, function(node) { var matchesSel = DOMIterator.matches(node, sel), matchesExclude = _this12.matchesExclude(node); if (!matchesSel || matchesExclude) { return NodeFilter.FILTER_REJECT; } else { return NodeFilter.FILTER_ACCEPT; } }, this.opt.done); } }, { key: "opt", set: function set$$1(val) { this._opt = _extends({}, { "element": "", "className": "", "exclude": [], "iframes": false, "iframesTimeout": 5e3, "separateWordSearch": true, "diacritics": true, "synonyms": {}, "accuracy": "partially", "acrossElements": false, "caseSensitive": false, "ignoreJoiners": false, "ignoreGroups": 0, "ignorePunctuation": [], "wildcards": "disabled", "each": function each() { }, "noMatch": function noMatch() { }, "filter": function filter() { return true; }, "done": function done() { }, "debug": false, "log": window.console }, val); }, get: function get$$1() { return this._opt; } }, { key: "iterator", get: function get$$1() { return new DOMIterator(this.ctx, this.opt.iframes, this.opt.exclude, this.opt.iframesTimeout); } }]); return Mark3; }(); function Mark2(ctx) { var _this = this; var instance = new Mark$1(ctx); this.mark = function(sv, opt) { instance.mark(sv, opt); return _this; }; this.markRegExp = function(sv, opt) { instance.markRegExp(sv, opt); return _this; }; this.markRanges = function(sv, opt) { instance.markRanges(sv, opt); return _this; }; this.unmark = function(opt) { instance.unmark(opt); return _this; }; return this; } return Mark2; }); } }); // lib/highlight.ts var import_mark = __toESM(require_mark(), 1); var PagefindHighlight = class { constructor(options = { markContext: null, highlightParam: "pagefind-highlight", markOptions: { className: "pagefind-highlight", exclude: ["[data-pagefind-ignore]", "[data-pagefind-ignore] *"] }, addStyles: true }) { var _a, _b; const { highlightParam, markContext, markOptions, addStyles } = options; this.highlightParam = highlightParam ?? "pagefind-highlight"; this.addStyles = addStyles ?? true; this.markContext = markContext !== void 0 ? markContext : null; this.markOptions = markOptions !== void 0 ? markOptions : { className: "pagefind-highlight", exclude: ["[data-pagefind-ignore]", "[data-pagefind-ignore] *"] }; (_a = this.markOptions).className ?? (_a.className = "pagefind__highlight"); (_b = this.markOptions).exclude ?? (_b.exclude = [ "[data-pagefind-ignore]", "[data-pagefind-ignore] *" ]); this.markOptions.separateWordSearch = false; this.highlight(); } getHighlightParams(paramName) { const urlParams = new URLSearchParams(window.location.search); return urlParams.getAll(paramName); } // Inline styles might be too hard to override addHighlightStyles(className) { if (!className) return; const styleElement = document.createElement("style"); styleElement.innerText = `:where(.${className}) { background-color: yellow; color: black; }`; document.head.appendChild(styleElement); } createMarkInstance() { if (this.markContext) { return new import_mark.default(this.markContext); } const pagefindBody = document.querySelectorAll("[data-pagefind-body]"); if (pagefindBody.length !== 0) { return new import_mark.default(pagefindBody); } else { return new import_mark.default(document.body); } } markText(instance, text) { instance.mark(text, this.markOptions); } highlight() { const params = this.getHighlightParams(this.highlightParam); if (!params || params.length === 0) return; this.addStyles && this.addHighlightStyles(this.markOptions.className); const markInstance = this.createMarkInstance(); this.markText(markInstance, params); } }; window.PagefindHighlight = PagefindHighlight; export { PagefindHighlight as default }; /*! Bundled license information: mark.js/dist/mark.js: (*!*************************************************** * mark.js v8.11.1 * https://markjs.io/ * Copyright (c) 2014–2018, Julian Kühnel * Released under the MIT license https://git.io/vwTVl *****************************************************) */
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
pagefind/pagefind-modular-ui.css
CSS
:root { --pagefind-ui-scale: 0.8; --pagefind-ui-primary: #034AD8; --pagefind-ui-fade: #707070; --pagefind-ui-text: #393939; --pagefind-ui-background: #ffffff; --pagefind-ui-border: #eeeeee; --pagefind-ui-tag: #eeeeee; --pagefind-ui-border-width: 2px; --pagefind-ui-border-radius: 8px; --pagefind-ui-image-border-radius: 8px; --pagefind-ui-image-box-ratio: 3 / 2; --pagefind-ui-font: system, -apple-system, ".SFNSText-Regular", "San Francisco", "Roboto", "Segoe UI", "Helvetica Neue", "Lucida Grande", sans-serif; } [data-pfmod-hidden] { display: none !important; } [data-pfmod-suppressed] { opacity: 0 !important; pointer-events: none !important; } [data-pfmod-sr-hidden] { -webkit-clip: rect(0 0 0 0) !important; clip: rect(0 0 0 0) !important; -webkit-clip-path: inset(100%) !important; clip-path: inset(100%) !important; height: 1px !important; overflow: hidden !important; overflow: clip !important; position: absolute !important; white-space: nowrap !important; width: 1px !important; } [data-pfmod-loading] { color: var(--pagefind-ui-text); background-color: var(--pagefind-ui-text); border-radius: var(--pagefind-ui-border-radius); opacity: 0.1; pointer-events: none; } /* Input */ .pagefind-modular-input-wrapper { position: relative; } .pagefind-modular-input-wrapper::before { background-color: var(--pagefind-ui-text); width: calc(18px * var(--pagefind-ui-scale)); height: calc(18px * var(--pagefind-ui-scale)); top: calc(23px * var(--pagefind-ui-scale)); left: calc(20px * var(--pagefind-ui-scale)); content: ""; position: absolute; display: block; opacity: 0.7; -webkit-mask-image: url("data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.7549 11.255H11.9649L11.6849 10.985C12.6649 9.845 13.2549 8.365 13.2549 6.755C13.2549 3.165 10.3449 0.255005 6.75488 0.255005C3.16488 0.255005 0.254883 3.165 0.254883 6.755C0.254883 10.345 3.16488 13.255 6.75488 13.255C8.36488 13.255 9.84488 12.665 10.9849 11.685L11.2549 11.965V12.755L16.2549 17.745L17.7449 16.255L12.7549 11.255ZM6.75488 11.255C4.26488 11.255 2.25488 9.245 2.25488 6.755C2.25488 4.26501 4.26488 2.255 6.75488 2.255C9.24488 2.255 11.2549 4.26501 11.2549 6.755C11.2549 9.245 9.24488 11.255 6.75488 11.255Z' fill='%23000000'/%3E%3C/svg%3E%0A"); mask-image: url("data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.7549 11.255H11.9649L11.6849 10.985C12.6649 9.845 13.2549 8.365 13.2549 6.755C13.2549 3.165 10.3449 0.255005 6.75488 0.255005C3.16488 0.255005 0.254883 3.165 0.254883 6.755C0.254883 10.345 3.16488 13.255 6.75488 13.255C8.36488 13.255 9.84488 12.665 10.9849 11.685L11.2549 11.965V12.755L16.2549 17.745L17.7449 16.255L12.7549 11.255ZM6.75488 11.255C4.26488 11.255 2.25488 9.245 2.25488 6.755C2.25488 4.26501 4.26488 2.255 6.75488 2.255C9.24488 2.255 11.2549 4.26501 11.2549 6.755C11.2549 9.245 9.24488 11.255 6.75488 11.255Z' fill='%23000000'/%3E%3C/svg%3E%0A"); -webkit-mask-size: 100%; mask-size: 100%; z-index: 9; pointer-events: none; } .pagefind-modular-input { height: calc(64px * var(--pagefind-ui-scale)); padding: 0 calc(70px * var(--pagefind-ui-scale)) 0 calc(54px * var(--pagefind-ui-scale)); background-color: var(--pagefind-ui-background); border: var(--pagefind-ui-border-width) solid var(--pagefind-ui-border); border-radius: var(--pagefind-ui-border-radius); font-size: calc(21px * var(--pagefind-ui-scale)); position: relative; appearance: none; -webkit-appearance: none; display: flex; width: 100%; box-sizing: border-box; font-weight: 700; } .pagefind-modular-input::placeholder { opacity: 0.2; } .pagefind-modular-input-clear { position: absolute; top: calc(2px * var(--pagefind-ui-scale)); right: calc(2px * var(--pagefind-ui-scale)); height: calc(60px * var(--pagefind-ui-scale)); border-radius: var(--pagefind-ui-border-radius); padding: 0 calc(15px * var(--pagefind-ui-scale)) 0 calc(2px * var(--pagefind-ui-scale)); color: var(--pagefind-ui-text); font-size: calc(14px * var(--pagefind-ui-scale)); cursor: pointer; background-color: var(--pagefind-ui-background); border: none; appearance: none; } /* ResultList */ .pagefind-modular-list-result { list-style-type: none; display: flex; align-items: flex-start; gap: min(calc(40px * var(--pagefind-ui-scale)), 3%); padding: calc(30px * var(--pagefind-ui-scale)) 0 calc(40px * var(--pagefind-ui-scale)); border-top: solid var(--pagefind-ui-border-width) var(--pagefind-ui-border); } .pagefind-modular-list-result:last-of-type { border-bottom: solid var(--pagefind-ui-border-width) var(--pagefind-ui-border); } .pagefind-modular-list-thumb { width: min(30%, calc((30% - (100px * var(--pagefind-ui-scale))) * 100000)); max-width: calc(120px * var(--pagefind-ui-scale)); margin-top: calc(10px * var(--pagefind-ui-scale)); aspect-ratio: var(--pagefind-ui-image-box-ratio); position: relative; } .pagefind-modular-list-image { display: block; position: absolute; left: 50%; transform: translateX(-50%); font-size: 0; width: auto; height: auto; max-width: 100%; max-height: 100%; border-radius: var(--pagefind-ui-image-border-radius); } .pagefind-modular-list-inner { flex: 1; display: flex; flex-direction: column; align-items: flex-start; margin-top: calc(10px * var(--pagefind-ui-scale)); } .pagefind-modular-list-title { display: inline-block; font-weight: 700; font-size: calc(21px * var(--pagefind-ui-scale)); margin-top: 0; margin-bottom: 0; } .pagefind-modular-list-link { color: var(--pagefind-ui-text); text-decoration: none; } .pagefind-modular-list-link:hover { text-decoration: underline; } .pagefind-modular-list-excerpt { display: inline-block; font-weight: 400; font-size: calc(16px * var(--pagefind-ui-scale)); margin-top: calc(4px * var(--pagefind-ui-scale)); margin-bottom: 0; min-width: calc(250px * var(--pagefind-ui-scale)); } /* FilterPills */ .pagefind-modular-filter-pills-wrapper { overflow-x: scroll; padding: 15px 0; } .pagefind-modular-filter-pills { display: flex; gap: 6px; } .pagefind-modular-filter-pill { display: flex; justify-content: center; align-items: center; border: none; appearance: none; padding: 0 calc(24px * var(--pagefind-ui-scale)); background-color: var(--pagefind-ui-background); color: var(--pagefind-ui-fade); border: var(--pagefind-ui-border-width) solid var(--pagefind-ui-border); border-radius: calc(25px * var(--pagefind-ui-scale)); font-size: calc(18px * var(--pagefind-ui-scale)); height: calc(50px * var(--pagefind-ui-scale)); cursor: pointer; white-space: nowrap; } .pagefind-modular-filter-pill:hover { border-color: var(--pagefind-ui-primary); } .pagefind-modular-filter-pill[aria-pressed="true"] { border-color: var(--pagefind-ui-primary); color: var(--pagefind-ui-primary); }
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
pagefind/pagefind-modular-ui.js
JavaScript
(()=>{var b=Object.defineProperty;var w=(i,e)=>{for(var t in e)b(i,t,{get:e[t],enumerable:!0})};var f={};w(f,{FilterPills:()=>h,Input:()=>l,Instance:()=>p,ResultList:()=>a,Summary:()=>o});var r=class i{constructor(e){this.element=document.createElement(e)}id(e){return this.element.id=e,this}class(e){return this.element.classList.add(e),this}attrs(e){for(let[t,s]of Object.entries(e))this.element.setAttribute(t,s);return this}text(e){return this.element.innerText=e,this}html(e){return this.element.innerHTML=e,this}handle(e,t){return this.element.addEventListener(e,t),this}addTo(e){return e instanceof i?e.element.appendChild(this.element):e.appendChild(this.element),this.element}};var T=async(i=100)=>new Promise(e=>setTimeout(e,i)),l=class{constructor(e={}){if(this.inputEl=null,this.clearEl=null,this.instance=null,this.searchID=0,this.debounceTimeoutMs=e.debounceTimeoutMs??300,e.inputElement){if(e.containerElement){console.warn("[Pagefind Input component]: inputElement and containerElement both supplied. Ignoring the container option.");return}this.initExisting(e.inputElement)}else if(e.containerElement)this.initContainer(e.containerElement);else{console.error("[Pagefind Input component]: No selector supplied for containerElement or inputElement");return}this.inputEl.addEventListener("input",async t=>{if(this.instance&&typeof t?.target?.value=="string"){this.updateState(t.target.value);let s=++this.searchID;if(await T(this.debounceTimeoutMs),s!==this.searchID)return null;this.instance?.triggerSearch(t.target.value)}}),this.inputEl.addEventListener("keydown",t=>{t.key==="Escape"&&(++this.searchID,this.inputEl.value="",this.instance?.triggerSearch(""),this.updateState("")),t.key==="Enter"&&t.preventDefault()}),this.inputEl.addEventListener("focus",()=>{this.instance?.triggerLoad()})}initContainer(e){let t=document.querySelector(e);if(!t){console.error(`[Pagefind Input component]: No container found for ${e} selector`);return}if(t.tagName==="INPUT")console.warn(`[Pagefind Input component]: Encountered input element for ${e} when a container was expected`),console.warn("[Pagefind Input component]: Treating containerElement option as inputElement and proceeding"),this.initExisting(e);else{t.innerHTML="";let s=0;for(;document.querySelector(`#pfmod-input-${s}`);)s+=1;let n=new r("form").class("pagefind-modular-input-wrapper").attrs({role:"search","aria-label":"Search this site",action:"javascript:void(0);"});new r("label").attrs({for:`pfmod-input-${s}`,"data-pfmod-sr-hidden":"true"}).text("Search this site").addTo(n),this.inputEl=new r("input").id(`pfmod-input-${s}`).class("pagefind-modular-input").attrs({autocapitalize:"none",enterkeyhint:"search"}).addTo(n),this.clearEl=new r("button").class("pagefind-modular-input-clear").attrs({"data-pfmod-suppressed":"true"}).text("Clear").handle("click",()=>{this.inputEl.value="",this.instance.triggerSearch(""),this.updateState("")}).addTo(n),n.addTo(t)}}initExisting(e){let t=document.querySelector(e);if(!t){console.error(`[Pagefind Input component]: No input element found for ${e} selector`);return}if(t.tagName!=="INPUT"){console.error(`[Pagefind Input component]: Expected ${e} to be an <input> element`);return}this.inputEl=t}updateState(e){this.clearEl&&(e&&e?.length?this.clearEl.removeAttribute("data-pfmod-suppressed"):this.clearEl.setAttribute("data-pfmod-suppressed","true"))}register(e){this.instance=e,this.instance.on("search",(t,s)=>{this.inputEl&&document.activeElement!==this.inputEl&&(this.inputEl.value=t,this.updateState(t))})}focus(){this.inputEl&&this.inputEl.focus()}};var g=i=>{if(i instanceof Element)return[i];if(Array.isArray(i)&&i.every(e=>e instanceof Element))return i;if(typeof i=="string"||i instanceof String){let e=document.createElement("div");return e.innerHTML=i,[...e.childNodes]}else return console.error(`[Pagefind ResultList component]: Expected template function to return an HTML element or string, got ${typeof i}`),[]},v=()=>{let i=(e=30)=>". ".repeat(Math.floor(10+Math.random()*e));return`<li class="pagefind-modular-list-result"> <div class="pagefind-modular-list-thumb" data-pfmod-loading></div> <div class="pagefind-modular-list-inner"> <p class="pagefind-modular-list-title" data-pfmod-loading>${i(30)}</p> <p class="pagefind-modular-list-excerpt" data-pfmod-loading>${i(40)}</p> </div> </li>`},y=i=>{let e=new r("li").class("pagefind-modular-list-result"),t=new r("div").class("pagefind-modular-list-thumb").addTo(e);i?.meta?.image&&new r("img").class("pagefind-modular-list-image").attrs({src:i.meta.image,alt:i.meta.image_alt||i.meta.title}).addTo(t);let s=new r("div").class("pagefind-modular-list-inner").addTo(e),n=new r("p").class("pagefind-modular-list-title").addTo(s);return new r("a").class("pagefind-modular-list-link").text(i.meta?.title).attrs({href:i.meta?.url||i.url}).addTo(n),new r("p").class("pagefind-modular-list-excerpt").html(i.excerpt).addTo(s),e.element},E=i=>{if(!(i instanceof HTMLElement))return null;let e=window.getComputedStyle(i).overflowY;return e!=="visible"&&e!=="hidden"?i:E(i.parentNode)},d=class{constructor(e={}){this.rawResult=e.result,this.placeholderNodes=e.placeholderNodes,this.resultFn=e.resultFn,this.intersectionEl=e.intersectionEl,this.result=null,this.waitForIntersection()}waitForIntersection(){if(!this.placeholderNodes?.length)return;let e={root:this.intersectionEl,rootMargin:"0px",threshold:.01};new IntersectionObserver((s,n)=>{this.result===null&&s?.[0]?.isIntersecting&&(this.load(),n.disconnect())},e).observe(this.placeholderNodes[0])}async load(){if(!this.placeholderNodes?.length)return;this.result=await this.rawResult.data();let e=this.resultFn(this.result),t=g(e);for(;this.placeholderNodes.length>1;)this.placeholderNodes.pop().remove();this.placeholderNodes[0].replaceWith(...t)}},a=class{constructor(e){if(this.intersectionEl=document.body,this.containerEl=null,this.results=[],this.placeholderTemplate=e.placeholderTemplate??v,this.resultTemplate=e.resultTemplate??y,e.containerElement)this.initContainer(e.containerElement);else{console.error("[Pagefind ResultList component]: No selector supplied for containerElement");return}}initContainer(e){let t=document.querySelector(e);if(!t){console.error(`[Pagefind ResultList component]: No container found for ${e} selector`);return}this.containerEl=t}append(e){for(let t of e)this.containerEl.appendChild(t)}register(e){e.on("results",t=>{this.containerEl&&(this.containerEl.innerHTML="",this.intersectionEl=E(this.containerEl),this.results=t.results.map(s=>{let n=g(this.placeholderTemplate());return this.append(n),new d({result:s,placeholderNodes:n,resultFn:this.resultTemplate,intersectionEl:this.intersectionEl})}))}),e.on("loading",()=>{this.containerEl&&(this.containerEl.innerHTML="")})}};var o=class{constructor(e={}){if(this.containerEl=null,this.defaultMessage=e.defaultMessage??"",this.term="",e.containerElement)this.initContainer(e.containerElement);else{console.error("[Pagefind Summary component]: No selector supplied for containerElement");return}}initContainer(e){let t=document.querySelector(e);if(!t){console.error(`[Pagefind Summary component]: No container found for ${e} selector`);return}this.containerEl=t,this.containerEl.innerText=this.defaultMessage}register(e){e.on("search",(t,s)=>{this.term=t}),e.on("results",t=>{if(!this.containerEl||!t)return;if(!this.term){this.containerEl.innerText=this.defaultMessage;return}let s=t?.results?.length??0;this.containerEl.innerText=`${s} result${s===1?"":"s"} for ${this.term}`}),e.on("loading",()=>{this.containerEl&&(this.containerEl.innerText=`Searching for ${this.term}...`)})}};var h=class{constructor(e={}){if(this.instance=null,this.wrapper=null,this.pillContainer=null,this.available={},this.selected=["All"],this.total=0,this.filterMemo="",this.filter=e.filter,this.ordering=e.ordering??null,this.alwaysShow=e.alwaysShow??!1,this.selectMultiple=e.selectMultiple??!1,!this.filter?.length){console.error("[Pagefind FilterPills component]: No filter option supplied, nothing to display");return}if(e.containerElement)this.initContainer(e.containerElement);else{console.error("[Pagefind FilterPills component]: No selector supplied for containerElement");return}}initContainer(e){let t=document.querySelector(e);if(!t){console.error(`[Pagefind FilterPills component]: No container found for ${e} selector`);return}t.innerHTML="";let s=`pagefind_modular_filter_pills_${this.filter}`,n=new r("div").class("pagefind-modular-filter-pills-wrapper").attrs({role:"group","aria-labelledby":s});this.alwaysShow||n.attrs({"data-pfmod-hidden":!0}),new r("div").id(s).class("pagefind-modular-filter-pills-label").attrs({"data-pfmod-sr-hidden":!0}).text(`Filter results by ${this.filter}`).addTo(n),this.pillContainer=new r("div").class("pagefind-modular-filter-pills").addTo(n),this.wrapper=n.addTo(t)}update(){let e=this.available.map(t=>t[0]).join("~");e==this.filterMemo?this.updateExisting():(this.renderNew(),this.filterMemo=e)}pushFilters(){let e=this.selected.filter(t=>t!=="All");this.instance.triggerFilter(this.filter,e)}pillInner(e,t){return this.total?`<span aria-label="${e}">${e} (${t})</span>`:`<span aria-label="${e}">${e}</span>`}renderNew(){this.available.forEach(([e,t])=>{new r("button").class("pagefind-modular-filter-pill").html(this.pillInner(e,t)).attrs({"aria-pressed":this.selected.includes(e),type:"button"}).handle("click",()=>{e==="All"?this.selected=["All"]:this.selected.includes(e)?this.selected=this.selected.filter(s=>s!==e):this.selectMultiple?this.selected.push(e):this.selected=[e],this.selected?.length?this.selected?.length>1&&(this.selected=this.selected.filter(s=>s!=="All")):this.selected=["All"],this.update(),this.pushFilters()}).addTo(this.pillContainer)})}updateExisting(){let e=[...this.pillContainer.childNodes];this.available.forEach(([t,s],n)=>{e[n].innerHTML=this.pillInner(t,s),e[n].setAttribute("aria-pressed",this.selected.includes(t))})}register(e){this.instance=e,this.instance.on("filters",t=>{if(!this.pillContainer)return;this.selectMultiple?t=t.available:t=t.total;let s=t[this.filter];if(!s){console.warn(`[Pagefind FilterPills component]: No possible values found for the ${this.filter} filter`);return}this.available=Object.entries(s),Array.isArray(this.ordering)?this.available.sort((n,c)=>{let m=this.ordering.indexOf(n[0]),_=this.ordering.indexOf(c[0]);return(m===-1?1/0:m)-(_===-1?1/0:_)}):this.available.sort((n,c)=>n[0].localeCompare(c[0])),this.available.unshift(["All",this.total]),this.update()}),e.on("results",t=>{this.pillContainer&&(this.total=t?.unfilteredResultCount||0,this.available?.[0]?.[0]==="All"&&(this.available[0][1]=this.total),this.total||this.alwaysShow?this.wrapper.removeAttribute("data-pfmod-hidden"):this.wrapper.setAttribute("data-pfmod-hidden","true"),this.update())})}};var F=async(i=50)=>await new Promise(e=>setTimeout(e,i)),u;try{u=new URL(document.currentScript.src).pathname.match(/^(.*\/)(?:pagefind-)?modular-ui.js.*$/)[1]}catch{u="/pagefind/"}var p=class{constructor(e={}){this.__pagefind__=null,this.__initializing__=null,this.__searchID__=0,this.__hooks__={search:[],filters:[],loading:[],results:[]},this.components=[],this.searchTerm="",this.searchFilters={},this.searchResult={},this.availableFilters=null,this.totalFilters=null,this.options={bundlePath:e.bundlePath??u,mergeIndex:e.mergeIndex??[]},delete e.bundlePath,delete e.resetStyles,delete e.processResult,delete e.processTerm,delete e.debounceTimeoutMs,delete e.mergeIndex,delete e.translations,this.pagefindOptions=e}add(e){e?.register?.(this),this.components.push(e)}on(e,t){if(!this.__hooks__[e]){let s=Object.keys(this.__hooks__).join(", ");console.error(`[Pagefind Composable]: Unknown event type ${e}. Supported events: [${s}]`);return}if(typeof t!="function"){console.error(`[Pagefind Composable]: Expected callback to be a function, received ${typeof t}`);return}this.__hooks__[e].push(t)}triggerLoad(){this.__load__()}triggerSearch(e){this.searchTerm=e,this.__dispatch__("search",e,this.searchFilters),this.__search__(e,this.searchFilters)}triggerSearchWithFilters(e,t){this.searchTerm=e,this.searchFilters=t,this.__dispatch__("search",e,t),this.__search__(e,t)}triggerFilters(e){this.searchFilters=e,this.__dispatch__("search",this.searchTerm,e),this.__search__(this.searchTerm,e)}triggerFilter(e,t){this.searchFilters=this.searchFilters||{},this.searchFilters[e]=t,this.__dispatch__("search",this.searchTerm,this.searchFilters),this.__search__(this.searchTerm,this.searchFilters)}__dispatch__(e,...t){this.__hooks__[e]?.forEach(s=>s?.(...t))}async __clear__(){this.__dispatch__("results",{results:[],unfilteredTotalCount:0}),this.availableFilters=await this.__pagefind__.filters(),this.totalFilters=this.availableFilters,this.__dispatch__("filters",{available:this.availableFilters,total:this.totalFilters})}async __search__(e,t){this.__dispatch__("loading"),await this.__load__();let s=++this.__searchID__;if(!e||!e.length)return this.__clear__();let n=await this.__pagefind__.search(e,{filters:t});n&&this.__searchID__===s&&(n.filters&&Object.keys(n.filters)?.length&&(this.availableFilters=n.filters,this.totalFilters=n.totalFilters,this.__dispatch__("filters",{available:this.availableFilters,total:this.totalFilters})),this.searchResult=n,this.__dispatch__("results",this.searchResult))}async __load__(){if(this.__initializing__){for(;!this.__pagefind__;)await F(50);return}if(this.__initializing__=!0,!this.__pagefind__){let e;try{e=await import(`${this.options.bundlePath}pagefind.js`)}catch(t){console.error(t),console.error([`Pagefind couldn't be loaded from ${this.options.bundlePath}pagefind.js`,"You can configure this by passing a bundlePath option to PagefindComposable Instance",`[DEBUG: Loaded from ${document?.currentScript?.src??"no known script location"}]`].join(` `))}await e.options(this.pagefindOptions||{});for(let t of this.options.mergeIndex){if(!t.bundlePath)throw new Error("mergeIndex requires a bundlePath parameter");let s=t.bundlePath;delete t.bundlePath,await e.mergeIndex(s,t)}this.__pagefind__=e}this.availableFilters=await this.__pagefind__.filters(),this.totalFilters=this.availableFilters,this.__dispatch__("filters",{available:this.availableFilters,total:this.totalFilters})}};window.PagefindModularUI=f;})();
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
pagefind/pagefind-ui.css
CSS
.pagefind-ui__result.svelte-j9e30.svelte-j9e30{list-style-type:none;display:flex;align-items:flex-start;gap:min(calc(40px * var(--pagefind-ui-scale)),3%);padding:calc(30px * var(--pagefind-ui-scale)) 0 calc(40px * var(--pagefind-ui-scale));border-top:solid var(--pagefind-ui-border-width) var(--pagefind-ui-border)}.pagefind-ui__result.svelte-j9e30.svelte-j9e30:last-of-type{border-bottom:solid var(--pagefind-ui-border-width) var(--pagefind-ui-border)}.pagefind-ui__result-thumb.svelte-j9e30.svelte-j9e30{width:min(30%,calc((30% - (100px * var(--pagefind-ui-scale))) * 100000));max-width:calc(120px * var(--pagefind-ui-scale));margin-top:calc(10px * var(--pagefind-ui-scale));aspect-ratio:var(--pagefind-ui-image-box-ratio);position:relative}.pagefind-ui__result-image.svelte-j9e30.svelte-j9e30{display:block;position:absolute;left:50%;transform:translate(-50%);font-size:0;width:auto;height:auto;max-width:100%;max-height:100%;border-radius:var(--pagefind-ui-image-border-radius)}.pagefind-ui__result-inner.svelte-j9e30.svelte-j9e30{flex:1;display:flex;flex-direction:column;align-items:flex-start;margin-top:calc(10px * var(--pagefind-ui-scale))}.pagefind-ui__result-title.svelte-j9e30.svelte-j9e30{display:inline-block;font-weight:700;font-size:calc(21px * var(--pagefind-ui-scale));margin-top:0;margin-bottom:0}.pagefind-ui__result-title.svelte-j9e30 .pagefind-ui__result-link.svelte-j9e30{color:var(--pagefind-ui-text);text-decoration:none}.pagefind-ui__result-title.svelte-j9e30 .pagefind-ui__result-link.svelte-j9e30:hover{text-decoration:underline}.pagefind-ui__result-excerpt.svelte-j9e30.svelte-j9e30{display:inline-block;font-weight:400;font-size:calc(16px * var(--pagefind-ui-scale));margin-top:calc(4px * var(--pagefind-ui-scale));margin-bottom:0;min-width:calc(250px * var(--pagefind-ui-scale))}.pagefind-ui__loading.svelte-j9e30.svelte-j9e30{color:var(--pagefind-ui-text);background-color:var(--pagefind-ui-text);border-radius:var(--pagefind-ui-border-radius);opacity:.1;pointer-events:none}.pagefind-ui__result-tags.svelte-j9e30.svelte-j9e30{list-style-type:none;padding:0;display:flex;gap:calc(20px * var(--pagefind-ui-scale));flex-wrap:wrap;margin-top:calc(20px * var(--pagefind-ui-scale))}.pagefind-ui__result-tag.svelte-j9e30.svelte-j9e30{padding:calc(4px * var(--pagefind-ui-scale)) calc(8px * var(--pagefind-ui-scale));font-size:calc(14px * var(--pagefind-ui-scale));border-radius:var(--pagefind-ui-border-radius);background-color:var(--pagefind-ui-tag)}.pagefind-ui__result.svelte-4xnkmf.svelte-4xnkmf{list-style-type:none;display:flex;align-items:flex-start;gap:min(calc(40px * var(--pagefind-ui-scale)),3%);padding:calc(30px * var(--pagefind-ui-scale)) 0 calc(40px * var(--pagefind-ui-scale));border-top:solid var(--pagefind-ui-border-width) var(--pagefind-ui-border)}.pagefind-ui__result.svelte-4xnkmf.svelte-4xnkmf:last-of-type{border-bottom:solid var(--pagefind-ui-border-width) var(--pagefind-ui-border)}.pagefind-ui__result-nested.svelte-4xnkmf.svelte-4xnkmf{display:flex;flex-direction:column;padding-left:calc(20px * var(--pagefind-ui-scale))}.pagefind-ui__result-nested.svelte-4xnkmf.svelte-4xnkmf:first-of-type{padding-top:calc(10px * var(--pagefind-ui-scale))}.pagefind-ui__result-nested.svelte-4xnkmf .pagefind-ui__result-link.svelte-4xnkmf{font-size:.9em;position:relative}.pagefind-ui__result-nested.svelte-4xnkmf .pagefind-ui__result-link.svelte-4xnkmf:before{content:"\2937 ";position:absolute;top:0;right:calc(100% + .1em)}.pagefind-ui__result-thumb.svelte-4xnkmf.svelte-4xnkmf{width:min(30%,calc((30% - (100px * var(--pagefind-ui-scale))) * 100000));max-width:calc(120px * var(--pagefind-ui-scale));margin-top:calc(10px * var(--pagefind-ui-scale));aspect-ratio:var(--pagefind-ui-image-box-ratio);position:relative}.pagefind-ui__result-image.svelte-4xnkmf.svelte-4xnkmf{display:block;position:absolute;left:50%;transform:translate(-50%);font-size:0;width:auto;height:auto;max-width:100%;max-height:100%;border-radius:var(--pagefind-ui-image-border-radius)}.pagefind-ui__result-inner.svelte-4xnkmf.svelte-4xnkmf{flex:1;display:flex;flex-direction:column;align-items:flex-start;margin-top:calc(10px * var(--pagefind-ui-scale))}.pagefind-ui__result-title.svelte-4xnkmf.svelte-4xnkmf{display:inline-block;font-weight:700;font-size:calc(21px * var(--pagefind-ui-scale));margin-top:0;margin-bottom:0}.pagefind-ui__result-title.svelte-4xnkmf .pagefind-ui__result-link.svelte-4xnkmf{color:var(--pagefind-ui-text);text-decoration:none}.pagefind-ui__result-title.svelte-4xnkmf .pagefind-ui__result-link.svelte-4xnkmf:hover{text-decoration:underline}.pagefind-ui__result-excerpt.svelte-4xnkmf.svelte-4xnkmf{display:inline-block;font-weight:400;font-size:calc(16px * var(--pagefind-ui-scale));margin-top:calc(4px * var(--pagefind-ui-scale));margin-bottom:0;min-width:calc(250px * var(--pagefind-ui-scale))}.pagefind-ui__loading.svelte-4xnkmf.svelte-4xnkmf{color:var(--pagefind-ui-text);background-color:var(--pagefind-ui-text);border-radius:var(--pagefind-ui-border-radius);opacity:.1;pointer-events:none}.pagefind-ui__result-tags.svelte-4xnkmf.svelte-4xnkmf{list-style-type:none;padding:0;display:flex;gap:calc(20px * var(--pagefind-ui-scale));flex-wrap:wrap;margin-top:calc(20px * var(--pagefind-ui-scale))}.pagefind-ui__result-tag.svelte-4xnkmf.svelte-4xnkmf{padding:calc(4px * var(--pagefind-ui-scale)) calc(8px * var(--pagefind-ui-scale));font-size:calc(14px * var(--pagefind-ui-scale));border-radius:var(--pagefind-ui-border-radius);background-color:var(--pagefind-ui-tag)}legend.svelte-1v2r7ls.svelte-1v2r7ls{position:absolute;clip:rect(0 0 0 0)}.pagefind-ui__filter-panel.svelte-1v2r7ls.svelte-1v2r7ls{min-width:min(calc(260px * var(--pagefind-ui-scale)),100%);flex:1;display:flex;flex-direction:column;margin-top:calc(20px * var(--pagefind-ui-scale))}.pagefind-ui__filter-group.svelte-1v2r7ls.svelte-1v2r7ls{border:0;padding:0}.pagefind-ui__filter-block.svelte-1v2r7ls.svelte-1v2r7ls{padding:0;display:block;border-bottom:solid calc(2px * var(--pagefind-ui-scale)) var(--pagefind-ui-border);padding:calc(20px * var(--pagefind-ui-scale)) 0}.pagefind-ui__filter-name.svelte-1v2r7ls.svelte-1v2r7ls{font-size:calc(16px * var(--pagefind-ui-scale));position:relative;display:flex;align-items:center;list-style:none;font-weight:700;cursor:pointer;height:calc(24px * var(--pagefind-ui-scale))}.pagefind-ui__filter-name.svelte-1v2r7ls.svelte-1v2r7ls::-webkit-details-marker{display:none}.pagefind-ui__filter-name.svelte-1v2r7ls.svelte-1v2r7ls:after{position:absolute;content:"";right:calc(6px * var(--pagefind-ui-scale));top:50%;width:calc(8px * var(--pagefind-ui-scale));height:calc(8px * var(--pagefind-ui-scale));border:solid calc(2px * var(--pagefind-ui-scale)) currentColor;border-right:0;border-top:0;transform:translateY(-70%) rotate(-45deg)}.pagefind-ui__filter-block[open].svelte-1v2r7ls .pagefind-ui__filter-name.svelte-1v2r7ls:after{transform:translateY(-70%) rotate(-225deg)}.pagefind-ui__filter-group.svelte-1v2r7ls.svelte-1v2r7ls{display:flex;flex-direction:column;gap:calc(20px * var(--pagefind-ui-scale));padding-top:calc(30px * var(--pagefind-ui-scale))}.pagefind-ui__filter-value.svelte-1v2r7ls.svelte-1v2r7ls{position:relative;display:flex;align-items:center;gap:calc(8px * var(--pagefind-ui-scale))}.pagefind-ui__filter-value.svelte-1v2r7ls.svelte-1v2r7ls:before{position:absolute;content:"";top:50%;left:calc(8px * var(--pagefind-ui-scale));width:0px;height:0px;border:solid 1px #fff;opacity:0;transform:translate(calc(4.5px * var(--pagefind-ui-scale) * -1),calc(.8px * var(--pagefind-ui-scale))) skew(-5deg) rotate(-45deg);transform-origin:top left;border-top:0;border-right:0;pointer-events:none}.pagefind-ui__filter-value.pagefind-ui__filter-value--checked.svelte-1v2r7ls.svelte-1v2r7ls:before{opacity:1;width:calc(9px * var(--pagefind-ui-scale));height:calc(4px * var(--pagefind-ui-scale));transition:width .1s ease-out .1s,height .1s ease-in}.pagefind-ui__filter-checkbox.svelte-1v2r7ls.svelte-1v2r7ls{margin:0;width:calc(16px * var(--pagefind-ui-scale));height:calc(16px * var(--pagefind-ui-scale));border:solid 1px var(--pagefind-ui-border);appearance:none;-webkit-appearance:none;border-radius:calc(var(--pagefind-ui-border-radius) / 2);background-color:var(--pagefind-ui-background);cursor:pointer}.pagefind-ui__filter-checkbox.svelte-1v2r7ls.svelte-1v2r7ls:checked{background-color:var(--pagefind-ui-primary);border:solid 1px var(--pagefind-ui-primary)}.pagefind-ui__filter-label.svelte-1v2r7ls.svelte-1v2r7ls{cursor:pointer;font-size:calc(16px * var(--pagefind-ui-scale));font-weight:400}.pagefind-ui--reset *:where(:not(html,iframe,canvas,img,svg,video):not(svg *,symbol *)){all:unset;display:revert;outline:revert}.pagefind-ui--reset *,.pagefind-ui--reset *:before,.pagefind-ui--reset *:after{box-sizing:border-box}.pagefind-ui--reset a,.pagefind-ui--reset button{cursor:revert}.pagefind-ui--reset ol,.pagefind-ui--reset ul,.pagefind-ui--reset menu{list-style:none}.pagefind-ui--reset img{max-width:100%}.pagefind-ui--reset table{border-collapse:collapse}.pagefind-ui--reset input,.pagefind-ui--reset textarea{-webkit-user-select:auto}.pagefind-ui--reset textarea{white-space:revert}.pagefind-ui--reset meter{-webkit-appearance:revert;appearance:revert}.pagefind-ui--reset ::placeholder{color:unset}.pagefind-ui--reset :where([hidden]){display:none}.pagefind-ui--reset :where([contenteditable]:not([contenteditable="false"])){-moz-user-modify:read-write;-webkit-user-modify:read-write;overflow-wrap:break-word;-webkit-line-break:after-white-space;-webkit-user-select:auto}.pagefind-ui--reset :where([draggable="true"]){-webkit-user-drag:element}.pagefind-ui--reset mark{all:revert}:root{--pagefind-ui-scale:.8;--pagefind-ui-primary:#393939;--pagefind-ui-text:#393939;--pagefind-ui-background:#ffffff;--pagefind-ui-border:#eeeeee;--pagefind-ui-tag:#eeeeee;--pagefind-ui-border-width:2px;--pagefind-ui-border-radius:8px;--pagefind-ui-image-border-radius:8px;--pagefind-ui-image-box-ratio:3 / 2;--pagefind-ui-font:system, -apple-system, "BlinkMacSystemFont", ".SFNSText-Regular", "San Francisco", "Roboto", "Segoe UI", "Helvetica Neue", "Lucida Grande", "Ubuntu", "arial", sans-serif}.pagefind-ui.svelte-e9gkc3{width:100%;color:var(--pagefind-ui-text);font-family:var(--pagefind-ui-font)}.pagefind-ui__hidden.svelte-e9gkc3{display:none!important}.pagefind-ui__suppressed.svelte-e9gkc3{opacity:0;pointer-events:none}.pagefind-ui__form.svelte-e9gkc3{position:relative}.pagefind-ui__form.svelte-e9gkc3:before{background-color:var(--pagefind-ui-text);width:calc(18px * var(--pagefind-ui-scale));height:calc(18px * var(--pagefind-ui-scale));top:calc(23px * var(--pagefind-ui-scale));left:calc(20px * var(--pagefind-ui-scale));content:"";position:absolute;display:block;opacity:.7;-webkit-mask-image:url("data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.7549 11.255H11.9649L11.6849 10.985C12.6649 9.845 13.2549 8.365 13.2549 6.755C13.2549 3.165 10.3449 0.255005 6.75488 0.255005C3.16488 0.255005 0.254883 3.165 0.254883 6.755C0.254883 10.345 3.16488 13.255 6.75488 13.255C8.36488 13.255 9.84488 12.665 10.9849 11.685L11.2549 11.965V12.755L16.2549 17.745L17.7449 16.255L12.7549 11.255ZM6.75488 11.255C4.26488 11.255 2.25488 9.245 2.25488 6.755C2.25488 4.26501 4.26488 2.255 6.75488 2.255C9.24488 2.255 11.2549 4.26501 11.2549 6.755C11.2549 9.245 9.24488 11.255 6.75488 11.255Z' fill='%23000000'/%3E%3C/svg%3E%0A");mask-image:url("data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.7549 11.255H11.9649L11.6849 10.985C12.6649 9.845 13.2549 8.365 13.2549 6.755C13.2549 3.165 10.3449 0.255005 6.75488 0.255005C3.16488 0.255005 0.254883 3.165 0.254883 6.755C0.254883 10.345 3.16488 13.255 6.75488 13.255C8.36488 13.255 9.84488 12.665 10.9849 11.685L11.2549 11.965V12.755L16.2549 17.745L17.7449 16.255L12.7549 11.255ZM6.75488 11.255C4.26488 11.255 2.25488 9.245 2.25488 6.755C2.25488 4.26501 4.26488 2.255 6.75488 2.255C9.24488 2.255 11.2549 4.26501 11.2549 6.755C11.2549 9.245 9.24488 11.255 6.75488 11.255Z' fill='%23000000'/%3E%3C/svg%3E%0A");-webkit-mask-size:100%;mask-size:100%;z-index:9;pointer-events:none}.pagefind-ui__search-input.svelte-e9gkc3{height:calc(64px * var(--pagefind-ui-scale));padding:0 calc(70px * var(--pagefind-ui-scale)) 0 calc(54px * var(--pagefind-ui-scale));background-color:var(--pagefind-ui-background);border:var(--pagefind-ui-border-width) solid var(--pagefind-ui-border);border-radius:var(--pagefind-ui-border-radius);font-size:calc(21px * var(--pagefind-ui-scale));position:relative;appearance:none;-webkit-appearance:none;display:flex;width:100%;box-sizing:border-box;font-weight:700}.pagefind-ui__search-input.svelte-e9gkc3::placeholder{opacity:.2}.pagefind-ui__search-clear.svelte-e9gkc3{position:absolute;top:calc(3px * var(--pagefind-ui-scale));right:calc(3px * var(--pagefind-ui-scale));height:calc(58px * var(--pagefind-ui-scale));padding:0 calc(15px * var(--pagefind-ui-scale)) 0 calc(2px * var(--pagefind-ui-scale));color:var(--pagefind-ui-text);font-size:calc(14px * var(--pagefind-ui-scale));cursor:pointer;background-color:var(--pagefind-ui-background);border-radius:var(--pagefind-ui-border-radius)}.pagefind-ui__drawer.svelte-e9gkc3{gap:calc(60px * var(--pagefind-ui-scale));display:flex;flex-direction:row;flex-wrap:wrap}.pagefind-ui__results-area.svelte-e9gkc3{min-width:min(calc(400px * var(--pagefind-ui-scale)),100%);flex:1000;margin-top:calc(20px * var(--pagefind-ui-scale))}.pagefind-ui__results.svelte-e9gkc3{padding:0}.pagefind-ui__message.svelte-e9gkc3{box-sizing:content-box;font-size:calc(16px * var(--pagefind-ui-scale));height:calc(24px * var(--pagefind-ui-scale));padding:calc(20px * var(--pagefind-ui-scale)) 0;display:flex;align-items:center;font-weight:700;margin-top:0}.pagefind-ui__button.svelte-e9gkc3{margin-top:calc(40px * var(--pagefind-ui-scale));border:var(--pagefind-ui-border-width) solid var(--pagefind-ui-border);border-radius:var(--pagefind-ui-border-radius);height:calc(48px * var(--pagefind-ui-scale));padding:0 calc(12px * var(--pagefind-ui-scale));font-size:calc(16px * var(--pagefind-ui-scale));color:var(--pagefind-ui-primary);background:var(--pagefind-ui-background);width:100%;text-align:center;font-weight:700;cursor:pointer}.pagefind-ui__button.svelte-e9gkc3:hover{border-color:var(--pagefind-ui-primary);color:var(--pagefind-ui-primary);background:var(--pagefind-ui-background)}
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
pagefind/pagefind-ui.js
JavaScript
(()=>{var is=Object.defineProperty;var v=(n,e)=>{for(var t in e)is(n,t,{get:e[t],enumerable:!0})};function j(){}function lt(n){return n()}function Qt(){return Object.create(null)}function V(n){n.forEach(lt)}function Ye(n){return typeof n=="function"}function G(n,e){return n!=n?e==e:n!==e||n&&typeof n=="object"||typeof n=="function"}var Ke;function le(n,e){return Ke||(Ke=document.createElement("a")),Ke.href=e,n===Ke.href}function xt(n){return Object.keys(n).length===0}var $t=typeof window<"u"?window:typeof globalThis<"u"?globalThis:global,fe=class{constructor(e){this.options=e,this._listeners="WeakMap"in $t?new WeakMap:void 0}observe(e,t){return this._listeners.set(e,t),this._getObserver().observe(e,this.options),()=>{this._listeners.delete(e),this._observer.unobserve(e)}}_getObserver(){var e;return(e=this._observer)!==null&&e!==void 0?e:this._observer=new ResizeObserver(t=>{var s;for(let r of t)fe.entries.set(r.target,r),(s=this._listeners.get(r.target))===null||s===void 0||s(r)})}};fe.entries="WeakMap"in $t?new WeakMap:void 0;var en=!1;function as(){en=!0}function os(){en=!1}function b(n,e){n.appendChild(e)}function y(n,e,t){n.insertBefore(e,t||null)}function C(n){n.parentNode&&n.parentNode.removeChild(n)}function Q(n,e){for(let t=0;t<n.length;t+=1)n[t]&&n[t].d(e)}function k(n){return document.createElement(n)}function us(n){return document.createElementNS("http://www.w3.org/2000/svg",n)}function A(n){return document.createTextNode(n)}function M(){return A(" ")}function x(){return A("")}function K(n,e,t,s){return n.addEventListener(e,t,s),()=>n.removeEventListener(e,t,s)}function p(n,e,t){t==null?n.removeAttribute(e):n.getAttribute(e)!==t&&n.setAttribute(e,t)}function cs(n){return Array.from(n.childNodes)}function N(n,e){e=""+e,n.data!==e&&(n.data=e)}function it(n,e){n.value=e??""}function W(n,e,t){n.classList[t?"add":"remove"](e)}var Xe=class{constructor(e=!1){this.is_svg=!1,this.is_svg=e,this.e=this.n=null}c(e){this.h(e)}m(e,t,s=null){this.e||(this.is_svg?this.e=us(t.nodeName):this.e=k(t.nodeType===11?"TEMPLATE":t.nodeName),this.t=t.tagName!=="TEMPLATE"?t:t.content,this.c(e)),this.i(s)}h(e){this.e.innerHTML=e,this.n=Array.from(this.e.nodeName==="TEMPLATE"?this.e.content.childNodes:this.e.childNodes)}i(e){for(let t=0;t<this.n.length;t+=1)y(this.t,this.n[t],e)}p(e){this.d(),this.h(e),this.i(this.a)}d(){this.n.forEach(C)}};var de;function _e(n){de=n}function tn(){if(!de)throw new Error("Function called outside component initialization");return de}function at(n){tn().$$.on_mount.push(n)}function ot(n){tn().$$.on_destroy.push(n)}var ne=[];var re=[],se=[],nt=[],_s=Promise.resolve(),st=!1;function fs(){st||(st=!0,_s.then(sn))}function rt(n){se.push(n)}function nn(n){nt.push(n)}var tt=new Set,te=0;function sn(){if(te!==0)return;let n=de;do{try{for(;te<ne.length;){let e=ne[te];te++,_e(e),ds(e.$$)}}catch(e){throw ne.length=0,te=0,e}for(_e(null),ne.length=0,te=0;re.length;)re.pop()();for(let e=0;e<se.length;e+=1){let t=se[e];tt.has(t)||(tt.add(t),t())}se.length=0}while(ne.length);for(;nt.length;)nt.pop()();st=!1,tt.clear(),_e(n)}function ds(n){if(n.fragment!==null){n.update(),V(n.before_update);let e=n.dirty;n.dirty=[-1],n.fragment&&n.fragment.p(n.ctx,e),n.after_update.forEach(rt)}}function hs(n){let e=[],t=[];se.forEach(s=>n.indexOf(s)===-1?e.push(s):t.push(s)),t.forEach(s=>s()),se=e}var Je=new Set,ee;function ie(){ee={r:0,c:[],p:ee}}function ae(){ee.r||V(ee.c),ee=ee.p}function z(n,e){n&&n.i&&(Je.delete(n),n.i(e))}function I(n,e,t,s){if(n&&n.o){if(Je.has(n))return;Je.add(n),ee.c.push(()=>{Je.delete(n),s&&(t&&n.d(1),s())}),n.o(e)}else s&&s()}function rn(n,e){I(n,1,1,()=>{e.delete(n.key)})}function ln(n,e,t,s,r,l,i,a,o,h,_,f){let c=n.length,E=l.length,u=c,m={};for(;u--;)m[n[u].key]=u;let d=[],R=new Map,T=new Map,S=[];for(u=E;u--;){let F=f(r,l,u),U=t(F),P=i.get(U);P?s&&S.push(()=>P.p(F,e)):(P=h(U,F),P.c()),R.set(U,d[u]=P),U in m&&T.set(U,Math.abs(u-m[U]))}let w=new Set,B=new Set;function X(F){z(F,1),F.m(a,_),i.set(F.key,F),_=F.first,E--}for(;c&&E;){let F=d[E-1],U=n[c-1],P=F.key,Z=U.key;F===U?(_=F.first,c--,E--):R.has(Z)?!i.has(P)||w.has(P)?X(F):B.has(Z)?c--:T.get(P)>T.get(Z)?(B.add(P),X(F)):(w.add(Z),c--):(o(U,i),c--)}for(;c--;){let F=n[c];R.has(F.key)||o(F,i)}for(;E;)X(d[E-1]);return V(S),d}var ms=["allowfullscreen","allowpaymentrequest","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],Fi=new Set([...ms]);function an(n,e,t){let s=n.$$.props[e];s!==void 0&&(n.$$.bound[s]=t,t(n.$$.ctx[s]))}function Ze(n){n&&n.c()}function he(n,e,t,s){let{fragment:r,after_update:l}=n.$$;r&&r.m(e,t),s||rt(()=>{let i=n.$$.on_mount.map(lt).filter(Ye);n.$$.on_destroy?n.$$.on_destroy.push(...i):V(i),n.$$.on_mount=[]}),l.forEach(rt)}function oe(n,e){let t=n.$$;t.fragment!==null&&(hs(t.after_update),V(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function ps(n,e){n.$$.dirty[0]===-1&&(ne.push(n),fs(),n.$$.dirty.fill(0)),n.$$.dirty[e/31|0]|=1<<e%31}function J(n,e,t,s,r,l,i,a=[-1]){let o=de;_e(n);let h=n.$$={fragment:null,ctx:[],props:l,update:j,not_equal:r,bound:Qt(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(o?o.$$.context:[])),callbacks:Qt(),dirty:a,skip_bound:!1,root:e.target||o.$$.root};i&&i(h.root);let _=!1;if(h.ctx=t?t(n,e.props||{},(f,c,...E)=>{let u=E.length?E[0]:c;return h.ctx&&r(h.ctx[f],h.ctx[f]=u)&&(!h.skip_bound&&h.bound[f]&&h.bound[f](u),_&&ps(n,f)),c}):[],h.update(),_=!0,V(h.before_update),h.fragment=s?s(h.ctx):!1,e.target){if(e.hydrate){as();let f=cs(e.target);h.fragment&&h.fragment.l(f),f.forEach(C)}else h.fragment&&h.fragment.c();e.intro&&z(n.$$.fragment),he(n,e.target,e.anchor,e.customElement),os(),sn()}_e(o)}var gs;typeof HTMLElement=="function"&&(gs=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){let{on_mount:n}=this.$$;this.$$.on_disconnect=n.map(lt).filter(Ye);for(let e in this.$$.slotted)this.appendChild(this.$$.slotted[e])}attributeChangedCallback(n,e,t){this[n]=t}disconnectedCallback(){V(this.$$.on_disconnect)}$destroy(){oe(this,1),this.$destroy=j}$on(n,e){if(!Ye(e))return j;let t=this.$$.callbacks[n]||(this.$$.callbacks[n]=[]);return t.push(e),()=>{let s=t.indexOf(e);s!==-1&&t.splice(s,1)}}$set(n){this.$$set&&!xt(n)&&(this.$$.skip_bound=!0,this.$$set(n),this.$$.skip_bound=!1)}});var q=class{$destroy(){oe(this,1),this.$destroy=j}$on(e,t){if(!Ye(t))return j;let s=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return s.push(t),()=>{let r=s.indexOf(t);r!==-1&&s.splice(r,1)}}$set(e){this.$$set&&!xt(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}};function D(n){let e=typeof n=="string"?n.charCodeAt(0):n;return e>=97&&e<=122||e>=65&&e<=90}function $(n){let e=typeof n=="string"?n.charCodeAt(0):n;return e>=48&&e<=57}function Y(n){return D(n)||$(n)}var on=["art-lojban","cel-gaulish","no-bok","no-nyn","zh-guoyu","zh-hakka","zh-min","zh-min-nan","zh-xiang"];var ut={"en-gb-oed":"en-GB-oxendict","i-ami":"ami","i-bnn":"bnn","i-default":null,"i-enochian":null,"i-hak":"hak","i-klingon":"tlh","i-lux":"lb","i-mingo":null,"i-navajo":"nv","i-pwn":"pwn","i-tao":"tao","i-tay":"tay","i-tsu":"tsu","sgn-be-fr":"sfb","sgn-be-nl":"vgt","sgn-ch-de":"sgg","art-lojban":"jbo","cel-gaulish":null,"no-bok":"nb","no-nyn":"nn","zh-guoyu":"cmn","zh-hakka":"hak","zh-min":null,"zh-min-nan":"nan","zh-xiang":"hsn"};var Es={}.hasOwnProperty;function Qe(n,e={}){let t=un(),s=String(n),r=s.toLowerCase(),l=0;if(n==null)throw new Error("Expected string, got `"+n+"`");if(Es.call(ut,r)){let a=ut[r];return(e.normalize===void 0||e.normalize===null||e.normalize)&&typeof a=="string"?Qe(a):(t[on.includes(r)?"regular":"irregular"]=s,t)}for(;D(r.charCodeAt(l))&&l<9;)l++;if(l>1&&l<9){if(t.language=s.slice(0,l),l<4){let a=0;for(;r.charCodeAt(l)===45&&D(r.charCodeAt(l+1))&&D(r.charCodeAt(l+2))&&D(r.charCodeAt(l+3))&&!D(r.charCodeAt(l+4));){if(a>2)return i(l,3,"Too many extended language subtags, expected at most 3 subtags");t.extendedLanguageSubtags.push(s.slice(l+1,l+4)),l+=4,a++}}for(r.charCodeAt(l)===45&&D(r.charCodeAt(l+1))&&D(r.charCodeAt(l+2))&&D(r.charCodeAt(l+3))&&D(r.charCodeAt(l+4))&&!D(r.charCodeAt(l+5))&&(t.script=s.slice(l+1,l+5),l+=5),r.charCodeAt(l)===45&&(D(r.charCodeAt(l+1))&&D(r.charCodeAt(l+2))&&!D(r.charCodeAt(l+3))?(t.region=s.slice(l+1,l+3),l+=3):$(r.charCodeAt(l+1))&&$(r.charCodeAt(l+2))&&$(r.charCodeAt(l+3))&&!$(r.charCodeAt(l+4))&&(t.region=s.slice(l+1,l+4),l+=4));r.charCodeAt(l)===45;){let a=l+1,o=a;for(;Y(r.charCodeAt(o));){if(o-a>7)return i(o,1,"Too long variant, expected at most 8 characters");o++}if(o-a>4||o-a>3&&$(r.charCodeAt(a)))t.variants.push(s.slice(a,o)),l=o;else break}for(;r.charCodeAt(l)===45&&!(r.charCodeAt(l+1)===120||!Y(r.charCodeAt(l+1))||r.charCodeAt(l+2)!==45||!Y(r.charCodeAt(l+3)));){let a=l+2,o=0;for(;r.charCodeAt(a)===45&&Y(r.charCodeAt(a+1))&&Y(r.charCodeAt(a+2));){let h=a+1;for(a=h+2,o++;Y(r.charCodeAt(a));){if(a-h>7)return i(a,2,"Too long extension, expected at most 8 characters");a++}}if(!o)return i(a,4,"Empty extension, extensions must have at least 2 characters of content");t.extensions.push({singleton:s.charAt(l+1),extensions:s.slice(l+3,a).split("-")}),l=a}}else l=0;if(l===0&&r.charCodeAt(l)===120||r.charCodeAt(l)===45&&r.charCodeAt(l+1)===120){l=l?l+2:1;let a=l;for(;r.charCodeAt(a)===45&&Y(r.charCodeAt(a+1));){let o=l+1;for(a=o;Y(r.charCodeAt(a));){if(a-o>7)return i(a,5,"Too long private-use area, expected at most 8 characters");a++}t.privateuse.push(s.slice(l+1,a)),l=a}}if(l!==s.length)return i(l,6,"Found superfluous content after tag");return t;function i(a,o,h){return e.warning&&e.warning(h,o,a),e.forgiving?t:un()}}function un(){return{language:null,extendedLanguageSubtags:[],script:null,region:null,variants:[],extensions:[],privateuse:[],irregular:null,regular:null}}function cn(n,e,t){let s=n.slice();return s[8]=e[t][0],s[9]=e[t][1],s}function bs(n){let e,t,s,r,l,i=n[0]&&_n(n);return{c(){i&&i.c(),e=M(),t=k("div"),s=k("p"),s.textContent=`${n[3](30)}`,r=M(),l=k("p"),l.textContent=`${n[3](40)}`,p(s,"class","pagefind-ui__result-title pagefind-ui__loading svelte-j9e30"),p(l,"class","pagefind-ui__result-excerpt pagefind-ui__loading svelte-j9e30"),p(t,"class","pagefind-ui__result-inner svelte-j9e30")},m(a,o){i&&i.m(a,o),y(a,e,o),y(a,t,o),b(t,s),b(t,r),b(t,l)},p(a,o){a[0]?i||(i=_n(a),i.c(),i.m(e.parentNode,e)):i&&(i.d(1),i=null)},d(a){i&&i.d(a),a&&C(e),a&&C(t)}}}function Rs(n){let e,t,s,r,l=n[1].meta?.title+"",i,a,o,h,_=n[1].excerpt+"",f,c=n[0]&&fn(n),E=n[2].length&&hn(n);return{c(){c&&c.c(),e=M(),t=k("div"),s=k("p"),r=k("a"),i=A(l),o=M(),h=k("p"),f=M(),E&&E.c(),p(r,"class","pagefind-ui__result-link svelte-j9e30"),p(r,"href",a=n[1].meta?.url||n[1].url),p(s,"class","pagefind-ui__result-title svelte-j9e30"),p(h,"class","pagefind-ui__result-excerpt svelte-j9e30"),p(t,"class","pagefind-ui__result-inner svelte-j9e30")},m(u,m){c&&c.m(u,m),y(u,e,m),y(u,t,m),b(t,s),b(s,r),b(r,i),b(t,o),b(t,h),h.innerHTML=_,b(t,f),E&&E.m(t,null)},p(u,m){u[0]?c?c.p(u,m):(c=fn(u),c.c(),c.m(e.parentNode,e)):c&&(c.d(1),c=null),m&2&&l!==(l=u[1].meta?.title+"")&&N(i,l),m&2&&a!==(a=u[1].meta?.url||u[1].url)&&p(r,"href",a),m&2&&_!==(_=u[1].excerpt+"")&&(h.innerHTML=_),u[2].length?E?E.p(u,m):(E=hn(u),E.c(),E.m(t,null)):E&&(E.d(1),E=null)},d(u){c&&c.d(u),u&&C(e),u&&C(t),E&&E.d()}}}function _n(n){let e;return{c(){e=k("div"),p(e,"class","pagefind-ui__result-thumb pagefind-ui__loading svelte-j9e30")},m(t,s){y(t,e,s)},d(t){t&&C(e)}}}function fn(n){let e,t=n[1].meta.image&&dn(n);return{c(){e=k("div"),t&&t.c(),p(e,"class","pagefind-ui__result-thumb svelte-j9e30")},m(s,r){y(s,e,r),t&&t.m(e,null)},p(s,r){s[1].meta.image?t?t.p(s,r):(t=dn(s),t.c(),t.m(e,null)):t&&(t.d(1),t=null)},d(s){s&&C(e),t&&t.d()}}}function dn(n){let e,t,s;return{c(){e=k("img"),p(e,"class","pagefind-ui__result-image svelte-j9e30"),le(e.src,t=n[1].meta?.image)||p(e,"src",t),p(e,"alt",s=n[1].meta?.image_alt||n[1].meta?.title)},m(r,l){y(r,e,l)},p(r,l){l&2&&!le(e.src,t=r[1].meta?.image)&&p(e,"src",t),l&2&&s!==(s=r[1].meta?.image_alt||r[1].meta?.title)&&p(e,"alt",s)},d(r){r&&C(e)}}}function hn(n){let e,t=n[2],s=[];for(let r=0;r<t.length;r+=1)s[r]=mn(cn(n,t,r));return{c(){e=k("ul");for(let r=0;r<s.length;r+=1)s[r].c();p(e,"class","pagefind-ui__result-tags svelte-j9e30")},m(r,l){y(r,e,l);for(let i=0;i<s.length;i+=1)s[i]&&s[i].m(e,null)},p(r,l){if(l&4){t=r[2];let i;for(i=0;i<t.length;i+=1){let a=cn(r,t,i);s[i]?s[i].p(a,l):(s[i]=mn(a),s[i].c(),s[i].m(e,null))}for(;i<s.length;i+=1)s[i].d(1);s.length=t.length}},d(r){r&&C(e),Q(s,r)}}}function mn(n){let e,t=n[8].replace(/^(\w)/,pn)+"",s,r,l=n[9]+"",i,a;return{c(){e=k("li"),s=A(t),r=A(": "),i=A(l),a=M(),p(e,"class","pagefind-ui__result-tag svelte-j9e30")},m(o,h){y(o,e,h),b(e,s),b(e,r),b(e,i),b(e,a)},p(o,h){h&4&&t!==(t=o[8].replace(/^(\w)/,pn)+"")&&N(s,t),h&4&&l!==(l=o[9]+"")&&N(i,l)},d(o){o&&C(e)}}}function Ts(n){let e;function t(l,i){return l[1]?Rs:bs}let s=t(n,-1),r=s(n);return{c(){e=k("li"),r.c(),p(e,"class","pagefind-ui__result svelte-j9e30")},m(l,i){y(l,e,i),r.m(e,null)},p(l,[i]){s===(s=t(l,i))&&r?r.p(l,i):(r.d(1),r=s(l),r&&(r.c(),r.m(e,null)))},i:j,o:j,d(l){l&&C(e),r.d()}}}var pn=n=>n.toLocaleUpperCase();function ks(n,e,t){let{show_images:s=!0}=e,{process_result:r=null}=e,{result:l={data:async()=>{}}}=e,i=["title","image","image_alt","url"],a,o=[],h=async f=>{t(1,a=await f.data()),t(1,a=r?.(a)??a),t(2,o=Object.entries(a.meta).filter(([c])=>!i.includes(c)))},_=(f=30)=>". ".repeat(Math.floor(10+Math.random()*f));return n.$$set=f=>{"show_images"in f&&t(0,s=f.show_images),"process_result"in f&&t(4,r=f.process_result),"result"in f&&t(5,l=f.result)},n.$$.update=()=>{if(n.$$.dirty&32)e:h(l)},[s,a,o,_,r,l]}var ct=class extends q{constructor(e){super(),J(this,e,ks,Ts,G,{show_images:0,process_result:4,result:5})}},gn=ct;function En(n,e,t){let s=n.slice();return s[11]=e[t][0],s[12]=e[t][1],s}function bn(n,e,t){let s=n.slice();return s[15]=e[t],s}function Cs(n){let e,t,s,r,l,i=n[0]&&Rn(n);return{c(){i&&i.c(),e=M(),t=k("div"),s=k("p"),s.textContent=`${n[5](30)}`,r=M(),l=k("p"),l.textContent=`${n[5](40)}`,p(s,"class","pagefind-ui__result-title pagefind-ui__loading svelte-4xnkmf"),p(l,"class","pagefind-ui__result-excerpt pagefind-ui__loading svelte-4xnkmf"),p(t,"class","pagefind-ui__result-inner svelte-4xnkmf")},m(a,o){i&&i.m(a,o),y(a,e,o),y(a,t,o),b(t,s),b(t,r),b(t,l)},p(a,o){a[0]?i||(i=Rn(a),i.c(),i.m(e.parentNode,e)):i&&(i.d(1),i=null)},d(a){i&&i.d(a),a&&C(e),a&&C(t)}}}function ys(n){let e,t,s,r,l=n[1].meta?.title+"",i,a,o,h,_,f=n[0]&&Tn(n),c=n[4]&&Cn(n),E=n[3],u=[];for(let d=0;d<E.length;d+=1)u[d]=yn(bn(n,E,d));let m=n[2].length&&Sn(n);return{c(){f&&f.c(),e=M(),t=k("div"),s=k("p"),r=k("a"),i=A(l),o=M(),c&&c.c(),h=M();for(let d=0;d<u.length;d+=1)u[d].c();_=M(),m&&m.c(),p(r,"class","pagefind-ui__result-link svelte-4xnkmf"),p(r,"href",a=n[1].meta?.url||n[1].url),p(s,"class","pagefind-ui__result-title svelte-4xnkmf"),p(t,"class","pagefind-ui__result-inner svelte-4xnkmf")},m(d,R){f&&f.m(d,R),y(d,e,R),y(d,t,R),b(t,s),b(s,r),b(r,i),b(t,o),c&&c.m(t,null),b(t,h);for(let T=0;T<u.length;T+=1)u[T]&&u[T].m(t,null);b(t,_),m&&m.m(t,null)},p(d,R){if(d[0]?f?f.p(d,R):(f=Tn(d),f.c(),f.m(e.parentNode,e)):f&&(f.d(1),f=null),R&2&&l!==(l=d[1].meta?.title+"")&&N(i,l),R&2&&a!==(a=d[1].meta?.url||d[1].url)&&p(r,"href",a),d[4]?c?c.p(d,R):(c=Cn(d),c.c(),c.m(t,h)):c&&(c.d(1),c=null),R&8){E=d[3];let T;for(T=0;T<E.length;T+=1){let S=bn(d,E,T);u[T]?u[T].p(S,R):(u[T]=yn(S),u[T].c(),u[T].m(t,_))}for(;T<u.length;T+=1)u[T].d(1);u.length=E.length}d[2].length?m?m.p(d,R):(m=Sn(d),m.c(),m.m(t,null)):m&&(m.d(1),m=null)},d(d){f&&f.d(d),d&&C(e),d&&C(t),c&&c.d(),Q(u,d),m&&m.d()}}}function Rn(n){let e;return{c(){e=k("div"),p(e,"class","pagefind-ui__result-thumb pagefind-ui__loading svelte-4xnkmf")},m(t,s){y(t,e,s)},d(t){t&&C(e)}}}function Tn(n){let e,t=n[1].meta.image&&kn(n);return{c(){e=k("div"),t&&t.c(),p(e,"class","pagefind-ui__result-thumb svelte-4xnkmf")},m(s,r){y(s,e,r),t&&t.m(e,null)},p(s,r){s[1].meta.image?t?t.p(s,r):(t=kn(s),t.c(),t.m(e,null)):t&&(t.d(1),t=null)},d(s){s&&C(e),t&&t.d()}}}function kn(n){let e,t,s;return{c(){e=k("img"),p(e,"class","pagefind-ui__result-image svelte-4xnkmf"),le(e.src,t=n[1].meta?.image)||p(e,"src",t),p(e,"alt",s=n[1].meta?.image_alt||n[1].meta?.title)},m(r,l){y(r,e,l)},p(r,l){l&2&&!le(e.src,t=r[1].meta?.image)&&p(e,"src",t),l&2&&s!==(s=r[1].meta?.image_alt||r[1].meta?.title)&&p(e,"alt",s)},d(r){r&&C(e)}}}function Cn(n){let e,t=n[1].excerpt+"";return{c(){e=k("p"),p(e,"class","pagefind-ui__result-excerpt svelte-4xnkmf")},m(s,r){y(s,e,r),e.innerHTML=t},p(s,r){r&2&&t!==(t=s[1].excerpt+"")&&(e.innerHTML=t)},d(s){s&&C(e)}}}function yn(n){let e,t,s,r=n[15].title+"",l,i,a,o,h=n[15].excerpt+"";return{c(){e=k("div"),t=k("p"),s=k("a"),l=A(r),a=M(),o=k("p"),p(s,"class","pagefind-ui__result-link svelte-4xnkmf"),p(s,"href",i=n[15].url),p(t,"class","pagefind-ui__result-title svelte-4xnkmf"),p(o,"class","pagefind-ui__result-excerpt svelte-4xnkmf"),p(e,"class","pagefind-ui__result-nested svelte-4xnkmf")},m(_,f){y(_,e,f),b(e,t),b(t,s),b(s,l),b(e,a),b(e,o),o.innerHTML=h},p(_,f){f&8&&r!==(r=_[15].title+"")&&N(l,r),f&8&&i!==(i=_[15].url)&&p(s,"href",i),f&8&&h!==(h=_[15].excerpt+"")&&(o.innerHTML=h)},d(_){_&&C(e)}}}function Sn(n){let e,t=n[2],s=[];for(let r=0;r<t.length;r+=1)s[r]=vn(En(n,t,r));return{c(){e=k("ul");for(let r=0;r<s.length;r+=1)s[r].c();p(e,"class","pagefind-ui__result-tags svelte-4xnkmf")},m(r,l){y(r,e,l);for(let i=0;i<s.length;i+=1)s[i]&&s[i].m(e,null)},p(r,l){if(l&4){t=r[2];let i;for(i=0;i<t.length;i+=1){let a=En(r,t,i);s[i]?s[i].p(a,l):(s[i]=vn(a),s[i].c(),s[i].m(e,null))}for(;i<s.length;i+=1)s[i].d(1);s.length=t.length}},d(r){r&&C(e),Q(s,r)}}}function vn(n){let e,t=n[11].replace(/^(\w)/,Mn)+"",s,r,l=n[12]+"",i,a;return{c(){e=k("li"),s=A(t),r=A(": "),i=A(l),a=M(),p(e,"class","pagefind-ui__result-tag svelte-4xnkmf")},m(o,h){y(o,e,h),b(e,s),b(e,r),b(e,i),b(e,a)},p(o,h){h&4&&t!==(t=o[11].replace(/^(\w)/,Mn)+"")&&N(s,t),h&4&&l!==(l=o[12]+"")&&N(i,l)},d(o){o&&C(e)}}}function Ss(n){let e;function t(l,i){return l[1]?ys:Cs}let s=t(n,-1),r=s(n);return{c(){e=k("li"),r.c(),p(e,"class","pagefind-ui__result svelte-4xnkmf")},m(l,i){y(l,e,i),r.m(e,null)},p(l,[i]){s===(s=t(l,i))&&r?r.p(l,i):(r.d(1),r=s(l),r&&(r.c(),r.m(e,null)))},i:j,o:j,d(l){l&&C(e),r.d()}}}var Mn=n=>n.toLocaleUpperCase();function vs(n,e,t){let{show_images:s=!0}=e,{process_result:r=null}=e,{result:l={data:async()=>{}}}=e,i=["title","image","image_alt","url"],a,o=[],h=[],_=!1,f=(u,m)=>{if(u.length<=m)return u;let d=[...u].sort((R,T)=>T.locations.length-R.locations.length).slice(0,3).map(R=>R.url);return u.filter(R=>d.includes(R.url))},c=async u=>{t(1,a=await u.data()),t(1,a=r?.(a)??a),t(2,o=Object.entries(a.meta).filter(([m])=>!i.includes(m))),Array.isArray(a.sub_results)&&(t(4,_=a.sub_results?.[0]?.url===(a.meta?.url||a.url)),_?t(3,h=f(a.sub_results.slice(1),3)):t(3,h=f([...a.sub_results],3)))},E=(u=30)=>". ".repeat(Math.floor(10+Math.random()*u));return n.$$set=u=>{"show_images"in u&&t(0,s=u.show_images),"process_result"in u&&t(6,r=u.process_result),"result"in u&&t(7,l=u.result)},n.$$.update=()=>{if(n.$$.dirty&128)e:c(l)},[s,a,o,h,_,E,r,l]}var _t=class extends q{constructor(e){super(),J(this,e,vs,Ss,G,{show_images:0,process_result:6,result:7})}},An=_t;function wn(n,e,t){let s=n.slice();return s[9]=e[t][0],s[10]=e[t][1],s[11]=e,s[12]=t,s}function Fn(n,e,t){let s=n.slice();return s[13]=e[t][0],s[14]=e[t][1],s[15]=e,s[16]=t,s}function Hn(n){let e,t,s=n[3]("filters_label",n[4],n[5])+"",r,l,i=Object.entries(n[1]),a=[];for(let o=0;o<i.length;o+=1)a[o]=jn(wn(n,i,o));return{c(){e=k("fieldset"),t=k("legend"),r=A(s),l=M();for(let o=0;o<a.length;o+=1)a[o].c();p(t,"class","pagefind-ui__filter-panel-label svelte-1v2r7ls"),p(e,"class","pagefind-ui__filter-panel svelte-1v2r7ls")},m(o,h){y(o,e,h),b(e,t),b(t,r),b(e,l);for(let _=0;_<a.length;_+=1)a[_]&&a[_].m(e,null)},p(o,h){if(h&56&&s!==(s=o[3]("filters_label",o[4],o[5])+"")&&N(r,s),h&71){i=Object.entries(o[1]);let _;for(_=0;_<i.length;_+=1){let f=wn(o,i,_);a[_]?a[_].p(f,h):(a[_]=jn(f),a[_].c(),a[_].m(e,null))}for(;_<a.length;_+=1)a[_].d(1);a.length=i.length}},d(o){o&&C(e),Q(a,o)}}}function Nn(n){let e,t,s,r,l,i,a,o,h=n[13]+"",_,f=n[14]+"",c,E,u,m,d,R;function T(){n[8].call(t,n[9],n[13])}return{c(){e=k("div"),t=k("input"),i=M(),a=k("label"),o=new Xe(!1),_=A(" ("),c=A(f),E=A(")"),m=M(),p(t,"class","pagefind-ui__filter-checkbox svelte-1v2r7ls"),p(t,"type","checkbox"),p(t,"id",s=n[9]+"-"+n[13]),p(t,"name",r=n[9]),t.__value=l=n[13],t.value=t.__value,o.a=_,p(a,"class","pagefind-ui__filter-label svelte-1v2r7ls"),p(a,"for",u=n[9]+"-"+n[13]),p(e,"class","pagefind-ui__filter-value svelte-1v2r7ls"),W(e,"pagefind-ui__filter-value--checked",n[0][`${n[9]}:${n[13]}`])},m(S,w){y(S,e,w),b(e,t),t.checked=n[0][`${n[9]}:${n[13]}`],b(e,i),b(e,a),o.m(h,a),b(a,_),b(a,c),b(a,E),b(e,m),d||(R=K(t,"change",T),d=!0)},p(S,w){n=S,w&2&&s!==(s=n[9]+"-"+n[13])&&p(t,"id",s),w&2&&r!==(r=n[9])&&p(t,"name",r),w&2&&l!==(l=n[13])&&(t.__value=l,t.value=t.__value),w&3&&(t.checked=n[0][`${n[9]}:${n[13]}`]),w&2&&h!==(h=n[13]+"")&&o.p(h),w&2&&f!==(f=n[14]+"")&&N(c,f),w&2&&u!==(u=n[9]+"-"+n[13])&&p(a,"for",u),w&3&&W(e,"pagefind-ui__filter-value--checked",n[0][`${n[9]}:${n[13]}`])},d(S){S&&C(e),d=!1,R()}}}function On(n){let e,t=(n[2]||n[14]||n[0][`${n[9]}:${n[13]}`])&&Nn(n);return{c(){t&&t.c(),e=x()},m(s,r){t&&t.m(s,r),y(s,e,r)},p(s,r){s[2]||s[14]||s[0][`${s[9]}:${s[13]}`]?t?t.p(s,r):(t=Nn(s),t.c(),t.m(e.parentNode,e)):t&&(t.d(1),t=null)},d(s){t&&t.d(s),s&&C(e)}}}function jn(n){let e,t,s=n[9].replace(/^(\w)/,zn)+"",r,l,i,a=n[9]+"",o,h,_=Object.entries(n[10]||{}),f=[];for(let c=0;c<_.length;c+=1)f[c]=On(Fn(n,_,c));return{c(){e=k("details"),t=k("summary"),r=M(),l=k("fieldset"),i=k("legend"),o=M();for(let c=0;c<f.length;c+=1)f[c].c();h=M(),p(t,"class","pagefind-ui__filter-name svelte-1v2r7ls"),p(i,"class","pagefind-ui__filter-group-label svelte-1v2r7ls"),p(l,"class","pagefind-ui__filter-group svelte-1v2r7ls"),p(e,"class","pagefind-ui__filter-block svelte-1v2r7ls"),e.open=n[6]},m(c,E){y(c,e,E),b(e,t),t.innerHTML=s,b(e,r),b(e,l),b(l,i),i.innerHTML=a,b(l,o);for(let u=0;u<f.length;u+=1)f[u]&&f[u].m(l,null);b(e,h)},p(c,E){if(E&2&&s!==(s=c[9].replace(/^(\w)/,zn)+"")&&(t.innerHTML=s),E&2&&a!==(a=c[9]+"")&&(i.innerHTML=a),E&7){_=Object.entries(c[10]||{});let u;for(u=0;u<_.length;u+=1){let m=Fn(c,_,u);f[u]?f[u].p(m,E):(f[u]=On(m),f[u].c(),f[u].m(l,null))}for(;u<f.length;u+=1)f[u].d(1);f.length=_.length}E&64&&(e.open=c[6])},d(c){c&&C(e),Q(f,c)}}}function Ms(n){let e=n[1]&&Object.entries(n[1]).length,t,s=e&&Hn(n);return{c(){s&&s.c(),t=x()},m(r,l){s&&s.m(r,l),y(r,t,l)},p(r,[l]){l&2&&(e=r[1]&&Object.entries(r[1]).length),e?s?s.p(r,l):(s=Hn(r),s.c(),s.m(t.parentNode,t)):s&&(s.d(1),s=null)},i:j,o:j,d(r){s&&s.d(r),r&&C(t)}}}var zn=n=>n.toLocaleUpperCase();function As(n,e,t){let{available_filters:s=null}=e,{show_empty_filters:r=!0}=e,{translate:l=()=>""}=e,{automatic_translations:i={}}=e,{translations:a={}}=e,o={},h=!1,_=!1;function f(c,E){o[`${c}:${E}`]=this.checked,t(0,o)}return n.$$set=c=>{"available_filters"in c&&t(1,s=c.available_filters),"show_empty_filters"in c&&t(2,r=c.show_empty_filters),"translate"in c&&t(3,l=c.translate),"automatic_translations"in c&&t(4,i=c.automatic_translations),"translations"in c&&t(5,a=c.translations)},n.$$.update=()=>{if(n.$$.dirty&130){e:if(s&&!h){t(7,h=!0);let c=Object.entries(s||{});c.length===1&&Object.entries(c[0][1])?.length<=6&&t(6,_=!0)}}},[o,s,r,l,i,a,_,h,f]}var ft=class extends q{constructor(e){super(),J(this,e,As,Ms,G,{available_filters:1,show_empty_filters:2,translate:3,automatic_translations:4,translations:5,selected_filters:0})}get selected_filters(){return this.$$.ctx[0]}},Dn=ft;var dt={};v(dt,{comments:()=>Fs,default:()=>Os,direction:()=>Hs,strings:()=>Ns,thanks_to:()=>ws});var ws="Jan Claasen <jan@cloudcannon.com>",Fs="",Hs="ltr",Ns={placeholder:"Soek",clear_search:"Opruim",load_more:"Laai nog resultate",search_label:"Soek hierdie webwerf",filters_label:"Filters",zero_results:"Geen resultate vir [SEARCH_TERM]",many_results:"[COUNT] resultate vir [SEARCH_TERM]",one_result:"[COUNT] resultate vir [SEARCH_TERM]",alt_search:"Geen resultate vir [SEARCH_TERM]. Toon resultate vir [DIFFERENT_TERM] in plaas daarvan",search_suggestion:"Geen resultate vir [SEARCH_TERM]. Probeer eerder een van die volgende terme:",searching:"Soek vir [SEARCH_TERM]"},Os={thanks_to:ws,comments:Fs,direction:Hs,strings:Ns};var ht={};v(ht,{comments:()=>zs,default:()=>Is,direction:()=>Ds,strings:()=>Us,thanks_to:()=>js});var js="Maruf Alom <mail@marufalom.com>",zs="",Ds="ltr",Us={placeholder:"\u0985\u09A8\u09C1\u09B8\u09A8\u09CD\u09A7\u09BE\u09A8 \u0995\u09B0\u09C1\u09A8",clear_search:"\u09AE\u09C1\u099B\u09C7 \u09AB\u09C7\u09B2\u09C1\u09A8",load_more:"\u0986\u09B0\u09CB \u09AB\u09B2\u09BE\u09AB\u09B2 \u09A6\u09C7\u0996\u09C1\u09A8",search_label:"\u098F\u0987 \u0993\u09DF\u09C7\u09AC\u09B8\u09BE\u0987\u099F\u09C7 \u0985\u09A8\u09C1\u09B8\u09A8\u09CD\u09A7\u09BE\u09A8 \u0995\u09B0\u09C1\u09A8",filters_label:"\u09AB\u09BF\u09B2\u09CD\u099F\u09BE\u09B0",zero_results:"[SEARCH_TERM] \u098F\u09B0 \u099C\u09A8\u09CD\u09AF \u0995\u09BF\u099B\u09C1 \u0996\u09C1\u0981\u099C\u09C7 \u09AA\u09BE\u0993\u09DF\u09BE \u09AF\u09BE\u09DF\u09A8\u09BF",many_results:"[COUNT]-\u099F\u09BF \u09AB\u09B2\u09BE\u09AB\u09B2 \u09AA\u09BE\u0993\u09DF\u09BE \u0997\u09BF\u09DF\u09C7\u099B\u09C7 [SEARCH_TERM] \u098F\u09B0 \u099C\u09A8\u09CD\u09AF",one_result:"[COUNT]-\u099F\u09BF \u09AB\u09B2\u09BE\u09AB\u09B2 \u09AA\u09BE\u0993\u09DF\u09BE \u0997\u09BF\u09DF\u09C7\u099B\u09C7 [SEARCH_TERM] \u098F\u09B0 \u099C\u09A8\u09CD\u09AF",alt_search:"\u0995\u09CB\u09A8 \u0995\u09BF\u099B\u09C1 \u0996\u09C1\u0981\u099C\u09C7 \u09AA\u09BE\u0993\u09DF\u09BE \u09AF\u09BE\u09DF\u09A8\u09BF [SEARCH_TERM] \u098F\u09B0 \u099C\u09A8\u09CD\u09AF. \u09AA\u09B0\u09BF\u09AC\u09B0\u09CD\u09A4\u09C7 [DIFFERENT_TERM] \u098F\u09B0 \u099C\u09A8\u09CD\u09AF \u09A6\u09C7\u0996\u09BE\u09A8\u09CB \u09B9\u099A\u09CD\u099B\u09C7",search_suggestion:"\u0995\u09CB\u09A8 \u0995\u09BF\u099B\u09C1 \u0996\u09C1\u0981\u099C\u09C7 \u09AA\u09BE\u0993\u09DF\u09BE \u09AF\u09BE\u09DF\u09A8\u09BF [SEARCH_TERM] \u098F\u09B0 \u09AC\u09BF\u09B7\u09DF\u09C7. \u09A8\u09BF\u09A8\u09CD\u09AE\u09C7\u09B0 \u09AC\u09BF\u09B7\u09DF\u09AC\u09B8\u09CD\u09A4\u09C1 \u0996\u09C1\u0981\u099C\u09C7 \u09A6\u09C7\u0996\u09C1\u09A8:",searching:"\u0985\u09A8\u09C1\u09B8\u09A8\u09CD\u09A7\u09BE\u09A8 \u099A\u09B2\u099B\u09C7 [SEARCH_TERM]..."},Is={thanks_to:js,comments:zs,direction:Ds,strings:Us};var mt={};v(mt,{comments:()=>Ls,default:()=>Ws,direction:()=>qs,strings:()=>Bs,thanks_to:()=>Ps});var Ps="Pablo Villaverde <https://github.com/pvillaverde>",Ls="",qs="ltr",Bs={placeholder:"Cerca",clear_search:"Netejar",load_more:"Veure m\xE9es resultats",search_label:"Cerca en aquest lloc",filters_label:"Filtres",zero_results:"No es van trobar resultats per [SEARCH_TERM]",many_results:"[COUNT] resultats trobats per [SEARCH_TERM]",one_result:"[COUNT] resultat trobat per [SEARCH_TERM]",alt_search:"No es van trobar resultats per [SEARCH_TERM]. Mostrant al seu lloc resultats per [DIFFERENT_TERM]",search_suggestion:"No es van trobar resultats per [SEARCH_TERM]. Proveu una de les cerques seg\xFCents:",searching:"Cercant [SEARCH_TERM]..."},Ws={thanks_to:Ps,comments:Ls,direction:qs,strings:Bs};var pt={};v(pt,{comments:()=>Gs,default:()=>Ys,direction:()=>Ks,strings:()=>Js,thanks_to:()=>Vs});var Vs="Jonas Smedegaard <dr@jones.dk>",Gs="",Ks="ltr",Js={placeholder:"S\xF8g",clear_search:"Nulstil",load_more:"Indl\xE6s flere resultater",search_label:"S\xF8g p\xE5 dette website",filters_label:"Filtre",zero_results:"Ingen resultater for [SEARCH_TERM]",many_results:"[COUNT] resultater for [SEARCH_TERM]",one_result:"[COUNT] resultat for [SEARCH_TERM]",alt_search:"Ingen resultater for [SEARCH_TERM]. Viser resultater for [DIFFERENT_TERM] i stedet",search_suggestion:"Ingen resultater for [SEARCH_TERM]. Pr\xF8v et af disse s\xF8geord i stedet:",searching:"S\xF8ger efter [SEARCH_TERM]..."},Ys={thanks_to:Vs,comments:Gs,direction:Ks,strings:Js};var gt={};v(gt,{comments:()=>Zs,default:()=>$s,direction:()=>Qs,strings:()=>xs,thanks_to:()=>Xs});var Xs="Jan Claasen <jan@cloudcannon.com>",Zs="",Qs="ltr",xs={placeholder:"Suche",clear_search:"L\xF6schen",load_more:"Mehr Ergebnisse laden",search_label:"Suche diese Seite",filters_label:"Filter",zero_results:"Keine Ergebnisse f\xFCr [SEARCH_TERM]",many_results:"[COUNT] Ergebnisse f\xFCr [SEARCH_TERM]",one_result:"[COUNT] Ergebnis f\xFCr [SEARCH_TERM]",alt_search:"Keine Ergebnisse f\xFCr [SEARCH_TERM]. Stattdessen werden Ergebnisse f\xFCr [DIFFERENT_TERM] angezeigt",search_suggestion:"Keine Ergebnisse f\xFCr [SEARCH_TERM]. Versuchen Sie eine der folgenden Suchen:",searching:"Suche f\xFCr [SEARCH_TERM]"},$s={thanks_to:Xs,comments:Zs,direction:Qs,strings:xs};var Et={};v(Et,{comments:()=>tr,default:()=>rr,direction:()=>nr,strings:()=>sr,thanks_to:()=>er});var er="Liam Bigelow <liam@cloudcannon.com>",tr="",nr="ltr",sr={placeholder:"Search",clear_search:"Clear",load_more:"Load more results",search_label:"Search this site",filters_label:"Filters",zero_results:"No results for [SEARCH_TERM]",many_results:"[COUNT] results for [SEARCH_TERM]",one_result:"[COUNT] result for [SEARCH_TERM]",alt_search:"No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",search_suggestion:"No results for [SEARCH_TERM]. Try one of the following searches:",searching:"Searching for [SEARCH_TERM]..."},rr={thanks_to:er,comments:tr,direction:nr,strings:sr};var bt={};v(bt,{comments:()=>ir,default:()=>ur,direction:()=>ar,strings:()=>or,thanks_to:()=>lr});var lr="Pablo Villaverde <https://github.com/pvillaverde>",ir="",ar="ltr",or={placeholder:"Buscar",clear_search:"Limpiar",load_more:"Ver m\xE1s resultados",search_label:"Buscar en este sitio",filters_label:"Filtros",zero_results:"No se encontraron resultados para [SEARCH_TERM]",many_results:"[COUNT] resultados encontrados para [SEARCH_TERM]",one_result:"[COUNT] resultado encontrado para [SEARCH_TERM]",alt_search:"No se encontraron resultados para [SEARCH_TERM]. Mostrando en su lugar resultados para [DIFFERENT_TERM]",search_suggestion:"No se encontraron resultados para [SEARCH_TERM]. Prueba una de las siguientes b\xFAsquedas:",searching:"Buscando [SEARCH_TERM]..."},ur={thanks_to:lr,comments:ir,direction:ar,strings:or};var Rt={};v(Rt,{comments:()=>_r,default:()=>hr,direction:()=>fr,strings:()=>dr,thanks_to:()=>cr});var cr="Valtteri Laitinen <dev@valtlai.fi>",_r="",fr="ltr",dr={placeholder:"Haku",clear_search:"Tyhjenn\xE4",load_more:"Lataa lis\xE4\xE4 tuloksia",search_label:"Hae t\xE4lt\xE4 sivustolta",filters_label:"Suodattimet",zero_results:"Ei tuloksia haulle [SEARCH_TERM]",many_results:"[COUNT] tulosta haulle [SEARCH_TERM]",one_result:"[COUNT] tulos haulle [SEARCH_TERM]",alt_search:"Ei tuloksia haulle [SEARCH_TERM]. N\xE4ytet\xE4\xE4n tulokset sen sijaan haulle [DIFFERENT_TERM]",search_suggestion:"Ei tuloksia haulle [SEARCH_TERM]. Kokeile jotain seuraavista:",searching:"Haetaan [SEARCH_TERM]..."},hr={thanks_to:cr,comments:_r,direction:fr,strings:dr};var Tt={};v(Tt,{comments:()=>pr,default:()=>br,direction:()=>gr,strings:()=>Er,thanks_to:()=>mr});var mr="Nicolas Friedli <nicolas@theologique.ch>",pr="",gr="ltr",Er={placeholder:"Rechercher",clear_search:"Nettoyer",load_more:"Charger plus de r\xE9sultats",search_label:"Recherche sur ce site",filters_label:"Filtres",zero_results:"Pas de r\xE9sultat pour [SEARCH_TERM]",many_results:"[COUNT] r\xE9sultats pour [SEARCH_TERM]",one_result:"[COUNT] r\xE9sultat pour [SEARCH_TERM]",alt_search:"Pas de r\xE9sultat pour [SEARCH_TERM]. Montre les r\xE9sultats pour [DIFFERENT_TERM] \xE0 la place",search_suggestion:"Pas de r\xE9sultat pour [SEARCH_TERM]. Essayer une des recherches suivantes:",searching:"Recherche [SEARCH_TERM]..."},br={thanks_to:mr,comments:pr,direction:gr,strings:Er};var kt={};v(kt,{comments:()=>Tr,default:()=>yr,direction:()=>kr,strings:()=>Cr,thanks_to:()=>Rr});var Rr="Pablo Villaverde <https://github.com/pvillaverde>",Tr="",kr="ltr",Cr={placeholder:"Buscar",clear_search:"Limpar",load_more:"Ver m\xE1is resultados",search_label:"Buscar neste sitio",filters_label:"Filtros",zero_results:"Non se atoparon resultados para [SEARCH_TERM]",many_results:"[COUNT] resultados atopados para [SEARCH_TERM]",one_result:"[COUNT] resultado atopado para [SEARCH_TERM]",alt_search:"Non se atoparon resultados para [SEARCH_TERM]. Amosando no seu lugar resultados para [DIFFERENT_TERM]",search_suggestion:"Non se atoparon resultados para [SEARCH_TERM]. Probe unha das seguintes pesquisas:",searching:"Buscando [SEARCH_TERM]..."},yr={thanks_to:Rr,comments:Tr,direction:kr,strings:Cr};var Ct={};v(Ct,{comments:()=>vr,default:()=>wr,direction:()=>Mr,strings:()=>Ar,thanks_to:()=>Sr});var Sr="Amit Yadav <amit@thetechbasket.com>",vr="",Mr="ltr",Ar={placeholder:"\u0916\u094B\u091C\u0947\u0902",clear_search:"\u0938\u093E\u092B \u0915\u0930\u0947\u0902",load_more:"\u0914\u0930 \u0905\u0927\u093F\u0915 \u092A\u0930\u093F\u0923\u093E\u092E \u0932\u094B\u0921 \u0915\u0930\u0947\u0902",search_label:"\u0907\u0938 \u0938\u093E\u0907\u091F \u092E\u0947\u0902 \u0916\u094B\u091C\u0947\u0902",filters_label:"\u092B\u093C\u093F\u0932\u094D\u091F\u0930",zero_results:"\u0915\u094B\u0908 \u092A\u0930\u093F\u0923\u093E\u092E [SEARCH_TERM] \u0915\u0947 \u0932\u093F\u090F \u0928\u0939\u0940\u0902 \u092E\u093F\u0932\u093E",many_results:"[COUNT] \u092A\u0930\u093F\u0923\u093E\u092E [SEARCH_TERM] \u0915\u0947 \u0932\u093F\u090F \u092E\u093F\u0932\u0947",one_result:"[COUNT] \u092A\u0930\u093F\u0923\u093E\u092E [SEARCH_TERM] \u0915\u0947 \u0932\u093F\u090F \u092E\u093F\u0932\u093E",alt_search:"[SEARCH_TERM] \u0915\u0947 \u0932\u093F\u090F \u0915\u094B\u0908 \u092A\u0930\u093F\u0923\u093E\u092E \u0928\u0939\u0940\u0902 \u092E\u093F\u0932\u093E\u0964 \u0907\u0938\u0915\u0947 \u092C\u091C\u093E\u092F [DIFFERENT_TERM] \u0915\u0947 \u0932\u093F\u090F \u092A\u0930\u093F\u0923\u093E\u092E \u0926\u093F\u0916\u093E \u0930\u0939\u093E \u0939\u0948",search_suggestion:"[SEARCH_TERM] \u0915\u0947 \u0932\u093F\u090F \u0915\u094B\u0908 \u092A\u0930\u093F\u0923\u093E\u092E \u0928\u0939\u0940\u0902 \u092E\u093F\u0932\u093E\u0964 \u0928\u093F\u092E\u094D\u0928\u0932\u093F\u0916\u093F\u0924 \u0916\u094B\u091C\u094B\u0902 \u092E\u0947\u0902 \u0938\u0947 \u0915\u094B\u0908 \u090F\u0915 \u0906\u091C\u093C\u092E\u093E\u090F\u0902:",searching:"[SEARCH_TERM] \u0915\u0940 \u0916\u094B\u091C \u0915\u0940 \u091C\u093E \u0930\u0939\u0940 \u0939\u0948..."},wr={thanks_to:Sr,comments:vr,direction:Mr,strings:Ar};var yt={};v(yt,{comments:()=>Hr,default:()=>jr,direction:()=>Nr,strings:()=>Or,thanks_to:()=>Fr});var Fr="Diomed <https://github.com/diomed>",Hr="",Nr="ltr",Or={placeholder:"Tra\u017Ei",clear_search:"O\u010Disti",load_more:"U\u010Ditaj vi\u0161e rezultata",search_label:"Pretra\u017Ei ovu stranicu",filters_label:"Filteri",zero_results:"Nema rezultata za [SEARCH_TERM]",many_results:"[COUNT] rezultata za [SEARCH_TERM]",one_result:"[COUNT] rezultat za [SEARCH_TERM]",alt_search:"Nema rezultata za [SEARCH_TERM]. Prikazujem rezultate za [DIFFERENT_TERM]",search_suggestion:"Nema rezultata za [SEARCH_TERM]. Poku\u0161aj s jednom od ovih pretraga:",searching:"Pretra\u017Eujem [SEARCH_TERM]..."},jr={thanks_to:Fr,comments:Hr,direction:Nr,strings:Or};var St={};v(St,{comments:()=>Dr,default:()=>Pr,direction:()=>Ur,strings:()=>Ir,thanks_to:()=>zr});var zr="Adam Laki <info@adamlaki.com>",Dr="",Ur="ltr",Ir={placeholder:"Keres\xE9s",clear_search:"T\xF6rl\xE9s",load_more:"Tov\xE1bbi tal\xE1latok bet\xF6lt\xE9se",search_label:"Keres\xE9s az oldalon",filters_label:"Sz\u0171r\xE9s",zero_results:"Nincs tal\xE1lat a(z) [SEARCH_TERM] kifejez\xE9sre",many_results:"[COUNT] db tal\xE1lat a(z) [SEARCH_TERM] kifejez\xE9sre",one_result:"[COUNT] db tal\xE1lat a(z) [SEARCH_TERM] kifejez\xE9sre",alt_search:"Nincs tal\xE1lat a(z) [SEARCH_TERM] kifejez\xE9sre. Tal\xE1latok mutat\xE1sa ink\xE1bb a(z) [DIFFERENT_TERM] kifejez\xE9sre",search_suggestion:"Nincs tal\xE1lat a(z) [SEARCH_TERM] kifejez\xE9sre. Pr\xF3b\xE1ld meg a k\xF6vetkez\u0151 keres\xE9sek egyik\xE9t:",searching:"Keres\xE9s a(z) [SEARCH_TERM] kifejez\xE9sre..."},Pr={thanks_to:zr,comments:Dr,direction:Ur,strings:Ir};var vt={};v(vt,{comments:()=>qr,default:()=>Vr,direction:()=>Br,strings:()=>Wr,thanks_to:()=>Lr});var Lr="Nixentric",qr="",Br="ltr",Wr={placeholder:"Cari",clear_search:"Bersihkan",load_more:"Muat lebih banyak hasil",search_label:"Telusuri situs ini",filters_label:"Filter",zero_results:"[SEARCH_TERM] tidak ditemukan",many_results:"Ditemukan [COUNT] hasil untuk [SEARCH_TERM]",one_result:"Ditemukan [COUNT] hasil untuk [SEARCH_TERM]",alt_search:"[SEARCH_TERM] tidak ditemukan. Menampilkan hasil [DIFFERENT_TERM] sebagai gantinya",search_suggestion:"[SEARCH_TERM] tidak ditemukan. Coba salah satu pencarian berikut ini:",searching:"Mencari [SEARCH_TERM]..."},Vr={thanks_to:Lr,comments:qr,direction:Br,strings:Wr};var Mt={};v(Mt,{comments:()=>Kr,default:()=>Xr,direction:()=>Jr,strings:()=>Yr,thanks_to:()=>Gr});var Gr="Cosette Bruhns Alonso, Andrew Janco <apjanco@upenn.edu>",Kr="",Jr="ltr",Yr={placeholder:"Cerca",clear_search:"Cancella la cronologia",load_more:"Mostra pi\xF9 risultati",search_label:"Cerca nel sito",filters_label:"Filtri di ricerca",zero_results:"Nessun risultato per [SEARCH_TERM]",many_results:"[COUNT] risultati per [SEARCH_TERM]",one_result:"[COUNT] risultato per [SEARCH_TERM]",alt_search:"Nessun risultato per [SEARCH_TERM]. Mostrando risultati per [DIFFERENT_TERM] come alternativa.",search_suggestion:"Nessun risultato per [SEARCH_TERM]. Prova una delle seguenti ricerche:",searching:"Cercando [SEARCH_TERM]..."},Xr={thanks_to:Gr,comments:Kr,direction:Jr,strings:Yr};var At={};v(At,{comments:()=>Qr,default:()=>el,direction:()=>xr,strings:()=>$r,thanks_to:()=>Zr});var Zr="Tate",Qr="",xr="ltr",$r={placeholder:"\u691C\u7D22",clear_search:"\u6D88\u3059",load_more:"\u3082\u3063\u3068\u8AAD\u307F\u8FBC\u3080",search_label:"\u3053\u306E\u30B5\u30A4\u30C8\u3092\u691C\u7D22",filters_label:"\u30D5\u30A3\u30EB\u30BF",zero_results:"[SEARCH_TERM]\u306E\u691C\u7D22\u306B\u4E00\u81F4\u3059\u308B\u4EF6\u306F\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F",many_results:"[SEARCH_TERM]\u306E[COUNT]\u4EF6\u306E\u691C\u7D22\u7D50\u679C",one_result:"[SEARCH_TERM]\u306E[COUNT]\u4EF6\u306E\u691C\u7D22\u7D50\u679C",alt_search:"[SEARCH_TERM]\u306E\u691C\u7D22\u306B\u4E00\u81F4\u3059\u308B\u4EF6\u306F\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002[DIFFERENT_TERM]\u306E\u691C\u7D22\u7D50\u679C\u3092\u8868\u793A\u3057\u3066\u3044\u307E\u3059",search_suggestion:"[SEARCH_TERM]\u306E\u691C\u7D22\u306B\u4E00\u81F4\u3059\u308B\u4EF6\u306F\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u6B21\u306E\u3044\u305A\u308C\u304B\u306E\u691C\u7D22\u3092\u8A66\u3057\u3066\u304F\u3060\u3055\u3044",searching:"[SEARCH_TERM]\u3092\u691C\u7D22\u3057\u3066\u3044\u307E\u3059"},el={thanks_to:Zr,comments:Qr,direction:xr,strings:$r};var wt={};v(wt,{comments:()=>nl,default:()=>ll,direction:()=>sl,strings:()=>rl,thanks_to:()=>tl});var tl="",nl="",sl="ltr",rl={placeholder:"Rapu",clear_search:"Whakakore",load_more:"Whakauta \u0113tahi otinga k\u0113",search_label:"Rapu",filters_label:"T\u0101tari",zero_results:"Otinga kore ki [SEARCH_TERM]",many_results:"[COUNT] otinga ki [SEARCH_TERM]",one_result:"[COUNT] otinga ki [SEARCH_TERM]",alt_search:"Otinga kore ki [SEARCH_TERM]. Otinga k\u0113 ki [DIFFERENT_TERM]",search_suggestion:"Otinga kore ki [SEARCH_TERM]. whakam\u0101tau ki ng\u0101 mea atu:",searching:"Rapu ki [SEARCH_TERM]..."},ll={thanks_to:tl,comments:nl,direction:sl,strings:rl};var Ft={};v(Ft,{comments:()=>al,default:()=>cl,direction:()=>ol,strings:()=>ul,thanks_to:()=>il});var il="Paul van Brouwershaven",al="",ol="ltr",ul={placeholder:"Zoeken",clear_search:"Reset",load_more:"Meer resultaten laden",search_label:"Doorzoek deze site",filters_label:"Filters",zero_results:"Geen resultaten voor [SEARCH_TERM]",many_results:"[COUNT] resultaten voor [SEARCH_TERM]",one_result:"[COUNT] resultaat voor [SEARCH_TERM]",alt_search:"Geen resultaten voor [SEARCH_TERM]. In plaats daarvan worden resultaten voor [DIFFERENT_TERM] weergegeven",search_suggestion:"Geen resultaten voor [SEARCH_TERM]. Probeer een van de volgende zoekopdrachten:",searching:"Zoeken naar [SEARCH_TERM]..."},cl={thanks_to:il,comments:al,direction:ol,strings:ul};var Ht={};v(Ht,{comments:()=>fl,default:()=>ml,direction:()=>dl,strings:()=>hl,thanks_to:()=>_l});var _l="Christopher Wingate",fl="",dl="ltr",hl={placeholder:"S\xF8k",clear_search:"Fjern",load_more:"Last flere resultater",search_label:"S\xF8k p\xE5 denne siden",filters_label:"Filtre",zero_results:"Ingen resultater for [SEARCH_TERM]",many_results:"[COUNT] resultater for [SEARCH_TERM]",one_result:"[COUNT] resultat for [SEARCH_TERM]",alt_search:"Ingen resultater for [SEARCH_TERM]. Viser resultater for [DIFFERENT_TERM] i stedet",search_suggestion:"Ingen resultater for [SEARCH_TERM]. Pr\xF8v en av disse s\xF8keordene i stedet:",searching:"S\xF8ker etter [SEARCH_TERM]"},ml={thanks_to:_l,comments:fl,direction:dl,strings:hl};var Nt={};v(Nt,{comments:()=>gl,default:()=>Rl,direction:()=>El,strings:()=>bl,thanks_to:()=>pl});var pl="",gl="",El="ltr",bl={placeholder:"Szukaj",clear_search:"Wyczy\u015B\u0107",load_more:"Za\u0142aduj wi\u0119cej",search_label:"Przeszukaj t\u0119 stron\u0119",filters_label:"Filtry",zero_results:"Brak wynik\xF3w dla [SEARCH_TERM]",many_results:"[COUNT] wynik\xF3w dla [SEARCH_TERM]",one_result:"[COUNT] wynik dla [SEARCH_TERM]",alt_search:"Brak wynik\xF3w dla [SEARCH_TERM]. Wy\u015Bwietlam wyniki dla [DIFFERENT_TERM]",search_suggestion:"Brak wynik\xF3w dla [SEARCH_TERM]. Pokrewne wyniki wyszukiwania:",searching:"Szukam [SEARCH_TERM]..."},Rl={thanks_to:pl,comments:gl,direction:El,strings:bl};var Ot={};v(Ot,{comments:()=>kl,default:()=>Sl,direction:()=>Cl,strings:()=>yl,thanks_to:()=>Tl});var Tl="Jonatah",kl="",Cl="ltr",yl={placeholder:"Pesquisar",clear_search:"Limpar",load_more:"Ver mais resultados",search_label:"Pesquisar",filters_label:"Filtros",zero_results:"Nenhum resultado encontrado para [SEARCH_TERM]",many_results:"[COUNT] resultados encontrados para [SEARCH_TERM]",one_result:"[COUNT] resultado encontrado para [SEARCH_TERM]",alt_search:"Nenhum resultado encontrado para [SEARCH_TERM]. Exibindo resultados para [DIFFERENT_TERM]",search_suggestion:"Nenhum resultado encontrado para [SEARCH_TERM]. Tente uma das seguintes pesquisas:",searching:"Pesquisando por [SEARCH_TERM]..."},Sl={thanks_to:Tl,comments:kl,direction:Cl,strings:yl};var jt={};v(jt,{comments:()=>Ml,default:()=>Fl,direction:()=>Al,strings:()=>wl,thanks_to:()=>vl});var vl="Aleksandr Gordeev",Ml="",Al="ltr",wl={placeholder:"\u041F\u043E\u0438\u0441\u043A",clear_search:"\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u043F\u043E\u043B\u0435",load_more:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0435\u0449\u0435",search_label:"\u041F\u043E\u0438\u0441\u043A \u043F\u043E \u0441\u0430\u0439\u0442\u0443",filters_label:"\u0424\u0438\u043B\u044C\u0442\u0440\u044B",zero_results:"\u041D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443: [SEARCH_TERM]",many_results:"[COUNT] \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u043E\u0432 \u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443: [SEARCH_TERM]",one_result:"[COUNT] \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443: [SEARCH_TERM]",alt_search:"\u041D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443: [SEARCH_TERM]. \u041F\u043E\u043A\u0430\u0437\u0430\u043D\u044B \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u044B \u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443: [DIFFERENT_TERM]",search_suggestion:"\u041D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443: [SEARCH_TERM]. \u041F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u043E\u0434\u0438\u043D \u0438\u0437 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0445 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432",searching:"\u041F\u043E\u0438\u0441\u043A \u043F\u043E \u0437\u0430\u043F\u0440\u043E\u0441\u0443: [SEARCH_TERM]"},Fl={thanks_to:vl,comments:Ml,direction:Al,strings:wl};var zt={};v(zt,{comments:()=>Nl,default:()=>zl,direction:()=>Ol,strings:()=>jl,thanks_to:()=>Hl});var Hl="Andrija Sagicc",Nl="",Ol="ltr",jl={placeholder:"\u041F\u0440\u0435\u0442\u0440\u0430\u0433\u0430",clear_search:"\u0411\u0440\u0438\u0441\u0430\u045A\u0435",load_more:"\u041F\u0440\u0438\u043A\u0430\u0437 \u0432\u0438\u0448\u0435 \u0440\u0435\u0437\u0443\u043B\u0442\u0430\u0442\u0430",search_label:"\u041F\u0440\u0435\u0442\u0440\u0430\u0433\u0430 \u0441\u0430\u0458\u0442\u0430",filters_label:"\u0424\u0438\u043B\u0442\u0435\u0440\u0438",zero_results:"\u041D\u0435\u043C\u0430 \u0440\u0435\u0437\u0443\u043B\u0442\u0430\u0442\u0430 \u0437\u0430 [SEARCH_TERM]",many_results:"[COUNT] \u0440\u0435\u0437\u0443\u043B\u0442\u0430\u0442\u0430 \u0437\u0430 [SEARCH_TERM]",one_result:"[COUNT] \u0440\u0435\u0437\u0443\u043B\u0442\u0430\u0442\u0430 \u0437\u0430 [SEARCH_TERM]",alt_search:"\u041D\u0435\u043C\u0430 \u0440\u0435\u0437\u0443\u043B\u0442\u0430\u0442\u0430 \u0437\u0430 [SEARCH_TERM]. \u041F\u0440\u0438\u043A\u0430\u0437 \u0434\u043E\u0434\u0430\u0442\u043D\u0438\u043A \u0440\u0435\u0437\u0443\u043B\u0442\u0430\u0442\u0430 \u0437\u0430 [DIFFERENT_TERM]",search_suggestion:"\u041D\u0435\u043C\u0430 \u0440\u0435\u0437\u0443\u043B\u0442\u0430\u0442\u0430 \u0437\u0430 [SEARCH_TERM]. \u041F\u043E\u043A\u0443\u0448\u0430\u0458\u0442\u0435 \u0441\u0430 \u043D\u0435\u043A\u043E\u043C \u043E\u0434 \u0441\u043B\u0435\u0434\u0435\u045B\u0438\u0445 \u043F\u0440\u0435\u0442\u0440\u0430\u0433\u0430:",searching:"\u041F\u0440\u0435\u0442\u0440\u0430\u0433\u0430 \u0442\u0435\u0440\u043C\u0438\u043D\u0430 [SEARCH_TERM]..."},zl={thanks_to:Hl,comments:Nl,direction:Ol,strings:jl};var Dt={};v(Dt,{comments:()=>Ul,default:()=>Ll,direction:()=>Il,strings:()=>Pl,thanks_to:()=>Dl});var Dl="Montazar Al-Jaber <montazar@nanawee.tech>",Ul="",Il="ltr",Pl={placeholder:"S\xF6k",clear_search:"Rensa",load_more:"Visa fler tr\xE4ffar",search_label:"S\xF6k p\xE5 denna sida",filters_label:"Filter",zero_results:"[SEARCH_TERM] gav inga tr\xE4ffar",many_results:"[SEARCH_TERM] gav [COUNT] tr\xE4ffar",one_result:"[SEARCH_TERM] gav [COUNT] tr\xE4ff",alt_search:"[SEARCH_TERM] gav inga tr\xE4ffar. Visar resultat f\xF6r [DIFFERENT_TERM] ist\xE4llet",search_suggestion:"[SEARCH_TERM] gav inga tr\xE4ffar. F\xF6rs\xF6k igen med en av f\xF6ljande s\xF6kord:",searching:"S\xF6ker efter [SEARCH_TERM]..."},Ll={thanks_to:Dl,comments:Ul,direction:Il,strings:Pl};var Ut={};v(Ut,{comments:()=>Bl,default:()=>Gl,direction:()=>Wl,strings:()=>Vl,thanks_to:()=>ql});var ql="",Bl="",Wl="ltr",Vl={placeholder:"\u0BA4\u0BC7\u0B9F\u0BC1\u0B95",clear_search:"\u0B85\u0BB4\u0BBF\u0B95\u0BCD\u0B95\u0BC1\u0B95",load_more:"\u0BAE\u0BC7\u0BB2\u0BC1\u0BAE\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0BC1\u0B95\u0BB3\u0BC8\u0B95\u0BCD \u0B95\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B95",search_label:"\u0B87\u0BA8\u0BCD\u0BA4 \u0BA4\u0BB3\u0BA4\u0BCD\u0BA4\u0BBF\u0BB2\u0BCD \u0BA4\u0BC7\u0B9F\u0BC1\u0B95",filters_label:"\u0BB5\u0B9F\u0BBF\u0B95\u0B9F\u0BCD\u0B9F\u0BB2\u0BCD\u0B95\u0BB3\u0BCD",zero_results:"[SEARCH_TERM] \u0B95\u0BCD\u0B95\u0BBE\u0BA9 \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0BC1\u0B95\u0BB3\u0BCD \u0B87\u0BB2\u0BCD\u0BB2\u0BC8",many_results:"[SEARCH_TERM] \u0B95\u0BCD\u0B95\u0BBE\u0BA9 [COUNT] \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0BC1\u0B95\u0BB3\u0BCD",one_result:"[SEARCH_TERM] \u0B95\u0BCD\u0B95\u0BBE\u0BA9 \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0BC1",alt_search:"[SEARCH_TERM] \u0B87\u0BA4\u0BCD\u0BA4\u0BC7\u0B9F\u0BB2\u0BC1\u0B95\u0BCD\u0B95\u0BBE\u0BA9 \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0BC1\u0B95\u0BB3\u0BCD \u0B87\u0BB2\u0BCD\u0BB2\u0BC8, \u0B87\u0BA8\u0BCD\u0BA4 \u0BA4\u0BC7\u0B9F\u0BB2\u0BCD\u0B95\u0BB3\u0BC1\u0B95\u0BCD\u0B95\u0BBE\u0BA9 \u0B92\u0BA4\u0BCD\u0BA4 \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0BC1\u0B95\u0BB3\u0BCD [DIFFERENT_TERM]",search_suggestion:"[SEARCH_TERM] \u0B87\u0BA4\u0BCD \u0BA4\u0BC7\u0B9F\u0BB2\u0BC1\u0B95\u0BCD\u0B95\u0BBE\u0BA9 \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0BC1\u0B95\u0BB3\u0BCD \u0B87\u0BB2\u0BCD\u0BB2\u0BC8.\u0B87\u0BA4\u0BB1\u0BCD\u0B95\u0BC1 \u0BAA\u0BA4\u0BBF\u0BB2\u0BC0\u0B9F\u0BBE\u0BA9 \u0BA4\u0BC7\u0B9F\u0BB2\u0BCD\u0B95\u0BB3\u0BC8 \u0BA4\u0BC7\u0B9F\u0BC1\u0B95:",searching:"[SEARCH_TERM] \u0BA4\u0BC7\u0B9F\u0BAA\u0BCD\u0BAA\u0B9F\u0BC1\u0B95\u0BBF\u0BA9\u0BCD\u0BB1\u0BA4\u0BC1"},Gl={thanks_to:ql,comments:Bl,direction:Wl,strings:Vl};var It={};v(It,{comments:()=>Jl,default:()=>Zl,direction:()=>Yl,strings:()=>Xl,thanks_to:()=>Kl});var Kl="Taylan \xD6zg\xFCr Bildik",Jl="",Yl="ltr",Xl={placeholder:"Ara\u015Ft\u0131r",clear_search:"Temizle",load_more:"Daha fazla sonu\xE7",search_label:"Site genelinde arama",filters_label:"Filtreler",zero_results:"[SEARCH_TERM] i\xE7in sonu\xE7 yok",many_results:"[SEARCH_TERM] i\xE7in [COUNT] sonu\xE7 bulundu",one_result:"[SEARCH_TERM] i\xE7in [COUNT] sonu\xE7 bulundu",alt_search:"[SEARCH_TERM] i\xE7in sonu\xE7 yok. Bunun yerine [DIFFERENT_TERM] i\xE7in sonu\xE7lar g\xF6steriliyor",search_suggestion:"[SEARCH_TERM] i\xE7in sonu\xE7 yok. Alternatif olarak a\u015Fa\u011F\u0131daki kelimelerden birini deneyebilirsiniz:",searching:"[SEARCH_TERM] ara\u015Ft\u0131r\u0131l\u0131yor..."},Zl={thanks_to:Kl,comments:Jl,direction:Yl,strings:Xl};var Pt={};v(Pt,{comments:()=>xl,default:()=>ti,direction:()=>$l,strings:()=>ei,thanks_to:()=>Ql});var Ql="Long Nhat Nguyen",xl="",$l="ltr",ei={placeholder:"T\xECm ki\u1EBFm",clear_search:"X\xF3a",load_more:"Nhi\u1EC1u k\u1EBFt qu\u1EA3 h\u01A1n",search_label:"T\xECm ki\u1EBFm trong trang n\xE0y",filters_label:"B\u1ED9 l\u1ECDc",zero_results:"Kh\xF4ng t\xECm th\u1EA5y k\u1EBFt qu\u1EA3 cho [SEARCH_TERM]",many_results:"[COUNT] k\u1EBFt qu\u1EA3 cho [SEARCH_TERM]",one_result:"[COUNT] k\u1EBFt qu\u1EA3 cho [SEARCH_TERM]",alt_search:"Kh\xF4ng t\xECm th\u1EA5y k\u1EBFt qu\u1EA3 cho [SEARCH_TERM]. Ki\u1EC3m th\u1ECB k\u1EBFt qu\u1EA3 thay th\u1EBF v\u1EDBi [DIFFERENT_TERM]",search_suggestion:"Kh\xF4ng t\xECm th\u1EA5y k\u1EBFt qu\u1EA3 cho [SEARCH_TERM]. Th\u1EED m\u1ED9t trong c\xE1c t\xECm ki\u1EBFm:",searching:"\u0110ang t\xECm ki\u1EBFm cho [SEARCH_TERM]..."},ti={thanks_to:Ql,comments:xl,direction:$l,strings:ei};var Lt={};v(Lt,{comments:()=>si,default:()=>ii,direction:()=>ri,strings:()=>li,thanks_to:()=>ni});var ni="Amber Song",si="",ri="ltr",li={placeholder:"\u641C\u7D22",clear_search:"\u6E05\u9664",load_more:"\u52A0\u8F7D\u66F4\u591A\u7ED3\u679C",search_label:"\u7AD9\u5185\u641C\u7D22",filters_label:"\u7B5B\u9009",zero_results:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C",many_results:"\u627E\u5230 [COUNT] \u4E2A [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C",one_result:"\u627E\u5230 [COUNT] \u4E2A [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C",alt_search:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C\u3002\u6539\u4E3A\u663E\u793A [DIFFERENT_TERM] \u7684\u76F8\u5173\u7ED3\u679C",search_suggestion:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C\u3002\u8BF7\u5C1D\u8BD5\u4EE5\u4E0B\u641C\u7D22\u3002",searching:"\u6B63\u5728\u641C\u7D22 [SEARCH_TERM]..."},ii={thanks_to:ni,comments:si,direction:ri,strings:li};var qt={};v(qt,{comments:()=>oi,default:()=>_i,direction:()=>ui,strings:()=>ci,thanks_to:()=>ai});var ai="Amber Song",oi="",ui="ltr",ci={placeholder:"\u641C\u7D22",clear_search:"\u6E05\u9664",load_more:"\u52A0\u8F09\u66F4\u591A\u7D50\u679C",search_label:"\u7AD9\u5167\u641C\u7D22",filters_label:"\u7BE9\u9078",zero_results:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u95DC\u7D50\u679C",many_results:"\u627E\u5230 [COUNT] \u500B [SEARCH_TERM] \u7684\u76F8\u95DC\u7D50\u679C",one_result:"\u627E\u5230 [COUNT] \u500B [SEARCH_TERM] \u7684\u76F8\u95DC\u7D50\u679C",alt_search:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u95DC\u7D50\u679C\u3002\u6539\u70BA\u986F\u793A [DIFFERENT_TERM] \u7684\u76F8\u95DC\u7D50\u679C",search_suggestion:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u95DC\u7D50\u679C\u3002\u8ACB\u5617\u8A66\u4EE5\u4E0B\u641C\u7D22\u3002",searching:"\u6B63\u5728\u641C\u7D22 [SEARCH_TERM]..."},_i={thanks_to:ai,comments:oi,direction:ui,strings:ci};var Bt={};v(Bt,{comments:()=>di,default:()=>pi,direction:()=>hi,strings:()=>mi,thanks_to:()=>fi});var fi="Amber Song",di="",hi="ltr",mi={placeholder:"\u641C\u7D22",clear_search:"\u6E05\u9664",load_more:"\u52A0\u8F7D\u66F4\u591A\u7ED3\u679C",search_label:"\u7AD9\u5185\u641C\u7D22",filters_label:"\u7B5B\u9009",zero_results:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C",many_results:"\u627E\u5230 [COUNT] \u4E2A [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C",one_result:"\u627E\u5230 [COUNT] \u4E2A [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C",alt_search:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C\u3002\u6539\u4E3A\u663E\u793A [DIFFERENT_TERM] \u7684\u76F8\u5173\u7ED3\u679C",search_suggestion:"\u672A\u627E\u5230 [SEARCH_TERM] \u7684\u76F8\u5173\u7ED3\u679C\u3002\u8BF7\u5C1D\u8BD5\u4EE5\u4E0B\u641C\u7D22\u3002",searching:"\u6B63\u5728\u641C\u7D22 [SEARCH_TERM]..."},pi={thanks_to:fi,comments:di,direction:hi,strings:mi};var gi=[dt,ht,mt,pt,gt,Et,bt,Rt,Tt,kt,Ct,yt,St,vt,Mt,At,wt,Ft,Ht,Nt,Ot,jt,zt,Dt,Ut,It,Pt,Lt,qt,Bt],Un=gi,In=["../../translations/af.json","../../translations/bn.json","../../translations/ca.json","../../translations/da.json","../../translations/de.json","../../translations/en.json","../../translations/es.json","../../translations/fi.json","../../translations/fr.json","../../translations/gl.json","../../translations/hi.json","../../translations/hr.json","../../translations/hu.json","../../translations/id.json","../../translations/it.json","../../translations/ja.json","../../translations/mi.json","../../translations/nl.json","../../translations/no.json","../../translations/pl.json","../../translations/pt.json","../../translations/ru.json","../../translations/sr.json","../../translations/sv.json","../../translations/ta.json","../../translations/tr.json","../../translations/vi.json","../../translations/zh-cn.json","../../translations/zh-tw.json","../../translations/zh.json"];function Pn(n,e,t){let s=n.slice();return s[48]=e[t],s}function Ln(n){let e,t,s;function r(i){n[34](i)}let l={show_empty_filters:n[4],available_filters:n[16],translate:n[18],automatic_translations:n[17],translations:n[5]};return n[7]!==void 0&&(l.selected_filters=n[7]),e=new Dn({props:l}),re.push(()=>an(e,"selected_filters",r)),{c(){Ze(e.$$.fragment)},m(i,a){he(e,i,a),s=!0},p(i,a){let o={};a[0]&16&&(o.show_empty_filters=i[4]),a[0]&65536&&(o.available_filters=i[16]),a[0]&131072&&(o.automatic_translations=i[17]),a[0]&32&&(o.translations=i[5]),!t&&a[0]&128&&(t=!0,o.selected_filters=i[7],nn(()=>t=!1)),e.$set(o)},i(i){s||(z(e.$$.fragment,i),s=!0)},o(i){I(e.$$.fragment,i),s=!1},d(i){oe(e,i)}}}function qn(n){let e,t,s,r,l=[Ri,bi],i=[];function a(o,h){return o[12]?0:1}return t=a(n,[-1,-1]),s=i[t]=l[t](n),{c(){e=k("div"),s.c(),p(e,"class","pagefind-ui__results-area svelte-e9gkc3")},m(o,h){y(o,e,h),i[t].m(e,null),r=!0},p(o,h){let _=t;t=a(o,h),t===_?i[t].p(o,h):(ie(),I(i[_],1,1,()=>{i[_]=null}),ae(),s=i[t],s?s.p(o,h):(s=i[t]=l[t](o),s.c()),z(s,1),s.m(e,null))},i(o){r||(z(s),r=!0)},o(o){I(s),r=!1},d(o){o&&C(e),i[t].d()}}}function bi(n){let e,t,s,r=[],l=new Map,i,a,o;function h(m,d){return m[11].results.length===0?Ci:m[11].results.length===1?ki:Ti}let _=h(n,[-1,-1]),f=_(n),c=n[11].results.slice(0,n[15]),E=m=>m[48].id;for(let m=0;m<c.length;m+=1){let d=Pn(n,c,m),R=E(d);l.set(R,r[m]=Bn(R,d))}let u=n[11].results.length>n[15]&&Wn(n);return{c(){e=k("p"),f.c(),t=M(),s=k("ol");for(let m=0;m<r.length;m+=1)r[m].c();i=M(),u&&u.c(),a=x(),p(e,"class","pagefind-ui__message svelte-e9gkc3"),p(s,"class","pagefind-ui__results svelte-e9gkc3")},m(m,d){y(m,e,d),f.m(e,null),y(m,t,d),y(m,s,d);for(let R=0;R<r.length;R+=1)r[R]&&r[R].m(s,null);y(m,i,d),u&&u.m(m,d),y(m,a,d),o=!0},p(m,d){_===(_=h(m,d))&&f?f.p(m,d):(f.d(1),f=_(m),f&&(f.c(),f.m(e,null))),d[0]&34830&&(c=m[11].results.slice(0,m[15]),ie(),r=ln(r,d,E,1,m,c,l,s,rn,Bn,null,Pn),ae()),m[11].results.length>m[15]?u?u.p(m,d):(u=Wn(m),u.c(),u.m(a.parentNode,a)):u&&(u.d(1),u=null)},i(m){if(!o){for(let d=0;d<c.length;d+=1)z(r[d]);o=!0}},o(m){for(let d=0;d<r.length;d+=1)I(r[d]);o=!1},d(m){m&&C(e),f.d(),m&&C(t),m&&C(s);for(let d=0;d<r.length;d+=1)r[d].d();m&&C(i),u&&u.d(m),m&&C(a)}}}function Ri(n){let e,t=n[14]&&Vn(n);return{c(){t&&t.c(),e=x()},m(s,r){t&&t.m(s,r),y(s,e,r)},p(s,r){s[14]?t?t.p(s,r):(t=Vn(s),t.c(),t.m(e.parentNode,e)):t&&(t.d(1),t=null)},i:j,o:j,d(s){t&&t.d(s),s&&C(e)}}}function Ti(n){let e=n[18]("many_results",n[17],n[5]).replace(/\[SEARCH_TERM\]/,n[14]).replace(/\[COUNT\]/,new Intl.NumberFormat(n[5].language).format(n[11].results.length))+"",t;return{c(){t=A(e)},m(s,r){y(s,t,r)},p(s,r){r[0]&149536&&e!==(e=s[18]("many_results",s[17],s[5]).replace(/\[SEARCH_TERM\]/,s[14]).replace(/\[COUNT\]/,new Intl.NumberFormat(s[5].language).format(s[11].results.length))+"")&&N(t,e)},d(s){s&&C(t)}}}function ki(n){let e=n[18]("one_result",n[17],n[5]).replace(/\[SEARCH_TERM\]/,n[14]).replace(/\[COUNT\]/,new Intl.NumberFormat(n[5].language).format(1))+"",t;return{c(){t=A(e)},m(s,r){y(s,t,r)},p(s,r){r[0]&147488&&e!==(e=s[18]("one_result",s[17],s[5]).replace(/\[SEARCH_TERM\]/,s[14]).replace(/\[COUNT\]/,new Intl.NumberFormat(s[5].language).format(1))+"")&&N(t,e)},d(s){s&&C(t)}}}function Ci(n){let e=n[18]("zero_results",n[17],n[5]).replace(/\[SEARCH_TERM\]/,n[14])+"",t;return{c(){t=A(e)},m(s,r){y(s,t,r)},p(s,r){r[0]&147488&&e!==(e=s[18]("zero_results",s[17],s[5]).replace(/\[SEARCH_TERM\]/,s[14])+"")&&N(t,e)},d(s){s&&C(t)}}}function yi(n){let e,t;return e=new gn({props:{show_images:n[1],process_result:n[3],result:n[48]}}),{c(){Ze(e.$$.fragment)},m(s,r){he(e,s,r),t=!0},p(s,r){let l={};r[0]&2&&(l.show_images=s[1]),r[0]&8&&(l.process_result=s[3]),r[0]&34816&&(l.result=s[48]),e.$set(l)},i(s){t||(z(e.$$.fragment,s),t=!0)},o(s){I(e.$$.fragment,s),t=!1},d(s){oe(e,s)}}}function Si(n){let e,t;return e=new An({props:{show_images:n[1],process_result:n[3],result:n[48]}}),{c(){Ze(e.$$.fragment)},m(s,r){he(e,s,r),t=!0},p(s,r){let l={};r[0]&2&&(l.show_images=s[1]),r[0]&8&&(l.process_result=s[3]),r[0]&34816&&(l.result=s[48]),e.$set(l)},i(s){t||(z(e.$$.fragment,s),t=!0)},o(s){I(e.$$.fragment,s),t=!1},d(s){oe(e,s)}}}function Bn(n,e){let t,s,r,l,i,a=[Si,yi],o=[];function h(_,f){return _[2]?0:1}return s=h(e,[-1,-1]),r=o[s]=a[s](e),{key:n,first:null,c(){t=x(),r.c(),l=x(),this.first=t},m(_,f){y(_,t,f),o[s].m(_,f),y(_,l,f),i=!0},p(_,f){e=_;let c=s;s=h(e,f),s===c?o[s].p(e,f):(ie(),I(o[c],1,1,()=>{o[c]=null}),ae(),r=o[s],r?r.p(e,f):(r=o[s]=a[s](e),r.c()),z(r,1),r.m(l.parentNode,l))},i(_){i||(z(r),i=!0)},o(_){I(r),i=!1},d(_){_&&C(t),o[s].d(_),_&&C(l)}}}function Wn(n){let e,t=n[18]("load_more",n[17],n[5])+"",s,r,l;return{c(){e=k("button"),s=A(t),p(e,"type","button"),p(e,"class","pagefind-ui__button svelte-e9gkc3")},m(i,a){y(i,e,a),b(e,s),r||(l=K(e,"click",n[20]),r=!0)},p(i,a){a[0]&131104&&t!==(t=i[18]("load_more",i[17],i[5])+"")&&N(s,t)},d(i){i&&C(e),r=!1,l()}}}function Vn(n){let e,t=n[18]("searching",n[17],n[5]).replace(/\[SEARCH_TERM\]/,n[14])+"",s;return{c(){e=k("p"),s=A(t),p(e,"class","pagefind-ui__message svelte-e9gkc3")},m(r,l){y(r,e,l),b(e,s)},p(r,l){l[0]&147488&&t!==(t=r[18]("searching",r[17],r[5]).replace(/\[SEARCH_TERM\]/,r[14])+"")&&N(s,t)},d(r){r&&C(e)}}}function vi(n){let e,t,s,r,l,i,a=n[18]("clear_search",n[17],n[5])+"",o,h,_,f,c,E,u,m,d=n[10]&&Ln(n),R=n[13]&&qn(n);return{c(){e=k("div"),t=k("form"),s=k("input"),l=M(),i=k("button"),o=A(a),h=M(),_=k("div"),d&&d.c(),f=M(),R&&R.c(),p(s,"class","pagefind-ui__search-input svelte-e9gkc3"),p(s,"type","text"),p(s,"placeholder",r=n[18]("placeholder",n[17],n[5])),p(s,"autocapitalize","none"),p(s,"enterkeyhint","search"),p(i,"class","pagefind-ui__search-clear svelte-e9gkc3"),W(i,"pagefind-ui__suppressed",!n[6]),p(_,"class","pagefind-ui__drawer svelte-e9gkc3"),W(_,"pagefind-ui__hidden",!n[13]),p(t,"class","pagefind-ui__form svelte-e9gkc3"),p(t,"role","search"),p(t,"aria-label",c=n[18]("search_label",n[17],n[5])),p(t,"action","javascript:void(0);"),p(e,"class","pagefind-ui svelte-e9gkc3"),W(e,"pagefind-ui--reset",n[0])},m(T,S){y(T,e,S),b(e,t),b(t,s),it(s,n[6]),n[31](s),b(t,l),b(t,i),b(i,o),n[32](i),b(t,h),b(t,_),d&&d.m(_,null),b(_,f),R&&R.m(_,null),E=!0,u||(m=[K(s,"focus",n[19]),K(s,"keydown",n[29]),K(s,"input",n[30]),K(i,"click",n[33]),K(t,"submit",Mi)],u=!0)},p(T,S){(!E||S[0]&131104&&r!==(r=T[18]("placeholder",T[17],T[5])))&&p(s,"placeholder",r),S[0]&64&&s.value!==T[6]&&it(s,T[6]),(!E||S[0]&131104)&&a!==(a=T[18]("clear_search",T[17],T[5])+"")&&N(o,a),(!E||S[0]&64)&&W(i,"pagefind-ui__suppressed",!T[6]),T[10]?d?(d.p(T,S),S[0]&1024&&z(d,1)):(d=Ln(T),d.c(),z(d,1),d.m(_,f)):d&&(ie(),I(d,1,1,()=>{d=null}),ae()),T[13]?R?(R.p(T,S),S[0]&8192&&z(R,1)):(R=qn(T),R.c(),z(R,1),R.m(_,null)):R&&(ie(),I(R,1,1,()=>{R=null}),ae()),(!E||S[0]&8192)&&W(_,"pagefind-ui__hidden",!T[13]),(!E||S[0]&131104&&c!==(c=T[18]("search_label",T[17],T[5])))&&p(t,"aria-label",c),(!E||S[0]&1)&&W(e,"pagefind-ui--reset",T[0])},i(T){E||(z(d),z(R),E=!0)},o(T){I(d),I(R),E=!1},d(T){T&&C(e),n[31](null),n[32](null),d&&d.d(),R&&R.d(),u=!1,V(m)}}}var Mi=n=>n.preventDefault();function Ai(n,e,t){let s={},r=In.map(g=>g.match(/([^\/]+)\.json$/)[1]);for(let g=0;g<r.length;g++)s[r[g]]={language:r[g],...Un[g].strings};let{base_path:l="/pagefind/"}=e,{page_size:i=5}=e,{reset_styles:a=!0}=e,{show_images:o=!0}=e,{show_sub_results:h=!1}=e,{excerpt_length:_}=e,{process_result:f=null}=e,{process_term:c=null}=e,{show_empty_filters:E=!0}=e,{debounce_timeout_ms:u=300}=e,{pagefind_options:m={}}=e,{merge_index:d=[]}=e,{trigger_search_term:R=""}=e,{translations:T={}}=e,S="",w,B,X,F=40,U=!1,P=[],Z=!1,$e=!1,Gt=0,Kt="",et=i,Jt=null,ue=null,Ge={},Yt=s.en,Kn=(g,H,O)=>O[g]??H[g]??"";at(()=>{let g=document?.querySelector?.("html")?.getAttribute?.("lang")||"en",H=Qe(g.toLocaleLowerCase());t(17,Yt=s[`${H.language}-${H.script}-${H.region}`]||s[`${H.language}-${H.region}`]||s[`${H.language}`]||s.en)}),ot(()=>{w?.destroy?.(),w=null});let Xt=async()=>{if(!U&&(t(10,U=!0),!w)){let g;try{g=await import(`${l}pagefind.js`)}catch(O){console.error(O),console.error([`Pagefind couldn't be loaded from ${this.options.bundlePath}pagefind.js`,"You can configure this by passing a bundlePath option to PagefindUI",`[DEBUG: Loaded from ${document?.currentScript?.src??"no known script location"}]`].join(` `))}_||t(22,_=h?12:30);let H={...m||{},excerptLength:_};await g.options(H);for(let O of d){if(!O.bundlePath)throw new Error("mergeIndex requires a bundlePath parameter");let L=O.bundlePath;delete O.bundlePath,await g.mergeIndex(L,O)}w=g,Jn()}},Jn=async()=>{w&&(Jt=await w.filters(),(!ue||!Object.keys(ue).length)&&t(16,ue=Jt))},Yn=g=>{let H={};return Object.entries(g).filter(([,O])=>O).forEach(([O])=>{let[L,ls]=O.split(/:(.*)$/);H[L]=H[L]||[],H[L].push(ls)}),H},ce,Xn=async(g,H)=>{if(!g){t(13,$e=!1),ce&&clearTimeout(ce);return}let O=Yn(H),L=()=>Zn(g,O);u>0&&g?(ce&&clearTimeout(ce),ce=setTimeout(L,u),await Zt(),w.preload(g,{filters:O})):L(),Qn()},Zt=async()=>{for(;!w;)Xt(),await new Promise(g=>setTimeout(g,50))},Zn=async(g,H)=>{t(14,Kt=g||""),typeof c=="function"&&(g=c(g)),t(12,Z=!0),t(13,$e=!0),await Zt();let O=++Gt,L=await w.search(g,{filters:H});Gt===O&&(L.filters&&Object.keys(L.filters)?.length&&t(16,ue=L.filters),t(11,P=L),t(12,Z=!1),t(15,et=i))},Qn=()=>{let g=X.offsetWidth;g!=F&&t(8,B.style.paddingRight=`${g+2}px`,B)},xn=g=>{g?.preventDefault(),t(15,et+=i)},$n=g=>{g.key==="Escape"&&(t(6,S=""),B.blur()),g.key==="Enter"&&g.preventDefault()};function es(){S=this.value,t(6,S),t(21,R)}function ts(g){re[g?"unshift":"push"](()=>{B=g,t(8,B)})}function ns(g){re[g?"unshift":"push"](()=>{X=g,t(9,X)})}let ss=()=>{t(6,S=""),B.blur()};function rs(g){Ge=g,t(7,Ge)}return n.$$set=g=>{"base_path"in g&&t(23,l=g.base_path),"page_size"in g&&t(24,i=g.page_size),"reset_styles"in g&&t(0,a=g.reset_styles),"show_images"in g&&t(1,o=g.show_images),"show_sub_results"in g&&t(2,h=g.show_sub_results),"excerpt_length"in g&&t(22,_=g.excerpt_length),"process_result"in g&&t(3,f=g.process_result),"process_term"in g&&t(25,c=g.process_term),"show_empty_filters"in g&&t(4,E=g.show_empty_filters),"debounce_timeout_ms"in g&&t(26,u=g.debounce_timeout_ms),"pagefind_options"in g&&t(27,m=g.pagefind_options),"merge_index"in g&&t(28,d=g.merge_index),"trigger_search_term"in g&&t(21,R=g.trigger_search_term),"translations"in g&&t(5,T=g.translations)},n.$$.update=()=>{if(n.$$.dirty[0]&2097152)e:R&&(t(6,S=R),t(21,R=""));if(n.$$.dirty[0]&192)e:Xn(S,Ge)},[a,o,h,f,E,T,S,Ge,B,X,U,P,Z,$e,Kt,et,ue,Yt,Kn,Xt,xn,R,_,l,i,c,u,m,d,$n,es,ts,ns,ss,rs]}var Wt=class extends q{constructor(e){super(),J(this,e,Ai,vi,G,{base_path:23,page_size:24,reset_styles:0,show_images:1,show_sub_results:2,excerpt_length:22,process_result:3,process_term:25,show_empty_filters:4,debounce_timeout_ms:26,pagefind_options:27,merge_index:28,trigger_search_term:21,translations:5},null,[-1,-1])}},Gn=Wt;var Vt;try{Vt=new URL(document.currentScript.src).pathname.match(/^(.*\/)(?:pagefind-)?ui.js.*$/)[1]}catch{Vt="/pagefind/"}var xe=class{constructor(e){this._pfs=null;let t=e.element??"[data-pagefind-ui]",s=e.bundlePath??Vt,r=e.pageSize??5,l=e.resetStyles??!0,i=e.showImages??!0,a=e.showSubResults??!1,o=e.excerptLength??0,h=e.processResult??null,_=e.processTerm??null,f=e.showEmptyFilters??!0,c=e.debounceTimeoutMs??300,E=e.mergeIndex??[],u=e.translations??[];delete e.element,delete e.bundlePath,delete e.pageSize,delete e.resetStyles,delete e.showImages,delete e.showSubResults,delete e.excerptLength,delete e.processResult,delete e.processTerm,delete e.showEmptyFilters,delete e.debounceTimeoutMs,delete e.mergeIndex,delete e.translations;let m=t instanceof HTMLElement?t:document.querySelector(t);m?this._pfs=new Gn({target:m,props:{base_path:s,page_size:r,reset_styles:l,show_images:i,show_sub_results:a,excerpt_length:o,process_result:h,process_term:_,show_empty_filters:f,debounce_timeout_ms:c,merge_index:E,translations:u,pagefind_options:e}}):console.error(`Pagefind UI couldn't find the selector ${t}`)}triggerSearch(e){this._pfs.$$set({trigger_search_term:e})}destroy(){this._pfs.$destroy()}};window.PagefindUI=xe;})();
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
pagefind/pagefind.js
JavaScript
const pagefind_version="1.0.4";let wasm_bindgen;(function(){const __exports={};let script_src;if(typeof document==='undefined'){script_src=location.href}else{script_src=new URL("UNHANDLED",location.href).toString()}let wasm;let cachedUint8Memory0=null;function getUint8Memory0(){if(cachedUint8Memory0===null||cachedUint8Memory0.byteLength===0){cachedUint8Memory0=new Uint8Array(wasm.memory.buffer)}return cachedUint8Memory0}let WASM_VECTOR_LEN=0;function passArray8ToWasm0(arg,malloc){const ptr=malloc(arg.length*1);getUint8Memory0().set(arg,ptr/1);WASM_VECTOR_LEN=arg.length;return ptr}__exports.init_pagefind=function(metadata_bytes){const ptr0=passArray8ToWasm0(metadata_bytes,wasm.__wbindgen_malloc);const len0=WASM_VECTOR_LEN;const ret=wasm.init_pagefind(ptr0,len0);return ret};__exports.load_index_chunk=function(ptr,chunk_bytes){const ptr0=passArray8ToWasm0(chunk_bytes,wasm.__wbindgen_malloc);const len0=WASM_VECTOR_LEN;const ret=wasm.load_index_chunk(ptr,ptr0,len0);return ret};__exports.load_filter_chunk=function(ptr,chunk_bytes){const ptr0=passArray8ToWasm0(chunk_bytes,wasm.__wbindgen_malloc);const len0=WASM_VECTOR_LEN;const ret=wasm.load_filter_chunk(ptr,ptr0,len0);return ret};const cachedTextEncoder=new TextEncoder('utf-8');const encodeString=(typeof cachedTextEncoder.encodeInto==='function'?function(arg,view){return cachedTextEncoder.encodeInto(arg,view)}:function(arg,view){const buf=cachedTextEncoder.encode(arg);view.set(buf);return{read:arg.length,written:buf.length}});function passStringToWasm0(arg,malloc,realloc){if(realloc===undefined){const buf=cachedTextEncoder.encode(arg);const ptr=malloc(buf.length);getUint8Memory0().subarray(ptr,ptr+buf.length).set(buf);WASM_VECTOR_LEN=buf.length;return ptr}let len=arg.length;let ptr=malloc(len);const mem=getUint8Memory0();let offset=0;for(;offset<len;offset++){const code=arg.charCodeAt(offset);if(code>0x7F)break;mem[ptr+offset]=code}if(offset!==len){if(offset!==0){arg=arg.slice(offset)}ptr=realloc(ptr,len,len=offset+arg.length*3);const view=getUint8Memory0().subarray(ptr+offset,ptr+len);const ret=encodeString(arg,view);offset+=ret.written}WASM_VECTOR_LEN=offset;return ptr}__exports.add_synthetic_filter=function(ptr,filter){const ptr0=passStringToWasm0(filter,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;const ret=wasm.add_synthetic_filter(ptr,ptr0,len0);return ret};let cachedInt32Memory0=null;function getInt32Memory0(){if(cachedInt32Memory0===null||cachedInt32Memory0.byteLength===0){cachedInt32Memory0=new Int32Array(wasm.memory.buffer)}return cachedInt32Memory0}const cachedTextDecoder=new TextDecoder('utf-8',{ignoreBOM:true,fatal:true});cachedTextDecoder.decode();function getStringFromWasm0(ptr,len){return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr,ptr+len))}__exports.request_indexes=function(ptr,query){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);const ptr0=passStringToWasm0(query,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;wasm.request_indexes(retptr,ptr,ptr0,len0);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];return getStringFromWasm0(r0,r1)}finally{wasm.__wbindgen_add_to_stack_pointer(16);wasm.__wbindgen_free(r0,r1)}};__exports.request_filter_indexes=function(ptr,filters){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);const ptr0=passStringToWasm0(filters,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;wasm.request_filter_indexes(retptr,ptr,ptr0,len0);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];return getStringFromWasm0(r0,r1)}finally{wasm.__wbindgen_add_to_stack_pointer(16);wasm.__wbindgen_free(r0,r1)}};__exports.request_all_filter_indexes=function(ptr){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.request_all_filter_indexes(retptr,ptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];return getStringFromWasm0(r0,r1)}finally{wasm.__wbindgen_add_to_stack_pointer(16);wasm.__wbindgen_free(r0,r1)}};__exports.filters=function(ptr){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);wasm.filters(retptr,ptr);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];return getStringFromWasm0(r0,r1)}finally{wasm.__wbindgen_add_to_stack_pointer(16);wasm.__wbindgen_free(r0,r1)}};__exports.search=function(ptr,query,filter,sort,exact){try{const retptr=wasm.__wbindgen_add_to_stack_pointer(-16);const ptr0=passStringToWasm0(query,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len0=WASM_VECTOR_LEN;const ptr1=passStringToWasm0(filter,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len1=WASM_VECTOR_LEN;const ptr2=passStringToWasm0(sort,wasm.__wbindgen_malloc,wasm.__wbindgen_realloc);const len2=WASM_VECTOR_LEN;wasm.search(retptr,ptr,ptr0,len0,ptr1,len1,ptr2,len2,exact);var r0=getInt32Memory0()[retptr/4+0];var r1=getInt32Memory0()[retptr/4+1];return getStringFromWasm0(r0,r1)}finally{wasm.__wbindgen_add_to_stack_pointer(16);wasm.__wbindgen_free(r0,r1)}};async function load(module,imports){if(typeof Response==='function'&&module instanceof Response){if(typeof WebAssembly.instantiateStreaming==='function'){try{return await WebAssembly.instantiateStreaming(module,imports)}catch(e){if(module.headers.get('Content-Type')!='application/wasm'){console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e)}else{throw e}}}const bytes=await module.arrayBuffer();return await WebAssembly.instantiate(bytes,imports)}else{const instance=await WebAssembly.instantiate(module,imports);if(instance instanceof WebAssembly.Instance){return{instance,module}}else{return instance}}}function getImports(){const imports={};imports.wbg={};return imports}function initMemory(imports,maybe_memory){}function finalizeInit(instance,module){wasm=instance.exports;init.__wbindgen_wasm_module=module;cachedInt32Memory0=null;cachedUint8Memory0=null;return wasm}function initSync(module){const imports=getImports();initMemory(imports);if(!(module instanceof WebAssembly.Module)){module=new WebAssembly.Module(module)}const instance=new WebAssembly.Instance(module,imports);return finalizeInit(instance,module)}async function init(input){if(typeof input==='undefined'){input=script_src.replace(/\.js$/,'_bg.wasm')}const imports=getImports();if(typeof input==='string'||(typeof Request==='function'&&input instanceof Request)||(typeof URL==='function'&&input instanceof URL)){input=fetch(input)}initMemory(imports);const{instance,module}=await load(await input,imports);return finalizeInit(instance,module)}wasm_bindgen=Object.assign(init,{initSync},__exports)})();var u8=Uint8Array;var u16=Uint16Array;var u32=Uint32Array;var fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]);var fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]);var clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var freb=function(eb,start){var b=new u16(31);for(var i2=0;i2<31;++i2){b[i2]=start+=1<<eb[i2-1]}var r=new u32(b[30]);for(var i2=1;i2<30;++i2){for(var j=b[i2];j<b[i2+1];++j){r[j]=j-b[i2]<<5|i2}}return[b,r]};var _a=freb(fleb,2);var fl=_a[0];var revfl=_a[1];fl[28]=258,revfl[258]=28;var _b=freb(fdeb,0);var fd=_b[0];var revfd=_b[1];var rev=new u16(32768);for(i=0;i<32768;++i){x=(i&43690)>>>1|(i&21845)<<1;x=(x&52428)>>>2|(x&13107)<<2;x=(x&61680)>>>4|(x&3855)<<4;rev[i]=((x&65280)>>>8|(x&255)<<8)>>>1}var x;var i;var hMap=function(cd,mb,r){var s=cd.length;var i2=0;var l=new u16(mb);for(;i2<s;++i2){if(cd[i2])++l[cd[i2]-1]}var le=new u16(mb);for(i2=0;i2<mb;++i2){le[i2]=le[i2-1]+l[i2-1]<<1}var co;if(r){co=new u16(1<<mb);var rvb=15-mb;for(i2=0;i2<s;++i2){if(cd[i2]){var sv=i2<<4|cd[i2];var r_1=mb-cd[i2];var v=le[cd[i2]-1]++<<r_1;for(var m=v|(1<<r_1)-1;v<=m;++v){co[rev[v]>>>rvb]=sv}}}}else{co=new u16(s);for(i2=0;i2<s;++i2){if(cd[i2]){co[i2]=rev[le[cd[i2]-1]++]>>>15-cd[i2]}}}return co};var flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;var i;for(i=144;i<256;++i)flt[i]=9;var i;for(i=256;i<280;++i)flt[i]=7;var i;for(i=280;i<288;++i)flt[i]=8;var i;var fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var i;var flrm=hMap(flt,9,1);var fdrm=hMap(fdt,5,1);var max=function(a){var m=a[0];for(var i2=1;i2<a.length;++i2){if(a[i2]>m)m=a[i2]}return m};var bits=function(d,p,m){var o=p/8|0;return(d[o]|d[o+1]<<8)>>(p&7)&m};var bits16=function(d,p){var o=p/8|0;return(d[o]|d[o+1]<<8|d[o+2]<<16)>>(p&7)};var shft=function(p){return(p+7)/8|0};var slc=function(v,s,e){if(s==null||s<0)s=0;if(e==null||e>v.length)e=v.length;var n=new(v.BYTES_PER_ELEMENT==2?u16:v.BYTES_PER_ELEMENT==4?u32:u8)(e-s);n.set(v.subarray(s,e));return n};var ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"];var err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);e.code=ind;if(Error.captureStackTrace)Error.captureStackTrace(e,err);if(!nt)throw e;return e};var inflt=function(dat,buf,st){var sl=dat.length;if(!sl||st&&st.f&&!st.l)return buf||new u8(0);var noBuf=!buf||st;var noSt=!st||st.i;if(!st)st={};if(!buf)buf=new u8(sl*3);var cbuf=function(l2){var bl=buf.length;if(l2>bl){var nbuf=new u8(Math.max(bl*2,l2));nbuf.set(buf);buf=nbuf}};var final=st.f||0,pos=st.p||0,bt=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n;var tbts=sl*8;do{if(!lm){final=bits(dat,pos,1);var type=bits(dat,pos+1,3);pos+=3;if(!type){var s=shft(pos)+4,l=dat[s-4]|dat[s-3]<<8,t=s+l;if(t>sl){if(noSt)err(0);break}if(noBuf)cbuf(bt+l);buf.set(dat.subarray(s,t),bt);st.b=bt+=l,st.p=pos=t*8,st.f=final;continue}else if(type==1)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(type==2){var hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4;var tl=hLit+bits(dat,pos+5,31)+1;pos+=14;var ldt=new u8(tl);var clt=new u8(19);for(var i2=0;i2<hcLen;++i2){clt[clim[i2]]=bits(dat,pos+i2*3,7)}pos+=hcLen*3;var clb=max(clt),clbmsk=(1<<clb)-1;var clm=hMap(clt,clb,1);for(var i2=0;i2<tl;){var r=clm[bits(dat,pos,clbmsk)];pos+=r&15;var s=r>>>4;if(s<16){ldt[i2++]=s}else{var c=0,n=0;if(s==16)n=3+bits(dat,pos,3),pos+=2,c=ldt[i2-1];else if(s==17)n=3+bits(dat,pos,7),pos+=3;else if(s==18)n=11+bits(dat,pos,127),pos+=7;while(n--)ldt[i2++]=c}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt);dbt=max(dt);lm=hMap(lt,lbt,1);dm=hMap(dt,dbt,1)}else err(1);if(pos>tbts){if(noSt)err(0);break}}if(noBuf)cbuf(bt+131072);var lms=(1<<lbt)-1,dms=(1<<dbt)-1;var lpos=pos;for(;;lpos=pos){var c=lm[bits16(dat,pos)&lms],sym=c>>>4;pos+=c&15;if(pos>tbts){if(noSt)err(0);break}if(!c)err(2);if(sym<256)buf[bt++]=sym;else if(sym==256){lpos=pos,lm=null;break}else{var add=sym-254;if(sym>264){var i2=sym-257,b=fleb[i2];add=bits(dat,pos,(1<<b)-1)+fl[i2];pos+=b}var d=dm[bits16(dat,pos)&dms],dsym=d>>>4;if(!d)err(3);pos+=d&15;var dt=fd[dsym];if(dsym>3){var b=fdeb[dsym];dt+=bits16(dat,pos)&(1<<b)-1,pos+=b}if(pos>tbts){if(noSt)err(0);break}if(noBuf)cbuf(bt+131072);var end=bt+add;for(;bt<end;bt+=4){buf[bt]=buf[bt-dt];buf[bt+1]=buf[bt+1-dt];buf[bt+2]=buf[bt+2-dt];buf[bt+3]=buf[bt+3-dt]}bt=end}}st.l=lm,st.p=lpos,st.b=bt,st.f=final;if(lm)final=1,st.m=lbt,st.d=dm,st.n=dbt}while(!final);return bt==buf.length?buf:slc(buf,0,bt)};var et=new u8(0);var gzs=function(d){if(d[0]!=31||d[1]!=139||d[2]!=8)err(6,"invalid gzip data");var flg=d[3];var st=10;if(flg&4)st+=d[10]|(d[11]<<8)+2;for(var zs=(flg>>3&1)+(flg>>4&1);zs>0;zs-=!d[st++]);return st+(flg&2)};var gzl=function(d){var l=d.length;return(d[l-4]|d[l-3]<<8|d[l-2]<<16|d[l-1]<<24)>>>0};function gunzipSync(data,out){return inflt(data.subarray(gzs(data),-8),out||new u8(gzl(data)))}var td=typeof TextDecoder!="undefined"&&new TextDecoder();var tds=0;try{td.decode(et,{stream:true});tds=1}catch(e){}var gz_default=gunzipSync;var calculate_excerpt_region=(word_positions,excerpt_length)=>{if(word_positions.length===0){return 0}let words=[];for(const word of word_positions){words[word.location]=words[word.location]||0;words[word.location]+=word.balanced_score}if(words.length<=excerpt_length){return 0}let densest=words.slice(0,excerpt_length).reduce((partialSum,a)=>partialSum+a,0);let working_sum=densest;let densest_at=[0];for(let i2=0;i2<words.length;i2++){const boundary=i2+excerpt_length;working_sum+=(words[boundary]??0)-(words[i2]??0);if(working_sum>densest){densest=working_sum;densest_at=[i2]}else if(working_sum===densest&&densest_at[densest_at.length-1]===i2-1){densest_at.push(i2)}}let midpoint=densest_at[Math.floor(densest_at.length/2)];return midpoint};var build_excerpt=(content,start,length,locations,not_before,not_from)=>{let is_zws_delimited=content.includes("\u200B");let fragment_words=[];if(is_zws_delimited){fragment_words=content.split("\u200B")}else{fragment_words=content.split(/[\r\n\s]+/g)}for(let word of locations){if(fragment_words[word]?.startsWith(`<mark>`)){continue}fragment_words[word]=`<mark>${fragment_words[word]}</mark>`}let endcap=not_from??fragment_words.length;let startcap=not_before??0;if(endcap-startcap<length){length=endcap-startcap}if(start+length>endcap){start=endcap-length}if(start<startcap){start=startcap}return fragment_words.slice(start,start+length).join(is_zws_delimited?"":" ").trim()};var calculate_sub_results=(fragment,desired_excerpt_length)=>{const anchors=fragment.anchors.filter((a)=>/h\d/i.test(a.element)&&a.text?.length&&/\S/.test(a.text)).sort((a,b)=>a.location-b.location);const results=[];let current_anchor_position=0;let current_anchor={title:fragment.meta["title"],url:fragment.url,weighted_locations:[],locations:[],excerpt:""};const add_result=(end_range)=>{if(current_anchor.locations.length){const relative_weighted_locations=current_anchor.weighted_locations.map((l)=>{return{weight:l.weight,balanced_score:l.balanced_score,location:l.location-current_anchor_position}});const excerpt_start=calculate_excerpt_region(relative_weighted_locations,desired_excerpt_length)+current_anchor_position;const excerpt_length=end_range?Math.min(end_range-excerpt_start,desired_excerpt_length):desired_excerpt_length;current_anchor.excerpt=build_excerpt(fragment.raw_content??"",excerpt_start,excerpt_length,current_anchor.locations,current_anchor_position,end_range);results.push(current_anchor)}};for(let word of fragment.weighted_locations){if(!anchors.length||word.location<anchors[0].location){current_anchor.weighted_locations.push(word);current_anchor.locations.push(word.location)}else{let next_anchor=anchors.shift();add_result(next_anchor.location);while(anchors.length&&word.location>=anchors[0].location){next_anchor=anchors.shift()}let anchored_url=fragment.url;try{const url_is_fq=/^((https?:)?\/\/)/.test(anchored_url);if(url_is_fq){let fq_url=new URL(anchored_url);fq_url.hash=next_anchor.id;anchored_url=fq_url.toString()}else{if(!/^\//.test(anchored_url)){anchored_url=`/${anchored_url}`}let fq_url=new URL(`https://example.com${anchored_url}`);fq_url.hash=next_anchor.id;anchored_url=fq_url.toString().replace(/^https:\/\/example.com/,"")}}catch(e){console.error(`Pagefind: Couldn't process ${anchored_url} for a search result`)}current_anchor_position=next_anchor.location;current_anchor={title:next_anchor.text,url:anchored_url,anchor:next_anchor,weighted_locations:[word],locations:[word.location],excerpt:""}}}add_result(anchors[0]?.location);return results};var asyncSleep=async(ms=100)=>{return new Promise((r)=>setTimeout(r,ms))};var PagefindInstance=class{constructor(opts={}){this.version=pagefind_version;this.backend=wasm_bindgen;this.decoder=new TextDecoder("utf-8");this.wasm=null;this.basePath=opts.basePath||"/pagefind/";this.primary=opts.primary||false;if(this.primary&&!opts.basePath){this.initPrimary()}if(/[^\/]$/.test(this.basePath)){this.basePath=`${this.basePath}/`}if(window?.location?.origin&&this.basePath.startsWith(window.location.origin)){this.basePath=this.basePath.replace(window.location.origin,"")}this.baseUrl=opts.baseUrl||this.defaultBaseUrl();if(!/^(\/|https?:\/\/)/.test(this.baseUrl)){this.baseUrl=`/${this.baseUrl}`}this.indexWeight=opts.indexWeight??1;this.excerptLength=opts.excerptLength??30;this.mergeFilter=opts.mergeFilter??{};this.highlightParam=opts.highlightParam??null;this.loaded_chunks={};this.loaded_filters={};this.loaded_fragments={};this.raw_ptr=null;this.searchMeta=null;this.languages=null}initPrimary(){let derivedBasePath=import.meta.url.match(/^(.*\/)pagefind.js.*$/)?.[1];if(derivedBasePath){this.basePath=derivedBasePath}else{console.warn(["Pagefind couldn't determine the base of the bundle from the import path. Falling back to the default.","Set a basePath option when initialising Pagefind to ignore this message."].join("\n"))}}defaultBaseUrl(){let default_base=this.basePath.match(/^(.*\/)_?pagefind/)?.[1];return default_base||"/"}async options(options2){const opts=["basePath","baseUrl","indexWeight","excerptLength","mergeFilter","highlightParam"];for(const[k,v]of Object.entries(options2)){if(k==="mergeFilter"){let filters2=this.stringifyFilters(v);let ptr=await this.getPtr();this.raw_ptr=this.backend.add_synthetic_filter(ptr,filters2)}else if(opts.includes(k)){if(k==="basePath"&&typeof v==="string")this.basePath=v;if(k==="baseUrl"&&typeof v==="string")this.baseUrl=v;if(k==="indexWeight"&&typeof v==="number")this.indexWeight=v;if(k==="excerptLength"&&typeof v==="number")this.excerptLength=v;if(k==="mergeFilter"&&typeof v==="object")this.mergeFilter=v;if(k==="highlightParam"&&typeof v==="string")this.highlightParam=v}else{console.warn(`Unknown Pagefind option ${k}. Allowed options: [${opts.join(", ")}]`)}}}decompress(data,file="unknown file"){if(this.decoder.decode(data.slice(0,12))==="pagefind_dcd"){return data.slice(12)}data=gz_default(data);if(this.decoder.decode(data.slice(0,12))!=="pagefind_dcd"){console.error(`Decompressing ${file} appears to have failed: Missing signature`);return data}return data.slice(12)}async init(language,opts){await this.loadEntry();let index=this.findIndex(language);let lang_wasm=index.wasm?index.wasm:"unknown";let resources=[this.loadMeta(index.hash)];if(opts.load_wasm===true){resources.push(this.loadWasm(lang_wasm))}await Promise.all(resources);this.raw_ptr=this.backend.init_pagefind(new Uint8Array(this.searchMeta));if(Object.keys(this.mergeFilter)?.length){let filters2=this.stringifyFilters(this.mergeFilter);let ptr=await this.getPtr();this.raw_ptr=this.backend.add_synthetic_filter(ptr,filters2)}}async loadEntry(){try{let entry_response=await fetch(`${this.basePath}pagefind-entry.json?ts=${Date.now()}`);let entry_json=await entry_response.json();this.languages=entry_json.languages;if(entry_json.version!==this.version){if(this.primary){console.warn(["Pagefind JS version doesn't match the version in your search index.",`Pagefind JS: ${this.version}. Pagefind index: ${entry_json.version}`,"If you upgraded Pagefind recently, you likely have a cached pagefind.js file.","If you encounter any search errors, try clearing your cache."].join("\n"))}else{console.warn(["Merging a Pagefind index from a different version than the main Pagefind instance.",`Main Pagefind JS: ${this.version}. Merged index (${this.basePath}): ${entry_json.version}`,"If you encounter any search errors, make sure that both sites are running the same version of Pagefind."].join("\n"))}}}catch(e){console.error(`Failed to load Pagefind metadata: ${e?.toString()}`);throw new Error("Failed to load Pagefind metadata")}}findIndex(language){if(this.languages){let index=this.languages[language];if(index)return index;index=this.languages[language.split("-")[0]];if(index)return index;let topLang=Object.values(this.languages).sort((a,b)=>b.page_count-a.page_count);if(topLang[0])return topLang[0]}throw new Error("Pagefind Error: No language indexes found.")}async loadMeta(index){try{let compressed_resp=await fetch(`${this.basePath}pagefind.${index}.pf_meta`);let compressed_meta=await compressed_resp.arrayBuffer();this.searchMeta=this.decompress(new Uint8Array(compressed_meta),"Pagefind metadata")}catch(e){console.error(`Failed to load the meta index: ${e?.toString()}`)}}async loadWasm(language){try{const wasm_url=`${this.basePath}wasm.${language}.pagefind`;let compressed_resp=await fetch(wasm_url);let compressed_wasm=await compressed_resp.arrayBuffer();const final_wasm=this.decompress(new Uint8Array(compressed_wasm),"Pagefind WebAssembly");if(!final_wasm){throw new Error("No WASM after decompression")}this.wasm=await this.backend(final_wasm)}catch(e){console.error(`Failed to load the Pagefind WASM: ${e?.toString()}`);throw new Error(`Failed to load the Pagefind WASM: ${e?.toString()}`)}}async _loadGenericChunk(url,method){try{let compressed_resp=await fetch(url);let compressed_chunk=await compressed_resp.arrayBuffer();let chunk=this.decompress(new Uint8Array(compressed_chunk),url);let ptr=await this.getPtr();this.raw_ptr=this.backend[method](ptr,chunk)}catch(e){console.error(`Failed to load the index chunk ${url}: ${e?.toString()}`)}}async loadChunk(hash){if(!this.loaded_chunks[hash]){const url=`${this.basePath}index/${hash}.pf_index`;this.loaded_chunks[hash]=this._loadGenericChunk(url,"load_index_chunk")}return await this.loaded_chunks[hash]}async loadFilterChunk(hash){if(!this.loaded_filters[hash]){const url=`${this.basePath}filter/${hash}.pf_filter`;this.loaded_filters[hash]=this._loadGenericChunk(url,"load_filter_chunk")}return await this.loaded_filters[hash]}async _loadFragment(hash){let compressed_resp=await fetch(`${this.basePath}fragment/${hash}.pf_fragment`);let compressed_fragment=await compressed_resp.arrayBuffer();let fragment=this.decompress(new Uint8Array(compressed_fragment),`Fragment ${hash}`);return JSON.parse(new TextDecoder().decode(fragment))}async loadFragment(hash,weighted_locations=[],search_term){if(!this.loaded_fragments[hash]){this.loaded_fragments[hash]=this._loadFragment(hash)}let fragment=await this.loaded_fragments[hash];fragment.weighted_locations=weighted_locations;fragment.locations=weighted_locations.map((l)=>l.location);if(!fragment.raw_content){fragment.raw_content=fragment.content.replace(/</g,"&lt;").replace(/>/g,"&gt;");fragment.content=fragment.content.replace(/\u200B/g,"")}if(!fragment.raw_url){fragment.raw_url=fragment.url}fragment.url=this.processedUrl(fragment.raw_url,search_term);const excerpt_start=calculate_excerpt_region(weighted_locations,this.excerptLength);fragment.excerpt=build_excerpt(fragment.raw_content,excerpt_start,this.excerptLength,fragment.locations);fragment.sub_results=calculate_sub_results(fragment,this.excerptLength);return fragment}fullUrl(raw){if(/^(https?:)?\/\//.test(raw)){return raw}return`${this.baseUrl}/${raw}`.replace(/\/+/g,"/").replace(/^(https?:\/)/,"$1/")}processedUrl(url,search_term){const normalized=this.fullUrl(url);if(this.highlightParam===null){return normalized}let individual_terms=search_term.split(/\s+/);try{let processed=new URL(normalized);for(const term of individual_terms){processed.searchParams.append(this.highlightParam,term)}return processed.toString()}catch(e){try{let processed=new URL(`https://example.com${normalized}`);for(const term of individual_terms){processed.searchParams.append(this.highlightParam,term)}return processed.toString().replace(/^https:\/\/example\.com/,"")}catch(e2){return normalized}}}async getPtr(){while(this.raw_ptr===null){await asyncSleep(50)}if(!this.raw_ptr){console.error("Pagefind: WASM Error (No pointer)");throw new Error("Pagefind: WASM Error (No pointer)")}return this.raw_ptr}parseFilters(str){let output={};if(!str)return output;for(const block of str.split("__PF_FILTER_DELIM__")){let[filter,values]=block.split(/:(.*)$/);output[filter]={};if(values){for(const valueBlock of values.split("__PF_VALUE_DELIM__")){if(valueBlock){let extract=valueBlock.match(/^(.*):(\d+)$/);if(extract){let[,value,count]=extract;output[filter][value]=parseInt(count)??count}}}}}return output}stringifyFilters(obj={}){return JSON.stringify(obj)}stringifySorts(obj={}){let sorts=Object.entries(obj);for(let[sort,direction]of sorts){if(sorts.length>1){console.warn(`Pagefind was provided multiple sort options in this search, but can only operate on one. Using the ${sort} sort.`)}if(direction!=="asc"&&direction!=="desc"){console.warn(`Pagefind was provided a sort with unknown direction ${direction}. Supported: [asc, desc]`)}return`${sort}:${direction}`}return``}async filters(){let ptr=await this.getPtr();let filters2=this.backend.request_all_filter_indexes(ptr);let filter_chunks=filters2.split(" ").filter((v)=>v).map((chunk)=>this.loadFilterChunk(chunk));await Promise.all([...filter_chunks]);ptr=await this.getPtr();let results=this.backend.filters(ptr);return this.parseFilters(results)}async preload(term,options2={}){await this.search(term,{...options2,preload:true})}async search(term,options2={}){options2={verbose:false,filters:{},sort:{},...options2};const log=(str)=>{if(options2.verbose)console.log(str)};log(`Starting search on ${this.basePath}`);let start=Date.now();let ptr=await this.getPtr();let filter_only=term===null;term=term??"";let exact_search=/^\s*".+"\s*$/.test(term);if(exact_search){log(`Running an exact search`)}term=term.toLowerCase().trim().replace(/[\.`~!@#\$%\^&\*\(\)\{\}\[\]\\\|:;'",<>\/\?\-]/g,"").replace(/\s{2,}/g," ").trim();log(`Normalized search term to ${term}`);if(!term?.length&&!filter_only){return{results:[],unfilteredResultCount:0,filters:{},totalFilters:{},timings:{preload:Date.now()-start,search:Date.now()-start,total:Date.now()-start}}}let sort_list=this.stringifySorts(options2.sort);log(`Stringified sort to ${sort_list}`);const filter_list=this.stringifyFilters(options2.filters);log(`Stringified filters to ${filter_list}`);let index_resp=this.backend.request_indexes(ptr,term);let filter_resp=this.backend.request_filter_indexes(ptr,filter_list);let chunks=index_resp.split(" ").filter((v)=>v).map((chunk)=>this.loadChunk(chunk));let filter_chunks=filter_resp.split(" ").filter((v)=>v).map((chunk)=>this.loadFilterChunk(chunk));await Promise.all([...chunks,...filter_chunks]);log(`Loaded necessary chunks to run search`);if(options2.preload){log(`Preload \u2014 bailing out of search operation now.`);return null}ptr=await this.getPtr();let searchStart=Date.now();let result=this.backend.search(ptr,term,filter_list,sort_list,exact_search);log(`Got the raw search result: ${result}`);let[unfilteredResultCount,all_results,filters2,totalFilters]=result.split(/:([^:]*):(.*)__PF_UNFILTERED_DELIM__(.*)$/);let filterObj=this.parseFilters(filters2);let totalFilterObj=this.parseFilters(totalFilters);log(`Remaining filters: ${JSON.stringify(result)}`);let results=all_results.length?all_results.split(" "):[];let resultsInterface=results.map((result2)=>{let[hash,score,all_locations]=result2.split("@");log(`Processing result: hash:${hash} score:${score} locations:${all_locations}`);let weighted_locations=all_locations.length?all_locations.split(",").map((l)=>{let[weight,balanced_score,location]=l.split(">");return{weight:parseInt(weight)/24,balanced_score:parseFloat(balanced_score),location:parseInt(location)}}):[];let locations=weighted_locations.map((l)=>l.location);return{id:hash,score:parseFloat(score)*this.indexWeight,words:locations,data:async()=>await this.loadFragment(hash,weighted_locations,term)}});const searchTime=Date.now()-searchStart;const realTime=Date.now()-start;log(`Found ${results.length} result${results.length == 1 ? "" : "s"} for "${term}" in ${Date.now() - searchStart}ms (${Date.now() - start}ms realtime)`);return{results:resultsInterface,unfilteredResultCount:parseInt(unfilteredResultCount),filters:filterObj,totalFilters:totalFilterObj,timings:{preload:realTime-searchTime,search:searchTime,total:realTime}}}};var Pagefind=class{constructor(options2={}){this.backend=wasm_bindgen;this.primaryLanguage="unknown";this.searchID=0;this.primary=new PagefindInstance({...options2,primary:true});this.instances=[this.primary];this.init(options2?.language)}async options(options2){await this.primary.options(options2)}async init(overrideLanguage){if(document?.querySelector){const langCode=document.querySelector("html")?.getAttribute("lang")||"unknown";this.primaryLanguage=langCode.toLocaleLowerCase()}await this.primary.init(overrideLanguage?overrideLanguage:this.primaryLanguage,{load_wasm:true})}async mergeIndex(indexPath,options2={}){if(this.primary.basePath.startsWith(indexPath)){console.warn(`Skipping mergeIndex ${indexPath} that appears to be the same as the primary index (${this.primary.basePath})`);return}let newInstance=new PagefindInstance({primary:false,basePath:indexPath});this.instances.push(newInstance);while(this.primary.wasm===null){await asyncSleep(50)}await newInstance.init(options2.language||this.primaryLanguage,{load_wasm:false});delete options2["language"];await newInstance.options(options2)}mergeFilters(filters2){const merged={};for(const searchFilter of filters2){for(const[filterKey,values]of Object.entries(searchFilter)){if(!merged[filterKey]){merged[filterKey]=values;continue}else{const filter=merged[filterKey];for(const[valueKey,count]of Object.entries(values)){filter[valueKey]=(filter[valueKey]||0)+count}}}}return merged}async filters(){let filters2=await Promise.all(this.instances.map((i2)=>i2.filters()));return this.mergeFilters(filters2)}async preload(term,options2={}){await Promise.all(this.instances.map((i2)=>i2.preload(term,options2)))}async debouncedSearch(term,options2,debounceTimeoutMs){const thisSearchID=++this.searchID;this.preload(term,options2);await asyncSleep(debounceTimeoutMs);if(thisSearchID!==this.searchID){return null}const searchResult=await this.search(term,options2);if(thisSearchID!==this.searchID){return null}return searchResult}async search(term,options2={}){let search2=await Promise.all(this.instances.map((i2)=>i2.search(term,options2)));const filters2=this.mergeFilters(search2.map((s)=>s.filters));const totalFilters=this.mergeFilters(search2.map((s)=>s.totalFilters));const results=search2.map((s)=>s.results).flat().sort((a,b)=>b.score-a.score);const timings=search2.map((s)=>s.timings);const unfilteredResultCount=search2.reduce((sum,s)=>sum+s.unfilteredResultCount,0);return{results,unfilteredResultCount,filters:filters2,totalFilters,timings}}};var pagefind=void 0;var initial_options=void 0;var init_pagefind=()=>{if(!pagefind){pagefind=new Pagefind(initial_options??{})}};var options=async(new_options)=>{if(pagefind){await pagefind.options(new_options)}else{initial_options=new_options}};var init=async()=>{init_pagefind()};var destroy=async()=>{pagefind=void 0;initial_options=void 0};var mergeIndex=async(indexPath,options2)=>{init_pagefind();return await pagefind.mergeIndex(indexPath,options2)};var search=async(term,options2)=>{init_pagefind();return await pagefind.search(term,options2)};var debouncedSearch=async(term,options2,debounceTimeoutMs=300)=>{init_pagefind();return await pagefind.debouncedSearch(term,options2,debounceTimeoutMs)};var preload=async(term,options2)=>{init_pagefind();return await pagefind.preload(term,options2)};var filters=async()=>{init_pagefind();return await pagefind.filters()};export{debouncedSearch,destroy,filters,init,mergeIndex,options,preload,search}
zachleat/pagefind-search
37
A web component to search with Pagefind.
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
demo.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="" /> <title>table-saw Web Component Demo</title> <style> /* Demo styles */ td { padding: .3em; } .demo-numeric { text-align: right; } resize-asaurus { outline: 2px solid #ddd; background-color: #f2f2f2; } </style> <!-- tablesaw --> <script type="module" src="table-saw.js"></script> <!-- resizer via 3rd party CDN, not recommended for production use --> <script type="module" src="https://esm.sh/@zachleat/resizeasaurus@4.0.0"></script> </head> <body> <header> <h1>table-saw Web Component Demo</h1> <p>Source code available at <a href="https://github.com/zachleat/table-saw/"><code>https://github.com/zachleat/table-saw/</code></a></p> </header> <main> <h2>Using media queries (viewport based)</h2> <table-saw breakpoint="(max-width: 30em)" ratio="1/1" zero-padding> <table> <thead> <tr> <th scope="col">Movie Title</th> <th scope="col">Rank</th> <th scope="col">Year</th> <th scope="col"><abbr title="Rotten Tomato Rating">Rating</abbr></th> <th scope="col">Gross</th> </tr> </thead> <tbody> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Avatar_(2009_film)">Avatar</a></td> <td>1</td> <td>2009</td> <td>83%</td> <td>$2.7B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Titanic_(1997_film)">Titanic</a></td> <td>2</td> <td>1997</td> <td>88%</td> <td>$2.1B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/The_Avengers_(2012_film)">The Avengers</a></td> <td>3</td> <td>2012</td> <td>92%</td> <td>$1.5B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Harry_Potter_and_the_Deathly_Hallows_%E2%80%93_Part_2">Harry Potter and the Deathly Hallows—Part 2</a></td> <td>4</td> <td>2011</td> <td>96%</td> <td>$1.3B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Frozen_(2013_film)">Frozen</a></td> <td>5</td> <td>2013</td> <td>89%</td> <td>$1.2B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Iron_Man_3">Iron Man 3</a></td> <td>6</td> <td>2013</td> <td>78%</td> <td>$1.2B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Transformers:_Dark_of_the_Moon">Transformers: Dark of the Moon</a></td> <td>7</td> <td>2011</td> <td>36%</td> <td>$1.1B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/The_Lord_of_the_Rings:_The_Return_of_the_King">The Lord of the Rings: The Return of the King</a></td> <td>8</td> <td>2003</td> <td>95%</td> <td>$1.1B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Skyfall">Skyfall</a></td> <td>9</td> <td>2012</td> <td>92%</td> <td>$1.1B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Transformers:_Age_of_Extinction">Transformers: Age of Extinction</a></td> <td>10</td> <td>2014</td> <td>18%</td> <td>$1.0B</td> </tr> </tbody> </table> </table-saw> <h2>Using container queries</h2> <resize-asaurus> <table-saw breakpoint="(max-width: 30em)" type="container" ratio="1/1" zero-padding text-align> <table> <thead> <tr> <th scope="col">Movie Title</th> <th scope="col">Rank</th> <th scope="col" class="demo-numeric">Year</th> <th scope="col"><abbr title="Rotten Tomato Rating">Rating</abbr></th> <th scope="col">Gross</th> </tr> </thead> <tbody> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Avatar_(2009_film)">Avatar</a></td> <td>1</td> <td>2009</td> <td>83%</td> <td>$2.7B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Titanic_(1997_film)">Titanic</a></td> <td>2</td> <td class="demo-numeric">1997</td> <td><!-- test -->88%</td> <td>$2.1B <a href="">Link</a> test</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/The_Avengers_(2012_film)">The Avengers</a></td> <td>3</td> <td class="demo-numeric">2012</td> <td><!-- test --><span>92%</span></td> <td>$1.5B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Harry_Potter_and_the_Deathly_Hallows_%E2%80%93_Part_2">Harry Potter and the Deathly Hallows—Part 2</a></td> <td>4</td> <td class="demo-numeric">2011</td> <td>96%</td> <td>$1.3B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Frozen_(2013_film)">Frozen</a></td> <td>5</td> <td class="demo-numeric">2013</td> <td>89%</td> <td>$1.2B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Iron_Man_3">Iron Man 3</a></td> <td>6</td> <td class="demo-numeric">2013</td> <td>78%</td> <td>$1.2B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Transformers:_Dark_of_the_Moon">Transformers: Dark of the Moon</a></td> <td>7</td> <td class="demo-numeric">2011</td> <td>36%</td> <td>$1.1B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/The_Lord_of_the_Rings:_The_Return_of_the_King">The Lord of the Rings: The Return of the King</a></td> <td>8</td> <td class="demo-numeric">2003</td> <td>95%</td> <td>$1.1B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Skyfall">Skyfall</a></td> <td>9</td> <td class="demo-numeric">2012</td> <td>92%</td> <td>$1.1B</td> </tr> <tr> <td class="title"><a href="http://en.wikipedia.org/wiki/Transformers:_Age_of_Extinction">Transformers: Age of Extinction</a></td> <td>10</td> <td class="demo-numeric">2014</td> <td>18%</td> <td>$1.0B</td> </tr> </tbody> </table> </table-saw> </resize-asaurus> <h2>Multiple child tables in one &lt;table-saw&gt;</h2> <table-saw breakpoint="(max-width: 43.6875em)"> <h3>First table</h3> <table> <thead> <tr> <th scope="col">Pricing Strategies</th> <th scope="col">Hourly-based</th> <th scope="col">Project-based</th> <th scope="col">Value-based</th> <th scope="col">Retainer-based</th> <th scope="col">Tier-based</th> </tr> </thead> <tbody> <tr> <td><strong>Overview</strong></td> <td>Pricing per hour.</td> <td>Fixed price per project.</td> <td>Fixed price based on value delivered.</td> <td>Fixed price for a set number of hours.</td> <td>Fixed price packages at different price points.</td> </tr> <tr> <td><strong>Benefits</strong></td> <td>Straightforward and easy to calculate.</td> <td>Ensures budget predictability, and encourages efficiency.</td> <td> Higher earnings when the impact is significant. Emphasizes results. </td> <td> Ensures a steady and predictable income stream. Builds longterm business relationships. </td> <td> Caters to various client needs and budgets. Simplifies clients’ decision-making. </td> </tr> <tr> <td><strong>Challenges</strong></td> <td> May incentivize slower work. Emphasizes hours worked rather than value of work. </td> <td> Unforeseen changes or requests can lead to scope creep, and threaten profitability. </td> <td> Dependent on ability to communicate the value delivered effectively. </td> <td>Dependent on client’s trust.</td> <td> Lack of transparency in terms and pricing may cause confusion. </td> </tr> <tr> <td><strong>Ideal projects or clients</strong></td> <td> Small projects, or projects subject to change due to timelines or requirements. </td> <td>Projects with clear expectations and scope.</td> <td>Clients with clear pain points and business goals.</td> <td>Repeat and ongoing client projects.</td> <td>Client roster with widely varying needs and budgets.</td> </tr> </tbody> </table> <h3>Second table</h3> <table> <thead> <tr> <th scope="col">Pricing Strategies</th> <th scope="col">Hourly-based</th> <th scope="col">Project-based</th> <th scope="col">Value-based</th> <th scope="col">Retainer-based</th> <th scope="col">Tier-based</th> </tr> </thead> <tbody> <tr> <td><strong>Overview</strong></td> <td>Pricing per hour.</td> <td>Fixed price per project.</td> <td>Fixed price based on value delivered.</td> <td>Fixed price for a set number of hours.</td> <td>Fixed price packages at different price points.</td> </tr> <tr> <td><strong>Benefits</strong></td> <td>Straightforward and easy to calculate.</td> <td>Ensures budget predictability, and encourages efficiency.</td> <td> Higher earnings when the impact is significant. Emphasizes results. </td> <td> Ensures a steady and predictable income stream. Builds longterm business relationships. </td> <td> Caters to various client needs and budgets. Simplifies clients’ decision-making. </td> </tr> <tr> <td><strong>Challenges</strong></td> <td> May incentivize slower work. Emphasizes hours worked rather than value of work. </td> <td> Unforeseen changes or requests can lead to scope creep, and threaten profitability. </td> <td> Dependent on ability to communicate the value delivered effectively. </td> <td>Dependent on client’s trust.</td> <td> Lack of transparency in terms and pricing may cause confusion. </td> </tr> <tr> <td><strong>Ideal projects or clients</strong></td> <td> Small projects, or projects subject to change due to timelines or requirements. </td> <td>Projects with clear expectations and scope.</td> <td>Clients with clear pain points and business goals.</td> <td>Repeat and ongoing client projects.</td> <td>Client roster with widely varying needs and budgets.</td> </tr> </tbody> </table> </table-saw> <h2>Console logs an error when missing `th` elements</h2> <table-saw breakpoint="(max-width: 43.6875em)"> <table> <thead> <tr> <td>Pricing Strategies</td> <td>Hourly-based</td> <td>Project-based</td> </tr> </thead> <tbody> <tr> <td><strong>Ideal projects or clients</strong></td> <td> Small projects, or projects subject to change due to timelines or requirements. </td> <td>Projects with clear expectations and scope.</td> </tr> </tbody> </table> </table-saw> <h2>Hidden in details</h2> <details> <summary>Expand to show</summary> <table-saw breakpoint="(max-width: 30em)"> <table> <thead> <tr> <th>Pricing Strategies</th> <th>Hourly-based</th> <th>Project-based</th> </tr> </thead> <tbody> <tr> <td><strong>Ideal projects or clients</strong></td> <td> Small projects, or projects subject to change due to timelines or requirements. </td> <td>Projects with clear expectations and scope.</td> </tr> </tbody> </table> </table-saw> </details> <h2>Shadow root</h2> <script type="module"> const host = document.querySelector("#myHost"); const shadow = host.attachShadow({ mode: "open" }); const div = document.createElement("div"); div.innerHTML = `<table-saw breakpoint="(max-width: 30em)"> <table> <thead> <tr> <th>Pricing Strategies</th> <th>Hourly-based</th> <th>Project-based</th> </tr> </thead> <tbody> <tr> <td><strong>Ideal projects or clients</strong></td> <td> Small projects, or projects subject to change due to timelines or requirements. </td> <td>Projects with clear expectations and scope.</td> </tr> </tbody> </table> </table-saw>`; shadow.appendChild(div); </script> <div id="myHost"></div> </main> </body> </html>
zachleat/table-saw
336
A small web component for responsive <table> elements.
HTML
zachleat
Zach Leatherman
11ty, fortawesome
table-saw.js
JavaScript
class Tablesaw extends HTMLElement { static dupes = {}; constructor() { super(); this.autoOffset = 50; this._needsStylesheet = true; this.attrs = { breakpoint: "breakpoint", breakpointBackwardsCompat: "media", type: "type", ratio: "ratio", label: "data-tablesaw-label", zeropad: "zero-padding", forceTextAlign: "text-align" }; this.defaults = { breakpoint: '(max-width: 39.9375em)', // same as Filament Group’s Tablesaw ratio: '1fr 2fr', }; this.classes = { wrap: "tablesaw-wrap" } this.props = { ratio: "--table-saw-ratio", bold: "--table-saw-header-bold", }; } generateCss(breakpoint, type) { return ` table-saw.${this._id} { display: block; ${type === "container" ? "container-type: inline-size;" : ""} } @${type} ${breakpoint} { table-saw.${this._id} thead :is(th, td) { position: absolute; height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px); } table-saw.${this._id} :is(tbody, tfoot) tr { display: block; } table-saw.${this._id} :is(tbody, tfoot) :is(th, td):before { font-weight: var(${this.props.bold}); content: attr(${this.attrs.label}); } table-saw.${this._id} :is(tbody, tfoot) :is(th, td) { display: grid; gap: 0 1em; grid-template-columns: var(${this.props.ratio}, ${this.defaults.ratio}); } table-saw.${this._id}[${this.attrs.forceTextAlign}] :is(tbody, tfoot) :is(th, td) { text-align: ${this.getAttribute(this.attrs.forceTextAlign) || "left"}; } table-saw.${this._id}[${this.attrs.zeropad}] :is(tbody, tfoot) :is(th, td) { padding-left: 0; padding-right: 0; } }`; } connectedCallback() { // Cut-the-mustard // https://caniuse.com/mdn-api_cssstylesheet_replacesync if(!("replaceSync" in CSSStyleSheet.prototype)) { return; } this.addHeaders(); this.setRatio(); if(!this._needsStylesheet) { return; } let sheet = new CSSStyleSheet(); let breakpoint = this.getAttribute(this.attrs.breakpoint) || this.getAttribute(this.attrs.breakpointBackwardsCompat) || this.defaults.breakpoint; let type = this.getAttribute(this.attrs.type) || "media"; this._id = `ts_${type.slice(0, 1)}${breakpoint.replace(/[^a-z0-9]/gi, "_")}`; this.classList.add(this._id); if(!Tablesaw.dupes[this._id]) { let css = this.generateCss(breakpoint, type); sheet.replaceSync(css); let root = this.getRootNode(); root.adoptedStyleSheets.push(sheet); // only add to global de-dupe if not a shadow root if(root.host && root !== root.host.shadowRoot) { Tablesaw.dupes[this._id] = true; } } } addHeaders() { let headerCells = this.querySelectorAll("thead th"); let labels = Array.from(headerCells).map((cell, index) => { // Set headers to be bold (if headers are bold) if(index === 0) { let styles = window.getComputedStyle(cell); if(styles) { // Copy other styles? let bold = styles.getPropertyValue("font-weight"); this.setBold(bold); } } let label = cell.innerText.trim(); if (label === "") { label = cell.textContent.trim(); } return label; }); if(labels.length === 0) { this._needsStylesheet = false; console.error("No `<th>` elements found:", this); return; } let cells = this.querySelectorAll("tbody :is(td, th)"); for(let cell of cells) { if(!labels[cell.cellIndex]) { continue; } cell.setAttribute(this.attrs.label, labels[cell.cellIndex]); let nodeCount = 0; for(let n of cell.childNodes) { // text or element node if(n.nodeType === 3 || n.nodeType === 1) { nodeCount++; } } // wrap if this cell has child nodes for correct grid alignment if(nodeCount > 1) { let wrapper = document.createElement("div"); wrapper.classList.add(this.classes.wrap); while(cell.firstChild) { wrapper.appendChild(cell.firstChild); } cell.appendChild(wrapper); } } } setBold(bold) { if(bold || bold === "") { this.style.setProperty(this.props.bold, bold); } } setRatio() { let ratio = this.getAttribute(this.attrs.ratio); if(ratio) { let ratioString = ratio.split("/").join("fr ") + "fr"; this.style.setProperty(this.props.ratio, ratioString); } } } if("customElements" in window) { window.customElements.define("table-saw", Tablesaw); } export { Tablesaw };
zachleat/table-saw
336
A small web component for responsive <table> elements.
HTML
zachleat
Zach Leatherman
11ty, fortawesome
demo.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <title>&lt;throb-ber&gt; Web Component</title> <style> /* Demo styles */ body { font-family: system-ui, sans-serif; } /* See https://www.zachleat.com/web/fluid-images/#content-layout-shift-addendum */ img { display: block; max-width: 100%; height: auto; } /* Demo styles */ throb-ber { max-width: 30em; } </style> <script type="module" src="throbber.js"></script> <script type="module"> // Transparent image swaps to real image after simulated 2 seconds setTimeout(() => { let images = document.getElementsByClassName("demo-image"); for(let img of images) { let throbber = img.closest("throb-ber"); throbber.removeAttribute("pause"); img.src ='https://v1.screenshot.11ty.dev/https%3A%2F%2Fconf.11ty.dev%2Fticket-image%2F876cecc5531648eab7137c5f853c7539/opengraph/'; } }, 2000); </script> </head> <body> <header> <h1>&lt;throb-ber&gt; Web Component</h1> </header> <main> <p><a href="https://github.com/zachleat/throbber">Back to the Source Code</a></p> <p>These images have a simulated +2s loading delay.</p> <h2>Stock</h2> <!-- this `pause` attribute is for swapping the src from a Data URI, you probably don’t want it --> <throb-ber pause style="background: #666;"> <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E" alt="One uniquely generated virtual ticket for 11ty Conference." width="1200" height="630" loading="eager" decoding="async" class="demo-image"> </throb-ber> <h2>Custom height</h3> <throb-ber pause style="background: #666; --throbber-height: 100%;"> <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E" alt="One uniquely generated virtual ticket for 11ty Conference." width="1200" height="630" loading="eager" decoding="async" class="demo-image"> </throb-ber> <h2>Custom Gradient</h2> <throb-ber pause style="background: #ddd; --throbber-opacity: 1; --throbber-image: linear-gradient(to right, white, rebeccapurple)"> <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E" alt="One uniquely generated virtual ticket for 11ty Conference." width="1200" height="630" loading="eager" decoding="async" class="demo-image"> </throb-ber> </main> </body> </html>
zachleat/throbber
17
A loading indicator overlay for images (and maybe other things later).
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
throbber.js
JavaScript
class Throbber extends HTMLElement { static tagName = "throb-ber"; static register(tagName, registry) { if(!registry && ("customElements" in globalThis)) { registry = globalThis.customElements; } registry?.define(tagName || this.tagName, this); } static attr = { delay: "delay", // minimum amount of time before the throbber shows pause: "pause", // even if an image load event fires, don’t resolve yet (datauri to real url swapping) }; static classes = { throbber: "throbber", active: "active", }; static css = ` @keyframes rainbow { 0% { background-position: 0% 50%; } 100% { background-position: 100% 50%; } } :host { display: block; position: var(--throbber-position, relative); /* Allow other parents to be stacking context */ } .${Throbber.classes.throbber}, .${Throbber.classes.throbber}:before { position: absolute; inset: 0; bottom: auto; z-index: 1; pointer-events: none; height: var(--throbber-height, .5em); } :host(:not(.${Throbber.classes.active})) .${Throbber.classes.throbber}:before { opacity: 0; } .${Throbber.classes.throbber}:before { content: ""; display: block; opacity: var(--throbber-opacity, .8); transition: opacity .3s; background-image: var(--throbber-image, linear-gradient(238deg, #ff0000, #ff8000, #ffff00, #80ff00, #00ff00, #00ff80, #00ffff, #0080ff, #0000ff, #8000ff, #ff0080)); background-size: 1200% 1200%; background-position: 2% 80%; animation: rainbow 4s ease-out alternate infinite; } @media (prefers-reduced-motion: reduce) { .${Throbber.classes.throbber} { animation: none; } } `; get delay() { return parseInt(this.getAttribute(Throbber.attr.delay), 10) || 200; } get isPaused() { return this.hasAttribute(Throbber.attr.pause); } useAnimation() { return "matchMedia" in window && !window.matchMedia('(prefers-reduced-motion: reduce)').matches; } connectedCallback() { // https://caniuse.com/mdn-api_cssstylesheet_replacesync if(this.shadowRoot || !("replaceSync" in CSSStyleSheet.prototype) || !this.useAnimation()) { return; } let shadowroot = this.attachShadow({ mode: "open" }); let sheet = new CSSStyleSheet(); sheet.replaceSync(Throbber.css); shadowroot.adoptedStyleSheets = [sheet]; let slot = document.createElement("slot"); shadowroot.appendChild(slot); let throbber = document.createElement("div"); throbber.classList.add(Throbber.classes.throbber); // feature?: click to remove // throbber.addEventListener("click", () => { // this.removeIndicator(); // }) shadowroot.appendChild(throbber); let promises = []; let images = this.querySelectorAll("img"); if(images.length > 0) { if(this.delay && !this.isPaused) { setTimeout(() => { this.addIndicator(); }, this.delay) } else { this.addIndicator(); } for(let img of images) { promises.push(new Promise((resolve, reject) => { // resolve on error on on load img.addEventListener("load", () => { if(!this.isPaused) { resolve() } }); img.addEventListener("error", () => { if(!this.isPaused) { resolve() } }); })); } } this.ready = Promise.all(promises).then(() => { this.finished = true; this.removeIndicator(); }); } addIndicator() { if(this.finished) { return; } this.classList.add(Throbber.classes.active); } removeIndicator() { this.classList.remove(Throbber.classes.active); } } Throbber.register(); export { Throbber }
zachleat/throbber
17
A loading indicator overlay for images (and maybe other things later).
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
demo.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <title>&lt;webcare-webshare&gt; Web Component</title> <style> /* Demo styles */ body { font-family: system-ui, sans-serif; } button { border-radius: .5em; padding: .25em; font-size: 1.5em; line-height: 1; } </style> <script type="module" src="webcare-webshare.js"></script> </head> <body> <header> <h1>&lt;webcare-webshare&gt; Web Component</h1> </header> <main> <p><a href="https://github.com/zachleat/webcare-webshare">Back to the Source Code</a></p> <h2>Stock</h2> <p>Prefers the Web Share API, falls back to a copy to clipboard feature when unavailable.</p> <webcare-webshare share-text="I am going to the 11ty Conference! #11ty #11tyConf" share-url="https://conf.11ty.dev/"> <button disabled>Share your ticket!</button> </webcare-webshare> <h2>Custom button text for Clipboard (before and after)</h2> <p>Set custom text on the button when the Web Share API is not available.</p> <webcare-webshare share-text="I am going to the 11ty Conference! #11ty #11tyConf" share-url="https://conf.11ty.dev/" label-copy="📋 Copy your ticket URL" label-after-copy="✅ Copied to Clipboard"> <button disabled>Share your ticket!</button> </webcare-webshare> <h2>Custom content for Clipboard</h2> <p>Override <code>share-url</code> as the default content that is copied when using Copy to Clipboard.</p> <webcare-webshare share-text="I am going to the 11ty Conference! #11ty #11tyConf" share-url="https://conf.11ty.dev/" copy-text="Go to https://conf.11ty.dev/"> <button disabled>Share your ticket!</button> </webcare-webshare> </main> </body> </html>
zachleat/webcare-webshare
25
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
webcare-webshare.js
JavaScript
// Inspired by https://web.dev/patterns/web-apps/share/ class WebcareWebshare extends HTMLElement { static tagName = "webcare-webshare"; static register(tagName, registry) { if(!registry && ("customElements" in globalThis)) { registry = globalThis.customElements; } registry?.define(tagName || this.tagName, this); } static attr = { text: "share-text", url: "share-url", copyContent: "copy-text", // optional, defaults to url labelCopy: "label-copy", labelAfterCopied: "label-after-copy", } get text() { return this.getAttribute(WebcareWebshare.attr.text) || document.title; } get url() { if(this.hasAttribute(WebcareWebshare.attr.url)) { return this.getAttribute(WebcareWebshare.attr.url); } let canonical = document.querySelector('link[rel="canonical"]'); return canonical?.href || location.href; } get copyLabel() { return this.getAttribute(WebcareWebshare.attr.labelAfterCopied) || "Copied."; } get copyContent() { return this.getAttribute(WebcareWebshare.attr.copyContent) || this.url; } canShare() { return "share" in navigator; } connectedCallback() { if(this.shadowRoot) { return; } let shadowroot = this.attachShadow({ mode: "open" }); let slot = document.createElement("slot"); shadowroot.appendChild(slot); this.button = this.querySelector("button"); this.button?.removeAttribute("disabled"); let copyLabel = this.getAttribute(WebcareWebshare.attr.labelCopy); if(this.button && !this.canShare() && copyLabel) { this.button.innerText = copyLabel; } this.button?.addEventListener("click", () => { this.share(); }); } async copyToClipboard() { if(!("clipboard" in navigator)) { return; } await navigator.clipboard.writeText(this.copyContent); if(this.button) { this.button.textContent = this.copyLabel; } } async share() { // Feature detection to see if the Web Share API is supported. if (!this.canShare()) { await this.copyToClipboard(); return; } try { await navigator.share({ url: this.url, text: this.text, title: this.text, }); return; } catch (err) { // If the user cancels, an `AbortError` is thrown. if (err.name !== "AbortError") { console.error(err.name, err.message); } } } } WebcareWebshare.register(); export { WebcareWebshare }
zachleat/webcare-webshare
25
JavaScript
zachleat
Zach Leatherman
11ty, fortawesome
main.go
Go
package main import ( "bytes" "fmt" "os" "os/exec" "path/filepath" "strings" "github.com/yuin/goldmark" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/renderer/html" ) var version = "dev" // Set by GoReleaser at build time // Markdown to HTML converter using goldmark var md goldmark.Markdown func init() { // Configure goldmark with table support and safe HTML rendering md = goldmark.New( goldmark.WithExtensions( extension.Table, // Enable Markdown table support ), goldmark.WithRendererOptions( html.WithUnsafe(), // Allow raw HTML passthrough ), ) } // convertMarkdownToHTML converts Markdown text to HTML func convertMarkdownToHTML(markdown string) (string, error) { var buf bytes.Buffer if err := md.Convert([]byte(markdown), &buf); err != nil { return "", fmt.Errorf("markdown conversion failed: %w", err) } // Trim trailing newline (goldmark adds it) html := strings.TrimSuffix(buf.String(), "\n") return html, nil } // readAndConvertFile reads a file and converts it to HTML if it's Markdown func readAndConvertFile(path string) (string, error) { content, err := os.ReadFile(path) if err != nil { return "", fmt.Errorf("failed to read file %s: %w", path, err) } ext := strings.ToLower(filepath.Ext(path)) // If .html file, return as-is if ext == ".html" || ext == ".htm" { return string(content), nil } // If .md file or no extension, convert Markdown to HTML if ext == ".md" || ext == "" { return convertMarkdownToHTML(string(content)) } // Unknown extension - assume Markdown for safety (agent-friendly default) return convertMarkdownToHTML(string(content)) } // processArgs intercepts and modifies arguments for Markdown conversion func processArgs(args []string) ([]string, error) { result := make([]string, 0, len(args)) i := 0 for i < len(args) { arg := args[i] // Check for flags that need conversion if arg == "--description" || arg == "--body" { if i+1 >= len(args) { return nil, fmt.Errorf("flag %s requires a value", arg) } // Convert inline Markdown text to HTML markdown := args[i+1] html, err := convertMarkdownToHTML(markdown) if err != nil { return nil, fmt.Errorf("converting %s: %w", arg, err) } result = append(result, arg, html) i += 2 continue } if arg == "--description_file" || arg == "--body_file" { if i+1 >= len(args) { return nil, fmt.Errorf("flag %s requires a file path", arg) } // Read file and convert to HTML filePath := args[i+1] html, err := readAndConvertFile(filePath) if err != nil { return nil, err } // Create temp file with HTML content tmpFile, err := os.CreateTemp("", "fizzy-md-*.html") if err != nil { return nil, fmt.Errorf("failed to create temp file: %w", err) } defer tmpFile.Close() if _, err := tmpFile.WriteString(html); err != nil { return nil, fmt.Errorf("failed to write temp file: %w", err) } // Replace flag with temp file path result = append(result, arg, tmpFile.Name()) i += 2 continue } // Pass through all other arguments unchanged result = append(result, arg) i++ } return result, nil } func main() { // Get original args (skip program name) args := os.Args[1:] // Handle --version flag if len(args) == 1 && (args[0] == "--version" || args[0] == "-v") { fmt.Printf("fizzy-md version %s\n", version) os.Exit(0) } // Handle stdin mode: if no args and stdin is piped, convert and output if len(args) == 0 { stat, _ := os.Stdin.Stat() if (stat.Mode() & os.ModeCharDevice) == 0 { // Stdin is piped, not a terminal var buf bytes.Buffer if _, err := buf.ReadFrom(os.Stdin); err != nil { fmt.Fprintf(os.Stderr, "fizzy-md error: failed to read stdin: %v\n", err) os.Exit(1) } html, err := convertMarkdownToHTML(buf.String()) if err != nil { fmt.Fprintf(os.Stderr, "fizzy-md error: %v\n", err) os.Exit(1) } fmt.Print(html) os.Exit(0) } } // Process args for Markdown conversion processedArgs, err := processArgs(args) if err != nil { fmt.Fprintf(os.Stderr, "fizzy-md error: %v\n", err) os.Exit(1) } // Find fizzy executable fizzyPath, err := exec.LookPath("fizzy") if err != nil { fmt.Fprintf(os.Stderr, "fizzy-md error: fizzy command not found in PATH\n") fmt.Fprintf(os.Stderr, "Please install fizzy-cli: https://github.com/robzolkos/fizzy-cli\n") os.Exit(1) } // Execute real fizzy with processed args cmd := exec.Command(fizzyPath, processedArgs...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { if exitErr, ok := err.(*exec.ExitError); ok { os.Exit(exitErr.ExitCode()) } fmt.Fprintf(os.Stderr, "fizzy-md error: %v\n", err) os.Exit(1) } }
zainfathoni/fizzy-md
2
Transparent Markdown→HTML wrapper for Fizzy CLI. Write natural Markdown, get perfect HTML for Fizzy cards and comments.
Go
zainfathoni
Zain Fathoni
book-that-app
main_test.go
Go
package main import ( "os" "path/filepath" "strings" "testing" ) func TestConvertMarkdownToHTML(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "simple paragraph", input: "Hello world", expected: "<p>Hello world</p>", }, { name: "heading h2", input: "## Heading", expected: "<h2>Heading</h2>", }, { name: "heading h3", input: "### Subheading", expected: "<h3>Subheading</h3>", }, { name: "bold text", input: "This is **bold** text", expected: "<p>This is <strong>bold</strong> text</p>", }, { name: "italic text", input: "This is *italic* text", expected: "<p>This is <em>italic</em> text</p>", }, { name: "inline code", input: "Use `code` here", expected: "<p>Use <code>code</code> here</p>", }, { name: "unordered list", input: "- Item 1\n- Item 2\n- Item 3", expected: "<ul>\n<li>Item 1</li>\n<li>Item 2</li>\n<li>Item 3</li>\n</ul>", }, { name: "ordered list", input: "1. First\n2. Second\n3. Third", expected: "<ol>\n<li>First</li>\n<li>Second</li>\n<li>Third</li>\n</ol>", }, { name: "link", input: "Check [this link](https://example.com)", expected: `<p>Check <a href="https://example.com">this link</a></p>`, }, { name: "code block", input: "```\ncode here\n```", expected: "<pre><code>code here\n</code></pre>", }, { name: "code block with language", input: "```go\nfunc main() {}\n```", expected: "<pre><code class=\"language-go\">func main() {}\n</code></pre>", }, { name: "blockquote", input: "> This is a quote", expected: "<blockquote>\n<p>This is a quote</p>\n</blockquote>", }, { name: "complex document", input: "## Overview\n\nThis is **important**.\n\n- Item 1\n- Item 2", expected: "<h2>Overview</h2>\n<p>This is <strong>important</strong>.</p>\n<ul>\n<li>Item 1</li>\n<li>Item 2</li>\n</ul>", }, { name: "empty string", input: "", expected: "", }, { name: "emoji preservation", input: "Status: ✅ Complete 🚀", expected: "<p>Status: ✅ Complete 🚀</p>", }, { name: "simple table", input: "| Name | Value |\n|------|-------|\n| Foo | Bar |\n| Baz | Qux |", expected: `<table> <thead> <tr> <th>Name</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>Foo</td> <td>Bar</td> </tr> <tr> <td>Baz</td> <td>Qux</td> </tr> </tbody> </table>`, }, { name: "table with alignment", input: "| Left | Center | Right |\n|:-----|:------:|------:|\n| A | B | C |", expected: `<table> <thead> <tr> <th style="text-align:left">Left</th> <th style="text-align:center">Center</th> <th style="text-align:right">Right</th> </tr> </thead> <tbody> <tr> <td style="text-align:left">A</td> <td style="text-align:center">B</td> <td style="text-align:right">C</td> </tr> </tbody> </table>`, }, { name: "table with inline formatting", input: "| **Bold** | *Italic* | `Code` |\n|----------|----------|--------|\n| foo | bar | baz |", expected: `<table> <thead> <tr> <th><strong>Bold</strong></th> <th><em>Italic</em></th> <th><code>Code</code></th> </tr> </thead> <tbody> <tr> <td>foo</td> <td>bar</td> <td>baz</td> </tr> </tbody> </table>`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := convertMarkdownToHTML(tt.input) if err != nil { t.Fatalf("unexpected error: %v", err) } if result != tt.expected { t.Errorf("\nInput: %q\nExpected: %q\nGot: %q", tt.input, tt.expected, result) } }) } } func TestReadAndConvertFile(t *testing.T) { // Create temp directory for test files tmpDir := t.TempDir() tests := []struct { name string filename string content string expected string expectError bool }{ { name: "markdown file (.md)", filename: "test.md", content: "## Hello\n\nWorld", expected: "<h2>Hello</h2>\n<p>World</p>", }, { name: "html file (.html) - passthrough", filename: "test.html", content: "<h2>Already HTML</h2>", expected: "<h2>Already HTML</h2>", }, { name: "htm file (.htm) - passthrough", filename: "test.htm", content: "<p>Also HTML</p>", expected: "<p>Also HTML</p>", }, { name: "no extension - assume markdown", filename: "notes", content: "**Bold** text", expected: "<p><strong>Bold</strong> text</p>", }, { name: "txt extension - convert as markdown", filename: "notes.txt", content: "## Heading", expected: "<h2>Heading</h2>", }, { name: "non-existent file", filename: "does-not-exist.md", content: "", expected: "", expectError: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var filePath string if !tt.expectError || tt.filename != "does-not-exist.md" { // Create test file filePath = filepath.Join(tmpDir, tt.filename) if err := os.WriteFile(filePath, []byte(tt.content), 0644); err != nil { t.Fatalf("failed to create test file: %v", err) } } else { filePath = filepath.Join(tmpDir, tt.filename) } result, err := readAndConvertFile(filePath) if tt.expectError { if err == nil { t.Errorf("expected error but got none") } return } if err != nil { t.Fatalf("unexpected error: %v", err) } if result != tt.expected { t.Errorf("\nFilename: %s\nExpected: %q\nGot: %q", tt.filename, tt.expected, result) } }) } } func TestProcessArgs(t *testing.T) { tests := []struct { name string input []string checkFn func([]string) error expectError bool }{ { name: "passthrough - no conversion needed", input: []string{"card", "list", "--board", "123"}, checkFn: func(result []string) error { expected := []string{"card", "list", "--board", "123"} if len(result) != len(expected) { return nil // length mismatch will be caught } for i, v := range expected { if result[i] != v { return nil } } return nil }, }, { name: "convert --description flag", input: []string{"card", "create", "--title", "Test", "--description", "## Hello"}, checkFn: func(result []string) error { // Check that --description value was converted for i, v := range result { if v == "--description" && i+1 < len(result) { if !strings.Contains(result[i+1], "<h2>") { t.Errorf("expected HTML conversion, got: %s", result[i+1]) } return nil } } t.Error("--description flag not found in result") return nil }, }, { name: "convert --body flag", input: []string{"comment", "create", "--card", "42", "--body", "**Bold** text"}, checkFn: func(result []string) error { // Check that --body value was converted for i, v := range result { if v == "--body" && i+1 < len(result) { if !strings.Contains(result[i+1], "<strong>") { t.Errorf("expected HTML conversion, got: %s", result[i+1]) } return nil } } t.Error("--body flag not found in result") return nil }, }, { name: "missing value for --description", input: []string{"card", "create", "--description"}, expectError: true, }, { name: "missing value for --body", input: []string{"comment", "create", "--body"}, expectError: true, }, { name: "multiple flags in one command", input: []string{"card", "create", "--title", "Test", "--description", "## Hello", "--board", "123"}, checkFn: func(result []string) error { foundTitle := false foundBoard := false foundDescription := false for i, v := range result { if v == "--title" && i+1 < len(result) && result[i+1] == "Test" { foundTitle = true } if v == "--board" && i+1 < len(result) && result[i+1] == "123" { foundBoard = true } if v == "--description" && i+1 < len(result) { if strings.Contains(result[i+1], "<h2>") { foundDescription = true } } } if !foundTitle { t.Error("--title flag not preserved correctly") } if !foundBoard { t.Error("--board flag not preserved correctly") } if !foundDescription { t.Error("--description not converted correctly") } return nil }, }, { name: "empty args", input: []string{}, checkFn: func(result []string) error { if len(result) != 0 { t.Errorf("expected empty result, got %v", result) } return nil }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := processArgs(tt.input) if tt.expectError { if err == nil { t.Errorf("expected error but got none") } return } if err != nil { t.Fatalf("unexpected error: %v", err) } if tt.checkFn != nil { tt.checkFn(result) } }) } } func TestProcessArgsWithFiles(t *testing.T) { tmpDir := t.TempDir() // Create test markdown file mdFile := filepath.Join(tmpDir, "test.md") if err := os.WriteFile(mdFile, []byte("## From File\n\n- Item 1\n- Item 2"), 0644); err != nil { t.Fatalf("failed to create test file: %v", err) } // Create test HTML file (should passthrough) htmlFile := filepath.Join(tmpDir, "test.html") if err := os.WriteFile(htmlFile, []byte("<h2>Already HTML</h2>"), 0644); err != nil { t.Fatalf("failed to create test file: %v", err) } t.Run("convert --description_file with .md", func(t *testing.T) { result, err := processArgs([]string{"card", "create", "--title", "Test", "--description_file", mdFile}) if err != nil { t.Fatalf("unexpected error: %v", err) } // Find the converted file path for i, v := range result { if v == "--description_file" && i+1 < len(result) { tmpPath := result[i+1] content, err := os.ReadFile(tmpPath) if err != nil { t.Fatalf("failed to read temp file: %v", err) } if !strings.Contains(string(content), "<h2>From File</h2>") { t.Errorf("expected converted HTML, got: %s", content) } if !strings.Contains(string(content), "<li>Item 1</li>") { t.Errorf("expected list conversion, got: %s", content) } return } } t.Error("--description_file flag not found in result") }) t.Run("passthrough --description_file with .html", func(t *testing.T) { result, err := processArgs([]string{"card", "create", "--title", "Test", "--description_file", htmlFile}) if err != nil { t.Fatalf("unexpected error: %v", err) } // Find the file path - should still create temp file but with passthrough content for i, v := range result { if v == "--description_file" && i+1 < len(result) { tmpPath := result[i+1] content, err := os.ReadFile(tmpPath) if err != nil { t.Fatalf("failed to read temp file: %v", err) } if string(content) != "<h2>Already HTML</h2>" { t.Errorf("expected passthrough, got: %s", content) } return } } t.Error("--description_file flag not found in result") }) t.Run("error on non-existent file", func(t *testing.T) { _, err := processArgs([]string{"card", "create", "--description_file", "/nonexistent/file.md"}) if err == nil { t.Error("expected error for non-existent file") } }) } // Benchmark for performance requirement (<100ms) func BenchmarkConvertMarkdownToHTML(b *testing.B) { input := `## Overview This is a **complex** document with multiple elements. ### Features - Feature 1 with ` + "`code`" + ` - Feature 2 with **bold** - Feature 3 with *italic* ### Code Example ` + "```go\nfunc main() {\n fmt.Println(\"Hello\")\n}\n```" + ` ### Conclusion > This is a blockquote for emphasis. Visit [our site](https://example.com) for more info. ` b.ResetTimer() for i := 0; i < b.N; i++ { _, _ = convertMarkdownToHTML(input) } } func BenchmarkProcessArgs(b *testing.B) { args := []string{ "card", "create", "--title", "Test Card", "--description", "## Hello\n\nThis is **bold** and *italic*.\n\n- Item 1\n- Item 2", "--board", "123", } b.ResetTimer() for i := 0; i < b.N; i++ { _, _ = processArgs(args) } }
zainfathoni/fizzy-md
2
Transparent Markdown→HTML wrapper for Fizzy CLI. Write natural Markdown, get perfect HTML for Fizzy cards and comments.
Go
zainfathoni
Zain Fathoni
book-that-app
example/lib/main.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/widgets.dart'; import 'package:chicago/chicago.dart'; import 'src/activity_indicators.dart'; import 'src/alerts.dart'; import 'src/asset_image_precache.dart'; import 'src/buttons.dart'; import 'src/calendars.dart'; import 'src/lists.dart'; import 'src/navigation.dart'; import 'src/spinners.dart'; import 'src/splitters.dart'; import 'src/tables.dart'; void main() { runApp(KitchenSink()); } class KitchenSink extends StatelessWidget { const KitchenSink({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ChicagoApp( title: 'Chicago "Kitchen Sink" Demo', home: ColoredBox( color: const Color(0xffdddcd5), child: Padding( padding: const EdgeInsets.all(8), child: BorderPane( borderColor: const Color(0xff999999), backgroundColor: const Color(0xfff7f5ee), child: AssetImagePrecache( paths: const <String>[ 'assets/anchor.png', 'assets/bell.png', 'assets/clock.png', 'assets/cup.png', 'assets/flag_red.png', 'assets/house.png', 'assets/star.png', ], loadingIndicator: Container(), child: ScrollPane( view: BoxPane( padding: const EdgeInsets.all(6), children: const <Widget>[ ButtonsDemo(), ListsDemo(), CalendarsDemo(), NavigationDemo(), SplittersDemo(), ActivityIndicatorsDemo(), SpinnersDemo(), TablesDemo(), AlertsDemo(), ], ), ), ), ), ), ), ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/activity_indicators.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; class ActivityIndicatorsDemo extends StatelessWidget { const ActivityIndicatorsDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Rollup( heading: const HeaderText('Meters & Activity Indicators'), semanticLabel: 'Meters and activity indicators', childBuilder: (BuildContext context) { return BorderPane( borderColor: const Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: const EdgeInsets.fromLTRB(4, 2, 4, 4), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: const [ MetersDemo(), SizedBox(width: 12), ActivityIndicatorDemo(), ], ), ), ); }, ); } } class MetersDemo extends StatelessWidget { const MetersDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Meters'), SizedBox(height: 12), Row( children: [ Meter.simple(percentage: 0.5, gridFrequency: 1, text: '50%'), SizedBox(width: 6), Text('50%'), ], ), SizedBox(height: 8), Row( children: [ Meter(percentage: 0.4, gridFrequency: 0.1), SizedBox(width: 6), Text('40%'), ], ), SizedBox(height: 8), Row( children: [Meter(percentage: 0.75), SizedBox(width: 6), Text('75%')], ), SizedBox(height: 8), Row( children: [ Meter.simple(percentage: 0.75, gridFrequency: 1, text: '75%'), SizedBox(width: 6), Text('75%'), ], ), SizedBox(height: 8), Row( children: [ Meter(percentage: 0.95, fillColor: const Color(0xffaa0000)), SizedBox(width: 6), Text('Danger: 95%!'), ], ), ], ); } } class ActivityIndicatorDemo extends StatelessWidget { const ActivityIndicatorDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Activity Indicators'), Row( crossAxisAlignment: CrossAxisAlignment.start, children: const <Widget>[ SizedBox(width: 24, height: 24, child: ActivityIndicator()), SizedBox( width: 48, height: 48, child: ActivityIndicator(color: Color(0xffaa0000)), ), SizedBox( width: 96, height: 96, child: ActivityIndicator(color: Color(0xff4c82b8)), ), ], ), ], ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/alerts.dart
Dart
import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; class AlertsDemo extends StatefulWidget { const AlertsDemo({Key? key}) : super(key: key); @override _AlertsDemoState createState() => _AlertsDemoState(); } class _AlertsDemoState extends State<AlertsDemo> { late RadioButtonController<MessageType?> _controller; late RadioButtonController<String> _iconController; static const Map<MessageType, String> _messages = { MessageType.error: 'This is an error message.', MessageType.warning: 'This is a warning message.', MessageType.question: 'This is a question message.', MessageType.info: 'This is an info message.', }; void _handleShowPrompt() { if (_controller.value != null) { Prompt.open( context: context, messageType: _controller.value!, message: _messages[_controller.value!]!, body: Container(), options: ['OK'], selectedOption: 0, ); } else { Prompt.open( context: context, messageType: MessageType.question, message: 'Please select your favorite icon:', body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ RadioButton<String>( value: 'bell', controller: _iconController, trailing: Row( children: [ Image(image: AssetImage('assets/bell.png')), SizedBox(width: 4), Text('Bell'), ], ), ), SizedBox(height: 4), RadioButton<String>( value: 'clock', controller: _iconController, trailing: Row( children: [ Image(image: AssetImage('assets/clock.png')), SizedBox(width: 4), Text('Clock'), ], ), ), SizedBox(height: 4), RadioButton<String>( value: 'house', controller: _iconController, trailing: Row( children: [ Image(image: AssetImage('assets/house.png')), SizedBox(width: 4), Text('House'), ], ), ), ], ), options: ['OK', 'Cancel'], selectedOption: 0, ); } } @override void initState() { super.initState(); _controller = RadioButtonController<MessageType>(MessageType.error); _iconController = RadioButtonController<String>('house'); } @override void dispose() { _controller.dispose(); _iconController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Rollup( heading: HeaderText('Alerts'), semanticLabel: 'Alerts', childBuilder: (BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ RadioButton<MessageType?>( value: MessageType.error, controller: _controller, trailing: Text('Error'), ), SizedBox(height: 4), RadioButton<MessageType?>( value: MessageType.warning, controller: _controller, trailing: Text('Warning'), ), SizedBox(height: 4), RadioButton<MessageType?>( value: MessageType.question, controller: _controller, trailing: Text('Question'), ), SizedBox(height: 4), RadioButton<MessageType?>( value: MessageType.info, controller: _controller, trailing: Text('Info'), ), SizedBox(height: 4), RadioButton<MessageType?>( value: null, controller: _controller, trailing: Text('Custom'), ), SizedBox(height: 6), PushButton(label: 'Show Prompt', onPressed: _handleShowPrompt), ], ), ), ); }, ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/asset_image_precache.dart
Dart
import 'package:flutter/widgets.dart'; class AssetImagePrecache extends StatefulWidget { const AssetImagePrecache({ Key? key, required this.paths, required this.child, this.loadingIndicator, }) : super(key: key); final List<String> paths; final Widget child; final Widget? loadingIndicator; @override _AssetImagePrecacheState createState() => _AssetImagePrecacheState(); } class _AssetImagePrecacheState extends State<AssetImagePrecache> { Iterable<Future<void>>? _futures; bool _isComplete = false; @override void didChangeDependencies() { super.didChangeDependencies(); if (_futures == null && !_isComplete) { // precacheImage() guarantees that the futures will not throw _futures = widget.paths .map<AssetImage>((String path) => AssetImage(path)) .map<Future<void>>( (AssetImage image) => precacheImage(image, context), ); Future.wait<void>(_futures!).then((void _) { setState(() { _futures = null; _isComplete = true; }); }); } } @override Widget build(BuildContext context) { return _isComplete ? widget.child : widget.loadingIndicator ?? widget.child; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/buttons.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; VoidCallback _acknowledgeAction(BuildContext context, String action) { return () { Prompt.open( context: context, messageType: MessageType.info, message: 'Registered $action.', body: Container(), options: ['OK'], selectedOption: 0, ); }; } VoidCallback _acknowledgeButtonPress(BuildContext context) { return _acknowledgeAction(context, 'a button press'); } VoidCallback _acknowledgeLinkPress(BuildContext context) { return _acknowledgeAction(context, 'a link'); } class ButtonsDemo extends StatefulWidget { const ButtonsDemo({Key? key}) : super(key: key); @override _ButtonsDemoState createState() => _ButtonsDemoState(); } class _ButtonsDemoState extends State<ButtonsDemo> { late RollupController _controller; @override void initState() { super.initState(); _controller = RollupController(isExpanded: true); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Rollup( controller: _controller, heading: HeaderText('Buttons'), semanticLabel: 'Buttons', childBuilder: (BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ BasicButtonsDemo(), SizedBox(width: 4), RadioButtonsDemo(), SizedBox(width: 4), CheckboxesDemo(), SizedBox(width: 4), LinkButtonsDemo(), ], ); }, ); } } class BasicButtonsDemo extends StatelessWidget { @override Widget build(BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: EdgeInsets.fromLTRB(4, 2, 4, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Basic Push Buttons'), SizedBox(height: 4), Row( children: [ PushButton( label: 'One', onPressed: _acknowledgeButtonPress(context), ), SizedBox(width: 4), PushButton( label: 'Two', onPressed: _acknowledgeButtonPress(context), ), SizedBox(width: 4), PushButton(label: 'Three'), ], ), SizedBox(height: 10), BoldText('Image Buttons'), SizedBox(height: 4), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ PushButton( label: 'Bell', icon: 'assets/bell.png', onPressed: _acknowledgeButtonPress(context), ), SizedBox(width: 4), PushButton( label: 'Clock', icon: 'assets/clock.png', axis: Axis.vertical, onPressed: _acknowledgeButtonPress(context), ), SizedBox(width: 4), PushButton(label: 'House', icon: 'assets/house.png'), ], ), SizedBox(height: 10), BoldText('Toolbar Buttons'), SizedBox(height: 4), Row( children: [ PushButton( icon: 'assets/bell.png', isToolbar: true, onPressed: _acknowledgeButtonPress(context), ), SizedBox(width: 4), PushButton( icon: 'assets/clock.png', isToolbar: true, onPressed: _acknowledgeButtonPress(context), ), SizedBox(width: 4), PushButton(icon: 'assets/house.png', isToolbar: true), ], ), ], ), ), ); } } class RadioButtonsDemo extends StatefulWidget { @override _RadioButtonsDemoState createState() => _RadioButtonsDemoState(); } class _RadioButtonsDemoState extends State<RadioButtonsDemo> { late RadioButtonController<String> _basicController; late RadioButtonController<String> _imageController; @override void initState() { super.initState(); _basicController = RadioButtonController('three'); _imageController = RadioButtonController('house'); } @override void dispose() { _basicController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: EdgeInsets.fromLTRB(4, 2, 4, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Basic Radio Buttons'), SizedBox(height: 4), Row( children: [ RadioButton<String>( value: 'one', controller: _basicController, trailing: Text('One'), ), SizedBox(width: 4), RadioButton<String>( value: 'two', controller: _basicController, trailing: Text('Two'), ), SizedBox(width: 4), RadioButton<String>( value: 'three', controller: _basicController, trailing: Text('Three'), isEnabled: false, ), ], ), SizedBox(height: 10), BoldText('Image Radio Buttons'), SizedBox(height: 4), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ RadioButton<String>( value: 'bell', controller: _imageController, trailing: Row( children: [ Image.asset('assets/bell.png'), SizedBox(width: 4), Text('Bell'), ], ), ), SizedBox(height: 4), RadioButton<String>( value: 'clock', controller: _imageController, trailing: Row( children: [ Image.asset('assets/clock.png'), SizedBox(width: 4), Text('Clock'), ], ), ), SizedBox(height: 4), RadioButton<String>( value: 'house', controller: _imageController, isEnabled: false, trailing: Row( children: [ Image.asset('assets/house.png'), SizedBox(width: 4), Text('House'), ], ), ), ], ), ], ), ), ); } } class CheckboxesDemo extends StatefulWidget { @override _CheckboxesDemoState createState() => _CheckboxesDemoState(); } class _CheckboxesDemoState extends State<CheckboxesDemo> { late CheckboxController _threeController; late CheckboxController _houseController; late CheckboxController _readController; late CheckboxController _writeController; late CheckboxController _executeController; @override void initState() { super.initState(); _threeController = CheckboxController.simple(true); _houseController = CheckboxController.simple(true); _readController = CheckboxController.triState( state: CheckboxState.checked, canUserToggleMixed: true, ); _writeController = CheckboxController.triState( state: CheckboxState.unchecked, canUserToggleMixed: true, ); _executeController = CheckboxController.triState( state: CheckboxState.mixed, canUserToggleMixed: true, ); } @override void dispose() { _threeController.dispose(); _houseController.dispose(); _readController.dispose(); _writeController.dispose(); _executeController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: EdgeInsets.fromLTRB(4, 2, 4, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Basic Checkboxes'), SizedBox(height: 4), Row( children: [ Checkbox(trailing: Text('One')), SizedBox(width: 4), Checkbox(trailing: Text('Two')), SizedBox(width: 4), Checkbox( trailing: Text('Three'), controller: _threeController, isEnabled: false, ), ], ), SizedBox(height: 10), BoldText('Image Checkboxes'), SizedBox(height: 4), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Checkbox( trailing: Row( children: [ Image.asset('assets/clock.png'), SizedBox(width: 4), Text('Clock'), ], ), ), SizedBox(height: 4), Checkbox( trailing: Row( children: [ Image.asset('assets/bell.png'), SizedBox(width: 4), Text('Bell'), ], ), ), SizedBox(height: 4), Checkbox( controller: _houseController, isEnabled: false, trailing: Row( children: [ Image.asset('assets/house.png'), SizedBox(width: 4), Text('House'), ], ), ), ], ), SizedBox(height: 10), BoldText('Tri-state Checkboxes'), SizedBox(height: 4), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Checkbox(controller: _readController, trailing: Text('Read')), SizedBox(height: 4), Checkbox(controller: _writeController, trailing: Text('Write')), SizedBox(height: 4), Checkbox( controller: _executeController, trailing: Text('Execute'), isEnabled: false, ), ], ), ], ), ), ); } } class LinkButtonsDemo extends StatelessWidget { @override Widget build(BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: EdgeInsets.fromLTRB(4, 2, 4, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Basic Link Buttons'), SizedBox(height: 4), Row( children: [ LinkButton( text: 'One', onPressed: _acknowledgeLinkPress(context), ), SizedBox(width: 4), LinkButton( text: 'Two', onPressed: _acknowledgeLinkPress(context), ), SizedBox(width: 4), LinkButton(text: 'Three'), ], ), SizedBox(height: 10), BoldText('Image Link Buttons'), SizedBox(height: 4), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ LinkButton( text: 'Bell', image: AssetImage('assets/bell.png'), onPressed: _acknowledgeLinkPress(context), ), SizedBox(height: 4), LinkButton( text: 'Clock', image: AssetImage('assets/clock.png'), onPressed: _acknowledgeLinkPress(context), ), SizedBox(height: 4), LinkButton( text: 'House', image: AssetImage('assets/house.png'), ), ], ), ], ), ), ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/calendars.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; class CalendarsDemo extends StatelessWidget { const CalendarsDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Rollup( heading: HeaderText('Calendars'), semanticLabel: 'Calendars', childBuilder: (BuildContext context) { return BorderPane( backgroundColor: Color(0xffffffff), borderColor: Color(0xff999999), child: Padding( padding: EdgeInsets.fromLTRB(6, 4, 6, 10), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Basic'), Calendar(initialYear: 2021, initialMonth: 2), ], ), SizedBox(width: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Calendar Buttons'), CalendarButton(initialSelectedDate: CalendarDate.today()), ], ), ], ), ), ); }, ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/lists.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; class ListsDemo extends StatelessWidget { const ListsDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Rollup( heading: const HeaderText('Lists'), semanticLabel: 'Lists', childBuilder: (BuildContext context) { return BorderPane( borderColor: const Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: const EdgeInsets.fromLTRB(4, 2, 4, 4), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: const [ BasicListDemo(), SizedBox(width: 12), LazyListDemo(), SizedBox(width: 12), MultiSelectListDemo(), SizedBox(width: 12), ImageListDemo(), SizedBox(width: 12), ListButtonsDemo(), ], ), ), ); }, ); } } class BasicListDemo extends StatefulWidget { const BasicListDemo({Key? key}) : super(key: key); @override _BasicListDemoState createState() => _BasicListDemoState(); } class _BasicListDemoState extends State<BasicListDemo> { late ListViewSelectionController _selectionController; static const List<String> _colors = [ 'Blue', 'Green', 'Orange', 'Purple', 'Red', 'Yellow', ]; static Widget _buildItem( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { String text = _colors[index]; return isSelected ? WhiteText(text) : Text(text); } @override void initState() { super.initState(); _selectionController = ListViewSelectionController(); } @override void dispose() { _selectionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const BoldText('Basic'), const SizedBox(height: 4), SizedBox( width: 72, height: 90, child: BorderPane( borderColor: const Color(0xff999999), child: ScrollableListView( itemHeight: 19, length: _colors.length, selectionController: _selectionController, itemBuilder: _buildItem, ), ), ), ], ); } } class LazyListDemo extends StatefulWidget { const LazyListDemo({Key? key}) : super(key: key); @override _LazyListDemoState createState() => _LazyListDemoState(); } class _LazyListDemoState extends State<LazyListDemo> { late ListViewSelectionController _selectionController; static Widget _buildItem( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { String text = '${index + 1}'; return isSelected ? WhiteText(text) : Text(text); } @override void initState() { super.initState(); _selectionController = ListViewSelectionController(); } @override void dispose() { _selectionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const BoldText('Lazy'), const SizedBox(height: 4), SizedBox( width: 90, height: 90, child: BorderPane( borderColor: const Color(0xff999999), child: ScrollableListView( itemHeight: 19, length: 1000000, selectionController: _selectionController, itemBuilder: _buildItem, ), ), ), ], ); } } class MultiSelectListDemo extends StatefulWidget { const MultiSelectListDemo({Key? key}) : super(key: key); @override _MultiSelectListDemoState createState() => _MultiSelectListDemoState(); } class _MultiSelectListDemoState extends State<MultiSelectListDemo> { late ListViewSelectionController _selectionController; static const List<String> _shapes = [ 'Circle', 'Ellipse', 'Square', 'Rectangle', 'Hexagon', 'Octagon', ]; static Widget _buildItem( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { String text = _shapes[index]; return isSelected ? WhiteText(text) : Text(text); } @override void initState() { super.initState(); _selectionController = ListViewSelectionController( selectMode: SelectMode.multi, )..selectedRanges = [Span(0, 0), Span(2, 3)]; } @override void dispose() { _selectionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const BoldText('Multi-Select'), const SizedBox(height: 4), SizedBox( width: 90, height: 90, child: BorderPane( borderColor: const Color(0xff999999), child: ScrollableListView( itemHeight: 19, length: _shapes.length, selectionController: _selectionController, itemBuilder: _buildItem, ), ), ), ], ); } } class ImageListDemo extends StatefulWidget { const ImageListDemo({Key? key}) : super(key: key); @override _ImageListDemoState createState() => _ImageListDemoState(); } class _ImageItem { const _ImageItem(this.name, this.asset); final String name; final String asset; } class _ImageListDemoState extends State<ImageListDemo> { late ListViewSelectionController _selectionController; late ListViewItemDisablerController _disablerController; static const List<_ImageItem> _items = [ _ImageItem('Anchor', 'assets/anchor.png'), _ImageItem('Bell', 'assets/bell.png'), _ImageItem('Clock', 'assets/clock.png'), _ImageItem('Cup', 'assets/cup.png'), _ImageItem('House', 'assets/house.png'), _ImageItem('Star', 'assets/star.png'), ]; static Widget _buildItem( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { final String text = _items[index].name; return Row( children: [ Image.asset(_items[index].asset), SizedBox(width: 4), isDisabled ? GreyText(text) : isSelected ? WhiteText(text) : Text(text), ], ); } @override void initState() { super.initState(); _selectionController = ListViewSelectionController(); _disablerController = ListViewItemDisablerController() ..filter = (int index) => index == 2 || index == 3; } @override void dispose() { _selectionController.dispose(); _disablerController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const BoldText('Image'), const SizedBox(height: 4), SizedBox( width: 90, height: 90, child: BorderPane( borderColor: const Color(0xff999999), child: ScrollableListView( itemHeight: 19, length: _items.length, selectionController: _selectionController, itemDisabledController: _disablerController, itemBuilder: _buildItem, ), ), ), ], ); } } class ListButtonsDemo extends StatefulWidget { const ListButtonsDemo({Key? key}) : super(key: key); @override _ListButtonsDemoState createState() => _ListButtonsDemoState(); } class _ColorItem { const _ColorItem(this.color, this.name); final Color color; final String name; } class _ListButtonsDemoState extends State<ListButtonsDemo> { late ListViewSelectionController _basicSelectionController; late ListViewSelectionController _imageSelectionController; late ListViewSelectionController _colorSelectionController; Widget _buildColorItem( _ColorItem item, { bool isSelected = false, bool includeName = true, }) { Widget result = SizedBox( width: 19, height: 19, child: SetBaseline( baseline: 15.5, child: DecoratedBox( decoration: BoxDecoration(border: Border.all(), color: item.color), ), ), ); if (includeName) { result = Row( children: [ result, SizedBox(width: 8), isSelected ? WhiteText(item.name) : Text(item.name), ], ); } return result; } @override void initState() { super.initState(); _basicSelectionController = ListViewSelectionController()..selectedIndex = 0; _imageSelectionController = ListViewSelectionController()..selectedIndex = 2; _colorSelectionController = ListViewSelectionController()..selectedIndex = 0; } @override void dispose() { _basicSelectionController.dispose(); _imageSelectionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('List Buttons'), SizedBox(height: 4), FormPane( children: [ FormPaneField( label: 'Basic', child: ListButton<String>( items: ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple'], selectionController: _basicSelectionController, ), ), FormPaneField( label: 'Image', child: ListButton<String>( items: ['anchor', 'bell', 'clock', 'cup', 'house', 'star'], selectionController: _imageSelectionController, builder: ( BuildContext context, String? item, bool isForMeasurementOnly, ) { final String asset = item as String; final String path = 'assets/$asset.png'; final String label = asset[0].toUpperCase() + asset.substring(1); return Padding( padding: EdgeInsets.all(1), child: Row( children: [ Image.asset(path), SizedBox(width: 4), Text(label, maxLines: 1, softWrap: false), ], ), ); }, itemBuilder: ( BuildContext context, String item, bool isSelected, bool isHighlighted, bool isDisabled, ) { final String path = 'assets/$item.png'; final String label = item[0].toUpperCase() + item.substring(1); return Padding( padding: const EdgeInsets.all(5), child: Row( children: [ Image.asset(path), const SizedBox(width: 4), isDisabled ? GreyText(label) : isSelected ? WhiteText(label) : Text(label), ], ), ); }, ), ), FormPaneField( label: 'Color', child: ListButton<_ColorItem>( selectionController: _colorSelectionController, items: const <_ColorItem>[ _ColorItem(Color(0xffff0000), 'Red'), _ColorItem(Color(0xffffa500), 'Orange'), _ColorItem(Color(0xffffff00), 'Yellow'), _ColorItem(Color(0xff00ff00), 'Green'), _ColorItem(Color(0xff0000ff), 'Blue'), _ColorItem(Color(0xff4b0082), 'Indigo'), _ColorItem(Color(0xff8f008f), 'Violet'), ], builder: ( BuildContext context, _ColorItem? item, bool isForMeasurementOnly, ) { return _buildColorItem( item!, isSelected: false, includeName: false, ); }, itemBuilder: ( BuildContext context, _ColorItem item, bool isSelected, bool isHighlighted, bool isDisabled, ) { return Padding( padding: EdgeInsets.all(5), child: _buildColorItem(item, isSelected: isSelected), ); }, ), ), ], ), ], ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/navigation.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; class NavigationDemo extends StatelessWidget { const NavigationDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Rollup( heading: const HeaderText('Navigation'), semanticLabel: 'Navigation', childBuilder: (BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: const [ TabsDemo(), SizedBox(width: 12), // ExpandersDemo(), // SizedBox(width: 12), // AccordionDemo(), // SizedBox(width: 12), RollupDemo(), ], ); }, ); } } class TabsDemo extends StatelessWidget { const TabsDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: EdgeInsets.fromLTRB(4, 2, 4, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Tab Pane'), SizedBox(height: 4), ConstrainedBox( constraints: BoxConstraints(maxWidth: 400, maxHeight: 100), child: TabPane( tabs: [ Tab( label: 'Pomegranate', builder: (BuildContext context) { return Center( child: ColoredText('Red', Color(0xffff0000)), ); }, ), Tab( label: 'Mango', builder: (BuildContext context) { return Center( child: ColoredText('Orange', Color(0xffffa500)), ); }, ), Tab( label: 'Banana', builder: (BuildContext context) { return Center( child: ColoredText('Yellow', Color(0xffffff00)), ); }, ), Tab( label: 'Lime', builder: (BuildContext context) { return Center( child: ColoredText('Green', Color(0xff00ff00)), ); }, ), Tab( label: 'Blueberry', builder: (BuildContext context) { return Center( child: ColoredText('Blue', Color(0xff0000ff)), ); }, ), Tab( label: 'Plum', builder: (BuildContext context) { return Center( child: ColoredText('Purple', Color(0xff800080)), ); }, ), ], ), ), ], ), ), ); } } class RollupDemo extends StatefulWidget { const RollupDemo({Key? key}) : super(key: key); @override _RollupDemoState createState() => _RollupDemoState(); } class _RollupDemoState extends State<RollupDemo> { late CheckboxController _ellipseController; late CheckboxController _squareController; late CheckboxController _octagonController; late RadioButtonController<String> _radioController; @override void initState() { super.initState(); _ellipseController = CheckboxController.simple(true); _squareController = CheckboxController.simple(true); _octagonController = CheckboxController.simple(true); _radioController = RadioButtonController<String>('star'); } @override void dispose() { _ellipseController.dispose(); _squareController.dispose(); _octagonController.dispose(); _radioController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: EdgeInsets.fromLTRB(4, 2, 4, 4), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Rollups'), SizedBox(height: 4), Rollup( heading: Text('Colors'), semanticLabel: 'Colors', childBuilder: (BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ ColoredText('Red', Color(0xffff0000)), ColoredText('Orange', Color(0xffffa500)), ColoredText('Yellow', Color(0xffffff00)), ColoredText('Green', Color(0xff00ff00)), ColoredText('Blue', Color(0xff0000ff)), ColoredText('Purple', Color(0xff800080)), ], ); }, ), Rollup( heading: Text('Shapes'), semanticLabel: 'Shapes', childBuilder: (BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Checkbox(trailing: Text('Circle')), Checkbox( trailing: Text('Ellipse'), controller: _ellipseController, ), Checkbox( trailing: Text('Square'), controller: _squareController, ), const Checkbox(trailing: Text('Rectangle')), const Checkbox(trailing: Text('Hexagon')), Checkbox( trailing: Text('Octagon'), controller: _octagonController, ), ], ); }, ), Rollup( heading: Text('Images'), semanticLabel: 'Images', childBuilder: (BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ RadioButton<String>( value: 'anchor', controller: _radioController, trailing: Row( children: [ Image(image: AssetImage('assets/anchor.png')), SizedBox(width: 4), Text('Anchor'), ], ), ), RadioButton<String>( value: 'bell', controller: _radioController, trailing: Row( children: [ Image(image: AssetImage('assets/bell.png')), SizedBox(width: 4), Text('Bell'), ], ), ), RadioButton<String>( value: 'clock', controller: _radioController, trailing: Row( children: [ Image(image: AssetImage('assets/clock.png')), SizedBox(width: 4), Text('Clock'), ], ), ), RadioButton<String>( value: 'cup', controller: _radioController, trailing: Row( children: [ Image(image: AssetImage('assets/cup.png')), SizedBox(width: 4), Text('Cup'), ], ), ), RadioButton<String>( value: 'house', controller: _radioController, trailing: Row( children: [ Image(image: AssetImage('assets/house.png')), SizedBox(width: 4), Text('House'), ], ), ), RadioButton<String>( value: 'star', controller: _radioController, trailing: Row( children: [ Image(image: AssetImage('assets/star.png')), SizedBox(width: 4), Text('Star'), ], ), ), ], ); }, ), ], ), ), ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/spinners.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; class SpinnersDemo extends StatefulWidget { const SpinnersDemo({Key? key}) : super(key: key); @override _SpinnersDemoState createState() => _SpinnersDemoState(); } class _SpinnersDemoState extends State<SpinnersDemo> { late SpinnerController _basicController; late SpinnerController _numericController; late SpinnerController _dateController; static Widget _buildBasicItem(context, index, isEnabled) { const List<String> numbers = ['One', 'Two', 'Three', 'Four', 'Five']; return Spinner.defaultItemBuilder(context, numbers[index]); } static Widget _buildNumericItem(context, index, isEnabled) { return Spinner.defaultItemBuilder(context, '${index * 4}'); } static Widget _buildDateItem(context, index, isEnabled) { const CalendarDate baseDate = CalendarDate(2019, 11, 30); final CalendarDate date = baseDate + index; return Spinner.defaultItemBuilder(context, date.toString()); } @override void initState() { super.initState(); _basicController = SpinnerController()..selectedIndex = 0; _numericController = SpinnerController()..selectedIndex = 0; _dateController = SpinnerController()..selectedIndex = 0; } @override void dispose() { _basicController.dispose(); _numericController.dispose(); _dateController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Rollup( heading: const HeaderText('Spinners'), semanticLabel: 'Spinners', childBuilder: (BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ BorderPane( borderColor: const Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: const EdgeInsets.all(2), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FormPane( children: [ FormPaneField( label: 'Basic', child: Spinner( length: 5, isCircular: true, sizeToContent: true, controller: _basicController, itemBuilder: _buildBasicItem, ), ), FormPaneField( label: 'Numeric', child: SizedBox( width: 60, child: Spinner( length: 260 ~/ 4, controller: _numericController, itemBuilder: _buildNumericItem, ), ), ), FormPaneField( label: 'Date', child: Spinner( length: 365, controller: _dateController, itemBuilder: _buildDateItem, ), ), ], ), ], ), ), ), SizedBox(width: 4), // BorderPane( // borderColor: Color(0xff999999), // backgroundColor: Color(0xffffffff), // child: Padding( // padding: EdgeInsets.all(2), // child: Column( // children: [ // ], // ), // ), // ), ], ); }, ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/splitters.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; class SplittersDemo extends StatelessWidget { const SplittersDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Rollup( heading: HeaderText('Splitters'), semanticLabel: 'Splitters', childBuilder: (BuildContext context) { return BorderPane( borderColor: Color(0xff999999), backgroundColor: Color(0xffffffff), child: Padding( padding: EdgeInsets.all(4), child: SizedBox( width: 400, height: 360, child: SplitPane( orientation: Axis.vertical, initialSplitRatio: 0.5, before: SplitPane( orientation: Axis.horizontal, initialSplitRatio: 0.5, before: BorderPane( borderColor: Color(0xff999999), child: Image(image: AssetImage('assets/bell.png')), ), after: BorderPane( borderColor: Color(0xff999999), child: Image(image: AssetImage('assets/clock.png')), ), ), after: BorderPane( borderColor: Color(0xff999999), child: Image(image: AssetImage('assets/star.png')), ), ), ), ), ); }, ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/tables.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'text.dart'; typedef TableRowComparator = int Function(Map<String, int> row1, Map<String, int> row2); final math.Random rand = math.Random(); const int tableLength = 10000; final List<Map<String, int>> tableData = List<Map<String, int>>.generate( tableLength, (int index) { return <String, int>{ 'i': index, 'a': rand.nextInt(20), 'b': rand.nextInt(100), 'c': rand.nextInt(500), 'd': rand.nextInt(10000), }; }, ); class TablesDemo extends StatelessWidget { const TablesDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Rollup( heading: const HeaderText('Tables'), semanticLabel: 'Tables', childBuilder: (BuildContext context) { return BorderPane( borderColor: const Color(0xff999999), backgroundColor: const Color(0xffffffff), child: Padding( padding: const EdgeInsets.all(4), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: const <Widget>[ SortableTableDemo(), SizedBox(width: 8), CustomTableDemo(), SizedBox(width: 8), EditableTableDemo(), ], ), ), ); }, ); } } class SortableTableDemo extends StatefulWidget { const SortableTableDemo({Key? key}) : super(key: key); @override _SortableTableDemoState createState() => _SortableTableDemoState(); } class _SortableTableDemoState extends State<SortableTableDemo> { late TableViewSelectionController _selectionController; late TableViewSortController _sortController; late TableViewMetricsController _metricsController; late ScrollPaneController _scrollController; static TableColumn _createTableColumn(String key, String name) { return TableColumn( key: key, width: ConstrainedTableColumnWidth(width: 48), headerBuilder: (BuildContext context, int columnIndex) { return Text(name); }, cellBuilder: ( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { final int? value = tableData[rowIndex][key]; TextStyle style = DefaultTextStyle.of(context).style; if (hasFocus && rowSelected) { style = style.copyWith(color: Color(0xffffffff)); } return Text('$value', style: style); }, ); } static TableColumn _createFlexTableColumn() { return TableColumn( key: 'flex', headerBuilder: (BuildContext context, int columnIndex) { return Text(''); }, cellBuilder: ( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { return Container(); }, ); } static TableRowComparator _getTableRowComparator( String sortKey, SortDirection direction, ) { return (Map<String, int> row1, Map<String, int> row2) { int value1 = row1[sortKey]!; int value2 = row2[sortKey]!; int result = value1.compareTo(value2); if (direction == SortDirection.descending) { result *= -1; } return result; }; } @override void initState() { super.initState(); _selectionController = TableViewSelectionController(); _sortController = TableViewSortController(); _metricsController = TableViewMetricsController(); _scrollController = ScrollPaneController(); _sortController['i'] = SortDirection.ascending; _sortController.addListener( TableViewSortListener( onChanged: (TableViewSortController controller) { final String sortKey = controller.keys.first; final SortDirection direction = controller[sortKey]!; Map<String, int>? selectedItem; if (_selectionController.selectedIndex != -1) { selectedItem = tableData[_selectionController.selectedIndex]; } final TableRowComparator comparator = _getTableRowComparator( sortKey, direction, ); tableData.sort(comparator); if (selectedItem != null) { int selectedIndex = binarySearch( tableData, selectedItem, compare: comparator, ); assert(selectedIndex >= 0); _selectionController.selectedIndex = selectedIndex; final Rect rowBounds = _metricsController.metrics.getRowBounds( selectedIndex, ); _scrollController.scrollToVisible(rowBounds); } }, ), ); } @override void dispose() { _selectionController.dispose(); _sortController.dispose(); _metricsController.dispose(); _scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Sortable'), SizedBox(height: 4), SizedBox( width: 276, height: 160, child: BorderPane( borderColor: Color(0xff999999), child: ScrollableTableView( selectionController: _selectionController, sortController: _sortController, metricsController: _metricsController, scrollController: _scrollController, includeHeader: true, rowHeight: 19, length: tableLength, columns: [ _createTableColumn('i', '#'), _createTableColumn('a', 'A'), _createTableColumn('b', 'B'), _createTableColumn('c', 'C'), _createTableColumn('d', 'D'), _createFlexTableColumn(), ], ), ), ), ], ); } } class CustomTableDemo extends StatefulWidget { const CustomTableDemo({Key? key}) : super(key: key); @override _CustomTableDemoState createState() => _CustomTableDemoState(); } class _CustomItem { const _CustomItem(this.asset, this.name, this.isChecked); final String asset; final String name; final bool isChecked; _CustomItem toggleChecked() => _CustomItem(asset, name, !isChecked); } class _CustomTableDemoState extends State<CustomTableDemo> { late TableViewSelectionController _selectionController; late List<_CustomItem> _items; static Widget _buildIsCheckedHeader(BuildContext context, int columnIndex) { return Image.asset('assets/flag_red.png'); } Widget _buildIsCheckedCell( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { final _CustomItem item = _items[rowIndex]; return Padding( padding: EdgeInsets.all(2), child: BasicCheckbox( state: item.isChecked ? CheckboxState.checked : CheckboxState.unchecked, onTap: () { setState(() { _items[rowIndex] = _items[rowIndex].toggleChecked(); }); }, ), ); } static Widget _buildIconHeader(BuildContext context, int columnIndex) { return Text('Icon'); } Widget _buildIconCell( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { final _CustomItem item = _items[rowIndex]; final String asset = 'assets/${item.asset}.png'; return Image.asset(asset); } static Widget _buildNameHeader(BuildContext context, int columnIndex) { return Text('Name'); } Widget _buildNameCell( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { final _CustomItem item = _items[rowIndex]; return hasFocus && rowSelected ? WhiteText(item.name) : Text(item.name); } @override void initState() { super.initState(); _selectionController = TableViewSelectionController( selectMode: SelectMode.multi, ); _items = <_CustomItem>[ _CustomItem('anchor', 'Anchor', true), _CustomItem('bell', 'Bell', false), _CustomItem('clock', 'Clock', false), _CustomItem('cup', 'Cup', true), _CustomItem('house', 'House', false), _CustomItem('star', 'Star', false), ]; } @override void dispose() { _selectionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const BoldText('Custom Content'), SizedBox(height: 4), SizedBox( width: 276, height: 160, child: BorderPane( borderColor: Color(0xff999999), child: ScrollableTableView( selectionController: _selectionController, includeHeader: true, rowHeight: 19, length: 6, columns: [ TableColumn( key: 'flag', width: FixedTableColumnWidth(20), headerBuilder: _buildIsCheckedHeader, cellBuilder: _buildIsCheckedCell, ), TableColumn( key: 'icon', width: ConstrainedTableColumnWidth(width: 50), headerBuilder: _buildIconHeader, cellBuilder: _buildIconCell, ), TableColumn( key: 'name', width: FlexTableColumnWidth(), headerBuilder: _buildNameHeader, cellBuilder: _buildNameCell, ), ], ), ), ), ], ); } } class EditableTableDemo extends StatefulWidget { const EditableTableDemo({Key? key}) : super(key: key); @override _EditableTableDemoState createState() => _EditableTableDemoState(); } class _EditableItem { const _EditableItem(this.animal, this.name); final String animal; final String name; } class _EditableTableDemoState extends State<EditableTableDemo> { late TableViewSelectionController _selectionController; late TableViewEditorController _editorController; late TextEditingController _textController; late ListViewSelectionController _listButtonController; late List<_EditableItem> _items; static const List<String> editableTableListButtonOptions = [ 'Dog', 'Cat', 'Snake', 'Fish', 'Bird', ]; static Widget _buildTypeHeader(BuildContext context, int columnIndex) { return Text('Type'); } Widget _buildTypeCell( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { if (isEditing) { return ListButton<String>( items: editableTableListButtonOptions, selectionController: _listButtonController, ); } else { final String text = _items[rowIndex].animal; return Padding( padding: EdgeInsets.all(2), child: hasFocus && rowSelected ? WhiteText(text) : Text(text), ); } } static Widget _buildNameHeader(BuildContext context, int columnIndex) { return Text('Name'); } Widget _buildNameCell( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { if (isEditing) { return TextInput(controller: _textController); } else { final String text = _items[rowIndex].name; return Padding( padding: EdgeInsets.all(2), child: hasFocus && rowSelected ? WhiteText(text) : Text(text), ); } } static Widget _buildFlexHeader(BuildContext context, int columnIndex) { return Container(); } static Widget _buildFlexCell( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool rowSelected, bool rowHighlighted, bool isEditing, bool isRowDisabled, ) { return Container(); } @override void initState() { super.initState(); _selectionController = TableViewSelectionController(); _editorController = TableViewEditorController(); _textController = TextEditingController(); _listButtonController = ListViewSelectionController(); _items = <_EditableItem>[ _EditableItem('Dog', 'Boomer'), _EditableItem('Dog', 'Faith'), _EditableItem('Cat', 'Sasha'), _EditableItem('Snake', 'Goliath'), ]; int editingRowIndex = -1; _editorController.addListener( TableViewEditorListener( onPreviewEditStarted: ( TableViewEditorController controller, int rowIndex, int columnIndex, ) { _listButtonController.selectedIndex = editableTableListButtonOptions .indexOf(_items[rowIndex].animal); _textController.text = _items[rowIndex].name; editingRowIndex = rowIndex; return Vote.approve; }, onEditFinished: ( TableViewEditorController controller, TableViewEditOutcome outcome, ) { if (outcome == TableViewEditOutcome.saved) { final String animal = editableTableListButtonOptions[_listButtonController .selectedIndex]; final String name = _textController.text; setState(() { _items[editingRowIndex] = _EditableItem(animal, name); }); } }, ), ); } @override void dispose() { _selectionController.dispose(); _editorController.dispose(); _textController.dispose(); _listButtonController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BoldText('Editable'), SizedBox(height: 4), SizedBox( width: 276, height: 160, child: BorderPane( borderColor: Color(0xff999999), child: ScrollableTableView( selectionController: _selectionController, editorController: _editorController, includeHeader: true, rowHeight: 23, length: _items.length, columns: [ TableColumn( key: 'type', width: ConstrainedTableColumnWidth(width: 100), headerBuilder: _buildTypeHeader, cellBuilder: _buildTypeCell, ), TableColumn( key: 'name', width: ConstrainedTableColumnWidth(width: 100), headerBuilder: _buildNameHeader, cellBuilder: _buildNameCell, ), TableColumn( key: 'flex', width: FlexTableColumnWidth(), headerBuilder: _buildFlexHeader, cellBuilder: _buildFlexCell, ), ], ), ), ), ], ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/lib/src/text.dart
Dart
import 'package:flutter/widgets.dart'; class BoldText extends StatelessWidget { const BoldText(this.text, {Key? key}) : super(key: key); final String text; @override Widget build(BuildContext context) { final TextStyle baseStyle = DefaultTextStyle.of(context).style; final TextStyle boldStyle = baseStyle.copyWith(fontWeight: FontWeight.bold); return Text(text, style: boldStyle); } } class HeaderText extends StatelessWidget { const HeaderText(this.text, {Key? key}) : super(key: key); final String text; @override Widget build(BuildContext context) { final TextStyle baseStyle = DefaultTextStyle.of(context).style; final TextStyle headerStyle = baseStyle.copyWith( fontWeight: FontWeight.bold, color: Color(0xff2b5580), ); return Text(text, style: headerStyle); } } class ColoredText extends StatelessWidget { const ColoredText(this.text, this.color, {Key? key}) : super(key: key); final String text; final Color color; @override Widget build(BuildContext context) { final TextStyle baseStyle = DefaultTextStyle.of(context).style; final TextStyle coloredStyle = baseStyle.copyWith(color: color); return Text(text, style: coloredStyle); } } class WhiteText extends ColoredText { const WhiteText(String text, {Key? key}) : super(text, const Color(0xffffffff), key: key); } class GreyText extends ColoredText { const GreyText(String text, {Key? key}) : super(text, const Color(0xff999999), key: key); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/macos/Flutter/GeneratedPluginRegistrant.swift
Swift
// // Generated file. Do not edit. // import FlutterMacOS import Foundation func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/macos/Runner/AppDelegate.swift
Swift
import Cocoa import FlutterMacOS @main class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { return true } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/macos/Runner/MainFlutterWindow.swift
Swift
import Cocoa import FlutterMacOS class MainFlutterWindow: NSWindow { override func awakeFromNib() { let flutterViewController = FlutterViewController() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) super.awakeFromNib() } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/macos/RunnerTests/RunnerTests.swift
Swift
import FlutterMacOS import Cocoa import XCTest class RunnerTests: XCTestCase { func testExample() { // If you add code to the Runner application, consider adding tests here. // See https://developer.apple.com/documentation/xctest for more information about using XCTest. } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
example/web/index.html
HTML
<!DOCTYPE html> <html> <head> <!-- If you are serving your web app in a path other than the root, change the href value below to reflect the base path you are serving from. The path provided below has to start and end with a slash "/" in order for it to work correctly. For more details: * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base This is a placeholder for base href that will be replaced by the value of the `--base-href` argument provided to `flutter build`. --> <base href="$FLUTTER_BASE_HREF"> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <!-- iOS meta tags & icons --> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="demo"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png"/> <title>demo</title> <link rel="manifest" href="manifest.json"> </head> <body> <script src="flutter_bootstrap.js" async></script> </body> </html>
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/chicago.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. export 'src/activity_indicator.dart'; export 'src/app.dart'; export 'src/basic_list_view.dart' hide main; export 'src/basic_table_view.dart'; export 'src/border_pane.dart'; export 'src/box_pane.dart'; export 'src/calendar.dart'; export 'src/calendar_button.dart'; export 'src/checkbox.dart'; export 'src/colors.dart'; export 'src/form_pane.dart'; export 'src/foundation.dart'; export 'src/hover_builder.dart'; export 'src/indexed_offset.dart'; export 'src/link_button.dart'; export 'src/list_button.dart'; export 'src/list_view.dart' hide main; export 'src/listener_list.dart'; export 'src/meter.dart'; export 'src/navigator_listener.dart'; export 'src/push_button.dart'; export 'src/radio_button.dart'; export 'src/rollup.dart'; export 'src/scroll_bar.dart'; export 'src/scroll_pane.dart'; export 'src/set_baseline.dart'; export 'src/sheet.dart'; export 'src/sorting.dart'; export 'src/span.dart'; export 'src/spinner.dart'; export 'src/split_pane.dart'; export 'src/tab_pane.dart'; export 'src/table_pane.dart' hide main; export 'src/table_view.dart'; export 'src/text_input.dart'; export 'src/widget_surveyor.dart';
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/action_tracker.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; abstract class ActionTracker<I extends Intent> extends StatefulWidget { const ActionTracker({Key? key, required this.intent, this.onActionInvoked}) : super(key: key); final I intent; final ValueChanged<Object?>? onActionInvoked; @override @protected ActionTrackerStateMixin<I, ActionTracker<I>> createState(); } mixin ActionTrackerStateMixin<I extends Intent, T extends ActionTracker<I>> on State<T> { Action<I>? _action; bool _enabled = false; void _attachToAction() { setState(() { _action = Actions.find<I>(context); _enabled = _action!.isEnabled(widget.intent); }); _action!.addActionListener(_actionUpdated as void Function(Action<Intent>)); } void _detachFromAction() { if (_action != null) { _action!.removeActionListener( _actionUpdated as void Function(Action<Intent>), ); setState(() { _action = null; _enabled = false; }); } } void _actionUpdated(Action<I> action) { setState(() { _enabled = action.isEnabled(widget.intent); }); } @protected @nonVirtual bool get isEnabled => _enabled; @protected @nonVirtual void invokeAction() { assert(_action != null); assert(_enabled); assert(_action!.isEnabled(widget.intent)); final Object? result = Actions.of( context, ).invokeAction(_action!, widget.intent, context); if (widget.onActionInvoked != null) { widget.onActionInvoked!(result); } } @override @protected void didChangeDependencies() { super.didChangeDependencies(); _detachFromAction(); _attachToAction(); } @override void dispose() { _action?.removeActionListener( _actionUpdated as void Function(Action<Intent>), ); super.dispose(); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/activity_indicator.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'visibility_aware.dart'; const Duration _duration = Duration(milliseconds: 1200); const double _defaultSize = 128; const int _spokes = 12; const Color _defaultColor = Color(0xff000000); class ActivityIndicator extends StatefulWidget { const ActivityIndicator({ Key? key, this.color = _defaultColor, this.semanticLabel = 'Loading', }) : super(key: key); final Color color; final String semanticLabel; @override _ActivityIndicatorState createState() => _ActivityIndicatorState(); } class _ActivityIndicatorState extends State<ActivityIndicator> with SingleTickerProviderStateMixin<ActivityIndicator> { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController(duration: _duration, vsync: this); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Semantics( label: widget.semanticLabel, child: RepaintBoundary( child: _RawActivityIndicator( color: widget.color, controller: _controller, ), ), ); } } class _RawActivityIndicator extends LeafRenderObjectWidget { const _RawActivityIndicator({ Key? key, required this.color, required this.controller, }) : super(key: key); final Color color; final AnimationController controller; @override RenderObject createRenderObject(BuildContext context) { return _RenderRawActivityIndicator(color: color, controller: controller); } @override void updateRenderObject( BuildContext context, _RenderRawActivityIndicator renderObject, ) { renderObject ..color = color ..controller = controller; } } class _RenderRawActivityIndicator extends RenderBox with VisibilityAwareMixin { _RenderRawActivityIndicator({ Color color = _defaultColor, required AnimationController controller, }) : _color = color, _colors = _splitColor(color), _controller = controller { assert(!_controller.isAnimating); } Color _color; List<Color> _colors = <Color>[]; Color get color => _color; set color(Color value) { if (value != _color) { _color = value; _colors = _splitColor(_color); markNeedsPaint(); } } AnimationController _controller; AnimationController get controller => _controller; set controller(AnimationController value) { if (value != _controller) { AnimationController oldController = _controller; _controller = value; if (attached) { oldController.removeListener(markNeedsPaint); _controller.addListener(markNeedsPaint); if (isVisible) { oldController.stop(); _controller.repeat(); } } } } @override void attach(covariant PipelineOwner owner) { super.attach(owner); _controller.addListener(markNeedsPaint); assert(!controller.isAnimating); if (isVisible) { _controller.repeat(); } } @override void detach() { _controller.removeListener(markNeedsPaint); if (isVisible) { assert(controller.isAnimating); _controller.stop(); } super.detach(); } @override void handleIsVisibleChanged() { if (attached) { if (isVisible) { _controller.repeat(); } else { _controller.stop(); } } } @override double computeMinIntrinsicWidth(double height) => _defaultSize; @override double computeMaxIntrinsicWidth(double height) => _defaultSize; @override double computeMinIntrinsicHeight(double width) => _defaultSize; @override double computeMaxIntrinsicHeight(double width) => _defaultSize; @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) { double size = math.min(constraints.maxWidth, constraints.maxHeight); if (size.isInfinite) { size = _defaultSize; } return constraints.constrain(Size.square(size)); } static List<Color> _splitColor(Color color) { return List<Color>.generate(_spokes, (int index) { final int alpha = (255 * index / _spokes).floor(); return color.withAlpha(alpha); }); } static final Tween<double> _rotationTween = _StepTween( begin: 0, end: 2 * math.pi, step: 2 * math.pi / _spokes, ); @override void paint(PaintingContext context, Offset offset) { final Canvas canvas = context.canvas; canvas.translate(offset.dx, offset.dy); if (size.width > size.height) { canvas.translate((size.width - size.height) / 2, 0); final double scale = size.height / _defaultSize; canvas.scale(scale); } else if (size.width != _defaultSize || size.height != _defaultSize) { canvas.translate(0, (size.height - size.width) / 2); final double scale = size.width / _defaultSize; canvas.scale(scale); } final double rotationValue = _rotationTween.evaluate(_controller); canvas.translate(_defaultSize / 2, _defaultSize / 2); canvas.rotate(rotationValue); final double increment = 2 * math.pi / _spokes; final Paint paint = Paint()..style = PaintingStyle.fill; for (int i = 0; i < _spokes; i++) { paint.color = _colors[i]; canvas.drawRRect( RRect.fromLTRBR(24, -4, 56, 4, Radius.circular(4)), paint, ); canvas.rotate(increment); } } } class _StepTween extends Tween<double> { _StepTween({required double begin, required double end, required this.step}) : super(begin: begin, end: end); final double step; @override @protected double lerp(double t) { double value = super.lerp(t); int steps = (value / step).floor(); return steps * step; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/app.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Needed because chicago.TextInput still depends on Material import 'package:flutter/material.dart' show DefaultMaterialLocalizations, Material; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'navigator_listener.dart'; import 'scroll_pane.dart'; class ChicagoApp extends StatefulWidget { const ChicagoApp({Key? key, this.title = 'Chicago App', this.home}) : super(key: key); final String title; final Widget? home; @override _ChicagoAppState createState() => _ChicagoAppState(); } class _ChicagoAppState extends State<ChicagoApp> with WidgetsBindingObserver { bool _scrollToVisibleScheduled = false; @override void didChangeMetrics() { FocusNode? focusNode = FocusManager.instance.primaryFocus; BuildContext? focusContext = focusNode?.context; if (focusNode != null && focusContext != null) { final ScrollPaneState? scrollPane = ScrollPane.of(focusContext); if (scrollPane != null && !_scrollToVisibleScheduled) { _scrollToVisibleScheduled = true; SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { _scrollToVisibleScheduled = false; assert(mounted && scrollPane.mounted && focusNode.hasPrimaryFocus); final RenderObject? focusRenderObject = focusContext.findRenderObject(); if (focusRenderObject is RenderBox) { final Rect focusRect = Offset.zero & focusRenderObject.size; scrollPane.scrollToVisible(focusRect, context: focusContext); } }); } } } @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override Widget build(BuildContext context) { return NavigatorListener( child: WidgetsApp( title: widget.title, color: Color(0xffffffff), localizationsDelegates: [ DefaultMaterialLocalizations.delegate, // TODO: Remove ], builder: (BuildContext context, Widget? navigator) { return Padding( padding: MediaQuery.of(context).viewInsets, child: DefaultTextStyle( style: TextStyle( fontFamily: 'Dialog', fontSize: 14, color: Color(0xff000000), ), child: SafeArea( child: Material( // TODO: Remove child: Navigator( observers: [NavigatorListener.of(context).observer], onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( settings: settings, pageBuilder: ( BuildContext _, Animation<double> __, Animation<double> ___, ) { return widget.home ?? Container(); }, ); }, ), ), ), ), ); }, ), ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/basic_list_view.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'debug.dart'; import 'segment.dart'; import 'scroll_pane.dart'; void main() { runApp( Directionality( textDirection: TextDirection.ltr, child: DefaultTextStyle( style: TextStyle(fontFamily: 'Verdana', color: const Color(0xffffffff)), child: ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.stretch, view: BasicListView( length: 1000, itemHeight: 20, itemBuilder: (BuildContext context, int index) { return Padding( padding: EdgeInsets.only(left: index.toDouble()), child: Text('$index'), ); }, ), ), ), ), ); } typedef ListItemVisitor = void Function(int index); typedef ListItemChildVisitor = void Function(RenderBox child, int index); typedef ListItemHost = void Function(ListItemVisitor visitor); typedef ListViewLayoutCallback = void Function({ required ListItemHost visitChildrenToRemove, required ListItemHost visitChildrenToBuild, }); typedef BasicListItemBuilder = Widget Function(BuildContext context, int index); class BasicListView extends RenderObjectWidget { const BasicListView({ Key? key, required this.length, required this.itemHeight, required this.itemBuilder, }) : assert(length >= 0), super(key: key); final int length; final double itemHeight; final BasicListItemBuilder itemBuilder; @override BasicListViewElement createElement() => BasicListViewElement(this); @override @protected RenderBasicListView createRenderObject(BuildContext context) { return RenderBasicListView(itemHeight: itemHeight, length: length); } @override @protected void updateRenderObject( BuildContext context, covariant RenderBasicListView renderObject, ) { renderObject ..itemHeight = itemHeight ..length = length; } } abstract class ListItemRange with Diagnosticable { const ListItemRange(); void visitItems(ListItemVisitor visitor); bool contains(int index) { bool result = false; visitItems((int i) { if (i == index) { result = true; } }); return result; } ListItemRange where(bool test(int index)) { return ProxyListItemRange((ListItemVisitor visitor) { visitItems((int index) { if (test(index)) { visitor(index); } }); }); } ListItemRange subtract(ListItemRange other) { return where((int index) => !other.contains(index)); } ListItemRange intersect(ListItemRange other) { return where((int index) => other.contains(index)); } } class SingleListItemRange extends ListItemRange { const SingleListItemRange(this.index); final int index; @override void visitItems(ListItemVisitor visitor) { visitor(index); } @override bool contains(int index) { return index == this.index; } } class ListItemSequence extends ListItemRange { const ListItemSequence(this.start, this.end); final int start; final int end; static const ListItemSequence empty = ListItemSequence(0, -1); bool get isNormalized => start >= 0 && start <= end; /// True if [visitCells] will not visit anything. /// /// An empty [ListItemSequence] is guaranteed to have an [isNormalized] value of /// false. bool get isEmpty => start > end; @override void visitItems(ListItemVisitor visitor) { for (int index = start; index <= end; index++) { visitor(index); } } @override bool contains(int index) { return index >= start && index <= end; } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('start', start)); properties.add(IntProperty('end', end)); } } class EmptyListItemRange extends ListItemRange { const EmptyListItemRange(); @override void visitItems(ListItemVisitor visitor) {} @override bool contains(int index) => false; } class ProxyListItemRange extends ListItemRange { const ProxyListItemRange(this.host); final ListItemHost host; @override void visitItems(ListItemVisitor visitor) => host(visitor); @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Function>('host', host)); } } class UnionListItemRange extends ListItemRange { UnionListItemRange([List<ListItemRange> ranges = const <ListItemRange>[]]) : _ranges = List<ListItemRange>.from(ranges); final List<ListItemRange> _ranges; void add(ListItemRange range) { _ranges.add(range); } @override void visitItems(ListItemVisitor visitor) { final Set<int> indexes = <int>{}; for (ListItemRange range in _ranges) { range.visitItems((int index) { if (indexes.add(index)) { visitor(index); } }); } } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<List<ListItemRange>>('ranges', _ranges)); } } @immutable class ListViewSlot with Diagnosticable { const ListViewSlot(this.index); final int index; @override bool operator ==(Object other) { if (identical(this, other)) return true; if (runtimeType != other.runtimeType) return false; return other is ListViewSlot && index == other.index; } @override int get hashCode => index.hashCode; @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('index', index)); } } mixin ListViewElementMixin on RenderObjectElement { Map<int, Element>? _children; @override RenderBasicListView get renderObject => super.renderObject as RenderBasicListView; @override @protected void reassemble() { super.reassemble(); renderObject.markNeedsBuild(); } @override void update(covariant RenderObjectWidget newWidget) { assert(widget != newWidget); super.update(newWidget); assert(widget == newWidget); renderObject.updateLayoutCallback(_layout); } @protected Widget renderItem(int index); void _layout({ required ListItemHost visitChildrenToRemove, required ListItemHost visitChildrenToBuild, }) { owner!.buildScope(this, () { visitChildrenToRemove((int index) { assert(_children != null); assert(_children!.containsKey(index)); final Element child = _children![index]!; final Element? newChild = updateChild( child, null, null /* unused for remove */, ); assert(newChild == null); _children!.remove(index); }); visitChildrenToBuild((int index) { assert(_children != null); late Widget built; try { built = renderItem(index); assert(() { if (debugPaintListItemBuilds) { debugCurrentListItemColor = debugCurrentListItemColor.withHue( (debugCurrentListItemColor.hue + 2) % 360.0, ); built = DecoratedBox( decoration: BoxDecoration( color: debugCurrentListItemColor.toColor(), ), position: DecorationPosition.foreground, child: built, ); } return true; }()); debugWidgetBuilderValue(widget, built); } catch (e, stack) { built = ErrorWidget.builder( _debugReportException( ErrorDescription('building $widget'), e, stack, informationCollector: () sync* { yield DiagnosticsDebugCreator(DebugCreator(this)); }, ), ); } late final Element child; final ListViewSlot slot = ListViewSlot(index); try { child = updateChild(_children![index], built, slot)!; } catch (e, stack) { built = ErrorWidget.builder( _debugReportException( ErrorDescription('building $widget'), e, stack, informationCollector: () sync* { yield DiagnosticsDebugCreator(DebugCreator(this)); }, ), ); child = updateChild(null, built, slot)!; } _children![index] = child; }); }); } static FlutterErrorDetails _debugReportException( DiagnosticsNode context, dynamic exception, StackTrace stack, { required InformationCollector informationCollector, }) { final FlutterErrorDetails details = FlutterErrorDetails( exception: exception, stack: stack, library: 'payouts', context: context, informationCollector: informationCollector, ); FlutterError.reportError(details); return details; } @override void performRebuild() { // This gets called if markNeedsBuild() is called on us. // That might happen if, e.g., our builder uses Inherited widgets. // Force the callback to be called, even if the layout constraints are the // same. This is because that callback may depend on the updated widget // configuration, or an inherited widget. renderObject.markNeedsBuild(); super.performRebuild(); // Calls widget.updateRenderObject } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _children = <int, Element>{}; renderObject.updateLayoutCallback(_layout); } @override void unmount() { renderObject.updateLayoutCallback(null); super.unmount(); } @override void visitChildren(ElementVisitor visitor) { for (final Element child in _children!.values) { visitor(child); } } @override void forgetChild(Element child) { assert(child.slot is ListViewSlot); final ListViewSlot slot = child.slot as ListViewSlot; assert(_children != null); assert(_children!.containsKey(slot.index)); assert(_children![slot.index] == child); _children!.remove(slot.index); super.forgetChild(child); } @override void insertRenderObjectChild(RenderBox child, ListViewSlot slot) { assert(child.parent == null); renderObject.insert(child, index: slot.index); assert(child.parent == renderObject); } @override void moveRenderObjectChild( RenderBox child, ListViewSlot? oldSlot, ListViewSlot newSlot, ) { assert(child.parent == renderObject); renderObject.move(child, index: newSlot.index); assert(child.parent == renderObject); } @override void removeRenderObjectChild(RenderBox child, ListViewSlot? slot) { assert(child.parent == renderObject); renderObject.remove(child); assert(child.parent == null); } } class BasicListViewElement extends RenderObjectElement with ListViewElementMixin { BasicListViewElement(BasicListView listView) : super(listView); @override BasicListView get widget => super.widget as BasicListView; @override void update(BasicListView newWidget) { if (widget.itemBuilder != newWidget.itemBuilder) { renderObject.markNeedsBuild(); } super.update(newWidget); } @override @protected Widget renderItem(int index) { return widget.itemBuilder(this, index); } } class RenderBasicListView extends RenderSegment { RenderBasicListView({required double itemHeight, required int length}) { this.itemHeight = itemHeight; this.length = length; } double? _itemHeight; double get itemHeight => _itemHeight!; set itemHeight(double value) { if (_itemHeight == value) return; _itemHeight = value; // The fact that the cell constraints changed could affect the built // output (e.g. if the cell builder uses LayoutBuilder). markNeedsBuild(); } int? _length; int get length => _length!; set length(int value) { assert(value >= 0); if (_length == value) return; _length = value; // We rebuild because the cell at any given offset may not contain the same // contents as it did before the length changed. markNeedsBuild(); } Map<int, RenderBox> _children = <int, RenderBox>{}; void insert(RenderBox child, {required int index}) { final RenderBox? oldChild = _children.remove(index); if (oldChild != null) dropChild(oldChild); _children[index] = child; child.parentData = ListViewParentData(index: index); adoptChild(child); } void move(RenderBox child, {required int index}) { remove(child); insert(child, index: index); } void remove(RenderBox child) { assert(child.parentData is ListViewParentData); final ListViewParentData parentData = child.parentData as ListViewParentData; assert(_children[parentData.index] == child); _children.remove(parentData.index); dropChild(child); } ListViewLayoutCallback? _layoutCallback; /// Change the layout callback. @protected void updateLayoutCallback(ListViewLayoutCallback? value) { if (value == _layoutCallback) return; _layoutCallback = value; markNeedsBuild(); } /// Whether the whole list view is in need of being built. bool _needsBuild = true; /// Marks this list view as needing to rebuild. /// /// See also: /// /// * [markItemsDirty], which marks specific items as needing to rebuild. @protected void markNeedsBuild() { _needsBuild = true; markNeedsLayout(); } /// Specific items in need of building. UnionListItemRange? _dirtyItems; /// Marks specific items as needing to rebuild. /// /// See also: /// /// * [markNeedsBuild], which marks the whole list view as needing to /// rebuild. @protected void markItemsDirty(ListItemRange items) { _dirtyItems ??= UnionListItemRange(); _dirtyItems!.add(items); markNeedsLayout(); } @override void attach(PipelineOwner owner) { super.attach(owner); visitChildren((RenderObject child) { child.attach(owner); }); } @override void detach() { super.detach(); visitChildren((RenderObject child) { child.detach(); }); } @protected void visitListItems( ListItemChildVisitor visitor, { bool allowMutations = false, }) { Iterable<MapEntry<int, RenderBox>> items = _children.entries; if (allowMutations) items = items.toList(growable: false); for (MapEntry<int, RenderBox> item in items) { final int index = item.key; final RenderBox child = item.value; visitor(child, index); } } @override void visitChildren(RenderObjectVisitor visitor) { visitListItems((RenderBox child, int index) { visitor(child); }); } int getItemAt(double dy) => dy ~/ itemHeight; Rect getItemBounds(int index) { assert(index >= 0 && index < length); return Rect.fromLTWH(0, index * itemHeight, size.width, itemHeight); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final int index = getItemAt(position.dy); if (!_children.containsKey(index)) { // No list item at the given position. return false; } assert(index >= 0); final RenderBox child = _children[index]!; final BoxParentData parentData = child.parentData as BoxParentData; return result.addWithPaintOffset( offset: parentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - parentData.offset); return child.hitTest(result, position: transformed); }, ); } @override bool hitTestSelf(Offset position) { int index = getItemAt(position.dy); return index >= 0 && index < length; } @override void setupParentData(RenderBox child) { // We manually attach the parent data in [insert] before adopting the child, // so by the time this is called, the parent data is already set-up. assert(child.parentData is ListViewParentData); super.setupParentData(child); } // @override // double computeMinIntrinsicWidth(double height) { // double intrinsicWidth = 0; // for (int i = 0; i < length; i++) { // owner; // Widget built = itemBuilder(context: debugCreator, index: i); // } // return intrinsicWidth; // } @override double computeMinIntrinsicHeight(double width) { return length * itemHeight; } @override double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); @override @protected void performLayout() { size = constraints.constrainDimensions( double.infinity, itemHeight * length, ); // Relies on size being set. rebuildIfNecessary(); visitListItems((RenderBox child, int index) { final double itemY = index * itemHeight; child.layout( BoxConstraints.tightFor(width: size.width, height: itemHeight), ); final BoxParentData parentData = child.parentData as BoxParentData; parentData.offset = Offset(0, itemY); }); } Rect? _viewport; bool _isInBounds(int index) { return index < length; } bool _isBuilt(int index) { return _children.containsKey(index); } bool _isNotBuilt(int index) { return !_children.containsKey(index); } @protected ListItemRange builtCells() { return ProxyListItemRange((ListItemVisitor visitor) { visitListItems((RenderBox child, int index) { visitor(index); }, allowMutations: true); }); } ListItemSequence _getIntersectingItems(Rect rect) { if (rect.isEmpty) { return ListItemSequence.empty; } int bottomIndex = rect.bottom ~/ itemHeight; if (rect.bottom.remainder(itemHeight) == 0) { // The rect goes *right up* to the item but doesn't actually overlap it. bottomIndex -= 1; } return ListItemSequence(rect.top ~/ itemHeight, bottomIndex); } @protected void rebuildIfNecessary() { assert(_layoutCallback != null); assert(debugDoingThisLayout); final Rect? previousViewport = _viewport; _viewport = constraints.viewportResolver.resolve(size); if (!_needsBuild && _dirtyItems == null && _viewport == previousViewport) { return; } final ListItemRange builtCells = this.builtCells(); final ListItemSequence viewportItemSequence = _getIntersectingItems( _viewport!, ); ListItemRange removeCells = builtCells.subtract(viewportItemSequence); ListItemRange buildCells; if (_needsBuild) { removeCells = UnionListItemRange(<ListItemRange>[ removeCells, builtCells.where((int index) => index >= length), ]); buildCells = viewportItemSequence; _needsBuild = false; _dirtyItems = null; } else if (_dirtyItems != null) { buildCells = UnionListItemRange(<ListItemRange>[ _dirtyItems!.intersect(viewportItemSequence), viewportItemSequence.where(_isNotBuilt), ]); _dirtyItems = null; } else { assert(previousViewport != null); if (_viewport!.overlaps(previousViewport!)) { final Rect overlap = _viewport!.intersect(previousViewport); final ListItemSequence overlapItemSequence = _getIntersectingItems( overlap, ); removeCells = _getIntersectingItems( previousViewport, ).subtract(overlapItemSequence); buildCells = viewportItemSequence.subtract(overlapItemSequence); } else { buildCells = viewportItemSequence; } } invokeLayoutCallback<SegmentConstraints>((SegmentConstraints _) { _layoutCallback!( visitChildrenToRemove: removeCells.where(_isBuilt).visitItems, visitChildrenToBuild: buildCells.where(_isInBounds).visitItems, ); }); } @override void paint(PaintingContext context, Offset offset) { visitChildren((RenderObject child) { final BoxParentData parentData = child.parentData as BoxParentData; context.paintChild(child, offset + parentData.offset); }); } @override void redepthChildren() { visitChildren((RenderObject child) { redepthChild(child); }); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> result = <DiagnosticsNode>[]; visitListItems((RenderBox child, int index) { result.add(child.toDiagnosticsNode(name: 'child $index')); }); return result; } } class ListViewParentData extends BoxParentData { ListViewParentData({required this.index}); final int index; @override String toString() => '${super.toString()}, index=$index'; }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/basic_table_view.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'debug.dart'; import 'listener_list.dart'; import 'segment.dart'; import 'widget_surveyor.dart'; const double _kDoublePrecisionTolerance = 0.001; /// Signature for a function that renders cells in a [BasicTableView]. /// /// Cell builders are properties of the [BasicTableColumn], so each column /// specifies the cell builder for cells in that column. typedef BasicTableCellBuilder = Widget Function(BuildContext context, int rowIndex, int columnIndex); typedef TableCellVisitor = void Function(int rowIndex, int columnIndex); typedef TableCellChildVisitor = void Function(RenderBox child, int rowIndex, int columnIndex); typedef TableCellHost = void Function(TableCellVisitor visitor); typedef TableViewLayoutCallback = void Function({ required TableCellHost visitChildrenToRemove, required TableCellHost visitChildrenToBuild, }); typedef TableViewPrototypeCellBuilder = Widget? Function(int columnIndex); abstract class AbstractTableColumn with Diagnosticable { const AbstractTableColumn(); TableColumnWidth get width; @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Diagnosticable>('width', width)); } @override int get hashCode => width.hashCode; @override bool operator ==(Object other) { if (identical(this, other)) return true; if (runtimeType != other.runtimeType) return false; return other is AbstractTableColumn && width == other.width; } } class BasicTableColumn extends AbstractTableColumn { const BasicTableColumn({ this.width = const FlexTableColumnWidth(), required this.cellBuilder, this.prototypeCellBuilder, }); /// The width specification for this column. @override final TableColumnWidth width; /// The builder responsible for the look & feel of cells in this column. final BasicTableCellBuilder cellBuilder; /// The builder responsible for building the "prototype cell" for this /// column. /// /// The prototype cell is a cell with sample data that is appropriate for the /// column. The prototype cells for every column join to form a "prototype /// row". The prototype row is used for things like calculating the fixed /// row height of a table view or for calculating a table view's baseline. /// /// Prototype cells are rendered in a standalone widget tree, so any widgets /// that require inherited data (such a [DefaultTextStyle] or /// [Directionality]) should be explicitly passed such information, or the /// builder should explicitly include such inherited widgets in the built /// hierarchy. /// /// If this is not specified, this column wll not contribute data towards the /// prototype row. If the prototype row contains no cells, then the table /// view will report no baseline. final WidgetBuilder? prototypeCellBuilder; @override int get hashCode => Object.hash(super.hashCode, cellBuilder); @override bool operator ==(Object other) { if (identical(this, other)) return true; return super == other && other is BasicTableColumn && cellBuilder == other.cellBuilder; } } @immutable abstract class TableColumnWidth with Diagnosticable { const TableColumnWidth(this.width); final double width; bool get isFlex => false; @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('width', width)); properties.add(DiagnosticsProperty<bool>('isFlex', isFlex)); } @override int get hashCode => Object.hash(width, isFlex); @override bool operator ==(Object other) { if (identical(this, other)) return true; if (runtimeType != other.runtimeType) return false; return other is TableColumnWidth && width == other.width && isFlex == other.isFlex; } } class FixedTableColumnWidth extends TableColumnWidth { const FixedTableColumnWidth(double width) : assert(width >= 0), assert(width < double.infinity), super(width); } class FlexTableColumnWidth extends TableColumnWidth { const FlexTableColumnWidth({double flex = 1}) : assert(flex > 0), super(flex); @override bool get isFlex => true; } class BasicTableView extends RenderObjectWidget { const BasicTableView({ Key? key, required this.length, required this.columns, required this.rowHeight, this.roundColumnWidthsToWholePixel = false, this.metricsController, }) : assert(length >= 0), super(key: key); final int length; final List<BasicTableColumn> columns; final double rowHeight; final bool roundColumnWidthsToWholePixel; final TableViewMetricsController? metricsController; @override BasicTableViewElement createElement() => BasicTableViewElement(this); @override @protected RenderBasicTableView createRenderObject(BuildContext context) { return RenderBasicTableView( rowHeight: rowHeight, length: length, columns: columns, roundColumnWidthsToWholePixel: roundColumnWidthsToWholePixel, metricsController: metricsController, ); } @override @protected void updateRenderObject( BuildContext context, covariant RenderBasicTableView renderObject, ) { renderObject ..rowHeight = rowHeight ..length = length ..columns = columns ..roundColumnWidthsToWholePixel = roundColumnWidthsToWholePixel ..metricsController = metricsController; } } @immutable class TableViewSlot with Diagnosticable { const TableViewSlot(this.rowIndex, this.columnIndex); final int rowIndex; final int columnIndex; @override bool operator ==(Object other) { if (identical(this, other)) return true; if (runtimeType != other.runtimeType) return false; return other is TableViewSlot && rowIndex == other.rowIndex && columnIndex == other.columnIndex; } @override int get hashCode => Object.hash(rowIndex, columnIndex); @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('row', rowIndex)); properties.add(IntProperty('column', columnIndex)); } } abstract class TableCellRange with Diagnosticable { const TableCellRange(); void visitCells(TableCellVisitor visitor); bool contains(int rowIndex, int columnIndex) { bool result = false; visitCells((int i, int j) { if (i == rowIndex && j == columnIndex) { result = true; } }); return result; } bool containsCell(TableCellOffset cellOffset) { return contains(cellOffset.rowIndex, cellOffset.columnIndex); } /// The collection of rows contained in this cell range. /// /// If a row appears in this iterable, it does _not_ necessarily follow that /// all cells in the row are contained in this cell range. Put another way, /// if only one cell in a row is contained in this cell range, the row will /// still be returned here. /// /// Each row will only appear once in the returned iterable, even if multiple /// cells within that row are contained in this cell range. Iterable<int> get rows { final Set<int> visitedRows = <int>{}; visitCells((int rowIndex, int columnIndex) { if (!visitedRows.contains(rowIndex)) { visitedRows.add(rowIndex); } }); return visitedRows; } TableCellRange where(bool test(int rowIndex, int columnIndex)) { return ProxyTableCellRange((TableCellVisitor visitor) { visitCells((int rowIndex, int columnIndex) { if (test(rowIndex, columnIndex)) { visitor(rowIndex, columnIndex); } }); }); } TableCellRange subtract(TableCellRange other) { return where( (int rowIndex, int columnIndex) => !other.contains(rowIndex, columnIndex), ); } TableCellRange intersect(TableCellRange other) { return where( (int rowIndex, int columnIndex) => other.contains(rowIndex, columnIndex), ); } } class SingleCellRange extends TableCellRange { const SingleCellRange(this.rowIndex, this.columnIndex); final int rowIndex; final int columnIndex; @override void visitCells(TableCellVisitor visitor) { visitor(rowIndex, columnIndex); } @override bool contains(int rowIndex, int columnIndex) { return rowIndex == this.rowIndex && columnIndex == this.columnIndex; } @override Iterable<int> get rows { return <int>[rowIndex]; } } class TableCellRect extends TableCellRange { const TableCellRect.fromLTRB(this.left, this.top, this.right, this.bottom); final int left; final int top; final int right; final int bottom; static const TableCellRect empty = TableCellRect.fromLTRB(0, 0, -1, -1); bool get isNormalized => left >= 0 && top >= 0 && left <= right && top <= bottom; /// True if [visitCells] will not visit anything. /// /// An empty [TableCellRect] is guaranteed to have an [isNormalized] value of /// false. bool get isEmpty => left > right || top > bottom; @override void visitCells(TableCellVisitor visitor) { for (int rowIndex = top; rowIndex <= bottom; rowIndex++) { for (int columnIndex = left; columnIndex <= right; columnIndex++) { visitor(rowIndex, columnIndex); } } } @override bool contains(int rowIndex, int columnIndex) { return rowIndex >= top && rowIndex <= bottom && columnIndex >= left && columnIndex <= right; } @override Iterable<int> get rows { return List<int>.generate(bottom - top + 1, (int i) => top + i); } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('left', left)); properties.add(IntProperty('top', top)); properties.add(IntProperty('right', right)); properties.add(IntProperty('bottom', bottom)); } } class EmptyTableCellRange extends TableCellRange { const EmptyTableCellRange(); @override void visitCells(TableCellVisitor visitor) {} @override bool contains(int rowIndex, int columnIndex) => false; @override Iterable<int> get rows => <int>[]; } class ProxyTableCellRange extends TableCellRange { const ProxyTableCellRange(this.host); final TableCellHost host; @override void visitCells(TableCellVisitor visitor) => host(visitor); @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Function>('host', host)); } } class UnionTableCellRange extends TableCellRange { UnionTableCellRange([List<TableCellRange> ranges = const <TableCellRange>[]]) : _ranges = List<TableCellRange>.from(ranges); final List<TableCellRange> _ranges; void add(TableCellRange range) { _ranges.add(range); } @override void visitCells(TableCellVisitor visitor) { final Set<TableCellOffset> cellOffsets = <TableCellOffset>{}; for (TableCellRange range in _ranges) { range.visitCells((int rowIndex, int columnIndex) { if (cellOffsets.add(TableCellOffset(rowIndex, columnIndex))) { visitor(rowIndex, columnIndex); } }); } } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add( DiagnosticsProperty<List<TableCellRange>>('ranges', _ranges), ); } } @immutable class TableCellOffset with Diagnosticable { const TableCellOffset(this.rowIndex, this.columnIndex); final int rowIndex; final int columnIndex; @override int get hashCode => Object.hash(rowIndex, columnIndex); @override bool operator ==(Object other) { if (identical(this, other)) return true; if (runtimeType != other.runtimeType) return false; return other is TableCellOffset && other.rowIndex == rowIndex && other.columnIndex == columnIndex; } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('rowIndex', rowIndex)); properties.add(IntProperty('columnIndex', columnIndex)); } } mixin TableViewElementMixin on RenderObjectElement { @override RenderTableViewMixin get renderObject => super.renderObject as RenderTableViewMixin; @protected Widget renderCell(int rowIndex, int columnIndex); @protected Widget? buildPrototypeCell(int columnIndex); late Map<int, Map<int, Element>> _children; @override void update(RenderObjectWidget newWidget) { assert(widget != newWidget); super.update(newWidget); assert(widget == newWidget); renderObject.updateLayoutCallback(_layout); renderObject.updatePrototypeCellBuilder(buildPrototypeCell); } void _layout({ required TableCellHost visitChildrenToRemove, required TableCellHost visitChildrenToBuild, }) { owner!.buildScope(this, () { visitChildrenToRemove((int rowIndex, int columnIndex) { assert(_children.containsKey(rowIndex)); final Map<int, Element> row = _children[rowIndex]!; assert(row.containsKey(columnIndex)); final Element child = row[columnIndex]!; final Element? newChild = updateChild( child, null, null /* unused for remove */, ); assert(newChild == null); row.remove(columnIndex); if (row.isEmpty) { _children.remove(rowIndex); } }); visitChildrenToBuild((int rowIndex, int columnIndex) { Widget built; try { built = renderCell(rowIndex, columnIndex); assert(() { if (debugPaintTableCellBuilds) { debugCurrentTableCellColor = debugCurrentTableCellColor.withHue( (debugCurrentTableCellColor.hue + 2) % 360.0, ); built = DecoratedBox( decoration: BoxDecoration( color: debugCurrentTableCellColor.toColor(), ), position: DecorationPosition.foreground, child: built, ); } return true; }()); debugWidgetBuilderValue(widget, built); } catch (e, stack) { built = ErrorWidget.builder( _debugReportException( ErrorDescription('building $widget'), e, stack, informationCollector: () sync* { yield DiagnosticsDebugCreator(DebugCreator(this)); }, ), ); } late final Element child; final TableViewSlot slot = TableViewSlot(rowIndex, columnIndex); final Map<int, Element> row = _children.putIfAbsent( rowIndex, () => <int, Element>{}, ); try { child = updateChild(row[columnIndex], built, slot)!; } catch (e, stack) { built = ErrorWidget.builder( _debugReportException( ErrorDescription('building $widget'), e, stack, informationCollector: () sync* { yield DiagnosticsDebugCreator(DebugCreator(this)); }, ), ); child = updateChild(null, built, slot)!; } row[columnIndex] = child; }); }); } static FlutterErrorDetails _debugReportException( DiagnosticsNode context, dynamic exception, StackTrace stack, { required InformationCollector informationCollector, }) { final FlutterErrorDetails details = FlutterErrorDetails( exception: exception, stack: stack, library: 'payouts', context: context, informationCollector: informationCollector, ); FlutterError.reportError(details); return details; } @override void performRebuild() { // This gets called if markNeedsBuild() is called on us. // That might happen if, e.g., our builder uses Inherited widgets. // Force the callback to be called, even if the layout constraints are the // same. This is because that callback may depend on the updated widget // configuration, or an inherited widget. renderObject.markNeedsBuild(); super.performRebuild(); // Calls widget.updateRenderObject } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _children = <int, Map<int, Element>>{}; renderObject.updateLayoutCallback(_layout); renderObject.updatePrototypeCellBuilder(buildPrototypeCell); } @override void unmount() { renderObject.updateLayoutCallback(null); renderObject.updatePrototypeCellBuilder(null); super.unmount(); } @override void visitChildren(ElementVisitor visitor) { for (final Map<int, Element> row in _children.values) { for (final Element child in row.values) { visitor(child); } } } @override void forgetChild(Element child) { assert(child.slot is TableViewSlot); final TableViewSlot slot = child.slot as TableViewSlot; assert(_children.containsKey(slot.rowIndex)); final Map<int, Element> row = _children[slot.rowIndex]!; assert(row.containsKey(slot.columnIndex)); assert(row[slot.columnIndex] == child); row.remove(slot.columnIndex); if (row.isEmpty) { _children.remove(slot.rowIndex); } super.forgetChild(child); } @override void insertRenderObjectChild(RenderBox child, TableViewSlot slot) { assert(child.parent == null); renderObject.insert( child, rowIndex: slot.rowIndex, columnIndex: slot.columnIndex, ); assert(child.parent == renderObject); } @override void moveRenderObjectChild( RenderBox child, TableViewSlot? oldSlot, TableViewSlot newSlot, ) { assert(child.parent == renderObject); renderObject.move( child, rowIndex: newSlot.rowIndex, columnIndex: newSlot.columnIndex, ); assert(child.parent == renderObject); } @override void removeRenderObjectChild(RenderBox child, TableViewSlot? slot) { assert(child.parent == renderObject); renderObject.remove(child); assert(child.parent == null); } } class BasicTableViewElement extends RenderObjectElement with TableViewElementMixin { BasicTableViewElement(BasicTableView tableView) : super(tableView); @override BasicTableView get widget => super.widget as BasicTableView; @override RenderBasicTableView get renderObject => super.renderObject as RenderBasicTableView; @override @protected Widget renderCell(int rowIndex, int columnIndex) { final BasicTableColumn column = widget.columns[columnIndex]; return column.cellBuilder(this, rowIndex, columnIndex); } @override @protected Widget? buildPrototypeCell(int columnIndex) { final BasicTableColumn column = widget.columns[columnIndex]; return column.prototypeCellBuilder != null ? column.prototypeCellBuilder!(this) : null; } } mixin RenderTableViewMixin on RenderSegment { List<AbstractTableColumn> get columns; set columns(covariant List<AbstractTableColumn> value); @protected List<AbstractTableColumn>? get rawColumns; double? _rowHeight; double get rowHeight => _rowHeight!; set rowHeight(double value) { if (_rowHeight == value) return; _rowHeight = value; markNeedsMetrics(); // The fact that the cell constraints changed could affect the built // output (e.g. if the cell builder uses LayoutBuilder). markNeedsBuild(); } int? _length; int get length => _length!; set length(int value) { assert(value >= 0); if (_length == value) return; _length = value; markNeedsMetrics(); // We rebuild because the cell at any given offset may not contain the same // contents as it did before the length changed. markNeedsBuild(); } @protected int? get rawLength => _length; bool? _roundColumnWidthsToWholePixel; bool get roundColumnWidthsToWholePixel => _roundColumnWidthsToWholePixel!; set roundColumnWidthsToWholePixel(bool value) { if (_roundColumnWidthsToWholePixel == value) return; _roundColumnWidthsToWholePixel = value; markNeedsMetrics(); // The fact that the cell constraints may change could affect the built // output (e.g. if the cell builder uses LayoutBuilder). markNeedsBuild(); } TableViewMetricsController? _metricsController; TableViewMetricsController? get metricsController => _metricsController; set metricsController(TableViewMetricsController? value) { if (value == _metricsController) return; _metricsController = value; if (_metricsController != null && !_needsMetrics) { _metricsController!._setMetrics(_metrics!); } } Map<int, Map<int, RenderBox>> _children = <int, Map<int, RenderBox>>{}; void insert( RenderBox child, { required int rowIndex, required int columnIndex, }) { final Map<int, RenderBox> row = _children.putIfAbsent( rowIndex, () => <int, RenderBox>{}, ); final RenderBox? oldChild = row.remove(columnIndex); if (oldChild != null) dropChild(oldChild); row[columnIndex] = child; child.parentData = _TableViewParentData() ..rowIndex = rowIndex ..columnIndex = columnIndex; adoptChild(child); } void move( RenderBox child, { required int rowIndex, required int columnIndex, }) { remove(child); insert(child, rowIndex: rowIndex, columnIndex: columnIndex); } void remove(RenderBox child) { assert(child.parentData is _TableViewParentData); final _TableViewParentData parentData = child.parentData as _TableViewParentData; final Map<int, RenderBox> row = _children[parentData.rowIndex]!; row.remove(parentData.columnIndex); if (row.isEmpty) { _children.remove(parentData.rowIndex); } dropChild(child); } TableViewLayoutCallback? _layoutCallback; /// Change the layout callback. @protected void updateLayoutCallback(TableViewLayoutCallback? value) { if (value == _layoutCallback) return; _layoutCallback = value; markNeedsBuild(); } TableViewPrototypeCellBuilder? _prototypeCellBuilder; @protected void updatePrototypeCellBuilder(TableViewPrototypeCellBuilder? value) { if (value == _prototypeCellBuilder) return; _prototypeCellBuilder = value; markNeedsLayout(); } /// Whether the whole table view is in need of being built. bool _needsBuild = true; /// Marks this table view as needing to rebuild. /// /// See also: /// /// * [markCellsDirty], which marks specific cells as needing to rebuild. @protected void markNeedsBuild() { _needsBuild = true; markNeedsLayout(); } /// Specific cells in need of building. UnionTableCellRange? _dirtyCells; /// Marks specific cells as needing to rebuild. /// /// See also: /// /// * [markNeedsBuild], which marks the whole table view as needing to /// rebuild. @protected void markCellsDirty(TableCellRange cells) { _dirtyCells ??= UnionTableCellRange(); _dirtyCells!.add(cells); markNeedsLayout(); } @override void attach(PipelineOwner owner) { super.attach(owner); visitChildren((RenderObject child) { child.attach(owner); }); } @override void detach() { super.detach(); visitChildren((RenderObject child) { child.detach(); }); } @protected void visitTableCells( TableCellChildVisitor visitor, { bool allowMutations = false, }) { Iterable<MapEntry<int, Map<int, RenderBox>>> rows = _children.entries; if (allowMutations) rows = rows.toList(growable: false); for (MapEntry<int, Map<int, RenderBox>> row in rows) { final int rowIndex = row.key; Iterable<MapEntry<int, RenderBox>> cells = row.value.entries; if (allowMutations) cells = cells.toList(growable: false); for (MapEntry<int, RenderBox> cell in cells) { final int columnIndex = cell.key; final RenderBox child = cell.value; visitor(child, rowIndex, columnIndex); } } } @override void visitChildren(RenderObjectVisitor visitor) { visitTableCells((RenderBox child, int rowIndex, int columnIndex) { visitor(child); }); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final TableCellOffset? cellOffset = metrics.getCellAt(position); if (cellOffset == null || !_children.containsKey(cellOffset.rowIndex) || !_children[cellOffset.rowIndex]!.containsKey(cellOffset.columnIndex)) { // No table cell at the given position. return false; } final RenderBox child = _children[cellOffset.rowIndex]![cellOffset.columnIndex]!; final BoxParentData parentData = child.parentData as BoxParentData; return result.addWithPaintOffset( offset: parentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - parentData.offset); return child.hitTest(result, position: transformed); }, ); } @override void setupParentData(RenderBox child) { // We manually attach the parent data in [insert] before adopting the child, // so by the time this is called, the parent data is already set-up. assert(child.parentData is _TableViewParentData); super.setupParentData(child); } @override double computeMinIntrinsicWidth(double height) { return columns .map<TableColumnWidth>((AbstractTableColumn column) => column.width) .where((TableColumnWidth width) => !width.isFlex) .map<double>((TableColumnWidth width) => width.width) .map<double>( (double w) => roundColumnWidthsToWholePixel ? w.roundToDouble() : w, ) .fold<double>(0, (double previous, double width) => previous + width); } @override double computeMaxIntrinsicWidth(double height) => computeMinIntrinsicWidth(height); @override double computeMinIntrinsicHeight(double width) { return length * rowHeight; } @override double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); @override double? computeDistanceToActualBaseline(TextBaseline baseline) { double? result; const WidgetSurveyor surveyor = WidgetSurveyor(); if (_prototypeCellBuilder != null) { for (int j = 0; j < columns.length; j++) { final Widget? prototype = _prototypeCellBuilder!(j); if (prototype != null) { final double? value = surveyor.measureDistanceToActualBaseline( prototype, baseline: baseline, ); if (result != null) { result = math.max(result, value ?? 0); } else { result = value; } } } } return result; } bool _needsMetrics = true; TableViewMetricsResolver? _metrics; Rect? _viewport; @protected TableViewMetricsResolver get metrics => _metrics!; @protected void markNeedsMetrics() { _needsMetrics = true; markNeedsLayout(); } @protected void calculateMetricsIfNecessary() { assert(debugDoingThisLayout); final BoxConstraints boxConstraints = constraints.asBoxConstraints(); if (_needsMetrics || _metrics!.constraints != boxConstraints) { _metrics = TableViewMetricsResolver.of( columns, rowHeight, length, boxConstraints, roundWidths: roundColumnWidthsToWholePixel, ); _needsMetrics = false; if (_metricsController != null) { _metricsController!._setMetrics(_metrics!); } } } @override @protected void performLayout() { calculateMetricsIfNecessary(); size = constraints.constrainDimensions( metrics.totalWidth, metrics.totalHeight, ); // Relies on size being set. rebuildIfNecessary(); visitTableCells((RenderBox child, int rowIndex, int columnIndex) { final Range columnBounds = metrics.columnBounds[columnIndex]; final double rowY = rowIndex * rowHeight; child.layout( BoxConstraints.tightFor(width: columnBounds.extent, height: rowHeight), ); final BoxParentData parentData = child.parentData as BoxParentData; parentData.offset = Offset(columnBounds.start, rowY); }); } bool _isInBounds(int rowIndex, int columnIndex) { return rowIndex < length && columnIndex < columns.length; } bool _isBuilt(int rowIndex, int columnIndex) { return _children.containsKey(rowIndex) && _children[rowIndex]!.containsKey(columnIndex); } bool _isNotBuilt(int rowIndex, int columnIndex) { return !_children.containsKey(rowIndex) || !_children[rowIndex]!.containsKey(columnIndex); } @protected TableCellRange builtCells() { return ProxyTableCellRange((TableCellVisitor visitor) { visitTableCells((RenderBox child, int rowIndex, int columnIndex) { visitor(rowIndex, columnIndex); }, allowMutations: true); }); } @protected void rebuildIfNecessary() { assert(_layoutCallback != null); assert(debugDoingThisLayout); final Rect? previousViewport = _viewport; _viewport = constraints.viewportResolver.resolve(size); if (!_needsBuild && _dirtyCells == null && _viewport == previousViewport) { return; } final TableCellRange builtCells = this.builtCells(); final TableCellRect viewportCellRect = metrics.intersect(_viewport!); TableCellRange removeCells = builtCells.subtract(viewportCellRect); TableCellRange buildCells; if (_needsBuild) { removeCells = UnionTableCellRange(<TableCellRange>[ removeCells, builtCells.where((int rowIndex, int columnIndex) => rowIndex >= length), ]); buildCells = viewportCellRect; _needsBuild = false; _dirtyCells = null; } else if (_dirtyCells != null) { buildCells = UnionTableCellRange(<TableCellRange>[ _dirtyCells!.intersect(viewportCellRect), viewportCellRect.where(_isNotBuilt), ]); _dirtyCells = null; } else { assert(previousViewport != null); if (_viewport!.overlaps(previousViewport!)) { final Rect overlap = _viewport!.intersect(previousViewport); final TableCellRect overlapCellRect = metrics.intersect(overlap); removeCells = metrics .intersect(previousViewport) .subtract(overlapCellRect); buildCells = viewportCellRect.subtract(overlapCellRect); } else { buildCells = viewportCellRect; } } // TODO: lowering length causes stranded built cells - figure out why... invokeLayoutCallback<SegmentConstraints>((SegmentConstraints _) { _layoutCallback!( visitChildrenToRemove: removeCells.where(_isBuilt).visitCells, visitChildrenToBuild: buildCells.where(_isInBounds).visitCells, ); }); } @override void paint(PaintingContext context, Offset offset) { visitChildren((RenderObject child) { final BoxParentData parentData = child.parentData as BoxParentData; context.paintChild(child, offset + parentData.offset); }); } @override void redepthChildren() { visitChildren((RenderObject child) { redepthChild(child); }); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> result = <DiagnosticsNode>[]; visitTableCells((RenderBox child, int rowIndex, int columnIndex) { result.add(child.toDiagnosticsNode(name: 'child $rowIndex,$columnIndex')); }); return result; } } class RenderBasicTableView extends RenderSegment with RenderTableViewMixin { RenderBasicTableView({ required double rowHeight, required int length, required List<BasicTableColumn> columns, bool roundColumnWidthsToWholePixel = false, TableViewMetricsController? metricsController, }) { this.rowHeight = rowHeight; this.length = length; this.columns = columns; this.roundColumnWidthsToWholePixel = roundColumnWidthsToWholePixel; this.metricsController = metricsController; } List<BasicTableColumn>? _columns; @override List<BasicTableColumn>? get rawColumns => _columns; @override List<BasicTableColumn> get columns => _columns!; @override set columns(List<BasicTableColumn> value) { if (_columns == value) return; _columns = value; markNeedsMetrics(); markNeedsBuild(); } } class _TableViewParentData extends BoxParentData { late int rowIndex; late int columnIndex; @override String toString() => '${super.toString()}, rowIndex=$rowIndex, columnIndex=$columnIndex'; } /// Class capable of reporting various layout metrics of a [BasicTableView]. @immutable abstract class TableViewMetrics { /// Gets the row index found at the specified y-offset. /// /// The [dy] argument is in logical pixels and exists in the local coordinate /// space of the table view. /// /// Returns -1 if the offset doesn't overlap with a row in the table view. int getRowAt(double dy); /// Gets the column index found at the specified x-offset. /// /// The [dx] argument is in logical pixels and exists in the local coordinate /// space of the table view. /// /// Returns -1 if the offset doesn't overlap with a column in the table view. int getColumnAt(double dx); /// Gets the cell coordinates found at the specified offset. /// /// The [position] argument is in logical pixels and exists in the local /// coordinate space of the table view. /// /// Returns null if the offset doesn't overlap with a cell in the table view. TableCellOffset? getCellAt(Offset position); /// Gets the bounding [Rect] of the specified row in the table view. /// /// The returned [Rect] exists in the local coordinate space of the table /// view. /// /// The [rowIndex] argument must be greater than or equal to zero and less /// than the number of rows in the table view. Rect getRowBounds(int rowIndex); /// Gets the bounding [Rect] of the specified column in the table view. /// /// The returned [Rect] exists in the local coordinate space of the table /// view. /// /// The [columnIndex] argument must be greater than or equal to zero and less /// than the number of columns in the table view. Rect getColumnBounds(int columnIndex); /// Gets the bounding [Rect] of the specified cell in the table view. /// /// The returned [Rect] exists in the local coordinate space of the table /// view. /// /// Both the [rowIndex] and the [columnIndex] argument must represent valid /// (in bounds) values given the number of rows and columns in the table /// view. Rect getCellBounds(int rowIndex, int columnIndex); } typedef TableViewMetricsChangedHandler = void Function( TableViewMetricsController controller, TableViewMetrics? oldMetrics, ); class TableViewMetricsListener { const TableViewMetricsListener({required this.onChanged}); final TableViewMetricsChangedHandler onChanged; } class TableViewMetricsController with ListenerNotifier<TableViewMetricsListener> { TableViewMetrics? _metrics; TableViewMetrics get metrics => _metrics!; void _setMetrics(TableViewMetrics value) { if (value == _metrics) return; final TableViewMetrics? oldValue = _metrics; _metrics = value; notifyListeners((TableViewMetricsListener listener) { listener.onChanged(this, oldValue); }); } } /// Resolves column width specifications against [BoxConstraints]. /// /// Produces a list of column widths whose sum satisfies the /// [BoxConstraints.maxWidth] property of the [constraints] and whose values /// are as close as possible to satisfying the column width specifications. /// /// The sum of the column widths isn't required to satisfy the /// [BoxConstraints.minWidth] property of the [constraints] because the table /// view can be wider than the sum of its columns (yielding blank space), but /// it can't be skinnier. /// /// The returned list is guaranteed to be the same length as [columns] and /// contain only non-negative finite values. @visibleForTesting class TableViewMetricsResolver implements TableViewMetrics { const TableViewMetricsResolver._( this.columns, this.constraints, this.rowHeight, this.length, this.columnBounds, ); /// The columns of the table view. /// /// Each column's [AbstractTableColumn.width] specification is the source (when /// combined with [constraints]) of the resolved column widths in /// [columnWidth]. final List<AbstractTableColumn> columns; /// The [BoxConstraints] against which the width specifications of the /// [columns] were resolved. final BoxConstraints constraints; /// The fixed row height of each row in the table view. final double rowHeight; /// The number of rows in the table view. final int length; /// The offsets & widths of the columns in the table view. /// /// The values in this list correspond to the columns in the [columns] list. final List<Range> columnBounds; static TableViewMetricsResolver of( List<AbstractTableColumn> columns, double rowHeight, int length, BoxConstraints constraints, { bool roundWidths = false, }) { assert(constraints.runtimeType == BoxConstraints); double totalFlexWidth = 0; double totalFixedWidth = 0; final List<double> resolvedWidths = List<double>.filled(columns.length, 0); final Map<int, AbstractTableColumn> flexColumns = <int, AbstractTableColumn>{}; // Reserve space for the fixed-width columns first. for (int i = 0; i < columns.length; i++) { final AbstractTableColumn column = columns[i]; if (column.width.isFlex) { final FlexTableColumnWidth widthSpecification = column.width as FlexTableColumnWidth; totalFlexWidth += widthSpecification.width; flexColumns[i] = column; } else { double columnWidth = column.width.width; if (roundWidths) { columnWidth = columnWidth.roundToDouble(); } totalFixedWidth += columnWidth; resolvedWidths[i] = columnWidth; } } double maxWidthDelta = constraints.maxWidth - totalFixedWidth; if (maxWidthDelta.isNegative) { // The fixed-width columns have already exceeded the maxWidth constraint; // truncate trailing column widths until we meet the constraint. for (int i = resolvedWidths.length - 1; i >= 0; i--) { final double width = resolvedWidths[i]; if (width > 0) { final double adjustedWidth = math.max(width + maxWidthDelta, 0); final double adjustment = width - adjustedWidth; maxWidthDelta += adjustment; if (maxWidthDelta >= 0) { break; } } } assert(() { if (maxWidthDelta < -_kDoublePrecisionTolerance) { FlutterError.reportError( FlutterErrorDetails( exception: 'TableView column width adjustment was unable to satisfy the ' 'maxWidth constraint', stack: StackTrace.current, library: 'payouts', ), ); } return true; }()); } else if (flexColumns.isNotEmpty) { // There's still width to spare after fixed-width column allocations. double flexAllocation = 0; if (maxWidthDelta.isFinite) { flexAllocation = maxWidthDelta; } else if (totalFixedWidth < constraints.minWidth) { flexAllocation = constraints.minWidth - totalFixedWidth; } if (flexAllocation > 0) { for (MapEntry<int, AbstractTableColumn> flexColumn in flexColumns.entries) { final FlexTableColumnWidth widthSpecification = flexColumn.value.width as FlexTableColumnWidth; final double allocationPercentage = widthSpecification.width / totalFlexWidth; double columnWidth = flexAllocation * allocationPercentage; if (roundWidths) { columnWidth = columnWidth.roundToDouble(); } resolvedWidths[flexColumn.key] = columnWidth; } } } double left = 0; final List<Range> resolvedColumnBounds = List<Range>.generate( columns.length, (int index) { final double right = left + resolvedWidths[index]; final Range result = Range(left, right); left = right; return result; }, ); return TableViewMetricsResolver._( columns, constraints, rowHeight, length, resolvedColumnBounds, ); } /// The total column width of the table view. double get totalWidth => columnBounds.isEmpty ? 0 : columnBounds.last.end; double get totalHeight => length * rowHeight; TableCellRect intersect(Rect rect) { if (rect.isEmpty) { return TableCellRect.empty; } int leftIndex = columnBounds.indexWhere( (Range bounds) => bounds.end > rect.left, ); int rightIndex = columnBounds.lastIndexWhere( (Range bounds) => bounds.start < rect.right, ); if (leftIndex == -1 || rightIndex == -1) { return TableCellRect.empty; } else { int bottomIndex = rect.bottom ~/ rowHeight; if (rect.bottom.remainder(rowHeight) == 0) { // The rect goes *right up* to the cell but doesn't actually overlap it. bottomIndex -= 1; } return TableCellRect.fromLTRB( leftIndex, rect.top ~/ rowHeight, rightIndex, bottomIndex, ); } } @override Rect getRowBounds(int rowIndex) { assert(rowIndex >= 0 && rowIndex < length); return Rect.fromLTWH(0, rowIndex * rowHeight, totalWidth, rowHeight); } @override Rect getColumnBounds(int columnIndex) { assert(columnIndex >= 0 && columnIndex < columnBounds.length); final Range columnRange = columnBounds[columnIndex]; return Rect.fromLTRB( columnRange.start, 0, columnRange.end, length * rowHeight, ); } @override Rect getCellBounds(int rowIndex, int columnIndex) { final Range columnRange = columnBounds[columnIndex]; final double rowStart = rowIndex * rowHeight; return Rect.fromLTRB( columnRange.start, rowStart, columnRange.end, rowStart + rowHeight, ); } @override int getRowAt(double dy) { assert(dy.isFinite); if (dy.isNegative) { return -1; } final int rowIndex = dy ~/ rowHeight; if (rowIndex >= length) { return -1; } return rowIndex; } @override int getColumnAt(double dx) { assert(dx.isFinite); int columnIndex = columnBounds.indexWhere( (Range range) => range.start <= dx, ); if (columnIndex >= 0) { columnIndex = columnBounds.indexWhere( (Range range) => range.end > dx, columnIndex, ); } return columnIndex; } @override TableCellOffset? getCellAt(Offset position) { final int rowIndex = getRowAt(position.dy); final int columnIndex = getColumnAt(position.dx); if (rowIndex == -1 || columnIndex == -1) { return null; } return TableCellOffset(rowIndex, columnIndex); } } class Range with Diagnosticable { const Range(this.start, this.end) : assert(start <= end); final double start; final double end; double get extent => end - start; @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('start', start)); properties.add(DoubleProperty('end', end)); } @override int get hashCode => Object.hash(start, end); @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Range && other.start == start && other.end == end; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/border_pane.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'dart:ui'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart' as flutter show Border; class BorderPane extends StatelessWidget { const BorderPane({ Key? key, this.title, this.titleStyle, this.titlePadding = EdgeInsets.zero, this.textDirection, this.borderColor = const Color(0xff000000), this.borderThickness = 1, this.borderRadius = BorderRadius.zero, this.backgroundColor, this.inset = 0, required this.child, }) : super(key: key); final String? title; final TextStyle? titleStyle; final EdgeInsetsGeometry titlePadding; /// The directionality of this widget. /// /// This affects the placement of the [title] widget and the associated /// behavior of the [inset] amount. final TextDirection? textDirection; /// The color of the border. /// /// If unspecified, this defaults to black. final Color borderColor; /// The thickness of the border. /// /// If unspecified, this defaults to a 1-pixel border. final double borderThickness; /// The border radius. /// /// If unspecified, this defaults to a zero-radius (square) border. final BorderRadiusGeometry borderRadius; /// The color to paint inside the border, behind the [child] and [title]. /// /// If unspecified, the background will be transparent. final Color? backgroundColor; /// The indentation (in pixels) for [title]. /// /// If the [textDirection] is [TextDirection.ltr], then this will be a left /// indent. If the [textDirection] is [TextDirection.rtl], then this will be /// a right indent. final double inset; /// The widget to lay out inside the border. final Widget child; @override Widget build(BuildContext context) { Widget? titleWidget; if (title != null) { TextStyle? titleStyle = this.titleStyle; if (titleStyle == null) { final TextStyle baseStyle = DefaultTextStyle.of(context).style; titleStyle = baseStyle.copyWith( fontWeight: FontWeight.bold, color: const Color(0xff3c77b2), ); } titleWidget = Padding( padding: titlePadding, child: Text(title!, style: titleStyle), ); } return _BorderLayout( textDirection: textDirection ?? Directionality.of(context), inset: inset, title: titleWidget, child: DecoratedBox( decoration: BoxDecoration( border: flutter.Border.all( width: borderThickness, color: borderColor, ), borderRadius: borderRadius, color: backgroundColor, ), child: Padding(padding: EdgeInsets.all(borderThickness), child: child), ), ); } } class _BorderLayout extends RenderObjectWidget { _BorderLayout({ Key? key, required this.title, required this.child, required this.inset, required this.textDirection, }) : super(key: key); final Widget? title; final Widget child; final double inset; final TextDirection textDirection; @override RenderObjectElement createElement() => _BorderLayoutElement(this); @override _RenderBorderLayout createRenderObject(BuildContext context) { return _RenderBorderLayout(inset: inset, textDirection: textDirection); } @override void updateRenderObject( BuildContext context, _RenderBorderLayout renderObject, ) { renderObject ..inset = inset ..textDirection = textDirection; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<double>('inset', inset)); properties.add( DiagnosticsProperty<TextDirection>('textDirection', textDirection), ); } } enum _BorderLayoutSlot { title, child } class _BorderLayoutElement extends RenderObjectElement { _BorderLayoutElement(_BorderLayout widget) : super(widget); Element? _title; Element? _child; @override _BorderLayout get widget => super.widget as _BorderLayout; @override _RenderBorderLayout get renderObject => super.renderObject as _RenderBorderLayout; @override void visitChildren(ElementVisitor visitor) { if (_title != null) { visitor(_title!); } if (_child != null) { visitor(_child!); } } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _title = updateChild(_title, widget.title, _BorderLayoutSlot.title); _child = updateChild(_child, widget.child, _BorderLayoutSlot.child); } @override void insertRenderObjectChild(RenderBox child, _BorderLayoutSlot slot) { switch (slot) { case _BorderLayoutSlot.title: renderObject.title = child; break; case _BorderLayoutSlot.child: renderObject.child = child; break; } } @override void moveRenderObjectChild( RenderObject _, _BorderLayoutSlot? __, _BorderLayoutSlot? ___, ) { assert(false); } @override void update(RenderObjectWidget newWidget) { super.update(newWidget); _title = updateChild(_title, widget.title, _BorderLayoutSlot.title); _child = updateChild(_child, widget.child, _BorderLayoutSlot.child); } @override void forgetChild(Element child) { assert(child == _title || child == _child); if (child == _title) { _title = null; } else if (child == _child) { _child = null; } super.forgetChild(child); } @override void removeRenderObjectChild(RenderBox child, _BorderLayoutSlot? slot) { assert(child == renderObject.title || child == renderObject.child); switch (slot) { case _BorderLayoutSlot.title: renderObject.title = null; break; case _BorderLayoutSlot.child: renderObject.child = null; break; case null: assert(false); } } } class _RenderBorderLayout extends RenderBox { _RenderBorderLayout({ double inset = 0, TextDirection textDirection = TextDirection.ltr, }) { this.inset = inset; this.textDirection = textDirection; } double? _inset; double get inset => _inset!; set inset(double value) { if (value == _inset) return; _inset = value; markNeedsLayout(); } TextDirection? _textDirection; TextDirection get textDirection => _textDirection!; set textDirection(TextDirection value) { if (value == _textDirection) return; _textDirection = value; markNeedsLayout(); } RenderBox? _title; RenderBox? get title => _title; set title(RenderBox? value) { if (value == _title) return; if (_title != null) dropChild(_title!); _title = value; if (_title != null) adoptChild(_title!); } RenderBox? _child; RenderBox? get child => _child; set child(RenderBox? value) { if (value == _child) return; if (_child != null) dropChild(_child!); _child = value; if (_child != null) adoptChild(_child!); } @override void attach(PipelineOwner owner) { super.attach(owner); if (title != null) title!.attach(owner); if (child != null) child!.attach(owner); } @override void detach() { super.detach(); if (title != null) title!.detach(); if (child != null) child!.detach(); } @override void visitChildren(RenderObjectVisitor visitor) { if (title != null) visitor(title!); if (child != null) visitor(child!); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { bool isHit = false; for (RenderBox? child in [title, this.child]) { if (child != null) { final BoxParentData parentData = child.parentData as BoxParentData; isHit |= result.addWithPaintOffset( offset: parentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - parentData.offset); return child.hitTest(result, position: transformed); }, ); } } return isHit; } @override bool hitTestSelf(Offset position) => true; @override double computeMinIntrinsicWidth(double height) { double intrinsicWidth = 0; double titleHalfHeight = 0; if (title != null) { intrinsicWidth = title!.getMinIntrinsicWidth(double.infinity); titleHalfHeight = (title!.getMinIntrinsicHeight(intrinsicWidth) / 2).ceilToDouble(); } if (child != null) { if (height.isFinite) { height = math.max(height - titleHalfHeight, 0); } intrinsicWidth = math.max( child!.getMinIntrinsicWidth(height), intrinsicWidth, ); } return intrinsicWidth; } @override double computeMaxIntrinsicWidth(double height) => computeMinIntrinsicWidth(height); @override double computeMinIntrinsicHeight(double width) { double intrinsicHeight = 0; if (title != null) { double titleHeight = title!.getMinIntrinsicHeight(width - inset); intrinsicHeight += (titleHeight / 2).ceilToDouble(); } if (child != null) { intrinsicHeight += child!.getMinIntrinsicHeight(width); } return intrinsicHeight; } @override double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); @override void performLayout() { double titleHeight = 0; if (title != null) { title!.layout( constraints.deflate(EdgeInsets.only(left: inset)).loosen(), parentUsesSize: true, ); titleHeight = title!.size.height; } final double titleHalfHeight = (titleHeight / 2).roundToDouble(); Size childSize = Size.zero; if (child != null) { BoxConstraints childConstraints = constraints.deflate( EdgeInsets.only(top: titleHalfHeight), ); child!.layout(childConstraints, parentUsesSize: true); childSize = child!.size; final BoxParentData childParentData = child!.parentData as BoxParentData; childParentData.offset = Offset(0, titleHalfHeight); } size = constraints.constrainDimensions( childSize.width, childSize.height + titleHalfHeight, ); if (title != null) { final BoxParentData titleParentData = title!.parentData as BoxParentData; if (textDirection == TextDirection.ltr) { titleParentData.offset = Offset(inset, 0); } else { titleParentData.offset = Offset( size.width - title!.size.width - inset, 0, ); } } } @override void paint(PaintingContext context, Offset offset) { if (child != null) { final BoxParentData childParentData = child!.parentData as BoxParentData; if (title != null) { context.canvas.save(); try { final BoxParentData titleParentData = title!.parentData as BoxParentData; context.canvas.clipRect( (offset + titleParentData.offset) & title!.size, clipOp: ClipOp.difference, ); context.paintChild(child!, offset + childParentData.offset); } finally { context.canvas.restore(); } } else { context.paintChild(child!, offset + childParentData.offset); } } if (title != null) { final BoxParentData titleParentData = title!.parentData as BoxParentData; context.paintChild(title!, offset + titleParentData.offset); } } @override void redepthChildren() { if (title != null) redepthChild(title!); if (child != null) redepthChild(child!); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> result = <DiagnosticsNode>[]; void add(RenderBox? child, String name) { if (child != null) result.add(child.toDiagnosticsNode(name: name)); } add(title, 'title'); add(child, 'child'); return result; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/box_pane.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'segment.dart'; import 'visibility_aware.dart'; class BoxPane extends MultiChildRenderObjectWidget { BoxPane({ Key? key, this.axis = Axis.vertical, this.mainAxisAlignment = MainAxisAlignment.start, this.crossAxisAlignment = CrossAxisAlignment.start, this.padding = EdgeInsets.zero, this.spacing = 4, List<Widget> children = const <Widget>[], }) : super(key: key, children: children); final Axis axis; final MainAxisAlignment mainAxisAlignment; final CrossAxisAlignment crossAxisAlignment; final EdgeInsets padding; final double spacing; @override RenderBoxPane createRenderObject(BuildContext context) { return RenderBoxPane( axis: axis, mainAxisAlignment: mainAxisAlignment, crossAxisAlignment: crossAxisAlignment, padding: padding, spacing: spacing, ); } @override void updateRenderObject(BuildContext context, RenderBoxPane renderObject) { renderObject ..axis = axis ..mainAxisAlignment = mainAxisAlignment ..crossAxisAlignment = crossAxisAlignment ..padding = padding ..spacing = spacing; } } class BoxPaneParentData extends ContainerBoxParentData<RenderBox> {} class RenderBoxPane extends RenderSegment with ContainerRenderObjectMixin<RenderBox, BoxPaneParentData>, RenderBoxContainerDefaultsMixin<RenderBox, BoxPaneParentData> { RenderBoxPane({ Axis axis = Axis.horizontal, MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start, CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.start, EdgeInsets padding = EdgeInsets.zero, double spacing = 4, }) : _axis = axis, _mainAxisAlignment = mainAxisAlignment, _crossAxisAlignment = crossAxisAlignment, _padding = padding, _spacing = spacing; Axis _axis; Axis get axis => _axis; set axis(Axis value) { if (value != _axis) { _axis = value; markNeedsLayout(); } } MainAxisAlignment _mainAxisAlignment; MainAxisAlignment get mainAxisAlignment => _mainAxisAlignment; set mainAxisAlignment(MainAxisAlignment value) { if (value != _mainAxisAlignment) { _mainAxisAlignment = value; markNeedsLayout(); } } CrossAxisAlignment _crossAxisAlignment; CrossAxisAlignment get crossAxisAlignment => _crossAxisAlignment; set crossAxisAlignment(CrossAxisAlignment value) { if (value != _crossAxisAlignment) { _crossAxisAlignment = value; markNeedsLayout(); } } EdgeInsets _padding; EdgeInsets get padding => _padding; set padding(EdgeInsets value) { if (value != _padding) { _padding = value; markNeedsLayout(); } } double _spacing; double get spacing => _spacing; set spacing(double value) { if (value != _spacing) { _spacing = value; markNeedsLayout(); } } double _getCrossSize(Size size) { switch (_axis) { case Axis.horizontal: return size.height; case Axis.vertical: return size.width; } } double _getMainSize(Size size) { switch (_axis) { case Axis.horizontal: return size.width; case Axis.vertical: return size.height; } } Size _getSize(double mainSize, double crossSize) { switch (_axis) { case Axis.horizontal: return Size(mainSize, crossSize); case Axis.vertical: return Size(crossSize, mainSize); } } @override void setupParentData(RenderBox child) { if (child.parentData is! BoxPaneParentData) { child.parentData = BoxPaneParentData(); } } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { return defaultComputeDistanceToFirstActualBaseline(baseline); } @override double computeMinIntrinsicWidth(double height) { // TODO: implement computeMinIntrinsicWidth return super.computeMinIntrinsicWidth(height); } @override double computeMaxIntrinsicWidth(double height) { // TODO: implement computeMaxIntrinsicWidth return super.computeMaxIntrinsicWidth(height); } @override double computeMinIntrinsicHeight(double width) { // TODO: implement computeMinIntrinsicHeight return super.computeMinIntrinsicHeight(width); } @override double computeMaxIntrinsicHeight(double width) { // TODO: implement computeMaxIntrinsicHeight return super.computeMaxIntrinsicHeight(width); } @override Size computeDryLayout(BoxConstraints constraints) { // TODO: implement computeDryLayout return super.computeDryLayout(constraints); } @override void performLayout() { final BoxConstraints paddedConstraints = constraints.deflate(padding); double crossSize = 0; double mainSize = 0; int childCount = 0; RenderBox? child = firstChild; while (child != null) { childCount++; final BoxPaneParentData childParentData = child.parentData! as BoxPaneParentData; final BoxConstraints innerConstraints; if (crossAxisAlignment == CrossAxisAlignment.stretch) { switch (axis) { case Axis.horizontal: innerConstraints = BoxConstraints.tightFor( height: paddedConstraints.maxHeight, ); break; case Axis.vertical: innerConstraints = BoxConstraints.tightFor( width: paddedConstraints.maxWidth, ); break; } } else { switch (axis) { case Axis.horizontal: innerConstraints = BoxConstraints( maxHeight: paddedConstraints.maxHeight, ); break; case Axis.vertical: innerConstraints = BoxConstraints( maxWidth: paddedConstraints.maxWidth, ); break; } } child.layout(innerConstraints, parentUsesSize: true); final Size childSize = child.size; mainSize += _getMainSize(childSize); crossSize = math.max(crossSize, _getCrossSize(childSize)); assert(child.parentData == childParentData); child = childParentData.nextSibling; } mainSize += math.max(childCount - 1, 0) * spacing; size = constraints.constrain( padding.inflateSize(_getSize(mainSize, crossSize)), ); child = firstChild; double mainOffset; double crossPadding; switch (axis) { case Axis.horizontal: mainOffset = padding.left; crossPadding = padding.top; break; case Axis.vertical: mainOffset = padding.top; crossPadding = padding.left; break; } while (child != null) { final BoxPaneParentData childParentData = child.parentData! as BoxPaneParentData; switch (axis) { case Axis.horizontal: double dx = mainOffset; switch (mainAxisAlignment) { case MainAxisAlignment.start: // Existing dx is correct break; case MainAxisAlignment.center: dx = mainOffset + (size.width - mainSize - padding.horizontal) / 2; break; case MainAxisAlignment.end: dx = mainOffset + (size.width - mainSize - padding.horizontal); break; case MainAxisAlignment.spaceAround: case MainAxisAlignment.spaceBetween: case MainAxisAlignment.spaceEvenly: throw UnimplementedError(); } double dy = crossPadding; switch (crossAxisAlignment) { case CrossAxisAlignment.start: // Fallthrough case CrossAxisAlignment.stretch: // Initial value of dy is correct. break; case CrossAxisAlignment.center: dy = padding.top + (size.height - padding.vertical - child.size.height) / 2; break; case CrossAxisAlignment.baseline: throw UnimplementedError(); case CrossAxisAlignment.end: dy = size.height - child.size.height - padding.bottom; break; } childParentData.offset = Offset(dx, dy); mainOffset += child.size.width + spacing; break; case Axis.vertical: double dx = crossPadding; switch (crossAxisAlignment) { case CrossAxisAlignment.start: // Fallthrough case CrossAxisAlignment.stretch: // Initial value of dx is correct. break; case CrossAxisAlignment.center: dx = padding.left + (size.width - padding.horizontal - child.size.width) / 2; break; case CrossAxisAlignment.baseline: assert(() { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary( 'CrossAxisAlignment.baseline is not supported for vertical axes', ), ]); }()); // In non-debug mode, fall through to initial value of dx. break; case CrossAxisAlignment.end: dx = size.width - child.size.width - padding.right; break; } double dy = mainOffset; switch (mainAxisAlignment) { case MainAxisAlignment.start: // Existing dy is correct break; case MainAxisAlignment.center: dy = mainOffset + (size.height - mainSize - padding.vertical) / 2; break; case MainAxisAlignment.end: dy = mainOffset + (size.height - mainSize - padding.vertical); break; case MainAxisAlignment.spaceAround: case MainAxisAlignment.spaceBetween: case MainAxisAlignment.spaceEvenly: throw UnimplementedError(); } childParentData.offset = Offset(dx, dy); mainOffset += child.size.height + spacing; break; } assert(child.parentData == childParentData); child = childParentData.nextSibling; } } @override void paint(PaintingContext context, Offset offset) { final Rect viewport = constraints.viewportResolver.resolve(size); RenderBox? child = firstChild; while (child != null) { final BoxPaneParentData childParentData = child.parentData! as BoxPaneParentData; if (viewport.overlaps(childParentData.offset & child.size)) { VisibilityAwareMixin.setChildVisible(child, true); context.paintChild(child, childParentData.offset + offset); } else { VisibilityAwareMixin.setChildVisible(child, false); } child = childParentData.nextSibling; } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/calendar.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/widgets.dart' hide Border, TableCell, TableRow; import 'package:flutter/widgets.dart' as flutter show Border; import 'package:intl/intl.dart' as intl; import 'border_pane.dart'; import 'colors.dart'; import 'foundation.dart'; import 'hover_builder.dart'; import 'spinner.dart'; import 'table_pane.dart'; @immutable class CalendarDate implements Comparable<CalendarDate> { const CalendarDate(this.year, this.month, this.day); CalendarDate.fromDateTime(DateTime date) : year = date.year, month = date.month - 1, day = date.day - 1; factory CalendarDate.today() => CalendarDate.fromDateTime(DateTime.now()); final int year; final int month; final int day; static const List<int> _monthLengths = <int>[ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ]; static const int _gregorianCutoverYear = 1582; bool get isValid { if (year <= _gregorianCutoverYear || year > 9999) { return false; } if (month < 0 || month > 11) { return false; } if (day < 0 || day >= daysInMonth) { return false; } return true; } /// The day of the week, Monday (1) to Sunday (7). /// /// In accordance with ISO 8601, a week starts with Monday (which has the /// value 1). int get weekday => toDateTime().weekday; /// Whether the year represented by this calendar date is a leap year. bool get isLeapYear => _calculateIsLeapYear(year); static bool _calculateIsLeapYear(int year) { return (year & 3) == 0 && (year % 100 != 0 || year % 400 == 0); } /// The number of days in the month represented by this calendar date. int get daysInMonth => _calculateDaysInMonth(year, month); static int _calculateDaysInMonth(int year, int month) { int daysInMonth = _monthLengths[month]; if (_calculateIsLeapYear(year) && month == 1) { daysInMonth++; } return daysInMonth; } bool isBefore(CalendarDate other) => compareTo(other) < 0; bool isAfter(CalendarDate other) => compareTo(other) > 0; DateTime toDateTime() { return DateTime(year, month + 1, day + 1); } CalendarDate operator +(int days) { if (days == 0) { return this; } else if (days < 0) { return this - (-days); } else { int year = this.year; int month = this.month; int day = this.day + days; int daysInCurrentMonth; // TODO: this could probably be calculated in constant time. while (day >= (daysInCurrentMonth = _calculateDaysInMonth(year, month))) { day = day - daysInCurrentMonth; month++; if (month > 11) { month = 0; year++; } } return CalendarDate(year, month, day); } } CalendarDate operator -(int days) { if (days == 0) { return this; } else if (days < 0) { return this + (-days); } else { // TODO: handle subtracting more days than are in a month, such that month will decrease more than 1 int year = this.year; int month = this.month; int day = this.day - days; if (day < 0) { month--; if (month < 0) { month = 11; year--; } day = _monthLengths[month] + day; if (isLeapYear && month == 1) { day++; } } return CalendarDate(year, month, day); } } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is CalendarDate && year == other.year && month == other.month && day == other.day; } @override int get hashCode => Object.hash(year, month, day); @override int compareTo(CalendarDate other) { int result = year - other.year; if (result == 0) { result = month - other.month; if (result == 0) { result = day - other.day; } } return result; } bool operator <(CalendarDate other) => compareTo(other) < 0; bool operator <=(CalendarDate other) => compareTo(other) <= 0; bool operator >(CalendarDate other) => compareTo(other) > 0; bool operator >=(CalendarDate other) => compareTo(other) >= 0; @override String toString() { final String monthValue = '${month + 1}'; final String dayValue = '${day + 1}'; return '$year-${monthValue.padLeft(2, '0')}-${dayValue.padLeft(2, '0')}'; } } @immutable class CalendarDateFormat { const CalendarDateFormat._(this._pattern); final String _pattern; static const CalendarDateFormat short = CalendarDateFormat._('M/d/yy'); static const CalendarDateFormat medium = CalendarDateFormat._('MMM d, yyyy'); static const CalendarDateFormat long = CalendarDateFormat._('MMMM d, yyyy'); static const CalendarDateFormat iso8601 = CalendarDateFormat._('yyyy-MM-dd'); static final Map<String, intl.DateFormat> _formats = <String, intl.DateFormat>{}; String format(CalendarDate date) => formatDateTime(date.toDateTime()); String formatDateTime(DateTime date) { final intl.DateFormat format = _formats.putIfAbsent( _pattern, () => intl.DateFormat(_pattern), ); return format.format(date); } } class CalendarSelectionController extends ValueNotifier<CalendarDate?> { CalendarSelectionController([CalendarDate? value]) : super(value); } class Calendar extends StatefulWidget { const Calendar({ Key? key, required this.initialYear, required this.initialMonth, this.selectionController, this.disabledDateFilter, this.onDateChanged, }) : super(key: key); final int initialYear; final int initialMonth; final CalendarSelectionController? selectionController; final Predicate<CalendarDate>? disabledDateFilter; final ValueChanged<CalendarDate?>? onDateChanged; @override _CalendarState createState() => _CalendarState(); } class _CalendarState extends State<Calendar> { late SpinnerController _monthController; late SpinnerController _yearController; late TablePaneMetricsController _metricsController; late List<TableRow> _calendarRows; CalendarSelectionController? _selectionController; static final intl.DateFormat _fullMonth = intl.DateFormat('MMMM'); static final intl.DateFormat _dayOfWeekShort = intl.DateFormat('E'); static final int firstDayOfWeek = _dayOfWeekShort.dateSymbols.FIRSTDAYOFWEEK; static final DateTime _monday = DateTime(2020, 12, 7); CalendarSelectionController get selectionController { return widget.selectionController ?? _selectionController!; } void _updateCalendarRows() { final int year = _yearController.selectedIndex + CalendarDate._gregorianCutoverYear; final int month = _monthController.selectedIndex; final CalendarDate today = CalendarDate.fromDateTime(DateTime.now()); final CalendarDate startOfMonth = CalendarDate(year, month, 0); final int daysInMonth = startOfMonth.daysInMonth; final int firstDayOfMonthOffset = (firstDayOfWeek + 1 + startOfMonth.weekday) % 7; final int lastDayOfMonthOffset = (firstDayOfMonthOffset - 1 + daysInMonth) % 7; final int totalDaysShown = daysInMonth + firstDayOfMonthOffset + (6 - lastDayOfMonthOffset); assert(totalDaysShown % 7 == 0); final int numRows = totalDaysShown ~/ 7; setState(() { _calendarRows = List<TableRow>.generate(numRows, (int rowIndex) { return TableRow( children: List<Widget>.generate(7, (int columnIndex) { final int offset = rowIndex * 7 + columnIndex - firstDayOfMonthOffset; final CalendarDate date = startOfMonth + offset; bool isEnabled = date.month == month; if (widget.disabledDateFilter != null) { isEnabled &= !widget.disabledDateFilter!(date); } return _DateButton( date, isEnabled: isEnabled, isHighlighted: date == today, isSelected: date == selectionController.value, onTap: () => _handleTapOnDate(date), ); }), ); }); }); } void _handleTapOnDate(CalendarDate date) { selectionController.value = date; } void _handleSelectedDateChanged() { if (widget.onDateChanged != null) { widget.onDateChanged!(selectionController.value); } _updateCalendarRows(); } static Widget buildMonth(BuildContext context, int index, bool isEnabled) { String value = ''; if (index >= 0) { // Since we're only rendering the month, the year and day do not matter here. final DateTime date = DateTime(2000, index + 1); value = _fullMonth.format(date); } return Spinner.defaultItemBuilder(context, value); } static Widget buildYear(BuildContext context, int index, bool isEnabled) { String value = ''; if (index >= 0) { final int year = index + CalendarDate._gregorianCutoverYear; value = '$year'; } return Spinner.defaultItemBuilder(context, value); } static Widget buildDayOfWeekHeader(BuildContext context, int index) { // Since we're only rendering the month, the year and day do not matter here. final int offset = firstDayOfWeek + index; final DateTime date = _monday.add(Duration(days: offset)); return Padding( padding: EdgeInsets.fromLTRB(2, 2, 2, 5), child: Text( _dayOfWeekShort.format(date)[0], textAlign: TextAlign.center, style: DefaultTextStyle.of( context, ).style.copyWith(fontWeight: FontWeight.bold), ), ); } @override void initState() { super.initState(); _monthController = SpinnerController(); _yearController = SpinnerController(); _monthController.selectedIndex = widget.initialMonth; _yearController.selectedIndex = widget.initialYear - CalendarDate._gregorianCutoverYear; _monthController.addListener(_updateCalendarRows); _yearController.addListener(_updateCalendarRows); _metricsController = TablePaneMetricsController(); if (widget.selectionController == null) { _selectionController = CalendarSelectionController(); } selectionController.addListener(_handleSelectedDateChanged); _updateCalendarRows(); } @override void didUpdateWidget(Calendar oldWidget) { super.didUpdateWidget(oldWidget); if (widget.initialMonth != oldWidget.initialMonth) { _monthController.selectedIndex = widget.initialMonth; } if (widget.initialYear != oldWidget.initialYear) { _yearController.selectedIndex = widget.initialYear - CalendarDate._gregorianCutoverYear; } if (oldWidget.selectionController != widget.selectionController) { if (oldWidget.selectionController == null) { assert(widget.selectionController != null); assert(_selectionController != null); _selectionController!.removeListener(_handleSelectedDateChanged); _selectionController!.dispose(); _selectionController = null; } else { assert(_selectionController == null); oldWidget.selectionController!.removeListener( _handleSelectedDateChanged, ); } if (widget.selectionController == null) { assert(oldWidget.selectionController != null); assert(_selectionController == null); _selectionController = CalendarSelectionController( oldWidget.selectionController!.value, ); _selectionController!.addListener(_handleSelectedDateChanged); } else { widget.selectionController!.addListener(_handleSelectedDateChanged); } } } @override void dispose() { _monthController.removeListener(_updateCalendarRows); _yearController.removeListener(_updateCalendarRows); selectionController.removeListener(_handleSelectedDateChanged); _monthController.dispose(); _yearController.dispose(); _metricsController.dispose(); if (_selectionController != null) { assert(widget.selectionController == null); _selectionController!.dispose(); } super.dispose(); } @override void reassemble() { super.reassemble(); _updateCalendarRows(); } @override Widget build(BuildContext context) { return BorderPane( borderColor: const Color(0xff999999), backgroundColor: const Color(0xffffffff), child: CustomPaint( foregroundPainter: _DividerCustomPainter(_metricsController), child: TablePane( horizontalRelativeSize: MainAxisSize.min, metricsController: _metricsController, columns: List<TablePaneColumn>.filled(7, const TablePaneColumn()), children: <Widget>[ TableRow( backgroundColor: const Color(0xffdddcd5), children: [ TableCell( columnSpan: 7, child: Padding( padding: EdgeInsets.all(3), child: Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ Expanded( child: Spinner( length: 12, isCircular: true, sizeToContent: true, itemBuilder: buildMonth, controller: _monthController, ), ), const SizedBox(width: 4), Spinner( length: 9999 - CalendarDate._gregorianCutoverYear + 1, itemBuilder: buildYear, controller: _yearController, ), ], ), ), ), const EmptyTableCell(), const EmptyTableCell(), const EmptyTableCell(), const EmptyTableCell(), const EmptyTableCell(), const EmptyTableCell(), ], ), TableRow( children: List<Widget>.generate( 7, (int index) => buildDayOfWeekHeader(context, index), ), ), ..._calendarRows, ], ), ), ); } } class _DateButton extends StatelessWidget { const _DateButton( this.date, { this.isEnabled = true, this.isHighlighted = false, this.isSelected = false, required this.onTap, }); final CalendarDate date; final bool isEnabled; final bool isHighlighted; final bool isSelected; final VoidCallback onTap; Widget _buildContent(BuildContext context, TextStyle style) { return Padding( padding: EdgeInsets.fromLTRB(4, 4, 4, 5), child: Text('${date.day + 1}', style: style, textAlign: TextAlign.center), ); } @override Widget build(BuildContext context) { TextStyle style = DefaultTextStyle.of(context).style; if (isEnabled) { return HoverBuilder( builder: (BuildContext context, bool hover) { Color? color; BoxBorder? border; Gradient? gradient; if (isSelected) { gradient = LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: <Color>[ const Color(0xff14538b), brighten(const Color(0xff14538b)), ], ); style = style.copyWith(color: const Color(0xffffffff)); } else if (hover) { color = const Color(0xffdddcdb); } if (isHighlighted) { border = flutter.Border.all(color: const Color(0xffc4c3bc)); } return GestureDetector( onTap: onTap, child: DecoratedBox( decoration: BoxDecoration( color: color, border: border, gradient: gradient, ), child: _buildContent(context, style), ), ); }, ); } else { Widget content = _buildContent( context, style.copyWith(color: const Color(0xff999999)), ); if (isSelected) { content = ColoredBox( color: const Color( 0xffdddddd, ), // TODO: what's the canonical color here? child: content, ); } return content; } } } class _DividerCustomPainter extends CustomPainter { const _DividerCustomPainter(this.metricsController); final TablePaneMetricsController metricsController; @override void paint(Canvas canvas, Size size) { assert(metricsController.hasMetrics); final Paint paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = const Color(0xffc4c3bc); final Rect rowBounds = metricsController.getRowBounds(1)!; final double y = rowBounds.bottom - 1.5; canvas.drawLine(Offset(2.5, y), Offset(size.width - 2.5, y), paint); } @override bool shouldRepaint(_DividerCustomPainter oldDelegate) { return false; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/calendar_button.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/widgets.dart'; import 'calendar.dart'; import 'foundation.dart'; const _kPrototypeDate = CalendarDate(2000, 11, 30); class CalendarButton extends StatefulWidget { const CalendarButton({ Key? key, this.format = CalendarDateFormat.medium, this.initialSelectedDate, this.initialMonth, this.initialYear, this.selectionController, this.disabledDateFilter, this.onDateChanged, this.width = CalendarButtonWidth.expand, this.isEnabled = true, }) : super(key: key); final CalendarDateFormat format; final CalendarDate? initialSelectedDate; final int? initialMonth; final int? initialYear; final CalendarSelectionController? selectionController; final Predicate<CalendarDate>? disabledDateFilter; final ValueChanged<CalendarDate?>? onDateChanged; final CalendarButtonWidth width; final bool isEnabled; @override _CalendarButtonState createState() => _CalendarButtonState(); } /// Enum that specifies how a [CalendarButton] will calculate its width. enum CalendarButtonWidth { expand, shrinkWrap } class _CalendarButtonState extends State<CalendarButton> { CalendarSelectionController? _selectionController; CalendarDate? _selectedDate; bool _pressed = false; void _handleSelectedDateChanged() { CalendarDate? selectedDate = selectionController.value; if (widget.onDateChanged != null) { widget.onDateChanged!(selectedDate); } setState(() { _selectedDate = selectedDate; }); } void _showPopup() { final RenderBox button = context.findRenderObject() as RenderBox; final OverlayState? overlayState = Overlay.of(context); assert(() { if (overlayState == null) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('No overlay found in widget ancestry.'), ErrorDescription( 'Usually the Navigator created by WidgetsApp provides the overlay. ' 'Perhaps your app content was created above the Navigator with the WidgetsApp ' 'builder parameter.', ), ]); } return true; }()); final RenderBox overlay = overlayState!.context.findRenderObject() as RenderBox; final Offset buttonGlobalOffset = button.localToGlobal( Offset.zero, ancestor: overlay, ); // TODO: Why do we need to ceil here? final Offset buttonPosition = Offset( buttonGlobalOffset.dx.ceilToDouble(), buttonGlobalOffset.dy.ceilToDouble(), ); final _PopupCalendarRoute<CalendarDate> popupCalendarRoute = _PopupCalendarRoute<CalendarDate>( position: RelativeRect.fromRect( buttonPosition & button.size, Offset.zero & overlay.size, ), initialMonth: widget.initialMonth, initialYear: widget.initialYear, selectedDate: selectionController.value, disabledDateFilter: widget.disabledDateFilter, showMenuContext: context, ); Navigator.of(context).push<CalendarDate>(popupCalendarRoute).then(( CalendarDate? date, ) { if (mounted) { setState(() { _pressed = false; }); if (date != null) { selectionController.value = date; } } }); } static const BoxDecoration _enabledDecoration = BoxDecoration( border: Border.fromBorderSide(BorderSide(color: Color(0xff999999))), gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: <Color>[Color(0xffdddcd5), Color(0xfff3f1fa)], ), ); static const BoxDecoration _pressedDecoration = BoxDecoration( border: Border.fromBorderSide(BorderSide(color: Color(0xff999999))), gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: <Color>[Color(0xffdddcd5), Color(0xffc8c7c0)], ), ); static const BoxDecoration _disabledDecoration = BoxDecoration( border: Border.fromBorderSide(BorderSide(color: Color(0xff999999))), color: const Color(0xffdddcd5), ); CalendarSelectionController get selectionController { return _selectionController ?? widget.selectionController!; } @override void initState() { super.initState(); if (widget.selectionController == null) { _selectionController = CalendarSelectionController(); } selectionController.value ??= widget.initialSelectedDate; selectionController.addListener(_handleSelectedDateChanged); _handleSelectedDateChanged(); // to set the initial value of _selectedDate } @override void didUpdateWidget(covariant CalendarButton oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.selectionController != widget.selectionController) { if (oldWidget.selectionController == null) { assert(widget.selectionController != null); assert(_selectionController != null); _selectionController!.removeListener(_handleSelectedDateChanged); _selectionController!.dispose(); _selectionController = null; } else { assert(_selectionController == null); oldWidget.selectionController!.removeListener( _handleSelectedDateChanged, ); } if (widget.selectionController == null) { _selectionController = CalendarSelectionController(); _selectionController!.addListener(_handleSelectedDateChanged); } else { widget.selectionController!.addListener(_handleSelectedDateChanged); } _handleSelectedDateChanged(); // to set the initial value of _selectedDate } } @override void dispose() { selectionController.removeListener(_handleSelectedDateChanged); if (_selectionController != null) { assert(widget.selectionController == null); _selectionController!.dispose(); _selectionController = null; } super.dispose(); } @override Widget build(BuildContext context) { BoxDecoration decoration; if (widget.isEnabled) { decoration = _pressed ? _pressedDecoration : _enabledDecoration; } else { decoration = _disabledDecoration; } final CalendarDate date = _selectedDate ?? _kPrototypeDate; Widget content = Text( widget.format.format(date), maxLines: 1, softWrap: false, ); if (_selectedDate == null) { content = Opacity(opacity: 0, child: content); } Widget result = DecoratedBox( decoration: decoration, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { Widget contentArea = Padding( padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), child: Padding(padding: EdgeInsets.only(bottom: 1), child: content), ); if (widget.width == CalendarButtonWidth.expand && constraints.hasBoundedWidth) { contentArea = Expanded(child: contentArea); } return Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [ contentArea, SizedBox( width: 1, height: 20, child: ColoredBox(color: const Color(0xff999999)), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), child: const CustomPaint( size: Size(7, 4), painter: _ArrowPainter(), ), ), ], ); }, ), ); if (widget.isEnabled) { result = MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTapDown: (TapDownDetails details) { setState(() { _pressed = true; }); }, onTapCancel: () { setState(() { _pressed = false; }); }, onTap: () { setState(() { _showPopup(); }); }, child: result, ), ); } else { result = DefaultTextStyle( style: DefaultTextStyle.of( context, ).style.copyWith(color: const Color(0xff999999)), child: result, ); } return result; } } class _PopupCalendarRoute<T> extends PopupRoute<T> { _PopupCalendarRoute({ required this.position, required this.initialMonth, required this.initialYear, required this.selectedDate, required this.disabledDateFilter, required this.showMenuContext, }); final RelativeRect position; final int? initialMonth; final int? initialYear; final CalendarDate? selectedDate; final Predicate<CalendarDate>? disabledDateFilter; final BuildContext showMenuContext; @override Duration get transitionDuration => Duration.zero; @override Duration get reverseTransitionDuration => const Duration(milliseconds: 250); @override bool get barrierDismissible => true; @override Color? get barrierColor => null; @override String get barrierLabel => 'Dismiss'; @override Widget buildPage( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) { return SafeArea( child: CustomSingleChildLayout( delegate: _PopupCalendarRouteLayout(position), child: InheritedTheme.captureAll( showMenuContext, _PopupCalendar<T>( route: this, initialMonth: initialMonth, initialYear: initialYear, selectedDate: selectedDate, disabledDateFilter: disabledDateFilter, ), ), ), ); } } class _PopupCalendarRouteLayout extends SingleChildLayoutDelegate { _PopupCalendarRouteLayout(this.position); // Rectangle of underlying button, relative to the overlay's dimensions. final RelativeRect position; @override BoxConstraints getConstraintsForChild(BoxConstraints constraints) { const double padding = 8.0; return BoxConstraints.loose( constraints.biggest - const Offset(padding, padding) as Size, ); } /// `size` is the size of the overlay. /// /// `childSize` is the size of the menu, when fully open, as determined by /// [getConstraintsForChild]. @override Offset getPositionForChild(Size size, Size childSize) { final Rect buttonRect = position.toRect(Offset.zero & size); return Offset(buttonRect.left, buttonRect.bottom - 1); } @override bool shouldRelayout(_PopupCalendarRouteLayout oldDelegate) => position != oldDelegate.position; } class _PopupCalendar<T> extends StatefulWidget { const _PopupCalendar({ required this.initialMonth, required this.initialYear, required this.selectedDate, required this.disabledDateFilter, required this.route, }); final int? initialMonth; final int? initialYear; final CalendarDate? selectedDate; final Predicate<CalendarDate>? disabledDateFilter; final _PopupCalendarRoute<T> route; @override _PopupCalendarState<T> createState() => _PopupCalendarState<T>(); } class _PopupCalendarState<T> extends State<_PopupCalendar<T>> { late CalendarSelectionController _selectionController; void _handleDateSelected(CalendarDate? date) { assert(date != null); assert(date == _selectionController.value); Navigator.of(context).pop(date!); } @override void initState() { super.initState(); _selectionController = CalendarSelectionController(); _selectionController.value = widget.selectedDate; } @override void dispose() { _selectionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { const BoxShadow shadow = BoxShadow( color: Color(0x40000000), blurRadius: 3, offset: Offset(3, 3), ); final CurveTween opacity = CurveTween(curve: Curves.linear); final CalendarDate today = CalendarDate.today(); return AnimatedBuilder( animation: widget.route.animation!, builder: (BuildContext context, Widget? child) { return Opacity( opacity: opacity.evaluate(widget.route.animation!), child: ClipRect( clipper: const _ShadowClipper(shadow), child: DecoratedBox( decoration: const BoxDecoration( color: Color(0xffffffff), boxShadow: [shadow], ), child: Calendar( initialMonth: widget.initialMonth ?? widget.selectedDate?.month ?? today.month, initialYear: widget.initialYear ?? widget.selectedDate?.year ?? today.year, selectionController: _selectionController, disabledDateFilter: widget.disabledDateFilter, onDateChanged: _handleDateSelected, ), ), ), ); }, ); } } class _ShadowClipper extends CustomClipper<Rect> { const _ShadowClipper(this.shadow); final BoxShadow shadow; @override Rect getClip(Size size) { final double shadowRadius = shadow.blurRadius * 2 + shadow.spreadRadius; return Offset.zero & (size + Offset(shadowRadius, shadowRadius)); } @override bool shouldReclip(_ShadowClipper oldClipper) => false; } class _ArrowPainter extends CustomPainter { const _ArrowPainter(); @override void paint(Canvas canvas, Size size) { const _ArrowImage arrow = _ArrowImage(); double arrowX = (size.width - arrow.preferredSize.width) / 2; double arrowY = (size.height - arrow.preferredSize.height) / 2; canvas.save(); try { canvas.translate(arrowX, arrowY); arrow.paint(canvas, arrow.preferredSize); } finally { canvas.restore(); } } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } } class _ArrowImage { const _ArrowImage(); Size get preferredSize => const Size(7, 4); void paint(Canvas canvas, Size size) { Paint paint = Paint() ..style = PaintingStyle.fill ..isAntiAlias = true ..color = const Color(0xff000000); Path arrow = Path() ..fillType = PathFillType.evenOdd ..moveTo(0, 0) ..lineTo(size.width / 2, size.height + 0.5) ..lineTo(size.width, 0); arrow.close(); canvas.drawPath(arrow, paint); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/checkbox.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/src/colors.dart'; import 'package:flutter/widgets.dart'; const double _checkboxSize = 14; const double _checkmarkSize = 10; const double _defaultSpacing = 6; enum CheckboxState { checked, unchecked, mixed } class CheckboxController extends ChangeNotifier { CheckboxController.simple([bool checked = false]) : _isTriState = false, _canUserToggleMixed = false, _state = checked ? CheckboxState.checked : CheckboxState.unchecked; CheckboxController.triState({ CheckboxState state = CheckboxState.unchecked, bool canUserToggleMixed = false, }) : _isTriState = true, _canUserToggleMixed = canUserToggleMixed, _state = state; final bool _isTriState; bool get isTriState => _isTriState; final bool _canUserToggleMixed; bool get canUserToggleMixed => _canUserToggleMixed; CheckboxState _state; CheckboxState get state => _state; set state(CheckboxState value) { assert(_isTriState || value != CheckboxState.mixed); if (_state != value) { _state = value; notifyListeners(); } } bool get checked => _state == CheckboxState.checked; set checked(bool value) => state = value ? CheckboxState.checked : CheckboxState.unchecked; void toggleState() { if (canUserToggleMixed) { switch (state) { case CheckboxState.checked: state = CheckboxState.unchecked; break; case CheckboxState.unchecked: state = CheckboxState.mixed; break; case CheckboxState.mixed: state = CheckboxState.checked; break; } } else { checked = !checked; } } } class Checkbox extends StatefulWidget { const Checkbox({ Key? key, this.controller, this.onChange, this.trailing, this.spacing = _defaultSpacing, this.isEnabled = true, }) : super(key: key); /// The controller that governs the state of this checkbox. /// /// If this is unspecified, the checkbox will create and manage its own /// simple (non-tri-state) controller. final CheckboxController? controller; /// Callback that will be invoked when the state of the checkbox changes. /// /// Users who register for notifications on [controller] will receive the /// same notifications. final VoidCallback? onChange; /// A widget to show after the checkbox. /// /// Clicking on the widget will act as if the user clicked on the checkbox /// itself. /// /// This widget will be laid out with a spacing in between the checkbox and /// the widget. The amount of spacing is determined by the [spacing] /// property. final Widget? trailing; /// The spacing to add in between the checkbox and the [trailing] widget, in /// logical pixels. /// /// If the [trailing] widget is not specified, this value is not used. final double spacing; /// Whether the checkbox accepts user input. /// /// If this is false, the checkbox will still respond to changes in its /// controller, but the user will not be able to interact with the checkbox. final bool isEnabled; @override _CheckboxState createState() => _CheckboxState(); } class _CheckboxState extends State<Checkbox> { CheckboxController? _controller; CheckboxController get controller => _controller ?? widget.controller!; void _handleChanged() { setState(() { // We pull the checked value from the controller. }); if (widget.onChange != null) { widget.onChange!(); } } @override void initState() { super.initState(); if (widget.controller == null) { _controller = CheckboxController.simple(); } controller.addListener(_handleChanged); } @override void didUpdateWidget(covariant Checkbox oldWidget) { super.didUpdateWidget(oldWidget); if (widget.controller != oldWidget.controller) { final CheckboxController oldController = _controller ?? oldWidget.controller!; oldController.removeListener(_handleChanged); _controller?.dispose(); _controller = null; if (widget.controller == null) { _controller = CheckboxController.simple(); } controller.addListener(_handleChanged); } } @override void dispose() { controller.removeListener(_handleChanged); _controller?.dispose(); _controller = null; super.dispose(); } @override Widget build(BuildContext context) { return BasicCheckbox( key: widget.key, spacing: widget.spacing, state: controller.state, onTap: widget.isEnabled ? controller.toggleState : null, trailing: widget.trailing, ); } } class BasicCheckbox extends StatelessWidget { const BasicCheckbox({ Key? key, this.state = CheckboxState.unchecked, this.onTap, this.trailing, this.spacing = _defaultSpacing, }) : super(key: key); final CheckboxState state; final VoidCallback? onTap; final Widget? trailing; final double spacing; @override Widget build(BuildContext context) { final bool isEnabled = onTap != null; Widget? styledTrailing = trailing; if (styledTrailing != null) { styledTrailing = Padding( padding: EdgeInsets.only(left: spacing), child: styledTrailing, ); if (!isEnabled) { styledTrailing = Opacity(opacity: 0.5, child: styledTrailing); } } final Decoration backgroundDecoration; if (isEnabled) { backgroundDecoration = BoxDecoration( border: const Border.fromBorderSide( BorderSide(color: Color(0xff999999)), ), gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: <Color>[ darken(const Color(0xffffffff)), const Color(0xffffffff), ], ), ); } else { backgroundDecoration = const BoxDecoration( border: Border.fromBorderSide(BorderSide(color: Color(0xff999999))), color: Color(0xffe6e6e6), ); } Widget result = DecoratedBox( decoration: backgroundDecoration, child: SizedBox( width: _checkboxSize, height: _checkboxSize, child: CustomPaint(painter: CheckPainter(state, isEnabled)), ), ); if (styledTrailing != null) { result = Row(children: <Widget>[result, styledTrailing]); } if (isEnabled) { result = MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: onTap, child: AbsorbPointer(child: result), ), ); } return result; } } class CheckPainter extends CustomPainter { const CheckPainter(this.state, this.isEnabled); final CheckboxState state; final bool isEnabled; static const Color _enabledCheckmarkColor = Color(0xff2b5580); static const Color _disabledCheckmarkColor = Color(0xff999999); @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = isEnabled ? _enabledCheckmarkColor : _disabledCheckmarkColor; switch (state) { case CheckboxState.checked: paint ..style = PaintingStyle.stroke ..strokeWidth = 2.5 ..strokeCap = StrokeCap.round; double n = _checkmarkSize / 2; double m = _checkmarkSize / 4; double dx = (_checkboxSize - (n + m)) / 2; double dy = (_checkboxSize - n) / 2; canvas.save(); canvas.translate(0, (size.height - _checkboxSize) / 2); canvas.drawLine( Offset(dx, (n - m) + dy), Offset(m + dx, n + dy), paint, ); canvas.drawLine( Offset(m + dx, n + dy), Offset((m + n) + dx, dy), paint, ); canvas.restore(); break; case CheckboxState.mixed: paint ..style = PaintingStyle.fill ..isAntiAlias = false; canvas.drawRect( Rect.fromLTWH(4, _checkboxSize / 2 - 1, _checkboxSize - 8, 2), paint, ); break; case CheckboxState.unchecked: // Nothing to paint. break; } } @override bool shouldRepaint(CheckPainter oldDelegate) => state != oldDelegate.state; }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/colors.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:flutter/painting.dart'; Color brighten(Color color) { return _adjustBrightness(color, 0.1); } Color darken(Color color) { return _adjustBrightness(color, -0.1); } Color _adjustBrightness(Color color, double adjustment) { HSVColor hsv = HSVColor.fromColor(color); HSVColor adjusted = HSVColor.fromAHSV( hsv.alpha, hsv.hue, hsv.saturation, math.min(math.max(hsv.value + adjustment, 0), 1), ); return adjusted.toColor(); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/debug.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/painting.dart'; const HSVColor _kDebugDefaultRepaintColor = HSVColor.fromAHSV( 0.4, 60.0, 1.0, 1.0, ); /// Overlay a rotating set of colors when rebuilding table cells in checked /// mode. /// /// See also: /// /// * [debugRepaintRainbowEnabled], a similar flag for visualizing layer /// repaints. /// * [BasicTableView], [TableView], and [ScrollableTableView], which look /// for this flag when running in debug mode. bool debugPaintTableCellBuilds = false; /// The current color to overlay when repainting a table cell build. HSVColor debugCurrentTableCellColor = _kDebugDefaultRepaintColor; /// Overlay a rotating set of colors when rebuilding list items in checked /// mode. /// /// See also: /// /// * [debugRepaintRainbowEnabled], a similar flag for visualizing layer /// repaints. /// * [BasicListView] and [ListView], which look for this flag when running in /// debug mode. bool debugPaintListItemBuilds = false; /// The current color to overlay when repainting a list item build. HSVColor debugCurrentListItemColor = _kDebugDefaultRepaintColor;
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/deferred_layout.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; /// Mixin that allows subclasses to defer [markNeedsLayout] calls until the /// next transient frame callback. /// /// See also: /// /// * https://github.com/flutter/flutter/issues/64661, which describes when /// this might be necessary. mixin DeferredLayoutMixin on RenderObject { bool _needsLayoutDeferred = false; @override void markNeedsLayout() { if (!_deferMarkNeedsLayout) { super.markNeedsLayout(); } else if (!_needsLayoutDeferred) { _needsLayoutDeferred = true; SchedulerBinding.instance.scheduleFrameCallback((Duration timeStamp) { if (_needsLayoutDeferred) { _needsLayoutDeferred = false; super.markNeedsLayout(); } }); } } bool _deferMarkNeedsLayout = false; void deferMarkNeedsLayout(VoidCallback callback) { assert(!_deferMarkNeedsLayout); _deferMarkNeedsLayout = true; try { callback(); } finally { _deferMarkNeedsLayout = false; } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/focus_indicator.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:ui'; import 'package:flutter/widgets.dart'; class FocusIndicator extends StatelessWidget { const FocusIndicator({ Key? key, required this.isFocused, this.insets = EdgeInsets.zero, this.color = const Color(0xff999999), this.child, }) : super(key: key); final bool isFocused; final EdgeInsets insets; final Color color; final Widget? child; @override Widget build(BuildContext context) { return CustomPaint( painter: _FocusPainter(isFocused, insets, color), child: child, ); } } class _FocusPainter extends CustomPainter { const _FocusPainter(this.isFocused, this.padding, this.color); final bool isFocused; final EdgeInsets padding; final Color color; @override void paint(Canvas canvas, Size size) { if (isFocused) { Rect rect = Offset.zero & size; rect = rect.deflate(0.5); rect = padding.deflateRect(rect); final Path path = Path()..addRect(rect); final Path dashedPath = _dashPath(path, <double>[1, 1]); canvas.drawPath( dashedPath, Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = color, ); } } @override bool shouldRepaint(_FocusPainter oldDelegate) { return isFocused != oldDelegate.isFocused || padding != oldDelegate.padding || color != oldDelegate.color; } } /// The `dash` parameter is a list of dash offsets and lengths. For example, /// the array `[5, 10]` would result in dashes 5 pixels long followed by blank /// spaces 10 pixels long. The array `[5, 10, 5]` would result in a 5 pixel /// dash, a 10 pixel gap, a 5 pixel dash, a 5 pixel gap, a 10 pixel dash, etc. Path _dashPath(Path source, List<double> dash, {double offset = 0.5}) { final Path dest = Path(); for (final PathMetric metric in source.computeMetrics()) { double distance = offset; bool draw = true; for (int i = 0; distance < metric.length; i = (i + 1) % dash.length) { final double len = dash[i]; if (draw) { dest.addPath(metric.extractPath(distance, distance + len), Offset.zero); } distance += len; draw = !draw; } } return dest; }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/form_pane.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'foundation.dart'; @immutable class Flag { const Flag({required this.messageType, required this.message}); final MessageType messageType; final String message; } @immutable class FormPaneField { const FormPaneField({required this.label, required this.child, this.flag}); final String label; final Widget child; final Flag? flag; } class FormPane extends StatelessWidget { const FormPane({ Key? key, this.horizontalSpacing = 6, this.verticalSpacing = 6, this.flagImageOffset = 4, this.delimiter = ':', this.stretch = false, this.rightAlignLabels = false, required this.children, }) : super(key: key); final double horizontalSpacing; final double verticalSpacing; final double flagImageOffset; final String delimiter; final bool stretch; final bool rightAlignLabels; final List<FormPaneField> children; Widget _newLabel(FormPaneField field) { return Text('${field.label}$delimiter'); } Widget _newFlag(FormPaneField field) { if (field.flag == null) { return const _NoFlag(); } else { return field.flag!.messageType.toSmallImage(); // return Tooltip( // message: field.flag.message, // child: field.flag.messageType.toSmallImage(), // ); } } @override Widget build(BuildContext context) { return _RawForm( key: key, horizontalSpacing: horizontalSpacing, verticalSpacing: verticalSpacing, flagImageOffset: flagImageOffset, stretch: stretch, rightAlignLabels: rightAlignLabels, children: children .map<_RawFormField>((FormPaneField field) { return _RawFormField( label: _newLabel(field), child: field.child, flag: _newFlag(field), ); }) .toList(growable: false), ); } } class _RawFormField { const _RawFormField({ required this.label, required this.child, required this.flag, }); final Widget label; final Widget child; final Widget flag; } class _RawForm extends RenderObjectWidget { const _RawForm({ Key? key, this.horizontalSpacing = 6, this.verticalSpacing = 6, this.flagImageOffset = 4, this.stretch = false, this.rightAlignLabels = false, required this.children, }) : super(key: key); final double horizontalSpacing; final double verticalSpacing; final double flagImageOffset; final bool stretch; final bool rightAlignLabels; final List<_RawFormField> children; @override RenderObjectElement createElement() => _FormElement(this); @override _RenderForm createRenderObject(BuildContext context) { return _RenderForm( horizontalSpacing: horizontalSpacing, verticalSpacing: verticalSpacing, flagImageOffset: flagImageOffset, stretch: stretch, rightAlignLabels: rightAlignLabels, ); } @override void updateRenderObject( BuildContext context, covariant _RenderForm renderObject, ) { renderObject ..horizontalSpacing = horizontalSpacing ..verticalSpacing = verticalSpacing ..flagImageOffset = flagImageOffset ..stretch = stretch ..rightAlignLabels = rightAlignLabels; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add( DiagnosticsProperty<double>('horizontalSpacing', horizontalSpacing), ); properties.add( DiagnosticsProperty<double>('verticalSpacing', verticalSpacing), ); properties.add( DiagnosticsProperty<double>('flagImageOffset', flagImageOffset), ); properties.add(DiagnosticsProperty<bool>('stretch', stretch)); properties.add( DiagnosticsProperty<bool>('rightAlignLabels', rightAlignLabels), ); } } enum _SlotType { label, field, flag } @immutable class _FormSlot { const _FormSlot.label(this.previous) : type = _SlotType.label; const _FormSlot.field(this.previous) : type = _SlotType.field; const _FormSlot.flag(this.previous) : type = _SlotType.flag; final Element? previous; final _SlotType type; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) return false; return other is _FormSlot && previous == other.previous && type == other.type; } @override int get hashCode => Object.hash(previous, type); } class _FormRow { Element? label; Element? field; Element? flag; } class _FormElement extends RenderObjectElement { _FormElement(_RawForm widget) : super(widget); late List<_FormRow> _rows; @override _RawForm get widget => super.widget as _RawForm; @override _RenderForm get renderObject => super.renderObject as _RenderForm; @override void visitChildren(ElementVisitor visitor) { for (_FormRow row in _rows) { visitor(row.label!); visitor(row.field!); visitor(row.flag!); } } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _FormRow previous = _FormRow(); _rows = List<_FormRow>.generate(widget.children.length, (int index) { final _RawFormField field = widget.children[index]; _FormRow row = _FormRow(); row.label = updateChild( null, field.label, _FormSlot.label(previous.label), ); row.field = updateChild( null, field.child, _FormSlot.field(previous.field), ); row.flag = updateChild(null, field.flag, _FormSlot.flag(previous.flag)); previous = row; return row; }, growable: false); } @override void update(_RawForm newWidget) { super.update(newWidget); assert(widget == newWidget); List<_FormRow> newRows = <_FormRow>[]; _FormRow previous = _FormRow(); int i = 0; for (_RawFormField field in newWidget.children) { final _FormRow row = i < _rows.length ? _rows[i] : _FormRow(); newRows.add(row); row.label = updateChild( row.label, field.label, _FormSlot.label(previous.label), ); row.field = updateChild( row.field, field.child, _FormSlot.field(previous.field), ); row.flag = updateChild( row.flag, field.flag, _FormSlot.flag(previous.flag), ); previous = row; i++; } for (; i < _rows.length; i++) { final _FormRow row = _rows[i]; row.label = updateChild(row.label, null, null); row.field = updateChild(row.field, null, null); row.flag = updateChild(row.flag, null, null); } _rows = newRows.toList(growable: false); } @override void insertRenderObjectChild(RenderBox child, _FormSlot slot) { switch (slot.type) { case _SlotType.label: renderObject.insertLabel( child, after: slot.previous?.renderObject as RenderBox?, ); break; case _SlotType.field: renderObject.insertField( child, after: slot.previous?.renderObject as RenderBox?, ); break; case _SlotType.flag: renderObject.insertFlag( child, after: slot.previous?.renderObject as RenderBox?, ); break; } } @override void moveRenderObjectChild( RenderBox child, _FormSlot oldSlot, _FormSlot newSlot, ) { assert(oldSlot.type == newSlot.type); assert(child.parent == renderObject); switch (oldSlot.type) { case _SlotType.label: renderObject.moveLabel( child, after: newSlot.previous?.renderObject as RenderBox?, ); break; case _SlotType.field: renderObject.moveField( child, after: newSlot.previous?.renderObject as RenderBox?, ); break; case _SlotType.flag: renderObject.moveFlag( child, after: newSlot.previous?.renderObject as RenderBox?, ); break; } } @override void removeRenderObjectChild(RenderBox child, _FormSlot slot) { assert(child.parent == renderObject); switch (slot.type) { case _SlotType.label: renderObject.removeLabel(child); break; case _SlotType.field: renderObject.removeField(child); break; case _SlotType.flag: renderObject.removeFlag(child); break; } } @override void forgetChild(Element child) { print('TODO: forgetChild()'); super.forgetChild(child); } } class FormParentData extends ContainerBoxParentData<RenderBox> {} class _ChildList { int _childCount = 0; RenderBox? firstChild; RenderBox? lastChild; static bool _debugUltimatePreviousSiblingOf( RenderBox child, { required RenderBox? equals, }) { ContainerParentDataMixin<RenderBox> childParentData = child.parentData as ContainerParentDataMixin<RenderBox>; while (childParentData.previousSibling != null) { assert(childParentData.previousSibling != child); child = childParentData.previousSibling!; childParentData = child.parentData as ContainerParentDataMixin<RenderBox>; } return child == equals; } static bool _debugUltimateNextSiblingOf( RenderBox child, { required RenderBox? equals, }) { ContainerParentDataMixin<RenderBox> childParentData = child.parentData as ContainerParentDataMixin<RenderBox>; while (childParentData.nextSibling != null) { assert(childParentData.nextSibling != child); child = childParentData.nextSibling!; childParentData = child.parentData as ContainerParentDataMixin<RenderBox>; } return child == equals; } void insert(RenderBox child, {RenderBox? after}) { final FormParentData childParentData = child.parentData as FormParentData; assert(childParentData.nextSibling == null); assert(childParentData.previousSibling == null); _childCount += 1; assert(_childCount > 0); if (after == null) { // insert at the start (_firstChild) childParentData.nextSibling = firstChild; if (firstChild != null) { final FormParentData firstChildParentData = firstChild!.parentData as FormParentData; firstChildParentData.previousSibling = child; } firstChild = child; lastChild ??= child; } else { assert(firstChild != null); assert(lastChild != null); assert(_debugUltimatePreviousSiblingOf(after, equals: firstChild)); assert(_debugUltimateNextSiblingOf(after, equals: lastChild)); final FormParentData afterParentData = after.parentData as FormParentData; if (afterParentData.nextSibling == null) { // insert at the end (_lastChild); we'll end up with two or more children assert(after == lastChild); childParentData.previousSibling = after; afterParentData.nextSibling = child; lastChild = child; } else { // insert in the middle; we'll end up with three or more children // set up links from child to siblings childParentData.nextSibling = afterParentData.nextSibling; childParentData.previousSibling = after; // set up links from siblings to child final FormParentData childPreviousSiblingParentData = childParentData.previousSibling!.parentData as FormParentData; final FormParentData childNextSiblingParentData = childParentData.nextSibling!.parentData as FormParentData; childPreviousSiblingParentData.nextSibling = child; childNextSiblingParentData.previousSibling = child; assert(afterParentData.nextSibling == child); } } } void remove(RenderBox child) { final FormParentData childParentData = child.parentData! as FormParentData; assert(_debugUltimatePreviousSiblingOf(child, equals: firstChild)); assert(_debugUltimateNextSiblingOf(child, equals: lastChild)); assert(_childCount >= 0); if (childParentData.previousSibling == null) { assert(firstChild == child); firstChild = childParentData.nextSibling; } else { final FormParentData childPreviousSiblingParentData = childParentData.previousSibling!.parentData! as FormParentData; childPreviousSiblingParentData.nextSibling = childParentData.nextSibling; } if (childParentData.nextSibling == null) { assert(lastChild == child); lastChild = childParentData.previousSibling; } else { final FormParentData childNextSiblingParentData = childParentData.nextSibling!.parentData! as FormParentData; childNextSiblingParentData.previousSibling = childParentData.previousSibling; } childParentData.previousSibling = null; childParentData.nextSibling = null; _childCount -= 1; } } typedef FormRenderObjectVisitor = void Function(RenderBox label, RenderBox field, RenderBox flag); class _RenderForm extends RenderBox { _RenderForm({ required double horizontalSpacing, required double verticalSpacing, required double flagImageOffset, required bool stretch, required bool rightAlignLabels, }) { this.horizontalSpacing = horizontalSpacing; this.verticalSpacing = verticalSpacing; this.flagImageOffset = flagImageOffset; this.stretch = stretch; this.rightAlignLabels = rightAlignLabels; } static const double _flagImageSize = 16; double? _horizontalSpacing; double get horizontalSpacing => _horizontalSpacing!; set horizontalSpacing(double value) { if (value == _horizontalSpacing) return; _horizontalSpacing = value; markNeedsLayout(); } double? _verticalSpacing; double get verticalSpacing => _verticalSpacing!; set verticalSpacing(double value) { if (value == _verticalSpacing) return; _verticalSpacing = value; markNeedsLayout(); } double? _flagImageOffset; double get flagImageOffset => _flagImageOffset!; set flagImageOffset(double value) { if (value == _flagImageOffset) return; _flagImageOffset = value; markNeedsLayout(); } bool? _stretch; bool get stretch => _stretch!; set stretch(bool value) { if (value == _stretch) return; _stretch = value; markNeedsLayout(); } bool? _rightAlignLabels; bool get rightAlignLabels => _rightAlignLabels!; set rightAlignLabels(bool value) { if (value == _rightAlignLabels) return; _rightAlignLabels = value; markNeedsLayout(); } final Map<_SlotType, _ChildList> _children = <_SlotType, _ChildList>{ _SlotType.label: _ChildList(), _SlotType.field: _ChildList(), _SlotType.flag: _ChildList(), }; void _insertChild( RenderBox child, { RenderBox? after, required _SlotType type, }) { final _ChildList children = _children[type]!; assert(child != this, 'A RenderObject cannot be inserted into itself.'); assert( after != this, 'A RenderObject cannot simultaneously be both the parent and the sibling of another RenderObject.', ); assert(child != after, 'A RenderObject cannot be inserted after itself.'); assert(child != children.firstChild); assert(child != children.lastChild); adoptChild(child); children.insert(child, after: after); } void insertLabel(RenderBox label, {RenderBox? after}) { _insertChild(label, after: after, type: _SlotType.label); } void insertField(RenderBox child, {RenderBox? after}) { _insertChild(child, after: after, type: _SlotType.field); } void insertFlag(RenderBox child, {RenderBox? after}) { _insertChild(child, after: after, type: _SlotType.flag); } void _moveChild( RenderBox child, { RenderBox? after, required _SlotType type, }) { assert(child != this); assert(after != this); assert(child != after); assert(child.parent == this); final FormParentData childParentData = child.parentData! as FormParentData; if (childParentData.previousSibling == after) { return; } final _ChildList children = _children[type]!; children.remove(child); children.insert(child, after: after); markNeedsLayout(); } void moveLabel(RenderBox label, {RenderBox? after}) { _moveChild(label, after: after, type: _SlotType.label); } void moveField(RenderBox child, {RenderBox? after}) { _moveChild(child, after: after, type: _SlotType.field); } void moveFlag(RenderBox child, {RenderBox? after}) { _moveChild(child, after: after, type: _SlotType.flag); } void _removeChild(RenderBox child, {required _SlotType type}) { final _ChildList children = _children[type]!; children.remove(child); dropChild(child); } void removeLabel(RenderBox label) { _removeChild(label, type: _SlotType.label); } void removeField(RenderBox field) { _removeChild(field, type: _SlotType.field); } void removeFlag(RenderBox flag) { _removeChild(flag, type: _SlotType.flag); } @override void setupParentData(RenderBox child) { if (child.parentData is! FormParentData) { child.parentData = FormParentData(); } } @override void attach(PipelineOwner owner) { super.attach(owner); visitChildren((RenderObject child) { child.attach(owner); }); } @override void detach() { super.detach(); visitChildren((RenderObject child) { child.detach(); }); } @override void visitChildren(RenderObjectVisitor visitor) { visitRows((RenderBox label, RenderBox field, RenderBox flag) { visitor(label); visitor(field); visitor(flag); }); } void visitRows(FormRenderObjectVisitor visitor, {bool until()?}) { RenderBox? label = _children[_SlotType.label]!.firstChild; RenderBox? field = _children[_SlotType.field]!.firstChild; RenderBox? flag = _children[_SlotType.flag]!.firstChild; while (field != null) { assert(label != null); assert(flag != null); visitor(label!, field, flag!); if (until != null && until()) { return; } final FormParentData labelParentData = label.parentData as FormParentData; final FormParentData fieldParentData = field.parentData as FormParentData; final FormParentData flagParentData = flag.parentData as FormParentData; label = labelParentData.nextSibling; field = fieldParentData.nextSibling; flag = flagParentData.nextSibling; } assert(label == null); assert(flag == null); } void visitChildrenOfType(_SlotType type, RenderObjectVisitor visitor) { RenderBox? child = _children[type]!.firstChild; while (child != null) { visitor(child); final FormParentData childParentData = child.parentData as FormParentData; child = childParentData.nextSibling; } } @override void redepthChildren() { visitChildren((RenderObject child) { redepthChild(child); }); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { bool isHit = false; visitRows((RenderBox label, RenderBox field, RenderBox flag) { for (RenderBox child in [field, label, flag]) { final FormParentData childParentData = child.parentData as FormParentData; isHit = result.addWithPaintOffset( offset: childParentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - childParentData.offset); return child.hitTest(result, position: transformed); }, ); if (isHit) { return; } } }, until: () => isHit); return isHit; } @override double computeMinIntrinsicWidth(double height) { return 0; } @override double computeMaxIntrinsicWidth(double height) => computeMinIntrinsicWidth(height); @override double computeMinIntrinsicHeight(double width) { return 0; } @override double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); @override void performLayout() { // Determine the maximum label width double maxLabelWidth = 0; visitChildrenOfType(_SlotType.label, (RenderObject child) { child.layout(const BoxConstraints(), parentUsesSize: true); maxLabelWidth = math.max(maxLabelWidth, (child as RenderBox).size.width); }); BoxConstraints fieldConstraints = constraints.deflate( EdgeInsets.only( left: maxLabelWidth + horizontalSpacing + flagImageOffset + _flagImageSize, ), ); if (stretch) { fieldConstraints = fieldConstraints.tighten( width: fieldConstraints.maxWidth, ); } else { fieldConstraints = fieldConstraints.copyWith(minWidth: 0); } double rowY = 0; double maxFieldWidth = 0; visitRows((RenderBox label, RenderBox field, RenderBox flag) { final FormParentData labelParentData = label.parentData as FormParentData; final FormParentData childParentData = field.parentData as FormParentData; final FormParentData flagParentData = flag.parentData as FormParentData; final double labelAscent = label.getDistanceToBaseline(TextBaseline.alphabetic)!; final double labelDescent = label.size.height - labelAscent; field.layout(fieldConstraints, parentUsesSize: true); final double fieldAscent = field.getDistanceToBaseline(TextBaseline.alphabetic)!; final double fieldDescent = field.size.height - fieldAscent; final double baseline = math.max(labelAscent, fieldAscent); final double rowHeight = math.max( baseline + math.max(labelDescent, fieldDescent), _flagImageSize, ); // Align the label and field to baseline double labelX = rightAlignLabels ? maxLabelWidth - label.size.width : 0; double labelY = rowY + (baseline - labelAscent); labelParentData.offset = Offset(labelX, labelY); double fieldX = maxLabelWidth + horizontalSpacing; double fieldY = rowY + (baseline - fieldAscent); childParentData.offset = Offset(fieldX, fieldY); // Vertically center the flag on the label flag.layout(BoxConstraints.tight(Size.square(_flagImageSize))); double flagY = labelY + (label.size.height - _flagImageSize) / 2; flagParentData.offset = Offset( fieldX + field.size.width + flagImageOffset, flagY, ); rowY += rowHeight + verticalSpacing; maxFieldWidth = math.max(maxFieldWidth, field.size.width); }); size = constraints.constrainDimensions( maxLabelWidth + horizontalSpacing + maxFieldWidth + flagImageOffset + _flagImageSize, rowY - verticalSpacing, ); } @override void paint(PaintingContext context, Offset offset) { visitChildren((RenderObject child) { final FormParentData childParentData = child.parentData as FormParentData; context.paintChild(child, childParentData.offset + offset); }); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> result = <DiagnosticsNode>[]; void add(RenderBox child, String name) { result.add(child.toDiagnosticsNode(name: name)); } int i = 0; visitRows((RenderBox label, RenderBox field, RenderBox flag) { add(label, 'label_$i'); add(field, 'field_$i'); add(flag, 'flag_$i'); i++; }); return result; } } class _NoFlag extends LeafRenderObjectWidget { const _NoFlag({Key? key}) : super(key: key); @override RenderObject createRenderObject(BuildContext context) => _RenderNoFlag(); } class _RenderNoFlag extends RenderBox { @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) { return constraints.smallest; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/foundation.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; typedef Predicate<T> = bool Function(T item); int binarySearch<T>( List<T> sortedList, T value, { int Function(T, T)? compare, }) { compare ??= _defaultCompare<T>(); int min = 0; int max = sortedList.length; while (min < max) { int mid = min + ((max - min) >> 1); T element = sortedList[mid]; int comp = compare(element, value); if (comp == 0) { return mid; } else if (comp < 0) { min = mid + 1; } else { max = mid; } } return -(min + 1); } enum SelectMode { none, single, multi } /// Returns a [Comparator] that asserts that its first argument is comparable. Comparator<T> _defaultCompare<T>() { return (T value1, T value2) => (value1 as Comparable<T>).compareTo(value2); } /// Returns true if any shift key is pressed on a physical keyboard. bool isShiftKeyPressed() { final Set<LogicalKeyboardKey> keys = HardwareKeyboard.instance.logicalKeysPressed; return keys.contains(LogicalKeyboardKey.shiftLeft) || keys.contains(LogicalKeyboardKey.shiftRight); } /// Returns true if any "command" key is pressed on a physical keyboard. /// /// A command key is the "Command" (⌘) key on MacOS, and the "Control" (⌃) /// key on other platforms. bool isPlatformCommandKeyPressed([TargetPlatform? platform]) { platform ??= defaultTargetPlatform; final Set<LogicalKeyboardKey> keys = HardwareKeyboard.instance.logicalKeysPressed; switch (platform) { case TargetPlatform.macOS: return keys.contains(LogicalKeyboardKey.metaLeft) || keys.contains(LogicalKeyboardKey.metaRight); default: return keys.contains(LogicalKeyboardKey.controlLeft) || keys.contains(LogicalKeyboardKey.controlRight); } } bool isActivateKey(LogicalKeyboardKey key) { final Iterable<LogicalKeyboardKey> activateKeys = WidgetsApp .defaultShortcuts .entries .where( (MapEntry<ShortcutActivator, Intent> entry) => entry.value is ActivateIntent, ) .map<ShortcutActivator>( (MapEntry<ShortcutActivator, Intent> entry) => entry.key, ) .where((ShortcutActivator activator) => activator.triggers?.length == 1) .map<LogicalKeyboardKey>( (ShortcutActivator activator) => activator.triggers!.single, ); return activateKeys.contains(key); } class Vote { const Vote._(this._name); final String _name; static const Vote approve = Vote._('approve'); static const Vote deny = Vote._('deny'); static const Vote abstain = Vote._('abstain'); Vote tally(Vote other) { switch (other) { case approve: return this; case deny: return other; case abstain: return this == deny ? this : other; } throw StateError('Unreachable code'); } @override String toString() => _name; } class LinearConstraints extends Constraints { const LinearConstraints({this.min = 0, this.max = double.infinity}); const LinearConstraints.tight(double value) : min = value, max = value; LinearConstraints.width(BoxConstraints constraints) : min = constraints.minWidth, max = constraints.maxWidth; LinearConstraints.height(BoxConstraints constraints) : min = constraints.minHeight, max = constraints.maxHeight; final double min; final double max; static const LinearConstraints zero = LinearConstraints(max: 0); double constrainMainAxisSize(MainAxisSize mainAxisSize) { switch (mainAxisSize) { case MainAxisSize.min: return min; case MainAxisSize.max: return max; } } bool isSatisfiedBy(double value) => (min <= value) && (value <= max); bool get isBounded => max < double.infinity; @override bool get isNormalized => min >= 0 && min <= max; @override bool get isTight => min >= max; bool operator <(double value) => min < value && max < value; bool operator <=(double value) => min <= value && max <= value; bool operator >(double value) => min > value && max > value; bool operator >=(double value) => min >= value && max >= value; @override String toString() => 'LinearConstraints($min <= x <= $max)'; } class MessageType { const MessageType._(this._assetKey); final String _assetKey; static const MessageType error = MessageType._('error'); static const MessageType warning = MessageType._('warning'); static const MessageType question = MessageType._('question'); static const MessageType info = MessageType._('info'); Widget toImage() { return Image.asset( 'assets/message_type-$_assetKey-32x32.png', package: 'chicago', ); } Widget toSmallImage() { return Image.asset( 'assets/message_type-$_assetKey-16x16.png', package: 'chicago', ); } } class FakeSubscription<T> implements StreamSubscription<T> { const FakeSubscription(); @override Future<E> asFuture<E>([E? futureValue]) async { assert(false); return futureValue as E; } @override Future<void> cancel() async {} @override bool get isPaused => false; @override void onData(void Function(T data)? handleData) { assert(false); } @override void onDone(void Function()? handleDone) { assert(false); } @override void onError(Function? handleError) { assert(false); } @override void pause([Future<void>? resumeSignal]) { assert(false); } @override void resume() { assert(false); } } mixin RenderBoxWithChildDefaultsMixin on RenderObjectWithChildMixin<RenderBox> { bool defaultHitTestChild( BoxHitTestResult result, { required ui.Offset position, }) { if (child == null) { return false; } final BoxParentData childParentData = child!.parentData as BoxParentData; return result.addWithPaintOffset( offset: childParentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - childParentData.offset); return child!.hitTest(result, position: transformed); }, ); } void defaultPaintChild(PaintingContext context, Offset offset) { if (child != null) { final BoxParentData childParentData = child!.parentData as BoxParentData; context.paintChild(child!, offset + childParentData.offset); } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google