anchor.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // -*- coding: utf-8 -*-
  2. //
  3. // Simple CMS
  4. //
  5. // Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
  6. //
  7. // Licensed under the Apache License version 2.0
  8. // or the MIT license, at your option.
  9. // SPDX-License-Identifier: Apache-2.0 OR MIT
  10. use crate::resolver::Resolver;
  11. use anyhow as ah;
  12. #[derive(Clone, Debug)]
  13. pub struct Anchor {
  14. name: String,
  15. text: String,
  16. indent: Option<usize>,
  17. no_index: bool,
  18. }
  19. impl Anchor {
  20. pub fn new(name: &str, text: &str, indent: i64, no_index: bool) -> Self {
  21. let indent = if indent >= 0 {
  22. Some(indent.clamp(0, u8::MAX.into()).try_into().unwrap())
  23. } else {
  24. None
  25. };
  26. Self {
  27. name: name.to_string(),
  28. text: text.to_string(),
  29. indent,
  30. no_index,
  31. }
  32. }
  33. pub fn name(&self) -> &str {
  34. &self.name
  35. }
  36. pub fn text(&self) -> &str {
  37. &self.text
  38. }
  39. pub fn indent(&self) -> Option<usize> {
  40. self.indent
  41. }
  42. pub fn no_index(&self) -> bool {
  43. self.no_index
  44. }
  45. fn make_url(&self, resolver: &Resolver) -> ah::Result<String> {
  46. let ident = resolver.expand_variable("CMS_PAGEIDENT")?;
  47. let name = self.name();
  48. Ok(format!("{ident}#{name}"))
  49. }
  50. pub fn make_html(&self, resolver: &Resolver, with_id: bool) -> ah::Result<String> {
  51. let name = self.name();
  52. let text = self.text();
  53. let url = self.make_url(resolver)?;
  54. if with_id {
  55. Ok(format!(r#"<a id="{name}" href="{url}">{text}</a>"#))
  56. } else {
  57. Ok(format!(r#"<a href="{url}">{text}</a>"#))
  58. }
  59. }
  60. }
  61. // vim: ts=4 sw=4 expandtab